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, COALESCE(conname, '') AS conname,
22 COALESCE(condeferred, 'f') AS deferred,
23 COALESCE(condeferrable, 'f') AS deferrable,
24 CASE WHEN typname = 'int2' THEN 'smallint'
25 WHEN typname = 'int4' THEN 'integer'
26 WHEN typname = 'int8' THEN 'bigint'
27 WHEN typname = 'bpchar' THEN 'char'
28 ELSE typname END AS typname
30 JOIN pg_namespace n ON (n.oid = c.relnamespace)
31 JOIN pg_attribute a ON (a.attrelid = c.oid)
32 JOIN pg_type t ON (t.oid = a.atttypid)
33 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
40 $table = $db->tableName( $table, 'raw' );
43 $db->addQuotes( $db->getCoreSchema() ),
44 $db->addQuotes( $table ),
45 $db->addQuotes( $field )
48 $row = $db->fetchObject( $res );
52 $n = new PostgresField
;
53 $n->type
= $row->typname
;
54 $n->nullable
= ( $row->attnotnull
== 'f' );
56 $n->tablename
= $table;
57 $n->max_length
= $row->attlen
;
58 $n->deferrable
= ( $row->deferrable
== 't' );
59 $n->deferred
= ( $row->deferred
== 't' );
60 $n->conname
= $row->conname
;
68 function tableName() {
69 return $this->tablename
;
76 function isNullable() {
77 return $this->nullable
;
80 function maxLength() {
81 return $this->max_length
;
84 function is_deferrable() {
85 return $this->deferrable
;
88 function is_deferred() {
89 return $this->deferred
;
93 return $this->conname
;
99 * Used to debug transaction processing
100 * Only used if $wgDebugDBTransactions is true
105 class PostgresTransactionState
{
107 static $WATCHED = array(
109 "desc" => "Connection state changed from %s -> %s\n",
111 PGSQL_CONNECTION_OK
=> "OK",
112 PGSQL_CONNECTION_BAD
=> "BAD"
116 "desc" => "Transaction state changed from %s -> %s\n",
118 PGSQL_TRANSACTION_IDLE
=> "IDLE",
119 PGSQL_TRANSACTION_ACTIVE
=> "ACTIVE",
120 PGSQL_TRANSACTION_INTRANS
=> "TRANS",
121 PGSQL_TRANSACTION_INERROR
=> "ERROR",
122 PGSQL_TRANSACTION_UNKNOWN
=> "UNKNOWN"
127 public function __construct( $conn ) {
128 $this->mConn
= $conn;
130 $this->mCurrentState
= $this->mNewState
;
133 public function update() {
134 $this->mNewState
= array(
135 pg_connection_status( $this->mConn
),
136 pg_transaction_status( $this->mConn
)
140 public function check() {
141 global $wgDebugDBTransactions;
143 if ( $wgDebugDBTransactions ) {
144 if ( $this->mCurrentState
!== $this->mNewState
) {
145 $old = reset( $this->mCurrentState
);
146 $new = reset( $this->mNewState
);
147 foreach ( self
::$WATCHED as $watched ) {
149 $this->log_changed($old, $new, $watched);
151 $old = next( $this->mCurrentState
);
152 $new = next( $this->mNewState
);
157 $this->mCurrentState
= $this->mNewState
;
160 protected function describe_changed( $status, $desc_table ) {
161 if( isset( $desc_table[$status] ) ) {
162 return $desc_table[$status];
164 return "STATUS " . $status;
168 protected function log_changed( $old, $new, $watched ) {
169 wfDebug(sprintf($watched["desc"],
170 $this->describe_changed( $old, $watched["states"] ),
171 $this->describe_changed( $new, $watched["states"] ))
179 class DatabasePostgres
extends DatabaseBase
{
180 var $mInsertId = null;
181 var $mLastResult = null;
182 var $numeric_version = null;
183 var $mAffectedRows = null;
189 function cascadingDeletes() {
192 function cleanupTriggers() {
195 function strictIPs() {
198 function realTimestamps() {
201 function implicitGroupby() {
204 function implicitOrderby() {
207 function searchableIPs() {
210 function functionalIndexes() {
214 function hasConstraint( $name ) {
215 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" .
216 pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn
, $this->mConn
->getCoreSchema() ) ."'";
217 $res = $this->doQuery( $SQL );
218 return $this->numRows( $res );
222 * Usually aborts on failure
223 * @return DatabaseBase|null
225 function open( $server, $user, $password, $dbName ) {
226 # Test for Postgres support, to avoid suppressed fatal error
227 if ( !function_exists( 'pg_connect' ) ) {
228 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" );
233 if ( !strlen( $user ) ) { # e.g. the class is being loaded
237 $this->mServer
= $server;
239 $this->mUser
= $user;
240 $this->mPassword
= $password;
241 $this->mDBname
= $dbName;
243 $connectVars = array(
246 'password' => $password
248 if ( $server != false && $server != '' ) {
249 $connectVars['host'] = $server;
251 if ( $port != false && $port != '' ) {
252 $connectVars['port'] = $port;
254 $this->connectString
= $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
256 $this->installErrorHandler();
257 $this->mConn
= pg_connect( $this->connectString
);
258 $phpError = $this->restoreErrorHandler();
260 if ( !$this->mConn
) {
261 wfDebug( "DB connection error\n" );
262 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
263 wfDebug( $this->lastError() . "\n" );
264 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
267 $this->mOpened
= true;
268 $this->mTransactionState
= new PostgresTransactionState( $this->mConn
);
270 global $wgCommandLineMode;
271 # If called from the command-line (e.g. importDump), only show errors
272 if ( $wgCommandLineMode ) {
273 $this->doQuery( "SET client_min_messages = 'ERROR'" );
276 $this->query( "SET client_encoding='UTF8'", __METHOD__
);
277 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__
);
278 $this->query( "SET timezone = 'GMT'", __METHOD__
);
279 $this->query( "SET standard_conforming_strings = on", __METHOD__
);
281 global $wgDBmwschema;
282 $this->determineCoreSchema( $wgDBmwschema );
288 * Postgres doesn't support selectDB in the same way MySQL does. So if the
289 * DB name doesn't match the open connection, open a new one
292 function selectDB( $db ) {
293 if ( $this->mDBname
!== $db ) {
294 return (bool)$this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $db );
300 function makeConnectionString( $vars ) {
302 foreach ( $vars as $name => $value ) {
303 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
309 * Closes a database connection, if it is open
310 * Returns success, true if already closed
313 protected function closeConnection() {
314 return pg_close( $this->mConn
);
317 protected function doQuery( $sql ) {
318 if ( function_exists( 'mb_convert_encoding' ) ) {
319 $sql = mb_convert_encoding( $sql, 'UTF-8' );
321 $this->mTransactionState
->check();
322 $this->mLastResult
= pg_query( $this->mConn
, $sql );
323 $this->mTransactionState
->check();
324 $this->mAffectedRows
= null;
325 return $this->mLastResult
;
328 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
329 /* Transaction stays in the ERROR state until rolledback */
330 $this->rollback( __METHOD__
);
331 parent
::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
335 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
336 return $this->query( $sql, $fname, true );
339 function freeResult( $res ) {
340 if ( $res instanceof ResultWrapper
) {
343 wfSuppressWarnings();
344 $ok = pg_free_result( $res );
347 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
351 function fetchObject( $res ) {
352 if ( $res instanceof ResultWrapper
) {
355 wfSuppressWarnings();
356 $row = pg_fetch_object( $res );
358 # @todo FIXME: HACK HACK HACK HACK debug
360 # @todo hashar: not sure if the following test really trigger if the object
362 if( pg_last_error( $this->mConn
) ) {
363 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
368 function fetchRow( $res ) {
369 if ( $res instanceof ResultWrapper
) {
372 wfSuppressWarnings();
373 $row = pg_fetch_array( $res );
375 if( pg_last_error( $this->mConn
) ) {
376 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
381 function numRows( $res ) {
382 if ( $res instanceof ResultWrapper
) {
385 wfSuppressWarnings();
386 $n = pg_num_rows( $res );
388 if( pg_last_error( $this->mConn
) ) {
389 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
394 function numFields( $res ) {
395 if ( $res instanceof ResultWrapper
) {
398 return pg_num_fields( $res );
401 function fieldName( $res, $n ) {
402 if ( $res instanceof ResultWrapper
) {
405 return pg_field_name( $res, $n );
409 * This must be called after nextSequenceVal
412 function insertId() {
413 return $this->mInsertId
;
416 function dataSeek( $res, $row ) {
417 if ( $res instanceof ResultWrapper
) {
420 return pg_result_seek( $res, $row );
423 function lastError() {
424 if ( $this->mConn
) {
425 return pg_last_error();
427 return 'No database connection';
430 function lastErrno() {
431 return pg_last_error() ?
1 : 0;
434 function affectedRows() {
435 if ( !is_null( $this->mAffectedRows
) ) {
436 // Forced result for simulated queries
437 return $this->mAffectedRows
;
439 if( empty( $this->mLastResult
) ) {
442 return pg_affected_rows( $this->mLastResult
);
446 * Estimate rows in dataset
447 * Returns estimated count, based on EXPLAIN output
448 * This is not necessarily an accurate estimate, so use sparingly
449 * Returns -1 if count cannot be found
450 * Takes same arguments as Database::select()
453 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
454 $options['EXPLAIN'] = true;
455 $res = $this->select( $table, $vars, $conds, $fname, $options );
458 $row = $this->fetchRow( $res );
460 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
468 * Returns information about an index
469 * If errors are explicitly ignored, returns NULL on failure
472 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
473 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
474 $res = $this->query( $sql, $fname );
478 foreach ( $res as $row ) {
479 if ( $row->indexname
== $this->indexName( $index ) ) {
486 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
487 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
488 " AND indexdef LIKE 'CREATE UNIQUE%(" .
489 $this->strencode( $this->indexName( $index ) ) .
491 $res = $this->query( $sql, $fname );
495 foreach ( $res as $row ) {
502 * INSERT wrapper, inserts an array into a table
504 * $args may be a single associative array, or an array of these with numeric keys,
505 * for multi-row insert (Postgres version 8.2 and above only).
507 * @param $table String: Name of the table to insert to.
508 * @param $args Array: Items to insert into the table.
509 * @param $fname String: Name of the function, for profiling
510 * @param $options String or Array. Valid options: IGNORE
512 * @return bool Success of insert operation. IGNORE always returns true.
514 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
515 if ( !count( $args ) ) {
519 $table = $this->tableName( $table );
520 if (! isset( $this->numeric_version
) ) {
521 $this->getServerVersion();
524 if ( !is_array( $options ) ) {
525 $options = array( $options );
528 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
530 $keys = array_keys( $args[0] );
533 $keys = array_keys( $args );
536 // If IGNORE is set, we use savepoints to emulate mysql's behavior
537 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
539 // If we are not in a transaction, we need to be for savepoint trickery
542 if ( !$this->mTrxLevel
) {
543 $this->begin( __METHOD__
);
546 $olde = error_reporting( 0 );
547 // For future use, we may want to track the number of actual inserts
548 // Right now, insert (all writes) simply return true/false
549 $numrowsinserted = 0;
552 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
555 if ( $this->numeric_version
>= 8.2 && !$ignore ) {
557 foreach ( $args as $row ) {
563 $sql .= '(' . $this->makeList( $row ) . ')';
565 $res = (bool)$this->query( $sql, $fname, $ignore );
569 foreach ( $args as $row ) {
571 $tempsql .= '(' . $this->makeList( $row ) . ')';
574 $this->doQuery( "SAVEPOINT $ignore" );
577 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
580 $bar = pg_last_error();
581 if ( $bar != false ) {
582 $this->doQuery( $this->mConn
, "ROLLBACK TO $ignore" );
584 $this->doQuery( $this->mConn
, "RELEASE $ignore" );
589 // If any of them fail, we fail overall for this function call
590 // Note that this will be ignored if IGNORE is set
597 // Not multi, just a lone insert
599 $this->doQuery( "SAVEPOINT $ignore" );
602 $sql .= '(' . $this->makeList( $args ) . ')';
603 $res = (bool)$this->query( $sql, $fname, $ignore );
605 $bar = pg_last_error();
606 if ( $bar != false ) {
607 $this->doQuery( "ROLLBACK TO $ignore" );
609 $this->doQuery( "RELEASE $ignore" );
615 $olde = error_reporting( $olde );
617 $this->commit( __METHOD__
);
620 // Set the affected row count for the whole operation
621 $this->mAffectedRows
= $numrowsinserted;
623 // IGNORE always returns true
631 * INSERT SELECT wrapper
632 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
633 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
634 * $conds may be "*" to copy the whole table
635 * srcTable may be an array of tables.
636 * @todo FIXME: Implement this a little better (seperate select/insert)?
639 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
640 $insertOptions = array(), $selectOptions = array() )
642 $destTable = $this->tableName( $destTable );
644 // If IGNORE is set, we use savepoints to emulate mysql's behavior
645 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
647 if( is_array( $insertOptions ) ) {
648 $insertOptions = implode( ' ', $insertOptions ); // FIXME: This is unused
650 if( !is_array( $selectOptions ) ) {
651 $selectOptions = array( $selectOptions );
653 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
654 if( is_array( $srcTable ) ) {
655 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
657 $srcTable = $this->tableName( $srcTable );
660 // If we are not in a transaction, we need to be for savepoint trickery
663 if( !$this->mTrxLevel
) {
664 $this->begin( __METHOD__
);
667 $olde = error_reporting( 0 );
668 $numrowsinserted = 0;
669 $this->doQuery( "SAVEPOINT $ignore" );
672 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
673 " SELECT $startOpts " . implode( ',', $varMap ) .
674 " FROM $srcTable $useIndex";
676 if ( $conds != '*' ) {
677 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
680 $sql .= " $tailOpts";
682 $res = (bool)$this->query( $sql, $fname, $ignore );
684 $bar = pg_last_error();
685 if( $bar != false ) {
686 $this->doQuery( "ROLLBACK TO $ignore" );
688 $this->doQuery( "RELEASE $ignore" );
691 $olde = error_reporting( $olde );
693 $this->commit( __METHOD__
);
696 // Set the affected row count for the whole operation
697 $this->mAffectedRows
= $numrowsinserted;
699 // IGNORE always returns true
706 function tableName( $name, $format = 'quoted' ) {
707 # Replace reserved words with better ones
712 return 'pagecontent';
714 return parent
::tableName( $name, $format );
719 * Return the next in a sequence, save the value for retrieval via insertId()
722 function nextSequenceValue( $seqName ) {
723 $safeseq = str_replace( "'", "''", $seqName );
724 $res = $this->query( "SELECT nextval('$safeseq')" );
725 $row = $this->fetchRow( $res );
726 $this->mInsertId
= $row[0];
727 return $this->mInsertId
;
731 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
734 function currentSequenceValue( $seqName ) {
735 $safeseq = str_replace( "'", "''", $seqName );
736 $res = $this->query( "SELECT currval('$safeseq')" );
737 $row = $this->fetchRow( $res );
742 # Returns the size of a text field, or -1 for "unlimited"
743 function textFieldSize( $table, $field ) {
744 $table = $this->tableName( $table );
745 $sql = "SELECT t.typname as ftype,a.atttypmod as size
746 FROM pg_class c, pg_attribute a, pg_type t
747 WHERE relname='$table' AND a.attrelid=c.oid AND
748 a.atttypid=t.oid and a.attname='$field'";
749 $res =$this->query( $sql );
750 $row = $this->fetchObject( $res );
751 if ( $row->ftype
== 'varchar' ) {
752 $size = $row->size
- 4;
759 function limitResult( $sql, $limit, $offset = false ) {
760 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " : '' );
763 function wasDeadlock() {
764 return $this->lastErrno() == '40P01';
767 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
768 $newName = $this->addIdentifierQuotes( $newName );
769 $oldName = $this->addIdentifierQuotes( $oldName );
770 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
773 function listTables( $prefix = null, $fname = 'DatabasePostgres::listTables' ) {
774 $eschema = $this->addQuotes( $this->getCoreSchema() );
775 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
778 foreach( $result as $table ) {
779 $vars = get_object_vars($table);
780 $table = array_pop( $vars );
781 if( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
782 $endArray[] = $table;
789 function timestamp( $ts = 0 ) {
790 return wfTimestamp( TS_POSTGRES
, $ts );
795 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
796 * to http://www.php.net/manual/en/ref.pgsql.php
798 * Parsing a postgres array can be a tricky problem, he's my
799 * take on this, it handles multi-dimensional arrays plus
800 * escaping using a nasty regexp to determine the limits of each
803 * This should really be handled by PHP PostgreSQL module
806 * @param text string: postgreql array returned in a text form like {a,b}
807 * @param output string
813 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
814 if( false === $limit ) {
815 $limit = strlen( $text )-1;
820 if ( '{' != $text{$offset} ) {
821 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
822 $text, $match, 0, $offset );
823 $offset +
= strlen( $match[0] );
824 $output[] = ( '"' != $match[1]{0}
826 : stripcslashes( substr( $match[1], 1, -1 ) ) );
827 if ( '},' == $match[3] )
830 $offset = $this->pg_array_parse( $text, $output[], $limit, $offset+
1 );
831 } while ( $limit > $offset );
836 * Return aggregated value function call
838 function aggregateValue( $valuedata, $valuename = 'value' ) {
843 * @return string wikitext of a link to the server software's web site
845 public static function getSoftwareLink() {
846 return '[http://www.postgresql.org/ PostgreSQL]';
851 * Return current schema (executes SELECT current_schema())
855 * @return string return default schema for the current session
857 function getCurrentSchema() {
858 $res = $this->query( "SELECT current_schema()", __METHOD__
);
859 $row = $this->fetchRow( $res );
864 * Return list of schemas which are accessible without schema name
865 * This is list does not contain magic keywords like "$user"
868 * @seealso getSearchPath()
869 * @seealso setSearchPath()
871 * @return array list of actual schemas for the current sesson
873 function getSchemas() {
874 $res = $this->query( "SELECT current_schemas(false)", __METHOD__
);
875 $row = $this->fetchRow( $res );
877 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
878 return $this->pg_array_parse($row[0], $schemas);
882 * Return search patch for schemas
883 * This is different from getSchemas() since it contain magic keywords
888 * @return array how to search for table names schemas for the current user
890 function getSearchPath() {
891 $res = $this->query( "SHOW search_path", __METHOD__
);
892 $row = $this->fetchRow( $res );
893 /* PostgreSQL returns SHOW values as strings */
894 return explode(",", $row[0]);
897 function setSearchPath( $search_path ) {
899 * Update search_path, values should already be sanitized
900 * Values may contain magic keywords like "$user"
903 * @param array list of schemas to be searched by default
905 $this->query( "SET search_path = " . implode(", ", $search_path) );
909 * Determine default schema for MediaWiki core
910 * Adjust this session schema search path if desired schema exists
911 * and is not alread there.
913 * We need to have name of the core schema stored to be able
914 * to query database metadata.
916 * This will be also called by the installer after the schema is created
919 * @param desired_schema string
921 function determineCoreSchema( $desired_schema ) {
922 $this->begin( __METHOD__
);
923 if ( $this->schemaExists( $desired_schema ) ) {
924 if ( in_array( $desired_schema, $this->getSchemas() ) ) {
925 $this->mCoreSchema
= $desired_schema;
926 wfDebug("Schema \"" . $desired_schema . "\" already in the search path\n");
929 * Apped our schema (e.g. 'mediawiki') in front
933 $search_path = $this->getSearchPath();
934 array_unshift( $search_path,
935 $this->addIdentifierQuotes( $desired_schema ));
936 $this->setSearchPath( $search_path );
937 wfDebug("Schema \"" . $desired_schema . "\" added to the search path\n");
940 $this->mCoreSchema
= $this->getCurrentSchema();
941 wfDebug("Schema \"" . $desired_schema . "\" not found, using current \"". $this->mCoreSchema
."\"\n");
943 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
944 $this->commit( __METHOD__
);
948 * Return schema name fore core MediaWiki tables
951 * @return string core schema name
953 function getCoreSchema() {
954 return $this->mCoreSchema
;
958 * @return string Version information from the database
960 function getServerVersion() {
961 if ( !isset( $this->numeric_version
) ) {
962 $versionInfo = pg_version( $this->mConn
);
963 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
964 // Old client, abort install
965 $this->numeric_version
= '7.3 or earlier';
966 } elseif ( isset( $versionInfo['server'] ) ) {
968 $this->numeric_version
= $versionInfo['server'];
970 // Bug 16937: broken pgsql extension from PHP<5.3
971 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
974 return $this->numeric_version
;
978 * Query whether a given relation exists (in the given schema, or the
979 * default mw one if not given)
982 function relationExists( $table, $types, $schema = false ) {
983 if ( !is_array( $types ) ) {
984 $types = array( $types );
987 $schema = $this->getCoreSchema();
989 $table = $this->tableName( $table, 'raw' );
990 $etable = $this->addQuotes( $table );
991 $eschema = $this->addQuotes( $schema );
992 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
993 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
994 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
995 $res = $this->query( $SQL );
996 $count = $res ?
$res->numRows() : 0;
1001 * For backward compatibility, this function checks both tables and
1005 function tableExists( $table, $fname = __METHOD__
, $schema = false ) {
1006 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1009 function sequenceExists( $sequence, $schema = false ) {
1010 return $this->relationExists( $sequence, 'S', $schema );
1013 function triggerExists( $table, $trigger ) {
1015 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1016 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1017 AND tgrelid=pg_class.oid
1018 AND nspname=%s AND relname=%s AND tgname=%s
1020 $res = $this->query(
1023 $this->addQuotes( $this->getCoreSchema() ),
1024 $this->addQuotes( $table ),
1025 $this->addQuotes( $trigger )
1031 $rows = $res->numRows();
1035 function ruleExists( $table, $rule ) {
1036 $exists = $this->selectField( 'pg_rules', 'rulename',
1038 'rulename' => $rule,
1039 'tablename' => $table,
1040 'schemaname' => $this->getCoreSchema()
1043 return $exists === $rule;
1046 function constraintExists( $table, $constraint ) {
1047 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1048 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1049 $this->addQuotes( $this->getCoreSchema() ),
1050 $this->addQuotes( $table ),
1051 $this->addQuotes( $constraint )
1053 $res = $this->query( $SQL );
1057 $rows = $res->numRows();
1062 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1065 function schemaExists( $schema ) {
1066 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1067 array( 'nspname' => $schema ), __METHOD__
);
1068 return (bool)$exists;
1072 * Returns true if a given role (i.e. user) exists, false otherwise.
1075 function roleExists( $roleName ) {
1076 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1077 array( 'rolname' => $roleName ), __METHOD__
);
1078 return (bool)$exists;
1081 function fieldInfo( $table, $field ) {
1082 return PostgresField
::fromText( $this, $table, $field );
1086 * pg_field_type() wrapper
1089 function fieldType( $res, $index ) {
1090 if ( $res instanceof ResultWrapper
) {
1091 $res = $res->result
;
1093 return pg_field_type( $res, $index );
1096 /* Not even sure why this is used in the main codebase... */
1097 function limitResultForUpdate( $sql, $num ) {
1105 function encodeBlob( $b ) {
1106 return new Blob( pg_escape_bytea( $this->mConn
, $b ) );
1109 function decodeBlob( $b ) {
1110 if ( $b instanceof Blob
) {
1113 return pg_unescape_bytea( $b );
1116 function strencode( $s ) { # Should not be called by us
1117 return pg_escape_string( $this->mConn
, $s );
1121 * @param $s null|bool|Blob
1122 * @return int|string
1124 function addQuotes( $s ) {
1125 if ( is_null( $s ) ) {
1127 } elseif ( is_bool( $s ) ) {
1128 return intval( $s );
1129 } elseif ( $s instanceof Blob
) {
1130 return "'" . $s->fetch( $s ) . "'";
1132 return "'" . pg_escape_string( $this->mConn
, $s ) . "'";
1136 * Postgres specific version of replaceVars.
1137 * Calls the parent version in Database.php
1141 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1143 * @return string SQL string
1145 protected function replaceVars( $ins ) {
1146 $ins = parent
::replaceVars( $ins );
1148 if ( $this->numeric_version
>= 8.3 ) {
1149 // Thanks for not providing backwards-compatibility, 8.3
1150 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1153 if ( $this->numeric_version
<= 8.1 ) { // Our minimum version
1154 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1161 * Various select options
1165 * @param $options Array: an associative array of options to be turned into
1166 * an SQL query, valid keys are listed in the function.
1169 function makeSelectOptions( $options ) {
1170 $preLimitTail = $postLimitTail = '';
1171 $startOpts = $useIndex = '';
1173 $noKeyOptions = array();
1174 foreach ( $options as $key => $option ) {
1175 if ( is_numeric( $key ) ) {
1176 $noKeyOptions[$option] = true;
1180 if ( isset( $options['GROUP BY'] ) ) {
1181 $gb = is_array( $options['GROUP BY'] )
1182 ?
implode( ',', $options['GROUP BY'] )
1183 : $options['GROUP BY'];
1184 $preLimitTail .= " GROUP BY {$gb}";
1187 if ( isset( $options['HAVING'] ) ) {
1188 $preLimitTail .= " HAVING {$options['HAVING']}";
1191 if ( isset( $options['ORDER BY'] ) ) {
1192 $ob = is_array( $options['ORDER BY'] )
1193 ?
implode( ',', $options['ORDER BY'] )
1194 : $options['ORDER BY'];
1195 $preLimitTail .= " ORDER BY {$ob}";
1198 //if ( isset( $options['LIMIT'] ) ) {
1199 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1200 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1204 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1205 $postLimitTail .= ' FOR UPDATE';
1207 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1208 $postLimitTail .= ' LOCK IN SHARE MODE';
1210 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1211 $startOpts .= 'DISTINCT';
1214 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1217 function setFakeMaster( $enabled = true ) {}
1219 function getDBname() {
1220 return $this->mDBname
;
1223 function getServer() {
1224 return $this->mServer
;
1227 function buildConcat( $stringList ) {
1228 return implode( ' || ', $stringList );
1231 public function getSearchEngine() {
1232 return 'SearchPostgres';
1235 public function streamStatementEnd( &$sql, &$newLine ) {
1236 # Allow dollar quoting for function declarations
1237 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1238 if ( $this->delimiter
) {
1239 $this->delimiter
= false;
1242 $this->delimiter
= ';';
1245 return parent
::streamStatementEnd( $sql, $newLine );
1247 } // end DatabasePostgres class