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
27 class DatabasePostgres
extends DatabaseBase
{
32 protected $mLastResult = null;
33 /** @var int The number of rows affected as an integer */
34 protected $mAffectedRows = null;
37 private $mInsertId = null;
38 /** @var float|string */
39 private $numericVersion = null;
40 /** @var string Connect string to open a PostgreSQL connection */
41 private $connectString;
45 public function __construct( array $params ) {
46 $this->port
= isset( $params['port'] ) ?
$params['port'] : false;
47 parent
::__construct( $params );
54 function implicitGroupby() {
58 function implicitOrderby() {
62 function hasConstraint( $name ) {
63 $sql = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
64 "WHERE c.connamespace = n.oid AND conname = '" .
65 pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" .
66 pg_escape_string( $this->mConn
, $this->getCoreSchema() ) . "'";
67 $res = $this->doQuery( $sql );
69 return $this->numRows( $res );
73 * Usually aborts on failure
74 * @param string $server
76 * @param string $password
77 * @param string $dbName
78 * @throws DBConnectionError|Exception
79 * @return resource|bool|null
81 function open( $server, $user, $password, $dbName ) {
82 # Test for Postgres support, to avoid suppressed fatal error
83 if ( !function_exists( 'pg_connect' ) ) {
84 throw new DBConnectionError(
86 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
87 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
88 "webserver and database)\n"
92 if ( !strlen( $user ) ) { # e.g. the class is being loaded
96 $this->mServer
= $server;
98 $this->mPassword
= $password;
99 $this->mDBname
= $dbName;
104 'password' => $password
106 if ( $server != false && $server != '' ) {
107 $connectVars['host'] = $server;
109 if ( (int)$this->port
> 0 ) {
110 $connectVars['port'] = (int)$this->port
;
112 if ( $this->mFlags
& DBO_SSL
) {
113 $connectVars['sslmode'] = 1;
116 $this->connectString
= $this->makeConnectionString( $connectVars );
118 $this->installErrorHandler();
121 $this->mConn
= pg_connect( $this->connectString
);
122 } catch ( Exception
$ex ) {
123 $this->restoreErrorHandler();
127 $phpError = $this->restoreErrorHandler();
129 if ( !$this->mConn
) {
130 $this->queryLogger
->debug( "DB connection error\n" );
131 $this->queryLogger
->debug(
132 "Server: $server, Database: $dbName, User: $user, Password: " .
133 substr( $password, 0, 3 ) . "...\n" );
134 $this->queryLogger
->debug( $this->lastError() . "\n" );
135 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
138 $this->mOpened
= true;
140 # If called from the command-line (e.g. importDump), only show errors
141 if ( $this->cliMode
) {
142 $this->doQuery( "SET client_min_messages = 'ERROR'" );
145 $this->query( "SET client_encoding='UTF8'", __METHOD__
);
146 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__
);
147 $this->query( "SET timezone = 'GMT'", __METHOD__
);
148 $this->query( "SET standard_conforming_strings = on", __METHOD__
);
149 if ( $this->getServerVersion() >= 9.0 ) {
150 $this->query( "SET bytea_output = 'escape'", __METHOD__
); // PHP bug 53127
153 $this->determineCoreSchema( $this->mSchema
);
159 * Postgres doesn't support selectDB in the same way MySQL does. So if the
160 * DB name doesn't match the open connection, open a new one
164 function selectDB( $db ) {
165 if ( $this->mDBname
!== $db ) {
166 return (bool)$this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $db );
172 function makeConnectionString( $vars ) {
174 foreach ( $vars as $name => $value ) {
175 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
182 * Closes a database connection, if it is open
183 * Returns success, true if already closed
186 protected function closeConnection() {
187 return pg_close( $this->mConn
);
190 public function doQuery( $sql ) {
191 $sql = mb_convert_encoding( $sql, 'UTF-8' );
192 // Clear previously left over PQresult
193 while ( $res = pg_get_result( $this->mConn
) ) {
194 pg_free_result( $res );
196 if ( pg_send_query( $this->mConn
, $sql ) === false ) {
197 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
199 $this->mLastResult
= pg_get_result( $this->mConn
);
200 $this->mAffectedRows
= null;
201 if ( pg_result_error( $this->mLastResult
) ) {
205 return $this->mLastResult
;
208 protected function dumpError() {
212 PGSQL_DIAG_MESSAGE_PRIMARY
,
213 PGSQL_DIAG_MESSAGE_DETAIL
,
214 PGSQL_DIAG_MESSAGE_HINT
,
215 PGSQL_DIAG_STATEMENT_POSITION
,
216 PGSQL_DIAG_INTERNAL_POSITION
,
217 PGSQL_DIAG_INTERNAL_QUERY
,
219 PGSQL_DIAG_SOURCE_FILE
,
220 PGSQL_DIAG_SOURCE_LINE
,
221 PGSQL_DIAG_SOURCE_FUNCTION
223 foreach ( $diags as $d ) {
224 $this->queryLogger
->debug( sprintf( "PgSQL ERROR(%d): %s\n",
225 $d, pg_result_error_field( $this->mLastResult
, $d ) ) );
229 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
231 /* Check for constraint violation */
232 if ( $errno === '23505' ) {
233 parent
::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
238 /* Transaction stays in the ERROR state until rolled back */
239 if ( $this->mTrxLevel
) {
240 $ignore = $this->ignoreErrors( true );
241 $this->rollback( __METHOD__
);
242 $this->ignoreErrors( $ignore );
244 parent
::reportQueryError( $error, $errno, $sql, $fname, false );
247 function queryIgnore( $sql, $fname = __METHOD__
) {
248 return $this->query( $sql, $fname, true );
252 * @param stdClass|ResultWrapper $res
253 * @throws DBUnexpectedError
255 function freeResult( $res ) {
256 if ( $res instanceof ResultWrapper
) {
259 MediaWiki\
suppressWarnings();
260 $ok = pg_free_result( $res );
261 MediaWiki\restoreWarnings
();
263 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
268 * @param ResultWrapper|stdClass $res
270 * @throws DBUnexpectedError
272 function fetchObject( $res ) {
273 if ( $res instanceof ResultWrapper
) {
276 MediaWiki\
suppressWarnings();
277 $row = pg_fetch_object( $res );
278 MediaWiki\restoreWarnings
();
279 # @todo FIXME: HACK HACK HACK HACK debug
281 # @todo hashar: not sure if the following test really trigger if the object
283 if ( pg_last_error( $this->mConn
) ) {
284 throw new DBUnexpectedError(
286 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
293 function fetchRow( $res ) {
294 if ( $res instanceof ResultWrapper
) {
297 MediaWiki\
suppressWarnings();
298 $row = pg_fetch_array( $res );
299 MediaWiki\restoreWarnings
();
300 if ( pg_last_error( $this->mConn
) ) {
301 throw new DBUnexpectedError(
303 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
310 function numRows( $res ) {
311 if ( $res instanceof ResultWrapper
) {
314 MediaWiki\
suppressWarnings();
315 $n = pg_num_rows( $res );
316 MediaWiki\restoreWarnings
();
317 if ( pg_last_error( $this->mConn
) ) {
318 throw new DBUnexpectedError(
320 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) )
327 function numFields( $res ) {
328 if ( $res instanceof ResultWrapper
) {
332 return pg_num_fields( $res );
335 function fieldName( $res, $n ) {
336 if ( $res instanceof ResultWrapper
) {
340 return pg_field_name( $res, $n );
344 * Return the result of the last call to nextSequenceValue();
345 * This must be called after nextSequenceValue().
349 function insertId() {
350 return $this->mInsertId
;
358 function dataSeek( $res, $row ) {
359 if ( $res instanceof ResultWrapper
) {
363 return pg_result_seek( $res, $row );
366 function lastError() {
367 if ( $this->mConn
) {
368 if ( $this->mLastResult
) {
369 return pg_result_error( $this->mLastResult
);
371 return pg_last_error();
374 return 'No database connection';
378 function lastErrno() {
379 if ( $this->mLastResult
) {
380 return pg_result_error_field( $this->mLastResult
, PGSQL_DIAG_SQLSTATE
);
386 function affectedRows() {
387 if ( !is_null( $this->mAffectedRows
) ) {
388 // Forced result for simulated queries
389 return $this->mAffectedRows
;
391 if ( empty( $this->mLastResult
) ) {
395 return pg_affected_rows( $this->mLastResult
);
399 * Estimate rows in dataset
400 * Returns estimated count, based on EXPLAIN output
401 * This is not necessarily an accurate estimate, so use sparingly
402 * Returns -1 if count cannot be found
403 * Takes same arguments as Database::select()
405 * @param string $table
406 * @param string $vars
407 * @param string $conds
408 * @param string $fname
409 * @param array $options
412 function estimateRowCount( $table, $vars = '*', $conds = '',
413 $fname = __METHOD__
, $options = []
415 $options['EXPLAIN'] = true;
416 $res = $this->select( $table, $vars, $conds, $fname, $options );
419 $row = $this->fetchRow( $res );
421 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
422 $rows = (int)$count[1];
430 * Returns information about an index
431 * If errors are explicitly ignored, returns NULL on failure
433 * @param string $table
434 * @param string $index
435 * @param string $fname
438 function indexInfo( $table, $index, $fname = __METHOD__
) {
439 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
440 $res = $this->query( $sql, $fname );
444 foreach ( $res as $row ) {
445 if ( $row->indexname
== $this->indexName( $index ) ) {
454 * Returns is of attributes used in index
457 * @param string $index
458 * @param bool|string $schema
461 function indexAttributes( $index, $schema = false ) {
462 if ( $schema === false ) {
463 $schema = $this->getCoreSchema();
466 * A subquery would be not needed if we didn't care about the order
467 * of attributes, but we do
469 $sql = <<<__INDEXATTR__
473 i.indoption[s.g] as option,
476 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
480 ON cis.oid=isub.indexrelid
482 ON cis.relnamespace = ns.oid
483 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
489 ON ci.oid=i.indexrelid
491 ON ct.oid = i.indrelid
493 ON ci.relnamespace = n.oid
495 ci.relname='$index' AND n.nspname='$schema'
496 AND attrelid = ct.oid
497 AND i.indkey[s.g] = attnum
498 AND i.indclass[s.g] = opcls.oid
499 AND pg_am.oid = opcls.opcmethod
501 $res = $this->query( $sql, __METHOD__ );
504 foreach ( $res as $row ) {
518 function indexUnique( $table, $index, $fname = __METHOD__ ) {
519 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
520 " AND indexdef LIKE 'CREATE UNIQUE%(" .
521 $this->strencode( $this->indexName( $index ) ) .
523 $res = $this->query( $sql, $fname );
528 return $res->numRows() > 0;
531 function selectSQLText(
532 $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
534 // Change the FOR UPDATE option as necessary based on the join conditions. Then pass
535 // to the parent function to get the actual SQL text.
536 // In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
537 // can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to
538 // do so causes a DB error. This wrapper checks which tables can be locked and adjusts it
540 // MySQL uses "ORDER BY NULL" as an optimization hint, but that is illegal in PostgreSQL.
541 if ( is_array( $options ) ) {
542 $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
543 if ( $forUpdateKey !== false && $join_conds ) {
544 unset( $options[$forUpdateKey] );
546 foreach ( $join_conds as $table_cond => $join_cond ) {
547 if ( 0 === preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_cond[0] ) ) {
548 $options['FOR UPDATE'][] = $table_cond;
553 if ( isset( $options['ORDER BY'] ) && $options['ORDER BY'] == 'NULL' ) {
554 unset( $options['ORDER BY'] );
558 return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
562 * INSERT wrapper, inserts an array into a table
564 * $args may be a single associative array, or an array of these with numeric keys,
565 * for multi-row insert (Postgres version 8.2 and above only).
567 * @param string $table Name of the table to insert to.
568 * @param array $args Items to insert into the table.
569 * @param string $fname Name of the function, for profiling
570 * @param array|string $options String or array. Valid options: IGNORE
571 * @return bool Success of insert operation. IGNORE always returns true.
573 function insert( $table, $args, $fname = __METHOD__, $options = [] ) {
574 if ( !count( $args ) ) {
578 $table = $this->tableName( $table );
579 if ( !isset( $this->numericVersion ) ) {
580 $this->getServerVersion();
583 if ( !is_array( $options ) ) {
584 $options = [ $options ];
587 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
589 $keys = array_keys( $args[0] );
592 $keys = array_keys( $args );
595 // If IGNORE is set, we use savepoints to emulate mysql's behavior
596 $savepoint = $olde = null;
597 $numrowsinserted = 0;
598 if ( in_array( 'IGNORE', $options ) ) {
599 $savepoint = new SavepointPostgres( $this, 'mw', $this->queryLogger );
600 $olde = error_reporting( 0 );
601 // For future use, we may want to track the number of actual inserts
602 // Right now, insert (all writes) simply return true/false
605 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
608 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
610 foreach ( $args as $row ) {
616 $sql .= '(' . $this->makeList( $row ) . ')';
618 $res = (bool)$this->query( $sql, $fname, $savepoint );
622 foreach ( $args as $row ) {
624 $tempsql .= '(' . $this->makeList( $row ) . ')';
627 $savepoint->savepoint();
630 $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
633 $bar = pg_result_error( $this->mLastResult );
634 if ( $bar != false ) {
635 $savepoint->rollback();
637 $savepoint->release();
642 // If any of them fail, we fail overall for this function call
643 // Note that this will be ignored if IGNORE is set
650 // Not multi, just a lone insert
652 $savepoint->savepoint();
655 $sql .= '(' . $this->makeList( $args ) . ')';
656 $res = (bool)$this->query( $sql, $fname, $savepoint );
658 $bar = pg_result_error( $this->mLastResult );
659 if ( $bar != false ) {
660 $savepoint->rollback();
662 $savepoint->release();
668 error_reporting( $olde );
669 $savepoint->commit();
671 // Set the affected row count for the whole operation
672 $this->mAffectedRows = $numrowsinserted;
674 // IGNORE always returns true
682 * INSERT SELECT wrapper
683 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
684 * Source items may be literals rather then field names, but strings should
685 * be quoted with Database::addQuotes()
686 * $conds may be "*" to copy the whole table
687 * srcTable may be an array of tables.
688 * @todo FIXME: Implement this a little better (seperate select/insert)?
690 * @param string $destTable
691 * @param array|string $srcTable
692 * @param array $varMap
693 * @param array $conds
694 * @param string $fname
695 * @param array $insertOptions
696 * @param array $selectOptions
699 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
700 $insertOptions = [], $selectOptions = [] ) {
701 $destTable = $this->tableName( $destTable );
703 if ( !is_array( $insertOptions ) ) {
704 $insertOptions = [ $insertOptions ];
708 * If IGNORE is set, we use savepoints to emulate mysql's behavior
709 * Ignore LOW PRIORITY option, since it is MySQL-specific
711 $savepoint = $olde = null;
712 $numrowsinserted = 0;
713 if ( in_array( 'IGNORE', $insertOptions ) ) {
714 $savepoint = new SavepointPostgres( $this, 'mw', $this->queryLogger );
715 $olde = error_reporting( 0 );
716 $savepoint->savepoint();
719 if ( !is_array( $selectOptions ) ) {
720 $selectOptions = [ $selectOptions ];
722 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) =
723 $this->makeSelectOptions( $selectOptions );
724 if ( is_array( $srcTable ) ) {
725 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
727 $srcTable = $this->tableName( $srcTable );
730 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
731 " SELECT $startOpts " . implode( ',', $varMap ) .
732 " FROM $srcTable $useIndex $ignoreIndex ";
734 if ( $conds != '*' ) {
735 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
738 $sql .= " $tailOpts";
740 $res = (bool)$this->query( $sql, $fname, $savepoint );
742 $bar = pg_result_error( $this->mLastResult );
743 if ( $bar != false ) {
744 $savepoint->rollback();
746 $savepoint->release();
749 error_reporting( $olde );
750 $savepoint->commit();
752 // Set the affected row count for the whole operation
753 $this->mAffectedRows = $numrowsinserted;
755 // IGNORE always returns true
762 function tableName( $name, $format = 'quoted' ) {
763 # Replace reserved words with better ones
766 return $this->realTableName( 'mwuser', $format );
768 return $this->realTableName( 'pagecontent', $format );
770 return $this->realTableName( $name, $format );
774 /* Don't cheat on installer */
775 function realTableName( $name, $format = 'quoted' ) {
776 return parent::tableName( $name, $format );
780 * Return the next in a sequence, save the value for retrieval via insertId()
782 * @param string $seqName
785 function nextSequenceValue( $seqName ) {
786 $safeseq = str_replace( "'", "''", $seqName );
787 $res = $this->query( "SELECT nextval('$safeseq')" );
788 $row = $this->fetchRow( $res );
789 $this->mInsertId = $row[0];
791 return $this->mInsertId;
795 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
797 * @param string $seqName
800 function currentSequenceValue( $seqName ) {
801 $safeseq = str_replace( "'", "''", $seqName );
802 $res = $this->query( "SELECT currval('$safeseq')" );
803 $row = $this->fetchRow( $res );
809 # Returns the size of a text field, or -1 for "unlimited"
810 function textFieldSize( $table, $field ) {
811 $table = $this->tableName( $table );
812 $sql = "SELECT t.typname as ftype,a.atttypmod as size
813 FROM pg_class c, pg_attribute a, pg_type t
814 WHERE relname='$table' AND a.attrelid=c.oid AND
815 a.atttypid=t.oid and a.attname='$field'";
816 $res = $this->query( $sql );
817 $row = $this->fetchObject( $res );
818 if ( $row->ftype == 'varchar' ) {
819 $size = $row->size - 4;
827 function limitResult( $sql, $limit, $offset = false ) {
828 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
831 function wasDeadlock() {
832 return $this->lastErrno() == '40P01';
835 function duplicateTableStructure(
836 $oldName, $newName, $temporary = false, $fname = __METHOD__
838 $newName = $this->addIdentifierQuotes( $newName );
839 $oldName = $this->addIdentifierQuotes( $oldName );
841 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName " .
842 "(LIKE $oldName INCLUDING DEFAULTS)", $fname );
845 function listTables( $prefix = null, $fname = __METHOD__ ) {
846 $eschema = $this->addQuotes( $this->getCoreSchema() );
847 $result = $this->query(
848 "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
851 foreach ( $result as $table ) {
852 $vars = get_object_vars( $table );
853 $table = array_pop( $vars );
854 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
855 $endArray[] = $table;
862 function timestamp( $ts = 0 ) {
863 $ct = new ConvertableTimestamp( $ts );
865 return $ct->getTimestamp( TS_POSTGRES );
869 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
870 * to http://www.php.net/manual/en/ref.pgsql.php
872 * Parsing a postgres array can be a tricky problem, he's my
873 * take on this, it handles multi-dimensional arrays plus
874 * escaping using a nasty regexp to determine the limits of each
877 * This should really be handled by PHP PostgreSQL module
880 * @param string $text Postgreql array returned in a text form like {a,b}
881 * @param string $output
882 * @param int|bool $limit
886 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
887 if ( false === $limit ) {
888 $limit = strlen( $text ) - 1;
891 if ( '{}' == $text ) {
895 if ( '{' != $text[$offset] ) {
896 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
897 $text, $match, 0, $offset );
898 $offset += strlen( $match[0] );
899 $output[] = ( '"' != $match[1][0]
901 : stripcslashes( substr( $match[1], 1, -1 ) ) );
902 if ( '},' == $match[3] ) {
906 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
908 } while ( $limit > $offset );
914 * Return aggregated value function call
915 * @param array $valuedata
916 * @param string $valuename
919 public function aggregateValue( $valuedata, $valuename = 'value' ) {
924 * @return string Wikitext of a link to the server software's web site
926 public function getSoftwareLink() {
927 return '[{{int:version-db-postgres-url}} PostgreSQL]';
931 * Return current schema (executes SELECT current_schema())
935 * @return string Default schema for the current session
937 function getCurrentSchema() {
938 $res = $this->query( "SELECT current_schema()", __METHOD__ );
939 $row = $this->fetchRow( $res );
945 * Return list of schemas which are accessible without schema name
946 * This is list does not contain magic keywords like "$user"
949 * @see getSearchPath()
950 * @see setSearchPath()
952 * @return array List of actual schemas for the current sesson
954 function getSchemas() {
955 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
956 $row = $this->fetchRow( $res );
959 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
961 return $this->pg_array_parse( $row[0], $schemas );
965 * Return search patch for schemas
966 * This is different from getSchemas() since it contain magic keywords
971 * @return array How to search for table names schemas for the current user
973 function getSearchPath() {
974 $res = $this->query( "SHOW search_path", __METHOD__ );
975 $row = $this->fetchRow( $res );
977 /* PostgreSQL returns SHOW values as strings */
979 return explode( ",", $row[0] );
983 * Update search_path, values should already be sanitized
984 * Values may contain magic keywords like "$user"
987 * @param array $search_path List of schemas to be searched by default
989 function setSearchPath( $search_path ) {
990 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
994 * Determine default schema for MediaWiki core
995 * Adjust this session schema search path if desired schema exists
996 * and is not alread there.
998 * We need to have name of the core schema stored to be able
999 * to query database metadata.
1001 * This will be also called by the installer after the schema is created
1005 * @param string $desiredSchema
1007 function determineCoreSchema( $desiredSchema ) {
1008 $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
1009 if ( $this->schemaExists( $desiredSchema ) ) {
1010 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
1011 $this->mCoreSchema = $desiredSchema;
1012 $this->queryLogger->debug(
1013 "Schema \"" . $desiredSchema . "\" already in the search path\n" );
1016 * Prepend our schema (e.g. 'mediawiki') in front
1017 * of the search path
1020 $search_path = $this->getSearchPath();
1021 array_unshift( $search_path,
1022 $this->addIdentifierQuotes( $desiredSchema ) );
1023 $this->setSearchPath( $search_path );
1024 $this->mCoreSchema = $desiredSchema;
1025 $this->queryLogger->debug(
1026 "Schema \"" . $desiredSchema . "\" added to the search path\n" );
1029 $this->mCoreSchema = $this->getCurrentSchema();
1030 $this->queryLogger->debug(
1031 "Schema \"" . $desiredSchema . "\" not found, using current \"" .
1032 $this->mCoreSchema . "\"\n" );
1034 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1035 $this->commit( __METHOD__ );
1039 * Return schema name fore core MediaWiki tables
1042 * @return string Core schema name
1044 function getCoreSchema() {
1045 return $this->mCoreSchema;
1049 * @return string Version information from the database
1051 function getServerVersion() {
1052 if ( !isset( $this->numericVersion ) ) {
1053 $versionInfo = pg_version( $this->mConn );
1054 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1055 // Old client, abort install
1056 $this->numericVersion = '7.3 or earlier';
1057 } elseif ( isset( $versionInfo['server'] ) ) {
1059 $this->numericVersion = $versionInfo['server'];
1061 // Bug 16937: broken pgsql extension from PHP<5.3
1062 $this->numericVersion = pg_parameter_status( $this->mConn, 'server_version' );
1066 return $this->numericVersion;
1070 * Query whether a given relation exists (in the given schema, or the
1071 * default mw one if not given)
1072 * @param string $table
1073 * @param array|string $types
1074 * @param bool|string $schema
1077 function relationExists( $table, $types, $schema = false ) {
1078 if ( !is_array( $types ) ) {
1079 $types = [ $types ];
1082 $schema = $this->getCoreSchema();
1084 $table = $this->realTableName( $table, 'raw' );
1085 $etable = $this->addQuotes( $table );
1086 $eschema = $this->addQuotes( $schema );
1087 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1088 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1089 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1090 $res = $this->query( $sql );
1091 $count = $res ? $res->numRows() : 0;
1093 return (bool)$count;
1097 * For backward compatibility, this function checks both tables and
1099 * @param string $table
1100 * @param string $fname
1101 * @param bool|string $schema
1104 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1105 return $this->relationExists( $table, [ 'r', 'v' ], $schema );
1108 function sequenceExists( $sequence, $schema = false ) {
1109 return $this->relationExists( $sequence, 'S', $schema );
1112 function triggerExists( $table, $trigger ) {
1114 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1115 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1116 AND tgrelid=pg_class.oid
1117 AND nspname=%s AND relname=%s AND tgname=%s
1119 $res = $this->query(
1122 $this->addQuotes( $this->getCoreSchema() ),
1123 $this->addQuotes( $table ),
1124 $this->addQuotes( $trigger )
1130 $rows = $res->numRows();
1135 function ruleExists( $table, $rule ) {
1136 $exists = $this->selectField( 'pg_rules', 'rulename',
1138 'rulename' => $rule,
1139 'tablename' => $table,
1140 'schemaname' => $this->getCoreSchema()
1144 return $exists === $rule;
1147 function constraintExists( $table, $constraint ) {
1148 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1149 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1150 $this->addQuotes( $this->getCoreSchema() ),
1151 $this->addQuotes( $table ),
1152 $this->addQuotes( $constraint )
1154 $res = $this->query( $sql );
1158 $rows = $res->numRows();
1164 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1165 * @param string $schema
1168 function schemaExists( $schema ) {
1169 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1170 [ 'nspname' => $schema ], __METHOD__ );
1172 return (bool)$exists;
1176 * Returns true if a given role (i.e. user) exists, false otherwise.
1177 * @param string $roleName
1180 function roleExists( $roleName ) {
1181 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1182 [ 'rolname' => $roleName ], __METHOD__ );
1184 return (bool)$exists;
1188 * @var string $table
1189 * @var string $field
1190 * @return PostgresField|null
1192 function fieldInfo( $table, $field ) {
1193 return PostgresField::fromText( $this, $table, $field );
1197 * pg_field_type() wrapper
1198 * @param ResultWrapper|resource $res ResultWrapper or PostgreSQL query result resource
1199 * @param int $index Field number, starting from 0
1202 function fieldType( $res, $index ) {
1203 if ( $res instanceof ResultWrapper ) {
1204 $res = $res->result;
1207 return pg_field_type( $res, $index );
1214 function encodeBlob( $b ) {
1215 return new PostgresBlob( pg_escape_bytea( $b ) );
1218 function decodeBlob( $b ) {
1219 if ( $b instanceof PostgresBlob ) {
1221 } elseif ( $b instanceof Blob ) {
1225 return pg_unescape_bytea( $b );
1228 function strencode( $s ) {
1229 // Should not be called by us
1231 return pg_escape_string( $this->mConn, $s );
1235 * @param null|bool|Blob $s
1236 * @return int|string
1238 function addQuotes( $s ) {
1239 if ( is_null( $s ) ) {
1241 } elseif ( is_bool( $s ) ) {
1242 return intval( $s );
1243 } elseif ( $s instanceof Blob ) {
1244 if ( $s instanceof PostgresBlob ) {
1247 $s = pg_escape_bytea( $this->mConn, $s->fetch() );
1252 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1256 * Postgres specific version of replaceVars.
1257 * Calls the parent version in Database.php
1259 * @param string $ins SQL string, read from a stream (usually tables.sql)
1260 * @return string SQL string
1262 protected function replaceVars( $ins ) {
1263 $ins = parent::replaceVars( $ins );
1265 if ( $this->numericVersion >= 8.3 ) {
1266 // Thanks for not providing backwards-compatibility, 8.3
1267 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1270 if ( $this->numericVersion <= 8.1 ) { // Our minimum version
1271 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1278 * Various select options
1280 * @param array $options An associative array of options to be turned into
1281 * an SQL query, valid keys are listed in the function.
1284 function makeSelectOptions( $options ) {
1285 $preLimitTail = $postLimitTail = '';
1286 $startOpts = $useIndex = $ignoreIndex = '';
1289 foreach ( $options as $key => $option ) {
1290 if ( is_numeric( $key ) ) {
1291 $noKeyOptions[$option] = true;
1295 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1297 $preLimitTail .= $this->makeOrderBy( $options );
1299 // if ( isset( $options['LIMIT'] ) ) {
1300 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1301 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1305 if ( isset( $options['FOR UPDATE'] ) ) {
1306 $postLimitTail .= ' FOR UPDATE OF ' .
1307 implode( ', ', array_map( [ &$this, 'tableName' ], $options['FOR UPDATE'] ) );
1308 } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1309 $postLimitTail .= ' FOR UPDATE';
1312 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1313 $startOpts .= 'DISTINCT';
1316 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1319 function getDBname() {
1320 return $this->mDBname;
1323 function getServer() {
1324 return $this->mServer;
1327 function buildConcat( $stringList ) {
1328 return implode( ' || ', $stringList );
1331 public function buildGroupConcatField(
1332 $delimiter, $table, $field, $conds = '', $options = [], $join_conds = []
1334 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1336 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1340 * @param string $field Field or column to cast
1344 public function buildStringCast( $field ) {
1345 return $field . '::text';
1348 public function streamStatementEnd( &$sql, &$newLine ) {
1349 # Allow dollar quoting for function declarations
1350 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1351 if ( $this->delimiter ) {
1352 $this->delimiter = false;
1354 $this->delimiter = ';';
1358 return parent::streamStatementEnd( $sql, $newLine );
1362 * Check to see if a named lock is available. This is non-blocking.
1363 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1365 * @param string $lockName Name of lock to poll
1366 * @param string $method Name of method calling us
1370 public function lockIsFree( $lockName, $method ) {
1371 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1372 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1373 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1374 $row = $this->fetchObject( $result );
1376 return ( $row->lockstatus === 't' );
1380 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1381 * @param string $lockName
1382 * @param string $method
1383 * @param int $timeout
1386 public function lock( $lockName, $method, $timeout = 5 ) {
1387 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1388 $loop = new WaitConditionLoop(
1389 function () use ( $lockName, $key, $timeout, $method ) {
1390 $res = $this->query( "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1391 $row = $this->fetchObject( $res );
1392 if ( $row->lockstatus === 't' ) {
1393 parent::lock( $lockName, $method, $timeout ); // record
1397 return WaitConditionLoop::CONDITION_CONTINUE;
1402 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1406 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKSFROM
1407 * PG DOCS: http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1408 * @param string $lockName
1409 * @param string $method
1412 public function unlock( $lockName, $method ) {
1413 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1414 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1415 $row = $this->fetchObject( $result );
1417 if ( $row->lockstatus === 't' ) {
1418 parent::unlock( $lockName, $method ); // record
1422 $this->queryLogger->debug( __METHOD__ . " failed to release lock\n" );
1428 * @param string $lockName
1429 * @return string Integer
1431 private function bigintFromLockName( $lockName ) {
1432 return Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );