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 global $wgDebugDBTransactions;
319 if ( function_exists( 'mb_convert_encoding' ) ) {
320 $sql = mb_convert_encoding( $sql, 'UTF-8' );
322 $this->mTransactionState
->check();
323 $this->mLastResult
= pg_query( $this->mConn
, $sql );
324 $this->mTransactionState
->check();
325 $this->mAffectedRows
= null;
326 return $this->mLastResult
;
329 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
330 /* Transaction stays in the ERROR state until rolledback */
331 $this->rollback( __METHOD__
);
332 parent
::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
336 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
337 return $this->query( $sql, $fname, true );
340 function freeResult( $res ) {
341 if ( $res instanceof ResultWrapper
) {
344 wfSuppressWarnings();
345 $ok = pg_free_result( $res );
348 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
352 function fetchObject( $res ) {
353 if ( $res instanceof ResultWrapper
) {
356 wfSuppressWarnings();
357 $row = pg_fetch_object( $res );
359 # @todo FIXME: HACK HACK HACK HACK debug
361 # @todo hashar: not sure if the following test really trigger if the object
363 if( pg_last_error( $this->mConn
) ) {
364 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
369 function fetchRow( $res ) {
370 if ( $res instanceof ResultWrapper
) {
373 wfSuppressWarnings();
374 $row = pg_fetch_array( $res );
376 if( pg_last_error( $this->mConn
) ) {
377 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
382 function numRows( $res ) {
383 if ( $res instanceof ResultWrapper
) {
386 wfSuppressWarnings();
387 $n = pg_num_rows( $res );
389 if( pg_last_error( $this->mConn
) ) {
390 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
395 function numFields( $res ) {
396 if ( $res instanceof ResultWrapper
) {
399 return pg_num_fields( $res );
402 function fieldName( $res, $n ) {
403 if ( $res instanceof ResultWrapper
) {
406 return pg_field_name( $res, $n );
410 * This must be called after nextSequenceVal
413 function insertId() {
414 return $this->mInsertId
;
417 function dataSeek( $res, $row ) {
418 if ( $res instanceof ResultWrapper
) {
421 return pg_result_seek( $res, $row );
424 function lastError() {
425 if ( $this->mConn
) {
426 return pg_last_error();
428 return 'No database connection';
431 function lastErrno() {
432 return pg_last_error() ?
1 : 0;
435 function affectedRows() {
436 if ( !is_null( $this->mAffectedRows
) ) {
437 // Forced result for simulated queries
438 return $this->mAffectedRows
;
440 if( empty( $this->mLastResult
) ) {
443 return pg_affected_rows( $this->mLastResult
);
447 * Estimate rows in dataset
448 * Returns estimated count, based on EXPLAIN output
449 * This is not necessarily an accurate estimate, so use sparingly
450 * Returns -1 if count cannot be found
451 * Takes same arguments as Database::select()
454 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
455 $options['EXPLAIN'] = true;
456 $res = $this->select( $table, $vars, $conds, $fname, $options );
459 $row = $this->fetchRow( $res );
461 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
469 * Returns information about an index
470 * If errors are explicitly ignored, returns NULL on failure
473 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
474 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
475 $res = $this->query( $sql, $fname );
479 foreach ( $res as $row ) {
480 if ( $row->indexname
== $this->indexName( $index ) ) {
487 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
488 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
489 " AND indexdef LIKE 'CREATE UNIQUE%(" .
490 $this->strencode( $this->indexName( $index ) ) .
492 $res = $this->query( $sql, $fname );
496 foreach ( $res as $row ) {
503 * INSERT wrapper, inserts an array into a table
505 * $args may be a single associative array, or an array of these with numeric keys,
506 * for multi-row insert (Postgres version 8.2 and above only).
508 * @param $table String: Name of the table to insert to.
509 * @param $args Array: Items to insert into the table.
510 * @param $fname String: Name of the function, for profiling
511 * @param $options String or Array. Valid options: IGNORE
513 * @return bool Success of insert operation. IGNORE always returns true.
515 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
516 if ( !count( $args ) ) {
520 $table = $this->tableName( $table );
521 if (! isset( $this->numeric_version
) ) {
522 $this->getServerVersion();
525 if ( !is_array( $options ) ) {
526 $options = array( $options );
529 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
531 $keys = array_keys( $args[0] );
534 $keys = array_keys( $args );
537 // If IGNORE is set, we use savepoints to emulate mysql's behavior
538 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
540 // If we are not in a transaction, we need to be for savepoint trickery
543 if ( !$this->mTrxLevel
) {
544 $this->begin( __METHOD__
);
547 $olde = error_reporting( 0 );
548 // For future use, we may want to track the number of actual inserts
549 // Right now, insert (all writes) simply return true/false
550 $numrowsinserted = 0;
553 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
556 if ( $this->numeric_version
>= 8.2 && !$ignore ) {
558 foreach ( $args as $row ) {
564 $sql .= '(' . $this->makeList( $row ) . ')';
566 $res = (bool)$this->query( $sql, $fname, $ignore );
570 foreach ( $args as $row ) {
572 $tempsql .= '(' . $this->makeList( $row ) . ')';
575 $this->doQuery( "SAVEPOINT $ignore" );
578 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
581 $bar = pg_last_error();
582 if ( $bar != false ) {
583 $this->doQuery( $this->mConn
, "ROLLBACK TO $ignore" );
585 $this->doQuery( $this->mConn
, "RELEASE $ignore" );
590 // If any of them fail, we fail overall for this function call
591 // Note that this will be ignored if IGNORE is set
598 // Not multi, just a lone insert
600 $this->doQuery( "SAVEPOINT $ignore" );
603 $sql .= '(' . $this->makeList( $args ) . ')';
604 $res = (bool)$this->query( $sql, $fname, $ignore );
606 $bar = pg_last_error();
607 if ( $bar != false ) {
608 $this->doQuery( "ROLLBACK TO $ignore" );
610 $this->doQuery( "RELEASE $ignore" );
616 $olde = error_reporting( $olde );
618 $this->commit( __METHOD__
);
621 // Set the affected row count for the whole operation
622 $this->mAffectedRows
= $numrowsinserted;
624 // IGNORE always returns true
632 * INSERT SELECT wrapper
633 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
634 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
635 * $conds may be "*" to copy the whole table
636 * srcTable may be an array of tables.
637 * @todo FIXME: Implement this a little better (seperate select/insert)?
640 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
641 $insertOptions = array(), $selectOptions = array() )
643 $destTable = $this->tableName( $destTable );
645 // If IGNORE is set, we use savepoints to emulate mysql's behavior
646 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
648 if( is_array( $insertOptions ) ) {
649 $insertOptions = implode( ' ', $insertOptions ); // FIXME: This is unused
651 if( !is_array( $selectOptions ) ) {
652 $selectOptions = array( $selectOptions );
654 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
655 if( is_array( $srcTable ) ) {
656 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
658 $srcTable = $this->tableName( $srcTable );
661 // If we are not in a transaction, we need to be for savepoint trickery
664 if( !$this->mTrxLevel
) {
665 $this->begin( __METHOD__
);
668 $olde = error_reporting( 0 );
669 $numrowsinserted = 0;
670 $this->doQuery( "SAVEPOINT $ignore" );
673 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
674 " SELECT $startOpts " . implode( ',', $varMap ) .
675 " FROM $srcTable $useIndex";
677 if ( $conds != '*' ) {
678 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
681 $sql .= " $tailOpts";
683 $res = (bool)$this->query( $sql, $fname, $ignore );
685 $bar = pg_last_error();
686 if( $bar != false ) {
687 $this->doQuery( "ROLLBACK TO $ignore" );
689 $this->doQuery( "RELEASE $ignore" );
692 $olde = error_reporting( $olde );
694 $this->commit( __METHOD__
);
697 // Set the affected row count for the whole operation
698 $this->mAffectedRows
= $numrowsinserted;
700 // IGNORE always returns true
707 function tableName( $name, $format = 'quoted' ) {
708 # Replace reserved words with better ones
713 return 'pagecontent';
715 return parent
::tableName( $name, $format );
720 * Return the next in a sequence, save the value for retrieval via insertId()
723 function nextSequenceValue( $seqName ) {
724 $safeseq = str_replace( "'", "''", $seqName );
725 $res = $this->query( "SELECT nextval('$safeseq')" );
726 $row = $this->fetchRow( $res );
727 $this->mInsertId
= $row[0];
728 return $this->mInsertId
;
732 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
735 function currentSequenceValue( $seqName ) {
736 $safeseq = str_replace( "'", "''", $seqName );
737 $res = $this->query( "SELECT currval('$safeseq')" );
738 $row = $this->fetchRow( $res );
743 # Returns the size of a text field, or -1 for "unlimited"
744 function textFieldSize( $table, $field ) {
745 $table = $this->tableName( $table );
746 $sql = "SELECT t.typname as ftype,a.atttypmod as size
747 FROM pg_class c, pg_attribute a, pg_type t
748 WHERE relname='$table' AND a.attrelid=c.oid AND
749 a.atttypid=t.oid and a.attname='$field'";
750 $res =$this->query( $sql );
751 $row = $this->fetchObject( $res );
752 if ( $row->ftype
== 'varchar' ) {
753 $size = $row->size
- 4;
760 function limitResult( $sql, $limit, $offset = false ) {
761 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " : '' );
764 function wasDeadlock() {
765 return $this->lastErrno() == '40P01';
768 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
769 $newName = $this->addIdentifierQuotes( $newName );
770 $oldName = $this->addIdentifierQuotes( $oldName );
771 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
774 function listTables( $prefix = null, $fname = 'DatabasePostgres::listTables' ) {
775 $eschema = $this->addQuotes( $this->getCoreSchema() );
776 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
779 foreach( $result as $table ) {
780 $vars = get_object_vars($table);
781 $table = array_pop( $vars );
782 if( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
783 $endArray[] = $table;
790 function timestamp( $ts = 0 ) {
791 return wfTimestamp( TS_POSTGRES
, $ts );
796 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
797 * to http://www.php.net/manual/en/ref.pgsql.php
799 * Parsing a postgres array can be a tricky problem, he's my
800 * take on this, it handles multi-dimensional arrays plus
801 * escaping using a nasty regexp to determine the limits of each
804 * This should really be handled by PHP PostgreSQL module
807 * @param text string: postgreql array returned in a text form like {a,b}
808 * @param output string
814 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
815 if( false === $limit ) {
816 $limit = strlen( $text )-1;
821 if ( '{' != $text{$offset} ) {
822 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
823 $text, $match, 0, $offset );
824 $offset +
= strlen( $match[0] );
825 $output[] = ( '"' != $match[1]{0}
827 : stripcslashes( substr( $match[1], 1, -1 ) ) );
828 if ( '},' == $match[3] )
831 $offset = $this->pg_array_parse( $text, $output[], $limit, $offset+
1 );
832 } while ( $limit > $offset );
837 * Return aggregated value function call
839 function aggregateValue( $valuedata, $valuename = 'value' ) {
844 * @return string wikitext of a link to the server software's web site
846 public static function getSoftwareLink() {
847 return '[http://www.postgresql.org/ PostgreSQL]';
852 * Return current schema (executes SELECT current_schema())
856 * @return string return default schema for the current session
858 function getCurrentSchema() {
859 $res = $this->query( "SELECT current_schema()", __METHOD__
);
860 $row = $this->fetchRow( $res );
865 * Return list of schemas which are accessible without schema name
866 * This is list does not contain magic keywords like "$user"
869 * @seealso getSearchPath()
870 * @seealso setSearchPath()
872 * @return array list of actual schemas for the current sesson
874 function getSchemas() {
875 $res = $this->query( "SELECT current_schemas(false)", __METHOD__
);
876 $row = $this->fetchRow( $res );
878 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
879 return $this->pg_array_parse($row[0], $schemas);
883 * Return search patch for schemas
884 * This is different from getSchemas() since it contain magic keywords
889 * @return array how to search for table names schemas for the current user
891 function getSearchPath() {
892 $res = $this->query( "SHOW search_path", __METHOD__
);
893 $row = $this->fetchRow( $res );
894 /* PostgreSQL returns SHOW values as strings */
895 return explode(",", $row[0]);
898 function setSearchPath( $search_path ) {
900 * Update search_path, values should already be sanitized
901 * Values may contain magic keywords like "$user"
904 * @param array list of schemas to be searched by default
906 $this->query( "SET search_path = " . implode(", ", $search_path) );
910 * Determine default schema for MediaWiki core
911 * Adjust this session schema search path if desired schema exists
912 * and is not alread there.
914 * We need to have name of the core schema stored to be able
915 * to query database metadata.
917 * This will be also called by the installer after the schema is created
920 * @param desired_schema string
922 function determineCoreSchema( $desired_schema ) {
923 $this->begin( __METHOD__
);
924 if ( $this->schemaExists( $desired_schema ) ) {
925 if ( in_array( $desired_schema, $this->getSchemas() ) ) {
926 $this->mCoreSchema
= $desired_schema;
927 wfDebug("Schema \"" . $desired_schema . "\" already in the search path\n");
930 * Apped our schema (e.g. 'mediawiki') in front
934 $search_path = $this->getSearchPath();
935 array_unshift( $search_path,
936 $this->addIdentifierQuotes( $desired_schema ));
937 $this->setSearchPath( $search_path );
938 wfDebug("Schema \"" . $desired_schema . "\" added to the search path\n");
941 $this->mCoreSchema
= $this->getCurrentSchema();
942 wfDebug("Schema \"" . $desired_schema . "\" not found, using current \"". $this->mCoreSchema
."\"\n");
944 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
945 $this->commit( __METHOD__
);
949 * Return schema name fore core MediaWiki tables
952 * @return string core schema name
954 function getCoreSchema() {
955 return $this->mCoreSchema
;
959 * @return string Version information from the database
961 function getServerVersion() {
962 if ( !isset( $this->numeric_version
) ) {
963 $versionInfo = pg_version( $this->mConn
);
964 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
965 // Old client, abort install
966 $this->numeric_version
= '7.3 or earlier';
967 } elseif ( isset( $versionInfo['server'] ) ) {
969 $this->numeric_version
= $versionInfo['server'];
971 // Bug 16937: broken pgsql extension from PHP<5.3
972 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
975 return $this->numeric_version
;
979 * Query whether a given relation exists (in the given schema, or the
980 * default mw one if not given)
983 function relationExists( $table, $types, $schema = false ) {
984 if ( !is_array( $types ) ) {
985 $types = array( $types );
988 $schema = $this->getCoreSchema();
990 $table = $this->tableName( $table, 'raw' );
991 $etable = $this->addQuotes( $table );
992 $eschema = $this->addQuotes( $schema );
993 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
994 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
995 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
996 $res = $this->query( $SQL );
997 $count = $res ?
$res->numRows() : 0;
1002 * For backward compatibility, this function checks both tables and
1006 function tableExists( $table, $fname = __METHOD__
, $schema = false ) {
1007 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1010 function sequenceExists( $sequence, $schema = false ) {
1011 return $this->relationExists( $sequence, 'S', $schema );
1014 function triggerExists( $table, $trigger ) {
1016 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1017 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1018 AND tgrelid=pg_class.oid
1019 AND nspname=%s AND relname=%s AND tgname=%s
1021 $res = $this->query(
1024 $this->addQuotes( $this->getCoreSchema() ),
1025 $this->addQuotes( $table ),
1026 $this->addQuotes( $trigger )
1032 $rows = $res->numRows();
1036 function ruleExists( $table, $rule ) {
1037 $exists = $this->selectField( 'pg_rules', 'rulename',
1039 'rulename' => $rule,
1040 'tablename' => $table,
1041 'schemaname' => $this->getCoreSchema()
1044 return $exists === $rule;
1047 function constraintExists( $table, $constraint ) {
1048 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1049 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1050 $this->addQuotes( $this->getCoreSchema() ),
1051 $this->addQuotes( $table ),
1052 $this->addQuotes( $constraint )
1054 $res = $this->query( $SQL );
1058 $rows = $res->numRows();
1063 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1066 function schemaExists( $schema ) {
1067 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1068 array( 'nspname' => $schema ), __METHOD__
);
1069 return (bool)$exists;
1073 * Returns true if a given role (i.e. user) exists, false otherwise.
1076 function roleExists( $roleName ) {
1077 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1078 array( 'rolname' => $roleName ), __METHOD__
);
1079 return (bool)$exists;
1082 function fieldInfo( $table, $field ) {
1083 return PostgresField
::fromText( $this, $table, $field );
1087 * pg_field_type() wrapper
1090 function fieldType( $res, $index ) {
1091 if ( $res instanceof ResultWrapper
) {
1092 $res = $res->result
;
1094 return pg_field_type( $res, $index );
1097 /* Not even sure why this is used in the main codebase... */
1098 function limitResultForUpdate( $sql, $num ) {
1106 function encodeBlob( $b ) {
1107 return new Blob( pg_escape_bytea( $this->mConn
, $b ) );
1110 function decodeBlob( $b ) {
1111 if ( $b instanceof Blob
) {
1114 return pg_unescape_bytea( $b );
1117 function strencode( $s ) { # Should not be called by us
1118 return pg_escape_string( $this->mConn
, $s );
1122 * @param $s null|bool|Blob
1123 * @return int|string
1125 function addQuotes( $s ) {
1126 if ( is_null( $s ) ) {
1128 } elseif ( is_bool( $s ) ) {
1129 return intval( $s );
1130 } elseif ( $s instanceof Blob
) {
1131 return "'" . $s->fetch( $s ) . "'";
1133 return "'" . pg_escape_string( $this->mConn
, $s ) . "'";
1137 * Postgres specific version of replaceVars.
1138 * Calls the parent version in Database.php
1142 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1144 * @return string SQL string
1146 protected function replaceVars( $ins ) {
1147 $ins = parent
::replaceVars( $ins );
1149 if ( $this->numeric_version
>= 8.3 ) {
1150 // Thanks for not providing backwards-compatibility, 8.3
1151 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1154 if ( $this->numeric_version
<= 8.1 ) { // Our minimum version
1155 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1162 * Various select options
1166 * @param $options Array: an associative array of options to be turned into
1167 * an SQL query, valid keys are listed in the function.
1170 function makeSelectOptions( $options ) {
1171 $preLimitTail = $postLimitTail = '';
1172 $startOpts = $useIndex = '';
1174 $noKeyOptions = array();
1175 foreach ( $options as $key => $option ) {
1176 if ( is_numeric( $key ) ) {
1177 $noKeyOptions[$option] = true;
1181 if ( isset( $options['GROUP BY'] ) ) {
1182 $gb = is_array( $options['GROUP BY'] )
1183 ?
implode( ',', $options['GROUP BY'] )
1184 : $options['GROUP BY'];
1185 $preLimitTail .= " GROUP BY {$gb}";
1188 if ( isset( $options['HAVING'] ) ) {
1189 $preLimitTail .= " HAVING {$options['HAVING']}";
1192 if ( isset( $options['ORDER BY'] ) ) {
1193 $ob = is_array( $options['ORDER BY'] )
1194 ?
implode( ',', $options['ORDER BY'] )
1195 : $options['ORDER BY'];
1196 $preLimitTail .= " ORDER BY {$ob}";
1199 //if ( isset( $options['LIMIT'] ) ) {
1200 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1201 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1205 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1206 $postLimitTail .= ' FOR UPDATE';
1208 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1209 $postLimitTail .= ' LOCK IN SHARE MODE';
1211 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1212 $startOpts .= 'DISTINCT';
1215 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1218 function setFakeMaster( $enabled = true ) {}
1220 function getDBname() {
1221 return $this->mDBname
;
1224 function getServer() {
1225 return $this->mServer
;
1228 function buildConcat( $stringList ) {
1229 return implode( ' || ', $stringList );
1232 public function getSearchEngine() {
1233 return 'SearchPostgres';
1236 public function streamStatementEnd( &$sql, &$newLine ) {
1237 # Allow dollar quoting for function declarations
1238 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1239 if ( $this->delimiter
) {
1240 $this->delimiter
= false;
1243 $this->delimiter
= ';';
1246 return parent
::streamStatementEnd( $sql, $newLine );
1248 } // end DatabasePostgres class