3 * This is the Postgres database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 class PostgresField
implements Field
{
25 private $name, $tablename, $type, $nullable, $max_length, $deferred, $deferrable, $conname,
26 $has_default, $default;
29 * @param $db DatabaseBase
32 * @return null|PostgresField
34 static function fromText( $db, $table, $field ) {
37 attnotnull, attlen, conname AS conname,
40 COALESCE(condeferred, 'f') AS deferred,
41 COALESCE(condeferrable, 'f') AS deferrable,
42 CASE WHEN typname = 'int2' THEN 'smallint'
43 WHEN typname = 'int4' THEN 'integer'
44 WHEN typname = 'int8' THEN 'bigint'
45 WHEN typname = 'bpchar' THEN 'char'
46 ELSE typname END AS typname
48 JOIN pg_namespace n ON (n.oid = c.relnamespace)
49 JOIN pg_attribute a ON (a.attrelid = c.oid)
50 JOIN pg_type t ON (t.oid = a.atttypid)
51 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
52 LEFT JOIN pg_attrdef d on c.oid=d.adrelid and a.attnum=d.adnum
59 $table = $db->tableName( $table, 'raw' );
62 $db->addQuotes( $db->getCoreSchema() ),
63 $db->addQuotes( $table ),
64 $db->addQuotes( $field )
67 $row = $db->fetchObject( $res );
71 $n = new PostgresField
;
72 $n->type
= $row->typname
;
73 $n->nullable
= ( $row->attnotnull
== 'f' );
75 $n->tablename
= $table;
76 $n->max_length
= $row->attlen
;
77 $n->deferrable
= ( $row->deferrable
== 't' );
78 $n->deferred
= ( $row->deferred
== 't' );
79 $n->conname
= $row->conname
;
80 $n->has_default
= ( $row->atthasdef
=== 't' );
81 $n->default = $row->adsrc
;
89 function tableName() {
90 return $this->tablename
;
97 function isNullable() {
98 return $this->nullable
;
101 function maxLength() {
102 return $this->max_length
;
105 function is_deferrable() {
106 return $this->deferrable
;
109 function is_deferred() {
110 return $this->deferred
;
114 return $this->conname
;
119 function defaultValue() {
120 if( $this->has_default
) {
121 return $this->default;
130 * Used to debug transaction processing
131 * Only used if $wgDebugDBTransactions is true
136 class PostgresTransactionState
{
138 static $WATCHED = array(
140 "desc" => "Connection state changed from %s -> %s\n",
142 PGSQL_CONNECTION_OK
=> "OK",
143 PGSQL_CONNECTION_BAD
=> "BAD"
147 "desc" => "Transaction state changed from %s -> %s\n",
149 PGSQL_TRANSACTION_IDLE
=> "IDLE",
150 PGSQL_TRANSACTION_ACTIVE
=> "ACTIVE",
151 PGSQL_TRANSACTION_INTRANS
=> "TRANS",
152 PGSQL_TRANSACTION_INERROR
=> "ERROR",
153 PGSQL_TRANSACTION_UNKNOWN
=> "UNKNOWN"
158 public function __construct( $conn ) {
159 $this->mConn
= $conn;
161 $this->mCurrentState
= $this->mNewState
;
164 public function update() {
165 $this->mNewState
= array(
166 pg_connection_status( $this->mConn
),
167 pg_transaction_status( $this->mConn
)
171 public function check() {
172 global $wgDebugDBTransactions;
174 if ( $wgDebugDBTransactions ) {
175 if ( $this->mCurrentState
!== $this->mNewState
) {
176 $old = reset( $this->mCurrentState
);
177 $new = reset( $this->mNewState
);
178 foreach ( self
::$WATCHED as $watched ) {
180 $this->log_changed($old, $new, $watched);
182 $old = next( $this->mCurrentState
);
183 $new = next( $this->mNewState
);
188 $this->mCurrentState
= $this->mNewState
;
191 protected function describe_changed( $status, $desc_table ) {
192 if( isset( $desc_table[$status] ) ) {
193 return $desc_table[$status];
195 return "STATUS " . $status;
199 protected function log_changed( $old, $new, $watched ) {
200 wfDebug(sprintf($watched["desc"],
201 $this->describe_changed( $old, $watched["states"] ),
202 $this->describe_changed( $new, $watched["states"] ))
210 class DatabasePostgres
extends DatabaseBase
{
211 var $mInsertId = null;
212 var $mLastResult = null;
213 var $numeric_version = null;
214 var $mAffectedRows = null;
220 function cascadingDeletes() {
223 function cleanupTriggers() {
226 function strictIPs() {
229 function realTimestamps() {
232 function implicitGroupby() {
235 function implicitOrderby() {
238 function searchableIPs() {
241 function functionalIndexes() {
245 function hasConstraint( $name ) {
246 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" .
247 pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn
, $this->getCoreSchema() ) ."'";
248 $res = $this->doQuery( $SQL );
249 return $this->numRows( $res );
253 * Usually aborts on failure
254 * @return DatabaseBase|null
256 function open( $server, $user, $password, $dbName ) {
257 # Test for Postgres support, to avoid suppressed fatal error
258 if ( !function_exists( 'pg_connect' ) ) {
259 throw new DBConnectionError( $this, "Postgres functions missing, have you compiled PHP with the --with-pgsql option?\n (Note: if you recently installed PHP, you may need to restart your webserver and database)\n" );
264 if ( !strlen( $user ) ) { # e.g. the class is being loaded
268 $this->mServer
= $server;
270 $this->mUser
= $user;
271 $this->mPassword
= $password;
272 $this->mDBname
= $dbName;
274 $connectVars = array(
277 'password' => $password
279 if ( $server != false && $server != '' ) {
280 $connectVars['host'] = $server;
282 if ( $port != false && $port != '' ) {
283 $connectVars['port'] = $port;
285 $this->connectString
= $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
287 $this->installErrorHandler();
288 $this->mConn
= pg_connect( $this->connectString
);
289 $phpError = $this->restoreErrorHandler();
291 if ( !$this->mConn
) {
292 wfDebug( "DB connection error\n" );
293 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
294 wfDebug( $this->lastError() . "\n" );
295 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
298 $this->mOpened
= true;
299 $this->mTransactionState
= new PostgresTransactionState( $this->mConn
);
301 global $wgCommandLineMode;
302 # If called from the command-line (e.g. importDump), only show errors
303 if ( $wgCommandLineMode ) {
304 $this->doQuery( "SET client_min_messages = 'ERROR'" );
307 $this->query( "SET client_encoding='UTF8'", __METHOD__
);
308 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__
);
309 $this->query( "SET timezone = 'GMT'", __METHOD__
);
310 $this->query( "SET standard_conforming_strings = on", __METHOD__
);
312 global $wgDBmwschema;
313 $this->determineCoreSchema( $wgDBmwschema );
319 * Postgres doesn't support selectDB in the same way MySQL does. So if the
320 * DB name doesn't match the open connection, open a new one
323 function selectDB( $db ) {
324 if ( $this->mDBname
!== $db ) {
325 return (bool)$this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $db );
331 function makeConnectionString( $vars ) {
333 foreach ( $vars as $name => $value ) {
334 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
340 * Closes a database connection, if it is open
341 * Returns success, true if already closed
344 protected function closeConnection() {
345 return pg_close( $this->mConn
);
348 protected function doQuery( $sql ) {
349 if ( function_exists( 'mb_convert_encoding' ) ) {
350 $sql = mb_convert_encoding( $sql, 'UTF-8' );
352 $this->mTransactionState
->check();
353 if( pg_send_query( $this->mConn
, $sql ) === false ) {
354 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
356 $this->mLastResult
= pg_get_result( $this->mConn
);
357 $this->mTransactionState
->check();
358 $this->mAffectedRows
= null;
359 if ( pg_result_error( $this->mLastResult
) ) {
362 return $this->mLastResult
;
365 protected function dumpError () {
366 $diags = array( PGSQL_DIAG_SEVERITY
,
368 PGSQL_DIAG_MESSAGE_PRIMARY
,
369 PGSQL_DIAG_MESSAGE_DETAIL
,
370 PGSQL_DIAG_MESSAGE_HINT
,
371 PGSQL_DIAG_STATEMENT_POSITION
,
372 PGSQL_DIAG_INTERNAL_POSITION
,
373 PGSQL_DIAG_INTERNAL_QUERY
,
375 PGSQL_DIAG_SOURCE_FILE
,
376 PGSQL_DIAG_SOURCE_LINE
,
377 PGSQL_DIAG_SOURCE_FUNCTION
);
378 foreach ( $diags as $d ) {
379 wfDebug( sprintf("PgSQL ERROR(%d): %s\n", $d, pg_result_error_field( $this->mLastResult
, $d ) ) );
383 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
384 /* Transaction stays in the ERROR state until rolledback */
386 /* Check for constraint violation */
387 if ( $errno === '23505' ) {
388 parent
::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
392 /* Don't ignore serious errors */
393 $this->rollback( __METHOD__
);
394 parent
::reportQueryError( $error, $errno, $sql, $fname, false );
398 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
399 return $this->query( $sql, $fname, true );
402 function freeResult( $res ) {
403 if ( $res instanceof ResultWrapper
) {
406 wfSuppressWarnings();
407 $ok = pg_free_result( $res );
410 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
414 function fetchObject( $res ) {
415 if ( $res instanceof ResultWrapper
) {
418 wfSuppressWarnings();
419 $row = pg_fetch_object( $res );
421 # @todo FIXME: HACK HACK HACK HACK debug
423 # @todo hashar: not sure if the following test really trigger if the object
425 if( pg_last_error( $this->mConn
) ) {
426 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
431 function fetchRow( $res ) {
432 if ( $res instanceof ResultWrapper
) {
435 wfSuppressWarnings();
436 $row = pg_fetch_array( $res );
438 if( pg_last_error( $this->mConn
) ) {
439 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
444 function numRows( $res ) {
445 if ( $res instanceof ResultWrapper
) {
448 wfSuppressWarnings();
449 $n = pg_num_rows( $res );
451 if( pg_last_error( $this->mConn
) ) {
452 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
457 function numFields( $res ) {
458 if ( $res instanceof ResultWrapper
) {
461 return pg_num_fields( $res );
464 function fieldName( $res, $n ) {
465 if ( $res instanceof ResultWrapper
) {
468 return pg_field_name( $res, $n );
472 * This must be called after nextSequenceVal
475 function insertId() {
476 return $this->mInsertId
;
479 function dataSeek( $res, $row ) {
480 if ( $res instanceof ResultWrapper
) {
483 return pg_result_seek( $res, $row );
486 function lastError() {
487 if ( $this->mConn
) {
488 if ( $this->mLastResult
) {
489 return pg_result_error( $this->mLastResult
);
491 return pg_last_error();
494 return 'No database connection';
497 function lastErrno() {
498 if ( $this->mLastResult
) {
499 return pg_result_error_field( $this->mLastResult
, PGSQL_DIAG_SQLSTATE
);
505 function affectedRows() {
506 if ( !is_null( $this->mAffectedRows
) ) {
507 // Forced result for simulated queries
508 return $this->mAffectedRows
;
510 if( empty( $this->mLastResult
) ) {
513 return pg_affected_rows( $this->mLastResult
);
517 * Estimate rows in dataset
518 * Returns estimated count, based on EXPLAIN output
519 * This is not necessarily an accurate estimate, so use sparingly
520 * Returns -1 if count cannot be found
521 * Takes same arguments as Database::select()
524 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
525 $options['EXPLAIN'] = true;
526 $res = $this->select( $table, $vars, $conds, $fname, $options );
529 $row = $this->fetchRow( $res );
531 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
539 * Returns information about an index
540 * If errors are explicitly ignored, returns NULL on failure
543 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
544 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
545 $res = $this->query( $sql, $fname );
549 foreach ( $res as $row ) {
550 if ( $row->indexname
== $this->indexName( $index ) ) {
558 * Returns is of attributes used in index
563 function indexAttributes ( $index, $schema = false ) {
564 if ( $schema === false )
565 $schema = $this->getCoreSchema();
567 * A subquery would be not needed if we didn't care about the order
568 * of attributes, but we do
570 $sql = <<<__INDEXATTR__
574 i.indoption[s.g] as option,
577 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
581 ON cis.oid=isub.indexrelid
583 ON cis.relnamespace = ns.oid
584 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
590 ON ci.oid=i.indexrelid
592 ON ct.oid = i.indrelid
594 ON ci.relnamespace = n.oid
596 ci.relname='$index' AND n.nspname='$schema'
597 AND attrelid = ct.oid
598 AND i.indkey[s.g] = attnum
599 AND i.indclass[s.g] = opcls.oid
600 AND pg_am.oid = opcls.opcmethod
602 $res = $this->query($sql, __METHOD__);
605 foreach ( $res as $row ) {
619 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
620 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
621 " AND indexdef LIKE 'CREATE UNIQUE%(" .
622 $this->strencode( $this->indexName( $index ) ) .
624 $res = $this->query( $sql, $fname );
628 foreach ( $res as $row ) {
635 * INSERT wrapper, inserts an array into a table
637 * $args may be a single associative array, or an array of these with numeric keys,
638 * for multi-row insert (Postgres version 8.2 and above only).
640 * @param $table String: Name of the table to insert to.
641 * @param $args Array: Items to insert into the table.
642 * @param $fname String: Name of the function, for profiling
643 * @param $options String or Array. Valid options: IGNORE
645 * @return bool Success of insert operation. IGNORE always returns true.
647 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
648 if ( !count( $args ) ) {
652 $table = $this->tableName( $table );
653 if (! isset( $this->numeric_version ) ) {
654 $this->getServerVersion();
657 if ( !is_array( $options ) ) {
658 $options = array( $options );
661 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
663 $keys = array_keys( $args[0] );
666 $keys = array_keys( $args );
669 // If IGNORE is set, we use savepoints to emulate mysql's behavior
670 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
672 // If we are not in a transaction, we need to be for savepoint trickery
675 if ( !$this->mTrxLevel ) {
676 $this->begin( __METHOD__ );
679 $olde = error_reporting( 0 );
680 // For future use, we may want to track the number of actual inserts
681 // Right now, insert (all writes) simply return true/false
682 $numrowsinserted = 0;
685 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
688 if ( $this->numeric_version >= 8.2 && !$ignore ) {
690 foreach ( $args as $row ) {
696 $sql .= '(' . $this->makeList( $row ) . ')';
698 $res = (bool)$this->query( $sql, $fname, $ignore );
702 foreach ( $args as $row ) {
704 $tempsql .= '(' . $this->makeList( $row ) . ')';
707 $this->doQuery( "SAVEPOINT $ignore" );
710 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
713 $bar = pg_last_error();
714 if ( $bar != false ) {
715 $this->doQuery( $this->mConn, "ROLLBACK TO $ignore" );
717 $this->doQuery( $this->mConn, "RELEASE $ignore" );
722 // If any of them fail, we fail overall for this function call
723 // Note that this will be ignored if IGNORE is set
730 // Not multi, just a lone insert
732 $this->doQuery( "SAVEPOINT $ignore" );
735 $sql .= '(' . $this->makeList( $args ) . ')';
736 $res = (bool)$this->query( $sql, $fname, $ignore );
738 $bar = pg_last_error();
739 if ( $bar != false ) {
740 $this->doQuery( "ROLLBACK TO $ignore" );
742 $this->doQuery( "RELEASE $ignore" );
748 $olde = error_reporting( $olde );
750 $this->commit( __METHOD__ );
753 // Set the affected row count for the whole operation
754 $this->mAffectedRows = $numrowsinserted;
756 // IGNORE always returns true
764 * INSERT SELECT wrapper
765 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
766 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
767 * $conds may be "*" to copy the whole table
768 * srcTable may be an array of tables.
769 * @todo FIXME: Implement this a little better (seperate select/insert)?
772 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
773 $insertOptions = array(), $selectOptions = array() )
775 $destTable = $this->tableName( $destTable );
777 // If IGNORE is set, we use savepoints to emulate mysql's behavior
778 $ignore = in_array( 'IGNORE', $insertOptions ) ? 'mw' : '';
780 if( is_array( $insertOptions ) ) {
781 $insertOptions = implode( ' ', $insertOptions ); // FIXME: This is unused
783 if( !is_array( $selectOptions ) ) {
784 $selectOptions = array( $selectOptions );
786 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
787 if( is_array( $srcTable ) ) {
788 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
790 $srcTable = $this->tableName( $srcTable );
793 // If we are not in a transaction, we need to be for savepoint trickery
796 if( !$this->mTrxLevel ) {
797 $this->begin( __METHOD__ );
800 $olde = error_reporting( 0 );
801 $numrowsinserted = 0;
802 $this->doQuery( "SAVEPOINT $ignore" );
805 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
806 " SELECT $startOpts " . implode( ',', $varMap ) .
807 " FROM $srcTable $useIndex";
809 if ( $conds != '*' ) {
810 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
813 $sql .= " $tailOpts";
815 $res = (bool)$this->query( $sql, $fname, $ignore );
817 $bar = pg_last_error();
818 if( $bar != false ) {
819 $this->doQuery( "ROLLBACK TO $ignore" );
821 $this->doQuery( "RELEASE $ignore" );
824 $olde = error_reporting( $olde );
826 $this->commit( __METHOD__ );
829 // Set the affected row count for the whole operation
830 $this->mAffectedRows = $numrowsinserted;
832 // IGNORE always returns true
839 function tableName( $name, $format = 'quoted' ) {
840 # Replace reserved words with better ones
843 return $this->realTableName( 'mwuser', $format );
845 return $this->realTableName( 'pagecontent', $format );
847 return $this->realTableName( $name, $format );
851 /* Don't cheat on installer */
852 function realTableName( $name, $format = 'quoted' ) {
853 return parent::tableName( $name, $format );
857 * Return the next in a sequence, save the value for retrieval via insertId()
860 function nextSequenceValue( $seqName ) {
861 $safeseq = str_replace( "'", "''", $seqName );
862 $res = $this->query( "SELECT nextval('$safeseq')" );
863 $row = $this->fetchRow( $res );
864 $this->mInsertId = $row[0];
865 return $this->mInsertId;
869 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
872 function currentSequenceValue( $seqName ) {
873 $safeseq = str_replace( "'", "''", $seqName );
874 $res = $this->query( "SELECT currval('$safeseq')" );
875 $row = $this->fetchRow( $res );
880 # Returns the size of a text field, or -1 for "unlimited"
881 function textFieldSize( $table, $field ) {
882 $table = $this->tableName( $table );
883 $sql = "SELECT t.typname as ftype,a.atttypmod as size
884 FROM pg_class c, pg_attribute a, pg_type t
885 WHERE relname='$table' AND a.attrelid=c.oid AND
886 a.atttypid=t.oid and a.attname='$field'";
887 $res =$this->query( $sql );
888 $row = $this->fetchObject( $res );
889 if ( $row->ftype == 'varchar' ) {
890 $size = $row->size - 4;
897 function limitResult( $sql, $limit, $offset = false ) {
898 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
901 function wasDeadlock() {
902 return $this->lastErrno() == '40P01';
905 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
906 $newName = $this->addIdentifierQuotes( $newName );
907 $oldName = $this->addIdentifierQuotes( $oldName );
908 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
911 function listTables( $prefix = null, $fname = 'DatabasePostgres::listTables' ) {
912 $eschema = $this->addQuotes( $this->getCoreSchema() );
913 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
916 foreach( $result as $table ) {
917 $vars = get_object_vars($table);
918 $table = array_pop( $vars );
919 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
920 $endArray[] = $table;
927 function timestamp( $ts = 0 ) {
928 return wfTimestamp( TS_POSTGRES, $ts );
932 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
933 * to http://www.php.net/manual/en/ref.pgsql.php
935 * Parsing a postgres array can be a tricky problem, he's my
936 * take on this, it handles multi-dimensional arrays plus
937 * escaping using a nasty regexp to determine the limits of each
940 * This should really be handled by PHP PostgreSQL module
943 * @param $text string: postgreql array returned in a text form like {a,b}
944 * @param $output string
949 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
950 if( false === $limit ) {
951 $limit = strlen( $text )-1;
954 if( '{}' == $text ) {
958 if ( '{' != $text{$offset} ) {
959 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
960 $text, $match, 0, $offset );
961 $offset += strlen( $match[0] );
962 $output[] = ( '"' != $match[1]{0}
964 : stripcslashes( substr( $match[1], 1, -1 ) ) );
965 if ( '},' == $match[3] ) {
969 $offset = $this->pg_array_parse( $text, $output, $limit, $offset+1 );
971 } while ( $limit > $offset );
976 * Return aggregated value function call
978 function aggregateValue( $valuedata, $valuename = 'value' ) {
983 * @return string wikitext of a link to the server software's web site
985 public static function getSoftwareLink() {
986 return '[http://www.postgresql.org/ PostgreSQL]';
991 * Return current schema (executes SELECT current_schema())
995 * @return string return default schema for the current session
997 function getCurrentSchema() {
998 $res = $this->query( "SELECT current_schema()", __METHOD__);
999 $row = $this->fetchRow( $res );
1004 * Return list of schemas which are accessible without schema name
1005 * This is list does not contain magic keywords like "$user"
1008 * @seealso getSearchPath()
1009 * @seealso setSearchPath()
1011 * @return array list of actual schemas for the current sesson
1013 function getSchemas() {
1014 $res = $this->query( "SELECT current_schemas(false)", __METHOD__);
1015 $row = $this->fetchRow( $res );
1017 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
1018 return $this->pg_array_parse($row[0], $schemas);
1022 * Return search patch for schemas
1023 * This is different from getSchemas() since it contain magic keywords
1028 * @return array how to search for table names schemas for the current user
1030 function getSearchPath() {
1031 $res = $this->query( "SHOW search_path", __METHOD__);
1032 $row = $this->fetchRow( $res );
1033 /* PostgreSQL returns SHOW values as strings */
1034 return explode(",", $row[0]);
1038 * Update search_path, values should already be sanitized
1039 * Values may contain magic keywords like "$user"
1042 * @param $search_path array list of schemas to be searched by default
1044 function setSearchPath( $search_path ) {
1045 $this->query( "SET search_path = " . implode(", ", $search_path) );
1049 * Determine default schema for MediaWiki core
1050 * Adjust this session schema search path if desired schema exists
1051 * and is not alread there.
1053 * We need to have name of the core schema stored to be able
1054 * to query database metadata.
1056 * This will be also called by the installer after the schema is created
1059 * @param desired_schema string
1061 function determineCoreSchema( $desired_schema ) {
1062 $this->begin( __METHOD__ );
1063 if ( $this->schemaExists( $desired_schema ) ) {
1064 if ( in_array( $desired_schema, $this->getSchemas() ) ) {
1065 $this->mCoreSchema = $desired_schema;
1066 wfDebug("Schema \"" . $desired_schema . "\" already in the search path\n");
1069 * Prepend our schema (e.g. 'mediawiki') in front
1070 * of the search path
1073 $search_path = $this->getSearchPath();
1074 array_unshift( $search_path,
1075 $this->addIdentifierQuotes( $desired_schema ));
1076 $this->setSearchPath( $search_path );
1077 $this->mCoreSchema = $desired_schema;
1078 wfDebug("Schema \"" . $desired_schema . "\" added to the search path\n");
1081 $this->mCoreSchema = $this->getCurrentSchema();
1082 wfDebug("Schema \"" . $desired_schema . "\" not found, using current \"". $this->mCoreSchema ."\"\n");
1084 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1085 $this->commit( __METHOD__ );
1089 * Return schema name fore core MediaWiki tables
1092 * @return string core schema name
1094 function getCoreSchema() {
1095 return $this->mCoreSchema;
1099 * @return string Version information from the database
1101 function getServerVersion() {
1102 if ( !isset( $this->numeric_version ) ) {
1103 $versionInfo = pg_version( $this->mConn );
1104 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1105 // Old client, abort install
1106 $this->numeric_version = '7.3 or earlier';
1107 } elseif ( isset( $versionInfo['server'] ) ) {
1109 $this->numeric_version = $versionInfo['server'];
1111 // Bug 16937: broken pgsql extension from PHP<5.3
1112 $this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
1115 return $this->numeric_version;
1119 * Query whether a given relation exists (in the given schema, or the
1120 * default mw one if not given)
1123 function relationExists( $table, $types, $schema = false ) {
1124 if ( !is_array( $types ) ) {
1125 $types = array( $types );
1128 $schema = $this->getCoreSchema();
1130 $table = $this->realTableName( $table, 'raw' );
1131 $etable = $this->addQuotes( $table );
1132 $eschema = $this->addQuotes( $schema );
1133 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1134 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1135 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1136 $res = $this->query( $SQL );
1137 $count = $res ? $res->numRows() : 0;
1138 return (bool)$count;
1142 * For backward compatibility, this function checks both tables and
1146 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1147 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1150 function sequenceExists( $sequence, $schema = false ) {
1151 return $this->relationExists( $sequence, 'S', $schema );
1154 function triggerExists( $table, $trigger ) {
1156 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1157 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1158 AND tgrelid=pg_class.oid
1159 AND nspname=%s AND relname=%s AND tgname=%s
1161 $res = $this->query(
1164 $this->addQuotes( $this->getCoreSchema() ),
1165 $this->addQuotes( $table ),
1166 $this->addQuotes( $trigger )
1172 $rows = $res->numRows();
1176 function ruleExists( $table, $rule ) {
1177 $exists = $this->selectField( 'pg_rules', 'rulename',
1179 'rulename' => $rule,
1180 'tablename' => $table,
1181 'schemaname' => $this->getCoreSchema()
1184 return $exists === $rule;
1187 function constraintExists( $table, $constraint ) {
1188 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1189 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1190 $this->addQuotes( $this->getCoreSchema() ),
1191 $this->addQuotes( $table ),
1192 $this->addQuotes( $constraint )
1194 $res = $this->query( $SQL );
1198 $rows = $res->numRows();
1203 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1206 function schemaExists( $schema ) {
1207 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1208 array( 'nspname' => $schema ), __METHOD__ );
1209 return (bool)$exists;
1213 * Returns true if a given role (i.e. user) exists, false otherwise.
1216 function roleExists( $roleName ) {
1217 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1218 array( 'rolname' => $roleName ), __METHOD__ );
1219 return (bool)$exists;
1222 function fieldInfo( $table, $field ) {
1223 return PostgresField::fromText( $this, $table, $field );
1227 * pg_field_type() wrapper
1230 function fieldType( $res, $index ) {
1231 if ( $res instanceof ResultWrapper ) {
1232 $res = $res->result;
1234 return pg_field_type( $res, $index );
1237 /* Not even sure why this is used in the main codebase... */
1238 function limitResultForUpdate( $sql, $num ) {
1246 function encodeBlob( $b ) {
1247 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
1250 function decodeBlob( $b ) {
1251 if ( $b instanceof Blob ) {
1254 return pg_unescape_bytea( $b );
1257 function strencode( $s ) { # Should not be called by us
1258 return pg_escape_string( $this->mConn, $s );
1262 * @param $s null|bool|Blob
1263 * @return int|string
1265 function addQuotes( $s ) {
1266 if ( is_null( $s ) ) {
1268 } elseif ( is_bool( $s ) ) {
1269 return intval( $s );
1270 } elseif ( $s instanceof Blob ) {
1271 return "'" . $s->fetch( $s ) . "'";
1273 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1277 * Postgres specific version of replaceVars.
1278 * Calls the parent version in Database.php
1282 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1284 * @return string SQL string
1286 protected function replaceVars( $ins ) {
1287 $ins = parent::replaceVars( $ins );
1289 if ( $this->numeric_version >= 8.3 ) {
1290 // Thanks for not providing backwards-compatibility, 8.3
1291 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1294 if ( $this->numeric_version <= 8.1 ) { // Our minimum version
1295 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1302 * Various select options
1306 * @param $options Array: an associative array of options to be turned into
1307 * an SQL query, valid keys are listed in the function.
1310 function makeSelectOptions( $options ) {
1311 $preLimitTail = $postLimitTail = '';
1312 $startOpts = $useIndex = '';
1314 $noKeyOptions = array();
1315 foreach ( $options as $key => $option ) {
1316 if ( is_numeric( $key ) ) {
1317 $noKeyOptions[$option] = true;
1321 if ( isset( $options['GROUP BY'] ) ) {
1322 $gb = is_array( $options['GROUP BY'] )
1323 ? implode( ',', $options['GROUP BY'] )
1324 : $options['GROUP BY'];
1325 $preLimitTail .= " GROUP BY {$gb}";
1328 if ( isset( $options['HAVING'] ) ) {
1329 $preLimitTail .= " HAVING {$options['HAVING']}";
1332 if ( isset( $options['ORDER BY'] ) ) {
1333 $ob = is_array( $options['ORDER BY'] )
1334 ? implode( ',', $options['ORDER BY'] )
1335 : $options['ORDER BY'];
1336 $preLimitTail .= " ORDER BY {$ob}";
1339 //if ( isset( $options['LIMIT'] ) ) {
1340 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1341 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1345 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1346 $postLimitTail .= ' FOR UPDATE';
1348 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1349 $postLimitTail .= ' LOCK IN SHARE MODE';
1351 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1352 $startOpts .= 'DISTINCT';
1355 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1358 function setFakeMaster( $enabled = true ) {}
1360 function getDBname() {
1361 return $this->mDBname;
1364 function getServer() {
1365 return $this->mServer;
1368 function buildConcat( $stringList ) {
1369 return implode( ' || ', $stringList );
1372 public function getSearchEngine() {
1373 return 'SearchPostgres';
1376 public function streamStatementEnd( &$sql, &$newLine ) {
1377 # Allow dollar quoting for function declarations
1378 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1379 if ( $this->delimiter ) {
1380 $this->delimiter = false;
1383 $this->delimiter = ';';
1386 return parent::streamStatementEnd( $sql, $newLine );
1388 } // end DatabasePostgres class