3 * This is the Postgres database abstraction layer.
9 class PostgresField
implements Field
{
10 private $name, $tablename, $type, $nullable, $max_length, $deferred, $deferrable, $conname;
13 * @param $db DatabaseBase
16 * @return null|PostgresField
18 static function fromText( $db, $table, $field ) {
21 attnotnull, attlen, conname AS conname,
24 COALESCE(condeferred, 'f') AS deferred,
25 COALESCE(condeferrable, 'f') AS deferrable,
26 CASE WHEN typname = 'int2' THEN 'smallint'
27 WHEN typname = 'int4' THEN 'integer'
28 WHEN typname = 'int8' THEN 'bigint'
29 WHEN typname = 'bpchar' THEN 'char'
30 ELSE typname END AS typname
32 JOIN pg_namespace n ON (n.oid = c.relnamespace)
33 JOIN pg_attribute a ON (a.attrelid = c.oid)
34 JOIN pg_type t ON (t.oid = a.atttypid)
35 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
42 $table = $db->tableName( $table, 'raw' );
45 $db->addQuotes( $db->getCoreSchema() ),
46 $db->addQuotes( $table ),
47 $db->addQuotes( $field )
50 $row = $db->fetchObject( $res );
54 $n = new PostgresField
;
55 $n->type
= $row->typname
;
56 $n->nullable
= ( $row->attnotnull
== 'f' );
58 $n->tablename
= $table;
59 $n->max_length
= $row->attlen
;
60 $n->deferrable
= ( $row->deferrable
== 't' );
61 $n->deferred
= ( $row->deferred
== 't' );
62 $n->conname
= $row->conname
;
70 function tableName() {
71 return $this->tablename
;
78 function isNullable() {
79 return $this->nullable
;
82 function maxLength() {
83 return $this->max_length
;
86 function is_deferrable() {
87 return $this->deferrable
;
90 function is_deferred() {
91 return $this->deferred
;
95 return $this->conname
;
101 * Used to debug transaction processing
102 * Only used if $wgDebugDBTransactions is true
107 class PostgresTransactionState
{
109 static $WATCHED = array(
111 "desc" => "Connection state changed from %s -> %s\n",
113 PGSQL_CONNECTION_OK
=> "OK",
114 PGSQL_CONNECTION_BAD
=> "BAD"
118 "desc" => "Transaction state changed from %s -> %s\n",
120 PGSQL_TRANSACTION_IDLE
=> "IDLE",
121 PGSQL_TRANSACTION_ACTIVE
=> "ACTIVE",
122 PGSQL_TRANSACTION_INTRANS
=> "TRANS",
123 PGSQL_TRANSACTION_INERROR
=> "ERROR",
124 PGSQL_TRANSACTION_UNKNOWN
=> "UNKNOWN"
129 public function __construct( $conn ) {
130 $this->mConn
= $conn;
132 $this->mCurrentState
= $this->mNewState
;
135 public function update() {
136 $this->mNewState
= array(
137 pg_connection_status( $this->mConn
),
138 pg_transaction_status( $this->mConn
)
142 public function check() {
143 global $wgDebugDBTransactions;
145 if ( $wgDebugDBTransactions ) {
146 if ( $this->mCurrentState
!== $this->mNewState
) {
147 $old = reset( $this->mCurrentState
);
148 $new = reset( $this->mNewState
);
149 foreach ( self
::$WATCHED as $watched ) {
151 $this->log_changed($old, $new, $watched);
153 $old = next( $this->mCurrentState
);
154 $new = next( $this->mNewState
);
159 $this->mCurrentState
= $this->mNewState
;
162 protected function describe_changed( $status, $desc_table ) {
163 if( isset( $desc_table[$status] ) ) {
164 return $desc_table[$status];
166 return "STATUS " . $status;
170 protected function log_changed( $old, $new, $watched ) {
171 wfDebug(sprintf($watched["desc"],
172 $this->describe_changed( $old, $watched["states"] ),
173 $this->describe_changed( $new, $watched["states"] ))
181 class DatabasePostgres
extends DatabaseBase
{
182 var $mInsertId = null;
183 var $mLastResult = null;
184 var $numeric_version = null;
185 var $mAffectedRows = null;
191 function cascadingDeletes() {
194 function cleanupTriggers() {
197 function strictIPs() {
200 function realTimestamps() {
203 function implicitGroupby() {
206 function implicitOrderby() {
209 function searchableIPs() {
212 function functionalIndexes() {
216 function hasConstraint( $name ) {
217 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" .
218 pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn
, $this->getCoreSchema() ) ."'";
219 $res = $this->doQuery( $SQL );
220 return $this->numRows( $res );
224 * Usually aborts on failure
225 * @return DatabaseBase|null
227 function open( $server, $user, $password, $dbName ) {
228 # Test for Postgres support, to avoid suppressed fatal error
229 if ( !function_exists( 'pg_connect' ) ) {
230 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" );
235 if ( !strlen( $user ) ) { # e.g. the class is being loaded
239 $this->mServer
= $server;
241 $this->mUser
= $user;
242 $this->mPassword
= $password;
243 $this->mDBname
= $dbName;
245 $connectVars = array(
248 'password' => $password
250 if ( $server != false && $server != '' ) {
251 $connectVars['host'] = $server;
253 if ( $port != false && $port != '' ) {
254 $connectVars['port'] = $port;
256 $this->connectString
= $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
258 $this->installErrorHandler();
259 $this->mConn
= pg_connect( $this->connectString
);
260 $phpError = $this->restoreErrorHandler();
262 if ( !$this->mConn
) {
263 wfDebug( "DB connection error\n" );
264 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
265 wfDebug( $this->lastError() . "\n" );
266 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
269 $this->mOpened
= true;
270 $this->mTransactionState
= new PostgresTransactionState( $this->mConn
);
272 global $wgCommandLineMode;
273 # If called from the command-line (e.g. importDump), only show errors
274 if ( $wgCommandLineMode ) {
275 $this->doQuery( "SET client_min_messages = 'ERROR'" );
278 $this->query( "SET client_encoding='UTF8'", __METHOD__
);
279 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__
);
280 $this->query( "SET timezone = 'GMT'", __METHOD__
);
281 $this->query( "SET standard_conforming_strings = on", __METHOD__
);
283 global $wgDBmwschema;
284 $this->determineCoreSchema( $wgDBmwschema );
290 * Postgres doesn't support selectDB in the same way MySQL does. So if the
291 * DB name doesn't match the open connection, open a new one
294 function selectDB( $db ) {
295 if ( $this->mDBname
!== $db ) {
296 return (bool)$this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $db );
302 function makeConnectionString( $vars ) {
304 foreach ( $vars as $name => $value ) {
305 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
311 * Closes a database connection, if it is open
312 * Returns success, true if already closed
315 protected function closeConnection() {
316 return pg_close( $this->mConn
);
319 protected function doQuery( $sql ) {
320 global $wgDebugDBTransactions;
321 if ( function_exists( 'mb_convert_encoding' ) ) {
322 $sql = mb_convert_encoding( $sql, 'UTF-8' );
324 $this->mTransactionState
->check();
325 $this->mLastResult
= pg_query( $this->mConn
, $sql );
326 $this->mTransactionState
->check();
327 $this->mAffectedRows
= null;
328 return $this->mLastResult
;
331 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
332 /* Transaction stays in the ERROR state until rolledback */
333 $this->rollback( __METHOD__
);
334 parent
::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
338 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
339 return $this->query( $sql, $fname, true );
342 function freeResult( $res ) {
343 if ( $res instanceof ResultWrapper
) {
346 wfSuppressWarnings();
347 $ok = pg_free_result( $res );
350 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
354 function fetchObject( $res ) {
355 if ( $res instanceof ResultWrapper
) {
358 wfSuppressWarnings();
359 $row = pg_fetch_object( $res );
361 # @todo FIXME: HACK HACK HACK HACK debug
363 # @todo hashar: not sure if the following test really trigger if the object
365 if( pg_last_error( $this->mConn
) ) {
366 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
371 function fetchRow( $res ) {
372 if ( $res instanceof ResultWrapper
) {
375 wfSuppressWarnings();
376 $row = pg_fetch_array( $res );
378 if( pg_last_error( $this->mConn
) ) {
379 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
384 function numRows( $res ) {
385 if ( $res instanceof ResultWrapper
) {
388 wfSuppressWarnings();
389 $n = pg_num_rows( $res );
391 if( pg_last_error( $this->mConn
) ) {
392 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
397 function numFields( $res ) {
398 if ( $res instanceof ResultWrapper
) {
401 return pg_num_fields( $res );
404 function fieldName( $res, $n ) {
405 if ( $res instanceof ResultWrapper
) {
408 return pg_field_name( $res, $n );
412 * This must be called after nextSequenceVal
415 function insertId() {
416 return $this->mInsertId
;
419 function dataSeek( $res, $row ) {
420 if ( $res instanceof ResultWrapper
) {
423 return pg_result_seek( $res, $row );
426 function lastError() {
427 if ( $this->mConn
) {
428 return pg_last_error();
430 return 'No database connection';
433 function lastErrno() {
434 return pg_last_error() ?
1 : 0;
437 function affectedRows() {
438 if ( !is_null( $this->mAffectedRows
) ) {
439 // Forced result for simulated queries
440 return $this->mAffectedRows
;
442 if( empty( $this->mLastResult
) ) {
445 return pg_affected_rows( $this->mLastResult
);
449 * Estimate rows in dataset
450 * Returns estimated count, based on EXPLAIN output
451 * This is not necessarily an accurate estimate, so use sparingly
452 * Returns -1 if count cannot be found
453 * Takes same arguments as Database::select()
456 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
457 $options['EXPLAIN'] = true;
458 $res = $this->select( $table, $vars, $conds, $fname, $options );
461 $row = $this->fetchRow( $res );
463 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
471 * Returns information about an index
472 * If errors are explicitly ignored, returns NULL on failure
475 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
476 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
477 $res = $this->query( $sql, $fname );
481 foreach ( $res as $row ) {
482 if ( $row->indexname
== $this->indexName( $index ) ) {
489 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
490 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
491 " AND indexdef LIKE 'CREATE UNIQUE%(" .
492 $this->strencode( $this->indexName( $index ) ) .
494 $res = $this->query( $sql, $fname );
498 foreach ( $res as $row ) {
505 * INSERT wrapper, inserts an array into a table
507 * $args may be a single associative array, or an array of these with numeric keys,
508 * for multi-row insert (Postgres version 8.2 and above only).
510 * @param $table String: Name of the table to insert to.
511 * @param $args Array: Items to insert into the table.
512 * @param $fname String: Name of the function, for profiling
513 * @param $options String or Array. Valid options: IGNORE
515 * @return bool Success of insert operation. IGNORE always returns true.
517 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
518 if ( !count( $args ) ) {
522 $table = $this->tableName( $table );
523 if (! isset( $this->numeric_version
) ) {
524 $this->getServerVersion();
527 if ( !is_array( $options ) ) {
528 $options = array( $options );
531 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
533 $keys = array_keys( $args[0] );
536 $keys = array_keys( $args );
539 // If IGNORE is set, we use savepoints to emulate mysql's behavior
540 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
542 // If we are not in a transaction, we need to be for savepoint trickery
545 if ( !$this->mTrxLevel
) {
546 $this->begin( __METHOD__
);
549 $olde = error_reporting( 0 );
550 // For future use, we may want to track the number of actual inserts
551 // Right now, insert (all writes) simply return true/false
552 $numrowsinserted = 0;
555 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
558 if ( $this->numeric_version
>= 8.2 && !$ignore ) {
560 foreach ( $args as $row ) {
566 $sql .= '(' . $this->makeList( $row ) . ')';
568 $res = (bool)$this->query( $sql, $fname, $ignore );
572 foreach ( $args as $row ) {
574 $tempsql .= '(' . $this->makeList( $row ) . ')';
577 $this->doQuery( "SAVEPOINT $ignore" );
580 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
583 $bar = pg_last_error();
584 if ( $bar != false ) {
585 $this->doQuery( $this->mConn
, "ROLLBACK TO $ignore" );
587 $this->doQuery( $this->mConn
, "RELEASE $ignore" );
592 // If any of them fail, we fail overall for this function call
593 // Note that this will be ignored if IGNORE is set
600 // Not multi, just a lone insert
602 $this->doQuery( "SAVEPOINT $ignore" );
605 $sql .= '(' . $this->makeList( $args ) . ')';
606 $res = (bool)$this->query( $sql, $fname, $ignore );
608 $bar = pg_last_error();
609 if ( $bar != false ) {
610 $this->doQuery( "ROLLBACK TO $ignore" );
612 $this->doQuery( "RELEASE $ignore" );
618 $olde = error_reporting( $olde );
620 $this->commit( __METHOD__
);
623 // Set the affected row count for the whole operation
624 $this->mAffectedRows
= $numrowsinserted;
626 // IGNORE always returns true
634 * INSERT SELECT wrapper
635 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
636 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
637 * $conds may be "*" to copy the whole table
638 * srcTable may be an array of tables.
639 * @todo FIXME: Implement this a little better (seperate select/insert)?
642 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
643 $insertOptions = array(), $selectOptions = array() )
645 $destTable = $this->tableName( $destTable );
647 // If IGNORE is set, we use savepoints to emulate mysql's behavior
648 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
650 if( is_array( $insertOptions ) ) {
651 $insertOptions = implode( ' ', $insertOptions ); // FIXME: This is unused
653 if( !is_array( $selectOptions ) ) {
654 $selectOptions = array( $selectOptions );
656 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
657 if( is_array( $srcTable ) ) {
658 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
660 $srcTable = $this->tableName( $srcTable );
663 // If we are not in a transaction, we need to be for savepoint trickery
666 if( !$this->mTrxLevel
) {
667 $this->begin( __METHOD__
);
670 $olde = error_reporting( 0 );
671 $numrowsinserted = 0;
672 $this->doQuery( "SAVEPOINT $ignore" );
675 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
676 " SELECT $startOpts " . implode( ',', $varMap ) .
677 " FROM $srcTable $useIndex";
679 if ( $conds != '*' ) {
680 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
683 $sql .= " $tailOpts";
685 $res = (bool)$this->query( $sql, $fname, $ignore );
687 $bar = pg_last_error();
688 if( $bar != false ) {
689 $this->doQuery( "ROLLBACK TO $ignore" );
691 $this->doQuery( "RELEASE $ignore" );
694 $olde = error_reporting( $olde );
696 $this->commit( __METHOD__
);
699 // Set the affected row count for the whole operation
700 $this->mAffectedRows
= $numrowsinserted;
702 // IGNORE always returns true
709 function tableName( $name, $format = 'quoted' ) {
710 # Replace reserved words with better ones
715 return 'pagecontent';
717 return parent
::tableName( $name, $format );
722 * Return the next in a sequence, save the value for retrieval via insertId()
725 function nextSequenceValue( $seqName ) {
726 $safeseq = str_replace( "'", "''", $seqName );
727 $res = $this->query( "SELECT nextval('$safeseq')" );
728 $row = $this->fetchRow( $res );
729 $this->mInsertId
= $row[0];
730 return $this->mInsertId
;
734 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
737 function currentSequenceValue( $seqName ) {
738 $safeseq = str_replace( "'", "''", $seqName );
739 $res = $this->query( "SELECT currval('$safeseq')" );
740 $row = $this->fetchRow( $res );
745 # Returns the size of a text field, or -1 for "unlimited"
746 function textFieldSize( $table, $field ) {
747 $table = $this->tableName( $table );
748 $sql = "SELECT t.typname as ftype,a.atttypmod as size
749 FROM pg_class c, pg_attribute a, pg_type t
750 WHERE relname='$table' AND a.attrelid=c.oid AND
751 a.atttypid=t.oid and a.attname='$field'";
752 $res =$this->query( $sql );
753 $row = $this->fetchObject( $res );
754 if ( $row->ftype
== 'varchar' ) {
755 $size = $row->size
- 4;
762 function limitResult( $sql, $limit, $offset = false ) {
763 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " : '' );
766 function wasDeadlock() {
767 return $this->lastErrno() == '40P01';
770 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
771 $newName = $this->addIdentifierQuotes( $newName );
772 $oldName = $this->addIdentifierQuotes( $oldName );
773 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
776 function listTables( $prefix = null, $fname = 'DatabasePostgres::listTables' ) {
777 $eschema = $this->addQuotes( $this->getCoreSchema() );
778 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
781 foreach( $result as $table ) {
782 $vars = get_object_vars($table);
783 $table = array_pop( $vars );
784 if( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
785 $endArray[] = $table;
792 function timestamp( $ts = 0 ) {
793 return wfTimestamp( TS_POSTGRES
, $ts );
797 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
798 * to http://www.php.net/manual/en/ref.pgsql.php
800 * Parsing a postgres array can be a tricky problem, he's my
801 * take on this, it handles multi-dimensional arrays plus
802 * escaping using a nasty regexp to determine the limits of each
805 * This should really be handled by PHP PostgreSQL module
808 * @param $text string: postgreql array returned in a text form like {a,b}
809 * @param $output string
814 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
815 if( false === $limit ) {
816 $limit = strlen( $text )-1;
819 if( '{}' == $text ) {
823 if ( '{' != $text{$offset} ) {
824 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
825 $text, $match, 0, $offset );
826 $offset +
= strlen( $match[0] );
827 $output[] = ( '"' != $match[1]{0}
829 : stripcslashes( substr( $match[1], 1, -1 ) ) );
830 if ( '},' == $match[3] ) {
834 $offset = $this->pg_array_parse( $text, $output, $limit, $offset+
1 );
836 } while ( $limit > $offset );
841 * Return aggregated value function call
843 function aggregateValue( $valuedata, $valuename = 'value' ) {
848 * @return string wikitext of a link to the server software's web site
850 public static function getSoftwareLink() {
851 return '[http://www.postgresql.org/ PostgreSQL]';
856 * Return current schema (executes SELECT current_schema())
860 * @return string return default schema for the current session
862 function getCurrentSchema() {
863 $res = $this->query( "SELECT current_schema()", __METHOD__
);
864 $row = $this->fetchRow( $res );
869 * Return list of schemas which are accessible without schema name
870 * This is list does not contain magic keywords like "$user"
873 * @seealso getSearchPath()
874 * @seealso setSearchPath()
876 * @return array list of actual schemas for the current sesson
878 function getSchemas() {
879 $res = $this->query( "SELECT current_schemas(false)", __METHOD__
);
880 $row = $this->fetchRow( $res );
882 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
883 return $this->pg_array_parse($row[0], $schemas);
887 * Return search patch for schemas
888 * This is different from getSchemas() since it contain magic keywords
893 * @return array how to search for table names schemas for the current user
895 function getSearchPath() {
896 $res = $this->query( "SHOW search_path", __METHOD__
);
897 $row = $this->fetchRow( $res );
898 /* PostgreSQL returns SHOW values as strings */
899 return explode(",", $row[0]);
903 * Update search_path, values should already be sanitized
904 * Values may contain magic keywords like "$user"
907 * @param $search_path array list of schemas to be searched by default
909 function setSearchPath( $search_path ) {
910 $this->query( "SET search_path = " . implode(", ", $search_path) );
914 * Determine default schema for MediaWiki core
915 * Adjust this session schema search path if desired schema exists
916 * and is not alread there.
918 * We need to have name of the core schema stored to be able
919 * to query database metadata.
921 * This will be also called by the installer after the schema is created
924 * @param desired_schema string
926 function determineCoreSchema( $desired_schema ) {
927 $this->begin( __METHOD__
);
928 if ( $this->schemaExists( $desired_schema ) ) {
929 if ( in_array( $desired_schema, $this->getSchemas() ) ) {
930 $this->mCoreSchema
= $desired_schema;
931 wfDebug("Schema \"" . $desired_schema . "\" already in the search path\n");
934 * Append our schema (e.g. 'mediawiki') in front
938 $search_path = $this->getSearchPath();
939 array_unshift( $search_path,
940 $this->addIdentifierQuotes( $desired_schema ));
941 $this->setSearchPath( $search_path );
942 $this->mCoreSchema
= $desired_schema;
943 wfDebug("Schema \"" . $desired_schema . "\" added to the search path\n");
946 $this->mCoreSchema
= $this->getCurrentSchema();
947 wfDebug("Schema \"" . $desired_schema . "\" not found, using current \"". $this->mCoreSchema
."\"\n");
949 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
950 $this->commit( __METHOD__
);
954 * Return schema name fore core MediaWiki tables
957 * @return string core schema name
959 function getCoreSchema() {
960 return $this->mCoreSchema
;
964 * @return string Version information from the database
966 function getServerVersion() {
967 if ( !isset( $this->numeric_version
) ) {
968 $versionInfo = pg_version( $this->mConn
);
969 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
970 // Old client, abort install
971 $this->numeric_version
= '7.3 or earlier';
972 } elseif ( isset( $versionInfo['server'] ) ) {
974 $this->numeric_version
= $versionInfo['server'];
976 // Bug 16937: broken pgsql extension from PHP<5.3
977 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
980 return $this->numeric_version
;
984 * Query whether a given relation exists (in the given schema, or the
985 * default mw one if not given)
988 function relationExists( $table, $types, $schema = false ) {
989 if ( !is_array( $types ) ) {
990 $types = array( $types );
993 $schema = $this->getCoreSchema();
995 $table = $this->tableName( $table, 'raw' );
996 $etable = $this->addQuotes( $table );
997 $eschema = $this->addQuotes( $schema );
998 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
999 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1000 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1001 $res = $this->query( $SQL );
1002 $count = $res ?
$res->numRows() : 0;
1003 return (bool)$count;
1007 * For backward compatibility, this function checks both tables and
1011 function tableExists( $table, $fname = __METHOD__
, $schema = false ) {
1012 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1015 function sequenceExists( $sequence, $schema = false ) {
1016 return $this->relationExists( $sequence, 'S', $schema );
1019 function triggerExists( $table, $trigger ) {
1021 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1022 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1023 AND tgrelid=pg_class.oid
1024 AND nspname=%s AND relname=%s AND tgname=%s
1026 $res = $this->query(
1029 $this->addQuotes( $this->getCoreSchema() ),
1030 $this->addQuotes( $table ),
1031 $this->addQuotes( $trigger )
1037 $rows = $res->numRows();
1041 function ruleExists( $table, $rule ) {
1042 $exists = $this->selectField( 'pg_rules', 'rulename',
1044 'rulename' => $rule,
1045 'tablename' => $table,
1046 'schemaname' => $this->getCoreSchema()
1049 return $exists === $rule;
1052 function constraintExists( $table, $constraint ) {
1053 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1054 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1055 $this->addQuotes( $this->getCoreSchema() ),
1056 $this->addQuotes( $table ),
1057 $this->addQuotes( $constraint )
1059 $res = $this->query( $SQL );
1063 $rows = $res->numRows();
1068 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1071 function schemaExists( $schema ) {
1072 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1073 array( 'nspname' => $schema ), __METHOD__
);
1074 return (bool)$exists;
1078 * Returns true if a given role (i.e. user) exists, false otherwise.
1081 function roleExists( $roleName ) {
1082 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1083 array( 'rolname' => $roleName ), __METHOD__
);
1084 return (bool)$exists;
1087 function fieldInfo( $table, $field ) {
1088 return PostgresField
::fromText( $this, $table, $field );
1092 * pg_field_type() wrapper
1095 function fieldType( $res, $index ) {
1096 if ( $res instanceof ResultWrapper
) {
1097 $res = $res->result
;
1099 return pg_field_type( $res, $index );
1102 /* Not even sure why this is used in the main codebase... */
1103 function limitResultForUpdate( $sql, $num ) {
1111 function encodeBlob( $b ) {
1112 return new Blob( pg_escape_bytea( $this->mConn
, $b ) );
1115 function decodeBlob( $b ) {
1116 if ( $b instanceof Blob
) {
1119 return pg_unescape_bytea( $b );
1122 function strencode( $s ) { # Should not be called by us
1123 return pg_escape_string( $this->mConn
, $s );
1127 * @param $s null|bool|Blob
1128 * @return int|string
1130 function addQuotes( $s ) {
1131 if ( is_null( $s ) ) {
1133 } elseif ( is_bool( $s ) ) {
1134 return intval( $s );
1135 } elseif ( $s instanceof Blob
) {
1136 return "'" . $s->fetch( $s ) . "'";
1138 return "'" . pg_escape_string( $this->mConn
, $s ) . "'";
1142 * Postgres specific version of replaceVars.
1143 * Calls the parent version in Database.php
1147 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1149 * @return string SQL string
1151 protected function replaceVars( $ins ) {
1152 $ins = parent
::replaceVars( $ins );
1154 if ( $this->numeric_version
>= 8.3 ) {
1155 // Thanks for not providing backwards-compatibility, 8.3
1156 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1159 if ( $this->numeric_version
<= 8.1 ) { // Our minimum version
1160 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1167 * Various select options
1171 * @param $options Array: an associative array of options to be turned into
1172 * an SQL query, valid keys are listed in the function.
1175 function makeSelectOptions( $options ) {
1176 $preLimitTail = $postLimitTail = '';
1177 $startOpts = $useIndex = '';
1179 $noKeyOptions = array();
1180 foreach ( $options as $key => $option ) {
1181 if ( is_numeric( $key ) ) {
1182 $noKeyOptions[$option] = true;
1186 if ( isset( $options['GROUP BY'] ) ) {
1187 $gb = is_array( $options['GROUP BY'] )
1188 ?
implode( ',', $options['GROUP BY'] )
1189 : $options['GROUP BY'];
1190 $preLimitTail .= " GROUP BY {$gb}";
1193 if ( isset( $options['HAVING'] ) ) {
1194 $preLimitTail .= " HAVING {$options['HAVING']}";
1197 if ( isset( $options['ORDER BY'] ) ) {
1198 $ob = is_array( $options['ORDER BY'] )
1199 ?
implode( ',', $options['ORDER BY'] )
1200 : $options['ORDER BY'];
1201 $preLimitTail .= " ORDER BY {$ob}";
1204 //if ( isset( $options['LIMIT'] ) ) {
1205 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1206 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1210 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1211 $postLimitTail .= ' FOR UPDATE';
1213 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1214 $postLimitTail .= ' LOCK IN SHARE MODE';
1216 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1217 $startOpts .= 'DISTINCT';
1220 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1223 function setFakeMaster( $enabled = true ) {}
1225 function getDBname() {
1226 return $this->mDBname
;
1229 function getServer() {
1230 return $this->mServer
;
1233 function buildConcat( $stringList ) {
1234 return implode( ' || ', $stringList );
1237 public function getSearchEngine() {
1238 return 'SearchPostgres';
1241 public function streamStatementEnd( &$sql, &$newLine ) {
1242 # Allow dollar quoting for function declarations
1243 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1244 if ( $this->delimiter
) {
1245 $this->delimiter
= false;
1248 $this->delimiter
= ';';
1251 return parent
::streamStatementEnd( $sql, $newLine );
1253 } // end DatabasePostgres class