MediaWiki  master
DatabasePostgres.php
Go to the documentation of this file.
1 <?php
23 namespace Wikimedia\Rdbms;
24 
25 use RuntimeException;
26 use Wikimedia\AtEase\AtEase;
27 use Wikimedia\Timestamp\ConvertibleTimestamp;
28 use Wikimedia\WaitConditionLoop;
29 
33 class DatabasePostgres extends Database {
35  private $port;
37  private $coreSchema;
39  private $tempSchema;
43  private $numericVersion;
44 
47 
55  public function __construct( array $params ) {
56  $this->port = intval( $params['port'] ?? null );
57 
58  if ( isset( $params['keywordTableMap'] ) ) {
59  wfDeprecatedMsg( 'Passing keywordTableMap parameter to ' .
60  'DatabasePostgres::__construct() is deprecated', '1.37'
61  );
62 
63  $this->keywordTableMap = $params['keywordTableMap'];
64  }
65 
66  parent::__construct( $params );
67  }
68 
69  public function getType() {
70  return 'postgres';
71  }
72 
73  public function implicitOrderby() {
74  return false;
75  }
76 
77  public function hasConstraint( $name ) {
78  foreach ( $this->getCoreSchemas() as $schema ) {
79  $sql = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
80  "WHERE c.connamespace = n.oid AND conname = " .
81  $this->addQuotes( $name ) . " AND n.nspname = " .
82  $this->addQuotes( $schema );
83  $res = $this->doQuery( $sql );
84  if ( $res && $this->numRows( $res ) ) {
85  return true;
86  }
87  }
88  return false;
89  }
90 
91  protected function open( $server, $user, $password, $db, $schema, $tablePrefix ) {
92  if ( !function_exists( 'pg_connect' ) ) {
93  throw $this->newExceptionAfterConnectError(
94  "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
95  "option? (Note: if you recently installed PHP, you may need to restart your\n" .
96  "webserver and database)"
97  );
98  }
99 
100  $this->close( __METHOD__ );
101 
102  $connectVars = [
103  // A database must be specified in order to connect to Postgres. If $dbName is not
104  // specified, then use the standard "postgres" database that should exist by default.
105  'dbname' => strlen( $db ) ? $db : 'postgres',
106  'user' => $user,
107  'password' => $password
108  ];
109  if ( strlen( $server ) ) {
110  $connectVars['host'] = $server;
111  }
112  if ( $this->port > 0 ) {
113  $connectVars['port'] = $this->port;
114  }
115  if ( $this->getFlag( self::DBO_SSL ) ) {
116  $connectVars['sslmode'] = 'require';
117  }
118  $connectString = $this->makeConnectionString( $connectVars );
119 
120  $this->installErrorHandler();
121  try {
122  $this->conn = pg_connect( $connectString, PGSQL_CONNECT_FORCE_NEW ) ?: null;
123  } catch ( RuntimeException $e ) {
124  $this->restoreErrorHandler();
125  throw $this->newExceptionAfterConnectError( $e->getMessage() );
126  }
127  $error = $this->restoreErrorHandler();
128 
129  if ( !$this->conn ) {
130  throw $this->newExceptionAfterConnectError( $error ?: $this->lastError() );
131  }
132 
133  try {
134  // Since no transaction is active at this point, any SET commands should apply
135  // for the entire session (e.g. will not be reverted on transaction rollback).
136  // See https://www.postgresql.org/docs/8.3/sql-set.html
137  $variables = [
138  'client_encoding' => 'UTF8',
139  'datestyle' => 'ISO, YMD',
140  'timezone' => 'GMT',
141  'standard_conforming_strings' => 'on',
142  'bytea_output' => 'escape',
143  'client_min_messages' => 'ERROR'
144  ];
145  foreach ( $variables as $var => $val ) {
146  $this->query(
147  'SET ' . $this->addIdentifierQuotes( $var ) . ' = ' . $this->addQuotes( $val ),
148  __METHOD__,
149  self::QUERY_IGNORE_DBO_TRX | self::QUERY_NO_RETRY | self::QUERY_CHANGE_TRX
150  );
151  }
152  $this->determineCoreSchema( $schema );
153  $this->currentDomain = new DatabaseDomain( $db, $schema, $tablePrefix );
154  } catch ( RuntimeException $e ) {
155  throw $this->newExceptionAfterConnectError( $e->getMessage() );
156  }
157  }
158 
159  protected function relationSchemaQualifier() {
160  if ( $this->coreSchema === $this->currentDomain->getSchema() ) {
161  // The schema to be used is now in the search path; no need for explicit qualification
162  return '';
163  }
164 
165  return parent::relationSchemaQualifier();
166  }
167 
168  public function databasesAreIndependent() {
169  return true;
170  }
171 
172  public function doSelectDomain( DatabaseDomain $domain ) {
173  if ( $this->getDBname() !== $domain->getDatabase() ) {
174  // Postgres doesn't support selectDB in the same way MySQL does.
175  // So if the DB name doesn't match the open connection, open a new one
176  $this->open(
177  $this->connectionParams[self::CONN_HOST],
178  $this->connectionParams[self::CONN_USER],
179  $this->connectionParams[self::CONN_PASSWORD],
180  $domain->getDatabase(),
181  $domain->getSchema(),
182  $domain->getTablePrefix()
183  );
184  } else {
185  $this->currentDomain = $domain;
186  }
187 
188  return true;
189  }
190 
195  private function makeConnectionString( $vars ) {
196  $s = '';
197  foreach ( $vars as $name => $value ) {
198  $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
199  }
200 
201  return $s;
202  }
203 
204  protected function closeConnection() {
205  return $this->conn ? pg_close( $this->conn ) : true;
206  }
207 
208  protected function isTransactableQuery( $sql ) {
209  return parent::isTransactableQuery( $sql ) &&
210  !preg_match( '/^SELECT\s+pg_(try_|)advisory_\w+\‍(/', $sql );
211  }
212 
217  public function doQuery( $sql ) {
218  $conn = $this->getBindingHandle();
219 
220  $sql = mb_convert_encoding( $sql, 'UTF-8' );
221  // Clear previously left over PQresult
222  while ( $res = pg_get_result( $conn ) ) {
223  pg_free_result( $res );
224  }
225  if ( pg_send_query( $conn, $sql ) === false ) {
226  throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
227  }
228  $this->lastResultHandle = pg_get_result( $conn );
229  if ( pg_result_error( $this->lastResultHandle ) ) {
230  return false;
231  }
232 
234  }
235 
236  protected function dumpError() {
237  $diags = [
238  PGSQL_DIAG_SEVERITY,
239  PGSQL_DIAG_SQLSTATE,
240  PGSQL_DIAG_MESSAGE_PRIMARY,
241  PGSQL_DIAG_MESSAGE_DETAIL,
242  PGSQL_DIAG_MESSAGE_HINT,
243  PGSQL_DIAG_STATEMENT_POSITION,
244  PGSQL_DIAG_INTERNAL_POSITION,
245  PGSQL_DIAG_INTERNAL_QUERY,
246  PGSQL_DIAG_CONTEXT,
247  PGSQL_DIAG_SOURCE_FILE,
248  PGSQL_DIAG_SOURCE_LINE,
249  PGSQL_DIAG_SOURCE_FUNCTION
250  ];
251  foreach ( $diags as $d ) {
252  $this->queryLogger->debug( sprintf( "PgSQL ERROR(%d): %s",
253  $d, pg_result_error_field( $this->lastResultHandle, $d ) ) );
254  }
255  }
256 
257  public function freeResult( $res ) {
258  AtEase::suppressWarnings();
259  $ok = pg_free_result( ResultWrapper::unwrap( $res ) );
260  AtEase::restoreWarnings();
261  if ( !$ok ) {
262  throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
263  }
264  }
265 
266  public function fetchObject( $res ) {
267  AtEase::suppressWarnings();
268  $row = pg_fetch_object( ResultWrapper::unwrap( $res ) );
269  AtEase::restoreWarnings();
270  # @todo FIXME: HACK HACK HACK HACK debug
271 
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 ) )
279  );
280  }
281 
282  return $row;
283  }
284 
285  public function fetchRow( $res ) {
286  AtEase::suppressWarnings();
287  $row = pg_fetch_array( ResultWrapper::unwrap( $res ) );
288  AtEase::restoreWarnings();
289 
290  $conn = $this->getBindingHandle();
291  if ( pg_last_error( $conn ) ) {
292  throw new DBUnexpectedError(
293  $this,
294  'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
295  );
296  }
297 
298  return $row;
299  }
300 
301  public function numRows( $res ) {
302  if ( $res === false ) {
303  return 0;
304  }
305 
306  AtEase::suppressWarnings();
307  $n = pg_num_rows( ResultWrapper::unwrap( $res ) );
308  AtEase::restoreWarnings();
309 
310  $conn = $this->getBindingHandle();
311  if ( pg_last_error( $conn ) ) {
312  throw new DBUnexpectedError(
313  $this,
314  'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
315  );
316  }
317 
318  return $n;
319  }
320 
321  public function numFields( $res ) {
322  return pg_num_fields( ResultWrapper::unwrap( $res ) );
323  }
324 
325  public function fieldName( $res, $n ) {
326  return pg_field_name( ResultWrapper::unwrap( $res ), $n );
327  }
328 
329  public function insertId() {
330  $res = $this->query(
331  "SELECT lastval()",
332  __METHOD__,
333  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
334  );
335  $row = $this->fetchRow( $res );
336 
337  return $row[0] === null ? null : (int)$row[0];
338  }
339 
340  public function dataSeek( $res, $row ) {
341  return pg_result_seek( ResultWrapper::unwrap( $res ), $row );
342  }
343 
344  public function lastError() {
345  if ( $this->conn ) {
346  if ( $this->lastResultHandle ) {
347  return pg_result_error( $this->lastResultHandle );
348  } else {
349  return pg_last_error();
350  }
351  }
352 
353  return $this->getLastPHPError() ?: 'No database connection';
354  }
355 
356  public function lastErrno() {
357  if ( $this->lastResultHandle ) {
358  return pg_result_error_field( $this->lastResultHandle, PGSQL_DIAG_SQLSTATE );
359  } else {
360  return false;
361  }
362  }
363 
364  protected function fetchAffectedRowCount() {
365  if ( !$this->lastResultHandle ) {
366  return 0;
367  }
368 
369  return pg_affected_rows( $this->lastResultHandle );
370  }
371 
387  public function estimateRowCount( $table, $var = '*', $conds = '',
388  $fname = __METHOD__, $options = [], $join_conds = []
389  ) {
390  $conds = $this->normalizeConditions( $conds, $fname );
391  $column = $this->extractSingleFieldFromList( $var );
392  if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
393  $conds[] = "$column IS NOT NULL";
394  }
395 
396  $options['EXPLAIN'] = true;
397  $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
398  $rows = -1;
399  if ( $res ) {
400  $row = $this->fetchRow( $res );
401  $count = [];
402  if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
403  $rows = (int)$count[1];
404  }
405  }
406 
407  return $rows;
408  }
409 
410  public function indexInfo( $table, $index, $fname = __METHOD__ ) {
411  $res = $this->query(
412  "SELECT indexname FROM pg_indexes WHERE tablename='$table'",
413  $fname,
414  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
415  );
416  if ( !$res ) {
417  return null;
418  }
419  foreach ( $res as $row ) {
420  if ( $row->indexname == $this->indexName( $index ) ) {
421  return $row;
422  }
423  }
424 
425  return false;
426  }
427 
428  public function indexAttributes( $index, $schema = false ) {
429  if ( $schema === false ) {
430  $schemas = $this->getCoreSchemas();
431  } else {
432  $schemas = [ $schema ];
433  }
434 
435  $eindex = $this->addQuotes( $index );
436 
437  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
438  foreach ( $schemas as $schema ) {
439  $eschema = $this->addQuotes( $schema );
440  /*
441  * A subquery would be not needed if we didn't care about the order
442  * of attributes, but we do
443  */
444  $sql = <<<__INDEXATTR__
445 
446  SELECT opcname,
447  attname,
448  i.indoption[s.g] as option,
449  pg_am.amname
450  FROM
451  (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
452  FROM
453  pg_index isub
454  JOIN pg_class cis
455  ON cis.oid=isub.indexrelid
456  JOIN pg_namespace ns
457  ON cis.relnamespace = ns.oid
458  WHERE cis.relname=$eindex AND ns.nspname=$eschema) AS s,
459  pg_attribute,
460  pg_opclass opcls,
461  pg_am,
462  pg_class ci
463  JOIN pg_index i
464  ON ci.oid=i.indexrelid
465  JOIN pg_class ct
466  ON ct.oid = i.indrelid
467  JOIN pg_namespace n
468  ON ci.relnamespace = n.oid
469  WHERE
470  ci.relname=$eindex AND n.nspname=$eschema
471  AND attrelid = ct.oid
472  AND i.indkey[s.g] = attnum
473  AND i.indclass[s.g] = opcls.oid
474  AND pg_am.oid = opcls.opcmethod
475 __INDEXATTR__;
476  $res = $this->query( $sql, __METHOD__, $flags );
477  $a = [];
478  if ( $res ) {
479  foreach ( $res as $row ) {
480  $a[] = [
481  $row->attname,
482  $row->opcname,
483  $row->amname,
484  $row->option ];
485  }
486  return $a;
487  }
488  }
489  return null;
490  }
491 
492  public function indexUnique( $table, $index, $fname = __METHOD__ ) {
493  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
494  $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
495  " AND indexdef LIKE 'CREATE UNIQUE%(" .
496  $this->strencode( $this->indexName( $index ) ) .
497  ")'";
498  $res = $this->query( $sql, $fname, $flags );
499  if ( !$res ) {
500  return null;
501  }
502 
503  return $res->numRows() > 0;
504  }
505 
506  public function selectSQLText(
507  $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
508  ) {
509  if ( is_string( $options ) ) {
510  $options = [ $options ];
511  }
512 
513  // Change the FOR UPDATE option as necessary based on the join conditions. Then pass
514  // to the parent function to get the actual SQL text.
515  // In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
516  // can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to
517  // do so causes a DB error. This wrapper checks which tables can be locked and adjusts it
518  // accordingly.
519  // MySQL uses "ORDER BY NULL" as an optimization hint, but that is illegal in PostgreSQL.
520  if ( is_array( $options ) ) {
521  $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
522  if ( $forUpdateKey !== false && $join_conds ) {
523  unset( $options[$forUpdateKey] );
524  $options['FOR UPDATE'] = [];
525 
526  $toCheck = $table;
527  reset( $toCheck );
528  while ( $toCheck ) {
529  $alias = key( $toCheck );
530  $name = $toCheck[$alias];
531  unset( $toCheck[$alias] );
532 
533  $hasAlias = !is_numeric( $alias );
534  if ( !$hasAlias && is_string( $name ) ) {
535  $alias = $name;
536  }
537 
538  if ( !isset( $join_conds[$alias] ) ||
539  !preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_conds[$alias][0] )
540  ) {
541  if ( is_array( $name ) ) {
542  // It's a parenthesized group, process all the tables inside the group.
543  $toCheck = array_merge( $toCheck, $name );
544  } else {
545  // Quote alias names so $this->tableName() won't mangle them
546  $options['FOR UPDATE'][] = $hasAlias ? $this->addIdentifierQuotes( $alias ) : $alias;
547  }
548  }
549  }
550  }
551 
552  if ( isset( $options['ORDER BY'] ) && $options['ORDER BY'] == 'NULL' ) {
553  unset( $options['ORDER BY'] );
554  }
555  }
556 
557  return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
558  }
559 
561  return [ 'INSERT INTO', 'ON CONFLICT DO NOTHING' ];
562  }
563 
564  public function doInsertNonConflicting( $table, array $rows, $fname ) {
565  // Postgres 9.5 supports "ON CONFLICT"
566  if ( $this->getServerVersion() >= 9.5 ) {
567  parent::doInsertNonConflicting( $table, $rows, $fname );
568 
569  return;
570  }
571 
572  $affectedRowCount = 0;
573  // Emulate INSERT IGNORE via savepoints/rollback
574  $tok = $this->startAtomic( "$fname (outer)", self::ATOMIC_CANCELABLE );
575  try {
576  $encTable = $this->tableName( $table );
577  foreach ( $rows as $row ) {
578  list( $sqlColumns, $sqlTuples ) = $this->makeInsertLists( [ $row ] );
579  $tempsql = "INSERT INTO $encTable ($sqlColumns) VALUES $sqlTuples";
580 
581  $this->startAtomic( "$fname (inner)", self::ATOMIC_CANCELABLE );
582  try {
583  $this->query( $tempsql, $fname, self::QUERY_CHANGE_ROWS );
584  $this->endAtomic( "$fname (inner)" );
586  } catch ( DBQueryError $e ) {
587  $this->cancelAtomic( "$fname (inner)" );
588  // Our IGNORE is supposed to ignore duplicate key errors, but not others.
589  // (even though MySQL's version apparently ignores all errors)
590  if ( $e->errno !== '23505' ) {
591  throw $e;
592  }
593  }
594  }
595  } catch ( RuntimeException $e ) {
596  $this->cancelAtomic( "$fname (outer)", $tok );
597  throw $e;
598  }
599  $this->endAtomic( "$fname (outer)" );
600  // Set the affected row count for the whole operation
601  $this->affectedRowCount = $affectedRowCount;
602  }
603 
604  protected function makeUpdateOptionsArray( $options ) {
605  $options = $this->normalizeOptions( $options );
606  // PostgreSQL doesn't support anything like "ignore" for UPDATE.
607  $options = array_diff( $options, [ 'IGNORE' ] );
608 
609  return parent::makeUpdateOptionsArray( $options );
610  }
611 
630  protected function doInsertSelectNative(
631  $destTable,
632  $srcTable,
633  array $varMap,
634  $conds,
635  $fname,
636  array $insertOptions,
637  array $selectOptions,
638  $selectJoinConds
639  ) {
640  if ( in_array( 'IGNORE', $insertOptions ) ) {
641  if ( $this->getServerVersion() >= 9.5 ) {
642  // Use "ON CONFLICT DO" if we have it for IGNORE
643  $destTable = $this->tableName( $destTable );
644 
645  $selectSql = $this->selectSQLText(
646  $srcTable,
647  array_values( $varMap ),
648  $conds,
649  $fname,
650  $selectOptions,
651  $selectJoinConds
652  );
653 
654  $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
655  $selectSql . ' ON CONFLICT DO NOTHING';
656 
657  $this->query( $sql, $fname, self::QUERY_CHANGE_ROWS );
658  } else {
659  // IGNORE and we don't have ON CONFLICT DO NOTHING, so just use the non-native version
660  $this->doInsertSelectGeneric(
661  $destTable, $srcTable, $varMap, $conds, $fname,
662  $insertOptions, $selectOptions, $selectJoinConds
663  );
664  }
665  } else {
666  parent::doInsertSelectNative( $destTable, $srcTable, $varMap, $conds, $fname,
667  $insertOptions, $selectOptions, $selectJoinConds );
668  }
669  }
670 
671  public function tableName( $name, $format = 'quoted' ) {
672  return parent::tableName( $name, $format );
673  }
674 
680  public function remappedTableName( $name ) {
681  wfDeprecated( __METHOD__, '1.37' );
682 
683  return $this->keywordTableMap[$name] ?? $name;
684  }
685 
691  public function realTableName( $name, $format = 'quoted' ) {
692  return parent::tableName( $name, $format );
693  }
694 
695  public function nextSequenceValue( $seqName ) {
696  return new NextSequenceValue;
697  }
698 
705  public function currentSequenceValue( $seqName ) {
706  $res = $this->query(
707  "SELECT currval('" . str_replace( "'", "''", $seqName ) . "')",
708  __METHOD__,
709  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
710  );
711  $row = $this->fetchRow( $res );
712  $currval = $row[0];
713 
714  return $currval;
715  }
716 
717  public function textFieldSize( $table, $field ) {
718  $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
719  $encTable = $this->tableName( $table );
720  $sql = "SELECT t.typname as ftype,a.atttypmod as size
721  FROM pg_class c, pg_attribute a, pg_type t
722  WHERE relname='$encTable' AND a.attrelid=c.oid AND
723  a.atttypid=t.oid and a.attname='$field'";
724  $res = $this->query( $sql, __METHOD__, $flags );
725  $row = $this->fetchObject( $res );
726  if ( $row->ftype == 'varchar' ) {
727  $size = $row->size - 4;
728  } else {
729  $size = $row->size;
730  }
731 
732  return $size;
733  }
734 
735  public function limitResult( $sql, $limit, $offset = false ) {
736  return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
737  }
738 
739  public function wasDeadlock() {
740  // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
741  return $this->lastErrno() === '40P01';
742  }
743 
744  public function wasLockTimeout() {
745  // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
746  return $this->lastErrno() === '55P03';
747  }
748 
749  public function wasConnectionError( $errno ) {
750  // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
751  static $codes = [ '08000', '08003', '08006', '08001', '08004', '57P01', '57P03', '53300' ];
752 
753  return in_array( $errno, $codes, true );
754  }
755 
756  protected function wasKnownStatementRollbackError() {
757  return false; // transaction has to be rolled-back from error state
758  }
759 
760  public function duplicateTableStructure(
761  $oldName, $newName, $temporary = false, $fname = __METHOD__
762  ) {
763  $newNameE = $this->addIdentifierQuotes( $newName );
764  $oldNameE = $this->addIdentifierQuotes( $oldName );
765 
766  $temporary = $temporary ? 'TEMPORARY' : '';
767 
768  $ret = $this->query(
769  "CREATE $temporary TABLE $newNameE " .
770  "(LIKE $oldNameE INCLUDING DEFAULTS INCLUDING INDEXES)",
771  $fname,
772  self::QUERY_PSEUDO_PERMANENT | self::QUERY_CHANGE_SCHEMA
773  );
774  if ( !$ret ) {
775  return $ret;
776  }
777 
778  $res = $this->query(
779  'SELECT attname FROM pg_class c'
780  . ' JOIN pg_namespace n ON (n.oid = c.relnamespace)'
781  . ' JOIN pg_attribute a ON (a.attrelid = c.oid)'
782  . ' JOIN pg_attrdef d ON (c.oid=d.adrelid and a.attnum=d.adnum)'
783  . ' WHERE relkind = \'r\''
784  . ' AND nspname = ' . $this->addQuotes( $this->getCoreSchema() )
785  . ' AND relname = ' . $this->addQuotes( $oldName )
786  . ' AND pg_get_expr(adbin, adrelid) LIKE \'nextval(%\'',
787  $fname,
788  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
789  );
790  $row = $this->fetchObject( $res );
791  if ( $row ) {
792  $field = $row->attname;
793  $newSeq = "{$newName}_{$field}_seq";
794  $fieldE = $this->addIdentifierQuotes( $field );
795  $newSeqE = $this->addIdentifierQuotes( $newSeq );
796  $newSeqQ = $this->addQuotes( $newSeq );
797  $this->query(
798  "CREATE $temporary SEQUENCE $newSeqE OWNED BY $newNameE.$fieldE",
799  $fname,
800  self::QUERY_CHANGE_SCHEMA
801  );
802  $this->query(
803  "ALTER TABLE $newNameE ALTER COLUMN $fieldE SET DEFAULT nextval({$newSeqQ}::regclass)",
804  $fname,
805  self::QUERY_CHANGE_SCHEMA
806  );
807  }
808 
809  return $ret;
810  }
811 
812  protected function doTruncate( array $tables, $fname ) {
813  $encTables = $this->tableNamesN( ...$tables );
814  $sql = "TRUNCATE TABLE " . implode( ',', $encTables ) . " RESTART IDENTITY";
815  $this->query( $sql, $fname, self::QUERY_CHANGE_SCHEMA );
816  }
817 
824  public function listTables( $prefix = '', $fname = __METHOD__ ) {
825  $eschemas = implode( ',', array_map( [ $this, 'addQuotes' ], $this->getCoreSchemas() ) );
826  $result = $this->query(
827  "SELECT DISTINCT tablename FROM pg_tables WHERE schemaname IN ($eschemas)",
828  $fname,
829  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
830  );
831  $endArray = [];
832 
833  foreach ( $result as $table ) {
834  $vars = get_object_vars( $table );
835  $table = array_pop( $vars );
836  if ( $prefix == '' || strpos( $table, $prefix ) === 0 ) {
837  $endArray[] = $table;
838  }
839  }
840 
841  return $endArray;
842  }
843 
844  public function timestamp( $ts = 0 ) {
845  $ct = new ConvertibleTimestamp( $ts );
846 
847  return $ct->getTimestamp( TS_POSTGRES );
848  }
849 
868  private function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
869  if ( $limit === false ) {
870  $limit = strlen( $text ) - 1;
871  $output = [];
872  }
873  if ( $text == '{}' ) {
874  return $output;
875  }
876  do {
877  if ( $text[$offset] != '{' ) {
878  preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
879  $text, $match, 0, $offset );
880  $offset += strlen( $match[0] );
881  $output[] = ( $match[1][0] != '"'
882  ? $match[1]
883  : stripcslashes( substr( $match[1], 1, -1 ) ) );
884  if ( $match[3] == '},' ) {
885  return $output;
886  }
887  } else {
888  $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
889  }
890  } while ( $limit > $offset );
891 
892  return $output;
893  }
894 
895  public function aggregateValue( $valuedata, $valuename = 'value' ) {
896  return $valuedata;
897  }
898 
899  public function getSoftwareLink() {
900  return '[{{int:version-db-postgres-url}} PostgreSQL]';
901  }
902 
910  public function getCurrentSchema() {
911  $res = $this->query(
912  "SELECT current_schema()",
913  __METHOD__,
914  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
915  );
916  $row = $this->fetchRow( $res );
917 
918  return $row[0];
919  }
920 
931  public function getSchemas() {
932  $res = $this->query(
933  "SELECT current_schemas(false)",
934  __METHOD__,
935  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
936  );
937  $row = $this->fetchRow( $res );
938  $schemas = [];
939 
940  /* PHP pgsql support does not support array type, "{a,b}" string is returned */
941 
942  return $this->pg_array_parse( $row[0], $schemas );
943  }
944 
954  public function getSearchPath() {
955  $res = $this->query(
956  "SHOW search_path",
957  __METHOD__,
958  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
959  );
960  $row = $this->fetchRow( $res );
961 
962  /* PostgreSQL returns SHOW values as strings */
963 
964  return explode( ",", $row[0] );
965  }
966 
974  private function setSearchPath( $search_path ) {
975  $this->query(
976  "SET search_path = " . implode( ", ", $search_path ),
977  __METHOD__,
978  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_TRX
979  );
980  }
981 
996  public function determineCoreSchema( $desiredSchema ) {
997  if ( $this->trxLevel() ) {
998  // We do not want the schema selection to change on ROLLBACK or INSERT SELECT.
999  // See https://www.postgresql.org/docs/8.3/sql-set.html
1000  throw new DBUnexpectedError(
1001  $this,
1002  __METHOD__ . ": a transaction is currently active"
1003  );
1004  }
1005 
1006  if ( $this->schemaExists( $desiredSchema ) ) {
1007  if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
1008  $this->coreSchema = $desiredSchema;
1009  $this->queryLogger->debug(
1010  "Schema \"" . $desiredSchema . "\" already in the search path\n" );
1011  } else {
1012  // Prepend the desired schema to the search path (T17816)
1013  $search_path = $this->getSearchPath();
1014  array_unshift( $search_path, $this->addIdentifierQuotes( $desiredSchema ) );
1015  $this->setSearchPath( $search_path );
1016  $this->coreSchema = $desiredSchema;
1017  $this->queryLogger->debug(
1018  "Schema \"" . $desiredSchema . "\" added to the search path\n" );
1019  }
1020  } else {
1021  $this->coreSchema = $this->getCurrentSchema();
1022  $this->queryLogger->debug(
1023  "Schema \"" . $desiredSchema . "\" not found, using current \"" .
1024  $this->coreSchema . "\"\n" );
1025  }
1026  }
1027 
1034  public function getCoreSchema() {
1035  return $this->coreSchema;
1036  }
1037 
1044  public function getCoreSchemas() {
1045  if ( $this->tempSchema ) {
1046  return [ $this->tempSchema, $this->getCoreSchema() ];
1047  }
1048 
1049  $res = $this->query(
1050  "SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = pg_my_temp_schema()",
1051  __METHOD__,
1052  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1053  );
1054  $row = $this->fetchObject( $res );
1055  if ( $row ) {
1056  $this->tempSchema = $row->nspname;
1057  return [ $this->tempSchema, $this->getCoreSchema() ];
1058  }
1059 
1060  return [ $this->getCoreSchema() ];
1061  }
1062 
1063  public function getServerVersion() {
1064  if ( !isset( $this->numericVersion ) ) {
1065  $conn = $this->getBindingHandle();
1066  $versionInfo = pg_version( $conn );
1067  if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1068  // Old client, abort install
1069  $this->numericVersion = '7.3 or earlier';
1070  } elseif ( isset( $versionInfo['server'] ) ) {
1071  // Normal client
1072  $this->numericVersion = $versionInfo['server'];
1073  } else {
1074  // T18937: broken pgsql extension from PHP<5.3
1075  $this->numericVersion = pg_parameter_status( $conn, 'server_version' );
1076  }
1077  }
1078 
1079  return $this->numericVersion;
1080  }
1081 
1090  private function relationExists( $table, $types, $schema = false ) {
1091  if ( !is_array( $types ) ) {
1092  $types = [ $types ];
1093  }
1094  if ( $schema === false ) {
1095  $schemas = $this->getCoreSchemas();
1096  } else {
1097  $schemas = [ $schema ];
1098  }
1099  $table = $this->realTableName( $table, 'raw' );
1100  $etable = $this->addQuotes( $table );
1101  foreach ( $schemas as $schema ) {
1102  $eschema = $this->addQuotes( $schema );
1103  $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1104  . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1105  . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1106  $res = $this->query(
1107  $sql,
1108  __METHOD__,
1109  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1110  );
1111  if ( $res && $res->numRows() ) {
1112  return true;
1113  }
1114  }
1115 
1116  return false;
1117  }
1118 
1126  public function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1127  return $this->relationExists( $table, [ 'r', 'v' ], $schema );
1128  }
1129 
1130  public function sequenceExists( $sequence, $schema = false ) {
1131  return $this->relationExists( $sequence, 'S', $schema );
1132  }
1133 
1134  public function triggerExists( $table, $trigger ) {
1135  $q = <<<SQL
1136  SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1137  WHERE relnamespace=pg_namespace.oid AND relkind='r'
1138  AND tgrelid=pg_class.oid
1139  AND nspname=%s AND relname=%s AND tgname=%s
1140 SQL;
1141  foreach ( $this->getCoreSchemas() as $schema ) {
1142  $res = $this->query(
1143  sprintf(
1144  $q,
1145  $this->addQuotes( $schema ),
1146  $this->addQuotes( $table ),
1147  $this->addQuotes( $trigger )
1148  ),
1149  __METHOD__,
1150  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1151  );
1152  if ( $res && $res->numRows() ) {
1153  return true;
1154  }
1155  }
1156 
1157  return false;
1158  }
1159 
1160  public function ruleExists( $table, $rule ) {
1161  $exists = $this->selectField( 'pg_rules', 'rulename',
1162  [
1163  'rulename' => $rule,
1164  'tablename' => $table,
1165  'schemaname' => $this->getCoreSchemas()
1166  ],
1167  __METHOD__
1168  );
1169 
1170  return $exists === $rule;
1171  }
1172 
1173  public function constraintExists( $table, $constraint ) {
1174  foreach ( $this->getCoreSchemas() as $schema ) {
1175  $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1176  "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1177  $this->addQuotes( $schema ),
1178  $this->addQuotes( $table ),
1179  $this->addQuotes( $constraint )
1180  );
1181  $res = $this->query(
1182  $sql,
1183  __METHOD__,
1184  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1185  );
1186  if ( $res && $res->numRows() ) {
1187  return true;
1188  }
1189  }
1190  return false;
1191  }
1192 
1198  public function schemaExists( $schema ) {
1199  if ( !strlen( $schema ) ) {
1200  return false; // short-circuit
1201  }
1202 
1203  $res = $this->query(
1204  "SELECT 1 FROM pg_catalog.pg_namespace " .
1205  "WHERE nspname = " . $this->addQuotes( $schema ) . " LIMIT 1",
1206  __METHOD__,
1207  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1208  );
1209 
1210  return ( $this->numRows( $res ) > 0 );
1211  }
1212 
1218  public function roleExists( $roleName ) {
1219  $res = $this->query(
1220  "SELECT 1 FROM pg_catalog.pg_roles " .
1221  "WHERE rolname = " . $this->addQuotes( $roleName ) . " LIMIT 1",
1222  __METHOD__,
1223  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1224  );
1225 
1226  return ( $this->numRows( $res ) > 0 );
1227  }
1228 
1234  public function fieldInfo( $table, $field ) {
1235  return PostgresField::fromText( $this, $table, $field );
1236  }
1237 
1244  public function fieldType( $res, $index ) {
1245  return pg_field_type( ResultWrapper::unwrap( $res ), $index );
1246  }
1247 
1248  public function encodeBlob( $b ) {
1249  return new PostgresBlob( pg_escape_bytea( $b ) );
1250  }
1251 
1252  public function decodeBlob( $b ) {
1253  if ( $b instanceof PostgresBlob ) {
1254  $b = $b->fetch();
1255  } elseif ( $b instanceof Blob ) {
1256  return $b->fetch();
1257  }
1258 
1259  return pg_unescape_bytea( $b );
1260  }
1261 
1262  public function strencode( $s ) {
1263  // Should not be called by us
1264  return pg_escape_string( $this->getBindingHandle(), (string)$s );
1265  }
1266 
1267  public function addQuotes( $s ) {
1268  $conn = $this->getBindingHandle();
1269 
1270  if ( $s === null ) {
1271  return 'NULL';
1272  } elseif ( is_bool( $s ) ) {
1273  return (string)intval( $s );
1274  } elseif ( is_int( $s ) ) {
1275  return (string)$s;
1276  } elseif ( $s instanceof Blob ) {
1277  if ( $s instanceof PostgresBlob ) {
1278  $s = $s->fetch();
1279  } else {
1280  $s = pg_escape_bytea( $conn, $s->fetch() );
1281  }
1282  return "'$s'";
1283  } elseif ( $s instanceof NextSequenceValue ) {
1284  return 'DEFAULT';
1285  }
1286 
1287  return "'" . pg_escape_string( $conn, (string)$s ) . "'";
1288  }
1289 
1290  protected function makeSelectOptions( array $options ) {
1291  $preLimitTail = $postLimitTail = '';
1292  $startOpts = $useIndex = $ignoreIndex = '';
1293 
1294  $noKeyOptions = [];
1295  foreach ( $options as $key => $option ) {
1296  if ( is_numeric( $key ) ) {
1297  $noKeyOptions[$option] = true;
1298  }
1299  }
1300 
1301  $preLimitTail .= $this->makeGroupByWithHaving( $options );
1302 
1303  $preLimitTail .= $this->makeOrderBy( $options );
1304 
1305  if ( isset( $options['FOR UPDATE'] ) ) {
1306  $postLimitTail .= ' FOR UPDATE OF ' .
1307  implode( ', ', array_map( [ $this, 'tableName' ], $options['FOR UPDATE'] ) );
1308  } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1309  $postLimitTail .= ' FOR UPDATE';
1310  }
1311 
1312  if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1313  $startOpts .= 'DISTINCT';
1314  }
1315 
1316  return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1317  }
1318 
1319  public function buildConcat( $stringList ) {
1320  return implode( ' || ', $stringList );
1321  }
1322 
1323  public function buildGroupConcatField(
1324  $delimiter, $table, $field, $conds = '', $options = [], $join_conds = []
1325  ) {
1326  $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1327 
1328  return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1329  }
1330 
1331  public function buildStringCast( $field ) {
1332  return $field . '::text';
1333  }
1334 
1335  public function streamStatementEnd( &$sql, &$newLine ) {
1336  # Allow dollar quoting for function declarations
1337  if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1338  if ( $this->delimiter ) {
1339  $this->delimiter = false;
1340  } else {
1341  $this->delimiter = ';';
1342  }
1343  }
1344 
1345  return parent::streamStatementEnd( $sql, $newLine );
1346  }
1347 
1348  public function doLockTables( array $read, array $write, $method ) {
1349  $tablesWrite = [];
1350  foreach ( $write as $table ) {
1351  $tablesWrite[] = $this->tableName( $table );
1352  }
1353  $tablesRead = [];
1354  foreach ( $read as $table ) {
1355  $tablesRead[] = $this->tableName( $table );
1356  }
1357 
1358  // Acquire locks for the duration of the current transaction...
1359  if ( $tablesWrite ) {
1360  $this->query(
1361  'LOCK TABLE ONLY ' . implode( ',', $tablesWrite ) . ' IN EXCLUSIVE MODE',
1362  $method,
1363  self::QUERY_CHANGE_ROWS
1364  );
1365  }
1366  if ( $tablesRead ) {
1367  $this->query(
1368  'LOCK TABLE ONLY ' . implode( ',', $tablesRead ) . ' IN SHARE MODE',
1369  $method,
1370  self::QUERY_CHANGE_ROWS
1371  );
1372  }
1373 
1374  return true;
1375  }
1376 
1377  public function lockIsFree( $lockName, $method ) {
1378  if ( !parent::lockIsFree( $lockName, $method ) ) {
1379  return false; // already held
1380  }
1381  // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1382  $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1383  $res = $this->query(
1384  "SELECT (CASE(pg_try_advisory_lock($key))
1385  WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus",
1386  $method,
1387  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1388  );
1389  $row = $this->fetchObject( $res );
1390 
1391  return ( $row->lockstatus === 't' );
1392  }
1393 
1394  public function lock( $lockName, $method, $timeout = 5 ) {
1395  // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1396  $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1397  $loop = new WaitConditionLoop(
1398  function () use ( $lockName, $key, $timeout, $method ) {
1399  $res = $this->query(
1400  "SELECT pg_try_advisory_lock($key) AS lockstatus",
1401  $method,
1402  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_ROWS
1403  );
1404  $row = $this->fetchObject( $res );
1405  if ( $row->lockstatus === 't' ) {
1406  parent::lock( $lockName, $method, $timeout ); // record
1407  return true;
1408  }
1409 
1410  return WaitConditionLoop::CONDITION_CONTINUE;
1411  },
1412  $timeout
1413  );
1414 
1415  return ( $loop->invoke() === $loop::CONDITION_REACHED );
1416  }
1417 
1418  public function unlock( $lockName, $method ) {
1419  // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1420  $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1421  $result = $this->query(
1422  "SELECT pg_advisory_unlock($key) as lockstatus",
1423  $method,
1424  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_ROWS
1425  );
1426  $row = $this->fetchObject( $result );
1427 
1428  if ( $row->lockstatus === 't' ) {
1429  parent::unlock( $lockName, $method ); // record
1430  return true;
1431  }
1432 
1433  $this->queryLogger->debug( __METHOD__ . " failed to release lock" );
1434 
1435  return false;
1436  }
1437 
1438  public function serverIsReadOnly() {
1439  $res = $this->query(
1440  "SHOW default_transaction_read_only",
1441  __METHOD__,
1442  self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE
1443  );
1444  $row = $this->fetchObject( $res );
1445 
1446  return $row ? ( strtolower( $row->default_transaction_read_only ) === 'on' ) : false;
1447  }
1448 
1449  protected static function getAttributes() {
1450  return [ self::ATTR_SCHEMAS_AS_TABLE_GROUPS => true ];
1451  }
1452 
1457  private function bigintFromLockName( $lockName ) {
1458  return \Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1459  }
1460 }
1461 
1465 class_alias( DatabasePostgres::class, 'DatabasePostgres' );
Wikimedia\Rdbms\DatabasePostgres\freeResult
freeResult( $res)
Free a result object returned by query() or select()It's usually not necessary to call this,...
Definition: DatabasePostgres.php:257
Wikimedia\Rdbms\Database\getLastPHPError
getLastPHPError()
Definition: Database.php:913
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:52
Wikimedia\Rdbms\DatabasePostgres\$keywordTableMap
null string[] $keywordTableMap
Map of (reserved table name => alternate table name)
Definition: DatabasePostgres.php:41
Wikimedia\Rdbms\DatabasePostgres\doLockTables
doLockTables(array $read, array $write, $method)
Helper function for lockTables() that handles the actual table locking.
Definition: DatabasePostgres.php:1348
Wikimedia\Rdbms\DatabasePostgres\numFields
numFields( $res)
Get the number of fields in a result object.
Definition: DatabasePostgres.php:321
Wikimedia\Rdbms\DatabasePostgres\bigintFromLockName
bigintFromLockName( $lockName)
Definition: DatabasePostgres.php:1457
Wikimedia\Rdbms\Database\getBindingHandle
getBindingHandle()
Get the underlying binding connection handle.
Definition: Database.php:5696
Wikimedia\Rdbms\DatabasePostgres\$port
int $port
Definition: DatabasePostgres.php:35
Wikimedia\Rdbms\DatabasePostgres\tableName
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.This does two important things: it quo...
Definition: DatabasePostgres.php:671
Wikimedia\Rdbms\DatabasePostgres\getSoftwareLink
getSoftwareLink()
Returns a wikitext style link to the DB's website (e.g.
Definition: DatabasePostgres.php:899
Wikimedia\Rdbms\DatabasePostgres\closeConnection
closeConnection()
Closes underlying database connection.
Definition: DatabasePostgres.php:204
Wikimedia\Rdbms\DatabasePostgres\relationExists
relationExists( $table, $types, $schema=false)
Query whether a given relation exists (in the given schema, or the default mw one if not given)
Definition: DatabasePostgres.php:1090
Wikimedia\Rdbms\DatabasePostgres\makeUpdateOptionsArray
makeUpdateOptionsArray( $options)
Make UPDATE options array for Database::makeUpdateOptions.
Definition: DatabasePostgres.php:604
Wikimedia\Rdbms\DatabasePostgres\getSchemas
getSchemas()
Return list of schemas which are accessible without schema name This is list does not contain magic k...
Definition: DatabasePostgres.php:931
Wikimedia\Rdbms\DatabasePostgres\remappedTableName
remappedTableName( $name)
Definition: DatabasePostgres.php:680
Wikimedia\Rdbms\DatabasePostgres\addQuotes
addQuotes( $s)
Escape and quote a raw value string for use in a SQL query.stringStability: stableto override
Definition: DatabasePostgres.php:1267
Wikimedia\Rdbms\Database\tableNamesN
tableNamesN(... $tables)
Fetch a number of table names into an zero-indexed numerical array This is handy when you need to con...
Definition: Database.php:3002
Wikimedia\Rdbms\DatabasePostgres\fetchAffectedRowCount
fetchAffectedRowCount()
Definition: DatabasePostgres.php:364
Wikimedia\Rdbms\DatabasePostgres\getAttributes
static getAttributes()
Definition: DatabasePostgres.php:1449
Wikimedia\Rdbms\DatabasePostgres\getCoreSchemas
getCoreSchemas()
Return schema names for temporary tables and core application tables.
Definition: DatabasePostgres.php:1044
n
while(( $__line=Maintenance::readconsole()) !==false) print n
Definition: eval.php:69
Wikimedia\Rdbms\DatabasePostgres\fieldInfo
fieldInfo( $table, $field)
Definition: DatabasePostgres.php:1234
Wikimedia\Rdbms\DatabasePostgres\makeSelectOptions
makeSelectOptions(array $options)
Returns an optional USE INDEX clause to go after the table, and a string to go at the end of the quer...
Definition: DatabasePostgres.php:1290
Wikimedia\Rdbms\DatabasePostgres\unlock
unlock( $lockName, $method)
Release a lock.Named locks are not related to transactionsName of lock to release Name of the calling...
Definition: DatabasePostgres.php:1418
true
return true
Definition: router.php:90
Wikimedia\Rdbms\DatabasePostgres\listTables
listTables( $prefix='', $fname=__METHOD__)
Definition: DatabasePostgres.php:824
Wikimedia\Rdbms\Database\$delimiter
string $delimiter
Current SQL query delimiter.
Definition: Database.php:110
Wikimedia\Rdbms\Database\endAtomic
endAtomic( $fname=__METHOD__)
Ends an atomic section of SQL statements.
Definition: Database.php:4495
Wikimedia\Rdbms\Database\indexName
indexName( $index)
Allows for index remapping in queries where this is not consistent across DBMS.
Definition: Database.php:3187
Wikimedia\Rdbms\DatabasePostgres\fieldType
fieldType( $res, $index)
pg_field_type() wrapper
Definition: DatabasePostgres.php:1244
Wikimedia\Rdbms\DatabaseDomain\getTablePrefix
getTablePrefix()
Definition: DatabaseDomain.php:193
Wikimedia\Rdbms\DatabasePostgres\open
open( $server, $user, $password, $db, $schema, $tablePrefix)
Open a new connection to the database (closing any existing one)
Definition: DatabasePostgres.php:91
Wikimedia\Rdbms\DatabasePostgres\$numericVersion
float string $numericVersion
Definition: DatabasePostgres.php:43
Wikimedia\Rdbms
Definition: ChronologyProtector.php:24
Wikimedia\Rdbms\Database\normalizeConditions
normalizeConditions( $conds, $fname)
Definition: Database.php:2206
Wikimedia\Rdbms\Database\$server
string null $server
Server that this instance is currently connected to.
Definition: Database.php:83
Wikimedia\Rdbms\Database\normalizeOptions
normalizeOptions( $options)
Definition: Database.php:2279
Wikimedia\Rdbms\DatabasePostgres\doInsertSelectNative
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',...
Definition: DatabasePostgres.php:630
Wikimedia\Rdbms\Database\extractSingleFieldFromList
extractSingleFieldFromList( $var)
Definition: Database.php:2309
DBO_SSL
const DBO_SSL
Definition: defines.php:17
Wikimedia\Rdbms\DatabasePostgres\makeInsertNonConflictingVerbAndOptions
makeInsertNonConflictingVerbAndOptions()
Definition: DatabasePostgres.php:560
Wikimedia\Rdbms\DatabaseDomain\getDatabase
getDatabase()
Definition: DatabaseDomain.php:179
Wikimedia\Rdbms\DatabasePostgres
Definition: DatabasePostgres.php:33
Wikimedia\Rdbms\DatabasePostgres\textFieldSize
textFieldSize( $table, $field)
Returns the size of a text field, or -1 for "unlimited".intStability: stableto override
Definition: DatabasePostgres.php:717
$res
$res
Definition: testCompression.php:57
Wikimedia\Rdbms\Database\cancelAtomic
cancelAtomic( $fname=__METHOD__, AtomicSectionIdentifier $sectionId=null)
Cancel an atomic section of SQL statements.
Definition: Database.php:4545
Wikimedia\Rdbms\Database\getFlag
getFlag( $flag)
Returns a boolean whether the flag $flag is set for this connection.
Definition: Database.php:859
Wikimedia\Rdbms\DatabasePostgres\indexUnique
indexUnique( $table, $index, $fname=__METHOD__)
Determines if a given index is unique.Calling function nameboolStability: stableto override
Definition: DatabasePostgres.php:492
Wikimedia\Rdbms\Database\doInsertSelectGeneric
doInsertSelectGeneric( $destTable, $srcTable, array $varMap, $conds, $fname, array $insertOptions, array $selectOptions, $selectJoinConds)
Implementation of insertSelect() based on select() and insert()
Definition: Database.php:3617
Wikimedia\Rdbms\DatabasePostgres\insertId
insertId()
Get the inserted value of an auto-increment row.
Definition: DatabasePostgres.php:329
Wikimedia\Rdbms\DatabasePostgres\fetchObject
fetchObject( $res)
Fetch the next row from the given result object, in object form.
Definition: DatabasePostgres.php:266
Wikimedia\Rdbms\Database\$affectedRowCount
int null $affectedRowCount
Rows affected by the last query to query() or its CRUD wrappers.
Definition: Database.php:183
Wikimedia\Rdbms\DatabasePostgres\aggregateValue
aggregateValue( $valuedata, $valuename='value')
Return aggregated value alias.array|string Since 1.33 Stability: stableto override
Definition: DatabasePostgres.php:895
Wikimedia\Rdbms\DatabasePostgres\roleExists
roleExists( $roleName)
Returns true if a given role (i.e.
Definition: DatabasePostgres.php:1218
Wikimedia\Rdbms\DatabasePostgres\$coreSchema
string $coreSchema
Definition: DatabasePostgres.php:37
Wikimedia\Rdbms\Database\close
close( $fname=__METHOD__, $owner=null)
Close the database connection.
Definition: Database.php:953
Wikimedia\Rdbms\DatabasePostgres\encodeBlob
encodeBlob( $b)
Some DBMSs have a special format for inserting into blob fields, they don't allow simple quoted strin...
Definition: DatabasePostgres.php:1248
Wikimedia\Rdbms\DatabasePostgres\makeConnectionString
makeConnectionString( $vars)
Definition: DatabasePostgres.php:195
wfDeprecatedMsg
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
Definition: GlobalFunctions.php:1028
Wikimedia\Rdbms\DatabasePostgres\lockIsFree
lockIsFree( $lockName, $method)
Check to see if a named lock is not locked by any thread (non-blocking)Name of lock to poll Name of m...
Definition: DatabasePostgres.php:1377
Wikimedia\Rdbms\DatabasePostgres\isTransactableQuery
isTransactableQuery( $sql)
Determine whether a SQL statement is sensitive to isolation level.
Definition: DatabasePostgres.php:208
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:996
Wikimedia\Rdbms\DatabasePostgres\schemaExists
schemaExists( $schema)
Query whether a given schema exists.
Definition: DatabasePostgres.php:1198
Wikimedia\Rdbms\DatabasePostgres\implicitOrderby
implicitOrderby()
Returns true if this database does an implicit order by when the column has an index For example: SEL...
Definition: DatabasePostgres.php:73
Wikimedia\Rdbms\Database\startAtomic
startAtomic( $fname=__METHOD__, $cancelable=self::ATOMIC_NOT_CANCELABLE)
Begin an atomic section of SQL statements.
Definition: Database.php:4433
Wikimedia\Rdbms\DatabasePostgres\limitResult
limitResult( $sql, $limit, $offset=false)
Construct a LIMIT query with optional offset.The SQL should be adjusted so that only the first $limit...
Definition: DatabasePostgres.php:735
Wikimedia\Rdbms\DatabasePostgres\duplicateTableStructure
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
Creates a new table with structure copied from existing table.Note that unlike most database abstract...
Definition: DatabasePostgres.php:760
Wikimedia\Rdbms\PostgresField\fromText
static fromText(DatabasePostgres $db, $table, $field)
Definition: PostgresField.php:15
Wikimedia\Rdbms\Database\trxLevel
trxLevel()
Gets the current transaction level.
Definition: Database.php:594
Wikimedia\Rdbms\DatabasePostgres\doQuery
doQuery( $sql)
Definition: DatabasePostgres.php:217
Wikimedia\Rdbms\DatabasePostgres\buildStringCast
buildStringCast( $field)
Field or column to cast string 1.28Stability: stableto override
Definition: DatabasePostgres.php:1331
Wikimedia\Rdbms\DatabasePostgres\$lastResultHandle
resource null $lastResultHandle
Definition: DatabasePostgres.php:46
Wikimedia\Rdbms\Database\makeInsertLists
makeInsertLists(array $rows)
Make SQL lists of columns, row tuples for INSERT/VALUES expressions.
Definition: Database.php:2446
Wikimedia\Rdbms\DatabasePostgres\pg_array_parse
pg_array_parse( $text, &$output, $limit=false, $offset=1)
Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12 to https://www.php.net/manual/en/ref....
Definition: DatabasePostgres.php:868
Wikimedia\Rdbms\DatabasePostgres\lastErrno
lastErrno()
Get the last error number.
Definition: DatabasePostgres.php:356
Wikimedia\Rdbms\DatabasePostgres\selectSQLText
selectSQLText( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Take the same arguments as IDatabase::select() and return the SQL it would use.This can be useful for...
Definition: DatabasePostgres.php:506
Wikimedia\Rdbms\DatabasePostgres\numRows
numRows( $res)
Get the number of rows in a query result.
Definition: DatabasePostgres.php:301
Wikimedia\Rdbms\NextSequenceValue
Used by Database::nextSequenceValue() so Database::insert() can detect values coming from the depreca...
Definition: NextSequenceValue.php:11
Wikimedia\Rdbms\DatabasePostgres\strencode
strencode( $s)
Wrapper for addslashes()
Definition: DatabasePostgres.php:1262
Wikimedia\Rdbms\DBQueryError
@newable
Definition: DBQueryError.php:29
Wikimedia\Rdbms\DatabasePostgres\wasConnectionError
wasConnectionError( $errno)
Do not use this method outside of Database/DBError classes.
Definition: DatabasePostgres.php:749
Wikimedia\Rdbms\Database\installErrorHandler
installErrorHandler()
Set a custom error handler for logging errors during database connection.
Definition: Database.php:890
Wikimedia\Rdbms\Database\restoreErrorHandler
restoreErrorHandler()
Restore the previous error handler and return the last PHP error for this DB.
Definition: Database.php:901
Wikimedia\Rdbms\DatabasePostgres\serverIsReadOnly
serverIsReadOnly()
bool Whether the DB is marked as read-only server-side 1.28Stability: stableto override
Definition: DatabasePostgres.php:1438
Wikimedia\Rdbms\DatabasePostgres\doTruncate
doTruncate(array $tables, $fname)
Definition: DatabasePostgres.php:812
$s
foreach( $mmfl['setupFiles'] as $fileName) if( $queue) if(empty( $mmfl['quiet'])) $s
Definition: mergeMessageFileList.php:206
Wikimedia\Rdbms\DatabasePostgres\timestamp
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by ConvertibleTimestamp to the format used for ins...
Definition: DatabasePostgres.php:844
Wikimedia\Rdbms\DatabasePostgres\relationSchemaQualifier
relationSchemaQualifier()
Definition: DatabasePostgres.php:159
Wikimedia\Rdbms\Database\query
query( $sql, $fname=__METHOD__, $flags=self::QUERY_NORMAL)
Run an SQL query and return the result.
Definition: Database.php:1272
Wikimedia\Rdbms\DatabasePostgres\decodeBlob
decodeBlob( $b)
Some DBMSs return a special placeholder object representing blob fields in result objects....
Definition: DatabasePostgres.php:1252
Wikimedia\Rdbms\DatabasePostgres\getCurrentSchema
getCurrentSchema()
Return current schema (executes SELECT current_schema()) Needs transaction.
Definition: DatabasePostgres.php:910
Wikimedia\Rdbms\Database\$user
string null $user
User that this instance is currently connected under the name of.
Definition: Database.php:85
Wikimedia\Rdbms\DBUnexpectedError
@newable
Definition: DBUnexpectedError.php:29
Wikimedia\Rdbms\DatabasePostgres\realTableName
realTableName( $name, $format='quoted')
Definition: DatabasePostgres.php:691
Wikimedia\Rdbms\Database\selectField
selectField( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a single field from a single result row.
Definition: Database.php:1797
Wikimedia\Rdbms\DatabasePostgres\nextSequenceValue
nextSequenceValue( $seqName)
Deprecated method, calls should be removed.
Definition: DatabasePostgres.php:695
Wikimedia\Rdbms\DatabasePostgres\buildConcat
buildConcat( $stringList)
Build a concatenation list to feed into a SQL query.Raw SQL expression list; caller is responsible fo...
Definition: DatabasePostgres.php:1319
Wikimedia\Rdbms\DatabasePostgres\getType
getType()
Get the RDBMS type of the server (e.g.
Definition: DatabasePostgres.php:69
Wikimedia\Rdbms\Database\addIdentifierQuotes
addIdentifierQuotes( $s)
Escape a SQL identifier (e.g.table, column, database) for use in a SQL queryDepending on the database...
Definition: Database.php:3214
Wikimedia\Rdbms\DatabasePostgres\getServerVersion
getServerVersion()
A string describing the current software version, like from mysql_get_server_info()
Definition: DatabasePostgres.php:1063
Wikimedia\Rdbms\DatabasePostgres\lastError
lastError()
Get a description of the last error.
Definition: DatabasePostgres.php:344
Wikimedia\Rdbms\Database\newExceptionAfterConnectError
newExceptionAfterConnectError( $error)
Definition: Database.php:1768
Wikimedia\Rdbms\DatabasePostgres\__construct
__construct(array $params)
Definition: DatabasePostgres.php:55
Wikimedia\Rdbms\DatabasePostgres\constraintExists
constraintExists( $table, $constraint)
Definition: DatabasePostgres.php:1173
Wikimedia\Rdbms\DatabasePostgres\wasLockTimeout
wasLockTimeout()
Determines if the last failure was due to a lock timeout.Note that during a lock wait timeout,...
Definition: DatabasePostgres.php:744
Wikimedia\Rdbms\DatabasePostgres\streamStatementEnd
streamStatementEnd(&$sql, &$newLine)
Called by sourceStream() to check if we've reached a statement end.
Definition: DatabasePostgres.php:1335
Wikimedia\Rdbms\Database\makeGroupByWithHaving
makeGroupByWithHaving( $options)
Returns an optional GROUP BY with an optional HAVING.
Definition: Database.php:1927
Wikimedia\Rdbms\DatabaseDomain\getSchema
getSchema()
Definition: DatabaseDomain.php:186
Wikimedia\Rdbms\DatabasePostgres\sequenceExists
sequenceExists( $sequence, $schema=false)
Definition: DatabasePostgres.php:1130
Wikimedia\Rdbms\DatabasePostgres\tableExists
tableExists( $table, $fname=__METHOD__, $schema=false)
For backward compatibility, this function checks both tables and views.
Definition: DatabasePostgres.php:1126
Wikimedia\Rdbms\DatabasePostgres\buildGroupConcatField
buildGroupConcatField( $delimiter, $table, $field, $conds='', $options=[], $join_conds=[])
Definition: DatabasePostgres.php:1323
Wikimedia\Rdbms\Database\makeOrderBy
makeOrderBy( $options)
Returns an optional ORDER BY.
Definition: Database.php:1953
Wikimedia\Rdbms\Database\$flags
int $flags
Current bit field of class DBO_* constants.
Definition: Database.php:106
Wikimedia\Rdbms\DatabasePostgres\dataSeek
dataSeek( $res, $row)
Change the position of the cursor in a result object.
Definition: DatabasePostgres.php:340
Wikimedia\Rdbms\DatabasePostgres\ruleExists
ruleExists( $table, $rule)
Definition: DatabasePostgres.php:1160
Wikimedia\Rdbms\Database\select
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
Definition: Database.php:1965
Wikimedia\Rdbms\DatabasePostgres\wasKnownStatementRollbackError
wasKnownStatementRollbackError()
Definition: DatabasePostgres.php:756
Wikimedia\Rdbms\DatabasePostgres\fetchRow
fetchRow( $res)
Fetch the next row from the given result object, in associative array form.
Definition: DatabasePostgres.php:285
Wikimedia\Rdbms\DatabasePostgres\fieldName
fieldName( $res, $n)
Get a field name in a result object.
Definition: DatabasePostgres.php:325
Wikimedia\Rdbms\DatabasePostgres\dumpError
dumpError()
Definition: DatabasePostgres.php:236
Wikimedia\Rdbms\Database\$password
string null $password
Password used to establish the current connection.
Definition: Database.php:87
Wikimedia\Rdbms\DatabasePostgres\determineCoreSchema
determineCoreSchema( $desiredSchema)
Determine default schema for the current application Adjust this session schema search path if desire...
Definition: DatabasePostgres.php:996
Wikimedia\Rdbms\DatabasePostgres\getSearchPath
getSearchPath()
Return search patch for schemas This is different from getSchemas() since it contain magic keywords (...
Definition: DatabasePostgres.php:954
Wikimedia\Rdbms\DatabasePostgres\getCoreSchema
getCoreSchema()
Return schema name for core application tables.
Definition: DatabasePostgres.php:1034
Wikimedia\Rdbms\DatabaseDomain
Class to handle database/schema/prefix specifications for IDatabase.
Definition: DatabaseDomain.php:40
Wikimedia\Rdbms\DatabasePostgres\indexInfo
indexInfo( $table, $index, $fname=__METHOD__)
Get information about an index into an object.
Definition: DatabasePostgres.php:410
Wikimedia\Rdbms\DatabasePostgres\$tempSchema
string $tempSchema
Definition: DatabasePostgres.php:39
Wikimedia\Rdbms\DatabasePostgres\triggerExists
triggerExists( $table, $trigger)
Definition: DatabasePostgres.php:1134
Wikimedia\Rdbms\DatabasePostgres\currentSequenceValue
currentSequenceValue( $seqName)
Return the current value of a sequence.
Definition: DatabasePostgres.php:705
Wikimedia\Rdbms\DatabasePostgres\setSearchPath
setSearchPath( $search_path)
Update search_path, values should already be sanitized Values may contain magic keywords like "$user"...
Definition: DatabasePostgres.php:974
Wikimedia\Rdbms\DatabasePostgres\wasDeadlock
wasDeadlock()
Determines if the last failure was due to a deadlock.Note that during a deadlock, the prior transacti...
Definition: DatabasePostgres.php:739
Wikimedia\Rdbms\DatabasePostgres\doSelectDomain
doSelectDomain(DatabaseDomain $domain)
Definition: DatabasePostgres.php:172
Wikimedia\Rdbms\ResultWrapper\unwrap
static & unwrap(&$res)
Get the underlying RDBMS driver-specific result resource.
Definition: ResultWrapper.php:59
Wikimedia\Rdbms\PostgresBlob
@newable
Definition: PostgresBlob.php:8
Wikimedia\Rdbms\DatabasePostgres\lock
lock( $lockName, $method, $timeout=5)
Acquire a named lock.Named locks are not related to transactionsName of lock to aquire Name of the ca...
Definition: DatabasePostgres.php:1394
Wikimedia\Rdbms\DatabasePostgres\estimateRowCount
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 ...
Definition: DatabasePostgres.php:387
Wikimedia\Rdbms\DatabasePostgres\hasConstraint
hasConstraint( $name)
Definition: DatabasePostgres.php:77
Wikimedia\Rdbms\Database\$conn
object resource null $conn
Database connection.
Definition: Database.php:77
Wikimedia\Rdbms\DatabasePostgres\databasesAreIndependent
databasesAreIndependent()
Returns true if DBs are assumed to be on potentially different servers.In systems like mysql/mariadb,...
Definition: DatabasePostgres.php:168
Wikimedia\Rdbms\Database\getDBname
getDBname()
Get the current database name; null if there isn't one.
Definition: Database.php:2867
Wikimedia\Rdbms\DatabasePostgres\indexAttributes
indexAttributes( $index, $schema=false)
Definition: DatabasePostgres.php:428
Wikimedia\Rdbms\DatabasePostgres\doInsertNonConflicting
doInsertNonConflicting( $table, array $rows, $fname)
Definition: DatabasePostgres.php:564
Wikimedia\Rdbms\Blob
@newable
Definition: Blob.php:9