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 $conn = $this->getBindingHandle();
66 $sql = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
67 "WHERE c.connamespace = n.oid AND conname = '" .
68 pg_escape_string( $conn, $name ) . "' AND n.nspname = '" .
69 pg_escape_string( $conn, $this->getCoreSchema() ) . "'";
70 $res = $this->doQuery( $sql );
72 return $this->numRows( $res );
76 * Usually aborts on failure
77 * @param string $server
79 * @param string $password
80 * @param string $dbName
81 * @throws DBConnectionError|Exception
82 * @return resource|bool|null
84 function open( $server, $user, $password, $dbName ) {
85 # Test for Postgres support, to avoid suppressed fatal error
86 if ( !function_exists( 'pg_connect' ) ) {
87 throw new DBConnectionError(
89 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
90 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
91 "webserver and database)\n"
95 $this->mServer
= $server;
97 $this->mPassword
= $password;
98 $this->mDBname
= $dbName;
103 'password' => $password
105 if ( $server != false && $server != '' ) {
106 $connectVars['host'] = $server;
108 if ( (int)$this->port
> 0 ) {
109 $connectVars['port'] = (int)$this->port
;
111 if ( $this->mFlags
& self
::DBO_SSL
) {
112 $connectVars['sslmode'] = 1;
115 $this->connectString
= $this->makeConnectionString( $connectVars );
117 $this->installErrorHandler();
120 // Use new connections to let LoadBalancer/LBFactory handle reuse
121 $this->mConn
= pg_connect( $this->connectString
, PGSQL_CONNECT_FORCE_NEW
);
122 } catch ( Exception
$ex ) {
123 $this->restoreErrorHandler();
127 $phpError = $this->restoreErrorHandler();
129 if ( !$this->mConn
) {
130 $this->queryLogger
->debug(
131 "DB connection error\n" .
132 "Server: $server, Database: $dbName, User: $user, Password: " .
133 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 $this->mConn ?
pg_close( $this->mConn
) : true;
191 public function doQuery( $sql ) {
192 $conn = $this->getBindingHandle();
194 $sql = mb_convert_encoding( $sql, 'UTF-8' );
195 // Clear previously left over PQresult
196 while ( $res = pg_get_result( $conn ) ) {
197 pg_free_result( $res );
199 if ( pg_send_query( $conn, $sql ) === false ) {
200 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
202 $this->mLastResult
= pg_get_result( $conn );
203 $this->mAffectedRows
= null;
204 if ( pg_result_error( $this->mLastResult
) ) {
208 return $this->mLastResult
;
211 protected function dumpError() {
215 PGSQL_DIAG_MESSAGE_PRIMARY
,
216 PGSQL_DIAG_MESSAGE_DETAIL
,
217 PGSQL_DIAG_MESSAGE_HINT
,
218 PGSQL_DIAG_STATEMENT_POSITION
,
219 PGSQL_DIAG_INTERNAL_POSITION
,
220 PGSQL_DIAG_INTERNAL_QUERY
,
222 PGSQL_DIAG_SOURCE_FILE
,
223 PGSQL_DIAG_SOURCE_LINE
,
224 PGSQL_DIAG_SOURCE_FUNCTION
226 foreach ( $diags as $d ) {
227 $this->queryLogger
->debug( sprintf( "PgSQL ERROR(%d): %s\n",
228 $d, pg_result_error_field( $this->mLastResult
, $d ) ) );
232 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
234 /* Check for constraint violation */
235 if ( $errno === '23505' ) {
236 parent
::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
241 /* Transaction stays in the ERROR state until rolled back */
242 if ( $this->mTrxLevel
) {
243 $ignore = $this->ignoreErrors( true );
244 $this->rollback( __METHOD__
);
245 $this->ignoreErrors( $ignore );
247 parent
::reportQueryError( $error, $errno, $sql, $fname, false );
250 function queryIgnore( $sql, $fname = __METHOD__
) {
251 return $this->query( $sql, $fname, true );
255 * @param stdClass|ResultWrapper $res
256 * @throws DBUnexpectedError
258 function freeResult( $res ) {
259 if ( $res instanceof ResultWrapper
) {
262 MediaWiki\
suppressWarnings();
263 $ok = pg_free_result( $res );
264 MediaWiki\restoreWarnings
();
266 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
271 * @param ResultWrapper|stdClass $res
273 * @throws DBUnexpectedError
275 function fetchObject( $res ) {
276 if ( $res instanceof ResultWrapper
) {
279 MediaWiki\
suppressWarnings();
280 $row = pg_fetch_object( $res );
281 MediaWiki\restoreWarnings
();
282 # @todo FIXME: HACK HACK HACK HACK debug
284 # @todo hashar: not sure if the following test really trigger if the object
286 $conn = $this->getBindingHandle();
287 if ( pg_last_error( $conn ) ) {
288 throw new DBUnexpectedError(
290 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
297 function fetchRow( $res ) {
298 if ( $res instanceof ResultWrapper
) {
301 MediaWiki\
suppressWarnings();
302 $row = pg_fetch_array( $res );
303 MediaWiki\restoreWarnings
();
305 $conn = $this->getBindingHandle();
306 if ( pg_last_error( $conn ) ) {
307 throw new DBUnexpectedError(
309 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
316 function numRows( $res ) {
317 if ( $res instanceof ResultWrapper
) {
320 MediaWiki\
suppressWarnings();
321 $n = pg_num_rows( $res );
322 MediaWiki\restoreWarnings
();
324 $conn = $this->getBindingHandle();
325 if ( pg_last_error( $conn ) ) {
326 throw new DBUnexpectedError(
328 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
335 function numFields( $res ) {
336 if ( $res instanceof ResultWrapper
) {
340 return pg_num_fields( $res );
343 function fieldName( $res, $n ) {
344 if ( $res instanceof ResultWrapper
) {
348 return pg_field_name( $res, $n );
352 * Return the result of the last call to nextSequenceValue();
353 * This must be called after nextSequenceValue().
357 function insertId() {
358 return $this->mInsertId
;
366 function dataSeek( $res, $row ) {
367 if ( $res instanceof ResultWrapper
) {
371 return pg_result_seek( $res, $row );
374 function lastError() {
375 if ( $this->mConn
) {
376 if ( $this->mLastResult
) {
377 return pg_result_error( $this->mLastResult
);
379 return pg_last_error();
383 return $this->getLastPHPError() ?
: 'No database connection';
386 function lastErrno() {
387 if ( $this->mLastResult
) {
388 return pg_result_error_field( $this->mLastResult
, PGSQL_DIAG_SQLSTATE
);
394 function affectedRows() {
395 if ( !is_null( $this->mAffectedRows
) ) {
396 // Forced result for simulated queries
397 return $this->mAffectedRows
;
399 if ( empty( $this->mLastResult
) ) {
403 return pg_affected_rows( $this->mLastResult
);
407 * Estimate rows in dataset
408 * Returns estimated count, based on EXPLAIN output
409 * This is not necessarily an accurate estimate, so use sparingly
410 * Returns -1 if count cannot be found
411 * Takes same arguments as Database::select()
413 * @param string $table
414 * @param string $vars
415 * @param string $conds
416 * @param string $fname
417 * @param array $options
420 function estimateRowCount( $table, $vars = '*', $conds = '',
421 $fname = __METHOD__
, $options = []
423 $options['EXPLAIN'] = true;
424 $res = $this->select( $table, $vars, $conds, $fname, $options );
427 $row = $this->fetchRow( $res );
429 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
430 $rows = (int)$count[1];
438 * Returns information about an index
439 * If errors are explicitly ignored, returns NULL on failure
441 * @param string $table
442 * @param string $index
443 * @param string $fname
446 function indexInfo( $table, $index, $fname = __METHOD__
) {
447 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
448 $res = $this->query( $sql, $fname );
452 foreach ( $res as $row ) {
453 if ( $row->indexname
== $this->indexName( $index ) ) {
462 * Returns is of attributes used in index
465 * @param string $index
466 * @param bool|string $schema
469 function indexAttributes( $index, $schema = false ) {
470 if ( $schema === false ) {
471 $schema = $this->getCoreSchema();
474 * A subquery would be not needed if we didn't care about the order
475 * of attributes, but we do
477 $sql = <<<__INDEXATTR__
481 i.indoption[s.g] as option,
484 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
488 ON cis.oid=isub.indexrelid
490 ON cis.relnamespace = ns.oid
491 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
497 ON ci.oid=i.indexrelid
499 ON ct.oid = i.indrelid
501 ON ci.relnamespace = n.oid
503 ci.relname='$index' AND n.nspname='$schema'
504 AND attrelid = ct.oid
505 AND i.indkey[s.g] = attnum
506 AND i.indclass[s.g] = opcls.oid
507 AND pg_am.oid = opcls.opcmethod
509 $res = $this->query( $sql, __METHOD__ );
512 foreach ( $res as $row ) {
526 function indexUnique( $table, $index, $fname = __METHOD__ ) {
527 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
528 " AND indexdef LIKE 'CREATE UNIQUE%(" .
529 $this->strencode( $this->indexName( $index ) ) .
531 $res = $this->query( $sql, $fname );
536 return $res->numRows() > 0;
539 function selectSQLText(
540 $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
542 // Change the FOR UPDATE option as necessary based on the join conditions. Then pass
543 // to the parent function to get the actual SQL text.
544 // In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
545 // can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to
546 // do so causes a DB error. This wrapper checks which tables can be locked and adjusts it
548 // MySQL uses "ORDER BY NULL" as an optimization hint, but that is illegal in PostgreSQL.
549 if ( is_array( $options ) ) {
550 $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
551 if ( $forUpdateKey !== false && $join_conds ) {
552 unset( $options[$forUpdateKey] );
554 foreach ( $join_conds as $table_cond => $join_cond ) {
555 if ( 0 === preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_cond[0] ) ) {
556 $options['FOR UPDATE'][] = $table_cond;
561 if ( isset( $options['ORDER BY'] ) && $options['ORDER BY'] == 'NULL' ) {
562 unset( $options['ORDER BY'] );
566 return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
570 * INSERT wrapper, inserts an array into a table
572 * $args may be a single associative array, or an array of these with numeric keys,
573 * for multi-row insert (Postgres version 8.2 and above only).
575 * @param string $table Name of the table to insert to.
576 * @param array $args Items to insert into the table.
577 * @param string $fname Name of the function, for profiling
578 * @param array|string $options String or array. Valid options: IGNORE
579 * @return bool Success of insert operation. IGNORE always returns true.
581 function insert( $table, $args, $fname = __METHOD__, $options = [] ) {
582 if ( !count( $args ) ) {
586 $table = $this->tableName( $table );
587 if ( !isset( $this->numericVersion ) ) {
588 $this->getServerVersion();
591 if ( !is_array( $options ) ) {
592 $options = [ $options ];
595 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
597 $keys = array_keys( $args[0] );
600 $keys = array_keys( $args );
603 // If IGNORE is set, we use savepoints to emulate mysql's behavior
604 $savepoint = $olde = null;
605 $numrowsinserted = 0;
606 if ( in_array( 'IGNORE', $options ) ) {
607 $savepoint = new SavepointPostgres( $this, 'mw', $this->queryLogger );
608 $olde = error_reporting( 0 );
609 // For future use, we may want to track the number of actual inserts
610 // Right now, insert (all writes) simply return true/false
613 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
616 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
618 foreach ( $args as $row ) {
624 $sql .= '(' . $this->makeList( $row ) . ')';
626 $res = (bool)$this->query( $sql, $fname, $savepoint );
630 foreach ( $args as $row ) {
632 $tempsql .= '(' . $this->makeList( $row ) . ')';
635 $savepoint->savepoint();
638 $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
641 $bar = pg_result_error( $this->mLastResult );
642 if ( $bar != false ) {
643 $savepoint->rollback();
645 $savepoint->release();
650 // If any of them fail, we fail overall for this function call
651 // Note that this will be ignored if IGNORE is set
658 // Not multi, just a lone insert
660 $savepoint->savepoint();
663 $sql .= '(' . $this->makeList( $args ) . ')';
664 $res = (bool)$this->query( $sql, $fname, $savepoint );
666 $bar = pg_result_error( $this->mLastResult );
667 if ( $bar != false ) {
668 $savepoint->rollback();
670 $savepoint->release();
676 error_reporting( $olde );
677 $savepoint->commit();
679 // Set the affected row count for the whole operation
680 $this->mAffectedRows = $numrowsinserted;
682 // IGNORE always returns true
690 * INSERT SELECT wrapper
691 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
692 * Source items may be literals rather then field names, but strings should
693 * be quoted with Database::addQuotes()
694 * $conds may be "*" to copy the whole table
695 * srcTable may be an array of tables.
696 * @todo FIXME: Implement this a little better (seperate select/insert)?
698 * @param string $destTable
699 * @param array|string $srcTable
700 * @param array $varMap
701 * @param array $conds
702 * @param string $fname
703 * @param array $insertOptions
704 * @param array $selectOptions
707 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
708 $insertOptions = [], $selectOptions = [] ) {
709 $destTable = $this->tableName( $destTable );
711 if ( !is_array( $insertOptions ) ) {
712 $insertOptions = [ $insertOptions ];
716 * If IGNORE is set, we use savepoints to emulate mysql's behavior
717 * Ignore LOW PRIORITY option, since it is MySQL-specific
719 $savepoint = $olde = null;
720 $numrowsinserted = 0;
721 if ( in_array( 'IGNORE', $insertOptions ) ) {
722 $savepoint = new SavepointPostgres( $this, 'mw', $this->queryLogger );
723 $olde = error_reporting( 0 );
724 $savepoint->savepoint();
727 if ( !is_array( $selectOptions ) ) {
728 $selectOptions = [ $selectOptions ];
730 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) =
731 $this->makeSelectOptions( $selectOptions );
732 if ( is_array( $srcTable ) ) {
733 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
735 $srcTable = $this->tableName( $srcTable );
738 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
739 " SELECT $startOpts " . implode( ',', $varMap ) .
740 " FROM $srcTable $useIndex $ignoreIndex ";
742 if ( $conds != '*' ) {
743 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
746 $sql .= " $tailOpts";
748 $res = (bool)$this->query( $sql, $fname, $savepoint );
750 $bar = pg_result_error( $this->mLastResult );
751 if ( $bar != false ) {
752 $savepoint->rollback();
754 $savepoint->release();
757 error_reporting( $olde );
758 $savepoint->commit();
760 // Set the affected row count for the whole operation
761 $this->mAffectedRows = $numrowsinserted;
763 // IGNORE always returns true
770 function tableName( $name, $format = 'quoted' ) {
771 # Replace reserved words with better ones
774 return $this->realTableName( 'mwuser', $format );
776 return $this->realTableName( 'pagecontent', $format );
778 return $this->realTableName( $name, $format );
782 /* Don't cheat on installer */
783 function realTableName( $name, $format = 'quoted' ) {
784 return parent::tableName( $name, $format );
788 * Return the next in a sequence, save the value for retrieval via insertId()
790 * @param string $seqName
793 function nextSequenceValue( $seqName ) {
794 $safeseq = str_replace( "'", "''", $seqName );
795 $res = $this->query( "SELECT nextval('$safeseq')" );
796 $row = $this->fetchRow( $res );
797 $this->mInsertId = $row[0];
799 return $this->mInsertId;
803 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
805 * @param string $seqName
808 function currentSequenceValue( $seqName ) {
809 $safeseq = str_replace( "'", "''", $seqName );
810 $res = $this->query( "SELECT currval('$safeseq')" );
811 $row = $this->fetchRow( $res );
817 # Returns the size of a text field, or -1 for "unlimited"
818 function textFieldSize( $table, $field ) {
819 $table = $this->tableName( $table );
820 $sql = "SELECT t.typname as ftype,a.atttypmod as size
821 FROM pg_class c, pg_attribute a, pg_type t
822 WHERE relname='$table' AND a.attrelid=c.oid AND
823 a.atttypid=t.oid and a.attname='$field'";
824 $res = $this->query( $sql );
825 $row = $this->fetchObject( $res );
826 if ( $row->ftype == 'varchar' ) {
827 $size = $row->size - 4;
835 function limitResult( $sql, $limit, $offset = false ) {
836 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
839 function wasDeadlock() {
840 return $this->lastErrno() == '40P01';
843 function duplicateTableStructure(
844 $oldName, $newName, $temporary = false, $fname = __METHOD__
846 $newName = $this->addIdentifierQuotes( $newName );
847 $oldName = $this->addIdentifierQuotes( $oldName );
849 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName " .
850 "(LIKE $oldName INCLUDING DEFAULTS)", $fname );
853 function listTables( $prefix = null, $fname = __METHOD__ ) {
854 $eschema = $this->addQuotes( $this->getCoreSchema() );
855 $result = $this->query(
856 "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
859 foreach ( $result as $table ) {
860 $vars = get_object_vars( $table );
861 $table = array_pop( $vars );
862 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
863 $endArray[] = $table;
870 function timestamp( $ts = 0 ) {
871 $ct = new ConvertibleTimestamp( $ts );
873 return $ct->getTimestamp( TS_POSTGRES );
877 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
878 * to http://www.php.net/manual/en/ref.pgsql.php
880 * Parsing a postgres array can be a tricky problem, he's my
881 * take on this, it handles multi-dimensional arrays plus
882 * escaping using a nasty regexp to determine the limits of each
885 * This should really be handled by PHP PostgreSQL module
888 * @param string $text Postgreql array returned in a text form like {a,b}
889 * @param string $output
890 * @param int|bool $limit
894 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
895 if ( false === $limit ) {
896 $limit = strlen( $text ) - 1;
899 if ( '{}' == $text ) {
903 if ( '{' != $text[$offset] ) {
904 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
905 $text, $match, 0, $offset );
906 $offset += strlen( $match[0] );
907 $output[] = ( '"' != $match[1][0]
909 : stripcslashes( substr( $match[1], 1, -1 ) ) );
910 if ( '},' == $match[3] ) {
914 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
916 } while ( $limit > $offset );
922 * Return aggregated value function call
923 * @param array $valuedata
924 * @param string $valuename
927 public function aggregateValue( $valuedata, $valuename = 'value' ) {
932 * @return string Wikitext of a link to the server software's web site
934 public function getSoftwareLink() {
935 return '[{{int:version-db-postgres-url}} PostgreSQL]';
939 * Return current schema (executes SELECT current_schema())
943 * @return string Default schema for the current session
945 function getCurrentSchema() {
946 $res = $this->query( "SELECT current_schema()", __METHOD__ );
947 $row = $this->fetchRow( $res );
953 * Return list of schemas which are accessible without schema name
954 * This is list does not contain magic keywords like "$user"
957 * @see getSearchPath()
958 * @see setSearchPath()
960 * @return array List of actual schemas for the current sesson
962 function getSchemas() {
963 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
964 $row = $this->fetchRow( $res );
967 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
969 return $this->pg_array_parse( $row[0], $schemas );
973 * Return search patch for schemas
974 * This is different from getSchemas() since it contain magic keywords
979 * @return array How to search for table names schemas for the current user
981 function getSearchPath() {
982 $res = $this->query( "SHOW search_path", __METHOD__ );
983 $row = $this->fetchRow( $res );
985 /* PostgreSQL returns SHOW values as strings */
987 return explode( ",", $row[0] );
991 * Update search_path, values should already be sanitized
992 * Values may contain magic keywords like "$user"
995 * @param array $search_path List of schemas to be searched by default
997 function setSearchPath( $search_path ) {
998 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
1002 * Determine default schema for the current application
1003 * Adjust this session schema search path if desired schema exists
1004 * and is not alread there.
1006 * We need to have name of the core schema stored to be able
1007 * to query database metadata.
1009 * This will be also called by the installer after the schema is created
1013 * @param string $desiredSchema
1015 function determineCoreSchema( $desiredSchema ) {
1016 $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
1017 if ( $this->schemaExists( $desiredSchema ) ) {
1018 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
1019 $this->mCoreSchema = $desiredSchema;
1020 $this->queryLogger->debug(
1021 "Schema \"" . $desiredSchema . "\" already in the search path\n" );
1024 * Prepend our schema (e.g. 'mediawiki') in front
1025 * of the search path
1028 $search_path = $this->getSearchPath();
1029 array_unshift( $search_path,
1030 $this->addIdentifierQuotes( $desiredSchema ) );
1031 $this->setSearchPath( $search_path );
1032 $this->mCoreSchema = $desiredSchema;
1033 $this->queryLogger->debug(
1034 "Schema \"" . $desiredSchema . "\" added to the search path\n" );
1037 $this->mCoreSchema = $this->getCurrentSchema();
1038 $this->queryLogger->debug(
1039 "Schema \"" . $desiredSchema . "\" not found, using current \"" .
1040 $this->mCoreSchema . "\"\n" );
1042 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1043 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
1047 * Return schema name for core application tables
1050 * @return string Core schema name
1052 function getCoreSchema() {
1053 return $this->mCoreSchema;
1057 * @return string Version information from the database
1059 function getServerVersion() {
1060 if ( !isset( $this->numericVersion ) ) {
1061 $conn = $this->getBindingHandle();
1062 $versionInfo = pg_version( $conn );
1063 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1064 // Old client, abort install
1065 $this->numericVersion = '7.3 or earlier';
1066 } elseif ( isset( $versionInfo['server'] ) ) {
1068 $this->numericVersion = $versionInfo['server'];
1070 // Bug 16937: broken pgsql extension from PHP<5.3
1071 $this->numericVersion = pg_parameter_status( $conn, 'server_version' );
1075 return $this->numericVersion;
1079 * Query whether a given relation exists (in the given schema, or the
1080 * default mw one if not given)
1081 * @param string $table
1082 * @param array|string $types
1083 * @param bool|string $schema
1086 function relationExists( $table, $types, $schema = false ) {
1087 if ( !is_array( $types ) ) {
1088 $types = [ $types ];
1090 if ( $schema === false ) {
1091 $schema = $this->getCoreSchema();
1093 $table = $this->realTableName( $table, 'raw' );
1094 $etable = $this->addQuotes( $table );
1095 $eschema = $this->addQuotes( $schema );
1096 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1097 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1098 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1099 $res = $this->query( $sql );
1100 $count = $res ? $res->numRows() : 0;
1102 return (bool)$count;
1106 * For backward compatibility, this function checks both tables and
1108 * @param string $table
1109 * @param string $fname
1110 * @param bool|string $schema
1113 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1114 return $this->relationExists( $table, [ 'r', 'v' ], $schema );
1117 function sequenceExists( $sequence, $schema = false ) {
1118 return $this->relationExists( $sequence, 'S', $schema );
1121 function triggerExists( $table, $trigger ) {
1123 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1124 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1125 AND tgrelid=pg_class.oid
1126 AND nspname=%s AND relname=%s AND tgname=%s
1128 $res = $this->query(
1131 $this->addQuotes( $this->getCoreSchema() ),
1132 $this->addQuotes( $table ),
1133 $this->addQuotes( $trigger )
1139 $rows = $res->numRows();
1144 function ruleExists( $table, $rule ) {
1145 $exists = $this->selectField( 'pg_rules', 'rulename',
1147 'rulename' => $rule,
1148 'tablename' => $table,
1149 'schemaname' => $this->getCoreSchema()
1153 return $exists === $rule;
1156 function constraintExists( $table, $constraint ) {
1157 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1158 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1159 $this->addQuotes( $this->getCoreSchema() ),
1160 $this->addQuotes( $table ),
1161 $this->addQuotes( $constraint )
1163 $res = $this->query( $sql );
1167 $rows = $res->numRows();
1173 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1174 * @param string $schema
1177 function schemaExists( $schema ) {
1178 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1179 [ 'nspname' => $schema ], __METHOD__ );
1181 return (bool)$exists;
1185 * Returns true if a given role (i.e. user) exists, false otherwise.
1186 * @param string $roleName
1189 function roleExists( $roleName ) {
1190 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1191 [ 'rolname' => $roleName ], __METHOD__ );
1193 return (bool)$exists;
1197 * @var string $table
1198 * @var string $field
1199 * @return PostgresField|null
1201 function fieldInfo( $table, $field ) {
1202 return PostgresField::fromText( $this, $table, $field );
1206 * pg_field_type() wrapper
1207 * @param ResultWrapper|resource $res ResultWrapper or PostgreSQL query result resource
1208 * @param int $index Field number, starting from 0
1211 function fieldType( $res, $index ) {
1212 if ( $res instanceof ResultWrapper ) {
1213 $res = $res->result;
1216 return pg_field_type( $res, $index );
1223 function encodeBlob( $b ) {
1224 return new PostgresBlob( pg_escape_bytea( $b ) );
1227 function decodeBlob( $b ) {
1228 if ( $b instanceof PostgresBlob ) {
1230 } elseif ( $b instanceof Blob ) {
1234 return pg_unescape_bytea( $b );
1237 function strencode( $s ) {
1238 // Should not be called by us
1239 return pg_escape_string( $this->getBindingHandle(), $s );
1243 * @param string|int|null|bool|Blob $s
1244 * @return string|int
1246 function addQuotes( $s ) {
1247 $conn = $this->getBindingHandle();
1249 if ( is_null( $s ) ) {
1251 } elseif ( is_bool( $s ) ) {
1252 return intval( $s );
1253 } elseif ( $s instanceof Blob ) {
1254 if ( $s instanceof PostgresBlob ) {
1257 $s = pg_escape_bytea( $conn, $s->fetch() );
1262 return "'" . pg_escape_string( $conn, $s ) . "'";
1266 * Postgres specific version of replaceVars.
1267 * Calls the parent version in Database.php
1269 * @param string $ins SQL string, read from a stream (usually tables.sql)
1270 * @return string SQL string
1272 protected function replaceVars( $ins ) {
1273 $ins = parent::replaceVars( $ins );
1275 if ( $this->numericVersion >= 8.3 ) {
1276 // Thanks for not providing backwards-compatibility, 8.3
1277 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1280 if ( $this->numericVersion <= 8.1 ) { // Our minimum version
1281 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1288 * Various select options
1290 * @param array $options An associative array of options to be turned into
1291 * an SQL query, valid keys are listed in the function.
1294 function makeSelectOptions( $options ) {
1295 $preLimitTail = $postLimitTail = '';
1296 $startOpts = $useIndex = $ignoreIndex = '';
1299 foreach ( $options as $key => $option ) {
1300 if ( is_numeric( $key ) ) {
1301 $noKeyOptions[$option] = true;
1305 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1307 $preLimitTail .= $this->makeOrderBy( $options );
1309 // if ( isset( $options['LIMIT'] ) ) {
1310 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1311 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1315 if ( isset( $options['FOR UPDATE'] ) ) {
1316 $postLimitTail .= ' FOR UPDATE OF ' .
1317 implode( ', ', array_map( [ &$this, 'tableName' ], $options['FOR UPDATE'] ) );
1318 } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1319 $postLimitTail .= ' FOR UPDATE';
1322 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1323 $startOpts .= 'DISTINCT';
1326 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1329 function getDBname() {
1330 return $this->mDBname;
1333 function getServer() {
1334 return $this->mServer;
1337 function buildConcat( $stringList ) {
1338 return implode( ' || ', $stringList );
1341 public function buildGroupConcatField(
1342 $delimiter, $table, $field, $conds = '', $options = [], $join_conds = []
1344 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1346 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1350 * @param string $field Field or column to cast
1354 public function buildStringCast( $field ) {
1355 return $field . '::text';
1358 public function streamStatementEnd( &$sql, &$newLine ) {
1359 # Allow dollar quoting for function declarations
1360 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1361 if ( $this->delimiter ) {
1362 $this->delimiter = false;
1364 $this->delimiter = ';';
1368 return parent::streamStatementEnd( $sql, $newLine );
1372 * Check to see if a named lock is available. This is non-blocking.
1373 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1375 * @param string $lockName Name of lock to poll
1376 * @param string $method Name of method calling us
1380 public function lockIsFree( $lockName, $method ) {
1381 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1382 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1383 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1384 $row = $this->fetchObject( $result );
1386 return ( $row->lockstatus === 't' );
1390 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1391 * @param string $lockName
1392 * @param string $method
1393 * @param int $timeout
1396 public function lock( $lockName, $method, $timeout = 5 ) {
1397 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1398 $loop = new WaitConditionLoop(
1399 function () use ( $lockName, $key, $timeout, $method ) {
1400 $res = $this->query( "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1401 $row = $this->fetchObject( $res );
1402 if ( $row->lockstatus === 't' ) {
1403 parent::lock( $lockName, $method, $timeout ); // record
1407 return WaitConditionLoop::CONDITION_CONTINUE;
1412 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1416 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKSFROM
1417 * PG DOCS: http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1418 * @param string $lockName
1419 * @param string $method
1422 public function unlock( $lockName, $method ) {
1423 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1424 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1425 $row = $this->fetchObject( $result );
1427 if ( $row->lockstatus === 't' ) {
1428 parent::unlock( $lockName, $method ); // record
1432 $this->queryLogger->debug( __METHOD__ . " failed to release lock\n" );
1438 * @param string $lockName
1439 * @return string Integer
1441 private function bigintFromLockName( $lockName ) {
1442 return Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );