Added release notes for 'ContentHandler::runLegacyHooks' removal
[mediawiki.git] / includes / libs / rdbms / database / DatabasePostgres.php
blob42113b0851c9135da75e758a912b5bda574da0a0
1 <?php
2 /**
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
20 * @file
21 * @ingroup Database
23 use Wikimedia\WaitConditionLoop;
25 /**
26 * @ingroup Database
28 class DatabasePostgres extends Database {
29 /** @var int|bool */
30 protected $port;
32 /** @var resource */
33 protected $mLastResult = null;
34 /** @var int The number of rows affected as an integer */
35 protected $mAffectedRows = null;
37 /** @var int */
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;
43 /** @var string */
44 private $mCoreSchema;
45 /** @var string[] Map of (reserved table name => alternate table name) */
46 private $keywordTableMap = [];
48 /**
49 * @see Database::__construct()
50 * @param array $params Additional parameters include:
51 * - keywordTableMap : Map of reserved table names to alternative table names to use
53 public function __construct( array $params ) {
54 $this->port = isset( $params['port'] ) ? $params['port'] : false;
55 $this->keywordTableMap = isset( $params['keywordTableMap'] )
56 ? $params['keywordTableMap']
57 : [];
59 parent::__construct( $params );
62 public function getType() {
63 return 'postgres';
66 public function implicitGroupby() {
67 return false;
70 public function implicitOrderby() {
71 return false;
74 public function hasConstraint( $name ) {
75 $conn = $this->getBindingHandle();
77 $sql = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
78 "WHERE c.connamespace = n.oid AND conname = '" .
79 pg_escape_string( $conn, $name ) . "' AND n.nspname = '" .
80 pg_escape_string( $conn, $this->getCoreSchema() ) . "'";
81 $res = $this->doQuery( $sql );
83 return $this->numRows( $res );
86 public function open( $server, $user, $password, $dbName ) {
87 # Test for Postgres support, to avoid suppressed fatal error
88 if ( !function_exists( 'pg_connect' ) ) {
89 throw new DBConnectionError(
90 $this,
91 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
92 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
93 "webserver and database)\n"
97 $this->mServer = $server;
98 $this->mUser = $user;
99 $this->mPassword = $password;
100 $this->mDBname = $dbName;
102 $connectVars = [
103 'dbname' => $dbName,
104 'user' => $user,
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 );
118 $this->close();
119 $this->installErrorHandler();
121 try {
122 // Use new connections to let LoadBalancer/LBFactory handle reuse
123 $this->mConn = pg_connect( $this->connectString, PGSQL_CONNECT_FORCE_NEW );
124 } catch ( Exception $ex ) {
125 $this->restoreErrorHandler();
126 throw $ex;
129 $phpError = $this->restoreErrorHandler();
131 if ( !$this->mConn ) {
132 $this->queryLogger->debug(
133 "DB connection error\n" .
134 "Server: $server, Database: $dbName, User: $user, Password: " .
135 substr( $password, 0, 3 ) . "...\n"
137 $this->queryLogger->debug( $this->lastError() . "\n" );
138 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
141 $this->mOpened = true;
143 # If called from the command-line (e.g. importDump), only show errors
144 if ( $this->cliMode ) {
145 $this->doQuery( "SET client_min_messages = 'ERROR'" );
148 $this->query( "SET client_encoding='UTF8'", __METHOD__ );
149 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__ );
150 $this->query( "SET timezone = 'GMT'", __METHOD__ );
151 $this->query( "SET standard_conforming_strings = on", __METHOD__ );
152 if ( $this->getServerVersion() >= 9.0 ) {
153 $this->query( "SET bytea_output = 'escape'", __METHOD__ ); // PHP bug 53127
156 $this->determineCoreSchema( $this->mSchema );
157 // The schema to be used is now in the search path; no need for explicit qualification
158 $this->mSchema = '';
160 return $this->mConn;
164 * Postgres doesn't support selectDB in the same way MySQL does. So if the
165 * DB name doesn't match the open connection, open a new one
166 * @param string $db
167 * @return bool
169 public function selectDB( $db ) {
170 if ( $this->mDBname !== $db ) {
171 return (bool)$this->open( $this->mServer, $this->mUser, $this->mPassword, $db );
172 } else {
173 return true;
178 * @param string[] $vars
179 * @return string
181 private function makeConnectionString( $vars ) {
182 $s = '';
183 foreach ( $vars as $name => $value ) {
184 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
187 return $s;
190 protected function closeConnection() {
191 return $this->mConn ? pg_close( $this->mConn ) : true;
194 public function doQuery( $sql ) {
195 $conn = $this->getBindingHandle();
197 $sql = mb_convert_encoding( $sql, 'UTF-8' );
198 // Clear previously left over PQresult
199 while ( $res = pg_get_result( $conn ) ) {
200 pg_free_result( $res );
202 if ( pg_send_query( $conn, $sql ) === false ) {
203 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
205 $this->mLastResult = pg_get_result( $conn );
206 $this->mAffectedRows = null;
207 if ( pg_result_error( $this->mLastResult ) ) {
208 return false;
211 return $this->mLastResult;
214 protected function dumpError() {
215 $diags = [
216 PGSQL_DIAG_SEVERITY,
217 PGSQL_DIAG_SQLSTATE,
218 PGSQL_DIAG_MESSAGE_PRIMARY,
219 PGSQL_DIAG_MESSAGE_DETAIL,
220 PGSQL_DIAG_MESSAGE_HINT,
221 PGSQL_DIAG_STATEMENT_POSITION,
222 PGSQL_DIAG_INTERNAL_POSITION,
223 PGSQL_DIAG_INTERNAL_QUERY,
224 PGSQL_DIAG_CONTEXT,
225 PGSQL_DIAG_SOURCE_FILE,
226 PGSQL_DIAG_SOURCE_LINE,
227 PGSQL_DIAG_SOURCE_FUNCTION
229 foreach ( $diags as $d ) {
230 $this->queryLogger->debug( sprintf( "PgSQL ERROR(%d): %s\n",
231 $d, pg_result_error_field( $this->mLastResult, $d ) ) );
235 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
236 if ( $tempIgnore ) {
237 /* Check for constraint violation */
238 if ( $errno === '23505' ) {
239 parent::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
241 return;
244 /* Transaction stays in the ERROR state until rolled back */
245 if ( $this->mTrxLevel ) {
246 $this->rollback( __METHOD__ );
248 parent::reportQueryError( $error, $errno, $sql, $fname, false );
251 public function freeResult( $res ) {
252 if ( $res instanceof ResultWrapper ) {
253 $res = $res->result;
255 MediaWiki\suppressWarnings();
256 $ok = pg_free_result( $res );
257 MediaWiki\restoreWarnings();
258 if ( !$ok ) {
259 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
263 public function fetchObject( $res ) {
264 if ( $res instanceof ResultWrapper ) {
265 $res = $res->result;
267 MediaWiki\suppressWarnings();
268 $row = pg_fetch_object( $res );
269 MediaWiki\restoreWarnings();
270 # @todo FIXME: HACK HACK HACK HACK debug
272 # @todo hashar: not sure if the following test really trigger if the object
273 # fetching failed.
274 $conn = $this->getBindingHandle();
275 if ( pg_last_error( $conn ) ) {
276 throw new DBUnexpectedError(
277 $this,
278 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
282 return $row;
285 public function fetchRow( $res ) {
286 if ( $res instanceof ResultWrapper ) {
287 $res = $res->result;
289 MediaWiki\suppressWarnings();
290 $row = pg_fetch_array( $res );
291 MediaWiki\restoreWarnings();
293 $conn = $this->getBindingHandle();
294 if ( pg_last_error( $conn ) ) {
295 throw new DBUnexpectedError(
296 $this,
297 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
301 return $row;
304 public function numRows( $res ) {
305 if ( $res instanceof ResultWrapper ) {
306 $res = $res->result;
308 MediaWiki\suppressWarnings();
309 $n = pg_num_rows( $res );
310 MediaWiki\restoreWarnings();
312 $conn = $this->getBindingHandle();
313 if ( pg_last_error( $conn ) ) {
314 throw new DBUnexpectedError(
315 $this,
316 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
320 return $n;
323 public function numFields( $res ) {
324 if ( $res instanceof ResultWrapper ) {
325 $res = $res->result;
328 return pg_num_fields( $res );
331 public function fieldName( $res, $n ) {
332 if ( $res instanceof ResultWrapper ) {
333 $res = $res->result;
336 return pg_field_name( $res, $n );
340 * Return the result of the last call to nextSequenceValue();
341 * This must be called after nextSequenceValue().
343 * @return int|null
345 public function insertId() {
346 return $this->mInsertId;
349 public function dataSeek( $res, $row ) {
350 if ( $res instanceof ResultWrapper ) {
351 $res = $res->result;
354 return pg_result_seek( $res, $row );
357 public function lastError() {
358 if ( $this->mConn ) {
359 if ( $this->mLastResult ) {
360 return pg_result_error( $this->mLastResult );
361 } else {
362 return pg_last_error();
366 return $this->getLastPHPError() ?: 'No database connection';
369 public function lastErrno() {
370 if ( $this->mLastResult ) {
371 return pg_result_error_field( $this->mLastResult, PGSQL_DIAG_SQLSTATE );
372 } else {
373 return false;
377 public function affectedRows() {
378 if ( !is_null( $this->mAffectedRows ) ) {
379 // Forced result for simulated queries
380 return $this->mAffectedRows;
382 if ( empty( $this->mLastResult ) ) {
383 return 0;
386 return pg_affected_rows( $this->mLastResult );
390 * Estimate rows in dataset
391 * Returns estimated count, based on EXPLAIN output
392 * This is not necessarily an accurate estimate, so use sparingly
393 * Returns -1 if count cannot be found
394 * Takes same arguments as Database::select()
396 * @param string $table
397 * @param string $vars
398 * @param string $conds
399 * @param string $fname
400 * @param array $options
401 * @return int
403 public function estimateRowCount( $table, $vars = '*', $conds = '',
404 $fname = __METHOD__, $options = []
406 $options['EXPLAIN'] = true;
407 $res = $this->select( $table, $vars, $conds, $fname, $options );
408 $rows = -1;
409 if ( $res ) {
410 $row = $this->fetchRow( $res );
411 $count = [];
412 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
413 $rows = (int)$count[1];
417 return $rows;
420 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
421 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
422 $res = $this->query( $sql, $fname );
423 if ( !$res ) {
424 return null;
426 foreach ( $res as $row ) {
427 if ( $row->indexname == $this->indexName( $index ) ) {
428 return $row;
432 return false;
435 public function indexAttributes( $index, $schema = false ) {
436 if ( $schema === false ) {
437 $schema = $this->getCoreSchema();
440 * A subquery would be not needed if we didn't care about the order
441 * of attributes, but we do
443 $sql = <<<__INDEXATTR__
445 SELECT opcname,
446 attname,
447 i.indoption[s.g] as option,
448 pg_am.amname
449 FROM
450 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
451 FROM
452 pg_index isub
453 JOIN pg_class cis
454 ON cis.oid=isub.indexrelid
455 JOIN pg_namespace ns
456 ON cis.relnamespace = ns.oid
457 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
458 pg_attribute,
459 pg_opclass opcls,
460 pg_am,
461 pg_class ci
462 JOIN pg_index i
463 ON ci.oid=i.indexrelid
464 JOIN pg_class ct
465 ON ct.oid = i.indrelid
466 JOIN pg_namespace n
467 ON ci.relnamespace = n.oid
468 WHERE
469 ci.relname='$index' AND n.nspname='$schema'
470 AND attrelid = ct.oid
471 AND i.indkey[s.g] = attnum
472 AND i.indclass[s.g] = opcls.oid
473 AND pg_am.oid = opcls.opcmethod
474 __INDEXATTR__;
475 $res = $this->query( $sql, __METHOD__ );
476 $a = [];
477 if ( $res ) {
478 foreach ( $res as $row ) {
479 $a[] = [
480 $row->attname,
481 $row->opcname,
482 $row->amname,
483 $row->option ];
485 } else {
486 return null;
489 return $a;
492 public function indexUnique( $table, $index, $fname = __METHOD__ ) {
493 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
494 " AND indexdef LIKE 'CREATE UNIQUE%(" .
495 $this->strencode( $this->indexName( $index ) ) .
496 ")'";
497 $res = $this->query( $sql, $fname );
498 if ( !$res ) {
499 return null;
502 return $res->numRows() > 0;
505 public function selectSQLText(
506 $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
508 // Change the FOR UPDATE option as necessary based on the join conditions. Then pass
509 // to the parent function to get the actual SQL text.
510 // In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
511 // can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to
512 // do so causes a DB error. This wrapper checks which tables can be locked and adjusts it
513 // accordingly.
514 // MySQL uses "ORDER BY NULL" as an optimization hint, but that is illegal in PostgreSQL.
515 if ( is_array( $options ) ) {
516 $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
517 if ( $forUpdateKey !== false && $join_conds ) {
518 unset( $options[$forUpdateKey] );
520 foreach ( $join_conds as $table_cond => $join_cond ) {
521 if ( 0 === preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_cond[0] ) ) {
522 $options['FOR UPDATE'][] = $table_cond;
527 if ( isset( $options['ORDER BY'] ) && $options['ORDER BY'] == 'NULL' ) {
528 unset( $options['ORDER BY'] );
532 return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
536 * INSERT wrapper, inserts an array into a table
538 * $args may be a single associative array, or an array of these with numeric keys,
539 * for multi-row insert (Postgres version 8.2 and above only).
541 * @param string $table Name of the table to insert to.
542 * @param array $args Items to insert into the table.
543 * @param string $fname Name of the function, for profiling
544 * @param array|string $options String or array. Valid options: IGNORE
545 * @return bool Success of insert operation. IGNORE always returns true.
547 public function insert( $table, $args, $fname = __METHOD__, $options = [] ) {
548 if ( !count( $args ) ) {
549 return true;
552 $table = $this->tableName( $table );
553 if ( !isset( $this->numericVersion ) ) {
554 $this->getServerVersion();
557 if ( !is_array( $options ) ) {
558 $options = [ $options ];
561 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
562 $multi = true;
563 $keys = array_keys( $args[0] );
564 } else {
565 $multi = false;
566 $keys = array_keys( $args );
569 // If IGNORE is set, we use savepoints to emulate mysql's behavior
570 $savepoint = $olde = null;
571 $numrowsinserted = 0;
572 if ( in_array( 'IGNORE', $options ) ) {
573 $savepoint = new SavepointPostgres( $this, 'mw', $this->queryLogger );
574 $olde = error_reporting( 0 );
575 // For future use, we may want to track the number of actual inserts
576 // Right now, insert (all writes) simply return true/false
579 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
581 if ( $multi ) {
582 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
583 $first = true;
584 foreach ( $args as $row ) {
585 if ( $first ) {
586 $first = false;
587 } else {
588 $sql .= ',';
590 $sql .= '(' . $this->makeList( $row ) . ')';
592 $res = (bool)$this->query( $sql, $fname, $savepoint );
593 } else {
594 $res = true;
595 $origsql = $sql;
596 foreach ( $args as $row ) {
597 $tempsql = $origsql;
598 $tempsql .= '(' . $this->makeList( $row ) . ')';
600 if ( $savepoint ) {
601 $savepoint->savepoint();
604 $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
606 if ( $savepoint ) {
607 $bar = pg_result_error( $this->mLastResult );
608 if ( $bar != false ) {
609 $savepoint->rollback();
610 } else {
611 $savepoint->release();
612 $numrowsinserted++;
616 // If any of them fail, we fail overall for this function call
617 // Note that this will be ignored if IGNORE is set
618 if ( !$tempres ) {
619 $res = false;
623 } else {
624 // Not multi, just a lone insert
625 if ( $savepoint ) {
626 $savepoint->savepoint();
629 $sql .= '(' . $this->makeList( $args ) . ')';
630 $res = (bool)$this->query( $sql, $fname, $savepoint );
631 if ( $savepoint ) {
632 $bar = pg_result_error( $this->mLastResult );
633 if ( $bar != false ) {
634 $savepoint->rollback();
635 } else {
636 $savepoint->release();
637 $numrowsinserted++;
641 if ( $savepoint ) {
642 error_reporting( $olde );
643 $savepoint->commit();
645 // Set the affected row count for the whole operation
646 $this->mAffectedRows = $numrowsinserted;
648 // IGNORE always returns true
649 return true;
652 return $res;
656 * INSERT SELECT wrapper
657 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
658 * Source items may be literals rather then field names, but strings should
659 * be quoted with Database::addQuotes()
660 * $conds may be "*" to copy the whole table
661 * srcTable may be an array of tables.
662 * @todo FIXME: Implement this a little better (seperate select/insert)?
664 * @param string $destTable
665 * @param array|string $srcTable
666 * @param array $varMap
667 * @param array $conds
668 * @param string $fname
669 * @param array $insertOptions
670 * @param array $selectOptions
671 * @return bool
673 public function nativeInsertSelect(
674 $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
675 $insertOptions = [], $selectOptions = []
677 $destTable = $this->tableName( $destTable );
679 if ( !is_array( $insertOptions ) ) {
680 $insertOptions = [ $insertOptions ];
684 * If IGNORE is set, we use savepoints to emulate mysql's behavior
685 * Ignore LOW PRIORITY option, since it is MySQL-specific
687 $savepoint = $olde = null;
688 $numrowsinserted = 0;
689 if ( in_array( 'IGNORE', $insertOptions ) ) {
690 $savepoint = new SavepointPostgres( $this, 'mw', $this->queryLogger );
691 $olde = error_reporting( 0 );
692 $savepoint->savepoint();
695 if ( !is_array( $selectOptions ) ) {
696 $selectOptions = [ $selectOptions ];
698 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) =
699 $this->makeSelectOptions( $selectOptions );
700 if ( is_array( $srcTable ) ) {
701 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
702 } else {
703 $srcTable = $this->tableName( $srcTable );
706 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
707 " SELECT $startOpts " . implode( ',', $varMap ) .
708 " FROM $srcTable $useIndex $ignoreIndex ";
710 if ( $conds != '*' ) {
711 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
714 $sql .= " $tailOpts";
716 $res = (bool)$this->query( $sql, $fname, $savepoint );
717 if ( $savepoint ) {
718 $bar = pg_result_error( $this->mLastResult );
719 if ( $bar != false ) {
720 $savepoint->rollback();
721 } else {
722 $savepoint->release();
723 $numrowsinserted++;
725 error_reporting( $olde );
726 $savepoint->commit();
728 // Set the affected row count for the whole operation
729 $this->mAffectedRows = $numrowsinserted;
731 // IGNORE always returns true
732 return true;
735 return $res;
738 public function tableName( $name, $format = 'quoted' ) {
739 // Replace reserved words with better ones
740 $name = $this->remappedTableName( $name );
742 return parent::tableName( $name, $format );
746 * @param string $name
747 * @return string Value of $name or remapped name if $name is a reserved keyword
749 public function remappedTableName( $name ) {
750 return isset( $this->keywordTableMap[$name] ) ? $this->keywordTableMap[$name] : $name;
754 * @param string $name
755 * @param string $format
756 * @return string Qualified and encoded (if requested) table name
758 public function realTableName( $name, $format = 'quoted' ) {
759 return parent::tableName( $name, $format );
762 public function nextSequenceValue( $seqName ) {
763 $safeseq = str_replace( "'", "''", $seqName );
764 $res = $this->query( "SELECT nextval('$safeseq')" );
765 $row = $this->fetchRow( $res );
766 $this->mInsertId = $row[0];
768 return $this->mInsertId;
772 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
774 * @param string $seqName
775 * @return int
777 public function currentSequenceValue( $seqName ) {
778 $safeseq = str_replace( "'", "''", $seqName );
779 $res = $this->query( "SELECT currval('$safeseq')" );
780 $row = $this->fetchRow( $res );
781 $currval = $row[0];
783 return $currval;
786 public function textFieldSize( $table, $field ) {
787 $table = $this->tableName( $table );
788 $sql = "SELECT t.typname as ftype,a.atttypmod as size
789 FROM pg_class c, pg_attribute a, pg_type t
790 WHERE relname='$table' AND a.attrelid=c.oid AND
791 a.atttypid=t.oid and a.attname='$field'";
792 $res = $this->query( $sql );
793 $row = $this->fetchObject( $res );
794 if ( $row->ftype == 'varchar' ) {
795 $size = $row->size - 4;
796 } else {
797 $size = $row->size;
800 return $size;
803 public function limitResult( $sql, $limit, $offset = false ) {
804 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
807 public function wasDeadlock() {
808 return $this->lastErrno() == '40P01';
811 public function duplicateTableStructure(
812 $oldName, $newName, $temporary = false, $fname = __METHOD__
814 $newName = $this->addIdentifierQuotes( $newName );
815 $oldName = $this->addIdentifierQuotes( $oldName );
817 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName " .
818 "(LIKE $oldName INCLUDING DEFAULTS)", $fname );
821 public function listTables( $prefix = null, $fname = __METHOD__ ) {
822 $eschema = $this->addQuotes( $this->getCoreSchema() );
823 $result = $this->query(
824 "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
825 $endArray = [];
827 foreach ( $result as $table ) {
828 $vars = get_object_vars( $table );
829 $table = array_pop( $vars );
830 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
831 $endArray[] = $table;
835 return $endArray;
838 public function timestamp( $ts = 0 ) {
839 $ct = new ConvertibleTimestamp( $ts );
841 return $ct->getTimestamp( TS_POSTGRES );
845 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
846 * to https://secure.php.net/manual/en/ref.pgsql.php
848 * Parsing a postgres array can be a tricky problem, he's my
849 * take on this, it handles multi-dimensional arrays plus
850 * escaping using a nasty regexp to determine the limits of each
851 * data-item.
853 * This should really be handled by PHP PostgreSQL module
855 * @since 1.19
856 * @param string $text Postgreql array returned in a text form like {a,b}
857 * @param string $output
858 * @param int|bool $limit
859 * @param int $offset
860 * @return string
862 private function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
863 if ( false === $limit ) {
864 $limit = strlen( $text ) - 1;
865 $output = [];
867 if ( '{}' == $text ) {
868 return $output;
870 do {
871 if ( '{' != $text[$offset] ) {
872 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
873 $text, $match, 0, $offset );
874 $offset += strlen( $match[0] );
875 $output[] = ( '"' != $match[1][0]
876 ? $match[1]
877 : stripcslashes( substr( $match[1], 1, -1 ) ) );
878 if ( '},' == $match[3] ) {
879 return $output;
881 } else {
882 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
884 } while ( $limit > $offset );
886 return $output;
889 public function aggregateValue( $valuedata, $valuename = 'value' ) {
890 return $valuedata;
893 public function getSoftwareLink() {
894 return '[{{int:version-db-postgres-url}} PostgreSQL]';
898 * Return current schema (executes SELECT current_schema())
899 * Needs transaction
901 * @since 1.19
902 * @return string Default schema for the current session
904 public function getCurrentSchema() {
905 $res = $this->query( "SELECT current_schema()", __METHOD__ );
906 $row = $this->fetchRow( $res );
908 return $row[0];
912 * Return list of schemas which are accessible without schema name
913 * This is list does not contain magic keywords like "$user"
914 * Needs transaction
916 * @see getSearchPath()
917 * @see setSearchPath()
918 * @since 1.19
919 * @return array List of actual schemas for the current sesson
921 public function getSchemas() {
922 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
923 $row = $this->fetchRow( $res );
924 $schemas = [];
926 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
928 return $this->pg_array_parse( $row[0], $schemas );
932 * Return search patch for schemas
933 * This is different from getSchemas() since it contain magic keywords
934 * (like "$user").
935 * Needs transaction
937 * @since 1.19
938 * @return array How to search for table names schemas for the current user
940 public function getSearchPath() {
941 $res = $this->query( "SHOW search_path", __METHOD__ );
942 $row = $this->fetchRow( $res );
944 /* PostgreSQL returns SHOW values as strings */
946 return explode( ",", $row[0] );
950 * Update search_path, values should already be sanitized
951 * Values may contain magic keywords like "$user"
952 * @since 1.19
954 * @param array $search_path List of schemas to be searched by default
956 private function setSearchPath( $search_path ) {
957 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
961 * Determine default schema for the current application
962 * Adjust this session schema search path if desired schema exists
963 * and is not alread there.
965 * We need to have name of the core schema stored to be able
966 * to query database metadata.
968 * This will be also called by the installer after the schema is created
970 * @since 1.19
972 * @param string $desiredSchema
974 public function determineCoreSchema( $desiredSchema ) {
975 $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
976 if ( $this->schemaExists( $desiredSchema ) ) {
977 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
978 $this->mCoreSchema = $desiredSchema;
979 $this->queryLogger->debug(
980 "Schema \"" . $desiredSchema . "\" already in the search path\n" );
981 } else {
983 * Prepend our schema (e.g. 'mediawiki') in front
984 * of the search path
985 * Fixes bug 15816
987 $search_path = $this->getSearchPath();
988 array_unshift( $search_path,
989 $this->addIdentifierQuotes( $desiredSchema ) );
990 $this->setSearchPath( $search_path );
991 $this->mCoreSchema = $desiredSchema;
992 $this->queryLogger->debug(
993 "Schema \"" . $desiredSchema . "\" added to the search path\n" );
995 } else {
996 $this->mCoreSchema = $this->getCurrentSchema();
997 $this->queryLogger->debug(
998 "Schema \"" . $desiredSchema . "\" not found, using current \"" .
999 $this->mCoreSchema . "\"\n" );
1001 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1002 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
1006 * Return schema name for core application tables
1008 * @since 1.19
1009 * @return string Core schema name
1011 public function getCoreSchema() {
1012 return $this->mCoreSchema;
1015 public function getServerVersion() {
1016 if ( !isset( $this->numericVersion ) ) {
1017 $conn = $this->getBindingHandle();
1018 $versionInfo = pg_version( $conn );
1019 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1020 // Old client, abort install
1021 $this->numericVersion = '7.3 or earlier';
1022 } elseif ( isset( $versionInfo['server'] ) ) {
1023 // Normal client
1024 $this->numericVersion = $versionInfo['server'];
1025 } else {
1026 // Bug 16937: broken pgsql extension from PHP<5.3
1027 $this->numericVersion = pg_parameter_status( $conn, 'server_version' );
1031 return $this->numericVersion;
1035 * Query whether a given relation exists (in the given schema, or the
1036 * default mw one if not given)
1037 * @param string $table
1038 * @param array|string $types
1039 * @param bool|string $schema
1040 * @return bool
1042 private function relationExists( $table, $types, $schema = false ) {
1043 if ( !is_array( $types ) ) {
1044 $types = [ $types ];
1046 if ( $schema === false ) {
1047 $schema = $this->getCoreSchema();
1049 $etable = $this->addQuotes( $table );
1050 $eschema = $this->addQuotes( $schema );
1051 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1052 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1053 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1054 $res = $this->query( $sql );
1055 $count = $res ? $res->numRows() : 0;
1057 return (bool)$count;
1061 * For backward compatibility, this function checks both tables and views.
1062 * @param string $table
1063 * @param string $fname
1064 * @param bool|string $schema
1065 * @return bool
1067 public function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1068 return $this->relationExists( $table, [ 'r', 'v' ], $schema );
1071 public function sequenceExists( $sequence, $schema = false ) {
1072 return $this->relationExists( $sequence, 'S', $schema );
1075 public function triggerExists( $table, $trigger ) {
1076 $q = <<<SQL
1077 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1078 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1079 AND tgrelid=pg_class.oid
1080 AND nspname=%s AND relname=%s AND tgname=%s
1081 SQL;
1082 $res = $this->query(
1083 sprintf(
1085 $this->addQuotes( $this->getCoreSchema() ),
1086 $this->addQuotes( $table ),
1087 $this->addQuotes( $trigger )
1090 if ( !$res ) {
1091 return null;
1093 $rows = $res->numRows();
1095 return $rows;
1098 public function ruleExists( $table, $rule ) {
1099 $exists = $this->selectField( 'pg_rules', 'rulename',
1101 'rulename' => $rule,
1102 'tablename' => $table,
1103 'schemaname' => $this->getCoreSchema()
1107 return $exists === $rule;
1110 public function constraintExists( $table, $constraint ) {
1111 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1112 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1113 $this->addQuotes( $this->getCoreSchema() ),
1114 $this->addQuotes( $table ),
1115 $this->addQuotes( $constraint )
1117 $res = $this->query( $sql );
1118 if ( !$res ) {
1119 return null;
1121 $rows = $res->numRows();
1123 return $rows;
1127 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1128 * @param string $schema
1129 * @return bool
1131 public function schemaExists( $schema ) {
1132 if ( !strlen( $schema ) ) {
1133 return false; // short-circuit
1136 $exists = $this->selectField(
1137 '"pg_catalog"."pg_namespace"', 1, [ 'nspname' => $schema ], __METHOD__ );
1139 return (bool)$exists;
1143 * Returns true if a given role (i.e. user) exists, false otherwise.
1144 * @param string $roleName
1145 * @return bool
1147 public function roleExists( $roleName ) {
1148 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1149 [ 'rolname' => $roleName ], __METHOD__ );
1151 return (bool)$exists;
1155 * @var string $table
1156 * @var string $field
1157 * @return PostgresField|null
1159 public function fieldInfo( $table, $field ) {
1160 return PostgresField::fromText( $this, $table, $field );
1164 * pg_field_type() wrapper
1165 * @param ResultWrapper|resource $res ResultWrapper or PostgreSQL query result resource
1166 * @param int $index Field number, starting from 0
1167 * @return string
1169 public function fieldType( $res, $index ) {
1170 if ( $res instanceof ResultWrapper ) {
1171 $res = $res->result;
1174 return pg_field_type( $res, $index );
1177 public function encodeBlob( $b ) {
1178 return new PostgresBlob( pg_escape_bytea( $b ) );
1181 public function decodeBlob( $b ) {
1182 if ( $b instanceof PostgresBlob ) {
1183 $b = $b->fetch();
1184 } elseif ( $b instanceof Blob ) {
1185 return $b->fetch();
1188 return pg_unescape_bytea( $b );
1191 public function strencode( $s ) {
1192 // Should not be called by us
1193 return pg_escape_string( $this->getBindingHandle(), $s );
1196 public function addQuotes( $s ) {
1197 $conn = $this->getBindingHandle();
1199 if ( is_null( $s ) ) {
1200 return 'NULL';
1201 } elseif ( is_bool( $s ) ) {
1202 return intval( $s );
1203 } elseif ( $s instanceof Blob ) {
1204 if ( $s instanceof PostgresBlob ) {
1205 $s = $s->fetch();
1206 } else {
1207 $s = pg_escape_bytea( $conn, $s->fetch() );
1209 return "'$s'";
1212 return "'" . pg_escape_string( $conn, $s ) . "'";
1216 * Postgres specific version of replaceVars.
1217 * Calls the parent version in Database.php
1219 * @param string $ins SQL string, read from a stream (usually tables.sql)
1220 * @return string SQL string
1222 protected function replaceVars( $ins ) {
1223 $ins = parent::replaceVars( $ins );
1225 if ( $this->numericVersion >= 8.3 ) {
1226 // Thanks for not providing backwards-compatibility, 8.3
1227 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1230 if ( $this->numericVersion <= 8.1 ) { // Our minimum version
1231 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1234 return $ins;
1237 public function makeSelectOptions( $options ) {
1238 $preLimitTail = $postLimitTail = '';
1239 $startOpts = $useIndex = $ignoreIndex = '';
1241 $noKeyOptions = [];
1242 foreach ( $options as $key => $option ) {
1243 if ( is_numeric( $key ) ) {
1244 $noKeyOptions[$option] = true;
1248 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1250 $preLimitTail .= $this->makeOrderBy( $options );
1252 // if ( isset( $options['LIMIT'] ) ) {
1253 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1254 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1255 // : false );
1256 // }
1258 if ( isset( $options['FOR UPDATE'] ) ) {
1259 $postLimitTail .= ' FOR UPDATE OF ' .
1260 implode( ', ', array_map( [ &$this, 'tableName' ], $options['FOR UPDATE'] ) );
1261 } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1262 $postLimitTail .= ' FOR UPDATE';
1265 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1266 $startOpts .= 'DISTINCT';
1269 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1272 public function getDBname() {
1273 return $this->mDBname;
1276 public function getServer() {
1277 return $this->mServer;
1280 public function buildConcat( $stringList ) {
1281 return implode( ' || ', $stringList );
1284 public function buildGroupConcatField(
1285 $delimiter, $table, $field, $conds = '', $options = [], $join_conds = []
1287 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1289 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1292 public function buildStringCast( $field ) {
1293 return $field . '::text';
1296 public function streamStatementEnd( &$sql, &$newLine ) {
1297 # Allow dollar quoting for function declarations
1298 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1299 if ( $this->delimiter ) {
1300 $this->delimiter = false;
1301 } else {
1302 $this->delimiter = ';';
1306 return parent::streamStatementEnd( $sql, $newLine );
1309 public function lockIsFree( $lockName, $method ) {
1310 // http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1311 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1312 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1313 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1314 $row = $this->fetchObject( $result );
1316 return ( $row->lockstatus === 't' );
1319 public function lock( $lockName, $method, $timeout = 5 ) {
1320 // http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1321 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1322 $loop = new WaitConditionLoop(
1323 function () use ( $lockName, $key, $timeout, $method ) {
1324 $res = $this->query( "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1325 $row = $this->fetchObject( $res );
1326 if ( $row->lockstatus === 't' ) {
1327 parent::lock( $lockName, $method, $timeout ); // record
1328 return true;
1331 return WaitConditionLoop::CONDITION_CONTINUE;
1333 $timeout
1336 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1339 public function unlock( $lockName, $method ) {
1340 // http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1341 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1342 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1343 $row = $this->fetchObject( $result );
1345 if ( $row->lockstatus === 't' ) {
1346 parent::unlock( $lockName, $method ); // record
1347 return true;
1350 $this->queryLogger->debug( __METHOD__ . " failed to release lock\n" );
1352 return false;
1356 * @param string $lockName
1357 * @return string Integer
1359 private function bigintFromLockName( $lockName ) {
1360 return Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );