3 * This is the Postgres database abstraction layer.
9 class PostgresField
implements Field
{
10 private $name, $tablename, $type, $nullable, $max_length, $deferred, $deferrable, $conname,
11 $has_default, $default;
14 * @param $db DatabaseBase
17 * @return null|PostgresField
19 static function fromText( $db, $table, $field ) {
22 attnotnull, attlen, conname AS conname,
25 COALESCE(condeferred, 'f') AS deferred,
26 COALESCE(condeferrable, 'f') AS deferrable,
27 CASE WHEN typname = 'int2' THEN 'smallint'
28 WHEN typname = 'int4' THEN 'integer'
29 WHEN typname = 'int8' THEN 'bigint'
30 WHEN typname = 'bpchar' THEN 'char'
31 ELSE typname END AS typname
33 JOIN pg_namespace n ON (n.oid = c.relnamespace)
34 JOIN pg_attribute a ON (a.attrelid = c.oid)
35 JOIN pg_type t ON (t.oid = a.atttypid)
36 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
37 LEFT JOIN pg_attrdef d on c.oid=d.adrelid and a.attnum=d.adnum
44 $table = $db->tableName( $table, 'raw' );
47 $db->addQuotes( $db->getCoreSchema() ),
48 $db->addQuotes( $table ),
49 $db->addQuotes( $field )
52 $row = $db->fetchObject( $res );
56 $n = new PostgresField
;
57 $n->type
= $row->typname
;
58 $n->nullable
= ( $row->attnotnull
== 'f' );
60 $n->tablename
= $table;
61 $n->max_length
= $row->attlen
;
62 $n->deferrable
= ( $row->deferrable
== 't' );
63 $n->deferred
= ( $row->deferred
== 't' );
64 $n->conname
= $row->conname
;
65 $n->has_default
= ( $row->atthasdef
=== 't' );
66 $n->default = $row->adsrc
;
74 function tableName() {
75 return $this->tablename
;
82 function isNullable() {
83 return $this->nullable
;
86 function maxLength() {
87 return $this->max_length
;
90 function is_deferrable() {
91 return $this->deferrable
;
94 function is_deferred() {
95 return $this->deferred
;
99 return $this->conname
;
104 function defaultValue() {
105 if( $this->has_default
) {
106 return $this->default;
115 * Used to debug transaction processing
116 * Only used if $wgDebugDBTransactions is true
121 class PostgresTransactionState
{
123 static $WATCHED = array(
125 "desc" => "Connection state changed from %s -> %s\n",
127 PGSQL_CONNECTION_OK
=> "OK",
128 PGSQL_CONNECTION_BAD
=> "BAD"
132 "desc" => "Transaction state changed from %s -> %s\n",
134 PGSQL_TRANSACTION_IDLE
=> "IDLE",
135 PGSQL_TRANSACTION_ACTIVE
=> "ACTIVE",
136 PGSQL_TRANSACTION_INTRANS
=> "TRANS",
137 PGSQL_TRANSACTION_INERROR
=> "ERROR",
138 PGSQL_TRANSACTION_UNKNOWN
=> "UNKNOWN"
143 public function __construct( $conn ) {
144 $this->mConn
= $conn;
146 $this->mCurrentState
= $this->mNewState
;
149 public function update() {
150 $this->mNewState
= array(
151 pg_connection_status( $this->mConn
),
152 pg_transaction_status( $this->mConn
)
156 public function check() {
157 global $wgDebugDBTransactions;
159 if ( $wgDebugDBTransactions ) {
160 if ( $this->mCurrentState
!== $this->mNewState
) {
161 $old = reset( $this->mCurrentState
);
162 $new = reset( $this->mNewState
);
163 foreach ( self
::$WATCHED as $watched ) {
165 $this->log_changed($old, $new, $watched);
167 $old = next( $this->mCurrentState
);
168 $new = next( $this->mNewState
);
173 $this->mCurrentState
= $this->mNewState
;
176 protected function describe_changed( $status, $desc_table ) {
177 if( isset( $desc_table[$status] ) ) {
178 return $desc_table[$status];
180 return "STATUS " . $status;
184 protected function log_changed( $old, $new, $watched ) {
185 wfDebug(sprintf($watched["desc"],
186 $this->describe_changed( $old, $watched["states"] ),
187 $this->describe_changed( $new, $watched["states"] ))
195 class DatabasePostgres
extends DatabaseBase
{
196 var $mInsertId = null;
197 var $mLastResult = null;
198 var $numeric_version = null;
199 var $mAffectedRows = null;
205 function cascadingDeletes() {
208 function cleanupTriggers() {
211 function strictIPs() {
214 function realTimestamps() {
217 function implicitGroupby() {
220 function implicitOrderby() {
223 function searchableIPs() {
226 function functionalIndexes() {
230 function hasConstraint( $name ) {
231 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" .
232 pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn
, $this->getCoreSchema() ) ."'";
233 $res = $this->doQuery( $SQL );
234 return $this->numRows( $res );
238 * Usually aborts on failure
239 * @return DatabaseBase|null
241 function open( $server, $user, $password, $dbName ) {
242 # Test for Postgres support, to avoid suppressed fatal error
243 if ( !function_exists( 'pg_connect' ) ) {
244 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" );
249 if ( !strlen( $user ) ) { # e.g. the class is being loaded
253 $this->mServer
= $server;
255 $this->mUser
= $user;
256 $this->mPassword
= $password;
257 $this->mDBname
= $dbName;
259 $connectVars = array(
262 'password' => $password
264 if ( $server != false && $server != '' ) {
265 $connectVars['host'] = $server;
267 if ( $port != false && $port != '' ) {
268 $connectVars['port'] = $port;
270 $this->connectString
= $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
272 $this->installErrorHandler();
273 $this->mConn
= pg_connect( $this->connectString
);
274 $phpError = $this->restoreErrorHandler();
276 if ( !$this->mConn
) {
277 wfDebug( "DB connection error\n" );
278 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
279 wfDebug( $this->lastError() . "\n" );
280 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
283 $this->mOpened
= true;
284 $this->mTransactionState
= new PostgresTransactionState( $this->mConn
);
286 global $wgCommandLineMode;
287 # If called from the command-line (e.g. importDump), only show errors
288 if ( $wgCommandLineMode ) {
289 $this->doQuery( "SET client_min_messages = 'ERROR'" );
292 $this->query( "SET client_encoding='UTF8'", __METHOD__
);
293 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__
);
294 $this->query( "SET timezone = 'GMT'", __METHOD__
);
295 $this->query( "SET standard_conforming_strings = on", __METHOD__
);
297 global $wgDBmwschema;
298 $this->determineCoreSchema( $wgDBmwschema );
304 * Postgres doesn't support selectDB in the same way MySQL does. So if the
305 * DB name doesn't match the open connection, open a new one
308 function selectDB( $db ) {
309 if ( $this->mDBname
!== $db ) {
310 return (bool)$this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $db );
316 function makeConnectionString( $vars ) {
318 foreach ( $vars as $name => $value ) {
319 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
325 * Closes a database connection, if it is open
326 * Returns success, true if already closed
329 protected function closeConnection() {
330 return pg_close( $this->mConn
);
333 protected function doQuery( $sql ) {
334 if ( function_exists( 'mb_convert_encoding' ) ) {
335 $sql = mb_convert_encoding( $sql, 'UTF-8' );
337 $this->mTransactionState
->check();
338 if( pg_send_query( $this->mConn
, $sql ) === false ) {
339 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
341 $this->mLastResult
= pg_get_result( $this->mConn
);
342 $this->mTransactionState
->check();
343 $this->mAffectedRows
= null;
344 if ( pg_result_error( $this->mLastResult
) ) {
347 return $this->mLastResult
;
350 protected function dumpError () {
351 $diags = array( PGSQL_DIAG_SEVERITY
,
353 PGSQL_DIAG_MESSAGE_PRIMARY
,
354 PGSQL_DIAG_MESSAGE_DETAIL
,
355 PGSQL_DIAG_MESSAGE_HINT
,
356 PGSQL_DIAG_STATEMENT_POSITION
,
357 PGSQL_DIAG_INTERNAL_POSITION
,
358 PGSQL_DIAG_INTERNAL_QUERY
,
360 PGSQL_DIAG_SOURCE_FILE
,
361 PGSQL_DIAG_SOURCE_LINE
,
362 PGSQL_DIAG_SOURCE_FUNCTION
);
363 foreach ( $diags as $d ) {
364 wfDebug( sprintf("PgSQL ERROR(%d): %s\n", $d, pg_result_error_field( $this->mLastResult
, $d ) ) );
368 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
369 /* Transaction stays in the ERROR state until rolledback */
371 /* Check for constraint violation */
372 if ( $errno === '23505' ) {
373 parent
::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
377 /* Don't ignore serious errors */
378 $this->rollback( __METHOD__
);
379 parent
::reportQueryError( $error, $errno, $sql, $fname, false );
383 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
384 return $this->query( $sql, $fname, true );
387 function freeResult( $res ) {
388 if ( $res instanceof ResultWrapper
) {
391 wfSuppressWarnings();
392 $ok = pg_free_result( $res );
395 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
399 function fetchObject( $res ) {
400 if ( $res instanceof ResultWrapper
) {
403 wfSuppressWarnings();
404 $row = pg_fetch_object( $res );
406 # @todo FIXME: HACK HACK HACK HACK debug
408 # @todo hashar: not sure if the following test really trigger if the object
410 if( pg_last_error( $this->mConn
) ) {
411 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
416 function fetchRow( $res ) {
417 if ( $res instanceof ResultWrapper
) {
420 wfSuppressWarnings();
421 $row = pg_fetch_array( $res );
423 if( pg_last_error( $this->mConn
) ) {
424 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
429 function numRows( $res ) {
430 if ( $res instanceof ResultWrapper
) {
433 wfSuppressWarnings();
434 $n = pg_num_rows( $res );
436 if( pg_last_error( $this->mConn
) ) {
437 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
442 function numFields( $res ) {
443 if ( $res instanceof ResultWrapper
) {
446 return pg_num_fields( $res );
449 function fieldName( $res, $n ) {
450 if ( $res instanceof ResultWrapper
) {
453 return pg_field_name( $res, $n );
457 * This must be called after nextSequenceVal
460 function insertId() {
461 return $this->mInsertId
;
464 function dataSeek( $res, $row ) {
465 if ( $res instanceof ResultWrapper
) {
468 return pg_result_seek( $res, $row );
471 function lastError() {
472 if ( $this->mConn
) {
473 if ( $this->mLastResult
) {
474 return pg_result_error( $this->mLastResult
);
476 return pg_last_error();
479 return 'No database connection';
482 function lastErrno() {
483 if ( $this->mLastResult
) {
484 return pg_result_error_field( $this->mLastResult
, PGSQL_DIAG_SQLSTATE
);
490 function affectedRows() {
491 if ( !is_null( $this->mAffectedRows
) ) {
492 // Forced result for simulated queries
493 return $this->mAffectedRows
;
495 if( empty( $this->mLastResult
) ) {
498 return pg_affected_rows( $this->mLastResult
);
502 * Estimate rows in dataset
503 * Returns estimated count, based on EXPLAIN output
504 * This is not necessarily an accurate estimate, so use sparingly
505 * Returns -1 if count cannot be found
506 * Takes same arguments as Database::select()
509 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
510 $options['EXPLAIN'] = true;
511 $res = $this->select( $table, $vars, $conds, $fname, $options );
514 $row = $this->fetchRow( $res );
516 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
524 * Returns information about an index
525 * If errors are explicitly ignored, returns NULL on failure
528 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
529 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
530 $res = $this->query( $sql, $fname );
534 foreach ( $res as $row ) {
535 if ( $row->indexname
== $this->indexName( $index ) ) {
543 * Returns is of attributes used in index
548 function indexAttributes ( $index, $schema = false ) {
549 if ( $schema === false )
550 $schema = $this->getCoreSchema();
552 * A subquery would be not needed if we didn't care about the order
553 * of attributes, but we do
555 $sql = <<<__INDEXATTR__
559 i.indoption[s.g] as option,
562 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
566 ON cis.oid=isub.indexrelid
568 ON cis.relnamespace = ns.oid
569 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
575 ON ci.oid=i.indexrelid
577 ON ct.oid = i.indrelid
579 ON ci.relnamespace = n.oid
581 ci.relname='$index' AND n.nspname='$schema'
582 AND attrelid = ct.oid
583 AND i.indkey[s.g] = attnum
584 AND i.indclass[s.g] = opcls.oid
585 AND pg_am.oid = opcls.opcmethod
587 $res = $this->query($sql, __METHOD__);
590 foreach ( $res as $row ) {
604 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
605 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
606 " AND indexdef LIKE 'CREATE UNIQUE%(" .
607 $this->strencode( $this->indexName( $index ) ) .
609 $res = $this->query( $sql, $fname );
613 foreach ( $res as $row ) {
620 * INSERT wrapper, inserts an array into a table
622 * $args may be a single associative array, or an array of these with numeric keys,
623 * for multi-row insert (Postgres version 8.2 and above only).
625 * @param $table String: Name of the table to insert to.
626 * @param $args Array: Items to insert into the table.
627 * @param $fname String: Name of the function, for profiling
628 * @param $options String or Array. Valid options: IGNORE
630 * @return bool Success of insert operation. IGNORE always returns true.
632 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
633 if ( !count( $args ) ) {
637 $table = $this->tableName( $table );
638 if (! isset( $this->numeric_version ) ) {
639 $this->getServerVersion();
642 if ( !is_array( $options ) ) {
643 $options = array( $options );
646 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
648 $keys = array_keys( $args[0] );
651 $keys = array_keys( $args );
654 // If IGNORE is set, we use savepoints to emulate mysql's behavior
655 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
657 // If we are not in a transaction, we need to be for savepoint trickery
660 if ( !$this->mTrxLevel ) {
661 $this->begin( __METHOD__ );
664 $olde = error_reporting( 0 );
665 // For future use, we may want to track the number of actual inserts
666 // Right now, insert (all writes) simply return true/false
667 $numrowsinserted = 0;
670 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
673 if ( $this->numeric_version >= 8.2 && !$ignore ) {
675 foreach ( $args as $row ) {
681 $sql .= '(' . $this->makeList( $row ) . ')';
683 $res = (bool)$this->query( $sql, $fname, $ignore );
687 foreach ( $args as $row ) {
689 $tempsql .= '(' . $this->makeList( $row ) . ')';
692 $this->doQuery( "SAVEPOINT $ignore" );
695 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
698 $bar = pg_last_error();
699 if ( $bar != false ) {
700 $this->doQuery( $this->mConn, "ROLLBACK TO $ignore" );
702 $this->doQuery( $this->mConn, "RELEASE $ignore" );
707 // If any of them fail, we fail overall for this function call
708 // Note that this will be ignored if IGNORE is set
715 // Not multi, just a lone insert
717 $this->doQuery( "SAVEPOINT $ignore" );
720 $sql .= '(' . $this->makeList( $args ) . ')';
721 $res = (bool)$this->query( $sql, $fname, $ignore );
723 $bar = pg_last_error();
724 if ( $bar != false ) {
725 $this->doQuery( "ROLLBACK TO $ignore" );
727 $this->doQuery( "RELEASE $ignore" );
733 $olde = error_reporting( $olde );
735 $this->commit( __METHOD__ );
738 // Set the affected row count for the whole operation
739 $this->mAffectedRows = $numrowsinserted;
741 // IGNORE always returns true
749 * INSERT SELECT wrapper
750 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
751 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
752 * $conds may be "*" to copy the whole table
753 * srcTable may be an array of tables.
754 * @todo FIXME: Implement this a little better (seperate select/insert)?
757 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
758 $insertOptions = array(), $selectOptions = array() )
760 $destTable = $this->tableName( $destTable );
762 // If IGNORE is set, we use savepoints to emulate mysql's behavior
763 $ignore = in_array( 'IGNORE', $insertOptions ) ? 'mw' : '';
765 if( is_array( $insertOptions ) ) {
766 $insertOptions = implode( ' ', $insertOptions ); // FIXME: This is unused
768 if( !is_array( $selectOptions ) ) {
769 $selectOptions = array( $selectOptions );
771 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
772 if( is_array( $srcTable ) ) {
773 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
775 $srcTable = $this->tableName( $srcTable );
778 // If we are not in a transaction, we need to be for savepoint trickery
781 if( !$this->mTrxLevel ) {
782 $this->begin( __METHOD__ );
785 $olde = error_reporting( 0 );
786 $numrowsinserted = 0;
787 $this->doQuery( "SAVEPOINT $ignore" );
790 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
791 " SELECT $startOpts " . implode( ',', $varMap ) .
792 " FROM $srcTable $useIndex";
794 if ( $conds != '*' ) {
795 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
798 $sql .= " $tailOpts";
800 $res = (bool)$this->query( $sql, $fname, $ignore );
802 $bar = pg_last_error();
803 if( $bar != false ) {
804 $this->doQuery( "ROLLBACK TO $ignore" );
806 $this->doQuery( "RELEASE $ignore" );
809 $olde = error_reporting( $olde );
811 $this->commit( __METHOD__ );
814 // Set the affected row count for the whole operation
815 $this->mAffectedRows = $numrowsinserted;
817 // IGNORE always returns true
824 function tableName( $name, $format = 'quoted' ) {
825 # Replace reserved words with better ones
828 return $this->realTableName( 'mwuser', $format );
830 return $this->realTableName( 'pagecontent', $format );
832 return $this->realTableName( $name, $format );
836 /* Don't cheat on installer */
837 function realTableName( $name, $format = 'quoted' ) {
838 return parent::tableName( $name, $format );
842 * Return the next in a sequence, save the value for retrieval via insertId()
845 function nextSequenceValue( $seqName ) {
846 $safeseq = str_replace( "'", "''", $seqName );
847 $res = $this->query( "SELECT nextval('$safeseq')" );
848 $row = $this->fetchRow( $res );
849 $this->mInsertId = $row[0];
850 return $this->mInsertId;
854 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
857 function currentSequenceValue( $seqName ) {
858 $safeseq = str_replace( "'", "''", $seqName );
859 $res = $this->query( "SELECT currval('$safeseq')" );
860 $row = $this->fetchRow( $res );
865 # Returns the size of a text field, or -1 for "unlimited"
866 function textFieldSize( $table, $field ) {
867 $table = $this->tableName( $table );
868 $sql = "SELECT t.typname as ftype,a.atttypmod as size
869 FROM pg_class c, pg_attribute a, pg_type t
870 WHERE relname='$table' AND a.attrelid=c.oid AND
871 a.atttypid=t.oid and a.attname='$field'";
872 $res =$this->query( $sql );
873 $row = $this->fetchObject( $res );
874 if ( $row->ftype == 'varchar' ) {
875 $size = $row->size - 4;
882 function limitResult( $sql, $limit, $offset = false ) {
883 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
886 function wasDeadlock() {
887 return $this->lastErrno() == '40P01';
890 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
891 $newName = $this->addIdentifierQuotes( $newName );
892 $oldName = $this->addIdentifierQuotes( $oldName );
893 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
896 function listTables( $prefix = null, $fname = 'DatabasePostgres::listTables' ) {
897 $eschema = $this->addQuotes( $this->getCoreSchema() );
898 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
901 foreach( $result as $table ) {
902 $vars = get_object_vars($table);
903 $table = array_pop( $vars );
904 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
905 $endArray[] = $table;
912 function timestamp( $ts = 0 ) {
913 return wfTimestamp( TS_POSTGRES, $ts );
917 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
918 * to http://www.php.net/manual/en/ref.pgsql.php
920 * Parsing a postgres array can be a tricky problem, he's my
921 * take on this, it handles multi-dimensional arrays plus
922 * escaping using a nasty regexp to determine the limits of each
925 * This should really be handled by PHP PostgreSQL module
928 * @param $text string: postgreql array returned in a text form like {a,b}
929 * @param $output string
934 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
935 if( false === $limit ) {
936 $limit = strlen( $text )-1;
939 if( '{}' == $text ) {
943 if ( '{' != $text{$offset} ) {
944 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
945 $text, $match, 0, $offset );
946 $offset += strlen( $match[0] );
947 $output[] = ( '"' != $match[1]{0}
949 : stripcslashes( substr( $match[1], 1, -1 ) ) );
950 if ( '},' == $match[3] ) {
954 $offset = $this->pg_array_parse( $text, $output, $limit, $offset+1 );
956 } while ( $limit > $offset );
961 * Return aggregated value function call
963 function aggregateValue( $valuedata, $valuename = 'value' ) {
968 * @return string wikitext of a link to the server software's web site
970 public static function getSoftwareLink() {
971 return '[http://www.postgresql.org/ PostgreSQL]';
976 * Return current schema (executes SELECT current_schema())
980 * @return string return default schema for the current session
982 function getCurrentSchema() {
983 $res = $this->query( "SELECT current_schema()", __METHOD__);
984 $row = $this->fetchRow( $res );
989 * Return list of schemas which are accessible without schema name
990 * This is list does not contain magic keywords like "$user"
993 * @seealso getSearchPath()
994 * @seealso setSearchPath()
996 * @return array list of actual schemas for the current sesson
998 function getSchemas() {
999 $res = $this->query( "SELECT current_schemas(false)", __METHOD__);
1000 $row = $this->fetchRow( $res );
1002 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
1003 return $this->pg_array_parse($row[0], $schemas);
1007 * Return search patch for schemas
1008 * This is different from getSchemas() since it contain magic keywords
1013 * @return array how to search for table names schemas for the current user
1015 function getSearchPath() {
1016 $res = $this->query( "SHOW search_path", __METHOD__);
1017 $row = $this->fetchRow( $res );
1018 /* PostgreSQL returns SHOW values as strings */
1019 return explode(",", $row[0]);
1023 * Update search_path, values should already be sanitized
1024 * Values may contain magic keywords like "$user"
1027 * @param $search_path array list of schemas to be searched by default
1029 function setSearchPath( $search_path ) {
1030 $this->query( "SET search_path = " . implode(", ", $search_path) );
1034 * Determine default schema for MediaWiki core
1035 * Adjust this session schema search path if desired schema exists
1036 * and is not alread there.
1038 * We need to have name of the core schema stored to be able
1039 * to query database metadata.
1041 * This will be also called by the installer after the schema is created
1044 * @param desired_schema string
1046 function determineCoreSchema( $desired_schema ) {
1047 $this->begin( __METHOD__ );
1048 if ( $this->schemaExists( $desired_schema ) ) {
1049 if ( in_array( $desired_schema, $this->getSchemas() ) ) {
1050 $this->mCoreSchema = $desired_schema;
1051 wfDebug("Schema \"" . $desired_schema . "\" already in the search path\n");
1054 * Prepend our schema (e.g. 'mediawiki') in front
1055 * of the search path
1058 $search_path = $this->getSearchPath();
1059 array_unshift( $search_path,
1060 $this->addIdentifierQuotes( $desired_schema ));
1061 $this->setSearchPath( $search_path );
1062 $this->mCoreSchema = $desired_schema;
1063 wfDebug("Schema \"" . $desired_schema . "\" added to the search path\n");
1066 $this->mCoreSchema = $this->getCurrentSchema();
1067 wfDebug("Schema \"" . $desired_schema . "\" not found, using current \"". $this->mCoreSchema ."\"\n");
1069 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1070 $this->commit( __METHOD__ );
1074 * Return schema name fore core MediaWiki tables
1077 * @return string core schema name
1079 function getCoreSchema() {
1080 return $this->mCoreSchema;
1084 * @return string Version information from the database
1086 function getServerVersion() {
1087 if ( !isset( $this->numeric_version ) ) {
1088 $versionInfo = pg_version( $this->mConn );
1089 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1090 // Old client, abort install
1091 $this->numeric_version = '7.3 or earlier';
1092 } elseif ( isset( $versionInfo['server'] ) ) {
1094 $this->numeric_version = $versionInfo['server'];
1096 // Bug 16937: broken pgsql extension from PHP<5.3
1097 $this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
1100 return $this->numeric_version;
1104 * Query whether a given relation exists (in the given schema, or the
1105 * default mw one if not given)
1108 function relationExists( $table, $types, $schema = false ) {
1109 if ( !is_array( $types ) ) {
1110 $types = array( $types );
1113 $schema = $this->getCoreSchema();
1115 $table = $this->realTableName( $table, 'raw' );
1116 $etable = $this->addQuotes( $table );
1117 $eschema = $this->addQuotes( $schema );
1118 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1119 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1120 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1121 $res = $this->query( $SQL );
1122 $count = $res ? $res->numRows() : 0;
1123 return (bool)$count;
1127 * For backward compatibility, this function checks both tables and
1131 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1132 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1135 function sequenceExists( $sequence, $schema = false ) {
1136 return $this->relationExists( $sequence, 'S', $schema );
1139 function triggerExists( $table, $trigger ) {
1141 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1142 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1143 AND tgrelid=pg_class.oid
1144 AND nspname=%s AND relname=%s AND tgname=%s
1146 $res = $this->query(
1149 $this->addQuotes( $this->getCoreSchema() ),
1150 $this->addQuotes( $table ),
1151 $this->addQuotes( $trigger )
1157 $rows = $res->numRows();
1161 function ruleExists( $table, $rule ) {
1162 $exists = $this->selectField( 'pg_rules', 'rulename',
1164 'rulename' => $rule,
1165 'tablename' => $table,
1166 'schemaname' => $this->getCoreSchema()
1169 return $exists === $rule;
1172 function constraintExists( $table, $constraint ) {
1173 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1174 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1175 $this->addQuotes( $this->getCoreSchema() ),
1176 $this->addQuotes( $table ),
1177 $this->addQuotes( $constraint )
1179 $res = $this->query( $SQL );
1183 $rows = $res->numRows();
1188 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1191 function schemaExists( $schema ) {
1192 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1193 array( 'nspname' => $schema ), __METHOD__ );
1194 return (bool)$exists;
1198 * Returns true if a given role (i.e. user) exists, false otherwise.
1201 function roleExists( $roleName ) {
1202 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1203 array( 'rolname' => $roleName ), __METHOD__ );
1204 return (bool)$exists;
1207 function fieldInfo( $table, $field ) {
1208 return PostgresField::fromText( $this, $table, $field );
1212 * pg_field_type() wrapper
1215 function fieldType( $res, $index ) {
1216 if ( $res instanceof ResultWrapper ) {
1217 $res = $res->result;
1219 return pg_field_type( $res, $index );
1222 /* Not even sure why this is used in the main codebase... */
1223 function limitResultForUpdate( $sql, $num ) {
1231 function encodeBlob( $b ) {
1232 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
1235 function decodeBlob( $b ) {
1236 if ( $b instanceof Blob ) {
1239 return pg_unescape_bytea( $b );
1242 function strencode( $s ) { # Should not be called by us
1243 return pg_escape_string( $this->mConn, $s );
1247 * @param $s null|bool|Blob
1248 * @return int|string
1250 function addQuotes( $s ) {
1251 if ( is_null( $s ) ) {
1253 } elseif ( is_bool( $s ) ) {
1254 return intval( $s );
1255 } elseif ( $s instanceof Blob ) {
1256 return "'" . $s->fetch( $s ) . "'";
1258 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1262 * Postgres specific version of replaceVars.
1263 * Calls the parent version in Database.php
1267 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1269 * @return string SQL string
1271 protected function replaceVars( $ins ) {
1272 $ins = parent::replaceVars( $ins );
1274 if ( $this->numeric_version >= 8.3 ) {
1275 // Thanks for not providing backwards-compatibility, 8.3
1276 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1279 if ( $this->numeric_version <= 8.1 ) { // Our minimum version
1280 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1287 * Various select options
1291 * @param $options Array: an associative array of options to be turned into
1292 * an SQL query, valid keys are listed in the function.
1295 function makeSelectOptions( $options ) {
1296 $preLimitTail = $postLimitTail = '';
1297 $startOpts = $useIndex = '';
1299 $noKeyOptions = array();
1300 foreach ( $options as $key => $option ) {
1301 if ( is_numeric( $key ) ) {
1302 $noKeyOptions[$option] = true;
1306 if ( isset( $options['GROUP BY'] ) ) {
1307 $gb = is_array( $options['GROUP BY'] )
1308 ? implode( ',', $options['GROUP BY'] )
1309 : $options['GROUP BY'];
1310 $preLimitTail .= " GROUP BY {$gb}";
1313 if ( isset( $options['HAVING'] ) ) {
1314 $preLimitTail .= " HAVING {$options['HAVING']}";
1317 if ( isset( $options['ORDER BY'] ) ) {
1318 $ob = is_array( $options['ORDER BY'] )
1319 ? implode( ',', $options['ORDER BY'] )
1320 : $options['ORDER BY'];
1321 $preLimitTail .= " ORDER BY {$ob}";
1324 //if ( isset( $options['LIMIT'] ) ) {
1325 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1326 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1330 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1331 $postLimitTail .= ' FOR UPDATE';
1333 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1334 $postLimitTail .= ' LOCK IN SHARE MODE';
1336 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1337 $startOpts .= 'DISTINCT';
1340 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1343 function setFakeMaster( $enabled = true ) {}
1345 function getDBname() {
1346 return $this->mDBname;
1349 function getServer() {
1350 return $this->mServer;
1353 function buildConcat( $stringList ) {
1354 return implode( ' || ', $stringList );
1357 public function getSearchEngine() {
1358 return 'SearchPostgres';
1361 public function streamStatementEnd( &$sql, &$newLine ) {
1362 # Allow dollar quoting for function declarations
1363 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1364 if ( $this->delimiter ) {
1365 $this->delimiter = false;
1368 $this->delimiter = ';';
1371 return parent::streamStatementEnd( $sql, $newLine );
1373 } // end DatabasePostgres class