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
23 use Wikimedia\WaitConditionLoop
;
28 class DatabasePostgres
extends Database
{
33 protected $mLastResult = null;
34 /** @var int The number of rows affected as an integer */
35 protected $mAffectedRows = null;
38 private $mInsertId = null;
39 /** @var float|string */
40 private $numericVersion = null;
41 /** @var string Connect string to open a PostgreSQL connection */
42 private $connectString;
46 public function __construct( array $params ) {
47 $this->port
= isset( $params['port'] ) ?
$params['port'] : false;
48 parent
::__construct( $params );
55 function implicitGroupby() {
59 function implicitOrderby() {
63 function hasConstraint( $name ) {
64 $sql = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
65 "WHERE c.connamespace = n.oid AND conname = '" .
66 pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" .
67 pg_escape_string( $this->mConn
, $this->getCoreSchema() ) . "'";
68 $res = $this->doQuery( $sql );
70 return $this->numRows( $res );
74 * Usually aborts on failure
75 * @param string $server
77 * @param string $password
78 * @param string $dbName
79 * @throws DBConnectionError|Exception
80 * @return resource|bool|null
82 function open( $server, $user, $password, $dbName ) {
83 # Test for Postgres support, to avoid suppressed fatal error
84 if ( !function_exists( 'pg_connect' ) ) {
85 throw new DBConnectionError(
87 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
88 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
89 "webserver and database)\n"
93 if ( !strlen( $user ) ) { # e.g. the class is being loaded
97 $this->mServer
= $server;
99 $this->mPassword
= $password;
100 $this->mDBname
= $dbName;
105 'password' => $password
107 if ( $server != false && $server != '' ) {
108 $connectVars['host'] = $server;
110 if ( (int)$this->port
> 0 ) {
111 $connectVars['port'] = (int)$this->port
;
113 if ( $this->mFlags
& self
::DBO_SSL
) {
114 $connectVars['sslmode'] = 1;
117 $this->connectString
= $this->makeConnectionString( $connectVars );
119 $this->installErrorHandler();
122 $this->mConn
= pg_connect( $this->connectString
);
123 } catch ( Exception
$ex ) {
124 $this->restoreErrorHandler();
128 $phpError = $this->restoreErrorHandler();
130 if ( !$this->mConn
) {
131 $this->queryLogger
->debug( "DB connection error\n" );
132 $this->queryLogger
->debug(
133 "Server: $server, Database: $dbName, User: $user, Password: " .
134 substr( $password, 0, 3 ) . "...\n" );
135 $this->queryLogger
->debug( $this->lastError() . "\n" );
136 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
139 $this->mOpened
= true;
141 # If called from the command-line (e.g. importDump), only show errors
142 if ( $this->cliMode
) {
143 $this->doQuery( "SET client_min_messages = 'ERROR'" );
146 $this->query( "SET client_encoding='UTF8'", __METHOD__
);
147 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__
);
148 $this->query( "SET timezone = 'GMT'", __METHOD__
);
149 $this->query( "SET standard_conforming_strings = on", __METHOD__
);
150 if ( $this->getServerVersion() >= 9.0 ) {
151 $this->query( "SET bytea_output = 'escape'", __METHOD__
); // PHP bug 53127
154 $this->determineCoreSchema( $this->mSchema
);
160 * Postgres doesn't support selectDB in the same way MySQL does. So if the
161 * DB name doesn't match the open connection, open a new one
165 function selectDB( $db ) {
166 if ( $this->mDBname
!== $db ) {
167 return (bool)$this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $db );
173 function makeConnectionString( $vars ) {
175 foreach ( $vars as $name => $value ) {
176 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
183 * Closes a database connection, if it is open
184 * Returns success, true if already closed
187 protected function closeConnection() {
188 return pg_close( $this->mConn
);
191 public function doQuery( $sql ) {
192 $sql = mb_convert_encoding( $sql, 'UTF-8' );
193 // Clear previously left over PQresult
194 while ( $res = pg_get_result( $this->mConn
) ) {
195 pg_free_result( $res );
197 if ( pg_send_query( $this->mConn
, $sql ) === false ) {
198 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
200 $this->mLastResult
= pg_get_result( $this->mConn
);
201 $this->mAffectedRows
= null;
202 if ( pg_result_error( $this->mLastResult
) ) {
206 return $this->mLastResult
;
209 protected function dumpError() {
213 PGSQL_DIAG_MESSAGE_PRIMARY
,
214 PGSQL_DIAG_MESSAGE_DETAIL
,
215 PGSQL_DIAG_MESSAGE_HINT
,
216 PGSQL_DIAG_STATEMENT_POSITION
,
217 PGSQL_DIAG_INTERNAL_POSITION
,
218 PGSQL_DIAG_INTERNAL_QUERY
,
220 PGSQL_DIAG_SOURCE_FILE
,
221 PGSQL_DIAG_SOURCE_LINE
,
222 PGSQL_DIAG_SOURCE_FUNCTION
224 foreach ( $diags as $d ) {
225 $this->queryLogger
->debug( sprintf( "PgSQL ERROR(%d): %s\n",
226 $d, pg_result_error_field( $this->mLastResult
, $d ) ) );
230 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
232 /* Check for constraint violation */
233 if ( $errno === '23505' ) {
234 parent
::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
239 /* Transaction stays in the ERROR state until rolled back */
240 if ( $this->mTrxLevel
) {
241 $ignore = $this->ignoreErrors( true );
242 $this->rollback( __METHOD__
);
243 $this->ignoreErrors( $ignore );
245 parent
::reportQueryError( $error, $errno, $sql, $fname, false );
248 function queryIgnore( $sql, $fname = __METHOD__
) {
249 return $this->query( $sql, $fname, true );
253 * @param stdClass|ResultWrapper $res
254 * @throws DBUnexpectedError
256 function freeResult( $res ) {
257 if ( $res instanceof ResultWrapper
) {
260 MediaWiki\
suppressWarnings();
261 $ok = pg_free_result( $res );
262 MediaWiki\restoreWarnings
();
264 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
269 * @param ResultWrapper|stdClass $res
271 * @throws DBUnexpectedError
273 function fetchObject( $res ) {
274 if ( $res instanceof ResultWrapper
) {
277 MediaWiki\
suppressWarnings();
278 $row = pg_fetch_object( $res );
279 MediaWiki\restoreWarnings
();
280 # @todo FIXME: HACK HACK HACK HACK debug
282 # @todo hashar: not sure if the following test really trigger if the object
284 if ( pg_last_error( $this->mConn
) ) {
285 throw new DBUnexpectedError(
287 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
294 function fetchRow( $res ) {
295 if ( $res instanceof ResultWrapper
) {
298 MediaWiki\
suppressWarnings();
299 $row = pg_fetch_array( $res );
300 MediaWiki\restoreWarnings
();
301 if ( pg_last_error( $this->mConn
) ) {
302 throw new DBUnexpectedError(
304 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
311 function numRows( $res ) {
312 if ( $res instanceof ResultWrapper
) {
315 MediaWiki\
suppressWarnings();
316 $n = pg_num_rows( $res );
317 MediaWiki\restoreWarnings
();
318 if ( pg_last_error( $this->mConn
) ) {
319 throw new DBUnexpectedError(
321 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
328 function numFields( $res ) {
329 if ( $res instanceof ResultWrapper
) {
333 return pg_num_fields( $res );
336 function fieldName( $res, $n ) {
337 if ( $res instanceof ResultWrapper
) {
341 return pg_field_name( $res, $n );
345 * Return the result of the last call to nextSequenceValue();
346 * This must be called after nextSequenceValue().
350 function insertId() {
351 return $this->mInsertId
;
359 function dataSeek( $res, $row ) {
360 if ( $res instanceof ResultWrapper
) {
364 return pg_result_seek( $res, $row );
367 function lastError() {
368 if ( $this->mConn
) {
369 if ( $this->mLastResult
) {
370 return pg_result_error( $this->mLastResult
);
372 return pg_last_error();
375 return 'No database connection';
379 function lastErrno() {
380 if ( $this->mLastResult
) {
381 return pg_result_error_field( $this->mLastResult
, PGSQL_DIAG_SQLSTATE
);
387 function affectedRows() {
388 if ( !is_null( $this->mAffectedRows
) ) {
389 // Forced result for simulated queries
390 return $this->mAffectedRows
;
392 if ( empty( $this->mLastResult
) ) {
396 return pg_affected_rows( $this->mLastResult
);
400 * Estimate rows in dataset
401 * Returns estimated count, based on EXPLAIN output
402 * This is not necessarily an accurate estimate, so use sparingly
403 * Returns -1 if count cannot be found
404 * Takes same arguments as Database::select()
406 * @param string $table
407 * @param string $vars
408 * @param string $conds
409 * @param string $fname
410 * @param array $options
413 function estimateRowCount( $table, $vars = '*', $conds = '',
414 $fname = __METHOD__
, $options = []
416 $options['EXPLAIN'] = true;
417 $res = $this->select( $table, $vars, $conds, $fname, $options );
420 $row = $this->fetchRow( $res );
422 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
423 $rows = (int)$count[1];
431 * Returns information about an index
432 * If errors are explicitly ignored, returns NULL on failure
434 * @param string $table
435 * @param string $index
436 * @param string $fname
439 function indexInfo( $table, $index, $fname = __METHOD__
) {
440 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
441 $res = $this->query( $sql, $fname );
445 foreach ( $res as $row ) {
446 if ( $row->indexname
== $this->indexName( $index ) ) {
455 * Returns is of attributes used in index
458 * @param string $index
459 * @param bool|string $schema
462 function indexAttributes( $index, $schema = false ) {
463 if ( $schema === false ) {
464 $schema = $this->getCoreSchema();
467 * A subquery would be not needed if we didn't care about the order
468 * of attributes, but we do
470 $sql = <<<__INDEXATTR__
474 i.indoption[s.g] as option,
477 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
481 ON cis.oid=isub.indexrelid
483 ON cis.relnamespace = ns.oid
484 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
490 ON ci.oid=i.indexrelid
492 ON ct.oid = i.indrelid
494 ON ci.relnamespace = n.oid
496 ci.relname='$index' AND n.nspname='$schema'
497 AND attrelid = ct.oid
498 AND i.indkey[s.g] = attnum
499 AND i.indclass[s.g] = opcls.oid
500 AND pg_am.oid = opcls.opcmethod
502 $res = $this->query( $sql, __METHOD__ );
505 foreach ( $res as $row ) {
519 function indexUnique( $table, $index, $fname = __METHOD__ ) {
520 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
521 " AND indexdef LIKE 'CREATE UNIQUE%(" .
522 $this->strencode( $this->indexName( $index ) ) .
524 $res = $this->query( $sql, $fname );
529 return $res->numRows() > 0;
532 function selectSQLText(
533 $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
535 // Change the FOR UPDATE option as necessary based on the join conditions. Then pass
536 // to the parent function to get the actual SQL text.
537 // In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
538 // can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to
539 // do so causes a DB error. This wrapper checks which tables can be locked and adjusts it
541 // MySQL uses "ORDER BY NULL" as an optimization hint, but that is illegal in PostgreSQL.
542 if ( is_array( $options ) ) {
543 $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
544 if ( $forUpdateKey !== false && $join_conds ) {
545 unset( $options[$forUpdateKey] );
547 foreach ( $join_conds as $table_cond => $join_cond ) {
548 if ( 0 === preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_cond[0] ) ) {
549 $options['FOR UPDATE'][] = $table_cond;
554 if ( isset( $options['ORDER BY'] ) && $options['ORDER BY'] == 'NULL' ) {
555 unset( $options['ORDER BY'] );
559 return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
563 * INSERT wrapper, inserts an array into a table
565 * $args may be a single associative array, or an array of these with numeric keys,
566 * for multi-row insert (Postgres version 8.2 and above only).
568 * @param string $table Name of the table to insert to.
569 * @param array $args Items to insert into the table.
570 * @param string $fname Name of the function, for profiling
571 * @param array|string $options String or array. Valid options: IGNORE
572 * @return bool Success of insert operation. IGNORE always returns true.
574 function insert( $table, $args, $fname = __METHOD__, $options = [] ) {
575 if ( !count( $args ) ) {
579 $table = $this->tableName( $table );
580 if ( !isset( $this->numericVersion ) ) {
581 $this->getServerVersion();
584 if ( !is_array( $options ) ) {
585 $options = [ $options ];
588 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
590 $keys = array_keys( $args[0] );
593 $keys = array_keys( $args );
596 // If IGNORE is set, we use savepoints to emulate mysql's behavior
597 $savepoint = $olde = null;
598 $numrowsinserted = 0;
599 if ( in_array( 'IGNORE', $options ) ) {
600 $savepoint = new SavepointPostgres( $this, 'mw', $this->queryLogger );
601 $olde = error_reporting( 0 );
602 // For future use, we may want to track the number of actual inserts
603 // Right now, insert (all writes) simply return true/false
606 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
609 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
611 foreach ( $args as $row ) {
617 $sql .= '(' . $this->makeList( $row ) . ')';
619 $res = (bool)$this->query( $sql, $fname, $savepoint );
623 foreach ( $args as $row ) {
625 $tempsql .= '(' . $this->makeList( $row ) . ')';
628 $savepoint->savepoint();
631 $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
634 $bar = pg_result_error( $this->mLastResult );
635 if ( $bar != false ) {
636 $savepoint->rollback();
638 $savepoint->release();
643 // If any of them fail, we fail overall for this function call
644 // Note that this will be ignored if IGNORE is set
651 // Not multi, just a lone insert
653 $savepoint->savepoint();
656 $sql .= '(' . $this->makeList( $args ) . ')';
657 $res = (bool)$this->query( $sql, $fname, $savepoint );
659 $bar = pg_result_error( $this->mLastResult );
660 if ( $bar != false ) {
661 $savepoint->rollback();
663 $savepoint->release();
669 error_reporting( $olde );
670 $savepoint->commit();
672 // Set the affected row count for the whole operation
673 $this->mAffectedRows = $numrowsinserted;
675 // IGNORE always returns true
683 * INSERT SELECT wrapper
684 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
685 * Source items may be literals rather then field names, but strings should
686 * be quoted with Database::addQuotes()
687 * $conds may be "*" to copy the whole table
688 * srcTable may be an array of tables.
689 * @todo FIXME: Implement this a little better (seperate select/insert)?
691 * @param string $destTable
692 * @param array|string $srcTable
693 * @param array $varMap
694 * @param array $conds
695 * @param string $fname
696 * @param array $insertOptions
697 * @param array $selectOptions
700 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
701 $insertOptions = [], $selectOptions = [] ) {
702 $destTable = $this->tableName( $destTable );
704 if ( !is_array( $insertOptions ) ) {
705 $insertOptions = [ $insertOptions ];
709 * If IGNORE is set, we use savepoints to emulate mysql's behavior
710 * Ignore LOW PRIORITY option, since it is MySQL-specific
712 $savepoint = $olde = null;
713 $numrowsinserted = 0;
714 if ( in_array( 'IGNORE', $insertOptions ) ) {
715 $savepoint = new SavepointPostgres( $this, 'mw', $this->queryLogger );
716 $olde = error_reporting( 0 );
717 $savepoint->savepoint();
720 if ( !is_array( $selectOptions ) ) {
721 $selectOptions = [ $selectOptions ];
723 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) =
724 $this->makeSelectOptions( $selectOptions );
725 if ( is_array( $srcTable ) ) {
726 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
728 $srcTable = $this->tableName( $srcTable );
731 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
732 " SELECT $startOpts " . implode( ',', $varMap ) .
733 " FROM $srcTable $useIndex $ignoreIndex ";
735 if ( $conds != '*' ) {
736 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
739 $sql .= " $tailOpts";
741 $res = (bool)$this->query( $sql, $fname, $savepoint );
743 $bar = pg_result_error( $this->mLastResult );
744 if ( $bar != false ) {
745 $savepoint->rollback();
747 $savepoint->release();
750 error_reporting( $olde );
751 $savepoint->commit();
753 // Set the affected row count for the whole operation
754 $this->mAffectedRows = $numrowsinserted;
756 // IGNORE always returns true
763 function tableName( $name, $format = 'quoted' ) {
764 # Replace reserved words with better ones
767 return $this->realTableName( 'mwuser', $format );
769 return $this->realTableName( 'pagecontent', $format );
771 return $this->realTableName( $name, $format );
775 /* Don't cheat on installer */
776 function realTableName( $name, $format = 'quoted' ) {
777 return parent::tableName( $name, $format );
781 * Return the next in a sequence, save the value for retrieval via insertId()
783 * @param string $seqName
786 function nextSequenceValue( $seqName ) {
787 $safeseq = str_replace( "'", "''", $seqName );
788 $res = $this->query( "SELECT nextval('$safeseq')" );
789 $row = $this->fetchRow( $res );
790 $this->mInsertId = $row[0];
792 return $this->mInsertId;
796 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
798 * @param string $seqName
801 function currentSequenceValue( $seqName ) {
802 $safeseq = str_replace( "'", "''", $seqName );
803 $res = $this->query( "SELECT currval('$safeseq')" );
804 $row = $this->fetchRow( $res );
810 # Returns the size of a text field, or -1 for "unlimited"
811 function textFieldSize( $table, $field ) {
812 $table = $this->tableName( $table );
813 $sql = "SELECT t.typname as ftype,a.atttypmod as size
814 FROM pg_class c, pg_attribute a, pg_type t
815 WHERE relname='$table' AND a.attrelid=c.oid AND
816 a.atttypid=t.oid and a.attname='$field'";
817 $res = $this->query( $sql );
818 $row = $this->fetchObject( $res );
819 if ( $row->ftype == 'varchar' ) {
820 $size = $row->size - 4;
828 function limitResult( $sql, $limit, $offset = false ) {
829 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
832 function wasDeadlock() {
833 return $this->lastErrno() == '40P01';
836 function duplicateTableStructure(
837 $oldName, $newName, $temporary = false, $fname = __METHOD__
839 $newName = $this->addIdentifierQuotes( $newName );
840 $oldName = $this->addIdentifierQuotes( $oldName );
842 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName " .
843 "(LIKE $oldName INCLUDING DEFAULTS)", $fname );
846 function listTables( $prefix = null, $fname = __METHOD__ ) {
847 $eschema = $this->addQuotes( $this->getCoreSchema() );
848 $result = $this->query(
849 "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
852 foreach ( $result as $table ) {
853 $vars = get_object_vars( $table );
854 $table = array_pop( $vars );
855 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
856 $endArray[] = $table;
863 function timestamp( $ts = 0 ) {
864 $ct = new ConvertibleTimestamp( $ts );
866 return $ct->getTimestamp( TS_POSTGRES );
870 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
871 * to http://www.php.net/manual/en/ref.pgsql.php
873 * Parsing a postgres array can be a tricky problem, he's my
874 * take on this, it handles multi-dimensional arrays plus
875 * escaping using a nasty regexp to determine the limits of each
878 * This should really be handled by PHP PostgreSQL module
881 * @param string $text Postgreql array returned in a text form like {a,b}
882 * @param string $output
883 * @param int|bool $limit
887 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
888 if ( false === $limit ) {
889 $limit = strlen( $text ) - 1;
892 if ( '{}' == $text ) {
896 if ( '{' != $text[$offset] ) {
897 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
898 $text, $match, 0, $offset );
899 $offset += strlen( $match[0] );
900 $output[] = ( '"' != $match[1][0]
902 : stripcslashes( substr( $match[1], 1, -1 ) ) );
903 if ( '},' == $match[3] ) {
907 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
909 } while ( $limit > $offset );
915 * Return aggregated value function call
916 * @param array $valuedata
917 * @param string $valuename
920 public function aggregateValue( $valuedata, $valuename = 'value' ) {
925 * @return string Wikitext of a link to the server software's web site
927 public function getSoftwareLink() {
928 return '[{{int:version-db-postgres-url}} PostgreSQL]';
932 * Return current schema (executes SELECT current_schema())
936 * @return string Default schema for the current session
938 function getCurrentSchema() {
939 $res = $this->query( "SELECT current_schema()", __METHOD__ );
940 $row = $this->fetchRow( $res );
946 * Return list of schemas which are accessible without schema name
947 * This is list does not contain magic keywords like "$user"
950 * @see getSearchPath()
951 * @see setSearchPath()
953 * @return array List of actual schemas for the current sesson
955 function getSchemas() {
956 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
957 $row = $this->fetchRow( $res );
960 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
962 return $this->pg_array_parse( $row[0], $schemas );
966 * Return search patch for schemas
967 * This is different from getSchemas() since it contain magic keywords
972 * @return array How to search for table names schemas for the current user
974 function getSearchPath() {
975 $res = $this->query( "SHOW search_path", __METHOD__ );
976 $row = $this->fetchRow( $res );
978 /* PostgreSQL returns SHOW values as strings */
980 return explode( ",", $row[0] );
984 * Update search_path, values should already be sanitized
985 * Values may contain magic keywords like "$user"
988 * @param array $search_path List of schemas to be searched by default
990 function setSearchPath( $search_path ) {
991 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
995 * Determine default schema for the current application
996 * Adjust this session schema search path if desired schema exists
997 * and is not alread there.
999 * We need to have name of the core schema stored to be able
1000 * to query database metadata.
1002 * This will be also called by the installer after the schema is created
1006 * @param string $desiredSchema
1008 function determineCoreSchema( $desiredSchema ) {
1009 $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
1010 if ( $this->schemaExists( $desiredSchema ) ) {
1011 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
1012 $this->mCoreSchema = $desiredSchema;
1013 $this->queryLogger->debug(
1014 "Schema \"" . $desiredSchema . "\" already in the search path\n" );
1017 * Prepend our schema (e.g. 'mediawiki') in front
1018 * of the search path
1021 $search_path = $this->getSearchPath();
1022 array_unshift( $search_path,
1023 $this->addIdentifierQuotes( $desiredSchema ) );
1024 $this->setSearchPath( $search_path );
1025 $this->mCoreSchema = $desiredSchema;
1026 $this->queryLogger->debug(
1027 "Schema \"" . $desiredSchema . "\" added to the search path\n" );
1030 $this->mCoreSchema = $this->getCurrentSchema();
1031 $this->queryLogger->debug(
1032 "Schema \"" . $desiredSchema . "\" not found, using current \"" .
1033 $this->mCoreSchema . "\"\n" );
1035 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1036 $this->commit( __METHOD__ );
1040 * Return schema name for core application tables
1043 * @return string Core schema name
1045 function getCoreSchema() {
1046 return $this->mCoreSchema;
1050 * @return string Version information from the database
1052 function getServerVersion() {
1053 if ( !isset( $this->numericVersion ) ) {
1054 $versionInfo = pg_version( $this->mConn );
1055 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1056 // Old client, abort install
1057 $this->numericVersion = '7.3 or earlier';
1058 } elseif ( isset( $versionInfo['server'] ) ) {
1060 $this->numericVersion = $versionInfo['server'];
1062 // Bug 16937: broken pgsql extension from PHP<5.3
1063 $this->numericVersion = pg_parameter_status( $this->mConn, 'server_version' );
1067 return $this->numericVersion;
1071 * Query whether a given relation exists (in the given schema, or the
1072 * default mw one if not given)
1073 * @param string $table
1074 * @param array|string $types
1075 * @param bool|string $schema
1078 function relationExists( $table, $types, $schema = false ) {
1079 if ( !is_array( $types ) ) {
1080 $types = [ $types ];
1083 $schema = $this->getCoreSchema();
1085 $table = $this->realTableName( $table, 'raw' );
1086 $etable = $this->addQuotes( $table );
1087 $eschema = $this->addQuotes( $schema );
1088 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1089 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1090 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1091 $res = $this->query( $sql );
1092 $count = $res ? $res->numRows() : 0;
1094 return (bool)$count;
1098 * For backward compatibility, this function checks both tables and
1100 * @param string $table
1101 * @param string $fname
1102 * @param bool|string $schema
1105 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1106 return $this->relationExists( $table, [ 'r', 'v' ], $schema );
1109 function sequenceExists( $sequence, $schema = false ) {
1110 return $this->relationExists( $sequence, 'S', $schema );
1113 function triggerExists( $table, $trigger ) {
1115 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1116 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1117 AND tgrelid=pg_class.oid
1118 AND nspname=%s AND relname=%s AND tgname=%s
1120 $res = $this->query(
1123 $this->addQuotes( $this->getCoreSchema() ),
1124 $this->addQuotes( $table ),
1125 $this->addQuotes( $trigger )
1131 $rows = $res->numRows();
1136 function ruleExists( $table, $rule ) {
1137 $exists = $this->selectField( 'pg_rules', 'rulename',
1139 'rulename' => $rule,
1140 'tablename' => $table,
1141 'schemaname' => $this->getCoreSchema()
1145 return $exists === $rule;
1148 function constraintExists( $table, $constraint ) {
1149 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1150 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1151 $this->addQuotes( $this->getCoreSchema() ),
1152 $this->addQuotes( $table ),
1153 $this->addQuotes( $constraint )
1155 $res = $this->query( $sql );
1159 $rows = $res->numRows();
1165 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1166 * @param string $schema
1169 function schemaExists( $schema ) {
1170 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1171 [ 'nspname' => $schema ], __METHOD__ );
1173 return (bool)$exists;
1177 * Returns true if a given role (i.e. user) exists, false otherwise.
1178 * @param string $roleName
1181 function roleExists( $roleName ) {
1182 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1183 [ 'rolname' => $roleName ], __METHOD__ );
1185 return (bool)$exists;
1189 * @var string $table
1190 * @var string $field
1191 * @return PostgresField|null
1193 function fieldInfo( $table, $field ) {
1194 return PostgresField::fromText( $this, $table, $field );
1198 * pg_field_type() wrapper
1199 * @param ResultWrapper|resource $res ResultWrapper or PostgreSQL query result resource
1200 * @param int $index Field number, starting from 0
1203 function fieldType( $res, $index ) {
1204 if ( $res instanceof ResultWrapper ) {
1205 $res = $res->result;
1208 return pg_field_type( $res, $index );
1215 function encodeBlob( $b ) {
1216 return new PostgresBlob( pg_escape_bytea( $b ) );
1219 function decodeBlob( $b ) {
1220 if ( $b instanceof PostgresBlob ) {
1222 } elseif ( $b instanceof Blob ) {
1226 return pg_unescape_bytea( $b );
1229 function strencode( $s ) {
1230 // Should not be called by us
1232 return pg_escape_string( $this->mConn, $s );
1236 * @param string|int|null|bool|Blob $s
1237 * @return string|int
1239 function addQuotes( $s ) {
1240 if ( is_null( $s ) ) {
1242 } elseif ( is_bool( $s ) ) {
1243 return intval( $s );
1244 } elseif ( $s instanceof Blob ) {
1245 if ( $s instanceof PostgresBlob ) {
1248 $s = pg_escape_bytea( $this->mConn, $s->fetch() );
1253 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1257 * Postgres specific version of replaceVars.
1258 * Calls the parent version in Database.php
1260 * @param string $ins SQL string, read from a stream (usually tables.sql)
1261 * @return string SQL string
1263 protected function replaceVars( $ins ) {
1264 $ins = parent::replaceVars( $ins );
1266 if ( $this->numericVersion >= 8.3 ) {
1267 // Thanks for not providing backwards-compatibility, 8.3
1268 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1271 if ( $this->numericVersion <= 8.1 ) { // Our minimum version
1272 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1279 * Various select options
1281 * @param array $options An associative array of options to be turned into
1282 * an SQL query, valid keys are listed in the function.
1285 function makeSelectOptions( $options ) {
1286 $preLimitTail = $postLimitTail = '';
1287 $startOpts = $useIndex = $ignoreIndex = '';
1290 foreach ( $options as $key => $option ) {
1291 if ( is_numeric( $key ) ) {
1292 $noKeyOptions[$option] = true;
1296 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1298 $preLimitTail .= $this->makeOrderBy( $options );
1300 // if ( isset( $options['LIMIT'] ) ) {
1301 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1302 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1306 if ( isset( $options['FOR UPDATE'] ) ) {
1307 $postLimitTail .= ' FOR UPDATE OF ' .
1308 implode( ', ', array_map( [ &$this, 'tableName' ], $options['FOR UPDATE'] ) );
1309 } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1310 $postLimitTail .= ' FOR UPDATE';
1313 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1314 $startOpts .= 'DISTINCT';
1317 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1320 function getDBname() {
1321 return $this->mDBname;
1324 function getServer() {
1325 return $this->mServer;
1328 function buildConcat( $stringList ) {
1329 return implode( ' || ', $stringList );
1332 public function buildGroupConcatField(
1333 $delimiter, $table, $field, $conds = '', $options = [], $join_conds = []
1335 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1337 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1341 * @param string $field Field or column to cast
1345 public function buildStringCast( $field ) {
1346 return $field . '::text';
1349 public function streamStatementEnd( &$sql, &$newLine ) {
1350 # Allow dollar quoting for function declarations
1351 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1352 if ( $this->delimiter ) {
1353 $this->delimiter = false;
1355 $this->delimiter = ';';
1359 return parent::streamStatementEnd( $sql, $newLine );
1363 * Check to see if a named lock is available. This is non-blocking.
1364 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1366 * @param string $lockName Name of lock to poll
1367 * @param string $method Name of method calling us
1371 public function lockIsFree( $lockName, $method ) {
1372 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1373 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1374 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1375 $row = $this->fetchObject( $result );
1377 return ( $row->lockstatus === 't' );
1381 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1382 * @param string $lockName
1383 * @param string $method
1384 * @param int $timeout
1387 public function lock( $lockName, $method, $timeout = 5 ) {
1388 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1389 $loop = new WaitConditionLoop(
1390 function () use ( $lockName, $key, $timeout, $method ) {
1391 $res = $this->query( "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1392 $row = $this->fetchObject( $res );
1393 if ( $row->lockstatus === 't' ) {
1394 parent::lock( $lockName, $method, $timeout ); // record
1398 return WaitConditionLoop::CONDITION_CONTINUE;
1403 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1407 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKSFROM
1408 * PG DOCS: http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1409 * @param string $lockName
1410 * @param string $method
1413 public function unlock( $lockName, $method ) {
1414 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1415 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1416 $row = $this->fetchObject( $result );
1418 if ( $row->lockstatus === 't' ) {
1419 parent::unlock( $lockName, $method ); // record
1423 $this->queryLogger->debug( __METHOD__ . " failed to release lock\n" );
1429 * @param string $lockName
1430 * @return string Integer
1432 private function bigintFromLockName( $lockName ) {
1433 return Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );