MediaWiki  1.27.2
DatabasePostgres.php
Go to the documentation of this file.
1 <?php
24 class PostgresField implements Field {
27 
34  static function fromText( $db, $table, $field ) {
35  $q = <<<SQL
36 SELECT
37  attnotnull, attlen, conname AS conname,
38  atthasdef,
39  adsrc,
40  COALESCE(condeferred, 'f') AS deferred,
41  COALESCE(condeferrable, 'f') AS deferrable,
42  CASE WHEN typname = 'int2' THEN 'smallint'
43  WHEN typname = 'int4' THEN 'integer'
44  WHEN typname = 'int8' THEN 'bigint'
45  WHEN typname = 'bpchar' THEN 'char'
46  ELSE typname END AS typname
47 FROM pg_class c
48 JOIN pg_namespace n ON (n.oid = c.relnamespace)
49 JOIN pg_attribute a ON (a.attrelid = c.oid)
50 JOIN pg_type t ON (t.oid = a.atttypid)
51 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
52 LEFT JOIN pg_attrdef d on c.oid=d.adrelid and a.attnum=d.adnum
53 WHERE relkind = 'r'
54 AND nspname=%s
55 AND relname=%s
56 AND attname=%s;
57 SQL;
58 
59  $table = $db->tableName( $table, 'raw' );
60  $res = $db->query(
61  sprintf( $q,
62  $db->addQuotes( $db->getCoreSchema() ),
63  $db->addQuotes( $table ),
64  $db->addQuotes( $field )
65  )
66  );
67  $row = $db->fetchObject( $res );
68  if ( !$row ) {
69  return null;
70  }
71  $n = new PostgresField;
72  $n->type = $row->typname;
73  $n->nullable = ( $row->attnotnull == 'f' );
74  $n->name = $field;
75  $n->tablename = $table;
76  $n->max_length = $row->attlen;
77  $n->deferrable = ( $row->deferrable == 't' );
78  $n->deferred = ( $row->deferred == 't' );
79  $n->conname = $row->conname;
80  $n->has_default = ( $row->atthasdef === 't' );
81  $n->default = $row->adsrc;
82 
83  return $n;
84  }
85 
86  function name() {
87  return $this->name;
88  }
89 
90  function tableName() {
91  return $this->tablename;
92  }
93 
94  function type() {
95  return $this->type;
96  }
97 
98  function isNullable() {
99  return $this->nullable;
100  }
101 
102  function maxLength() {
103  return $this->max_length;
104  }
105 
106  function is_deferrable() {
107  return $this->deferrable;
108  }
109 
110  function is_deferred() {
111  return $this->deferred;
112  }
113 
114  function conname() {
115  return $this->conname;
116  }
122  function defaultValue() {
123  if ( $this->has_default ) {
125  } else {
126  return false;
127  }
128  }
129 }
130 
136 class SavepointPostgres {
138  protected $dbw;
139  protected $id;
140  protected $didbegin;
141 
146  public function __construct( $dbw, $id ) {
147  $this->dbw = $dbw;
148  $this->id = $id;
149  $this->didbegin = false;
150  /* If we are not in a transaction, we need to be for savepoint trickery */
151  if ( !$dbw->trxLevel() ) {
152  $dbw->begin( "FOR SAVEPOINT" );
153  $this->didbegin = true;
154  }
155  }
157  public function __destruct() {
158  if ( $this->didbegin ) {
159  $this->dbw->rollback();
160  $this->didbegin = false;
161  }
162  }
164  public function commit() {
165  if ( $this->didbegin ) {
166  $this->dbw->commit();
167  $this->didbegin = false;
168  }
169  }
171  protected function query( $keyword, $msg_ok, $msg_failed ) {
172  if ( $this->dbw->doQuery( $keyword . " " . $this->id ) !== false ) {
173  } else {
174  wfDebug( sprintf( $msg_failed, $this->id ) );
175  }
176  }
178  public function savepoint() {
179  $this->query( "SAVEPOINT",
180  "Transaction state: savepoint \"%s\" established.\n",
181  "Transaction state: establishment of savepoint \"%s\" FAILED.\n"
182  );
183  }
184 
185  public function release() {
186  $this->query( "RELEASE",
187  "Transaction state: savepoint \"%s\" released.\n",
188  "Transaction state: release of savepoint \"%s\" FAILED.\n"
189  );
190  }
191 
192  public function rollback() {
193  $this->query( "ROLLBACK TO",
194  "Transaction state: savepoint \"%s\" rolled back.\n",
195  "Transaction state: rollback of savepoint \"%s\" FAILED.\n"
196  );
197  }
198 
199  public function __toString() {
200  return (string)$this->id;
201  }
202 }
203 
207 class DatabasePostgres extends Database {
209  protected $mLastResult = null;
210 
212  protected $mAffectedRows = null;
213 
215  private $mInsertId = null;
218  private $numericVersion = null;
219 
221  private $connectString;
222 
224  private $mCoreSchema;
225 
226  function getType() {
227  return 'postgres';
228  }
229 
230  function cascadingDeletes() {
231  return true;
232  }
233 
234  function cleanupTriggers() {
235  return true;
236  }
237 
238  function strictIPs() {
239  return true;
240  }
241 
242  function realTimestamps() {
243  return true;
244  }
245 
246  function implicitGroupby() {
247  return false;
248  }
249 
250  function implicitOrderby() {
251  return false;
252  }
253 
254  function searchableIPs() {
255  return true;
256  }
257 
258  function functionalIndexes() {
259  return true;
260  }
261 
262  function hasConstraint( $name ) {
263  $sql = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
264  "WHERE c.connamespace = n.oid AND conname = '" .
265  pg_escape_string( $this->mConn, $name ) . "' AND n.nspname = '" .
266  pg_escape_string( $this->mConn, $this->getCoreSchema() ) . "'";
267  $res = $this->doQuery( $sql );
268 
269  return $this->numRows( $res );
270  }
271 
281  function open( $server, $user, $password, $dbName ) {
282  # Test for Postgres support, to avoid suppressed fatal error
283  if ( !function_exists( 'pg_connect' ) ) {
284  throw new DBConnectionError(
285  $this,
286  "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
287  "option? (Note: if you recently installed PHP, you may need to restart your\n" .
288  "webserver and database)\n"
289  );
290  }
291 
293 
294  if ( !strlen( $user ) ) { # e.g. the class is being loaded
295  return null;
296  }
297 
298  $this->mServer = $server;
299  $port = $wgDBport;
300  $this->mUser = $user;
301  $this->mPassword = $password;
302  $this->mDBname = $dbName;
303 
304  $connectVars = [
305  'dbname' => $dbName,
306  'user' => $user,
307  'password' => $password
308  ];
309  if ( $server != false && $server != '' ) {
310  $connectVars['host'] = $server;
311  }
312  if ( $port != false && $port != '' ) {
313  $connectVars['port'] = $port;
314  }
315  if ( $this->mFlags & DBO_SSL ) {
316  $connectVars['sslmode'] = 1;
317  }
318 
319  $this->connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW );
320  $this->close();
321  $this->installErrorHandler();
322 
323  try {
324  $this->mConn = pg_connect( $this->connectString );
325  } catch ( Exception $ex ) {
326  $this->restoreErrorHandler();
327  throw $ex;
328  }
329 
330  $phpError = $this->restoreErrorHandler();
331 
332  if ( !$this->mConn ) {
333  wfDebug( "DB connection error\n" );
334  wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " .
335  substr( $password, 0, 3 ) . "...\n" );
336  wfDebug( $this->lastError() . "\n" );
337  throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
338  }
339 
340  $this->mOpened = true;
341 
343  # If called from the command-line (e.g. importDump), only show errors
344  if ( $wgCommandLineMode ) {
345  $this->doQuery( "SET client_min_messages = 'ERROR'" );
346  }
347 
348  $this->query( "SET client_encoding='UTF8'", __METHOD__ );
349  $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__ );
350  $this->query( "SET timezone = 'GMT'", __METHOD__ );
351  $this->query( "SET standard_conforming_strings = on", __METHOD__ );
352  if ( $this->getServerVersion() >= 9.0 ) {
353  $this->query( "SET bytea_output = 'escape'", __METHOD__ ); // PHP bug 53127
354  }
355 
357  $this->determineCoreSchema( $wgDBmwschema );
358 
359  return $this->mConn;
360  }
361 
368  function selectDB( $db ) {
369  if ( $this->mDBname !== $db ) {
370  return (bool)$this->open( $this->mServer, $this->mUser, $this->mPassword, $db );
371  } else {
372  return true;
373  }
374  }
375 
376  function makeConnectionString( $vars ) {
377  $s = '';
378  foreach ( $vars as $name => $value ) {
379  $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
380  }
381 
382  return $s;
383  }
384 
390  protected function closeConnection() {
391  return pg_close( $this->mConn );
392  }
393 
394  public function doQuery( $sql ) {
395  $sql = mb_convert_encoding( $sql, 'UTF-8' );
396  // Clear previously left over PQresult
397  while ( $res = pg_get_result( $this->mConn ) ) {
398  pg_free_result( $res );
399  }
400  if ( pg_send_query( $this->mConn, $sql ) === false ) {
401  throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
402  }
403  $this->mLastResult = pg_get_result( $this->mConn );
404  $this->mAffectedRows = null;
405  if ( pg_result_error( $this->mLastResult ) ) {
406  return false;
407  }
408 
409  return $this->mLastResult;
410  }
412  protected function dumpError() {
413  $diags = [
414  PGSQL_DIAG_SEVERITY,
415  PGSQL_DIAG_SQLSTATE,
416  PGSQL_DIAG_MESSAGE_PRIMARY,
417  PGSQL_DIAG_MESSAGE_DETAIL,
418  PGSQL_DIAG_MESSAGE_HINT,
419  PGSQL_DIAG_STATEMENT_POSITION,
420  PGSQL_DIAG_INTERNAL_POSITION,
421  PGSQL_DIAG_INTERNAL_QUERY,
422  PGSQL_DIAG_CONTEXT,
423  PGSQL_DIAG_SOURCE_FILE,
424  PGSQL_DIAG_SOURCE_LINE,
425  PGSQL_DIAG_SOURCE_FUNCTION
426  ];
427  foreach ( $diags as $d ) {
428  wfDebug( sprintf( "PgSQL ERROR(%d): %s\n",
429  $d, pg_result_error_field( $this->mLastResult, $d ) ) );
430  }
431  }
432 
433  function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
434  if ( $tempIgnore ) {
435  /* Check for constraint violation */
436  if ( $errno === '23505' ) {
437  parent::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
438 
439  return;
440  }
441  }
442  /* Transaction stays in the ERROR state until rolled back */
443  if ( $this->mTrxLevel ) {
444  $ignore = $this->ignoreErrors( true );
445  $this->rollback( __METHOD__ );
446  $this->ignoreErrors( $ignore );
447  }
448  parent::reportQueryError( $error, $errno, $sql, $fname, false );
449  }
450 
451  function queryIgnore( $sql, $fname = __METHOD__ ) {
452  return $this->query( $sql, $fname, true );
453  }
459  function freeResult( $res ) {
460  if ( $res instanceof ResultWrapper ) {
461  $res = $res->result;
462  }
463  MediaWiki\suppressWarnings();
464  $ok = pg_free_result( $res );
465  MediaWiki\restoreWarnings();
466  if ( !$ok ) {
467  throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
468  }
469  }
470 
476  function fetchObject( $res ) {
477  if ( $res instanceof ResultWrapper ) {
478  $res = $res->result;
479  }
480  MediaWiki\suppressWarnings();
481  $row = pg_fetch_object( $res );
482  MediaWiki\restoreWarnings();
483  # @todo FIXME: HACK HACK HACK HACK debug
484 
485  # @todo hashar: not sure if the following test really trigger if the object
486  # fetching failed.
487  if ( pg_last_error( $this->mConn ) ) {
488  throw new DBUnexpectedError(
489  $this,
490  'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) )
491  );
492  }
493 
494  return $row;
495  }
496 
497  function fetchRow( $res ) {
498  if ( $res instanceof ResultWrapper ) {
499  $res = $res->result;
500  }
501  MediaWiki\suppressWarnings();
502  $row = pg_fetch_array( $res );
503  MediaWiki\restoreWarnings();
504  if ( pg_last_error( $this->mConn ) ) {
505  throw new DBUnexpectedError(
506  $this,
507  'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) )
508  );
509  }
510 
511  return $row;
512  }
513 
514  function numRows( $res ) {
515  if ( $res instanceof ResultWrapper ) {
516  $res = $res->result;
517  }
518  MediaWiki\suppressWarnings();
519  $n = pg_num_rows( $res );
520  MediaWiki\restoreWarnings();
521  if ( pg_last_error( $this->mConn ) ) {
522  throw new DBUnexpectedError(
523  $this,
524  'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) )
525  );
526  }
527 
528  return $n;
529  }
530 
531  function numFields( $res ) {
532  if ( $res instanceof ResultWrapper ) {
533  $res = $res->result;
534  }
535 
536  return pg_num_fields( $res );
537  }
538 
539  function fieldName( $res, $n ) {
540  if ( $res instanceof ResultWrapper ) {
541  $res = $res->result;
542  }
543 
544  return pg_field_name( $res, $n );
545  }
546 
553  function insertId() {
554  return $this->mInsertId;
555  }
556 
562  function dataSeek( $res, $row ) {
563  if ( $res instanceof ResultWrapper ) {
564  $res = $res->result;
565  }
566 
567  return pg_result_seek( $res, $row );
568  }
569 
570  function lastError() {
571  if ( $this->mConn ) {
572  if ( $this->mLastResult ) {
573  return pg_result_error( $this->mLastResult );
574  } else {
575  return pg_last_error();
576  }
577  } else {
578  return 'No database connection';
579  }
580  }
581 
582  function lastErrno() {
583  if ( $this->mLastResult ) {
584  return pg_result_error_field( $this->mLastResult, PGSQL_DIAG_SQLSTATE );
585  } else {
586  return false;
587  }
588  }
589 
590  function affectedRows() {
591  if ( !is_null( $this->mAffectedRows ) ) {
592  // Forced result for simulated queries
593  return $this->mAffectedRows;
594  }
595  if ( empty( $this->mLastResult ) ) {
596  return 0;
597  }
598 
599  return pg_affected_rows( $this->mLastResult );
600  }
601 
616  function estimateRowCount( $table, $vars = '*', $conds = '',
617  $fname = __METHOD__, $options = []
618  ) {
619  $options['EXPLAIN'] = true;
620  $res = $this->select( $table, $vars, $conds, $fname, $options );
621  $rows = -1;
622  if ( $res ) {
623  $row = $this->fetchRow( $res );
624  $count = [];
625  if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
626  $rows = (int)$count[1];
627  }
628  }
629 
630  return $rows;
631  }
632 
642  function indexInfo( $table, $index, $fname = __METHOD__ ) {
643  $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
644  $res = $this->query( $sql, $fname );
645  if ( !$res ) {
646  return null;
647  }
648  foreach ( $res as $row ) {
649  if ( $row->indexname == $this->indexName( $index ) ) {
650  return $row;
651  }
652  }
653 
654  return false;
655  }
656 
665  function indexAttributes( $index, $schema = false ) {
666  if ( $schema === false ) {
667  $schema = $this->getCoreSchema();
668  }
669  /*
670  * A subquery would be not needed if we didn't care about the order
671  * of attributes, but we do
672  */
673  $sql = <<<__INDEXATTR__
674 
675  SELECT opcname,
676  attname,
677  i.indoption[s.g] as option,
678  pg_am.amname
679  FROM
680  (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
681  FROM
682  pg_index isub
683  JOIN pg_class cis
684  ON cis.oid=isub.indexrelid
685  JOIN pg_namespace ns
686  ON cis.relnamespace = ns.oid
687  WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
688  pg_attribute,
689  pg_opclass opcls,
690  pg_am,
691  pg_class ci
692  JOIN pg_index i
693  ON ci.oid=i.indexrelid
694  JOIN pg_class ct
695  ON ct.oid = i.indrelid
696  JOIN pg_namespace n
697  ON ci.relnamespace = n.oid
698  WHERE
699  ci.relname='$index' AND n.nspname='$schema'
700  AND attrelid = ct.oid
701  AND i.indkey[s.g] = attnum
702  AND i.indclass[s.g] = opcls.oid
703  AND pg_am.oid = opcls.opcmethod
704 __INDEXATTR__;
705  $res = $this->query( $sql, __METHOD__ );
706  $a = [];
707  if ( $res ) {
708  foreach ( $res as $row ) {
709  $a[] = [
710  $row->attname,
711  $row->opcname,
712  $row->amname,
713  $row->option ];
714  }
715  } else {
716  return null;
717  }
718 
719  return $a;
720  }
721 
722  function indexUnique( $table, $index, $fname = __METHOD__ ) {
723  $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
724  " AND indexdef LIKE 'CREATE UNIQUE%(" .
725  $this->strencode( $this->indexName( $index ) ) .
726  ")'";
727  $res = $this->query( $sql, $fname );
728  if ( !$res ) {
729  return null;
730  }
731 
732  return $res->numRows() > 0;
733  }
734 
746  function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
747  $options = [], $join_conds = []
748  ) {
749  if ( is_array( $options ) ) {
750  $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
751  if ( $forUpdateKey !== false && $join_conds ) {
752  unset( $options[$forUpdateKey] );
753 
754  foreach ( $join_conds as $table_cond => $join_cond ) {
755  if ( 0 === preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_cond[0] ) ) {
756  $options['FOR UPDATE'][] = $table_cond;
757  }
758  }
759  }
760 
761  if ( isset( $options['ORDER BY'] ) && $options['ORDER BY'] == 'NULL' ) {
762  unset( $options['ORDER BY'] );
763  }
764  }
765 
766  return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
767  }
768 
781  function insert( $table, $args, $fname = __METHOD__, $options = [] ) {
782  if ( !count( $args ) ) {
783  return true;
784  }
785 
786  $table = $this->tableName( $table );
787  if ( !isset( $this->numericVersion ) ) {
788  $this->getServerVersion();
789  }
790 
791  if ( !is_array( $options ) ) {
792  $options = [ $options ];
793  }
794 
795  if ( isset( $args[0] ) && is_array( $args[0] ) ) {
796  $multi = true;
797  $keys = array_keys( $args[0] );
798  } else {
799  $multi = false;
800  $keys = array_keys( $args );
801  }
802 
803  // If IGNORE is set, we use savepoints to emulate mysql's behavior
804  $savepoint = null;
805  if ( in_array( 'IGNORE', $options ) ) {
806  $savepoint = new SavepointPostgres( $this, 'mw' );
807  $olde = error_reporting( 0 );
808  // For future use, we may want to track the number of actual inserts
809  // Right now, insert (all writes) simply return true/false
810  $numrowsinserted = 0;
811  }
812 
813  $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
814 
815  if ( $multi ) {
816  if ( $this->numericVersion >= 8.2 && !$savepoint ) {
817  $first = true;
818  foreach ( $args as $row ) {
819  if ( $first ) {
820  $first = false;
821  } else {
822  $sql .= ',';
823  }
824  $sql .= '(' . $this->makeList( $row ) . ')';
825  }
826  $res = (bool)$this->query( $sql, $fname, $savepoint );
827  } else {
828  $res = true;
829  $origsql = $sql;
830  foreach ( $args as $row ) {
831  $tempsql = $origsql;
832  $tempsql .= '(' . $this->makeList( $row ) . ')';
833 
834  if ( $savepoint ) {
835  $savepoint->savepoint();
836  }
837 
838  $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
839 
840  if ( $savepoint ) {
841  $bar = pg_result_error( $this->mLastResult );
842  if ( $bar != false ) {
843  $savepoint->rollback();
844  } else {
845  $savepoint->release();
846  $numrowsinserted++;
847  }
848  }
849 
850  // If any of them fail, we fail overall for this function call
851  // Note that this will be ignored if IGNORE is set
852  if ( !$tempres ) {
853  $res = false;
854  }
855  }
856  }
857  } else {
858  // Not multi, just a lone insert
859  if ( $savepoint ) {
860  $savepoint->savepoint();
861  }
862 
863  $sql .= '(' . $this->makeList( $args ) . ')';
864  $res = (bool)$this->query( $sql, $fname, $savepoint );
865  if ( $savepoint ) {
866  $bar = pg_result_error( $this->mLastResult );
867  if ( $bar != false ) {
868  $savepoint->rollback();
869  } else {
870  $savepoint->release();
871  $numrowsinserted++;
872  }
873  }
874  }
875  if ( $savepoint ) {
876  error_reporting( $olde );
877  $savepoint->commit();
878 
879  // Set the affected row count for the whole operation
880  $this->mAffectedRows = $numrowsinserted;
881 
882  // IGNORE always returns true
883  return true;
884  }
886  return $res;
887  }
888 
907  function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
908  $insertOptions = [], $selectOptions = [] ) {
909  $destTable = $this->tableName( $destTable );
910 
911  if ( !is_array( $insertOptions ) ) {
912  $insertOptions = [ $insertOptions ];
913  }
914 
915  /*
916  * If IGNORE is set, we use savepoints to emulate mysql's behavior
917  * Ignore LOW PRIORITY option, since it is MySQL-specific
918  */
919  $savepoint = null;
920  if ( in_array( 'IGNORE', $insertOptions ) ) {
921  $savepoint = new SavepointPostgres( $this, 'mw' );
922  $olde = error_reporting( 0 );
923  $numrowsinserted = 0;
924  $savepoint->savepoint();
925  }
926 
927  if ( !is_array( $selectOptions ) ) {
928  $selectOptions = [ $selectOptions ];
929  }
930  list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
931  if ( is_array( $srcTable ) ) {
932  $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
933  } else {
934  $srcTable = $this->tableName( $srcTable );
935  }
936 
937  $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
938  " SELECT $startOpts " . implode( ',', $varMap ) .
939  " FROM $srcTable $useIndex";
940 
941  if ( $conds != '*' ) {
942  $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
943  }
944 
945  $sql .= " $tailOpts";
946 
947  $res = (bool)$this->query( $sql, $fname, $savepoint );
948  if ( $savepoint ) {
949  $bar = pg_result_error( $this->mLastResult );
950  if ( $bar != false ) {
951  $savepoint->rollback();
952  } else {
953  $savepoint->release();
954  $numrowsinserted++;
955  }
956  error_reporting( $olde );
957  $savepoint->commit();
958 
959  // Set the affected row count for the whole operation
960  $this->mAffectedRows = $numrowsinserted;
961 
962  // IGNORE always returns true
963  return true;
964  }
965 
966  return $res;
967  }
968 
969  function tableName( $name, $format = 'quoted' ) {
970  # Replace reserved words with better ones
971  switch ( $name ) {
972  case 'user':
973  return $this->realTableName( 'mwuser', $format );
974  case 'text':
975  return $this->realTableName( 'pagecontent', $format );
976  default:
977  return $this->realTableName( $name, $format );
978  }
979  }
980 
981  /* Don't cheat on installer */
982  function realTableName( $name, $format = 'quoted' ) {
983  return parent::tableName( $name, $format );
984  }
992  function nextSequenceValue( $seqName ) {
993  $safeseq = str_replace( "'", "''", $seqName );
994  $res = $this->query( "SELECT nextval('$safeseq')" );
995  $row = $this->fetchRow( $res );
996  $this->mInsertId = $row[0];
997 
998  return $this->mInsertId;
999  }
1000 
1007  function currentSequenceValue( $seqName ) {
1008  $safeseq = str_replace( "'", "''", $seqName );
1009  $res = $this->query( "SELECT currval('$safeseq')" );
1010  $row = $this->fetchRow( $res );
1011  $currval = $row[0];
1013  return $currval;
1014  }
1015 
1016  # Returns the size of a text field, or -1 for "unlimited"
1017  function textFieldSize( $table, $field ) {
1018  $table = $this->tableName( $table );
1019  $sql = "SELECT t.typname as ftype,a.atttypmod as size
1020  FROM pg_class c, pg_attribute a, pg_type t
1021  WHERE relname='$table' AND a.attrelid=c.oid AND
1022  a.atttypid=t.oid and a.attname='$field'";
1023  $res = $this->query( $sql );
1024  $row = $this->fetchObject( $res );
1025  if ( $row->ftype == 'varchar' ) {
1026  $size = $row->size - 4;
1027  } else {
1028  $size = $row->size;
1029  }
1030 
1031  return $size;
1032  }
1033 
1034  function limitResult( $sql, $limit, $offset = false ) {
1035  return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
1036  }
1037 
1038  function wasDeadlock() {
1039  return $this->lastErrno() == '40P01';
1040  }
1041 
1042  function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1043  $newName = $this->addIdentifierQuotes( $newName );
1044  $oldName = $this->addIdentifierQuotes( $oldName );
1045 
1046  return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName " .
1047  "(LIKE $oldName INCLUDING DEFAULTS)", $fname );
1048  }
1049 
1050  function listTables( $prefix = null, $fname = __METHOD__ ) {
1051  $eschema = $this->addQuotes( $this->getCoreSchema() );
1052  $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
1053  $endArray = [];
1054 
1055  foreach ( $result as $table ) {
1056  $vars = get_object_vars( $table );
1057  $table = array_pop( $vars );
1058  if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1059  $endArray[] = $table;
1060  }
1061  }
1062 
1063  return $endArray;
1064  }
1065 
1066  function timestamp( $ts = 0 ) {
1067  return wfTimestamp( TS_POSTGRES, $ts );
1068  }
1069 
1088  function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
1089  if ( false === $limit ) {
1090  $limit = strlen( $text ) - 1;
1091  $output = [];
1092  }
1093  if ( '{}' == $text ) {
1094  return $output;
1095  }
1096  do {
1097  if ( '{' != $text[$offset] ) {
1098  preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
1099  $text, $match, 0, $offset );
1100  $offset += strlen( $match[0] );
1101  $output[] = ( '"' != $match[1][0]
1102  ? $match[1]
1103  : stripcslashes( substr( $match[1], 1, -1 ) ) );
1104  if ( '},' == $match[3] ) {
1105  return $output;
1106  }
1107  } else {
1108  $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
1109  }
1110  } while ( $limit > $offset );
1111 
1112  return $output;
1113  }
1114 
1121  public function aggregateValue( $valuedata, $valuename = 'value' ) {
1122  return $valuedata;
1123  }
1124 
1128  public function getSoftwareLink() {
1129  return '[{{int:version-db-postgres-url}} PostgreSQL]';
1130  }
1131 
1139  function getCurrentSchema() {
1140  $res = $this->query( "SELECT current_schema()", __METHOD__ );
1141  $row = $this->fetchRow( $res );
1142 
1143  return $row[0];
1144  }
1145 
1156  function getSchemas() {
1157  $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
1158  $row = $this->fetchRow( $res );
1159  $schemas = [];
1160 
1161  /* PHP pgsql support does not support array type, "{a,b}" string is returned */
1162 
1163  return $this->pg_array_parse( $row[0], $schemas );
1164  }
1165 
1175  function getSearchPath() {
1176  $res = $this->query( "SHOW search_path", __METHOD__ );
1177  $row = $this->fetchRow( $res );
1178 
1179  /* PostgreSQL returns SHOW values as strings */
1180 
1181  return explode( ",", $row[0] );
1182  }
1183 
1191  function setSearchPath( $search_path ) {
1192  $this->query( "SET search_path = " . implode( ", ", $search_path ) );
1193  }
1194 
1209  function determineCoreSchema( $desiredSchema ) {
1210  $this->begin( __METHOD__ );
1211  if ( $this->schemaExists( $desiredSchema ) ) {
1212  if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
1213  $this->mCoreSchema = $desiredSchema;
1214  wfDebug( "Schema \"" . $desiredSchema . "\" already in the search path\n" );
1215  } else {
1221  $search_path = $this->getSearchPath();
1222  array_unshift( $search_path,
1223  $this->addIdentifierQuotes( $desiredSchema ) );
1224  $this->setSearchPath( $search_path );
1225  $this->mCoreSchema = $desiredSchema;
1226  wfDebug( "Schema \"" . $desiredSchema . "\" added to the search path\n" );
1227  }
1228  } else {
1229  $this->mCoreSchema = $this->getCurrentSchema();
1230  wfDebug( "Schema \"" . $desiredSchema . "\" not found, using current \"" .
1231  $this->mCoreSchema . "\"\n" );
1232  }
1233  /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1234  $this->commit( __METHOD__ );
1235  }
1236 
1243  function getCoreSchema() {
1244  return $this->mCoreSchema;
1245  }
1246 
1250  function getServerVersion() {
1251  if ( !isset( $this->numericVersion ) ) {
1252  $versionInfo = pg_version( $this->mConn );
1253  if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1254  // Old client, abort install
1255  $this->numericVersion = '7.3 or earlier';
1256  } elseif ( isset( $versionInfo['server'] ) ) {
1257  // Normal client
1258  $this->numericVersion = $versionInfo['server'];
1259  } else {
1260  // Bug 16937: broken pgsql extension from PHP<5.3
1261  $this->numericVersion = pg_parameter_status( $this->mConn, 'server_version' );
1262  }
1263  }
1264 
1265  return $this->numericVersion;
1266  }
1267 
1276  function relationExists( $table, $types, $schema = false ) {
1277  if ( !is_array( $types ) ) {
1278  $types = [ $types ];
1279  }
1280  if ( !$schema ) {
1281  $schema = $this->getCoreSchema();
1282  }
1283  $table = $this->realTableName( $table, 'raw' );
1284  $etable = $this->addQuotes( $table );
1285  $eschema = $this->addQuotes( $schema );
1286  $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1287  . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1288  . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1289  $res = $this->query( $sql );
1290  $count = $res ? $res->numRows() : 0;
1291 
1292  return (bool)$count;
1293  }
1294 
1303  function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1304  return $this->relationExists( $table, [ 'r', 'v' ], $schema );
1305  }
1306 
1307  function sequenceExists( $sequence, $schema = false ) {
1308  return $this->relationExists( $sequence, 'S', $schema );
1309  }
1310 
1311  function triggerExists( $table, $trigger ) {
1312  $q = <<<SQL
1313  SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1314  WHERE relnamespace=pg_namespace.oid AND relkind='r'
1315  AND tgrelid=pg_class.oid
1316  AND nspname=%s AND relname=%s AND tgname=%s
1317 SQL;
1318  $res = $this->query(
1319  sprintf(
1320  $q,
1321  $this->addQuotes( $this->getCoreSchema() ),
1322  $this->addQuotes( $table ),
1323  $this->addQuotes( $trigger )
1324  )
1325  );
1326  if ( !$res ) {
1327  return null;
1328  }
1329  $rows = $res->numRows();
1330 
1331  return $rows;
1332  }
1333 
1334  function ruleExists( $table, $rule ) {
1335  $exists = $this->selectField( 'pg_rules', 'rulename',
1336  [
1337  'rulename' => $rule,
1338  'tablename' => $table,
1339  'schemaname' => $this->getCoreSchema()
1340  ]
1341  );
1342 
1343  return $exists === $rule;
1344  }
1346  function constraintExists( $table, $constraint ) {
1347  $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1348  "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1349  $this->addQuotes( $this->getCoreSchema() ),
1350  $this->addQuotes( $table ),
1351  $this->addQuotes( $constraint )
1352  );
1353  $res = $this->query( $sql );
1354  if ( !$res ) {
1355  return null;
1356  }
1357  $rows = $res->numRows();
1358 
1359  return $rows;
1360  }
1361 
1367  function schemaExists( $schema ) {
1368  $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1369  [ 'nspname' => $schema ], __METHOD__ );
1370 
1371  return (bool)$exists;
1372  }
1373 
1379  function roleExists( $roleName ) {
1380  $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1381  [ 'rolname' => $roleName ], __METHOD__ );
1382 
1383  return (bool)$exists;
1384  }
1385 
1386  function fieldInfo( $table, $field ) {
1387  return PostgresField::fromText( $this, $table, $field );
1388  }
1389 
1396  function fieldType( $res, $index ) {
1397  if ( $res instanceof ResultWrapper ) {
1398  $res = $res->result;
1399  }
1401  return pg_field_type( $res, $index );
1402  }
1403 
1408  function encodeBlob( $b ) {
1409  return new PostgresBlob( pg_escape_bytea( $b ) );
1410  }
1411 
1412  function decodeBlob( $b ) {
1413  if ( $b instanceof PostgresBlob ) {
1414  $b = $b->fetch();
1415  } elseif ( $b instanceof Blob ) {
1416  return $b->fetch();
1417  }
1418 
1419  return pg_unescape_bytea( $b );
1420  }
1421 
1422  function strencode( $s ) {
1423  // Should not be called by us
1424 
1425  return pg_escape_string( $this->mConn, $s );
1426  }
1427 
1432  function addQuotes( $s ) {
1433  if ( is_null( $s ) ) {
1434  return 'NULL';
1435  } elseif ( is_bool( $s ) ) {
1436  return intval( $s );
1437  } elseif ( $s instanceof Blob ) {
1438  if ( $s instanceof PostgresBlob ) {
1439  $s = $s->fetch();
1440  } else {
1441  $s = pg_escape_bytea( $this->mConn, $s->fetch() );
1442  }
1443  return "'$s'";
1444  }
1445 
1446  return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1447  }
1448 
1456  protected function replaceVars( $ins ) {
1457  $ins = parent::replaceVars( $ins );
1458 
1459  if ( $this->numericVersion >= 8.3 ) {
1460  // Thanks for not providing backwards-compatibility, 8.3
1461  $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1462  }
1463 
1464  if ( $this->numericVersion <= 8.1 ) { // Our minimum version
1465  $ins = str_replace( 'USING gin', 'USING gist', $ins );
1466  }
1467 
1468  return $ins;
1469  }
1470 
1478  function makeSelectOptions( $options ) {
1479  $preLimitTail = $postLimitTail = '';
1480  $startOpts = $useIndex = '';
1481 
1482  $noKeyOptions = [];
1483  foreach ( $options as $key => $option ) {
1484  if ( is_numeric( $key ) ) {
1485  $noKeyOptions[$option] = true;
1486  }
1487  }
1488 
1489  $preLimitTail .= $this->makeGroupByWithHaving( $options );
1490 
1491  $preLimitTail .= $this->makeOrderBy( $options );
1492 
1493  // if ( isset( $options['LIMIT'] ) ) {
1494  // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1495  // isset( $options['OFFSET'] ) ? $options['OFFSET']
1496  // : false );
1497  // }
1498 
1499  if ( isset( $options['FOR UPDATE'] ) ) {
1500  $postLimitTail .= ' FOR UPDATE OF ' .
1501  implode( ', ', array_map( [ &$this, 'tableName' ], $options['FOR UPDATE'] ) );
1502  } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1503  $postLimitTail .= ' FOR UPDATE';
1504  }
1505 
1506  if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1507  $startOpts .= 'DISTINCT';
1508  }
1509 
1510  return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail ];
1511  }
1512 
1513  function getDBname() {
1514  return $this->mDBname;
1515  }
1516 
1517  function getServer() {
1518  return $this->mServer;
1519  }
1520 
1521  function buildConcat( $stringList ) {
1522  return implode( ' || ', $stringList );
1523  }
1524 
1525  public function buildGroupConcatField(
1526  $delimiter, $table, $field, $conds = '', $options = [], $join_conds = []
1527  ) {
1528  $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1529 
1530  return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1531  }
1532 
1533  public function getSearchEngine() {
1534  return 'SearchPostgres';
1535  }
1536 
1537  public function streamStatementEnd( &$sql, &$newLine ) {
1538  # Allow dollar quoting for function declarations
1539  if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1540  if ( $this->delimiter ) {
1541  $this->delimiter = false;
1542  } else {
1543  $this->delimiter = ';';
1544  }
1545  }
1546 
1547  return parent::streamStatementEnd( $sql, $newLine );
1548  }
1549 
1559  public function lockIsFree( $lockName, $method ) {
1560  $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1561  $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1562  WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1563  $row = $this->fetchObject( $result );
1564 
1565  return ( $row->lockstatus === 't' );
1566  }
1575  public function lock( $lockName, $method, $timeout = 5 ) {
1576  $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1577  for ( $attempts = 1; $attempts <= $timeout; ++$attempts ) {
1578  $result = $this->query(
1579  "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1580  $row = $this->fetchObject( $result );
1581  if ( $row->lockstatus === 't' ) {
1582  parent::lock( $lockName, $method, $timeout ); // record
1583  return true;
1584  } else {
1585  sleep( 1 );
1586  }
1587  }
1588 
1589  wfDebug( __METHOD__ . " failed to acquire lock\n" );
1590 
1591  return false;
1592  }
1593 
1601  public function unlock( $lockName, $method ) {
1602  $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1603  $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1604  $row = $this->fetchObject( $result );
1605 
1606  if ( $row->lockstatus === 't' ) {
1607  parent::unlock( $lockName, $method ); // record
1608  return true;
1609  }
1610 
1611  wfDebug( __METHOD__ . " failed to release lock\n" );
1612 
1613  return false;
1614  }
1615 
1620  private function bigintFromLockName( $lockName ) {
1621  return Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1622  }
1623 } // end DatabasePostgres class
1624 
1625 class PostgresBlob extends Blob {
1626 }
select($table, $vars, $conds= '', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
Definition: Database.php:1230
indexAttributes($index, $schema=false)
Returns is of attributes used in index.
indexName($index)
Get the name of an index in a given table.
Definition: Database.php:1943
fetchRow($res)
Fetch the next row from the given result object, in associative array form.
lock($lockName, $method, $timeout=5)
See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS.
#define the
table suitable for use with IDatabase::select()
nextSequenceValue($seqName)
Return the next in a sequence, save the value for retrieval via insertId()
constraintExists($table, $constraint)
timestamp($ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
string $connectString
Connect string to open a PostgreSQL connection.
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
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2321
streamStatementEnd(&$sql, &$newLine)
getType()
Get the type of the DBMS, as it appears in $wgDBtype.
implicitOrderby()
Returns true if this database does an implicit order by when the column has an index For example: SEL...
name()
Field name.
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 except in special pages derived from QueryPage It s a common pitfall for new developers to submit code containing SQL queries which examine huge numbers of rows Remember that COUNT * is(N), counting rows in atable is like counting beans in a bucket.------------------------------------------------------------------------Replication------------------------------------------------------------------------The largest installation of MediaWiki, Wikimedia, uses a large set ofslave MySQL servers replicating writes made to a master MySQL server.Itis important to understand the issues associated with this setup if youwant to write code destined for Wikipedia.It's often the case that the best algorithm to use for a given taskdepends on whether or not replication is in use.Due to our unabashedWikipedia-centrism, we often just use the replication-friendly version, but if you like, you can use wfGetLB() ->getServerCount() > 1 tocheck to see if replication is in use.===Lag===Lag primarily occurs when large write queries are sent to the master.Writes on the master are executed in parallel, but they are executed inserial when they are replicated to the slaves.The master writes thequery to the binlog when the transaction is committed.The slaves pollthe binlog and start executing the query as soon as it appears.They canservice reads while they are performing a write query, but will not readanything more from the binlog and thus will perform no more writes.Thismeans that if the write query runs for a long time, the slaves will lagbehind the master for the time it takes for the write query to complete.Lag can be exacerbated by high read load.MediaWiki's load balancer willstop sending reads to a slave when it is lagged by more than 30 seconds.If the load ratios are set incorrectly, or if there is too much loadgenerally, this may lead to a slave permanently hovering around 30seconds lag.If all slaves are lagged by more than 30 seconds, MediaWiki will stopwriting to the database.All edits and other write operations will berefused, with an error returned to the user.This gives the slaves achance to catch up.Before we had this mechanism, the slaves wouldregularly lag by several minutes, making review of recent editsdifficult.In addition to this, MediaWiki attempts to ensure that the user seesevents occurring on the wiki in chronological order.A few seconds of lagcan be tolerated, as long as the user sees a consistent picture fromsubsequent requests.This is done by saving the master binlog positionin the session, and then at the start of each request, waiting for theslave to catch up to that position before doing any reads from it.Ifthis wait times out, reads are allowed anyway, but the request isconsidered to be in"lagged slave mode".Lagged slave mode can bechecked by calling wfGetLB() ->getLaggedSlaveMode().The onlypractical consequence at present is a warning displayed in the pagefooter.===Lag avoidance===To avoid excessive lag, queries which write large numbers of rows shouldbe split up, generally to write one row at a time.Multi-row INSERT...SELECT queries are the worst offenders should be avoided altogether.Instead do the select first and then the insert.===Working with lag===Despite our best efforts, it's not practical to guarantee a low-lagenvironment.Lag will usually be less than one second, but mayoccasionally be up to 30 seconds.For scalability, it's very importantto keep load on the master low, so simply sending all your queries tothe master is not the answer.So when you have a genuine need forup-to-date data, the following approach is advised:1) Do a quick query to the master for a sequence number or timestamp 2) Run the full query on the slave and check if it matches the data you gotfrom the master 3) If it doesn't, run the full query on the masterTo avoid swamping the master every time the slaves lag, use of thisapproach should be kept to a minimum.In most cases you should just readfrom the slave and let the user deal with the delay.------------------------------------------------------------------------Lock contention------------------------------------------------------------------------Due to the high write rate on Wikipedia(and some other wikis), MediaWiki developers need to be very careful to structure their writesto avoid long-lasting locks.By default, MediaWiki opens a transactionat the first query, and commits it before the output is sent.Locks willbe held from the time when the query is done until the commit.So youcan reduce lock time by doing as much processing as possible before youdo your write queries.Often this approach is not good enough, and it becomes necessary toenclose small groups of queries in their own transaction.Use thefollowing syntax:$dbw=wfGetDB(DB_MASTER
replaceVars($ins)
Postgres specific version of replaceVars.
aggregateValue($valuedata, $valuename= 'value')
Return aggregated value function call.
makeOrderBy($options)
Returns an optional ORDER BY.
Definition: Database.php:1217
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
resource $mConn
Database connection.
Definition: Database.php:52
getSearchPath()
Return search patch for schemas This is different from getSchemas() since it contain magic keywords (...
$wgDBmwschema
Mediawiki schema.
$value
query($keyword, $msg_ok, $msg_failed)
unlock($lockName, $method)
See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKSFROM PG DO...
Manage savepoints within a transaction.
reportQueryError($error, $errno, $sql, $fname, $tempIgnore=false)
Report a query error.
makeList($a, $mode=LIST_COMMA)
Makes an encoded list of strings from an array.
Definition: Database.php:1518
Base for all database-specific classes representing information about database fields.
indexUnique($table, $index, $fname=__METHOD__)
decodeBlob($b)
Some DBMSs return a special placeholder object representing blob fields in result objects...
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
relationExists($table, $types, $schema=false)
Query whether a given relation exists (in the given schema, or the default mw one if not given) ...
restoreErrorHandler()
Definition: Database.php:654
in this case you re responsible for computing and outputting the entire conflict i e
Definition: hooks.txt:1240
triggerExists($table, $trigger)
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
getCoreSchema()
Return schema name fore core MediaWiki tables.
lastError()
Get a description of the last error.
currentSequenceValue($seqName)
Return the current value of a sequence.
type()
Database type.
close()
Closes a database connection.
Definition: Database.php:694
selectDB($db)
Postgres doesn't support selectDB in the same way MySQL does.
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
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 '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. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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:Associative array mapping language codes to prefixed links of the form"language:title".&$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':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:1796
if($line===false) $args
Definition: cdb.php:64
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
limitResult($sql, $limit, $offset=false)
global $wgCommandLineMode
Definition: Setup.php:513
ignoreErrors($ignoreErrors=null)
Turns on (false) or off (true) the automatic generation and sending of a "we're sorry, but there has been a database error" page on database errors.
Definition: Database.php:223
getDBname()
Get the current DB name.
numFields($res)
Get the number of fields in a result object.
lastErrno()
Get the last error number.
const LIST_AND
Definition: Defines.php:193
trxLevel()
Gets the current transaction level.
Definition: Database.php:227
fieldName($res, $n)
Get a field name in a result object.
isNullable()
Whether this field can store NULL values.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1004
queryIgnore($sql, $fname=__METHOD__)
sequenceExists($sequence, $schema=false)
$res
Definition: database.txt:21
buildGroupConcatField($delimiter, $table, $field, $conds= '', $options=[], $join_conds=[])
getSchemas()
Return list of schemas which are accessible without schema name This is list does not contain magic k...
buildConcat($stringList)
Build a concatenation list to feed into a SQL query.
duplicateTableStructure($oldName, $newName, $temporary=false, $fname=__METHOD__)
determineCoreSchema($desiredSchema)
Determine default schema for MediaWiki core Adjust this session schema search path if desired schema ...
and(b) You must cause any modified files to carry prominent notices stating that You changed the files
implicitGroupby()
Returns true if this database does an implicit sort when doing GROUP BY.
while(($__line=Maintenance::readconsole())!==false) print n
Definition: eval.php:64
addIdentifierQuotes($s)
Quotes an identifier using backticks or "double quotes" depending on the database type...
Definition: Database.php:1982
setSearchPath($search_path)
Update search_path, values should already be sanitized Values may contain magic keywords like "$user"...
selectSQLText($table, $vars, $conds= '', $fname=__METHOD__, $options=[], $join_conds=[])
Change the FOR UPDATE option as necessary based on the join conditions.
roleExists($roleName)
Returns true if a given role (i.e.
insert($table, $args, $fname=__METHOD__, $options=[])
INSERT wrapper, inserts an array into a table.
return['SiteStore'=> function(MediaWikiServices $services){$loadBalancer=wfGetLB();$rawSiteStore=new DBSiteStore($loadBalancer);$cache=wfGetCache(wfIsHHVM()?CACHE_ACCEL:CACHE_ANYTHING);return new CachingSiteStore($rawSiteStore, $cache);},'SiteLookup'=> function(MediaWikiServices $services){return $services->getSiteStore();},'ConfigFactory'=> function(MediaWikiServices $services){$registry=$services->getBootstrapConfig() ->get( 'ConfigRegistry');$factory=new ConfigFactory();foreach($registry as $name=> $callback){$factory->register($name, $callback);}return $factory;},'MainConfig'=> function(MediaWikiServices $services){return $services->getConfigFactory() ->makeConfig( 'main');},'StatsdDataFactory'=> function(MediaWikiServices $services){return new BufferingStatsdDataFactory(rtrim($services->getMainConfig() ->get( 'StatsdMetricPrefix'), '.'));},'EventRelayerGroup'=> function(MediaWikiServices $services){return new EventRelayerGroup($services->getMainConfig() ->get( 'EventRelayerConfig'));},'SearchEngineFactory'=> function(MediaWikiServices $services){return new SearchEngineFactory($services->getSearchEngineConfig());},'SearchEngineConfig'=> function(MediaWikiServices $services){global $wgContLang;return new SearchEngineConfig($services->getMainConfig(), $wgContLang);},'SkinFactory'=> function(MediaWikiServices $services){return new SkinFactory();},]
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
affectedRows()
Get the number of rows affected by the last write query.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
bigintFromLockName($lockName)
wasDeadlock()
Determines if the last failure was due to a deadlock STUB.
float string $numericVersion
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object & $output
Definition: hooks.txt:1004
getCurrentSchema()
Return current schema (executes SELECT current_schema()) Needs transaction.
if($IP===false)
Definition: WebStart.php:59
ruleExists($table, $rule)
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
selectField($table, $var, $cond= '', $fname=__METHOD__, $options=[])
A SELECT wrapper which returns a single field from a single result row.
Definition: Database.php:1045
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined...
Definition: Setup.php:35
$wgDBport
Database port number (for PostgreSQL and Microsoft SQL Server).
listTables($prefix=null, $fname=__METHOD__)
List all tables on the database.
tableName($name, $format= 'quoted')
tableName()
Name of table this field belongs to.
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 http://www.php.net/manual/en/ref.pgsql.php.
begin($fname=__METHOD__)
Begin a transaction.
Definition: Database.php:2582
query($sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
Definition: Database.php:780
textFieldSize($table, $field)
tableExists($table, $fname=__METHOD__, $schema=false)
For backward compatibility, this function checks both tables and views.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive $limit
Definition: hooks.txt:1004
commit($fname=__METHOD__, $flush= '')
Commits a transaction previously started using begin().
Definition: Database.php:2657
open($server, $user, $password, $dbName)
Usually aborts on failure.
fieldType($res, $index)
pg_field_type() wrapper
$count
indexInfo($table, $index, $fname=__METHOD__)
Returns information about an index If errors are explicitly ignored, returns NULL on failure...
fieldInfo($table, $field)
mysql_fetch_field() wrapper Returns false if the field doesn't exist
insertSelect($destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[])
INSERT SELECT wrapper $varMap must be an associative array of the form array( 'dest1' => 'source1'...
We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going on
Definition: hooks.txt:86
rollback($fname=__METHOD__, $flush= '')
Rollback a transaction previously started using begin().
Definition: Database.php:2712
makeGroupByWithHaving($options)
Returns an optional GROUP BY with an optional HAVING.
Definition: Database.php:1191
int $mAffectedRows
The number of rows affected as an integer.
static fromText($db, $table, $field)
const TS_POSTGRES
Postgres format time.
getServer()
Get the server hostname or IP address.
closeConnection()
Closes a database connection, if it is open Returns success, true if already closed.
installErrorHandler()
Definition: Database.php:645
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:1996
schemaExists($schema)
Query whether a given schema exists.
makeSelectOptions($options)
Various select options.
realTableName($name, $format= 'quoted')
estimateRowCount($table, $vars= '*', $conds= '', $fname=__METHOD__, $options=[])
Estimate rows in dataset Returns estimated count, based on EXPLAIN output This is not necessarily an ...
lockIsFree($lockName, $method)
Check to see if a named lock is available.
insertId()
Return the result of the last call to nextSequenceValue(); This must be called after nextSequenceValu...
numRows($res)
Get the number of rows in a result object.
DatabasePostgres $dbw
Establish a savepoint within a transaction.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310