3 * This is the Postgres database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 class PostgresField
implements Field
{
25 private $name, $tablename, $type, $nullable, $max_length, $deferred, $deferrable, $conname,
26 $has_default, $default;
29 * @param IDatabase $db
30 * @param string $table
31 * @param string $field
32 * @return null|PostgresField
34 static function fromText( $db, $table, $field ) {
37 attnotnull, attlen, conname AS conname,
40 COALESCE(condeferred, 'f') AS deferred,
41 COALESCE(condeferrable, 'f') AS deferrable,
42 CASE WHEN typname = 'int2' THEN 'smallint'
43 WHEN typname = 'int4' THEN 'integer'
44 WHEN typname = 'int8' THEN 'bigint'
45 WHEN typname = 'bpchar' THEN 'char'
46 ELSE typname END AS typname
48 JOIN pg_namespace n ON (n.oid = c.relnamespace)
49 JOIN pg_attribute a ON (a.attrelid = c.oid)
50 JOIN pg_type t ON (t.oid = a.atttypid)
51 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
52 LEFT JOIN pg_attrdef d on c.oid=d.adrelid and a.attnum=d.adnum
59 $table = $db->tableName( $table, 'raw' );
62 $db->addQuotes( $db->getCoreSchema() ),
63 $db->addQuotes( $table ),
64 $db->addQuotes( $field )
67 $row = $db->fetchObject( $res );
71 $n = new PostgresField
;
72 $n->type
= $row->typname
;
73 $n->nullable
= ( $row->attnotnull
== 'f' );
75 $n->tablename
= $table;
76 $n->max_length
= $row->attlen
;
77 $n->deferrable
= ( $row->deferrable
== 't' );
78 $n->deferred
= ( $row->deferred
== 't' );
79 $n->conname
= $row->conname
;
80 $n->has_default
= ( $row->atthasdef
=== 't' );
81 $n->default = $row->adsrc
;
90 function tableName() {
91 return $this->tablename
;
98 function isNullable() {
99 return $this->nullable
;
102 function maxLength() {
103 return $this->max_length
;
106 function is_deferrable() {
107 return $this->deferrable
;
110 function is_deferred() {
111 return $this->deferred
;
115 return $this->conname
;
122 function defaultValue() {
123 if ( $this->has_default
) {
124 return $this->default;
132 * Manage savepoints within a transaction
136 class SavepointPostgres
{
137 /** @var DatabasePostgres Establish a savepoint within a transaction */
143 * @param IDatabase $dbw
146 public function __construct( $dbw, $id ) {
149 $this->didbegin
= false;
150 /* If we are not in a transaction, we need to be for savepoint trickery */
151 if ( !$dbw->trxLevel() ) {
152 $dbw->begin( "FOR SAVEPOINT", DatabasePostgres
::TRANSACTION_INTERNAL
);
153 $this->didbegin
= true;
157 public function __destruct() {
158 if ( $this->didbegin
) {
159 $this->dbw
->rollback();
160 $this->didbegin
= false;
164 public function commit() {
165 if ( $this->didbegin
) {
166 $this->dbw
->commit();
167 $this->didbegin
= false;
171 protected function query( $keyword, $msg_ok, $msg_failed ) {
172 if ( $this->dbw
->doQuery( $keyword . " " . $this->id
) !== false ) {
174 wfDebug( sprintf( $msg_failed, $this->id
) );
178 public function savepoint() {
179 $this->query( "SAVEPOINT",
180 "Transaction state: savepoint \"%s\" established.\n",
181 "Transaction state: establishment of savepoint \"%s\" FAILED.\n"
185 public function release() {
186 $this->query( "RELEASE",
187 "Transaction state: savepoint \"%s\" released.\n",
188 "Transaction state: release of savepoint \"%s\" FAILED.\n"
192 public function rollback() {
193 $this->query( "ROLLBACK TO",
194 "Transaction state: savepoint \"%s\" rolled back.\n",
195 "Transaction state: rollback of savepoint \"%s\" FAILED.\n"
199 public function __toString() {
200 return (string)$this->id
;
207 class DatabasePostgres
extends DatabaseBase
{
209 protected $mLastResult = null;
211 /** @var int The number of rows affected as an integer */
212 protected $mAffectedRows = null;
215 private $mInsertId = null;
217 /** @var float|string */
218 private $numericVersion = null;
220 /** @var string Connect string to open a PostgreSQL connection */
221 private $connectString;
224 private $mCoreSchema;
230 function implicitGroupby() {
234 function implicitOrderby() {
238 function hasConstraint( $name ) {
239 $sql = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
240 "WHERE c.connamespace = n.oid AND conname = '" .
241 pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" .
242 pg_escape_string( $this->mConn
, $this->getCoreSchema() ) . "'";
243 $res = $this->doQuery( $sql );
245 return $this->numRows( $res );
249 * Usually aborts on failure
250 * @param string $server
251 * @param string $user
252 * @param string $password
253 * @param string $dbName
254 * @throws DBConnectionError|Exception
255 * @return resource|bool|null
257 function open( $server, $user, $password, $dbName ) {
258 # Test for Postgres support, to avoid suppressed fatal error
259 if ( !function_exists( 'pg_connect' ) ) {
260 throw new DBConnectionError(
262 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
263 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
264 "webserver and database)\n"
270 if ( !strlen( $user ) ) { # e.g. the class is being loaded
274 $this->mServer
= $server;
276 $this->mUser
= $user;
277 $this->mPassword
= $password;
278 $this->mDBname
= $dbName;
283 'password' => $password
285 if ( $server != false && $server != '' ) {
286 $connectVars['host'] = $server;
288 if ( $port != false && $port != '' ) {
289 $connectVars['port'] = $port;
291 if ( $this->mFlags
& DBO_SSL
) {
292 $connectVars['sslmode'] = 1;
295 $this->connectString
= $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
297 $this->installErrorHandler();
300 $this->mConn
= pg_connect( $this->connectString
);
301 } catch ( Exception
$ex ) {
302 $this->restoreErrorHandler();
306 $phpError = $this->restoreErrorHandler();
308 if ( !$this->mConn
) {
309 wfDebug( "DB connection error\n" );
310 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " .
311 substr( $password, 0, 3 ) . "...\n" );
312 wfDebug( $this->lastError() . "\n" );
313 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
316 $this->mOpened
= true;
318 global $wgCommandLineMode;
319 # If called from the command-line (e.g. importDump), only show errors
320 if ( $wgCommandLineMode ) {
321 $this->doQuery( "SET client_min_messages = 'ERROR'" );
324 $this->query( "SET client_encoding='UTF8'", __METHOD__
);
325 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__
);
326 $this->query( "SET timezone = 'GMT'", __METHOD__
);
327 $this->query( "SET standard_conforming_strings = on", __METHOD__
);
328 if ( $this->getServerVersion() >= 9.0 ) {
329 $this->query( "SET bytea_output = 'escape'", __METHOD__
); // PHP bug 53127
332 global $wgDBmwschema;
333 $this->determineCoreSchema( $wgDBmwschema );
339 * Postgres doesn't support selectDB in the same way MySQL does. So if the
340 * DB name doesn't match the open connection, open a new one
344 function selectDB( $db ) {
345 if ( $this->mDBname
!== $db ) {
346 return (bool)$this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $db );
352 function makeConnectionString( $vars ) {
354 foreach ( $vars as $name => $value ) {
355 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
362 * Closes a database connection, if it is open
363 * Returns success, true if already closed
366 protected function closeConnection() {
367 return pg_close( $this->mConn
);
370 public function doQuery( $sql ) {
371 $sql = mb_convert_encoding( $sql, 'UTF-8' );
372 // Clear previously left over PQresult
373 while ( $res = pg_get_result( $this->mConn
) ) {
374 pg_free_result( $res );
376 if ( pg_send_query( $this->mConn
, $sql ) === false ) {
377 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
379 $this->mLastResult
= pg_get_result( $this->mConn
);
380 $this->mAffectedRows
= null;
381 if ( pg_result_error( $this->mLastResult
) ) {
385 return $this->mLastResult
;
388 protected function dumpError() {
392 PGSQL_DIAG_MESSAGE_PRIMARY
,
393 PGSQL_DIAG_MESSAGE_DETAIL
,
394 PGSQL_DIAG_MESSAGE_HINT
,
395 PGSQL_DIAG_STATEMENT_POSITION
,
396 PGSQL_DIAG_INTERNAL_POSITION
,
397 PGSQL_DIAG_INTERNAL_QUERY
,
399 PGSQL_DIAG_SOURCE_FILE
,
400 PGSQL_DIAG_SOURCE_LINE
,
401 PGSQL_DIAG_SOURCE_FUNCTION
403 foreach ( $diags as $d ) {
404 wfDebug( sprintf( "PgSQL ERROR(%d): %s\n",
405 $d, pg_result_error_field( $this->mLastResult
, $d ) ) );
409 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
411 /* Check for constraint violation */
412 if ( $errno === '23505' ) {
413 parent
::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
418 /* Transaction stays in the ERROR state until rolled back */
419 if ( $this->mTrxLevel
) {
420 $ignore = $this->ignoreErrors( true );
421 $this->rollback( __METHOD__
);
422 $this->ignoreErrors( $ignore );
424 parent
::reportQueryError( $error, $errno, $sql, $fname, false );
427 function queryIgnore( $sql, $fname = __METHOD__
) {
428 return $this->query( $sql, $fname, true );
432 * @param stdClass|ResultWrapper $res
433 * @throws DBUnexpectedError
435 function freeResult( $res ) {
436 if ( $res instanceof ResultWrapper
) {
439 MediaWiki\
suppressWarnings();
440 $ok = pg_free_result( $res );
441 MediaWiki\restoreWarnings
();
443 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
448 * @param ResultWrapper|stdClass $res
450 * @throws DBUnexpectedError
452 function fetchObject( $res ) {
453 if ( $res instanceof ResultWrapper
) {
456 MediaWiki\
suppressWarnings();
457 $row = pg_fetch_object( $res );
458 MediaWiki\restoreWarnings
();
459 # @todo FIXME: HACK HACK HACK HACK debug
461 # @todo hashar: not sure if the following test really trigger if the object
463 if ( pg_last_error( $this->mConn
) ) {
464 throw new DBUnexpectedError(
466 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
473 function fetchRow( $res ) {
474 if ( $res instanceof ResultWrapper
) {
477 MediaWiki\
suppressWarnings();
478 $row = pg_fetch_array( $res );
479 MediaWiki\restoreWarnings
();
480 if ( pg_last_error( $this->mConn
) ) {
481 throw new DBUnexpectedError(
483 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
490 function numRows( $res ) {
491 if ( $res instanceof ResultWrapper
) {
494 MediaWiki\
suppressWarnings();
495 $n = pg_num_rows( $res );
496 MediaWiki\restoreWarnings
();
497 if ( pg_last_error( $this->mConn
) ) {
498 throw new DBUnexpectedError(
500 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
507 function numFields( $res ) {
508 if ( $res instanceof ResultWrapper
) {
512 return pg_num_fields( $res );
515 function fieldName( $res, $n ) {
516 if ( $res instanceof ResultWrapper
) {
520 return pg_field_name( $res, $n );
524 * Return the result of the last call to nextSequenceValue();
525 * This must be called after nextSequenceValue().
529 function insertId() {
530 return $this->mInsertId
;
538 function dataSeek( $res, $row ) {
539 if ( $res instanceof ResultWrapper
) {
543 return pg_result_seek( $res, $row );
546 function lastError() {
547 if ( $this->mConn
) {
548 if ( $this->mLastResult
) {
549 return pg_result_error( $this->mLastResult
);
551 return pg_last_error();
554 return 'No database connection';
558 function lastErrno() {
559 if ( $this->mLastResult
) {
560 return pg_result_error_field( $this->mLastResult
, PGSQL_DIAG_SQLSTATE
);
566 function affectedRows() {
567 if ( !is_null( $this->mAffectedRows
) ) {
568 // Forced result for simulated queries
569 return $this->mAffectedRows
;
571 if ( empty( $this->mLastResult
) ) {
575 return pg_affected_rows( $this->mLastResult
);
579 * Estimate rows in dataset
580 * Returns estimated count, based on EXPLAIN output
581 * This is not necessarily an accurate estimate, so use sparingly
582 * Returns -1 if count cannot be found
583 * Takes same arguments as Database::select()
585 * @param string $table
586 * @param string $vars
587 * @param string $conds
588 * @param string $fname
589 * @param array $options
592 function estimateRowCount( $table, $vars = '*', $conds = '',
593 $fname = __METHOD__
, $options = []
595 $options['EXPLAIN'] = true;
596 $res = $this->select( $table, $vars, $conds, $fname, $options );
599 $row = $this->fetchRow( $res );
601 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
602 $rows = (int)$count[1];
610 * Returns information about an index
611 * If errors are explicitly ignored, returns NULL on failure
613 * @param string $table
614 * @param string $index
615 * @param string $fname
618 function indexInfo( $table, $index, $fname = __METHOD__
) {
619 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
620 $res = $this->query( $sql, $fname );
624 foreach ( $res as $row ) {
625 if ( $row->indexname
== $this->indexName( $index ) ) {
634 * Returns is of attributes used in index
637 * @param string $index
638 * @param bool|string $schema
641 function indexAttributes( $index, $schema = false ) {
642 if ( $schema === false ) {
643 $schema = $this->getCoreSchema();
646 * A subquery would be not needed if we didn't care about the order
647 * of attributes, but we do
649 $sql = <<<__INDEXATTR__
653 i.indoption[s.g] as option,
656 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
660 ON cis.oid=isub.indexrelid
662 ON cis.relnamespace = ns.oid
663 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
669 ON ci.oid=i.indexrelid
671 ON ct.oid = i.indrelid
673 ON ci.relnamespace = n.oid
675 ci.relname='$index' AND n.nspname='$schema'
676 AND attrelid = ct.oid
677 AND i.indkey[s.g] = attnum
678 AND i.indclass[s.g] = opcls.oid
679 AND pg_am.oid = opcls.opcmethod
681 $res = $this->query( $sql, __METHOD__ );
684 foreach ( $res as $row ) {
698 function indexUnique( $table, $index, $fname = __METHOD__ ) {
699 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
700 " AND indexdef LIKE 'CREATE UNIQUE%(" .
701 $this->strencode( $this->indexName( $index ) ) .
703 $res = $this->query( $sql, $fname );
708 return $res->numRows() > 0;
712 * Change the FOR UPDATE option as necessary based on the join conditions. Then pass
713 * to the parent function to get the actual SQL text.
715 * In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
716 * can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to do
717 * so causes a DB error. This wrapper checks which tables can be locked and adjusts it accordingly.
719 * MySQL uses "ORDER BY NULL" as an optimization hint, but that syntax is illegal in PostgreSQL.
720 * @see DatabaseBase::selectSQLText
722 function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
723 $options = [], $join_conds = []
725 if ( is_array( $options ) ) {
726 $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
727 if ( $forUpdateKey !== false && $join_conds ) {
728 unset( $options[$forUpdateKey] );
730 foreach ( $join_conds as $table_cond => $join_cond ) {
731 if ( 0 === preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_cond[0] ) ) {
732 $options['FOR UPDATE'][] = $table_cond;
737 if ( isset( $options['ORDER BY'] ) && $options['ORDER BY'] == 'NULL' ) {
738 unset( $options['ORDER BY'] );
742 return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
746 * INSERT wrapper, inserts an array into a table
748 * $args may be a single associative array, or an array of these with numeric keys,
749 * for multi-row insert (Postgres version 8.2 and above only).
751 * @param string $table Name of the table to insert to.
752 * @param array $args Items to insert into the table.
753 * @param string $fname Name of the function, for profiling
754 * @param array|string $options String or array. Valid options: IGNORE
755 * @return bool Success of insert operation. IGNORE always returns true.
757 function insert( $table, $args, $fname = __METHOD__, $options = [] ) {
758 if ( !count( $args ) ) {
762 $table = $this->tableName( $table );
763 if ( !isset( $this->numericVersion ) ) {
764 $this->getServerVersion();
767 if ( !is_array( $options ) ) {
768 $options = [ $options ];
771 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
773 $keys = array_keys( $args[0] );
776 $keys = array_keys( $args );
779 // If IGNORE is set, we use savepoints to emulate mysql's behavior
781 if ( in_array( 'IGNORE', $options ) ) {
782 $savepoint = new SavepointPostgres( $this, 'mw' );
783 $olde = error_reporting( 0 );
784 // For future use, we may want to track the number of actual inserts
785 // Right now, insert (all writes) simply return true/false
786 $numrowsinserted = 0;
789 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
792 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
794 foreach ( $args as $row ) {
800 $sql .= '(' . $this->makeList( $row ) . ')';
802 $res = (bool)$this->query( $sql, $fname, $savepoint );
806 foreach ( $args as $row ) {
808 $tempsql .= '(' . $this->makeList( $row ) . ')';
811 $savepoint->savepoint();
814 $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
817 $bar = pg_result_error( $this->mLastResult );
818 if ( $bar != false ) {
819 $savepoint->rollback();
821 $savepoint->release();
826 // If any of them fail, we fail overall for this function call
827 // Note that this will be ignored if IGNORE is set
834 // Not multi, just a lone insert
836 $savepoint->savepoint();
839 $sql .= '(' . $this->makeList( $args ) . ')';
840 $res = (bool)$this->query( $sql, $fname, $savepoint );
842 $bar = pg_result_error( $this->mLastResult );
843 if ( $bar != false ) {
844 $savepoint->rollback();
846 $savepoint->release();
852 error_reporting( $olde );
853 $savepoint->commit();
855 // Set the affected row count for the whole operation
856 $this->mAffectedRows = $numrowsinserted;
858 // IGNORE always returns true
866 * INSERT SELECT wrapper
867 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
868 * Source items may be literals rather then field names, but strings should
869 * be quoted with Database::addQuotes()
870 * $conds may be "*" to copy the whole table
871 * srcTable may be an array of tables.
872 * @todo FIXME: Implement this a little better (seperate select/insert)?
874 * @param string $destTable
875 * @param array|string $srcTable
876 * @param array $varMap
877 * @param array $conds
878 * @param string $fname
879 * @param array $insertOptions
880 * @param array $selectOptions
883 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
884 $insertOptions = [], $selectOptions = [] ) {
885 $destTable = $this->tableName( $destTable );
887 if ( !is_array( $insertOptions ) ) {
888 $insertOptions = [ $insertOptions ];
892 * If IGNORE is set, we use savepoints to emulate mysql's behavior
893 * Ignore LOW PRIORITY option, since it is MySQL-specific
896 if ( in_array( 'IGNORE', $insertOptions ) ) {
897 $savepoint = new SavepointPostgres( $this, 'mw' );
898 $olde = error_reporting( 0 );
899 $numrowsinserted = 0;
900 $savepoint->savepoint();
903 if ( !is_array( $selectOptions ) ) {
904 $selectOptions = [ $selectOptions ];
906 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) =
907 $this->makeSelectOptions( $selectOptions );
908 if ( is_array( $srcTable ) ) {
909 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
911 $srcTable = $this->tableName( $srcTable );
914 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
915 " SELECT $startOpts " . implode( ',', $varMap ) .
916 " FROM $srcTable $useIndex $ignoreIndex ";
918 if ( $conds != '*' ) {
919 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
922 $sql .= " $tailOpts";
924 $res = (bool)$this->query( $sql, $fname, $savepoint );
926 $bar = pg_result_error( $this->mLastResult );
927 if ( $bar != false ) {
928 $savepoint->rollback();
930 $savepoint->release();
933 error_reporting( $olde );
934 $savepoint->commit();
936 // Set the affected row count for the whole operation
937 $this->mAffectedRows = $numrowsinserted;
939 // IGNORE always returns true
946 function tableName( $name, $format = 'quoted' ) {
947 # Replace reserved words with better ones
950 return $this->realTableName( 'mwuser', $format );
952 return $this->realTableName( 'pagecontent', $format );
954 return $this->realTableName( $name, $format );
958 /* Don't cheat on installer */
959 function realTableName( $name, $format = 'quoted' ) {
960 return parent::tableName( $name, $format );
964 * Return the next in a sequence, save the value for retrieval via insertId()
966 * @param string $seqName
969 function nextSequenceValue( $seqName ) {
970 $safeseq = str_replace( "'", "''", $seqName );
971 $res = $this->query( "SELECT nextval('$safeseq')" );
972 $row = $this->fetchRow( $res );
973 $this->mInsertId = $row[0];
975 return $this->mInsertId;
979 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
981 * @param string $seqName
984 function currentSequenceValue( $seqName ) {
985 $safeseq = str_replace( "'", "''", $seqName );
986 $res = $this->query( "SELECT currval('$safeseq')" );
987 $row = $this->fetchRow( $res );
993 # Returns the size of a text field, or -1 for "unlimited"
994 function textFieldSize( $table, $field ) {
995 $table = $this->tableName( $table );
996 $sql = "SELECT t.typname as ftype,a.atttypmod as size
997 FROM pg_class c, pg_attribute a, pg_type t
998 WHERE relname='$table' AND a.attrelid=c.oid AND
999 a.atttypid=t.oid and a.attname='$field'";
1000 $res = $this->query( $sql );
1001 $row = $this->fetchObject( $res );
1002 if ( $row->ftype == 'varchar' ) {
1003 $size = $row->size - 4;
1011 function limitResult( $sql, $limit, $offset = false ) {
1012 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
1015 function wasDeadlock() {
1016 return $this->lastErrno() == '40P01';
1019 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1020 $newName = $this->addIdentifierQuotes( $newName );
1021 $oldName = $this->addIdentifierQuotes( $oldName );
1023 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName " .
1024 "(LIKE $oldName INCLUDING DEFAULTS)", $fname );
1027 function listTables( $prefix = null, $fname = __METHOD__ ) {
1028 $eschema = $this->addQuotes( $this->getCoreSchema() );
1029 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
1032 foreach ( $result as $table ) {
1033 $vars = get_object_vars( $table );
1034 $table = array_pop( $vars );
1035 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1036 $endArray[] = $table;
1043 function timestamp( $ts = 0 ) {
1044 return wfTimestamp( TS_POSTGRES, $ts );
1048 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
1049 * to http://www.php.net/manual/en/ref.pgsql.php
1051 * Parsing a postgres array can be a tricky problem, he's my
1052 * take on this, it handles multi-dimensional arrays plus
1053 * escaping using a nasty regexp to determine the limits of each
1056 * This should really be handled by PHP PostgreSQL module
1059 * @param string $text Postgreql array returned in a text form like {a,b}
1060 * @param string $output
1062 * @param int $offset
1065 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
1066 if ( false === $limit ) {
1067 $limit = strlen( $text ) - 1;
1070 if ( '{}' == $text ) {
1074 if ( '{' != $text[$offset] ) {
1075 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
1076 $text, $match, 0, $offset );
1077 $offset += strlen( $match[0] );
1078 $output[] = ( '"' != $match[1][0]
1080 : stripcslashes( substr( $match[1], 1, -1 ) ) );
1081 if ( '},' == $match[3] ) {
1085 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
1087 } while ( $limit > $offset );
1093 * Return aggregated value function call
1094 * @param array $valuedata
1095 * @param string $valuename
1098 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1103 * @return string Wikitext of a link to the server software's web site
1105 public function getSoftwareLink() {
1106 return '[{{int:version-db-postgres-url}} PostgreSQL]';
1110 * Return current schema (executes SELECT current_schema())
1114 * @return string Default schema for the current session
1116 function getCurrentSchema() {
1117 $res = $this->query( "SELECT current_schema()", __METHOD__ );
1118 $row = $this->fetchRow( $res );
1124 * Return list of schemas which are accessible without schema name
1125 * This is list does not contain magic keywords like "$user"
1128 * @see getSearchPath()
1129 * @see setSearchPath()
1131 * @return array List of actual schemas for the current sesson
1133 function getSchemas() {
1134 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
1135 $row = $this->fetchRow( $res );
1138 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
1140 return $this->pg_array_parse( $row[0], $schemas );
1144 * Return search patch for schemas
1145 * This is different from getSchemas() since it contain magic keywords
1150 * @return array How to search for table names schemas for the current user
1152 function getSearchPath() {
1153 $res = $this->query( "SHOW search_path", __METHOD__ );
1154 $row = $this->fetchRow( $res );
1156 /* PostgreSQL returns SHOW values as strings */
1158 return explode( ",", $row[0] );
1162 * Update search_path, values should already be sanitized
1163 * Values may contain magic keywords like "$user"
1166 * @param array $search_path List of schemas to be searched by default
1168 function setSearchPath( $search_path ) {
1169 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
1173 * Determine default schema for MediaWiki core
1174 * Adjust this session schema search path if desired schema exists
1175 * and is not alread there.
1177 * We need to have name of the core schema stored to be able
1178 * to query database metadata.
1180 * This will be also called by the installer after the schema is created
1184 * @param string $desiredSchema
1186 function determineCoreSchema( $desiredSchema ) {
1187 $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
1188 if ( $this->schemaExists( $desiredSchema ) ) {
1189 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
1190 $this->mCoreSchema = $desiredSchema;
1191 wfDebug( "Schema \"" . $desiredSchema . "\" already in the search path\n" );
1194 * Prepend our schema (e.g. 'mediawiki') in front
1195 * of the search path
1198 $search_path = $this->getSearchPath();
1199 array_unshift( $search_path,
1200 $this->addIdentifierQuotes( $desiredSchema ) );
1201 $this->setSearchPath( $search_path );
1202 $this->mCoreSchema = $desiredSchema;
1203 wfDebug( "Schema \"" . $desiredSchema . "\" added to the search path\n" );
1206 $this->mCoreSchema = $this->getCurrentSchema();
1207 wfDebug( "Schema \"" . $desiredSchema . "\" not found, using current \"" .
1208 $this->mCoreSchema . "\"\n" );
1210 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1211 $this->commit( __METHOD__ );
1215 * Return schema name fore core MediaWiki tables
1218 * @return string Core schema name
1220 function getCoreSchema() {
1221 return $this->mCoreSchema;
1225 * @return string Version information from the database
1227 function getServerVersion() {
1228 if ( !isset( $this->numericVersion ) ) {
1229 $versionInfo = pg_version( $this->mConn );
1230 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1231 // Old client, abort install
1232 $this->numericVersion = '7.3 or earlier';
1233 } elseif ( isset( $versionInfo['server'] ) ) {
1235 $this->numericVersion = $versionInfo['server'];
1237 // Bug 16937: broken pgsql extension from PHP<5.3
1238 $this->numericVersion = pg_parameter_status( $this->mConn, 'server_version' );
1242 return $this->numericVersion;
1246 * Query whether a given relation exists (in the given schema, or the
1247 * default mw one if not given)
1248 * @param string $table
1249 * @param array|string $types
1250 * @param bool|string $schema
1253 function relationExists( $table, $types, $schema = false ) {
1254 if ( !is_array( $types ) ) {
1255 $types = [ $types ];
1258 $schema = $this->getCoreSchema();
1260 $table = $this->realTableName( $table, 'raw' );
1261 $etable = $this->addQuotes( $table );
1262 $eschema = $this->addQuotes( $schema );
1263 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1264 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1265 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1266 $res = $this->query( $sql );
1267 $count = $res ? $res->numRows() : 0;
1269 return (bool)$count;
1273 * For backward compatibility, this function checks both tables and
1275 * @param string $table
1276 * @param string $fname
1277 * @param bool|string $schema
1280 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1281 return $this->relationExists( $table, [ 'r', 'v' ], $schema );
1284 function sequenceExists( $sequence, $schema = false ) {
1285 return $this->relationExists( $sequence, 'S', $schema );
1288 function triggerExists( $table, $trigger ) {
1290 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1291 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1292 AND tgrelid=pg_class.oid
1293 AND nspname=%s AND relname=%s AND tgname=%s
1295 $res = $this->query(
1298 $this->addQuotes( $this->getCoreSchema() ),
1299 $this->addQuotes( $table ),
1300 $this->addQuotes( $trigger )
1306 $rows = $res->numRows();
1311 function ruleExists( $table, $rule ) {
1312 $exists = $this->selectField( 'pg_rules', 'rulename',
1314 'rulename' => $rule,
1315 'tablename' => $table,
1316 'schemaname' => $this->getCoreSchema()
1320 return $exists === $rule;
1323 function constraintExists( $table, $constraint ) {
1324 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1325 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1326 $this->addQuotes( $this->getCoreSchema() ),
1327 $this->addQuotes( $table ),
1328 $this->addQuotes( $constraint )
1330 $res = $this->query( $sql );
1334 $rows = $res->numRows();
1340 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1341 * @param string $schema
1344 function schemaExists( $schema ) {
1345 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1346 [ 'nspname' => $schema ], __METHOD__ );
1348 return (bool)$exists;
1352 * Returns true if a given role (i.e. user) exists, false otherwise.
1353 * @param string $roleName
1356 function roleExists( $roleName ) {
1357 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1358 [ 'rolname' => $roleName ], __METHOD__ );
1360 return (bool)$exists;
1364 * @var string $table
1365 * @var string $field
1366 * @return PostgresField|null
1368 function fieldInfo( $table, $field ) {
1369 return PostgresField::fromText( $this, $table, $field );
1373 * pg_field_type() wrapper
1374 * @param ResultWrapper|resource $res ResultWrapper or PostgreSQL query result resource
1375 * @param int $index Field number, starting from 0
1378 function fieldType( $res, $index ) {
1379 if ( $res instanceof ResultWrapper ) {
1380 $res = $res->result;
1383 return pg_field_type( $res, $index );
1390 function encodeBlob( $b ) {
1391 return new PostgresBlob( pg_escape_bytea( $b ) );
1394 function decodeBlob( $b ) {
1395 if ( $b instanceof PostgresBlob ) {
1397 } elseif ( $b instanceof Blob ) {
1401 return pg_unescape_bytea( $b );
1404 function strencode( $s ) {
1405 // Should not be called by us
1407 return pg_escape_string( $this->mConn, $s );
1411 * @param null|bool|Blob $s
1412 * @return int|string
1414 function addQuotes( $s ) {
1415 if ( is_null( $s ) ) {
1417 } elseif ( is_bool( $s ) ) {
1418 return intval( $s );
1419 } elseif ( $s instanceof Blob ) {
1420 if ( $s instanceof PostgresBlob ) {
1423 $s = pg_escape_bytea( $this->mConn, $s->fetch() );
1428 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1432 * Postgres specific version of replaceVars.
1433 * Calls the parent version in Database.php
1435 * @param string $ins SQL string, read from a stream (usually tables.sql)
1436 * @return string SQL string
1438 protected function replaceVars( $ins ) {
1439 $ins = parent::replaceVars( $ins );
1441 if ( $this->numericVersion >= 8.3 ) {
1442 // Thanks for not providing backwards-compatibility, 8.3
1443 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1446 if ( $this->numericVersion <= 8.1 ) { // Our minimum version
1447 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1454 * Various select options
1456 * @param array $options An associative array of options to be turned into
1457 * an SQL query, valid keys are listed in the function.
1460 function makeSelectOptions( $options ) {
1461 $preLimitTail = $postLimitTail = '';
1462 $startOpts = $useIndex = $ignoreIndex = '';
1465 foreach ( $options as $key => $option ) {
1466 if ( is_numeric( $key ) ) {
1467 $noKeyOptions[$option] = true;
1471 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1473 $preLimitTail .= $this->makeOrderBy( $options );
1475 // if ( isset( $options['LIMIT'] ) ) {
1476 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1477 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1481 if ( isset( $options['FOR UPDATE'] ) ) {
1482 $postLimitTail .= ' FOR UPDATE OF ' .
1483 implode( ', ', array_map( [ &$this, 'tableName' ], $options['FOR UPDATE'] ) );
1484 } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1485 $postLimitTail .= ' FOR UPDATE';
1488 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1489 $startOpts .= 'DISTINCT';
1492 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1495 function getDBname() {
1496 return $this->mDBname;
1499 function getServer() {
1500 return $this->mServer;
1503 function buildConcat( $stringList ) {
1504 return implode( ' || ', $stringList );
1507 public function buildGroupConcatField(
1508 $delimiter, $table, $field, $conds = '', $options = [], $join_conds = []
1510 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1512 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1516 * @param string $field Field or column to cast
1520 public function buildStringCast( $field ) {
1521 return $field . '::text';
1524 public function streamStatementEnd( &$sql, &$newLine ) {
1525 # Allow dollar quoting for function declarations
1526 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1527 if ( $this->delimiter ) {
1528 $this->delimiter = false;
1530 $this->delimiter = ';';
1534 return parent::streamStatementEnd( $sql, $newLine );
1538 * Check to see if a named lock is available. This is non-blocking.
1539 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1541 * @param string $lockName Name of lock to poll
1542 * @param string $method Name of method calling us
1546 public function lockIsFree( $lockName, $method ) {
1547 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1548 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1549 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1550 $row = $this->fetchObject( $result );
1552 return ( $row->lockstatus === 't' );
1556 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1557 * @param string $lockName
1558 * @param string $method
1559 * @param int $timeout
1562 public function lock( $lockName, $method, $timeout = 5 ) {
1563 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1564 $loop = new WaitConditionLoop(
1565 function () use ( $lockName, $key, $timeout, $method ) {
1566 $res = $this->query( "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1567 $row = $this->fetchObject( $res );
1568 if ( $row->lockstatus === 't' ) {
1569 parent::lock( $lockName, $method, $timeout ); // record
1573 return WaitConditionLoop::CONDITION_CONTINUE;
1578 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1582 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKSFROM
1583 * PG DOCS: http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1584 * @param string $lockName
1585 * @param string $method
1588 public function unlock( $lockName, $method ) {
1589 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1590 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1591 $row = $this->fetchObject( $result );
1593 if ( $row->lockstatus === 't' ) {
1594 parent::unlock( $lockName, $method ); // record
1598 wfDebug( __METHOD__ . " failed to release lock\n" );
1604 * @param string $lockName
1605 * @return string Integer
1607 private function bigintFromLockName( $lockName ) {
1608 return Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1610 } // end DatabasePostgres class