34 static function fromText( $db, $table, $field ) {
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
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
59 $table = $db->tableName( $table,
'raw' );
62 $db->addQuotes( $db->getCoreSchema() ),
63 $db->addQuotes( $table ),
64 $db->addQuotes( $field )
67 $row = $db->fetchObject(
$res );
72 $n->
type = $row->typname;
73 $n->nullable = ( $row->attnotnull ==
'f' );
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;
123 if ( $this->has_default ) {
149 $this->didbegin =
false;
153 $this->didbegin =
true;
158 if ( $this->didbegin ) {
159 $this->dbw->rollback();
160 $this->didbegin =
false;
164 public function commit() {
165 if ( $this->didbegin ) {
166 $this->dbw->commit();
167 $this->didbegin =
false;
171 protected function query( $keyword, $msg_ok, $msg_failed ) {
172 if ( $this->dbw->doQuery( $keyword .
" " . $this->id ) !==
false ) {
174 wfDebug( sprintf( $msg_failed, $this->
id ) );
179 $this->
query(
"SAVEPOINT",
180 "Transaction state: savepoint \"%s\" established.\n",
181 "Transaction state: establishment of savepoint \"%s\" FAILED.\n"
186 $this->
query(
"RELEASE",
187 "Transaction state: savepoint \"%s\" released.\n",
188 "Transaction state: release of savepoint \"%s\" FAILED.\n"
194 "Transaction state: savepoint \"%s\" rolled back.\n",
195 "Transaction state: rollback of savepoint \"%s\" FAILED.\n"
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() ) .
"'";
281 function open( $server,
$user, $password, $dbName ) {
282 # Test for Postgres support, to avoid suppressed fatal error
283 if ( !function_exists(
'pg_connect' ) ) {
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"
294 if ( !strlen(
$user ) ) { #
e.g.
the class is being loaded
298 $this->mServer = $server;
300 $this->mUser =
$user;
301 $this->mPassword = $password;
302 $this->mDBname = $dbName;
307 'password' => $password
309 if ( $server !=
false && $server !=
'' ) {
310 $connectVars[
'host'] = $server;
312 if ( $port !=
false && $port !=
'' ) {
313 $connectVars[
'port'] = $port;
315 if ( $this->mFlags & DBO_SSL ) {
316 $connectVars[
'sslmode'] = 1;
324 $this->mConn = pg_connect( $this->connectString );
325 }
catch ( Exception $ex ) {
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" );
340 $this->mOpened =
true;
343 # If called from the command-line (e.g. importDump), only show errors
344 if ( $wgCommandLineMode ) {
345 $this->
doQuery(
"SET client_min_messages = 'ERROR'" );
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__ );
353 $this->
query(
"SET bytea_output = 'escape'", __METHOD__ );
369 if ( $this->mDBname !== $db ) {
370 return (
bool)$this->
open( $this->mServer, $this->mUser, $this->mPassword, $db );
379 $s .=
"$name='" . str_replace(
"'",
"\\'",
$value ) .
"' ";
391 return pg_close( $this->mConn );
394 public function doQuery( $sql ) {
395 $sql = mb_convert_encoding( $sql,
'UTF-8' );
397 while (
$res = pg_get_result( $this->mConn ) ) {
398 pg_free_result(
$res );
400 if ( pg_send_query( $this->mConn, $sql ) ===
false ) {
401 throw new DBUnexpectedError( $this,
"Unable to post new query to PostgreSQL\n" );
403 $this->mLastResult = pg_get_result( $this->mConn );
404 $this->mAffectedRows = null;
405 if ( pg_result_error( $this->mLastResult ) ) {
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,
423 PGSQL_DIAG_SOURCE_FILE,
424 PGSQL_DIAG_SOURCE_LINE,
425 PGSQL_DIAG_SOURCE_FUNCTION
427 foreach ( $diags
as $d ) {
428 wfDebug( sprintf(
"PgSQL ERROR(%d): %s\n",
429 $d, pg_result_error_field( $this->mLastResult, $d ) ) );
436 if ( $errno ===
'23505' ) {
437 parent::reportQueryError( $error, $errno, $sql,
$fname, $tempIgnore );
443 if ( $this->mTrxLevel ) {
448 parent::reportQueryError( $error, $errno, $sql,
$fname,
false );
460 if (
$res instanceof ResultWrapper ) {
463 MediaWiki\suppressWarnings();
464 $ok = pg_free_result(
$res );
465 MediaWiki\restoreWarnings();
477 if (
$res instanceof ResultWrapper ) {
480 MediaWiki\suppressWarnings();
481 $row = pg_fetch_object(
$res );
482 MediaWiki\restoreWarnings();
483 # @todo FIXME: HACK HACK HACK HACK debug
485 # @todo hashar: not sure if the following test really trigger if the object
487 if ( pg_last_error( $this->mConn ) ) {
490 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) )
498 if (
$res instanceof ResultWrapper ) {
501 MediaWiki\suppressWarnings();
502 $row = pg_fetch_array(
$res );
503 MediaWiki\restoreWarnings();
504 if ( pg_last_error( $this->mConn ) ) {
507 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) )
515 if (
$res instanceof ResultWrapper ) {
518 MediaWiki\suppressWarnings();
519 $n = pg_num_rows(
$res );
520 MediaWiki\restoreWarnings();
521 if ( pg_last_error( $this->mConn ) ) {
524 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) )
532 if (
$res instanceof ResultWrapper ) {
536 return pg_num_fields(
$res );
540 if (
$res instanceof ResultWrapper ) {
544 return pg_field_name(
$res, $n );
563 if (
$res instanceof ResultWrapper ) {
567 return pg_result_seek(
$res, $row );
571 if ( $this->mConn ) {
572 if ( $this->mLastResult ) {
573 return pg_result_error( $this->mLastResult );
575 return pg_last_error();
578 return 'No database connection';
583 if ( $this->mLastResult ) {
584 return pg_result_error_field( $this->mLastResult, PGSQL_DIAG_SQLSTATE );
591 if ( !is_null( $this->mAffectedRows ) ) {
595 if ( empty( $this->mLastResult ) ) {
599 return pg_affected_rows( $this->mLastResult );
625 if ( preg_match(
'/rows=(\d+)/', $row[0],
$count ) ) {
643 $sql =
"SELECT indexname FROM pg_indexes WHERE tablename='$table'";
648 foreach (
$res as $row ) {
649 if ( $row->indexname == $this->indexName( $index ) ) {
666 if ( $schema ===
false ) {
673 $sql = <<<__INDEXATTR__
677 i.indoption[s.g]
as option,
680 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
684 ON cis.oid=isub.indexrelid
686 ON cis.relnamespace = ns.oid
687 WHERE cis.relname=
'$index' AND ns.nspname=
'$schema') AS s,
693 ON ci.oid=i.indexrelid
695 ON ct.oid = i.indrelid
697 ON ci.relnamespace =
n.oid
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
708 foreach ( $res
as $row ) {
723 $sql =
"SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
724 " AND indexdef LIKE 'CREATE UNIQUE%(" .
732 return $res->numRows() > 0;
750 $forUpdateKey = array_search(
'FOR UPDATE',
$options,
true );
751 if ( $forUpdateKey !==
false && $join_conds ) {
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;
782 if ( !count(
$args ) ) {
787 if ( !isset( $this->numericVersion ) ) {
795 if ( isset(
$args[0] ) && is_array(
$args[0] ) ) {
805 if ( in_array(
'IGNORE',
$options ) ) {
807 $olde = error_reporting( 0 );
810 $numrowsinserted = 0;
813 $sql =
"INSERT INTO $table (" . implode(
',',
$keys ) .
') VALUES ';
816 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
824 $sql .=
'(' . $this->
makeList( $row ) .
')';
832 $tempsql .=
'(' . $this->
makeList( $row ) .
')';
835 $savepoint->savepoint();
838 $tempres = (bool)$this->
query( $tempsql,
$fname, $savepoint );
841 $bar = pg_result_error( $this->mLastResult );
842 if ( $bar !=
false ) {
843 $savepoint->rollback();
845 $savepoint->release();
860 $savepoint->savepoint();
866 $bar = pg_result_error( $this->mLastResult );
867 if ( $bar !=
false ) {
868 $savepoint->rollback();
870 $savepoint->release();
876 error_reporting( $olde );
877 $savepoint->commit();
880 $this->mAffectedRows = $numrowsinserted;
908 $insertOptions = [], $selectOptions = [] ) {
909 $destTable = $this->
tableName( $destTable );
911 if ( !is_array( $insertOptions ) ) {
912 $insertOptions = [ $insertOptions ];
920 if ( in_array(
'IGNORE', $insertOptions ) ) {
922 $olde = error_reporting( 0 );
923 $numrowsinserted = 0;
924 $savepoint->savepoint();
927 if ( !is_array( $selectOptions ) ) {
928 $selectOptions = [ $selectOptions ];
931 if ( is_array( $srcTable ) ) {
932 $srcTable = implode(
',', array_map( [ &$this,
'tableName' ], $srcTable ) );
934 $srcTable = $this->
tableName( $srcTable );
937 $sql =
"INSERT INTO $destTable (" . implode(
',', array_keys( $varMap ) ) .
')' .
938 " SELECT $startOpts " . implode(
',', $varMap ) .
939 " FROM $srcTable $useIndex";
941 if ( $conds !=
'*' ) {
945 $sql .=
" $tailOpts";
949 $bar = pg_result_error( $this->mLastResult );
950 if ( $bar !=
false ) {
951 $savepoint->rollback();
953 $savepoint->release();
956 error_reporting( $olde );
957 $savepoint->commit();
960 $this->mAffectedRows = $numrowsinserted;
970 # Replace reserved words with better ones
993 $safeseq = str_replace(
"'",
"''", $seqName );
994 $res = $this->
query(
"SELECT nextval('$safeseq')" );
996 $this->mInsertId = $row[0];
1008 $safeseq = str_replace(
"'",
"''", $seqName );
1009 $res = $this->
query(
"SELECT currval('$safeseq')" );
1016 # Returns the size of a text field, or -1 for "unlimited"
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'";
1025 if ( $row->ftype ==
'varchar' ) {
1026 $size = $row->size - 4;
1035 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " :
'' );
1046 return $this->
query(
'CREATE ' . ( $temporary ?
'TEMPORARY ' :
'' ) .
" TABLE $newName " .
1047 "(LIKE $oldName INCLUDING DEFAULTS)",
$fname );
1052 $result = $this->
query(
"SELECT tablename FROM pg_tables WHERE schemaname = $eschema",
$fname );
1056 $vars = get_object_vars( $table );
1057 $table = array_pop(
$vars );
1058 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1059 $endArray[] = $table;
1089 if (
false ===
$limit ) {
1090 $limit = strlen( $text ) - 1;
1093 if (
'{}' == $text ) {
1097 if (
'{' != $text[$offset] ) {
1098 preg_match(
"/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
1099 $text, $match, 0, $offset );
1100 $offset += strlen( $match[0] );
1101 $output[] = (
'"' != $match[1][0]
1103 : stripcslashes( substr( $match[1], 1, -1 ) ) );
1104 if (
'},' == $match[3] ) {
1110 }
while (
$limit > $offset );
1121 public function aggregateValue( $valuedata, $valuename =
'value' ) {
1129 return '[{{int:version-db-postgres-url}} PostgreSQL]';
1140 $res = $this->
query(
"SELECT current_schema()", __METHOD__ );
1157 $res = $this->
query(
"SELECT current_schemas(false)", __METHOD__ );
1176 $res = $this->
query(
"SHOW search_path", __METHOD__ );
1181 return explode(
",", $row[0] );
1192 $this->
query(
"SET search_path = " . implode(
", ", $search_path ) );
1210 $this->
begin( __METHOD__ );
1212 if ( in_array( $desiredSchema, $this->
getSchemas() ) ) {
1213 $this->mCoreSchema = $desiredSchema;
1214 wfDebug(
"Schema \"" . $desiredSchema .
"\" already in the search path\n" );
1222 array_unshift( $search_path,
1225 $this->mCoreSchema = $desiredSchema;
1226 wfDebug(
"Schema \"" . $desiredSchema .
"\" added to the search path\n" );
1230 wfDebug(
"Schema \"" . $desiredSchema .
"\" not found, using current \"" .
1231 $this->mCoreSchema .
"\"\n" );
1234 $this->
commit( __METHOD__ );
1251 if ( !isset( $this->numericVersion ) ) {
1252 $versionInfo = pg_version( $this->mConn );
1253 if ( version_compare( $versionInfo[
'client'],
'7.4.0',
'lt' ) ) {
1255 $this->numericVersion =
'7.3 or earlier';
1256 } elseif ( isset( $versionInfo[
'server'] ) ) {
1258 $this->numericVersion = $versionInfo[
'server'];
1261 $this->numericVersion = pg_parameter_status( $this->mConn,
'server_version' );
1277 if ( !is_array( $types ) ) {
1278 $types = [ $types ];
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 ) .
"')";
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
1329 $rows =
$res->numRows();
1335 $exists = $this->
selectField(
'pg_rules',
'rulename',
1337 'rulename' => $rule,
1338 'tablename' => $table,
1343 return $exists === $rule;
1347 $sql = sprintf(
"SELECT 1 FROM information_schema.table_constraints " .
1348 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1368 $exists = $this->
selectField(
'"pg_catalog"."pg_namespace"', 1,
1369 [
'nspname' => $schema ], __METHOD__ );
1371 return (
bool)$exists;
1380 $exists = $this->
selectField(
'"pg_catalog"."pg_roles"', 1,
1381 [
'rolname' => $roleName ], __METHOD__ );
1383 return (
bool)$exists;
1402 if (
$res instanceof ResultWrapper ) {
1406 return pg_field_type(
$res, $index );
1414 return new PostgresBlob( pg_escape_bytea( $b ) );
1418 if ( $b instanceof PostgresBlob ) {
1420 } elseif ( $b instanceof Blob ) {
1424 return pg_unescape_bytea( $b );
1430 return pg_escape_string( $this->mConn,
$s );
1438 if ( is_null(
$s ) ) {
1440 } elseif ( is_bool(
$s ) ) {
1441 return intval(
$s );
1442 } elseif (
$s instanceof Blob ) {
1443 if (
$s instanceof PostgresBlob ) {
1446 $s = pg_escape_bytea( $this->mConn,
$s->fetch() );
1451 return "'" . pg_escape_string( $this->mConn,
$s ) .
"'";
1462 $ins = parent::replaceVars( $ins );
1464 if ( $this->numericVersion >= 8.3 ) {
1466 $ins = preg_replace(
"/to_tsvector\s*\(\s*'default'\s*,/",
'to_tsvector(', $ins );
1469 if ( $this->numericVersion <= 8.1 ) {
1470 $ins = str_replace(
'USING gin',
'USING gist', $ins );
1484 $preLimitTail = $postLimitTail =
'';
1485 $startOpts = $useIndex =
'';
1489 if ( is_numeric( $key ) ) {
1490 $noKeyOptions[$option] =
true;
1505 $postLimitTail .=
' FOR UPDATE OF ' .
1506 implode(
', ', array_map( [ &$this,
'tableName' ],
$options[
'FOR UPDATE'] ) );
1507 } elseif ( isset( $noKeyOptions[
'FOR UPDATE'] ) ) {
1508 $postLimitTail .=
' FOR UPDATE';
1511 if ( isset( $noKeyOptions[
'DISTINCT'] ) || isset( $noKeyOptions[
'DISTINCTROW'] ) ) {
1512 $startOpts .=
'DISTINCT';
1515 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail ];
1527 return implode(
' || ', $stringList );
1535 return '(' . $this->
selectSQLText( $table, $fld, $conds, null, [], $join_conds ) .
')';
1539 return 'SearchPostgres';
1543 # Allow dollar quoting for function declarations
1544 if ( substr( $newLine, 0, 4 ) ==
'$mw$' ) {
1545 if ( $this->delimiter ) {
1546 $this->delimiter =
false;
1548 $this->delimiter =
';';
1552 return parent::streamStatementEnd( $sql, $newLine );
1564 public function lockIsFree( $lockName, $method ) {
1566 $result = $this->
query(
"SELECT (CASE(pg_try_advisory_lock($key))
1567 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1570 return ( $row->lockstatus ===
't' );
1580 public function lock( $lockName, $method, $timeout = 5 ) {
1582 for ( $attempts = 1; $attempts <= $timeout; ++$attempts ) {
1584 "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1586 if ( $row->lockstatus ===
't' ) {
1587 parent::lock( $lockName, $method, $timeout );
1594 wfDebug( __METHOD__ .
" failed to acquire lock\n" );
1606 public function unlock( $lockName, $method ) {
1608 $result = $this->
query(
"SELECT pg_advisory_unlock($key) as lockstatus", $method );
1611 if ( $row->lockstatus ===
't' ) {
1612 parent::unlock( $lockName, $method );
1616 wfDebug( __METHOD__ .
" failed to release lock\n" );
1626 return Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1630 class PostgresBlob
extends Blob {
select($table, $vars, $conds= '', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
indexAttributes($index, $schema=false)
Returns is of attributes used in index.
indexName($index)
Get the name of an index in a given table.
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
string $connectString
Connect string to open a PostgreSQL connection.
streamStatementEnd(&$sql, &$newLine)
processing should stop and the error should be shown to the user * false
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...
replaceVars($ins)
Postgres specific version of replaceVars.
aggregateValue($valuedata, $valuename= 'value')
Return aggregated value function call.
makeOrderBy($options)
Returns an optional ORDER BY.
resource $mConn
Database connection.
getSearchPath()
Return search patch for schemas This is different from getSchemas() since it contain magic keywords (...
$wgDBmwschema
Mediawiki schema.
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.
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
relationExists($table, $types, $schema=false)
Query whether a given relation exists (in the given schema, or the default mw one if not given) ...
in this case you re responsible for computing and outputting the entire conflict i e
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.
close()
Closes a database connection.
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':DEPRECATED!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
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
limitResult($sql, $limit, $offset=false)
global $wgCommandLineMode
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.
getDBname()
Get the current DB name.
Some quick notes on the file repository architecture Functionality is
numFields($res)
Get the number of fields in a result object.
makeConnectionString($vars)
lastErrno()
Get the last error number.
trxLevel()
Gets the current transaction level.
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
queryIgnore($sql, $fname=__METHOD__)
sequenceExists($sequence, $schema=false)
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
addIdentifierQuotes($s)
Quotes an identifier using backticks or "double quotes" depending on the database type...
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.
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
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
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
getCurrentSchema()
Return current schema (executes SELECT current_schema()) Needs transaction.
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
selectField($table, $var, $cond= '', $fname=__METHOD__, $options=[])
A SELECT wrapper which returns a single field from a single result row.
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined...
$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.
return['DBLoadBalancerFactory'=> function(MediaWikiServices $services){$config=$services->getMainConfig() ->get( 'LBFactoryConf');$class=LBFactory::getLBFactoryClass($config);if(!isset($config['readOnlyReason'])){$config['readOnlyReason']=wfConfiguredReadOnlyReason();}return new $class($config);},'DBLoadBalancer'=> function(MediaWikiServices $services){return $services->getDBLoadBalancerFactory() ->getMainLB();},'SiteStore'=> function(MediaWikiServices $services){$rawSiteStore=new DBSiteStore($services->getDBLoadBalancer());$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');},'InterwikiLookup'=> function(MediaWikiServices $services){global $wgContLang;$config=$services->getMainConfig();return new ClassicInterwikiLookup($wgContLang, ObjectCache::getMainWANInstance(), $config->get( 'InterwikiExpiry'), $config->get( 'InterwikiCache'), $config->get( 'InterwikiScopes'), $config->get( 'InterwikiFallbackSite'));},'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){$factory=new SkinFactory();$names=$services->getMainConfig() ->get( 'ValidSkinNames');foreach($names as $name=> $skin){$factory->register($name, $skin, function() use($name, $skin){$class="Skin$skin";return new $class($name);});}$factory->register( 'fallback', 'Fallback', function(){return new SkinFallback;});$factory->register( 'apioutput', 'ApiOutput', function(){return new SkinApi;});return $factory;},'WatchedItemStore'=> function(MediaWikiServices $services){$store=new WatchedItemStore($services->getDBLoadBalancer(), new HashBagOStuff([ 'maxKeys'=> 100]));$store->setStatsdDataFactory($services->getStatsdDataFactory());return $store;},'WatchedItemQueryService'=> function(MediaWikiServices $services){return new WatchedItemQueryService($services->getDBLoadBalancer());},'LinkCache'=> function(MediaWikiServices $services){return new LinkCache($services->getTitleFormatter());},'LinkRendererFactory'=> function(MediaWikiServices $services){return new LinkRendererFactory($services->getTitleFormatter(), $services->getLinkCache());},'LinkRenderer'=> function(MediaWikiServices $services){global $wgUser;if(defined( 'MW_NO_SESSION')){return $services->getLinkRendererFactory() ->create();}else{return $services->getLinkRendererFactory() ->createForUser($wgUser);}},'GenderCache'=> function(MediaWikiServices $services){return new GenderCache();},'_MediaWikiTitleCodec'=> function(MediaWikiServices $services){global $wgContLang;return new MediaWikiTitleCodec($wgContLang, $services->getGenderCache(), $services->getMainConfig() ->get( 'LocalInterwikis'));},'TitleFormatter'=> function(MediaWikiServices $services){return $services->getService( '_MediaWikiTitleCodec');},'TitleParser'=> function(MediaWikiServices $services){return $services->getService( '_MediaWikiTitleCodec');},]
query($sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
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
commit($fname=__METHOD__, $flush= '')
Commits a transaction previously started using begin().
open($server, $user, $password, $dbName)
Usually aborts on failure.
fieldType($res, $index)
pg_field_type() wrapper
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
rollback($fname=__METHOD__, $flush= '')
Rollback a transaction previously started using begin().
makeGroupByWithHaving($options)
Returns an optional GROUP BY with an optional HAVING.
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.
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
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