MediaWiki  master
DatabasePostgres.php
Go to the documentation of this file.
1 <?php
20 namespace Wikimedia\Rdbms;
21 
22 use RuntimeException;
25 use Wikimedia\WaitConditionLoop;
26 
32 class DatabasePostgres extends Database {
34  private $port;
36  private $tempSchema;
38  private $numericVersion;
39 
41  private $lastResultHandle;
42 
44  protected $platform;
45 
51  public function __construct( array $params ) {
52  $this->port = intval( $params['port'] ?? null );
53  parent::__construct( $params );
54 
55  $this->platform = new PostgresPlatform(
56  $this,
57  $this->logger,
58  $this->currentDomain,
59  $this->errorLogger
60  );
61  $this->replicationReporter = new ReplicationReporter(
62  $params['topologyRole'],
63  $this->logger,
64  $params['srvCache']
65  );
66  }
67 
68  public function getType() {
69  return 'postgres';
70  }
71 
72  protected function open( $server, $user, $password, $db, $schema, $tablePrefix ) {
73  if ( !function_exists( 'pg_connect' ) ) {
74  throw $this->newExceptionAfterConnectError(
75  "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
76  "option? (Note: if you recently installed PHP, you may need to restart your\n" .
77  "webserver and database)"
78  );
79  }
80 
81  $this->close( __METHOD__ );
82 
83  $connectVars = [
84  // A database must be specified in order to connect to Postgres. If $dbName is not
85  // specified, then use the standard "postgres" database that should exist by default.
86  'dbname' => ( $db !== null && $db !== '' ) ? $db : 'postgres',
87  'user' => $user,
88  'password' => $password
89  ];
90  if ( $server !== null && $server !== '' ) {
91  $connectVars['host'] = $server;
92  }
93  if ( $this->port > 0 ) {
94  $connectVars['port'] = $this->port;
95  }
96  if ( $this->ssl ) {
97  $connectVars['sslmode'] = 'require';
98  }
99  $connectString = $this->makeConnectionString( $connectVars );
100 
101  $this->installErrorHandler();
102  try {
103  $this->conn = pg_connect( $connectString, PGSQL_CONNECT_FORCE_NEW ) ?: null;
104  } catch ( RuntimeException $e ) {
105  $this->restoreErrorHandler();
106  throw $this->newExceptionAfterConnectError( $e->getMessage() );
107  }
108  $error = $this->restoreErrorHandler();
109 
110  if ( !$this->conn ) {
111  throw $this->newExceptionAfterConnectError( $error ?: $this->lastError() );
112  }
113 
114  try {
115  // Since no transaction is active at this point, any SET commands should apply
116  // for the entire session (e.g. will not be reverted on transaction rollback).
117  // See https://www.postgresql.org/docs/8.3/sql-set.html
118  $variables = [
119  'client_encoding' => 'UTF8',
120  'datestyle' => 'ISO, YMD',
121  'timezone' => 'GMT',
122  'standard_conforming_strings' => 'on',
123  'bytea_output' => 'escape',
124  'client_min_messages' => 'ERROR'
125  ];
126  foreach ( $variables as $var => $val ) {
127  $sql = 'SET ' . $this->platform->addIdentifierQuotes( $var ) . ' = ' . $this->addQuotes( $val );
128  $query = new Query( $sql, self::QUERY_NO_RETRY | self::QUERY_CHANGE_TRX, 'SET', [] );
129  $this->query( $query, __METHOD__ );
130  }
131  $this->determineCoreSchema( $schema );
132  $this->currentDomain = new DatabaseDomain( $db, $schema, $tablePrefix );
133  $this->platform->setCurrentDomain( $this->currentDomain );
134  } catch ( RuntimeException $e ) {
135  throw $this->newExceptionAfterConnectError( $e->getMessage() );
136  }
137  }
138 
139  public function databasesAreIndependent() {
140  return true;
141  }
142 
143  public function doSelectDomain( DatabaseDomain $domain ) {
144  $database = $domain->getDatabase();
145  if ( $database === null ) {
146  // A null database means "don't care" so leave it as is and update the table prefix
147  $this->currentDomain = new DatabaseDomain(
148  $this->currentDomain->getDatabase(),
149  $domain->getSchema() ?? $this->currentDomain->getSchema(),
150  $domain->getTablePrefix()
151  );
152  $this->platform->setCurrentDomain( $this->currentDomain );
153  } elseif ( $this->getDBname() !== $database ) {
154  // Postgres doesn't support selectDB in the same way MySQL does.
155  // So if the DB name doesn't match the open connection, open a new one
156  $this->open(
157  $this->connectionParams[self::CONN_HOST],
158  $this->connectionParams[self::CONN_USER],
159  $this->connectionParams[self::CONN_PASSWORD],
160  $database,
161  $domain->getSchema(),
162  $domain->getTablePrefix()
163  );
164  } else {
165  $this->currentDomain = $domain;
166  $this->platform->setCurrentDomain( $this->currentDomain );
167  }
168 
169  return true;
170  }
171 
176  private function makeConnectionString( $vars ) {
177  $s = '';
178  foreach ( $vars as $name => $value ) {
179  $s .= "$name='" . str_replace( [ "\\", "'" ], [ "\\\\", "\\'" ], $value ) . "' ";
180  }
181 
182  return $s;
183  }
184 
185  protected function closeConnection() {
186  return $this->conn ? pg_close( $this->conn ) : true;
187  }
188 
189  public function doSingleStatementQuery( string $sql ): QueryStatus {
190  $conn = $this->getBindingHandle();
191 
192  $sql = mb_convert_encoding( $sql, 'UTF-8' );
193  // Clear any previously left over result
194  while ( $priorRes = pg_get_result( $conn ) ) {
195  pg_free_result( $priorRes );
196  }
197 
198  if ( pg_send_query( $conn, $sql ) === false ) {
199  throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
200  }
201 
202  // Newer PHP versions use PgSql\Result instead of resource variables
203  // https://www.php.net/manual/en/function.pg-get-result.php
204  $pgRes = pg_get_result( $conn );
205  $this->lastResultHandle = $pgRes;
206  $res = pg_result_error( $pgRes ) ? false : $pgRes;
207 
208  return new QueryStatus(
209  is_bool( $res ) ? $res : new PostgresResultWrapper( $this, $conn, $res ),
210  $pgRes ? pg_affected_rows( $pgRes ) : 0,
211  $this->lastError(),
212  $this->lastErrno()
213  );
214  }
215 
216  protected function dumpError() {
217  $diags = [
218  PGSQL_DIAG_SEVERITY,
219  PGSQL_DIAG_SQLSTATE,
220  PGSQL_DIAG_MESSAGE_PRIMARY,
221  PGSQL_DIAG_MESSAGE_DETAIL,
222  PGSQL_DIAG_MESSAGE_HINT,
223  PGSQL_DIAG_STATEMENT_POSITION,
224  PGSQL_DIAG_INTERNAL_POSITION,
225  PGSQL_DIAG_INTERNAL_QUERY,
226  PGSQL_DIAG_CONTEXT,
227  PGSQL_DIAG_SOURCE_FILE,
228  PGSQL_DIAG_SOURCE_LINE,
229  PGSQL_DIAG_SOURCE_FUNCTION
230  ];
231  foreach ( $diags as $d ) {
232  $this->logger->debug( sprintf( "PgSQL ERROR(%d): %s",
233  $d, pg_result_error_field( $this->lastResultHandle, $d ) ) );
234  }
235  }
236 
237  protected function lastInsertId() {
238  // Avoid using query() to prevent unwanted side-effects like changing affected
239  // row counts or connection retries. Note that lastval() is connection-specific.
240  // Note that this causes "lastval is not yet defined in this session" errors if
241  // nextval() was never directly or implicitly triggered (error out any transaction).
242  $qs = $this->doSingleStatementQuery( "SELECT lastval() AS id" );
243 
244  return $qs->res ? (int)$qs->res->fetchRow()['id'] : 0;
245  }
246 
247  public function lastError() {
248  if ( $this->conn ) {
249  if ( $this->lastResultHandle ) {
250  return pg_result_error( $this->lastResultHandle );
251  } else {
252  return pg_last_error() ?: $this->lastConnectError;
253  }
254  }
255 
256  return $this->getLastPHPError() ?: 'No database connection';
257  }
258 
259  public function lastErrno() {
260  if ( $this->lastResultHandle ) {
261  $lastErrno = pg_result_error_field( $this->lastResultHandle, PGSQL_DIAG_SQLSTATE );
262  if ( $lastErrno !== false ) {
263  return $lastErrno;
264  }
265  }
266 
267  return '00000';
268  }
269 
285  public function estimateRowCount( $table, $var = '*', $conds = '',
286  $fname = __METHOD__, $options = [], $join_conds = []
287  ) {
288  $conds = $this->platform->normalizeConditions( $conds, $fname );
289  $column = $this->platform->extractSingleFieldFromList( $var );
290  if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
291  $conds[] = "$column IS NOT NULL";
292  }
293 
294  $options['EXPLAIN'] = true;
295  $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
296  $rows = -1;
297  if ( $res ) {
298  $row = $res->fetchRow();
299  $count = [];
300  if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
301  $rows = (int)$count[1];
302  }
303  }
304 
305  return $rows;
306  }
307 
308  public function indexInfo( $table, $index, $fname = __METHOD__ ) {
309  $query = new Query(
310  "SELECT indexname FROM pg_indexes WHERE tablename='$table'",
311  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
312  'SELECT',
313  [ $table ]
314  );
315  $res = $this->query( $query );
316  if ( !$res ) {
317  return null;
318  }
319  foreach ( $res as $row ) {
320  if ( $row->indexname == $this->platform->indexName( $index ) ) {
321  return $row;
322  }
323  }
324 
325  return false;
326  }
327 
328  public function indexAttributes( $index, $schema = false ) {
329  if ( $schema === false ) {
330  $schemas = $this->getCoreSchemas();
331  } else {
332  $schemas = [ $schema ];
333  }
334 
335  $eindex = $this->addQuotes( $index );
336 
337  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
338  foreach ( $schemas as $schema ) {
339  $eschema = $this->addQuotes( $schema );
340  /*
341  * A subquery would be not needed if we didn't care about the order
342  * of attributes, but we do
343  */
344  $sql = <<<__INDEXATTR__
345 
346  SELECT opcname,
347  attname,
348  i.indoption[s.g] as option,
349  pg_am.amname
350  FROM
351  (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
352  FROM
353  pg_index isub
354  JOIN pg_class cis
355  ON cis.oid=isub.indexrelid
356  JOIN pg_namespace ns
357  ON cis.relnamespace = ns.oid
358  WHERE cis.relname=$eindex AND ns.nspname=$eschema) AS s,
359  pg_attribute,
360  pg_opclass opcls,
361  pg_am,
362  pg_class ci
363  JOIN pg_index i
364  ON ci.oid=i.indexrelid
365  JOIN pg_class ct
366  ON ct.oid = i.indrelid
367  JOIN pg_namespace n
368  ON ci.relnamespace = n.oid
369  WHERE
370  ci.relname=$eindex AND n.nspname=$eschema
371  AND attrelid = ct.oid
372  AND i.indkey[s.g] = attnum
373  AND i.indclass[s.g] = opcls.oid
374  AND pg_am.oid = opcls.opcmethod
375 __INDEXATTR__;
376  $query = new Query( $sql, $flags, 'SELECT', [ 'pg_index', 'pg_class', 'pg_namespace' ] );
377  $res = $this->query( $query, __METHOD__ );
378  $a = [];
379  if ( $res ) {
380  foreach ( $res as $row ) {
381  $a[] = [
382  $row->attname,
383  $row->opcname,
384  $row->amname,
385  $row->option ];
386  }
387  return $a;
388  }
389  }
390  return null;
391  }
392 
393  public function indexUnique( $table, $index, $fname = __METHOD__ ) {
394  $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
395  " AND indexdef LIKE 'CREATE UNIQUE%(" .
396  $this->strencode( $this->platform->indexName( $index ) ) .
397  ")'";
398  $query = new Query( $sql, self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE, 'SELECT', [ 'pg_indexes' ] );
399  $res = $this->query( $query, $fname );
400  return $res && $res->numRows() > 0;
401  }
402 
421  protected function doInsertSelectNative(
422  $destTable,
423  $srcTable,
424  array $varMap,
425  $conds,
426  $fname,
427  array $insertOptions,
428  array $selectOptions,
429  $selectJoinConds
430  ) {
431  if ( in_array( 'IGNORE', $insertOptions ) ) {
432  // Use "ON CONFLICT DO" if we have it for IGNORE
433  $destTableEnc = $this->tableName( $destTable );
434 
435  $selectSql = $this->selectSQLText(
436  $srcTable,
437  array_values( $varMap ),
438  $conds,
439  $fname,
440  $selectOptions,
441  $selectJoinConds
442  );
443 
444  $sql = "INSERT INTO $destTableEnc (" . implode( ',', array_keys( $varMap ) ) . ') ' .
445  $selectSql . ' ON CONFLICT DO NOTHING';
446  $query = new Query( $sql, self::QUERY_CHANGE_ROWS, 'INSERT', [ $destTable, $srcTable ] );
447  $this->query( $query, $fname );
448  } else {
449  parent::doInsertSelectNative( $destTable, $srcTable, $varMap, $conds, $fname,
450  $insertOptions, $selectOptions, $selectJoinConds );
451  }
452  }
453 
459  public function realTableName( $name, $format = 'quoted' ) {
460  return parent::tableName( $name, $format );
461  }
462 
463  public function nextSequenceValue( $seqName ) {
464  return new NextSequenceValue;
465  }
466 
471  public function getValueTypesForWithClause( $table ) {
472  $typesByColumn = [];
473 
474  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
475  $encTable = $this->addQuotes( $table );
476  foreach ( $this->getCoreSchemas() as $schema ) {
477  $encSchema = $this->addQuotes( $schema );
478  $sql = "SELECT column_name,udt_name " .
479  "FROM information_schema.columns " .
480  "WHERE table_name = $encTable AND table_schema = $encSchema";
481  $query = new Query( $sql, $flags, 'SELECT', [ $table ] );
482  $res = $this->query( $query, __METHOD__ );
483  if ( $res->numRows() ) {
484  foreach ( $res as $row ) {
485  $typesByColumn[$row->column_name] = $row->udt_name;
486  }
487  break;
488  }
489  }
490 
491  return $typesByColumn;
492  }
493 
494  public function textFieldSize( $table, $field ) {
495  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
496  $encTable = $this->tableName( $table );
497  $sql = "SELECT t.typname as ftype,a.atttypmod as size
498  FROM pg_class c, pg_attribute a, pg_type t
499  WHERE relname='$encTable' AND a.attrelid=c.oid AND
500  a.atttypid=t.oid and a.attname='$field'";
501  $query = new Query( $sql, $flags, 'SELECT', [ $table ] );
502  $res = $this->query( $query, __METHOD__ );
503  $row = $res->fetchObject();
504  if ( $row->ftype == 'varchar' ) {
505  $size = $row->size - 4;
506  } else {
507  $size = $row->size;
508  }
509 
510  return $size;
511  }
512 
513  public function wasDeadlock() {
514  // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
515  return $this->lastErrno() === '40P01';
516  }
517 
518  protected function isConnectionError( $errno ) {
519  // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
520  static $codes = [ '08000', '08003', '08006', '08001', '08004', '57P01', '57P03', '53300' ];
521 
522  return in_array( $errno, $codes, true );
523  }
524 
525  protected function isQueryTimeoutError( $errno ) {
526  // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
527  return ( $errno === '57014' );
528  }
529 
530  protected function isKnownStatementRollbackError( $errno ) {
531  return false; // transaction has to be rolled-back from error state
532  }
533 
534  public function duplicateTableStructure(
535  $oldName, $newName, $temporary = false, $fname = __METHOD__
536  ) {
537  $newNameE = $this->platform->addIdentifierQuotes( $newName );
538  $oldNameE = $this->platform->addIdentifierQuotes( $oldName );
539 
540  $temporary = $temporary ? 'TEMPORARY' : '';
541  $query = new Query(
542  "CREATE $temporary TABLE $newNameE " .
543  "(LIKE $oldNameE INCLUDING DEFAULTS INCLUDING INDEXES)",
544  self::QUERY_PSEUDO_PERMANENT | self::QUERY_CHANGE_SCHEMA,
545  'SELECT',
546  [ $newName ]
547  );
548  $ret = $this->query( $query, $fname );
549  if ( !$ret ) {
550  return $ret;
551  }
552 
553  $sql = 'SELECT attname FROM pg_class c'
554  . ' JOIN pg_namespace n ON (n.oid = c.relnamespace)'
555  . ' JOIN pg_attribute a ON (a.attrelid = c.oid)'
556  . ' JOIN pg_attrdef d ON (c.oid=d.adrelid and a.attnum=d.adnum)'
557  . ' WHERE relkind = \'r\''
558  . ' AND nspname = ' . $this->addQuotes( $this->getCoreSchema() )
559  . ' AND relname = ' . $this->addQuotes( $oldName )
560  . ' AND pg_get_expr(adbin, adrelid) LIKE \'nextval(%\'';
561  $query = new Query(
562  $sql,
563  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
564  'SELECT',
565  [ 'pg_class', 'pg_namespace', 'pg_attribute', 'pg_attrdef' ]
566  );
567 
568  $res = $this->query( $query, $fname );
569  $row = $res->fetchObject();
570  if ( $row ) {
571  $field = $row->attname;
572  $newSeq = "{$newName}_{$field}_seq";
573  $fieldE = $this->platform->addIdentifierQuotes( $field );
574  $newSeqE = $this->platform->addIdentifierQuotes( $newSeq );
575  $newSeqQ = $this->addQuotes( $newSeq );
576  $query = new Query(
577  "CREATE $temporary SEQUENCE $newSeqE OWNED BY $newNameE.$fieldE",
578  self::QUERY_CHANGE_SCHEMA,
579  'CREATE',
580  [ $newName ]
581  );
582  $this->query( $query, $fname );
583  $query = new Query(
584  "ALTER TABLE $newNameE ALTER COLUMN $fieldE SET DEFAULT nextval({$newSeqQ}::regclass)",
585  self::QUERY_CHANGE_SCHEMA,
586  'ALTER',
587  [ $newName ]
588  );
589  $this->query( $query, $fname );
590  }
591 
592  return $ret;
593  }
594 
595  protected function doTruncate( array $tables, $fname ) {
596  $encTables = $this->tableNamesN( ...$tables );
597  $query = new Query(
598  "TRUNCATE TABLE " . implode( ',', $encTables ) . " RESTART IDENTITY",
599  self::QUERY_CHANGE_SCHEMA,
600  'TRUNCATE',
601  $tables
602  );
603  $this->query( $query, $fname );
604  }
605 
612  public function listTables( $prefix = '', $fname = __METHOD__ ) {
613  $eschemas = implode( ',', array_map( [ $this, 'addQuotes' ], $this->getCoreSchemas() ) );
614  $query = new Query(
615  "SELECT DISTINCT tablename FROM pg_tables WHERE schemaname IN ($eschemas)",
616  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
617  'SELECT',
618  'pg_tables'
619  );
620  $result = $this->query( $query, $fname );
621  $endArray = [];
622 
623  foreach ( $result as $table ) {
624  $vars = get_object_vars( $table );
625  $table = array_pop( $vars );
626  if ( $prefix == '' || strpos( $table, $prefix ) === 0 ) {
627  $endArray[] = $table;
628  }
629  }
630 
631  return $endArray;
632  }
633 
652  private function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
653  if ( $limit === false ) {
654  $limit = strlen( $text ) - 1;
655  $output = [];
656  }
657  if ( $text == '{}' ) {
658  return $output;
659  }
660  do {
661  if ( $text[$offset] != '{' ) {
662  preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
663  $text, $match, 0, $offset );
664  $offset += strlen( $match[0] );
665  $output[] = ( $match[1][0] != '"'
666  ? $match[1]
667  : stripcslashes( substr( $match[1], 1, -1 ) ) );
668  if ( $match[3] == '},' ) {
669  return $output;
670  }
671  } else {
672  $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
673  }
674  } while ( $limit > $offset );
675 
676  return $output;
677  }
678 
679  public function getSoftwareLink() {
680  return '[{{int:version-db-postgres-url}} PostgreSQL]';
681  }
682 
690  public function getCurrentSchema() {
691  $query = new Query(
692  "SELECT current_schema()",
693  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
694  'SELECT'
695  );
696  $res = $this->query( $query, __METHOD__ );
697  $row = $res->fetchRow();
698 
699  return $row[0];
700  }
701 
712  public function getSchemas() {
713  $query = new Query(
714  "SELECT current_schemas(false)",
715  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
716  'SELECT'
717  );
718  $res = $this->query( $query, __METHOD__ );
719  $row = $res->fetchRow();
720  $schemas = [];
721 
722  /* PHP pgsql support does not support array type, "{a,b}" string is returned */
723 
724  return $this->pg_array_parse( $row[0], $schemas );
725  }
726 
736  public function getSearchPath() {
737  $query = new Query(
738  "SHOW search_path",
739  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
740  'SHOW'
741  );
742  $res = $this->query( $query, __METHOD__ );
743  $row = $res->fetchRow();
744 
745  /* PostgreSQL returns SHOW values as strings */
746 
747  return explode( ",", $row[0] );
748  }
749 
757  private function setSearchPath( $search_path ) {
758  $query = new Query(
759  "SET search_path = " . implode( ", ", $search_path ),
760  self::QUERY_CHANGE_TRX,
761  'SET'
762  );
763  $this->query( $query, __METHOD__ );
764  }
765 
780  public function determineCoreSchema( $desiredSchema ) {
781  if ( $this->trxLevel() ) {
782  // We do not want the schema selection to change on ROLLBACK or INSERT SELECT.
783  // See https://www.postgresql.org/docs/8.3/sql-set.html
784  throw new DBUnexpectedError(
785  $this,
786  __METHOD__ . ": a transaction is currently active"
787  );
788  }
789 
790  if ( $this->schemaExists( $desiredSchema ) ) {
791  if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
792  $this->platform->setCoreSchema( $desiredSchema );
793  $this->logger->debug(
794  "Schema \"" . $desiredSchema . "\" already in the search path\n" );
795  } else {
796  // Prepend the desired schema to the search path (T17816)
797  $search_path = $this->getSearchPath();
798  array_unshift( $search_path, $this->platform->addIdentifierQuotes( $desiredSchema ) );
799  $this->setSearchPath( $search_path );
800  $this->platform->setCoreSchema( $desiredSchema );
801  $this->logger->debug(
802  "Schema \"" . $desiredSchema . "\" added to the search path\n" );
803  }
804  } else {
805  $this->platform->setCoreSchema( $this->getCurrentSchema() );
806  $this->logger->debug(
807  "Schema \"" . $desiredSchema . "\" not found, using current \"" .
808  $this->getCoreSchema() . "\"\n" );
809  }
810  }
811 
818  public function getCoreSchema() {
819  return $this->platform->getCoreSchema();
820  }
821 
828  public function getCoreSchemas() {
829  if ( $this->tempSchema ) {
830  return [ $this->tempSchema, $this->getCoreSchema() ];
831  }
832  $query = new Query(
833  "SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = pg_my_temp_schema()",
834  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
835  'SELECT',
836  'pg_catalog'
837  );
838  $res = $this->query( $query, __METHOD__ );
839  $row = $res->fetchObject();
840  if ( $row ) {
841  $this->tempSchema = $row->nspname;
842  return [ $this->tempSchema, $this->getCoreSchema() ];
843  }
844 
845  return [ $this->getCoreSchema() ];
846  }
847 
848  public function getServerVersion() {
849  if ( !isset( $this->numericVersion ) ) {
850  $conn = $this->getBindingHandle();
851  $versionInfo = pg_version( $conn );
852  if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
853  // Old client, abort install
854  $this->numericVersion = '7.3 or earlier';
855  } elseif ( isset( $versionInfo['server'] ) ) {
856  // Normal client
857  $this->numericVersion = $versionInfo['server'];
858  } else {
859  // T18937: broken pgsql extension from PHP<5.3
860  $this->numericVersion = pg_parameter_status( $conn, 'server_version' );
861  }
862  }
863 
864  return $this->numericVersion;
865  }
866 
875  private function relationExists( $table, $types, $schema = false ) {
876  if ( !is_array( $types ) ) {
877  $types = [ $types ];
878  }
879  if ( $schema === false ) {
880  $schemas = $this->getCoreSchemas();
881  } else {
882  $schemas = [ $schema ];
883  }
884  $table = $this->realTableName( $table, 'raw' );
885  $etable = $this->addQuotes( $table );
886  foreach ( $schemas as $schema ) {
887  $eschema = $this->addQuotes( $schema );
888  $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
889  . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
890  . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
891  $query = new Query(
892  $sql,
893  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
894  'SELECT',
895  'pg_catalog'
896  );
897  $res = $this->query( $query, __METHOD__ );
898  if ( $res && $res->numRows() ) {
899  return true;
900  }
901  }
902 
903  return false;
904  }
905 
913  public function tableExists( $table, $fname = __METHOD__, $schema = false ) {
914  return $this->relationExists( $table, [ 'r', 'v' ], $schema );
915  }
916 
917  public function sequenceExists( $sequence, $schema = false ) {
918  return $this->relationExists( $sequence, 'S', $schema );
919  }
920 
921  public function constraintExists( $table, $constraint ) {
922  foreach ( $this->getCoreSchemas() as $schema ) {
923  $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
924  "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
925  $this->addQuotes( $schema ),
926  $this->addQuotes( $table ),
927  $this->addQuotes( $constraint )
928  );
929  $query = new Query(
930  $sql,
931  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
932  'SELECT',
933  $table
934  );
935  $res = $this->query( $query, __METHOD__ );
936  if ( $res && $res->numRows() ) {
937  return true;
938  }
939  }
940  return false;
941  }
942 
948  public function schemaExists( $schema ) {
949  if ( !strlen( $schema ?? '' ) ) {
950  return false; // short-circuit
951  }
952  $query = new Query(
953  "SELECT 1 FROM pg_catalog.pg_namespace " .
954  "WHERE nspname = " . $this->addQuotes( $schema ) . " LIMIT 1",
955  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
956  'SELECT',
957  'pg_catalog'
958  );
959  $res = $this->query( $query, __METHOD__ );
960 
961  return ( $res->numRows() > 0 );
962  }
963 
969  public function roleExists( $roleName ) {
970  $query = new Query(
971  "SELECT 1 FROM pg_catalog.pg_roles " .
972  "WHERE rolname = " . $this->addQuotes( $roleName ) . " LIMIT 1",
973  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
974  'SELECT',
975  'pg_catalog'
976  );
977  $res = $this->query( $query, __METHOD__ );
978 
979  return ( $res->numRows() > 0 );
980  }
981 
987  public function fieldInfo( $table, $field ) {
988  return PostgresField::fromText( $this, $table, $field );
989  }
990 
991  public function encodeBlob( $b ) {
992  $conn = $this->getBindingHandle();
993 
994  return new PostgresBlob( pg_escape_bytea( $conn, $b ) );
995  }
996 
997  public function decodeBlob( $b ) {
998  if ( $b instanceof PostgresBlob ) {
999  $b = $b->fetch();
1000  } elseif ( $b instanceof Blob ) {
1001  return $b->fetch();
1002  }
1003 
1004  return pg_unescape_bytea( $b );
1005  }
1006 
1007  public function strencode( $s ) {
1008  // Should not be called by us
1009  return pg_escape_string( $this->getBindingHandle(), (string)$s );
1010  }
1011 
1012  public function addQuotes( $s ) {
1013  $conn = $this->getBindingHandle();
1014 
1015  if ( $s === null ) {
1016  return 'NULL';
1017  } elseif ( is_bool( $s ) ) {
1018  return (string)intval( $s );
1019  } elseif ( is_int( $s ) ) {
1020  return (string)$s;
1021  } elseif ( $s instanceof Blob ) {
1022  if ( $s instanceof PostgresBlob ) {
1023  $s = $s->fetch();
1024  } else {
1025  $s = pg_escape_bytea( $conn, $s->fetch() );
1026  }
1027  return "'$s'";
1028  } elseif ( $s instanceof NextSequenceValue ) {
1029  return 'DEFAULT';
1030  }
1031 
1032  return "'" . pg_escape_string( $conn, (string)$s ) . "'";
1033  }
1034 
1035  public function streamStatementEnd( &$sql, &$newLine ) {
1036  # Allow dollar quoting for function declarations
1037  if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1038  if ( $this->delimiter ) {
1039  $this->delimiter = false;
1040  } else {
1041  $this->delimiter = ';';
1042  }
1043  }
1044 
1045  return parent::streamStatementEnd( $sql, $newLine );
1046  }
1047 
1048  public function doLockIsFree( string $lockName, string $method ) {
1049  $query = new Query(
1050  $this->platform->lockIsFreeSQLText( $lockName ),
1051  self::QUERY_CHANGE_LOCKS,
1052  'SELECT'
1053  );
1054  $res = $this->query( $query, $method );
1055  $row = $res->fetchObject();
1056 
1057  return ( $row->unlocked === 't' );
1058  }
1059 
1060  public function doLock( string $lockName, string $method, int $timeout ) {
1061  $query = new Query(
1062  $this->platform->lockSQLText( $lockName, $timeout ),
1063  self::QUERY_CHANGE_LOCKS,
1064  'SELECT'
1065  );
1066 
1067  $acquired = null;
1068  $loop = new WaitConditionLoop(
1069  function () use ( $query, $method, &$acquired ) {
1070  $res = $this->query( $query, $method );
1071  $row = $res->fetchObject();
1072 
1073  if ( $row->acquired !== null ) {
1074  $acquired = (float)$row->acquired;
1075 
1076  return WaitConditionLoop::CONDITION_REACHED;
1077  }
1078 
1079  return WaitConditionLoop::CONDITION_CONTINUE;
1080  },
1081  $timeout
1082  );
1083  $loop->invoke();
1084 
1085  return $acquired;
1086  }
1087 
1088  public function doUnlock( string $lockName, string $method ) {
1089  $query = new Query(
1090  $this->platform->unlockSQLText( $lockName ),
1091  self::QUERY_CHANGE_LOCKS,
1092  'SELECT'
1093  );
1094  $result = $this->query( $query, $method );
1095  $row = $result->fetchObject();
1096 
1097  return ( $row->released === 't' );
1098  }
1099 
1100  protected function doFlushSession( $fname ) {
1101  $flags = self::QUERY_CHANGE_LOCKS | self::QUERY_NO_RETRY;
1102 
1103  // https://www.postgresql.org/docs/9.1/functions-admin.html
1104  $sql = "pg_advisory_unlock_all()";
1105  $query = new Query( $sql, $flags, 'UNLOCK' );
1106  $qs = $this->executeQuery( $query, __METHOD__, $flags );
1107  if ( $qs->res === false ) {
1108  $this->reportQueryError( $qs->message, $qs->code, $sql, $fname, true );
1109  }
1110  }
1111 
1112  public function serverIsReadOnly() {
1113  $query = new Query(
1114  "SHOW default_transaction_read_only",
1115  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
1116  'SHOW'
1117  );
1118  $res = $this->query( $query, __METHOD__ );
1119  $row = $res->fetchObject();
1120 
1121  return $row && strtolower( $row->default_transaction_read_only ) === 'on';
1122  }
1123 
1124  protected function getInsertIdColumnForUpsert( $table ) {
1125  $column = null;
1126 
1127  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
1128  $encTable = $this->addQuotes( $this->realTableName( $table, 'raw' ) );
1129  foreach ( $this->getCoreSchemas() as $schema ) {
1130  $encSchema = $this->addQuotes( $schema );
1131  $query = new Query(
1132  "SELECT column_name,data_type,column_default " .
1133  "FROM information_schema.columns " .
1134  "WHERE table_name = $encTable AND table_schema = $encSchema",
1135  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
1136  'SELECT'
1137  );
1138  $res = $this->query( $query, __METHOD__ );
1139  if ( $res->numRows() ) {
1140  foreach ( $res as $row ) {
1141  if (
1142  $row->column_default !== null &&
1143  str_starts_with( $row->column_default, "nextval(" ) &&
1144  in_array( $row->data_type, [ 'integer', 'bigint' ], true )
1145  ) {
1146  $column = $row->column_name;
1147  }
1148  }
1149  break;
1150  }
1151  }
1152 
1153  return $column;
1154  }
1155 
1156  public static function getAttributes() {
1157  return [ self::ATTR_SCHEMAS_AS_TABLE_GROUPS => true ];
1158  }
1159 }
1160 
1164 class_alias( DatabasePostgres::class, 'DatabasePostgres' );
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)
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 attempted 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)
lastErrno()
Get the RDBMS-specific error code from the last attempted query statement.
getCoreSchema()
Return schema name for core application tables.
strencode( $s)
Wrapper for addslashes()
lastInsertId()
Get a row ID from the last insert statement to implicitly assign one within the session.
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 this DB server is running in server-side read-only mode If an error occurs,...
Relational database abstraction object.
Definition: Database.php:45
restoreErrorHandler()
Restore the previous error handler and return the last PHP error for this DB.
Definition: Database.php:506
object resource null $conn
Database connection.
Definition: Database.php:68
newExceptionAfterConnectError( $error)
Definition: Database.php:1306
installErrorHandler()
Set a custom error handler for logging errors during database connection.
Definition: Database.php:495
close( $fname=__METHOD__)
Close the database connection.
Definition: Database.php:558
query( $sql, $fname=__METHOD__, $flags=0)
Run an SQL query statement and return the result.
Definition: Database.php:722
getBindingHandle()
Get the underlying binding connection handle.
Definition: Database.php:3272
getDBname()
Get the current database name; null if there isn't one.
Definition: Database.php:1608
Used by Database::nextSequenceValue() so Database::insert() can detect values coming from the depreca...
static fromText(DatabasePostgres $db, $table, $field)
Holds information on Query to be executed.
Definition: Query.php:31
return true
Definition: router.php:90