Go to the documentation of this file.
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;
122 if ( $this->has_default ) {
140 "desc" =>
"%s: Connection state changed from %s -> %s\n",
142 PGSQL_CONNECTION_OK =>
"OK",
143 PGSQL_CONNECTION_BAD =>
"BAD"
147 "desc" =>
"%s: Transaction state changed from %s -> %s\n",
149 PGSQL_TRANSACTION_IDLE =>
"IDLE",
150 PGSQL_TRANSACTION_ACTIVE =>
"ACTIVE",
151 PGSQL_TRANSACTION_INTRANS =>
"TRANS",
152 PGSQL_TRANSACTION_INERROR =>
"ERROR",
153 PGSQL_TRANSACTION_UNKNOWN =>
"UNKNOWN"
165 $this->mConn = $conn;
170 public function update() {
171 $this->mNewState =
array(
172 pg_connection_status( $this->mConn ),
173 pg_transaction_status( $this->mConn )
177 public function check() {
178 global $wgDebugDBTransactions;
180 if ( $wgDebugDBTransactions ) {
181 if ( $this->mCurrentState !== $this->mNewState ) {
182 $old = reset( $this->mCurrentState );
183 $new = reset( $this->mNewState );
184 foreach ( self::$WATCHED
as $watched ) {
185 if ( $old !== $new ) {
188 $old = next( $this->mCurrentState );
189 $new = next( $this->mNewState );
197 if ( isset( $desc_table[$status] ) ) {
198 return $desc_table[$status];
200 return "STATUS " . $status;
204 protected function log_changed( $old, $new, $watched ) {
205 wfDebug( sprintf( $watched[
"desc"],
231 $this->didbegin =
false;
235 $this->didbegin =
true;
240 if ( $this->didbegin ) {
241 $this->dbw->rollback();
242 $this->didbegin =
false;
247 if ( $this->didbegin ) {
248 $this->dbw->commit();
249 $this->didbegin =
false;
253 protected function query( $keyword, $msg_ok, $msg_failed ) {
254 global $wgDebugDBTransactions;
255 if ( $this->dbw->doQuery( $keyword .
" " . $this->id ) !==
false ) {
256 if ( $wgDebugDBTransactions ) {
257 wfDebug( sprintf( $msg_ok, $this->
id ) );
265 $this->
query(
"SAVEPOINT",
266 "Transaction state: savepoint \"%s\" established.\n",
267 "Transaction state: establishment of savepoint \"%s\" FAILED.\n"
272 $this->
query(
"RELEASE",
273 "Transaction state: savepoint \"%s\" released.\n",
274 "Transaction state: release of savepoint \"%s\" FAILED.\n"
280 "Transaction state: savepoint \"%s\" rolled back.\n",
281 "Transaction state: rollback of savepoint \"%s\" FAILED.\n"
352 $sql =
"SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
353 "WHERE c.connamespace = n.oid AND conname = '" .
354 pg_escape_string( $this->mConn,
$name ) .
"' AND n.nspname = '" .
355 pg_escape_string( $this->mConn, $this->
getCoreSchema() ) .
"'";
371 # Test for Postgres support, to avoid suppressed fatal error
372 if ( !function_exists(
'pg_connect' ) ) {
375 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
376 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
377 "webserver and database)\n"
383 if ( !strlen(
$user ) ) { #
e.g. the
class is being loaded
387 $this->mServer = $server;
389 $this->mUser =
$user;
391 $this->mDBname = $dbName;
393 $connectVars =
array(
398 if ( $server !=
false && $server !=
'' ) {
399 $connectVars[
'host'] = $server;
401 if ( $port !=
false && $port !=
'' ) {
402 $connectVars[
'port'] = $port;
404 if ( $this->mFlags &
DBO_SSL ) {
405 $connectVars[
'sslmode'] = 1;
413 $this->mConn = pg_connect( $this->connectString );
414 }
catch ( Exception $ex ) {
421 if ( !$this->mConn ) {
422 wfDebug(
"DB connection error\n" );
423 wfDebug(
"Server: $server, Database: $dbName, User: $user, Password: " .
429 $this->mOpened =
true;
433 # If called from the command-line (e.g. importDump), only show errors
435 $this->
doQuery(
"SET client_min_messages = 'ERROR'" );
438 $this->
query(
"SET client_encoding='UTF8'", __METHOD__ );
439 $this->
query(
"SET datestyle = 'ISO, YMD'", __METHOD__ );
440 $this->
query(
"SET timezone = 'GMT'", __METHOD__ );
441 $this->
query(
"SET standard_conforming_strings = on", __METHOD__ );
443 $this->
query(
"SET bytea_output = 'escape'", __METHOD__ );
459 if ( $this->mDBname !== $db ) {
460 return (
bool)$this->
open( $this->mServer, $this->mUser, $this->mPassword, $db );
469 $s .=
"$name='" . str_replace(
"'",
"\\'",
$value ) .
"' ";
481 return pg_close( $this->mConn );
484 public function doQuery( $sql ) {
485 if ( function_exists(
'mb_convert_encoding' ) ) {
486 $sql = mb_convert_encoding( $sql,
'UTF-8' );
488 $this->mTransactionState->check();
489 if ( pg_send_query( $this->mConn, $sql ) ===
false ) {
490 throw new DBUnexpectedError( $this,
"Unable to post new query to PostgreSQL\n" );
492 $this->mLastResult = pg_get_result( $this->mConn );
493 $this->mTransactionState->check();
494 $this->mAffectedRows =
null;
495 if ( pg_result_error( $this->mLastResult ) ) {
506 PGSQL_DIAG_MESSAGE_PRIMARY,
507 PGSQL_DIAG_MESSAGE_DETAIL,
508 PGSQL_DIAG_MESSAGE_HINT,
509 PGSQL_DIAG_STATEMENT_POSITION,
510 PGSQL_DIAG_INTERNAL_POSITION,
511 PGSQL_DIAG_INTERNAL_QUERY,
513 PGSQL_DIAG_SOURCE_FILE,
514 PGSQL_DIAG_SOURCE_LINE,
515 PGSQL_DIAG_SOURCE_FUNCTION
517 foreach ( $diags
as $d ) {
518 wfDebug( sprintf(
"PgSQL ERROR(%d): %s\n",
519 $d, pg_result_error_field( $this->mLastResult, $d ) ) );
527 if ( $errno ===
'23505' ) {
528 parent::reportQueryError(
$error, $errno, $sql,
$fname, $tempIgnore );
535 parent::reportQueryError(
$error, $errno, $sql,
$fname,
false );
568 $row = pg_fetch_object(
$res );
570 # @todo FIXME: HACK HACK HACK HACK debug
572 # @todo hashar: not sure if the following test really trigger if the object
574 if ( pg_last_error( $this->mConn ) ) {
577 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) )
589 $row = pg_fetch_array(
$res );
591 if ( pg_last_error( $this->mConn ) ) {
594 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) )
608 if ( pg_last_error( $this->mConn ) ) {
611 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) )
623 return pg_num_fields(
$res );
631 return pg_field_name(
$res,
$n );
654 return pg_result_seek(
$res, $row );
658 if ( $this->mConn ) {
659 if ( $this->mLastResult ) {
660 return pg_result_error( $this->mLastResult );
662 return pg_last_error();
665 return 'No database connection';
670 if ( $this->mLastResult ) {
671 return pg_result_error_field( $this->mLastResult, PGSQL_DIAG_SQLSTATE );
678 if ( !is_null( $this->mAffectedRows ) ) {
682 if ( empty( $this->mLastResult ) ) {
686 return pg_affected_rows( $this->mLastResult );
712 if ( preg_match(
'/rows=(\d+)/', $row[0],
$count ) ) {
730 $sql =
"SELECT indexname FROM pg_indexes WHERE tablename='$table'";
735 foreach (
$res as $row ) {
736 if ( $row->indexname == $this->indexName( $index ) ) {
753 if ( $schema ===
false ) {
760 $sql = <<<__INDEXATTR__
764 i.indoption[s.g]
as option,
767 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
771 ON cis.oid=isub.indexrelid
773 ON cis.relnamespace = ns.oid
774 WHERE cis.relname=
'$index' AND ns.nspname=
'$schema') AS s,
780 ON ci.oid=i.indexrelid
782 ON ct.oid = i.indrelid
784 ON ci.relnamespace =
n.oid
786 ci.relname='$index' AND
n.nspname='$schema'
787 AND attrelid = ct.oid
788 AND i.indkey[s.g] = attnum
789 AND i.indclass[s.g] = opcls.oid
790 AND pg_am.oid = opcls.opcmethod
795 foreach (
$res as $row ) {
810 $sql =
"SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
811 " AND indexdef LIKE 'CREATE UNIQUE%(" .
819 return $res->numRows() > 0;
836 $forUpdateKey = array_search(
'FOR UPDATE',
$options );
837 if ( $forUpdateKey !==
false && $join_conds ) {
840 foreach ( $join_conds
as $table_cond => $join_cond ) {
841 if ( 0 === preg_match(
'/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_cond[0] ) ) {
842 $options[
'FOR UPDATE'][] = $table_cond;
868 if ( !count(
$args ) ) {
873 if ( !isset( $this->numericVersion ) ) {
881 if ( isset(
$args[0] ) && is_array(
$args[0] ) ) {
891 if ( in_array(
'IGNORE',
$options ) ) {
893 $olde = error_reporting( 0 );
896 $numrowsinserted = 0;
899 $sql =
"INSERT INTO $table (" . implode(
',',
$keys ) .
') VALUES ';
902 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
910 $sql .=
'(' . $this->
makeList( $row ) .
')';
918 $tempsql .=
'(' . $this->
makeList( $row ) .
')';
921 $savepoint->savepoint();
924 $tempres = (bool)$this->
query( $tempsql,
$fname, $savepoint );
927 $bar = pg_last_error();
928 if ( $bar !=
false ) {
929 $savepoint->rollback();
931 $savepoint->release();
946 $savepoint->savepoint();
952 $bar = pg_last_error();
953 if ( $bar !=
false ) {
954 $savepoint->rollback();
956 $savepoint->release();
962 error_reporting( $olde );
963 $savepoint->commit();
966 $this->mAffectedRows = $numrowsinserted;
994 $insertOptions =
array(), $selectOptions =
array() ) {
995 $destTable = $this->
tableName( $destTable );
997 if ( !is_array( $insertOptions ) ) {
998 $insertOptions =
array( $insertOptions );
1006 if ( in_array(
'IGNORE', $insertOptions ) ) {
1008 $olde = error_reporting( 0 );
1009 $numrowsinserted = 0;
1010 $savepoint->savepoint();
1013 if ( !is_array( $selectOptions ) ) {
1014 $selectOptions =
array( $selectOptions );
1017 if ( is_array( $srcTable ) ) {
1018 $srcTable = implode(
',', array_map(
array( &$this,
'tableName' ), $srcTable ) );
1020 $srcTable = $this->
tableName( $srcTable );
1023 $sql =
"INSERT INTO $destTable (" . implode(
',', array_keys( $varMap ) ) .
')' .
1024 " SELECT $startOpts " . implode(
',', $varMap ) .
1025 " FROM $srcTable $useIndex";
1027 if ( $conds !=
'*' ) {
1031 $sql .=
" $tailOpts";
1035 $bar = pg_last_error();
1036 if ( $bar !=
false ) {
1037 $savepoint->rollback();
1039 $savepoint->release();
1042 error_reporting( $olde );
1043 $savepoint->commit();
1046 $this->mAffectedRows = $numrowsinserted;
1056 # Replace reserved words with better ones
1079 $safeseq = str_replace(
"'",
"''", $seqName );
1080 $res = $this->
query(
"SELECT nextval('$safeseq')" );
1082 $this->mInsertId = $row[0];
1094 $safeseq = str_replace(
"'",
"''", $seqName );
1095 $res = $this->
query(
"SELECT currval('$safeseq')" );
1102 # Returns the size of a text field, or -1 for "unlimited"
1105 $sql =
"SELECT t.typname as ftype,a.atttypmod as size
1106 FROM pg_class c, pg_attribute a, pg_type t
1107 WHERE relname='$table' AND a.attrelid=c.oid AND
1108 a.atttypid=t.oid and a.attname='$field'";
1111 if ( $row->ftype ==
'varchar' ) {
1112 $size = $row->size - 4;
1121 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " :
'' );
1132 return $this->
query(
'CREATE ' . ( $temporary ?
'TEMPORARY ' :
'' ) .
" TABLE $newName " .
1133 "(LIKE $oldName INCLUDING DEFAULTS)",
$fname );
1138 $result = $this->
query(
"SELECT tablename FROM pg_tables WHERE schemaname = $eschema",
$fname );
1139 $endArray =
array();
1143 $table = array_pop(
$vars );
1144 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1145 $endArray[] = $table;
1175 if (
false ===
$limit ) {
1176 $limit = strlen( $text ) - 1;
1179 if (
'{}' == $text ) {
1183 if (
'{' != $text[$offset] ) {
1184 preg_match(
"/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
1185 $text, $match, 0, $offset );
1186 $offset += strlen( $match[0] );
1187 $output[] = (
'"' != $match[1][0]
1189 : stripcslashes( substr( $match[1], 1, -1 ) ) );
1190 if (
'},' == $match[3] ) {
1196 }
while (
$limit > $offset );
1204 public function aggregateValue( $valuedata, $valuename =
'value' ) {
1212 return '[{{int:version-db-postgres-url}} PostgreSQL]';
1223 $res = $this->
query(
"SELECT current_schema()", __METHOD__ );
1240 $res = $this->
query(
"SELECT current_schemas(false)", __METHOD__ );
1259 $res = $this->
query(
"SHOW search_path", __METHOD__ );
1264 return explode(
",", $row[0] );
1275 $this->
query(
"SET search_path = " . implode(
", ", $search_path ) );
1293 $this->
begin( __METHOD__ );
1295 if ( in_array( $desiredSchema, $this->
getSchemas() ) ) {
1296 $this->mCoreSchema = $desiredSchema;
1297 wfDebug(
"Schema \"" . $desiredSchema .
"\" already in the search path\n" );
1305 array_unshift( $search_path,
1308 $this->mCoreSchema = $desiredSchema;
1309 wfDebug(
"Schema \"" . $desiredSchema .
"\" added to the search path\n" );
1313 wfDebug(
"Schema \"" . $desiredSchema .
"\" not found, using current \"" .
1314 $this->mCoreSchema .
"\"\n" );
1317 $this->
commit( __METHOD__ );
1334 if ( !isset( $this->numericVersion ) ) {
1335 $versionInfo = pg_version( $this->mConn );
1336 if ( version_compare( $versionInfo[
'client'],
'7.4.0',
'lt' ) ) {
1338 $this->numericVersion =
'7.3 or earlier';
1339 } elseif ( isset( $versionInfo[
'server'] ) ) {
1341 $this->numericVersion = $versionInfo[
'server'];
1344 $this->numericVersion = pg_parameter_status( $this->mConn,
'server_version' );
1360 if ( !is_array( $types ) ) {
1361 $types =
array( $types );
1369 $sql =
"SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1370 .
"WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1371 .
"AND c.relkind IN ('" . implode(
"','", $types ) .
"')";
1396 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1397 WHERE relnamespace=pg_namespace.oid AND relkind=
'r'
1398 AND tgrelid=pg_class.oid
1399 AND nspname=%s AND relname=%s AND tgname=%s
1412 $rows =
$res->numRows();
1420 'rulename' => $rule,
1421 'tablename' => $table,
1426 return $exists === $rule;
1430 $sql = sprintf(
"SELECT 1 FROM information_schema.table_constraints " .
1431 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1440 $rows =
$res->numRows();
1451 $exists = $this->
selectField(
'"pg_catalog"."pg_namespace"', 1,
1452 array(
'nspname' => $schema ), __METHOD__ );
1454 return (
bool)$exists;
1464 array(
'rolname' => $roleName ), __METHOD__ );
1466 return (
bool)$exists;
1484 return pg_field_type(
$res, $index );
1492 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
1496 if ( $b instanceof
Blob ) {
1500 return pg_unescape_bytea( $b );
1503 function strencode(
$s ) { # Should not be called by us
1504 return pg_escape_string( $this->mConn,
$s );
1512 if ( is_null(
$s ) ) {
1514 } elseif ( is_bool(
$s ) ) {
1515 return intval(
$s );
1516 } elseif (
$s instanceof
Blob ) {
1517 return "'" .
$s->fetch(
$s ) .
"'";
1520 return "'" . pg_escape_string( $this->mConn,
$s ) .
"'";
1531 $ins = parent::replaceVars( $ins );
1533 if ( $this->numericVersion >= 8.3 ) {
1535 $ins = preg_replace(
"/to_tsvector\s*\(\s*'default'\s*,/",
'to_tsvector(', $ins );
1538 if ( $this->numericVersion <= 8.1 ) {
1539 $ins = str_replace(
'USING gin',
'USING gist', $ins );
1553 $preLimitTail = $postLimitTail =
'';
1554 $startOpts = $useIndex =
'';
1556 $noKeyOptions =
array();
1558 if ( is_numeric( $key ) ) {
1559 $noKeyOptions[$option] =
true;
1573 if ( isset(
$options[
'FOR UPDATE'] ) ) {
1574 $postLimitTail .=
' FOR UPDATE OF ' . implode(
', ',
$options[
'FOR UPDATE'] );
1575 } elseif ( isset( $noKeyOptions[
'FOR UPDATE'] ) ) {
1576 $postLimitTail .=
' FOR UPDATE';
1579 if ( isset( $noKeyOptions[
'DISTINCT'] ) || isset( $noKeyOptions[
'DISTINCTROW'] ) ) {
1580 $startOpts .=
'DISTINCT';
1583 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1595 return implode(
' || ', $stringList );
1603 return '(' . $this->
selectSQLText( $table, $fld, $conds,
null,
array(), $join_conds ) .
')';
1607 return 'SearchPostgres';
1611 # Allow dollar quoting for function declarations
1612 if ( substr( $newLine, 0, 4 ) ==
'$mw$' ) {
1613 if ( $this->delimiter ) {
1614 $this->delimiter =
false;
1616 $this->delimiter =
';';
1620 return parent::streamStatementEnd( $sql, $newLine );
1632 public function lockIsFree( $lockName, $method ) {
1634 $result = $this->
query(
"SELECT (CASE(pg_try_advisory_lock($key))
1635 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1638 return ( $row->lockstatus ===
't' );
1648 public function lock( $lockName, $method, $timeout = 5 ) {
1650 for ( $attempts = 1; $attempts <= $timeout; ++$attempts ) {
1652 "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1654 if ( $row->lockstatus ===
't' ) {
1660 wfDebug( __METHOD__ .
" failed to acquire lock\n" );
1672 public function unlock( $lockName, $method ) {
1674 $result = $this->
query(
"SELECT pg_advisory_unlock($key) as lockstatus", $method );
1677 return ( $row->lockstatus ===
't' );
1685 return wfBaseConvert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
indexUnique( $table, $index, $fname=__METHOD__)
relationExists( $table, $types, $schema=false)
Query whether a given relation exists (in the given schema, or the default mw one if not given)
fieldInfo( $table, $field)
mysql_fetch_field() wrapper Returns false if the field doesn't exist
strictIPs()
Returns true if this database is strict about what can be put into an IP field.
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. $reader:XMLReader object $logInfo:Array of information Return false to stop further processing of the tag 'ImportHandlePageXMLTag':When parsing a XML tag in a page. $reader:XMLReader object $pageInfo:Array of information Return false to stop further processing of the tag 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information Return false to stop further processing of the tag 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. $reader:XMLReader object Return false to stop further processing of the tag 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. $reader:XMLReader object $revisionInfo:Array of information Return false to stop further processing of the tag '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 '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. '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 '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 '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 wfIsTrustedProxy() $ip:IP being check $result:Change this value to override the result of wfIsTrustedProxy() '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 User::isValidEmailAddr(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers '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) '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. '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
insert( $table, $args, $fname=__METHOD__, $options=array())
INSERT wrapper, inserts an array into a table.
insertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=array(), $selectOptions=array())
INSERT SELECT wrapper $varMap must be an associative array of the form array( 'dest1' => 'source1',...
getSchemas()
Return list of schemas which are accessible without schema name This is list does not contain magic k...
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
query( $keyword, $msg_ok, $msg_failed)
affectedRows()
Get the number of rows affected by the last write query.
static fromText( $db, $table, $field)
wasDeadlock()
Determines if the last failure was due to a deadlock STUB.
getCurrentSchema()
Return current schema (executes SELECT current_schema()) Needs transaction.
Base for all database-specific classes representing information about database fields.
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.
reportQueryError( $error, $errno, $sql, $fname, $tempIgnore=false)
Report a query error.
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
currentSequenceValue( $seqName)
Return the current value of a sequence.
makeList( $a, $mode=LIST_COMMA)
Makes an encoded list of strings from an array.
tableName()
Name of table this field belongs to.
close()
Closes a database connection.
query( $sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
aggregateValue( $valuedata, $valuename='value')
Return aggregated value function call.
PostgresTransactionState $mTransactionState
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
buildConcat( $stringList)
Build a concatenation list to feed into a SQL query.
implicitGroupby()
Returns true if this database does an implicit sort when doing GROUP BY.
float string $numericVersion
wfSuppressWarnings( $end=false)
Reference-counted warning suppression.
lock( $lockName, $method, $timeout=5)
See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS.
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
setSearchPath( $search_path)
Update search_path, values should already be sanitized Values may contain magic keywords like "$user"...
makeOrderBy( $options)
Returns an optional ORDER BY.
doQuery( $sql)
The DBMS-dependent part of query()
cascadingDeletes()
Returns true if this database supports (and uses) cascading deletes.
selectSQLText( $table, $vars, $conds='', $fname=__METHOD__, $options=array(), $join_conds=array())
Change the FOR UPDATE option as necessary based on the join conditions.
if(! $in) print Initializing normalization quick check tables n
in this case you re responsible for computing and outputting the entire conflict i e
fieldName( $res, $n)
Get a field name in a result object.
getSearchEngine()
Get search engine class.
unlock( $lockName, $method)
See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKSFROM PG DO...
indexAttributes( $index, $schema=false)
Returns is of attributes used in index.
makeConnectionString( $vars)
isNullable()
Whether this field can store NULL values.
makeSelectOptions( $options)
Various select options.
searchableIPs()
Returns true if this database can do a native search on IP columns e.g.
buildGroupConcatField( $delimiter, $table, $field, $conds='', $options=array(), $join_conds=array())
numFields( $res)
Get the number of fields in a result object.
indexName( $index)
Get the name of an index in a given table.
getServer()
Get the server hostname or IP address.
selectField( $table, $var, $cond='', $fname=__METHOD__, $options=array())
A SELECT wrapper which returns a single field from a single result row.
log_changed( $old, $new, $watched)
selectDB( $db)
Postgres doesn't support selectDB in the same way MySQL does.
resource $mConn
Database connection *.
estimateRowCount( $table, $vars=' *', $conds='', $fname=__METHOD__, $options=array())
Estimate rows in dataset Returns estimated count, based on EXPLAIN output This is not necessarily an ...
textFieldSize( $table, $field)
Returns the size of a text field, or -1 for "unlimited".
select( $table, $vars, $conds='', $fname=__METHOD__, $options=array(), $join_conds=array())
Execute a SELECT query constructed using the various parameters provided.
wfRestoreWarnings()
Restore error level to previous value.
global $wgCommandLineMode
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
open( $server, $user, $password, $dbName)
Usually aborts on failure.
describe_changed( $status, $desc_table)
decodeBlob( $b)
Some DBMSs return a special placeholder object representing blob fields in result objects.
closeConnection()
Closes a database connection, if it is open Returns success, true if already closed.
limitResult( $sql, $limit, $offset=false)
Construct a LIMIT query with optional offset.
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
realTimestamps()
Returns true if this database uses timestamps rather than integers.
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
insertId()
Return the result of the last call to nextSequenceValue(); This must be called after nextSequenceValu...
when a variable name is used in a it is silently declared as a new masking the global
int $mAffectedRows
The number of rows affected as an integer *.
Manage savepoints within a transaction.
getSearchPath()
Return search patch for schemas This is different from getSchemas() since it contain magic keywords (...
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.
Used to debug transaction processing Only used if $wgDebugDBTransactions is true.
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
processing should stop and the error should be shown to the user * false
fetchRow( $res)
Fetch the next row from the given result object, in associative array form.
tableExists( $table, $fname=__METHOD__, $schema=false)
For backward compatibility, this function checks both tables and views.
makeGroupByWithHaving( $options)
Returns an optional GROUP BY with an optional HAVING.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
lockIsFree( $lockName, $method)
Check to see if a named lock is available.
trxLevel()
Gets the current transaction level.
wfDebug( $text, $dest='all')
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Allows to change the fields on the form that will be generated $name
streamStatementEnd(&$sql, &$newLine)
Called by sourceStream() to check if we've reached a statement end.
cleanupTriggers()
Returns true if this database supports (and uses) triggers (e.g.
nextSequenceValue( $seqName)
Return the next in a sequence, save the value for retrieval via insertId()
sequenceExists( $sequence, $schema=false)
indexInfo( $table, $index, $fname=__METHOD__)
Returns information about an index If errors are explicitly ignored, returns NULL on failure.
realTableName( $name, $format='quoted')
pg_array_parse( $text, &$output, $limit=false, $offset=1)
triggerExists( $table, $trigger)
Database abstraction object.
roleExists( $roleName)
Returns true if a given role (i.e.
lastError()
Get a description of the last error.
schemaExists( $schema)
Query whether a given schema exists.
functionalIndexes()
Returns true if this database can use functional indexes.
string $connectString
Connect string to open a PostgreSQL connection *.
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 account $user
fieldType( $res, $index)
pg_field_type() wrapper
commit( $fname=__METHOD__, $flush='')
Commits a transaction previously started using begin().
return false to override stock group addition can be modified try getUserPermissionsErrors userCan checks are continued by internal code can override on output return false to not delete it return false to override the default password checks this Boolean value will be checked to determine if the password was valid return false to implement your own hashing method & $password
rollback( $fname=__METHOD__, $flush='')
Rollback a transaction previously started using begin().
getType()
Get the type of the DBMS, as it appears in $wgDBtype.
addIdentifierQuotes( $s)
Quotes an identifier using backticks or "double quotes" depending on the database type.
implicitOrderby()
Returns true if this database does an implicit order by when the column has an index For example: SEL...
numRows( $res)
Get the number of rows in a result object.
lastErrno()
Get the last error number.
begin( $fname=__METHOD__)
Begin a transaction.
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
wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true, $engine='auto')
Convert an arbitrarily-long digit string from one numeric base to another, optionally zero-padding to...
ruleExists( $table, $rule)
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
bigintFromLockName( $lockName)
getCoreSchema()
Return schema name fore core MediaWiki tables.
getDBname()
Get the current DB name.
const TS_POSTGRES
Postgres format time.
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
Creates a new table with structure copied from existing table Note that unlike most database abstract...
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
usually copyright or history_copyright This message must be in HTML not wikitext $subpages will be ignored and the rest of subPageSubtitle() will run. 'SkinTemplateBuildNavUrlsNav_urlsAfterPermalink' whether MediaWiki currently thinks this is a CSS JS page Hooks may change this value to override the return value of Title::isCssOrJsPage(). 'TitleIsAlwaysKnown' whether MediaWiki currently thinks this page is known isMovable() always returns false. $title whether MediaWiki currently thinks this page is movable Hooks may change this value to override the return value of Title::isMovable(). 'TitleIsWikitextPage' whether MediaWiki currently thinks this is a wikitext page Hooks may change this value to override the return value of Title::isWikitextPage() 'TitleMove' use UploadVerification and UploadVerifyFile instead where the first element is the message key and the remaining elements are used as parameters to the message based on mime etc Preferred in most cases over UploadVerification object with all info about the upload string as detected by MediaWiki Handlers will typically only apply for specific mime types object & $error
strencode( $s)
Wrapper for addslashes()
constraintExists( $table, $constraint)
determineCoreSchema( $desiredSchema)
Determine default schema for MediaWiki core Adjust this session schema search path if desired schema ...
if(!function_exists('version_compare')||version_compare(phpversion(), '5.3.2')< 0)
Result wrapper for grabbing data queried by someone else.
queryIgnore( $sql, $fname=__METHOD__)
DatabaseBase $dbw
Establish a savepoint within a transaction *.