MediaWiki  master
DatabasePostgres.php
Go to the documentation of this file.
1 <?php
20 namespace Wikimedia\Rdbms;
21 
22 use RuntimeException;
24 use Wikimedia\WaitConditionLoop;
25 
31 class DatabasePostgres extends Database {
33  private $port;
35  private $tempSchema;
37  private $keywordTableMap;
39  private $numericVersion;
40 
42  private $lastResultHandle;
43 
45  protected $platform;
46 
54  public function __construct( array $params ) {
55  $this->port = intval( $params['port'] ?? null );
56 
57  if ( isset( $params['keywordTableMap'] ) ) {
58  wfDeprecatedMsg( 'Passing keywordTableMap parameter to ' .
59  'DatabasePostgres::__construct() is deprecated', '1.37'
60  );
61 
62  $this->keywordTableMap = $params['keywordTableMap'];
63  }
64 
65  parent::__construct( $params );
66  $this->platform = new PostgresPlatform(
67  $this,
68  $params['queryLogger'],
69  $this->currentDomain
70  );
71  }
72 
73  public function getType() {
74  return 'postgres';
75  }
76 
77  protected function open( $server, $user, $password, $db, $schema, $tablePrefix ) {
78  if ( !function_exists( 'pg_connect' ) ) {
79  throw $this->newExceptionAfterConnectError(
80  "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
81  "option? (Note: if you recently installed PHP, you may need to restart your\n" .
82  "webserver and database)"
83  );
84  }
85 
86  $this->close( __METHOD__ );
87 
88  $connectVars = [
89  // A database must be specified in order to connect to Postgres. If $dbName is not
90  // specified, then use the standard "postgres" database that should exist by default.
91  'dbname' => strlen( $db ) ? $db : 'postgres',
92  'user' => $user,
93  'password' => $password
94  ];
95  if ( strlen( $server ) ) {
96  $connectVars['host'] = $server;
97  }
98  if ( $this->port > 0 ) {
99  $connectVars['port'] = $this->port;
100  }
101  if ( $this->ssl ) {
102  $connectVars['sslmode'] = 'require';
103  }
104  $connectString = $this->makeConnectionString( $connectVars );
105 
106  $this->installErrorHandler();
107  try {
108  $this->conn = pg_connect( $connectString, PGSQL_CONNECT_FORCE_NEW ) ?: null;
109  } catch ( RuntimeException $e ) {
110  $this->restoreErrorHandler();
111  throw $this->newExceptionAfterConnectError( $e->getMessage() );
112  }
113  $error = $this->restoreErrorHandler();
114 
115  if ( !$this->conn ) {
116  throw $this->newExceptionAfterConnectError( $error ?: $this->lastError() );
117  }
118 
119  try {
120  // Since no transaction is active at this point, any SET commands should apply
121  // for the entire session (e.g. will not be reverted on transaction rollback).
122  // See https://www.postgresql.org/docs/8.3/sql-set.html
123  $variables = [
124  'client_encoding' => 'UTF8',
125  'datestyle' => 'ISO, YMD',
126  'timezone' => 'GMT',
127  'standard_conforming_strings' => 'on',
128  'bytea_output' => 'escape',
129  'client_min_messages' => 'ERROR'
130  ];
131  foreach ( $variables as $var => $val ) {
132  $this->query(
133  'SET ' . $this->platform->addIdentifierQuotes( $var ) . ' = ' . $this->addQuotes( $val ),
134  __METHOD__,
135  self::QUERY_NO_RETRY | self::QUERY_CHANGE_TRX
136  );
137  }
138  $this->determineCoreSchema( $schema );
139  $this->currentDomain = new DatabaseDomain( $db, $schema, $tablePrefix );
140  $this->platform->setCurrentDomain( $this->currentDomain );
141  } catch ( RuntimeException $e ) {
142  throw $this->newExceptionAfterConnectError( $e->getMessage() );
143  }
144  }
145 
146  public function databasesAreIndependent() {
147  return true;
148  }
149 
150  public function doSelectDomain( DatabaseDomain $domain ) {
151  if ( $this->getDBname() !== $domain->getDatabase() ) {
152  // Postgres doesn't support selectDB in the same way MySQL does.
153  // So if the DB name doesn't match the open connection, open a new one
154  $this->open(
155  $this->connectionParams[self::CONN_HOST],
156  $this->connectionParams[self::CONN_USER],
157  $this->connectionParams[self::CONN_PASSWORD],
158  $domain->getDatabase(),
159  $domain->getSchema(),
160  $domain->getTablePrefix()
161  );
162  } else {
163  $this->currentDomain = $domain;
164  $this->platform->setCurrentDomain( $this->currentDomain );
165  }
166 
167  return true;
168  }
169 
174  private function makeConnectionString( $vars ) {
175  $s = '';
176  foreach ( $vars as $name => $value ) {
177  $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
178  }
179 
180  return $s;
181  }
182 
183  protected function closeConnection() {
184  return $this->conn ? pg_close( $this->conn ) : true;
185  }
186 
187  public function doSingleStatementQuery( string $sql ): QueryStatus {
188  $conn = $this->getBindingHandle();
189 
190  $sql = mb_convert_encoding( $sql, 'UTF-8' );
191  // Clear any previously left over result
192  while ( $priorRes = pg_get_result( $conn ) ) {
193  pg_free_result( $priorRes );
194  }
195 
196  if ( pg_send_query( $conn, $sql ) === false ) {
197  throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
198  }
199 
200  // Newer PHP versions use PgSql\Result instead of resource variables
201  // https://www.php.net/manual/en/function.pg-get-result.php
202  $pgRes = pg_get_result( $conn );
203  $this->lastResultHandle = $pgRes;
204  $res = pg_result_error( $pgRes ) ? false : $pgRes;
205 
206  return new QueryStatus(
207  is_bool( $res ) ? $res : new PostgresResultWrapper( $this, $conn, $res ),
208  $this->affectedRows(),
209  $this->lastError(),
210  $this->lastErrno()
211  );
212  }
213 
214  protected function doMultiStatementQuery( array $sqls ): array {
215  $qsByStatementId = [];
216 
217  $conn = $this->getBindingHandle();
218  // Clear any previously left over result
219  while ( $pgResultSet = pg_get_result( $conn ) ) {
220  pg_free_result( $pgResultSet );
221  }
222 
223  $combinedSql = mb_convert_encoding( implode( ";\n", $sqls ), 'UTF-8' );
224  pg_send_query( $conn, $combinedSql );
225 
226  reset( $sqls );
227  while ( ( $pgResultSet = pg_get_result( $conn ) ) !== false ) {
228  $this->lastResultHandle = $pgResultSet;
229 
230  $statementId = key( $sqls );
231  if ( $statementId !== null ) {
232  if ( pg_result_error( $pgResultSet ) ) {
233  $res = false;
234  } else {
235  $res = new PostgresResultWrapper( $this, $conn, $pgResultSet );
236  }
237  $qsByStatementId[$statementId] = new QueryStatus(
238  $res,
239  pg_affected_rows( $pgResultSet ),
240  (string)pg_result_error( $pgResultSet ),
241  pg_result_error_field( $pgResultSet, PGSQL_DIAG_SQLSTATE )
242  );
243  }
244  next( $sqls );
245  }
246  // Fill in status for statements aborted due to prior statement failure
247  while ( ( $statementId = key( $sqls ) ) !== null ) {
248  $qsByStatementId[$statementId] = new QueryStatus( false, 0, 'Query aborted', 0 );
249  next( $sqls );
250  }
251 
252  return $qsByStatementId;
253  }
254 
255  protected function dumpError() {
256  $diags = [
257  PGSQL_DIAG_SEVERITY,
258  PGSQL_DIAG_SQLSTATE,
259  PGSQL_DIAG_MESSAGE_PRIMARY,
260  PGSQL_DIAG_MESSAGE_DETAIL,
261  PGSQL_DIAG_MESSAGE_HINT,
262  PGSQL_DIAG_STATEMENT_POSITION,
263  PGSQL_DIAG_INTERNAL_POSITION,
264  PGSQL_DIAG_INTERNAL_QUERY,
265  PGSQL_DIAG_CONTEXT,
266  PGSQL_DIAG_SOURCE_FILE,
267  PGSQL_DIAG_SOURCE_LINE,
268  PGSQL_DIAG_SOURCE_FUNCTION
269  ];
270  foreach ( $diags as $d ) {
271  $this->queryLogger->debug( sprintf( "PgSQL ERROR(%d): %s",
272  $d, pg_result_error_field( $this->lastResultHandle, $d ) ) );
273  }
274  }
275 
276  public function insertId() {
277  $res = $this->query(
278  "SELECT lastval()",
279  __METHOD__,
280  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
281  );
282  $row = $res->fetchRow();
283 
284  // @phan-suppress-next-line PhanTypeMismatchReturnProbablyReal Return type is undefined for no lastval
285  return $row[0] === null ? null : (int)$row[0];
286  }
287 
288  public function lastError() {
289  if ( $this->conn ) {
290  if ( $this->lastResultHandle ) {
291  return pg_result_error( $this->lastResultHandle );
292  } else {
293  return pg_last_error();
294  }
295  }
296 
297  return $this->getLastPHPError() ?: 'No database connection';
298  }
299 
300  public function lastErrno() {
301  if ( $this->lastResultHandle ) {
302  $lastErrno = pg_result_error_field( $this->lastResultHandle, PGSQL_DIAG_SQLSTATE );
303  if ( $lastErrno !== false ) {
304  return $lastErrno;
305  }
306  }
307 
308  return '00000';
309  }
310 
311  protected function fetchAffectedRowCount() {
312  if ( !$this->lastResultHandle ) {
313  return 0;
314  }
315 
316  return pg_affected_rows( $this->lastResultHandle );
317  }
318 
334  public function estimateRowCount( $table, $var = '*', $conds = '',
335  $fname = __METHOD__, $options = [], $join_conds = []
336  ) {
337  $conds = $this->platform->normalizeConditions( $conds, $fname );
338  $column = $this->platform->extractSingleFieldFromList( $var );
339  if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
340  $conds[] = "$column IS NOT NULL";
341  }
342 
343  $options['EXPLAIN'] = true;
344  $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
345  $rows = -1;
346  if ( $res ) {
347  $row = $res->fetchRow();
348  $count = [];
349  if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
350  $rows = (int)$count[1];
351  }
352  }
353 
354  return $rows;
355  }
356 
357  public function indexInfo( $table, $index, $fname = __METHOD__ ) {
358  $res = $this->query(
359  "SELECT indexname FROM pg_indexes WHERE tablename='$table'",
360  $fname,
361  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
362  );
363  if ( !$res ) {
364  return null;
365  }
366  foreach ( $res as $row ) {
367  if ( $row->indexname == $this->indexName( $index ) ) {
368  return $row;
369  }
370  }
371 
372  return false;
373  }
374 
375  public function indexAttributes( $index, $schema = false ) {
376  if ( $schema === false ) {
377  $schemas = $this->getCoreSchemas();
378  } else {
379  $schemas = [ $schema ];
380  }
381 
382  $eindex = $this->addQuotes( $index );
383 
384  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
385  foreach ( $schemas as $schema ) {
386  $eschema = $this->addQuotes( $schema );
387  /*
388  * A subquery would be not needed if we didn't care about the order
389  * of attributes, but we do
390  */
391  $sql = <<<__INDEXATTR__
392 
393  SELECT opcname,
394  attname,
395  i.indoption[s.g] as option,
396  pg_am.amname
397  FROM
398  (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
399  FROM
400  pg_index isub
401  JOIN pg_class cis
402  ON cis.oid=isub.indexrelid
403  JOIN pg_namespace ns
404  ON cis.relnamespace = ns.oid
405  WHERE cis.relname=$eindex AND ns.nspname=$eschema) AS s,
406  pg_attribute,
407  pg_opclass opcls,
408  pg_am,
409  pg_class ci
410  JOIN pg_index i
411  ON ci.oid=i.indexrelid
412  JOIN pg_class ct
413  ON ct.oid = i.indrelid
414  JOIN pg_namespace n
415  ON ci.relnamespace = n.oid
416  WHERE
417  ci.relname=$eindex AND n.nspname=$eschema
418  AND attrelid = ct.oid
419  AND i.indkey[s.g] = attnum
420  AND i.indclass[s.g] = opcls.oid
421  AND pg_am.oid = opcls.opcmethod
422 __INDEXATTR__;
423  $res = $this->query( $sql, __METHOD__, $flags );
424  $a = [];
425  if ( $res ) {
426  foreach ( $res as $row ) {
427  $a[] = [
428  $row->attname,
429  $row->opcname,
430  $row->amname,
431  $row->option ];
432  }
433  return $a;
434  }
435  }
436  return null;
437  }
438 
439  public function indexUnique( $table, $index, $fname = __METHOD__ ) {
440  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
441  $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
442  " AND indexdef LIKE 'CREATE UNIQUE%(" .
443  $this->strencode( $this->indexName( $index ) ) .
444  ")'";
445  $res = $this->query( $sql, $fname, $flags );
446  if ( !$res ) {
447  return false;
448  }
449 
450  return $res->numRows() > 0;
451  }
452 
471  protected function doInsertSelectNative(
472  $destTable,
473  $srcTable,
474  array $varMap,
475  $conds,
476  $fname,
477  array $insertOptions,
478  array $selectOptions,
479  $selectJoinConds
480  ) {
481  if ( in_array( 'IGNORE', $insertOptions ) ) {
482  // Use "ON CONFLICT DO" if we have it for IGNORE
483  $destTable = $this->tableName( $destTable );
484 
485  $selectSql = $this->selectSQLText(
486  $srcTable,
487  array_values( $varMap ),
488  $conds,
489  $fname,
490  $selectOptions,
491  $selectJoinConds
492  );
493 
494  $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
495  $selectSql . ' ON CONFLICT DO NOTHING';
496 
497  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
498  } else {
499  parent::doInsertSelectNative( $destTable, $srcTable, $varMap, $conds, $fname,
500  $insertOptions, $selectOptions, $selectJoinConds );
501  }
502  }
503 
509  public function remappedTableName( $name ) {
510  wfDeprecated( __METHOD__, '1.37' );
511 
512  return $this->keywordTableMap[$name] ?? $name;
513  }
514 
520  public function realTableName( $name, $format = 'quoted' ) {
521  return parent::tableName( $name, $format );
522  }
523 
524  public function nextSequenceValue( $seqName ) {
525  return new NextSequenceValue;
526  }
527 
534  public function currentSequenceValue( $seqName ) {
535  $res = $this->query(
536  "SELECT currval('" . str_replace( "'", "''", $seqName ) . "')",
537  __METHOD__,
538  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
539  );
540  $row = $res->fetchRow();
541  $currval = $row[0];
542 
543  return $currval;
544  }
545 
546  public function textFieldSize( $table, $field ) {
547  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
548  $encTable = $this->tableName( $table );
549  $sql = "SELECT t.typname as ftype,a.atttypmod as size
550  FROM pg_class c, pg_attribute a, pg_type t
551  WHERE relname='$encTable' AND a.attrelid=c.oid AND
552  a.atttypid=t.oid and a.attname='$field'";
553  $res = $this->query( $sql, __METHOD__, $flags );
554  $row = $res->fetchObject();
555  if ( $row->ftype == 'varchar' ) {
556  $size = $row->size - 4;
557  } else {
558  $size = $row->size;
559  }
560 
561  return $size;
562  }
563 
564  public function wasDeadlock() {
565  // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
566  return $this->lastErrno() === '40P01';
567  }
568 
569  public function wasLockTimeout() {
570  // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
571  return $this->lastErrno() === '55P03';
572  }
573 
574  protected function isConnectionError( $errno ) {
575  // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
576  static $codes = [ '08000', '08003', '08006', '08001', '08004', '57P01', '57P03', '53300' ];
577 
578  return in_array( $errno, $codes, true );
579  }
580 
581  protected function isQueryTimeoutError( $errno ) {
582  // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
583  return ( $errno === '57014' );
584  }
585 
586  protected function isKnownStatementRollbackError( $errno ) {
587  return false; // transaction has to be rolled-back from error state
588  }
589 
590  public function duplicateTableStructure(
591  $oldName, $newName, $temporary = false, $fname = __METHOD__
592  ) {
593  $newNameE = $this->platform->addIdentifierQuotes( $newName );
594  $oldNameE = $this->platform->addIdentifierQuotes( $oldName );
595 
596  $temporary = $temporary ? 'TEMPORARY' : '';
597 
598  $ret = $this->query(
599  "CREATE $temporary TABLE $newNameE " .
600  "(LIKE $oldNameE INCLUDING DEFAULTS INCLUDING INDEXES)",
601  $fname,
602  self::QUERY_PSEUDO_PERMANENT | self::QUERY_CHANGE_SCHEMA
603  );
604  if ( !$ret ) {
605  return $ret;
606  }
607 
608  $res = $this->query(
609  'SELECT attname FROM pg_class c'
610  . ' JOIN pg_namespace n ON (n.oid = c.relnamespace)'
611  . ' JOIN pg_attribute a ON (a.attrelid = c.oid)'
612  . ' JOIN pg_attrdef d ON (c.oid=d.adrelid and a.attnum=d.adnum)'
613  . ' WHERE relkind = \'r\''
614  . ' AND nspname = ' . $this->addQuotes( $this->getCoreSchema() )
615  . ' AND relname = ' . $this->addQuotes( $oldName )
616  . ' AND pg_get_expr(adbin, adrelid) LIKE \'nextval(%\'',
617  $fname,
618  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
619  );
620  $row = $res->fetchObject();
621  if ( $row ) {
622  $field = $row->attname;
623  $newSeq = "{$newName}_{$field}_seq";
624  $fieldE = $this->platform->addIdentifierQuotes( $field );
625  $newSeqE = $this->platform->addIdentifierQuotes( $newSeq );
626  $newSeqQ = $this->addQuotes( $newSeq );
627  $this->query(
628  "CREATE $temporary SEQUENCE $newSeqE OWNED BY $newNameE.$fieldE",
629  $fname,
630  self::QUERY_CHANGE_SCHEMA
631  );
632  $this->query(
633  "ALTER TABLE $newNameE ALTER COLUMN $fieldE SET DEFAULT nextval({$newSeqQ}::regclass)",
634  $fname,
635  self::QUERY_CHANGE_SCHEMA
636  );
637  }
638 
639  return $ret;
640  }
641 
642  protected function doTruncate( array $tables, $fname ) {
643  $encTables = $this->tableNamesN( ...$tables );
644  $sql = "TRUNCATE TABLE " . implode( ',', $encTables ) . " RESTART IDENTITY";
645  $this->query( $sql, $fname, self::QUERY_CHANGE_SCHEMA );
646  }
647 
654  public function listTables( $prefix = '', $fname = __METHOD__ ) {
655  $eschemas = implode( ',', array_map( [ $this, 'addQuotes' ], $this->getCoreSchemas() ) );
656  $result = $this->query(
657  "SELECT DISTINCT tablename FROM pg_tables WHERE schemaname IN ($eschemas)",
658  $fname,
659  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
660  );
661  $endArray = [];
662 
663  foreach ( $result as $table ) {
664  $vars = get_object_vars( $table );
665  $table = array_pop( $vars );
666  if ( $prefix == '' || strpos( $table, $prefix ) === 0 ) {
667  $endArray[] = $table;
668  }
669  }
670 
671  return $endArray;
672  }
673 
692  private function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
693  if ( $limit === false ) {
694  $limit = strlen( $text ) - 1;
695  $output = [];
696  }
697  if ( $text == '{}' ) {
698  return $output;
699  }
700  do {
701  if ( $text[$offset] != '{' ) {
702  preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
703  $text, $match, 0, $offset );
704  $offset += strlen( $match[0] );
705  $output[] = ( $match[1][0] != '"'
706  ? $match[1]
707  : stripcslashes( substr( $match[1], 1, -1 ) ) );
708  if ( $match[3] == '},' ) {
709  return $output;
710  }
711  } else {
712  $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
713  }
714  } while ( $limit > $offset );
715 
716  return $output;
717  }
718 
719  public function getSoftwareLink() {
720  return '[{{int:version-db-postgres-url}} PostgreSQL]';
721  }
722 
730  public function getCurrentSchema() {
731  $res = $this->query(
732  "SELECT current_schema()",
733  __METHOD__,
734  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
735  );
736  $row = $res->fetchRow();
737 
738  return $row[0];
739  }
740 
751  public function getSchemas() {
752  $res = $this->query(
753  "SELECT current_schemas(false)",
754  __METHOD__,
755  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
756  );
757  $row = $res->fetchRow();
758  $schemas = [];
759 
760  /* PHP pgsql support does not support array type, "{a,b}" string is returned */
761 
762  return $this->pg_array_parse( $row[0], $schemas );
763  }
764 
774  public function getSearchPath() {
775  $res = $this->query(
776  "SHOW search_path",
777  __METHOD__,
778  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
779  );
780  $row = $res->fetchRow();
781 
782  /* PostgreSQL returns SHOW values as strings */
783 
784  return explode( ",", $row[0] );
785  }
786 
794  private function setSearchPath( $search_path ) {
795  $this->query(
796  "SET search_path = " . implode( ", ", $search_path ),
797  __METHOD__,
798  self::QUERY_CHANGE_TRX
799  );
800  }
801 
816  public function determineCoreSchema( $desiredSchema ) {
817  if ( $this->trxLevel() ) {
818  // We do not want the schema selection to change on ROLLBACK or INSERT SELECT.
819  // See https://www.postgresql.org/docs/8.3/sql-set.html
820  throw new DBUnexpectedError(
821  $this,
822  __METHOD__ . ": a transaction is currently active"
823  );
824  }
825 
826  if ( $this->schemaExists( $desiredSchema ) ) {
827  if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
828  $this->platform->setCoreSchema( $desiredSchema );
829  $this->queryLogger->debug(
830  "Schema \"" . $desiredSchema . "\" already in the search path\n" );
831  } else {
832  // Prepend the desired schema to the search path (T17816)
833  $search_path = $this->getSearchPath();
834  array_unshift( $search_path, $this->platform->addIdentifierQuotes( $desiredSchema ) );
835  $this->setSearchPath( $search_path );
836  $this->platform->setCoreSchema( $desiredSchema );
837  $this->queryLogger->debug(
838  "Schema \"" . $desiredSchema . "\" added to the search path\n" );
839  }
840  } else {
841  $this->platform->setCoreSchema( $this->getCurrentSchema() );
842  $this->queryLogger->debug(
843  "Schema \"" . $desiredSchema . "\" not found, using current \"" .
844  $this->getCoreSchema() . "\"\n" );
845  }
846  }
847 
854  public function getCoreSchema() {
855  return $this->platform->getCoreSchema();
856  }
857 
864  public function getCoreSchemas() {
865  if ( $this->tempSchema ) {
866  return [ $this->tempSchema, $this->getCoreSchema() ];
867  }
868 
869  $res = $this->query(
870  "SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = pg_my_temp_schema()",
871  __METHOD__,
872  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
873  );
874  $row = $res->fetchObject();
875  if ( $row ) {
876  $this->tempSchema = $row->nspname;
877  return [ $this->tempSchema, $this->getCoreSchema() ];
878  }
879 
880  return [ $this->getCoreSchema() ];
881  }
882 
883  public function getServerVersion() {
884  if ( !isset( $this->numericVersion ) ) {
885  $conn = $this->getBindingHandle();
886  $versionInfo = pg_version( $conn );
887  if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
888  // Old client, abort install
889  $this->numericVersion = '7.3 or earlier';
890  } elseif ( isset( $versionInfo['server'] ) ) {
891  // Normal client
892  $this->numericVersion = $versionInfo['server'];
893  } else {
894  // T18937: broken pgsql extension from PHP<5.3
895  $this->numericVersion = pg_parameter_status( $conn, 'server_version' );
896  }
897  }
898 
899  return $this->numericVersion;
900  }
901 
910  private function relationExists( $table, $types, $schema = false ) {
911  if ( !is_array( $types ) ) {
912  $types = [ $types ];
913  }
914  if ( $schema === false ) {
915  $schemas = $this->getCoreSchemas();
916  } else {
917  $schemas = [ $schema ];
918  }
919  $table = $this->realTableName( $table, 'raw' );
920  $etable = $this->addQuotes( $table );
921  foreach ( $schemas as $schema ) {
922  $eschema = $this->addQuotes( $schema );
923  $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
924  . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
925  . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
926  $res = $this->query(
927  $sql,
928  __METHOD__,
929  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
930  );
931  if ( $res && $res->numRows() ) {
932  return true;
933  }
934  }
935 
936  return false;
937  }
938 
946  public function tableExists( $table, $fname = __METHOD__, $schema = false ) {
947  return $this->relationExists( $table, [ 'r', 'v' ], $schema );
948  }
949 
950  public function sequenceExists( $sequence, $schema = false ) {
951  return $this->relationExists( $sequence, 'S', $schema );
952  }
953 
954  public function triggerExists( $table, $trigger ) {
955  $q = <<<SQL
956  SELECT 1 FROM pg_class, pg_namespace, pg_trigger
957  WHERE relnamespace=pg_namespace.oid AND relkind='r'
958  AND tgrelid=pg_class.oid
959  AND nspname=%s AND relname=%s AND tgname=%s
960 SQL;
961  foreach ( $this->getCoreSchemas() as $schema ) {
962  $res = $this->query(
963  sprintf(
964  $q,
965  $this->addQuotes( $schema ),
966  $this->addQuotes( $table ),
967  $this->addQuotes( $trigger )
968  ),
969  __METHOD__,
970  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
971  );
972  if ( $res && $res->numRows() ) {
973  return true;
974  }
975  }
976 
977  return false;
978  }
979 
980  public function ruleExists( $table, $rule ) {
981  $exists = $this->selectField( 'pg_rules', 'rulename',
982  [
983  'rulename' => $rule,
984  'tablename' => $table,
985  'schemaname' => $this->getCoreSchemas()
986  ],
987  __METHOD__
988  );
989 
990  return $exists === $rule;
991  }
992 
993  public function constraintExists( $table, $constraint ) {
994  foreach ( $this->getCoreSchemas() as $schema ) {
995  $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
996  "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
997  $this->addQuotes( $schema ),
998  $this->addQuotes( $table ),
999  $this->addQuotes( $constraint )
1000  );
1001  $res = $this->query(
1002  $sql,
1003  __METHOD__,
1004  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1005  );
1006  if ( $res && $res->numRows() ) {
1007  return true;
1008  }
1009  }
1010  return false;
1011  }
1012 
1018  public function schemaExists( $schema ) {
1019  if ( !strlen( $schema ) ) {
1020  return false; // short-circuit
1021  }
1022 
1023  $res = $this->query(
1024  "SELECT 1 FROM pg_catalog.pg_namespace " .
1025  "WHERE nspname = " . $this->addQuotes( $schema ) . " LIMIT 1",
1026  __METHOD__,
1027  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1028  );
1029 
1030  return ( $res->numRows() > 0 );
1031  }
1032 
1038  public function roleExists( $roleName ) {
1039  $res = $this->query(
1040  "SELECT 1 FROM pg_catalog.pg_roles " .
1041  "WHERE rolname = " . $this->addQuotes( $roleName ) . " LIMIT 1",
1042  __METHOD__,
1043  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1044  );
1045 
1046  return ( $res->numRows() > 0 );
1047  }
1048 
1054  public function fieldInfo( $table, $field ) {
1055  return PostgresField::fromText( $this, $table, $field );
1056  }
1057 
1058  public function encodeBlob( $b ) {
1059  return new PostgresBlob( pg_escape_bytea( $b ) );
1060  }
1061 
1062  public function decodeBlob( $b ) {
1063  if ( $b instanceof PostgresBlob ) {
1064  $b = $b->fetch();
1065  } elseif ( $b instanceof Blob ) {
1066  return $b->fetch();
1067  }
1068 
1069  return pg_unescape_bytea( $b );
1070  }
1071 
1072  public function strencode( $s ) {
1073  // Should not be called by us
1074  return pg_escape_string( $this->getBindingHandle(), (string)$s );
1075  }
1076 
1077  public function addQuotes( $s ) {
1078  $conn = $this->getBindingHandle();
1079 
1080  if ( $s === null ) {
1081  return 'NULL';
1082  } elseif ( is_bool( $s ) ) {
1083  return (string)intval( $s );
1084  } elseif ( is_int( $s ) ) {
1085  return (string)$s;
1086  } elseif ( $s instanceof Blob ) {
1087  if ( $s instanceof PostgresBlob ) {
1088  $s = $s->fetch();
1089  } else {
1090  $s = pg_escape_bytea( $conn, $s->fetch() );
1091  }
1092  return "'$s'";
1093  } elseif ( $s instanceof NextSequenceValue ) {
1094  return 'DEFAULT';
1095  }
1096 
1097  return "'" . pg_escape_string( $conn, (string)$s ) . "'";
1098  }
1099 
1100  public function streamStatementEnd( &$sql, &$newLine ) {
1101  # Allow dollar quoting for function declarations
1102  if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1103  if ( $this->delimiter ) {
1104  $this->delimiter = false;
1105  } else {
1106  $this->delimiter = ';';
1107  }
1108  }
1109 
1110  return parent::streamStatementEnd( $sql, $newLine );
1111  }
1112 
1113  public function doLockIsFree( string $lockName, string $method ) {
1114  $res = $this->query(
1115  $this->platform->lockIsFreeSQLText( $lockName ),
1116  $method,
1117  self::QUERY_CHANGE_LOCKS
1118  );
1119  $row = $res->fetchObject();
1120 
1121  return ( $row->unlocked === 't' );
1122  }
1123 
1124  public function doLock( string $lockName, string $method, int $timeout ) {
1125  $sql = $this->platform->lockSQLText( $lockName, $timeout );
1126 
1127  $acquired = null;
1128  $loop = new WaitConditionLoop(
1129  function () use ( $lockName, $sql, $timeout, $method, &$acquired ) {
1130  $res = $this->query(
1131  $sql,
1132  $method,
1133  self::QUERY_CHANGE_LOCKS
1134  );
1135  $row = $res->fetchObject();
1136 
1137  if ( $row->acquired !== null ) {
1138  $acquired = (float)$row->acquired;
1139 
1140  return WaitConditionLoop::CONDITION_REACHED;
1141  }
1142 
1143  return WaitConditionLoop::CONDITION_CONTINUE;
1144  },
1145  $timeout
1146  );
1147  $loop->invoke();
1148 
1149  return $acquired;
1150  }
1151 
1152  public function doUnlock( string $lockName, string $method ) {
1153  $result = $this->query(
1154  $this->platform->unlockSQLText( $lockName ),
1155  $method,
1156  self::QUERY_CHANGE_LOCKS
1157  );
1158  $row = $result->fetchObject();
1159 
1160  return ( $row->released === 't' );
1161  }
1162 
1163  protected function doFlushSession( $fname ) {
1164  $flags = self::QUERY_CHANGE_LOCKS | self::QUERY_NO_RETRY;
1165 
1166  // https://www.postgresql.org/docs/9.1/functions-admin.html
1167  $sql = "pg_advisory_unlock_all()";
1168  $qs = $this->executeQuery( $sql, __METHOD__, $flags, $sql );
1169  if ( $qs->res === false ) {
1170  $this->reportQueryError( $qs->message, $qs->code, $sql, $fname, true );
1171  }
1172  }
1173 
1174  public function serverIsReadOnly() {
1175  $res = $this->query(
1176  "SHOW default_transaction_read_only",
1177  __METHOD__,
1178  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1179  );
1180  $row = $res->fetchObject();
1181 
1182  return $row ? ( strtolower( $row->default_transaction_read_only ) === 'on' ) : false;
1183  }
1184 
1185  protected static function getAttributes() {
1186  return [ self::ATTR_SCHEMAS_AS_TABLE_GROUPS => true ];
1187  }
1188 }
1189 
1193 class_alias( DatabasePostgres::class, 'DatabasePostgres' );
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
Class to handle database/schema/prefix specifications for IDatabase.
Postgres database abstraction layer.
getCoreSchemas()
Return schema names for temporary tables and core application tables.
determineCoreSchema( $desiredSchema)
Determine default schema for the current application Adjust this session schema search path if desire...
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
Creates a new table with structure copied from existing table.Note that unlike most database abstract...
isQueryTimeoutError( $errno)
Checks whether the cause of the error is detected to be a timeout.
doLock(string $lockName, string $method, int $timeout)
insertId()
Get the inserted value of an auto-increment row.
indexAttributes( $index, $schema=false)
databasesAreIndependent()
Returns true if DBs are assumed to be on potentially different servers.In systems like mysql/mariadb,...
doUnlock(string $lockName, string $method)
doSingleStatementQuery(string $sql)
Run a query and return a QueryStatus instance with the query result information.
streamStatementEnd(&$sql, &$newLine)
Called by sourceStream() to check if we've reached a statement end.
doLockIsFree(string $lockName, string $method)
nextSequenceValue( $seqName)
Deprecated method, calls should be removed.
doSelectDomain(DatabaseDomain $domain)
roleExists( $roleName)
Returns true if a given role (i.e.
getSchemas()
Return list of schemas which are accessible without schema name This is list does not contain magic k...
indexInfo( $table, $index, $fname=__METHOD__)
Get information about an index into an object.
schemaExists( $schema)
Query whether a given schema exists.
estimateRowCount( $table, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Estimate rows in dataset Returns estimated count, based on EXPLAIN output This is not necessarily an ...
lastError()
Get the RDBMS-specific error description from the last query statement.
addQuotes( $s)
Escape and quote a raw value string for use in a SQL query.stringStability: stableto override
sequenceExists( $sequence, $schema=false)
wasDeadlock()
Determines if the last failure was due to a deadlock.Note that during a deadlock, the prior transacti...
doTruncate(array $tables, $fname)
currentSequenceValue( $seqName)
Return the current value of a sequence.
doMultiStatementQuery(array $sqls)
Execute a batch of query statements, aborting remaining statements if one fails.
lastErrno()
Get the RDBMS-specific error code from the last query statement.
getCoreSchema()
Return schema name for core application tables.
strencode( $s)
Wrapper for addslashes()
wasLockTimeout()
Determines if the last failure was due to a lock timeout.Note that during a lock wait timeout,...
isConnectionError( $errno)
Do not use this method outside of Database/DBError classes.
indexUnique( $table, $index, $fname=__METHOD__)
Determines if a given index is unique.Calling function nameboolStability: stableto override
open( $server, $user, $password, $db, $schema, $tablePrefix)
Open a new connection to the database (closing any existing one)
getServerVersion()
A string describing the current software version, like from mysql_get_server_info()
textFieldSize( $table, $field)
Returns the size of a text field, or -1 for "unlimited".intStability: stableto override
getCurrentSchema()
Return current schema (executes SELECT current_schema()) Needs transaction.
getSearchPath()
Return search patch for schemas This is different from getSchemas() since it contain magic keywords (...
tableExists( $table, $fname=__METHOD__, $schema=false)
For backward compatibility, this function checks both tables and views.
decodeBlob( $b)
Some DBMSs return a special placeholder object representing blob fields in result objects....
encodeBlob( $b)
Some DBMSs have a special format for inserting into blob fields, they don't allow simple quoted strin...
realTableName( $name, $format='quoted')
closeConnection()
Closes underlying database connection.
constraintExists( $table, $constraint)
getType()
Get the RDBMS type of the server (e.g.
doFlushSession( $fname)
Reset the server-side session state for named locks and table locks.
listTables( $prefix='', $fname=__METHOD__)
getSoftwareLink()
Returns a wikitext style link to the DB's website (e.g.
doInsertSelectNative( $destTable, $srcTable, array $varMap, $conds, $fname, array $insertOptions, array $selectOptions, $selectJoinConds)
INSERT SELECT wrapper $varMap must be an associative array of the form [ 'dest1' => 'source1',...
serverIsReadOnly()
bool Whether the DB is marked as read-only server-side If an error occurs, {query} 1....
Relational database abstraction object.
Definition: Database.php:44
string null $password
Password used to establish the current connection.
Definition: Database.php:79
restoreErrorHandler()
Restore the previous error handler and return the last PHP error for this DB.
Definition: Database.php:752
object resource null $conn
Database connection.
Definition: Database.php:69
newExceptionAfterConnectError( $error)
Definition: Database.php:1750
installErrorHandler()
Set a custom error handler for logging errors during database connection.
Definition: Database.php:741
affectedRows()
Get the number of rows affected by the last write query.
Definition: Database.php:3118
string null $server
Server that this instance is currently connected to.
Definition: Database.php:75
close( $fname=__METHOD__)
Close the database connection.
Definition: Database.php:804
string null $user
User that this instance is currently connected under the name of.
Definition: Database.php:77
query( $sql, $fname=__METHOD__, $flags=0)
Run an SQL query statement and return the result.
Definition: Database.php:1056
getBindingHandle()
Get the underlying binding connection handle.
Definition: Database.php:3694
getDBname()
Get the current database name; null if there isn't one.
Definition: Database.php:2014
Used by Database::nextSequenceValue() so Database::insert() can detect values coming from the depreca...
while(( $__line=Maintenance::readconsole()) !==false) print n
Definition: eval.php:69
foreach( $mmfl['setupFiles'] as $fileName) if( $queue) if(empty( $mmfl['quiet'])) $s
return true
Definition: router.php:90