MediaWiki  master
DatabasePostgres.php
Go to the documentation of this file.
1 <?php
23 namespace Wikimedia\Rdbms;
24 
29 
33 class DatabasePostgres extends Database {
35  protected $port;
36 
38  protected $lastResultHandle = null;
39 
41  private $numericVersion = null;
43  private $connectString;
45  private $coreSchema;
47  private $tempSchema;
49  private $keywordTableMap = [];
50 
56  public function __construct( array $params ) {
57  $this->port = $params['port'] ?? false;
58  $this->keywordTableMap = $params['keywordTableMap'] ?? [];
59 
60  parent::__construct( $params );
61  }
62 
63  public function getType() {
64  return 'postgres';
65  }
66 
67  public function implicitGroupby() {
68  return false;
69  }
70 
71  public function implicitOrderby() {
72  return false;
73  }
74 
75  public function hasConstraint( $name ) {
76  foreach ( $this->getCoreSchemas() as $schema ) {
77  $sql = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
78  "WHERE c.connamespace = n.oid AND conname = " .
79  $this->addQuotes( $name ) . " AND n.nspname = " .
80  $this->addQuotes( $schema );
81  $res = $this->doQuery( $sql );
82  if ( $res && $this->numRows( $res ) ) {
83  return true;
84  }
85  }
86  return false;
87  }
88 
89  protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
90  # Test for Postgres support, to avoid suppressed fatal error
91  if ( !function_exists( 'pg_connect' ) ) {
92  throw new DBConnectionError(
93  $this,
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)\n"
97  );
98  }
99 
100  $this->server = $server;
101  $this->user = $user;
102  $this->password = $password;
103 
104  $connectVars = [
105  // pg_connect() user $user as the default database. Since a database is *required*,
106  // at least pick a "don't care" database that is more likely to exist. This case
107  // arrises when LoadBalancer::getConnection( $i, [], '' ) is used.
108  'dbname' => strlen( $dbName ) ? $dbName : 'postgres',
109  'user' => $user,
110  'password' => $password
111  ];
112  if ( $server != false && $server != '' ) {
113  $connectVars['host'] = $server;
114  }
115  if ( (int)$this->port > 0 ) {
116  $connectVars['port'] = (int)$this->port;
117  }
118  if ( $this->flags & self::DBO_SSL ) {
119  $connectVars['sslmode'] = 'require';
120  }
121 
122  $this->connectString = $this->makeConnectionString( $connectVars );
123  $this->close();
124  $this->installErrorHandler();
125 
126  try {
127  // Use new connections to let LoadBalancer/LBFactory handle reuse
128  $this->conn = pg_connect( $this->connectString, PGSQL_CONNECT_FORCE_NEW );
129  } catch ( Exception $ex ) {
130  $this->restoreErrorHandler();
131  throw $ex;
132  }
133 
134  $phpError = $this->restoreErrorHandler();
135 
136  if ( !$this->conn ) {
137  $this->queryLogger->debug(
138  "DB connection error\n" .
139  "Server: $server, Database: $dbName, User: $user, Password: " .
140  substr( $password, 0, 3 ) . "...\n"
141  );
142  $this->queryLogger->debug( $this->lastError() . "\n" );
143  throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
144  }
145 
146  $this->opened = true;
147 
148  # If called from the command-line (e.g. importDump), only show errors
149  if ( $this->cliMode ) {
150  $this->doQuery( "SET client_min_messages = 'ERROR'" );
151  }
152 
153  $this->query( "SET client_encoding='UTF8'", __METHOD__ );
154  $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__ );
155  $this->query( "SET timezone = 'GMT'", __METHOD__ );
156  $this->query( "SET standard_conforming_strings = on", __METHOD__ );
157  $this->query( "SET bytea_output = 'escape'", __METHOD__ ); // PHP bug 53127
158 
159  $this->determineCoreSchema( $schema );
160  $this->currentDomain = new DatabaseDomain( $dbName, $schema, $tablePrefix );
161 
162  return (bool)$this->conn;
163  }
164 
165  protected function relationSchemaQualifier() {
166  if ( $this->coreSchema === $this->currentDomain->getSchema() ) {
167  // The schema to be used is now in the search path; no need for explicit qualification
168  return '';
169  }
170 
171  return parent::relationSchemaQualifier();
172  }
173 
174  public function databasesAreIndependent() {
175  return true;
176  }
177 
178  public function doSelectDomain( DatabaseDomain $domain ) {
179  if ( $this->getDBname() !== $domain->getDatabase() ) {
180  // Postgres doesn't support selectDB in the same way MySQL does.
181  // So if the DB name doesn't match the open connection, open a new one
182  $this->open(
183  $this->server,
184  $this->user,
185  $this->password,
186  $domain->getDatabase(),
187  $domain->getSchema(),
188  $domain->getTablePrefix()
189  );
190  } else {
191  $this->currentDomain = $domain;
192  }
193 
194  return true;
195  }
196 
201  private function makeConnectionString( $vars ) {
202  $s = '';
203  foreach ( $vars as $name => $value ) {
204  $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
205  }
206 
207  return $s;
208  }
209 
210  protected function closeConnection() {
211  return $this->conn ? pg_close( $this->conn ) : true;
212  }
213 
214  protected function isTransactableQuery( $sql ) {
215  return parent::isTransactableQuery( $sql ) &&
216  !preg_match( '/^SELECT\s+pg_(try_|)advisory_\w+\(/', $sql );
217  }
218 
223  public function doQuery( $sql ) {
224  $conn = $this->getBindingHandle();
225 
226  $sql = mb_convert_encoding( $sql, 'UTF-8' );
227  // Clear previously left over PQresult
228  while ( $res = pg_get_result( $conn ) ) {
229  pg_free_result( $res );
230  }
231  if ( pg_send_query( $conn, $sql ) === false ) {
232  throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
233  }
234  $this->lastResultHandle = pg_get_result( $conn );
235  if ( pg_result_error( $this->lastResultHandle ) ) {
236  return false;
237  }
238 
240  }
241 
242  protected function dumpError() {
243  $diags = [
244  PGSQL_DIAG_SEVERITY,
245  PGSQL_DIAG_SQLSTATE,
246  PGSQL_DIAG_MESSAGE_PRIMARY,
247  PGSQL_DIAG_MESSAGE_DETAIL,
248  PGSQL_DIAG_MESSAGE_HINT,
249  PGSQL_DIAG_STATEMENT_POSITION,
250  PGSQL_DIAG_INTERNAL_POSITION,
251  PGSQL_DIAG_INTERNAL_QUERY,
252  PGSQL_DIAG_CONTEXT,
253  PGSQL_DIAG_SOURCE_FILE,
254  PGSQL_DIAG_SOURCE_LINE,
255  PGSQL_DIAG_SOURCE_FUNCTION
256  ];
257  foreach ( $diags as $d ) {
258  $this->queryLogger->debug( sprintf( "PgSQL ERROR(%d): %s\n",
259  $d, pg_result_error_field( $this->lastResultHandle, $d ) ) );
260  }
261  }
262 
263  public function freeResult( $res ) {
264  if ( $res instanceof ResultWrapper ) {
265  $res = $res->result;
266  }
267  Wikimedia\suppressWarnings();
268  $ok = pg_free_result( $res );
269  Wikimedia\restoreWarnings();
270  if ( !$ok ) {
271  throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
272  }
273  }
274 
275  public function fetchObject( $res ) {
276  if ( $res instanceof ResultWrapper ) {
277  $res = $res->result;
278  }
279  Wikimedia\suppressWarnings();
280  $row = pg_fetch_object( $res );
281  Wikimedia\restoreWarnings();
282  # @todo FIXME: HACK HACK HACK HACK debug
283 
284  # @todo hashar: not sure if the following test really trigger if the object
285  # fetching failed.
286  $conn = $this->getBindingHandle();
287  if ( pg_last_error( $conn ) ) {
288  throw new DBUnexpectedError(
289  $this,
290  'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
291  );
292  }
293 
294  return $row;
295  }
296 
297  public function fetchRow( $res ) {
298  if ( $res instanceof ResultWrapper ) {
299  $res = $res->result;
300  }
301  Wikimedia\suppressWarnings();
302  $row = pg_fetch_array( $res );
303  Wikimedia\restoreWarnings();
304 
305  $conn = $this->getBindingHandle();
306  if ( pg_last_error( $conn ) ) {
307  throw new DBUnexpectedError(
308  $this,
309  'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
310  );
311  }
312 
313  return $row;
314  }
315 
316  public function numRows( $res ) {
317  if ( $res === false ) {
318  return 0;
319  }
320 
321  if ( $res instanceof ResultWrapper ) {
322  $res = $res->result;
323  }
324  Wikimedia\suppressWarnings();
325  $n = pg_num_rows( $res );
326  Wikimedia\restoreWarnings();
327 
328  $conn = $this->getBindingHandle();
329  if ( pg_last_error( $conn ) ) {
330  throw new DBUnexpectedError(
331  $this,
332  'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
333  );
334  }
335 
336  return $n;
337  }
338 
339  public function numFields( $res ) {
340  if ( $res instanceof ResultWrapper ) {
341  $res = $res->result;
342  }
343 
344  return pg_num_fields( $res );
345  }
346 
347  public function fieldName( $res, $n ) {
348  if ( $res instanceof ResultWrapper ) {
349  $res = $res->result;
350  }
351 
352  return pg_field_name( $res, $n );
353  }
354 
355  public function insertId() {
356  $res = $this->query( "SELECT lastval()" );
357  $row = $this->fetchRow( $res );
358  return is_null( $row[0] ) ? null : (int)$row[0];
359  }
360 
361  public function dataSeek( $res, $row ) {
362  if ( $res instanceof ResultWrapper ) {
363  $res = $res->result;
364  }
365 
366  return pg_result_seek( $res, $row );
367  }
368 
369  public function lastError() {
370  if ( $this->conn ) {
371  if ( $this->lastResultHandle ) {
372  return pg_result_error( $this->lastResultHandle );
373  } else {
374  return pg_last_error();
375  }
376  }
377 
378  return $this->getLastPHPError() ?: 'No database connection';
379  }
380 
381  public function lastErrno() {
382  if ( $this->lastResultHandle ) {
383  return pg_result_error_field( $this->lastResultHandle, PGSQL_DIAG_SQLSTATE );
384  } else {
385  return false;
386  }
387  }
388 
389  protected function fetchAffectedRowCount() {
390  if ( !$this->lastResultHandle ) {
391  return 0;
392  }
393 
394  return pg_affected_rows( $this->lastResultHandle );
395  }
396 
412  public function estimateRowCount( $table, $var = '*', $conds = '',
413  $fname = __METHOD__, $options = [], $join_conds = []
414  ) {
415  $conds = $this->normalizeConditions( $conds, $fname );
416  $column = $this->extractSingleFieldFromList( $var );
417  if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
418  $conds[] = "$column IS NOT NULL";
419  }
420 
421  $options['EXPLAIN'] = true;
422  $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
423  $rows = -1;
424  if ( $res ) {
425  $row = $this->fetchRow( $res );
426  $count = [];
427  if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
428  $rows = (int)$count[1];
429  }
430  }
431 
432  return $rows;
433  }
434 
435  public function indexInfo( $table, $index, $fname = __METHOD__ ) {
436  $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
437  $res = $this->query( $sql, $fname );
438  if ( !$res ) {
439  return null;
440  }
441  foreach ( $res as $row ) {
442  if ( $row->indexname == $this->indexName( $index ) ) {
443  return $row;
444  }
445  }
446 
447  return false;
448  }
449 
450  public function indexAttributes( $index, $schema = false ) {
451  if ( $schema === false ) {
452  $schemas = $this->getCoreSchemas();
453  } else {
454  $schemas = [ $schema ];
455  }
456 
457  $eindex = $this->addQuotes( $index );
458 
459  foreach ( $schemas as $schema ) {
460  $eschema = $this->addQuotes( $schema );
461  /*
462  * A subquery would be not needed if we didn't care about the order
463  * of attributes, but we do
464  */
465  $sql = <<<__INDEXATTR__
466 
467  SELECT opcname,
468  attname,
469  i.indoption[s.g] as option,
470  pg_am.amname
471  FROM
472  (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
473  FROM
474  pg_index isub
475  JOIN pg_class cis
476  ON cis.oid=isub.indexrelid
477  JOIN pg_namespace ns
478  ON cis.relnamespace = ns.oid
479  WHERE cis.relname=$eindex AND ns.nspname=$eschema) AS s,
480  pg_attribute,
481  pg_opclass opcls,
482  pg_am,
483  pg_class ci
484  JOIN pg_index i
485  ON ci.oid=i.indexrelid
486  JOIN pg_class ct
487  ON ct.oid = i.indrelid
488  JOIN pg_namespace n
489  ON ci.relnamespace = n.oid
490  WHERE
491  ci.relname=$eindex AND n.nspname=$eschema
492  AND attrelid = ct.oid
493  AND i.indkey[s.g] = attnum
494  AND i.indclass[s.g] = opcls.oid
495  AND pg_am.oid = opcls.opcmethod
496 __INDEXATTR__;
497  $res = $this->query( $sql, __METHOD__ );
498  $a = [];
499  if ( $res ) {
500  foreach ( $res as $row ) {
501  $a[] = [
502  $row->attname,
503  $row->opcname,
504  $row->amname,
505  $row->option ];
506  }
507  return $a;
508  }
509  }
510  return null;
511  }
512 
513  public function indexUnique( $table, $index, $fname = __METHOD__ ) {
514  $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
515  " AND indexdef LIKE 'CREATE UNIQUE%(" .
516  $this->strencode( $this->indexName( $index ) ) .
517  ")'";
518  $res = $this->query( $sql, $fname );
519  if ( !$res ) {
520  return null;
521  }
522 
523  return $res->numRows() > 0;
524  }
525 
526  public function selectSQLText(
527  $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
528  ) {
529  if ( is_string( $options ) ) {
530  $options = [ $options ];
531  }
532 
533  // Change the FOR UPDATE option as necessary based on the join conditions. Then pass
534  // to the parent function to get the actual SQL text.
535  // In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
536  // can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to
537  // do so causes a DB error. This wrapper checks which tables can be locked and adjusts it
538  // accordingly.
539  // MySQL uses "ORDER BY NULL" as an optimization hint, but that is illegal in PostgreSQL.
540  if ( is_array( $options ) ) {
541  $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
542  if ( $forUpdateKey !== false && $join_conds ) {
543  unset( $options[$forUpdateKey] );
544  $options['FOR UPDATE'] = [];
545 
546  $toCheck = $table;
547  reset( $toCheck );
548  while ( $toCheck ) {
549  $alias = key( $toCheck );
550  $name = $toCheck[$alias];
551  unset( $toCheck[$alias] );
552 
553  $hasAlias = !is_numeric( $alias );
554  if ( !$hasAlias && is_string( $name ) ) {
555  $alias = $name;
556  }
557 
558  if ( !isset( $join_conds[$alias] ) ||
559  !preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_conds[$alias][0] )
560  ) {
561  if ( is_array( $name ) ) {
562  // It's a parenthesized group, process all the tables inside the group.
563  $toCheck = array_merge( $toCheck, $name );
564  } else {
565  // Quote alias names so $this->tableName() won't mangle them
566  $options['FOR UPDATE'][] = $hasAlias ? $this->addIdentifierQuotes( $alias ) : $alias;
567  }
568  }
569  }
570  }
571 
572  if ( isset( $options['ORDER BY'] ) && $options['ORDER BY'] == 'NULL' ) {
573  unset( $options['ORDER BY'] );
574  }
575  }
576 
577  return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
578  }
579 
581  public function insert( $table, $args, $fname = __METHOD__, $options = [] ) {
582  if ( !count( $args ) ) {
583  return true;
584  }
585 
586  $table = $this->tableName( $table );
587  if ( !isset( $this->numericVersion ) ) {
588  $this->getServerVersion();
589  }
590 
591  if ( !is_array( $options ) ) {
592  $options = [ $options ];
593  }
594 
595  if ( isset( $args[0] ) && is_array( $args[0] ) ) {
596  $rows = $args;
597  $keys = array_keys( $args[0] );
598  } else {
599  $rows = [ $args ];
600  $keys = array_keys( $args );
601  }
602 
603  $ignore = in_array( 'IGNORE', $options );
604 
605  $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
606 
607  if ( $this->numericVersion >= 9.5 || !$ignore ) {
608  // No IGNORE or our PG has "ON CONFLICT DO NOTHING"
609  $first = true;
610  foreach ( $rows as $row ) {
611  if ( $first ) {
612  $first = false;
613  } else {
614  $sql .= ',';
615  }
616  $sql .= '(' . $this->makeList( $row ) . ')';
617  }
618  if ( $ignore ) {
619  $sql .= ' ON CONFLICT DO NOTHING';
620  }
621  $this->query( $sql, $fname );
622  } else {
623  // Emulate IGNORE by doing each row individually, with savepoints
624  // to roll back as necessary.
625  $numrowsinserted = 0;
626 
627  $tok = $this->startAtomic( "$fname (outer)", self::ATOMIC_CANCELABLE );
628  try {
629  foreach ( $rows as $row ) {
630  $tempsql = $sql;
631  $tempsql .= '(' . $this->makeList( $row ) . ')';
632 
633  $this->startAtomic( "$fname (inner)", self::ATOMIC_CANCELABLE );
634  try {
635  $this->query( $tempsql, $fname );
636  $this->endAtomic( "$fname (inner)" );
637  $numrowsinserted++;
638  } catch ( DBQueryError $e ) {
639  $this->cancelAtomic( "$fname (inner)" );
640  // Our IGNORE is supposed to ignore duplicate key errors, but not others.
641  // (even though MySQL's version apparently ignores all errors)
642  if ( $e->errno !== '23505' ) {
643  throw $e;
644  }
645  }
646  }
647  } catch ( Exception $e ) {
648  $this->cancelAtomic( "$fname (outer)", $tok );
649  throw $e;
650  }
651  $this->endAtomic( "$fname (outer)" );
652 
653  // Set the affected row count for the whole operation
654  $this->affectedRowCount = $numrowsinserted;
655  }
656 
657  return true;
658  }
659 
660  protected function makeUpdateOptionsArray( $options ) {
661  if ( !is_array( $options ) ) {
662  $options = [ $options ];
663  }
664 
665  // PostgreSQL doesn't support anything like "ignore" for
666  // UPDATE.
667  $options = array_diff( $options, [ 'IGNORE' ] );
668 
669  return parent::makeUpdateOptionsArray( $options );
670  }
671 
690  protected function nativeInsertSelect(
691  $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
692  $insertOptions = [], $selectOptions = [], $selectJoinConds = []
693  ) {
694  if ( !is_array( $insertOptions ) ) {
695  $insertOptions = [ $insertOptions ];
696  }
697 
698  if ( in_array( 'IGNORE', $insertOptions ) ) {
699  if ( $this->getServerVersion() >= 9.5 ) {
700  // Use ON CONFLICT DO NOTHING if we have it for IGNORE
701  $destTable = $this->tableName( $destTable );
702 
703  $selectSql = $this->selectSQLText(
704  $srcTable,
705  array_values( $varMap ),
706  $conds,
707  $fname,
708  $selectOptions,
709  $selectJoinConds
710  );
711 
712  $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
713  $selectSql . ' ON CONFLICT DO NOTHING';
714 
715  $this->query( $sql, $fname );
716  } else {
717  // IGNORE and we don't have ON CONFLICT DO NOTHING, so just use the non-native version
718  $this->nonNativeInsertSelect(
719  $destTable, $srcTable, $varMap, $conds, $fname,
720  $insertOptions, $selectOptions, $selectJoinConds
721  );
722  }
723  } else {
724  parent::nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname,
725  $insertOptions, $selectOptions, $selectJoinConds );
726  }
727  }
728 
729  public function tableName( $name, $format = 'quoted' ) {
730  // Replace reserved words with better ones
731  $name = $this->remappedTableName( $name );
732 
733  return parent::tableName( $name, $format );
734  }
735 
740  public function remappedTableName( $name ) {
741  return $this->keywordTableMap[$name] ?? $name;
742  }
743 
749  public function realTableName( $name, $format = 'quoted' ) {
750  return parent::tableName( $name, $format );
751  }
752 
753  public function nextSequenceValue( $seqName ) {
754  return new NextSequenceValue;
755  }
756 
763  public function currentSequenceValue( $seqName ) {
764  $safeseq = str_replace( "'", "''", $seqName );
765  $res = $this->query( "SELECT currval('$safeseq')" );
766  $row = $this->fetchRow( $res );
767  $currval = $row[0];
768 
769  return $currval;
770  }
771 
772  public function textFieldSize( $table, $field ) {
773  $table = $this->tableName( $table );
774  $sql = "SELECT t.typname as ftype,a.atttypmod as size
775  FROM pg_class c, pg_attribute a, pg_type t
776  WHERE relname='$table' AND a.attrelid=c.oid AND
777  a.atttypid=t.oid and a.attname='$field'";
778  $res = $this->query( $sql );
779  $row = $this->fetchObject( $res );
780  if ( $row->ftype == 'varchar' ) {
781  $size = $row->size - 4;
782  } else {
783  $size = $row->size;
784  }
785 
786  return $size;
787  }
788 
789  public function limitResult( $sql, $limit, $offset = false ) {
790  return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
791  }
792 
793  public function wasDeadlock() {
794  // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
795  return $this->lastErrno() === '40P01';
796  }
797 
798  public function wasLockTimeout() {
799  // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
800  return $this->lastErrno() === '55P03';
801  }
802 
803  public function wasConnectionError( $errno ) {
804  // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
805  static $codes = [ '08000', '08003', '08006', '08001', '08004', '57P01', '57P03', '53300' ];
806 
807  return in_array( $errno, $codes, true );
808  }
809 
810  protected function wasKnownStatementRollbackError() {
811  return false; // transaction has to be rolled-back from error state
812  }
813 
814  public function duplicateTableStructure(
815  $oldName, $newName, $temporary = false, $fname = __METHOD__
816  ) {
817  $newNameE = $this->addIdentifierQuotes( $newName );
818  $oldNameE = $this->addIdentifierQuotes( $oldName );
819 
820  $temporary = $temporary ? 'TEMPORARY' : '';
821 
822  $ret = $this->query(
823  "CREATE $temporary TABLE $newNameE " .
824  "(LIKE $oldNameE INCLUDING DEFAULTS INCLUDING INDEXES)",
825  $fname,
826  $this::QUERY_PSEUDO_PERMANENT
827  );
828  if ( !$ret ) {
829  return $ret;
830  }
831 
832  $res = $this->query( 'SELECT attname FROM pg_class c'
833  . ' JOIN pg_namespace n ON (n.oid = c.relnamespace)'
834  . ' JOIN pg_attribute a ON (a.attrelid = c.oid)'
835  . ' JOIN pg_attrdef d ON (c.oid=d.adrelid and a.attnum=d.adnum)'
836  . ' WHERE relkind = \'r\''
837  . ' AND nspname = ' . $this->addQuotes( $this->getCoreSchema() )
838  . ' AND relname = ' . $this->addQuotes( $oldName )
839  . ' AND pg_get_expr(adbin, adrelid) LIKE \'nextval(%\'',
840  $fname
841  );
842  $row = $this->fetchObject( $res );
843  if ( $row ) {
844  $field = $row->attname;
845  $newSeq = "{$newName}_{$field}_seq";
846  $fieldE = $this->addIdentifierQuotes( $field );
847  $newSeqE = $this->addIdentifierQuotes( $newSeq );
848  $newSeqQ = $this->addQuotes( $newSeq );
849  $this->query(
850  "CREATE $temporary SEQUENCE $newSeqE OWNED BY $newNameE.$fieldE",
851  $fname
852  );
853  $this->query(
854  "ALTER TABLE $newNameE ALTER COLUMN $fieldE SET DEFAULT nextval({$newSeqQ}::regclass)",
855  $fname
856  );
857  }
858 
859  return $ret;
860  }
861 
862  public function resetSequenceForTable( $table, $fname = __METHOD__ ) {
863  $table = $this->tableName( $table, 'raw' );
864  foreach ( $this->getCoreSchemas() as $schema ) {
865  $res = $this->query(
866  'SELECT c.oid FROM pg_class c JOIN pg_namespace n ON (n.oid = c.relnamespace)'
867  . ' WHERE relkind = \'r\''
868  . ' AND nspname = ' . $this->addQuotes( $schema )
869  . ' AND relname = ' . $this->addQuotes( $table ),
870  $fname
871  );
872  if ( !$res || !$this->numRows( $res ) ) {
873  continue;
874  }
875 
876  $oid = $this->fetchObject( $res )->oid;
877  $res = $this->query( 'SELECT pg_get_expr(adbin, adrelid) AS adsrc FROM pg_attribute a'
878  . ' JOIN pg_attrdef d ON (a.attrelid=d.adrelid and a.attnum=d.adnum)'
879  . " WHERE a.attrelid = $oid"
880  . ' AND pg_get_expr(adbin, adrelid) LIKE \'nextval(%\'',
881  $fname
882  );
883  $row = $this->fetchObject( $res );
884  if ( $row ) {
885  $this->query(
886  'SELECT ' . preg_replace( '/^nextval\((.+)\)$/', 'setval($1,1,false)', $row->adsrc ),
887  $fname
888  );
889  return true;
890  }
891  return false;
892  }
893 
894  return false;
895  }
896 
900  public function listTables( $prefix = null, $fname = __METHOD__ ) {
901  $eschemas = implode( ',', array_map( [ $this, 'addQuotes' ], $this->getCoreSchemas() ) );
902  $result = $this->query(
903  "SELECT DISTINCT tablename FROM pg_tables WHERE schemaname IN ($eschemas)", $fname );
904  $endArray = [];
905 
906  foreach ( $result as $table ) {
907  $vars = get_object_vars( $table );
908  $table = array_pop( $vars );
909  if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
910  $endArray[] = $table;
911  }
912  }
913 
914  return $endArray;
915  }
916 
917  public function timestamp( $ts = 0 ) {
918  $ct = new ConvertibleTimestamp( $ts );
919 
920  return $ct->getTimestamp( TS_POSTGRES );
921  }
922 
941  private function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
942  if ( $limit === false ) {
943  $limit = strlen( $text ) - 1;
944  $output = [];
945  }
946  if ( $text == '{}' ) {
947  return $output;
948  }
949  do {
950  if ( $text[$offset] != '{' ) {
951  preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
952  $text, $match, 0, $offset );
953  $offset += strlen( $match[0] );
954  $output[] = ( $match[1][0] != '"'
955  ? $match[1]
956  : stripcslashes( substr( $match[1], 1, -1 ) ) );
957  if ( $match[3] == '},' ) {
958  return $output;
959  }
960  } else {
961  $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
962  }
963  } while ( $limit > $offset );
964 
965  return $output;
966  }
967 
968  public function aggregateValue( $valuedata, $valuename = 'value' ) {
969  return $valuedata;
970  }
971 
972  public function getSoftwareLink() {
973  return '[{{int:version-db-postgres-url}} PostgreSQL]';
974  }
975 
983  public function getCurrentSchema() {
984  $res = $this->query( "SELECT current_schema()", __METHOD__ );
985  $row = $this->fetchRow( $res );
986 
987  return $row[0];
988  }
989 
1000  public function getSchemas() {
1001  $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
1002  $row = $this->fetchRow( $res );
1003  $schemas = [];
1004 
1005  /* PHP pgsql support does not support array type, "{a,b}" string is returned */
1006 
1007  return $this->pg_array_parse( $row[0], $schemas );
1008  }
1009 
1019  public function getSearchPath() {
1020  $res = $this->query( "SHOW search_path", __METHOD__ );
1021  $row = $this->fetchRow( $res );
1022 
1023  /* PostgreSQL returns SHOW values as strings */
1024 
1025  return explode( ",", $row[0] );
1026  }
1027 
1035  private function setSearchPath( $search_path ) {
1036  $this->query( "SET search_path = " . implode( ", ", $search_path ) );
1037  }
1038 
1053  public function determineCoreSchema( $desiredSchema ) {
1054  $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
1055  if ( $this->schemaExists( $desiredSchema ) ) {
1056  if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
1057  $this->coreSchema = $desiredSchema;
1058  $this->queryLogger->debug(
1059  "Schema \"" . $desiredSchema . "\" already in the search path\n" );
1060  } else {
1066  $search_path = $this->getSearchPath();
1067  array_unshift( $search_path,
1068  $this->addIdentifierQuotes( $desiredSchema ) );
1069  $this->setSearchPath( $search_path );
1070  $this->coreSchema = $desiredSchema;
1071  $this->queryLogger->debug(
1072  "Schema \"" . $desiredSchema . "\" added to the search path\n" );
1073  }
1074  } else {
1075  $this->coreSchema = $this->getCurrentSchema();
1076  $this->queryLogger->debug(
1077  "Schema \"" . $desiredSchema . "\" not found, using current \"" .
1078  $this->coreSchema . "\"\n" );
1079  }
1080  /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1081  $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
1082  }
1083 
1090  public function getCoreSchema() {
1091  return $this->coreSchema;
1092  }
1093 
1100  public function getCoreSchemas() {
1101  if ( $this->tempSchema ) {
1102  return [ $this->tempSchema, $this->getCoreSchema() ];
1103  }
1104 
1105  $res = $this->query(
1106  "SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = pg_my_temp_schema()", __METHOD__
1107  );
1108  $row = $this->fetchObject( $res );
1109  if ( $row ) {
1110  $this->tempSchema = $row->nspname;
1111  return [ $this->tempSchema, $this->getCoreSchema() ];
1112  }
1113 
1114  return [ $this->getCoreSchema() ];
1115  }
1116 
1117  public function getServerVersion() {
1118  if ( !isset( $this->numericVersion ) ) {
1119  $conn = $this->getBindingHandle();
1120  $versionInfo = pg_version( $conn );
1121  if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1122  // Old client, abort install
1123  $this->numericVersion = '7.3 or earlier';
1124  } elseif ( isset( $versionInfo['server'] ) ) {
1125  // Normal client
1126  $this->numericVersion = $versionInfo['server'];
1127  } else {
1128  // T18937: broken pgsql extension from PHP<5.3
1129  $this->numericVersion = pg_parameter_status( $conn, 'server_version' );
1130  }
1131  }
1132 
1133  return $this->numericVersion;
1134  }
1135 
1144  private function relationExists( $table, $types, $schema = false ) {
1145  if ( !is_array( $types ) ) {
1146  $types = [ $types ];
1147  }
1148  if ( $schema === false ) {
1149  $schemas = $this->getCoreSchemas();
1150  } else {
1151  $schemas = [ $schema ];
1152  }
1153  $table = $this->realTableName( $table, 'raw' );
1154  $etable = $this->addQuotes( $table );
1155  foreach ( $schemas as $schema ) {
1156  $eschema = $this->addQuotes( $schema );
1157  $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1158  . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1159  . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1160  $res = $this->query( $sql );
1161  if ( $res && $res->numRows() ) {
1162  return true;
1163  }
1164  }
1165 
1166  return false;
1167  }
1168 
1176  public function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1177  return $this->relationExists( $table, [ 'r', 'v' ], $schema );
1178  }
1179 
1180  public function sequenceExists( $sequence, $schema = false ) {
1181  return $this->relationExists( $sequence, 'S', $schema );
1182  }
1183 
1184  public function triggerExists( $table, $trigger ) {
1185  $q = <<<SQL
1186  SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1187  WHERE relnamespace=pg_namespace.oid AND relkind='r'
1188  AND tgrelid=pg_class.oid
1189  AND nspname=%s AND relname=%s AND tgname=%s
1190 SQL;
1191  foreach ( $this->getCoreSchemas() as $schema ) {
1192  $res = $this->query(
1193  sprintf(
1194  $q,
1195  $this->addQuotes( $schema ),
1196  $this->addQuotes( $table ),
1197  $this->addQuotes( $trigger )
1198  )
1199  );
1200  if ( $res && $res->numRows() ) {
1201  return true;
1202  }
1203  }
1204 
1205  return false;
1206  }
1207 
1208  public function ruleExists( $table, $rule ) {
1209  $exists = $this->selectField( 'pg_rules', 'rulename',
1210  [
1211  'rulename' => $rule,
1212  'tablename' => $table,
1213  'schemaname' => $this->getCoreSchemas()
1214  ]
1215  );
1216 
1217  return $exists === $rule;
1218  }
1219 
1220  public function constraintExists( $table, $constraint ) {
1221  foreach ( $this->getCoreSchemas() as $schema ) {
1222  $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1223  "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1224  $this->addQuotes( $schema ),
1225  $this->addQuotes( $table ),
1226  $this->addQuotes( $constraint )
1227  );
1228  $res = $this->query( $sql );
1229  if ( $res && $res->numRows() ) {
1230  return true;
1231  }
1232  }
1233  return false;
1234  }
1235 
1241  public function schemaExists( $schema ) {
1242  if ( !strlen( $schema ) ) {
1243  return false; // short-circuit
1244  }
1245 
1246  $exists = $this->selectField(
1247  '"pg_catalog"."pg_namespace"', 1, [ 'nspname' => $schema ], __METHOD__ );
1248 
1249  return (bool)$exists;
1250  }
1251 
1257  public function roleExists( $roleName ) {
1258  $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1259  [ 'rolname' => $roleName ], __METHOD__ );
1260 
1261  return (bool)$exists;
1262  }
1263 
1269  public function fieldInfo( $table, $field ) {
1270  return PostgresField::fromText( $this, $table, $field );
1271  }
1272 
1279  public function fieldType( $res, $index ) {
1280  if ( $res instanceof ResultWrapper ) {
1281  $res = $res->result;
1282  }
1283 
1284  return pg_field_type( $res, $index );
1285  }
1286 
1287  public function encodeBlob( $b ) {
1288  return new PostgresBlob( pg_escape_bytea( $b ) );
1289  }
1290 
1291  public function decodeBlob( $b ) {
1292  if ( $b instanceof PostgresBlob ) {
1293  $b = $b->fetch();
1294  } elseif ( $b instanceof Blob ) {
1295  return $b->fetch();
1296  }
1297 
1298  return pg_unescape_bytea( $b );
1299  }
1300 
1301  public function strencode( $s ) {
1302  // Should not be called by us
1303  return pg_escape_string( $this->getBindingHandle(), (string)$s );
1304  }
1305 
1306  public function addQuotes( $s ) {
1307  $conn = $this->getBindingHandle();
1308 
1309  if ( is_null( $s ) ) {
1310  return 'NULL';
1311  } elseif ( is_bool( $s ) ) {
1312  return intval( $s );
1313  } elseif ( $s instanceof Blob ) {
1314  if ( $s instanceof PostgresBlob ) {
1315  $s = $s->fetch();
1316  } else {
1317  $s = pg_escape_bytea( $conn, $s->fetch() );
1318  }
1319  return "'$s'";
1320  } elseif ( $s instanceof NextSequenceValue ) {
1321  return 'DEFAULT';
1322  }
1323 
1324  return "'" . pg_escape_string( $conn, (string)$s ) . "'";
1325  }
1326 
1327  public function makeSelectOptions( $options ) {
1328  $preLimitTail = $postLimitTail = '';
1329  $startOpts = $useIndex = $ignoreIndex = '';
1330 
1331  $noKeyOptions = [];
1332  foreach ( $options as $key => $option ) {
1333  if ( is_numeric( $key ) ) {
1334  $noKeyOptions[$option] = true;
1335  }
1336  }
1337 
1338  $preLimitTail .= $this->makeGroupByWithHaving( $options );
1339 
1340  $preLimitTail .= $this->makeOrderBy( $options );
1341 
1342  if ( isset( $options['FOR UPDATE'] ) ) {
1343  $postLimitTail .= ' FOR UPDATE OF ' .
1344  implode( ', ', array_map( [ $this, 'tableName' ], $options['FOR UPDATE'] ) );
1345  } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1346  $postLimitTail .= ' FOR UPDATE';
1347  }
1348 
1349  if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1350  $startOpts .= 'DISTINCT';
1351  }
1352 
1353  return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1354  }
1355 
1356  public function buildConcat( $stringList ) {
1357  return implode( ' || ', $stringList );
1358  }
1359 
1360  public function buildGroupConcatField(
1361  $delimiter, $table, $field, $conds = '', $options = [], $join_conds = []
1362  ) {
1363  $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1364 
1365  return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1366  }
1367 
1368  public function buildStringCast( $field ) {
1369  return $field . '::text';
1370  }
1371 
1372  public function streamStatementEnd( &$sql, &$newLine ) {
1373  # Allow dollar quoting for function declarations
1374  if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1375  if ( $this->delimiter ) {
1376  $this->delimiter = false;
1377  } else {
1378  $this->delimiter = ';';
1379  }
1380  }
1381 
1382  return parent::streamStatementEnd( $sql, $newLine );
1383  }
1384 
1385  public function doLockTables( array $read, array $write, $method ) {
1386  $tablesWrite = [];
1387  foreach ( $write as $table ) {
1388  $tablesWrite[] = $this->tableName( $table );
1389  }
1390  $tablesRead = [];
1391  foreach ( $read as $table ) {
1392  $tablesRead[] = $this->tableName( $table );
1393  }
1394 
1395  // Acquire locks for the duration of the current transaction...
1396  if ( $tablesWrite ) {
1397  $this->query(
1398  'LOCK TABLE ONLY ' . implode( ',', $tablesWrite ) . ' IN EXCLUSIVE MODE',
1399  $method
1400  );
1401  }
1402  if ( $tablesRead ) {
1403  $this->query(
1404  'LOCK TABLE ONLY ' . implode( ',', $tablesRead ) . ' IN SHARE MODE',
1405  $method
1406  );
1407  }
1408 
1409  return true;
1410  }
1411 
1412  public function lockIsFree( $lockName, $method ) {
1413  if ( !parent::lockIsFree( $lockName, $method ) ) {
1414  return false; // already held
1415  }
1416  // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1417  $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1418  $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1419  WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1420  $row = $this->fetchObject( $result );
1421 
1422  return ( $row->lockstatus === 't' );
1423  }
1424 
1425  public function lock( $lockName, $method, $timeout = 5 ) {
1426  // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1427  $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1428  $loop = new WaitConditionLoop(
1429  function () use ( $lockName, $key, $timeout, $method ) {
1430  $res = $this->query( "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1431  $row = $this->fetchObject( $res );
1432  if ( $row->lockstatus === 't' ) {
1433  parent::lock( $lockName, $method, $timeout ); // record
1434  return true;
1435  }
1436 
1437  return WaitConditionLoop::CONDITION_CONTINUE;
1438  },
1439  $timeout
1440  );
1441 
1442  return ( $loop->invoke() === $loop::CONDITION_REACHED );
1443  }
1444 
1445  public function unlock( $lockName, $method ) {
1446  // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1447  $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1448  $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1449  $row = $this->fetchObject( $result );
1450 
1451  if ( $row->lockstatus === 't' ) {
1452  parent::unlock( $lockName, $method ); // record
1453  return true;
1454  }
1455 
1456  $this->queryLogger->debug( __METHOD__ . " failed to release lock\n" );
1457 
1458  return false;
1459  }
1460 
1461  public function serverIsReadOnly() {
1462  $res = $this->query( "SHOW default_transaction_read_only", __METHOD__ );
1463  $row = $this->fetchObject( $res );
1464 
1465  return $row ? ( strtolower( $row->default_transaction_read_only ) === 'on' ) : false;
1466  }
1467 
1468  public static function getAttributes() {
1469  return [ self::ATTR_SCHEMAS_AS_TABLE_GROUPS => true ];
1470  }
1471 
1476  private function bigintFromLockName( $lockName ) {
1477  return \Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1478  }
1479 }
1480 
1484 class_alias( DatabasePostgres::class, 'DatabasePostgres' );
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
normalizeConditions( $conds, $fname)
Definition: Database.php:1984
open( $server, $user, $password, $dbName, $schema, $tablePrefix)
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
Definition: hooks.txt:2633
decodeBlob( $b)
Some DBMSs return a special placeholder object representing blob fields in result objects...
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to and or sell copies of the and to permit persons to whom the Software is furnished to do subject to the following WITHOUT WARRANTY OF ANY EXPRESS OR INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY DAMAGES OR OTHER WHETHER IN AN ACTION OF TORT OR ARISING FROM
Definition: LICENSE.txt:10
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
Creates a new table with structure copied from existing table.
setSearchPath( $search_path)
Update search_path, values should already be sanitized Values may contain magic keywords like "$user"...
resetSequenceForTable( $table, $fname=__METHOD__)
getType()
Get the type of the DBMS, as it appears in $wgDBtype.
fieldName( $res, $n)
Get a field name in a result object.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1982
begin( $fname=__METHOD__, $mode=self::TRANSACTION_EXPLICIT)
Begin a transaction.
Definition: Database.php:3876
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Result wrapper for grabbing data queried from an IDatabase object.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2159
nextSequenceValue( $seqName)
Deprecated method, calls should be removed.
sequenceExists( $sequence, $schema=false)
indexAttributes( $index, $schema=false)
addQuotes( $s)
Adds quotes and backslashes.
roleExists( $roleName)
Returns true if a given role (i.e.
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 ...
getSoftwareLink()
Returns a wikitext link to the DB&#39;s website, e.g., return "[https://www.mysql.com/ MySQL]"; Should at...
numRows( $res)
Get the number of rows in a query result.
doLockTables(array $read, array $write, $method)
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:1596
nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[], $selectJoinConds=[])
INSERT SELECT wrapper $varMap must be an associative array of the form [ &#39;dest1&#39; => &#39;source1&#39;...
$value
relationExists( $table, $types, $schema=false)
Query whether a given relation exists (in the given schema, or the default mw one if not given) ...
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message key
Definition: hooks.txt:2151
nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[], $selectJoinConds=[])
Implementation of insertSelect() based on select() and insert()
Definition: Database.php:3097
startAtomic( $fname=__METHOD__, $cancelable=self::ATOMIC_NOT_CANCELABLE)
Begin an atomic section of SQL statements.
Definition: Database.php:3723
endAtomic( $fname=__METHOD__)
Ends an atomic section of SQL statements.
Definition: Database.php:3753
query( $sql, $fname=__METHOD__, $flags=0)
Run an SQL query and return the result.
Definition: Database.php:1191
string $server
Server that this instance is currently connected to.
Definition: Database.php:81
lastErrno()
Get the last error number.
getCoreSchemas()
Return schema names for temporary tables and core application tables.
currentSequenceValue( $seqName)
Return the current value of a sequence.
streamStatementEnd(&$sql, &$newLine)
Called by sourceStream() to check if we&#39;ve reached a statement end.
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
indexInfo( $table, $index, $fname=__METHOD__)
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place $output
Definition: hooks.txt:2217
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1980
if( $line===false) $args
Definition: cdb.php:64
close()
Close the database connection.
Definition: Database.php:938
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for tableName() and addQuotes(). You will need both of them. ------------------------------------------------------------------------ Basic query optimisation ------------------------------------------------------------------------ MediaWiki developers who need to write DB queries should have some understanding of databases and the performance issues associated with them. Patches containing unacceptably slow features will not be accepted. Unindexed queries are generally not welcome in MediaWiki
freeResult( $res)
Free a result object returned by query() or select().
getCoreSchema()
Return schema name for core application tables.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1982
installErrorHandler()
Set a custom error handler for logging errors during database connection.
Definition: Database.php:876
getDBname()
Get the current DB name.
Definition: Database.php:2402
indexUnique( $table, $index, $fname=__METHOD__)
getSchemas()
Return list of schemas which are accessible without schema name This is list does not contain magic k...
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Ge...
listTables( $prefix=null, $fname=__METHOD__)
SecurityCheck-SQLInjection array_map not recognized T204911
string [] $keywordTableMap
Map of (reserved table name => alternate table name)
indexName( $index)
Allows for index remapping in queries where this is not consistent across DBMS.
Definition: Database.php:2729
unlock( $lockName, $method)
Release a lock.
insert( $table, $args, $fname=__METHOD__, $options=[])
doSelectDomain(DatabaseDomain $domain)
$res
Definition: database.txt:21
implicitOrderby()
Returns true if this database does an implicit order by when the column has an index For example: SEL...
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same user
Wikitext formatted, in the key only.
Definition: distributors.txt:9
dataSeek( $res, $row)
Change the position of the cursor in a result object.
$params
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1982
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.pgsql.php.
numFields( $res)
Get the number of fields in a result object.
buildConcat( $stringList)
Build a concatenation list to feed into a SQL query.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
string $connectString
Connect string to open a PostgreSQL connection.
buildGroupConcatField( $delimiter, $table, $field, $conds='', $options=[], $join_conds=[])
makeList( $a, $mode=self::LIST_COMMA)
Makes an encoded list of strings from an array.
Definition: Database.php:2200
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings, LocalSettings).
Definition: Setup.php:123
fetchObject( $res)
Fetch the next row from the given result object, in object form.
aggregateValue( $valuedata, $valuename='value')
Return aggregated value alias.
static fromText(DatabasePostgres $db, $table, $field)
textFieldSize( $table, $field)
Returns the size of a text field, or -1 for "unlimited".
cancelAtomic( $fname=__METHOD__, AtomicSectionIdentifier $sectionId=null)
Cancel an atomic section of SQL statements.
Definition: Database.php:3787
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
selectSQLText( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
The equivalent of IDatabase::select() except that the constructed SQL is returned, instead of being immediately executed.
encodeBlob( $b)
Some DBMSs have a special format for inserting into blob fields, they don&#39;t allow simple quoted strin...
Used by Database::nextSequenceValue() so Database::insert() can detect values coming from the depreca...
Class to handle database/prefix specification for IDatabase domains.
fieldType( $res, $index)
pg_field_type() wrapper
getServerVersion()
A string describing the current software version, like from mysql_get_server_info().
string bool $phpError
Definition: Database.php:79
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
Relational database abstraction object.
Definition: Database.php:48
lock( $lockName, $method, $timeout=5)
Acquire a named lock.
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
Definition: Database.php:1779
commit( $fname=__METHOD__, $flush=self::FLUSHING_ONE)
Commits a transaction previously started using begin().
Definition: Database.php:3939
implicitGroupby()
Returns true if this database does an implicit sort when doing GROUP BY.
restoreErrorHandler()
Restore the previous error handler and return the last PHP error for this DB.
Definition: Database.php:887
object resource null $conn
Database connection.
Definition: Database.php:108
databasesAreIndependent()
Returns true if DBs are assumed to be on potentially different servers.
string $user
User that this instance is currently connected under the name of.
Definition: Database.php:83
addIdentifierQuotes( $s)
Quotes an identifier, in order to make user controlled input safe.
Definition: Database.php:2750
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same so they can t rely on Unix and must forbid reads to even standard directories like tmp lest users read each others files We cannot assume that the user has the ability to install or run any programs not written as web accessible PHP scripts Since anything that works on cheap shared hosting will work if you have shell or root access MediaWiki s design is based around catering to the lowest common denominator Although we support higher end setups as the way many things work by default is tailored toward shared hosting These defaults are unconventional from the point of view of and they certainly aren t ideal for someone who s installing MediaWiki as MediaWiki does not conform to normal Unix filesystem layout Hopefully we ll offer direct support for standard layouts in the but for now *any change to the location of files is unsupported *Moving things and leaving symlinks will *probably *not break but it is *strongly *advised not to try any more intrusive changes to get MediaWiki to conform more closely to your filesystem hierarchy Any such attempt will almost certainly result in unnecessary bugs The standard recommended location to install relative to the web is it should be possible to enable the appropriate rewrite rules by if you can reconfigure the web server
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
makeOrderBy( $options)
Returns an optional ORDER BY.
Definition: Database.php:1767
wasLockTimeout()
Determines if the last failure was due to a lock timeout.
lockIsFree( $lockName, $method)
Check to see if a named lock is not locked by any thread (non-blocking)
storage can be distributed across multiple and multiple web servers can use the same cache cluster *********************W A R N I N G ***********************Memcached has no security or authentication Please ensure that your server is appropriately and that the port(s) used for memcached servers are not publicly accessible. Otherwise
fetchRow( $res)
Fetch the next row from the given result object, in associative array form.
makeGroupByWithHaving( $options)
Returns an optional GROUP BY with an optional HAVING.
Definition: Database.php:1741
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.
getSearchPath()
Return search patch for schemas This is different from getSchemas() since it contain magic keywords (...
lastError()
Get a description of the last error.
const DBO_SSL
Definition: defines.php:17
schemaExists( $schema)
Query whether a given schema exists.
wasDeadlock()
Determines if the last failure was due to a deadlock.
getBindingHandle()
Get the underlying binding connection handle.
Definition: Database.php:4715
determineCoreSchema( $desiredSchema)
Determine default schema for the current application Adjust this session schema search path if desire...
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2217
limitResult( $sql, $limit, $offset=false)
Construct a LIMIT query with optional offset.
insertId()
Get the inserted value of an auto-increment row.
realTableName( $name, $format='quoted')
string $password
Password used to establish the current connection.
Definition: Database.php:85
while(( $__line=Maintenance::readconsole()) !==false) print n
Definition: eval.php:64
constraintExists( $table, $constraint)
getCurrentSchema()
Return current schema (executes SELECT current_schema()) Needs transaction.
tableExists( $table, $fname=__METHOD__, $schema=false)
For backward compatibility, this function checks both tables and views.