23use Wikimedia\WaitConditionLoop;
66 $sql =
"SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
67 "WHERE c.connamespace = n.oid AND conname = '" .
68 pg_escape_string( $conn,
$name ) .
"' AND n.nspname = '" .
84 function open( $server, $user, $password, $dbName ) {
85 # Test for Postgres support, to avoid suppressed fatal error
86 if ( !function_exists(
'pg_connect' ) ) {
89 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
90 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
91 "webserver and database)\n"
95 $this->mServer = $server;
97 $this->mPassword = $password;
98 $this->mDBname = $dbName;
103 'password' => $password
105 if ( $server !=
false && $server !=
'' ) {
106 $connectVars[
'host'] = $server;
108 if ( (
int)$this->
port > 0 ) {
109 $connectVars[
'port'] = (int)$this->
port;
111 if ( $this->mFlags & self::DBO_SSL ) {
112 $connectVars[
'sslmode'] = 1;
121 $this->mConn = pg_connect( $this->connectString, PGSQL_CONNECT_FORCE_NEW );
122 }
catch ( Exception $ex ) {
129 if ( !$this->mConn ) {
130 $this->queryLogger->debug(
131 "DB connection error\n" .
132 "Server: $server, Database: $dbName, User: $user, Password: " .
133 substr( $password, 0, 3 ) .
"...\n"
135 $this->queryLogger->debug( $this->
lastError() .
"\n" );
139 $this->mOpened =
true;
141 # If called from the command-line (e.g. importDump), only show errors
142 if ( $this->cliMode ) {
143 $this->
doQuery(
"SET client_min_messages = 'ERROR'" );
146 $this->
query(
"SET client_encoding='UTF8'", __METHOD__ );
147 $this->
query(
"SET datestyle = 'ISO, YMD'", __METHOD__ );
148 $this->
query(
"SET timezone = 'GMT'", __METHOD__ );
149 $this->
query(
"SET standard_conforming_strings = on", __METHOD__ );
151 $this->
query(
"SET bytea_output = 'escape'", __METHOD__ );
156 $this->mSchema =
null;
168 if ( $this->mDBname !== $db ) {
169 return (
bool)$this->
open( $this->mServer, $this->mUser, $this->mPassword, $db );
178 $s .=
"$name='" . str_replace(
"'",
"\\'",
$value ) .
"' ";
190 return $this->mConn ? pg_close( $this->mConn ) :
true;
196 $sql = mb_convert_encoding( $sql,
'UTF-8' );
198 while (
$res = pg_get_result( $conn ) ) {
199 pg_free_result(
$res );
201 if ( pg_send_query( $conn, $sql ) ===
false ) {
202 throw new DBUnexpectedError( $this,
"Unable to post new query to PostgreSQL\n" );
204 $this->mLastResult = pg_get_result( $conn );
205 $this->mAffectedRows =
null;
206 if ( pg_result_error( $this->mLastResult ) ) {
217 PGSQL_DIAG_MESSAGE_PRIMARY,
218 PGSQL_DIAG_MESSAGE_DETAIL,
219 PGSQL_DIAG_MESSAGE_HINT,
220 PGSQL_DIAG_STATEMENT_POSITION,
221 PGSQL_DIAG_INTERNAL_POSITION,
222 PGSQL_DIAG_INTERNAL_QUERY,
224 PGSQL_DIAG_SOURCE_FILE,
225 PGSQL_DIAG_SOURCE_LINE,
226 PGSQL_DIAG_SOURCE_FUNCTION
228 foreach ( $diags
as $d ) {
229 $this->queryLogger->debug( sprintf(
"PgSQL ERROR(%d): %s\n",
230 $d, pg_result_error_field( $this->mLastResult, $d ) ) );
237 if ( $errno ===
'23505' ) {
238 parent::reportQueryError( $error, $errno, $sql,
$fname, $tempIgnore );
244 if ( $this->mTrxLevel ) {
249 parent::reportQueryError( $error, $errno, $sql,
$fname,
false );
264 MediaWiki\suppressWarnings();
265 $ok = pg_free_result(
$res );
266 MediaWiki\restoreWarnings();
281 MediaWiki\suppressWarnings();
282 $row = pg_fetch_object(
$res );
283 MediaWiki\restoreWarnings();
284 # @todo FIXME: HACK HACK HACK HACK debug
286 # @todo hashar: not sure if the following test really trigger if the object
289 if ( pg_last_error( $conn ) ) {
292 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
303 MediaWiki\suppressWarnings();
304 $row = pg_fetch_array(
$res );
305 MediaWiki\restoreWarnings();
308 if ( pg_last_error( $conn ) ) {
311 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
322 MediaWiki\suppressWarnings();
323 $n = pg_num_rows(
$res );
324 MediaWiki\restoreWarnings();
327 if ( pg_last_error( $conn ) ) {
330 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
342 return pg_num_fields(
$res );
350 return pg_field_name(
$res, $n );
373 return pg_result_seek(
$res, $row );
377 if ( $this->mConn ) {
378 if ( $this->mLastResult ) {
379 return pg_result_error( $this->mLastResult );
381 return pg_last_error();
389 if ( $this->mLastResult ) {
390 return pg_result_error_field( $this->mLastResult, PGSQL_DIAG_SQLSTATE );
397 if ( !is_null( $this->mAffectedRows ) ) {
401 if ( empty( $this->mLastResult ) ) {
405 return pg_affected_rows( $this->mLastResult );
431 if ( preg_match(
'/rows=(\d+)/', $row[0],
$count ) ) {
449 $sql =
"SELECT indexname FROM pg_indexes WHERE tablename='$table'";
454 foreach (
$res as $row ) {
455 if ( $row->indexname == $this->indexName( $index ) ) {
472 if ( $schema ===
false ) {
479 $sql = <<<__INDEXATTR__
483 i.indoption[s.g]
as option,
486 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
490 ON cis.oid=isub.indexrelid
492 ON cis.relnamespace = ns.oid
493 WHERE cis.relname=
'$index' AND ns.nspname=
'$schema') AS s,
499 ON ci.oid=i.indexrelid
501 ON ct.oid = i.indrelid
503 ON ci.relnamespace = n.oid
505 ci.relname=
'$index' AND n.nspname=
'$schema'
506 AND attrelid = ct.oid
507 AND i.indkey[s.g] = attnum
508 AND i.indclass[s.g] = opcls.oid
509 AND pg_am.oid = opcls.opcmethod
514 foreach (
$res as $row ) {
529 $sql =
"SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
530 " AND indexdef LIKE 'CREATE UNIQUE%(" .
538 return $res->numRows() > 0;
552 $forUpdateKey = array_search(
'FOR UPDATE',
$options,
true );
553 if ( $forUpdateKey !==
false && $join_conds ) {
556 foreach ( $join_conds
as $table_cond => $join_cond ) {
557 if ( 0 === preg_match(
'/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_cond[0] ) ) {
558 $options[
'FOR UPDATE'][] = $table_cond;
584 if ( !count(
$args ) ) {
589 if ( !isset( $this->numericVersion ) ) {
597 if ( isset(
$args[0] ) && is_array(
$args[0] ) ) {
606 $savepoint = $olde =
null;
607 $numrowsinserted = 0;
608 if ( in_array(
'IGNORE',
$options ) ) {
610 $olde = error_reporting( 0 );
615 $sql =
"INSERT INTO $table (" . implode(
',',
$keys ) .
') VALUES ';
618 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
626 $sql .=
'(' . $this->
makeList( $row ) .
')';
634 $tempsql .=
'(' . $this->
makeList( $row ) .
')';
637 $savepoint->savepoint();
640 $tempres = (bool)$this->
query( $tempsql,
$fname, $savepoint );
643 $bar = pg_result_error( $this->mLastResult );
644 if ( $bar !=
false ) {
645 $savepoint->rollback();
647 $savepoint->release();
662 $savepoint->savepoint();
668 $bar = pg_result_error( $this->mLastResult );
669 if ( $bar !=
false ) {
670 $savepoint->rollback();
672 $savepoint->release();
678 error_reporting( $olde );
679 $savepoint->commit();
682 $this->mAffectedRows = $numrowsinserted;
710 $insertOptions = [], $selectOptions = [] ) {
711 $destTable = $this->
tableName( $destTable );
713 if ( !is_array( $insertOptions ) ) {
714 $insertOptions = [ $insertOptions ];
721 $savepoint = $olde =
null;
722 $numrowsinserted = 0;
723 if ( in_array(
'IGNORE', $insertOptions ) ) {
725 $olde = error_reporting( 0 );
726 $savepoint->savepoint();
729 if ( !is_array( $selectOptions ) ) {
730 $selectOptions = [ $selectOptions ];
732 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) =
734 if ( is_array( $srcTable ) ) {
735 $srcTable = implode(
',', array_map( [ $this,
'tableName' ], $srcTable ) );
737 $srcTable = $this->
tableName( $srcTable );
740 $sql =
"INSERT INTO $destTable (" . implode(
',', array_keys( $varMap ) ) .
')' .
741 " SELECT $startOpts " . implode(
',', $varMap ) .
742 " FROM $srcTable $useIndex $ignoreIndex ";
744 if ( $conds !=
'*' ) {
748 $sql .=
" $tailOpts";
752 $bar = pg_result_error( $this->mLastResult );
753 if ( $bar !=
false ) {
754 $savepoint->rollback();
756 $savepoint->release();
759 error_reporting( $olde );
760 $savepoint->commit();
763 $this->mAffectedRows = $numrowsinserted;
776 return parent::tableName(
$name, $format );
785 if (
$name ===
'user' ) {
787 } elseif (
$name ===
'text' ) {
788 return 'pagecontent';
800 return parent::tableName(
$name, $format );
810 $safeseq = str_replace(
"'",
"''", $seqName );
811 $res = $this->
query(
"SELECT nextval('$safeseq')" );
813 $this->mInsertId = $row[0];
825 $safeseq = str_replace(
"'",
"''", $seqName );
826 $res = $this->
query(
"SELECT currval('$safeseq')" );
833 # Returns the size of a text field, or -1 for "unlimited"
836 $sql =
"SELECT t.typname as ftype,a.atttypmod as size
837 FROM pg_class c, pg_attribute a, pg_type t
838 WHERE relname='$table' AND a.attrelid=c.oid AND
839 a.atttypid=t.oid and a.attname='$field'";
842 if ( $row->ftype ==
'varchar' ) {
843 $size = $row->size - 4;
852 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " :
'' );
860 $oldName, $newName, $temporary =
false,
$fname = __METHOD__
865 return $this->
query(
'CREATE ' . ( $temporary ?
'TEMPORARY ' :
'' ) .
" TABLE $newName " .
866 "(LIKE $oldName INCLUDING DEFAULTS)",
$fname );
872 "SELECT tablename FROM pg_tables WHERE schemaname = $eschema",
$fname );
876 $vars = get_object_vars( $table );
877 $table = array_pop(
$vars );
878 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
879 $endArray[] = $table;
912 $limit = strlen( $text ) - 1;
915 if (
'{}' == $text ) {
919 if (
'{' != $text[$offset] ) {
920 preg_match(
"/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
921 $text, $match, 0, $offset );
922 $offset += strlen( $match[0] );
923 $output[] = (
'"' != $match[1][0]
925 : stripcslashes( substr( $match[1], 1, -1 ) ) );
926 if (
'},' == $match[3] ) {
932 }
while (
$limit > $offset );
951 return '[{{int:version-db-postgres-url}} PostgreSQL]';
962 $res = $this->
query(
"SELECT current_schema()", __METHOD__ );
979 $res = $this->
query(
"SELECT current_schemas(false)", __METHOD__ );
998 $res = $this->
query(
"SHOW search_path", __METHOD__ );
1003 return explode(
",", $row[0] );
1014 $this->
query(
"SET search_path = " . implode(
", ", $search_path ) );
1032 $this->
begin( __METHOD__, self::TRANSACTION_INTERNAL );
1034 if ( in_array( $desiredSchema, $this->
getSchemas() ) ) {
1035 $this->mCoreSchema = $desiredSchema;
1036 $this->queryLogger->debug(
1037 "Schema \"" . $desiredSchema .
"\" already in the search path\n" );
1045 array_unshift( $search_path,
1048 $this->mCoreSchema = $desiredSchema;
1049 $this->queryLogger->debug(
1050 "Schema \"" . $desiredSchema .
"\" added to the search path\n" );
1054 $this->queryLogger->debug(
1055 "Schema \"" . $desiredSchema .
"\" not found, using current \"" .
1056 $this->mCoreSchema .
"\"\n" );
1059 $this->
commit( __METHOD__, self::FLUSHING_INTERNAL );
1076 if ( !isset( $this->numericVersion ) ) {
1078 $versionInfo = pg_version( $conn );
1079 if ( version_compare( $versionInfo[
'client'],
'7.4.0',
'lt' ) ) {
1081 $this->numericVersion =
'7.3 or earlier';
1082 } elseif ( isset( $versionInfo[
'server'] ) ) {
1084 $this->numericVersion = $versionInfo[
'server'];
1087 $this->numericVersion = pg_parameter_status( $conn,
'server_version' );
1103 if ( !is_array( $types ) ) {
1104 $types = [ $types ];
1106 if ( $schema ===
false ) {
1112 $sql =
"SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1113 .
"WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1114 .
"AND c.relkind IN ('" . implode(
"','", $types ) .
"')";
1139 SELECT 1
FROM pg_class, pg_namespace, pg_trigger
1140 WHERE relnamespace=pg_namespace.oid AND relkind=
'r'
1141 AND tgrelid=pg_class.oid
1142 AND nspname=%s AND relname=%s AND tgname=%s
1155 $rows =
$res->numRows();
1161 $exists = $this->
selectField(
'pg_rules',
'rulename',
1163 'rulename' => $rule,
1164 'tablename' => $table,
1169 return $exists === $rule;
1173 $sql = sprintf(
"SELECT 1 FROM information_schema.table_constraints " .
1174 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1183 $rows =
$res->numRows();
1194 $exists = $this->
selectField(
'"pg_catalog"."pg_namespace"', 1,
1195 [
'nspname' => $schema ], __METHOD__ );
1197 return (
bool)$exists;
1206 $exists = $this->
selectField(
'"pg_catalog"."pg_roles"', 1,
1207 [
'rolname' => $roleName ], __METHOD__ );
1209 return (
bool)$exists;
1232 return pg_field_type(
$res, $index );
1246 } elseif ( $b instanceof
Blob ) {
1250 return pg_unescape_bytea( $b );
1265 if ( is_null(
$s ) ) {
1267 } elseif ( is_bool(
$s ) ) {
1268 return intval(
$s );
1269 } elseif (
$s instanceof
Blob ) {
1273 $s = pg_escape_bytea( $conn,
$s->fetch() );
1278 return "'" . pg_escape_string( $conn,
$s ) .
"'";
1289 $ins = parent::replaceVars( $ins );
1291 if ( $this->numericVersion >= 8.3 ) {
1293 $ins = preg_replace(
"/to_tsvector\s*\(\s*'default'\s*,/",
'to_tsvector(', $ins );
1296 if ( $this->numericVersion <= 8.1 ) {
1297 $ins = str_replace(
'USING gin',
'USING gist', $ins );
1311 $preLimitTail = $postLimitTail =
'';
1312 $startOpts = $useIndex = $ignoreIndex =
'';
1316 if ( is_numeric( $key ) ) {
1317 $noKeyOptions[$option] =
true;
1331 if ( isset(
$options[
'FOR UPDATE'] ) ) {
1332 $postLimitTail .=
' FOR UPDATE OF ' .
1333 implode(
', ', array_map( [ $this,
'tableName' ],
$options[
'FOR UPDATE'] ) );
1334 } elseif ( isset( $noKeyOptions[
'FOR UPDATE'] ) ) {
1335 $postLimitTail .=
' FOR UPDATE';
1338 if ( isset( $noKeyOptions[
'DISTINCT'] ) || isset( $noKeyOptions[
'DISTINCTROW'] ) ) {
1339 $startOpts .=
'DISTINCT';
1342 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1354 return implode(
' || ', $stringList );
1362 return '(' . $this->
selectSQLText( $table, $fld, $conds,
null, [], $join_conds ) .
')';
1371 return $field .
'::text';
1375 # Allow dollar quoting for function declarations
1376 if ( substr( $newLine, 0, 4 ) ==
'$mw$' ) {
1377 if ( $this->delimiter ) {
1378 $this->delimiter =
false;
1380 $this->delimiter =
';';
1384 return parent::streamStatementEnd( $sql, $newLine );
1398 $result = $this->
query(
"SELECT (CASE(pg_try_advisory_lock($key))
1399 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1402 return ( $row->lockstatus ===
't' );
1412 public function lock( $lockName, $method, $timeout = 5 ) {
1414 $loop =
new WaitConditionLoop(
1415 function ()
use ( $lockName, $key, $timeout, $method ) {
1416 $res = $this->
query(
"SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1418 if ( $row->lockstatus ===
't' ) {
1419 parent::lock( $lockName, $method, $timeout );
1423 return WaitConditionLoop::CONDITION_CONTINUE;
1428 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1438 public function unlock( $lockName, $method ) {
1440 $result = $this->
query(
"SELECT pg_advisory_unlock($key) as lockstatus", $method );
1443 if ( $row->lockstatus ===
't' ) {
1444 parent::unlock( $lockName, $method );
1448 $this->queryLogger->debug( __METHOD__ .
" failed to release lock\n" );
1458 return Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
Library for creating, parsing, and converting timestamps.
bigintFromLockName( $lockName)
string $connectString
Connect string to open a PostgreSQL connection.
affectedRows()
Get the number of rows affected by the last write query.
getCoreSchema()
Return schema name for core application tables.
triggerExists( $table, $trigger)
replaceVars( $ins)
Postgres specific version of replaceVars.
reportQueryError( $error, $errno, $sql, $fname, $tempIgnore=false)
Report a query error.
implicitGroupby()
Returns true if this database does an implicit sort when doing GROUP BY.
getType()
Get the type of the DBMS, as it appears in $wgDBtype.
unlock( $lockName, $method)
See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKSFROM PG DO...
wasDeadlock()
Determines if the last failure was due to a deadlock.
fieldName( $res, $n)
Get a field name in a result object.
getDBname()
Get the current DB name.
lastError()
Get a description of the last error.
nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[])
INSERT SELECT wrapper $varMap must be an associative array of the form [ 'dest1' => 'source1',...
selectSQLText( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
The equivalent of IDatabase::select() except that the constructed SQL is returned,...
makeSelectOptions( $options)
Various select options.
limitResult( $sql, $limit, $offset=false)
Construct a LIMIT query with optional offset.
textFieldSize( $table, $field)
Returns the size of a text field, or -1 for "unlimited".
makeConnectionString( $vars)
constraintExists( $table, $constraint)
fieldInfo( $table, $field)
mysql_fetch_field() wrapper Returns false if the field doesn't exist
getCurrentSchema()
Return current schema (executes SELECT current_schema()) Needs transaction.
selectDB( $db)
Postgres doesn't support selectDB in the same way MySQL does.
schemaExists( $schema)
Query whether a given schema exists.
buildGroupConcatField( $delimiter, $table, $field, $conds='', $options=[], $join_conds=[])
currentSequenceValue( $seqName)
Return the current value of a sequence.
fieldType( $res, $index)
pg_field_type() wrapper
lastErrno()
Get the last error number.
__construct(array $params)
Constructor and database handle and attempt to connect to the DB server.
realTableName( $name, $format='quoted')
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
getServer()
Get the server hostname or IP address.
roleExists( $roleName)
Returns true if a given role (i.e.
indexUnique( $table, $index, $fname=__METHOD__)
implicitOrderby()
Returns true if this database does an implicit order by when the column has an index For example: SEL...
indexInfo( $table, $index, $fname=__METHOD__)
Returns information about an index If errors are explicitly ignored, returns NULL on failure.
determineCoreSchema( $desiredSchema)
Determine default schema for the current application Adjust this session schema search path if desire...
numRows( $res)
Get the number of rows in a result object.
float string $numericVersion
indexAttributes( $index, $schema=false)
Returns is of attributes used in index.
fetchRow( $res)
Fetch the next row from the given result object, in associative array form.
insert( $table, $args, $fname=__METHOD__, $options=[])
INSERT wrapper, inserts an array into a table.
buildConcat( $stringList)
Build a concatenation list to feed into a SQL query.
streamStatementEnd(&$sql, &$newLine)
Called by sourceStream() to check if we've reached a statement end.
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.
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....
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
estimateRowCount( $table, $vars=' *', $conds='', $fname=__METHOD__, $options=[])
Estimate rows in dataset Returns estimated count, based on EXPLAIN output This is not necessarily an ...
numFields( $res)
Get the number of fields in a result object.
queryIgnore( $sql, $fname=__METHOD__)
getSchemas()
Return list of schemas which are accessible without schema name This is list does not contain magic k...
open( $server, $user, $password, $dbName)
Usually aborts on failure.
aggregateValue( $valuedata, $valuename='value')
Return aggregated value function call.
insertId()
Return the result of the last call to nextSequenceValue(); This must be called after nextSequenceValu...
strencode( $s)
Wrapper for addslashes()
nextSequenceValue( $seqName)
Return the next in a sequence, save the value for retrieval via insertId()
closeConnection()
Closes a database connection, if it is open Returns success, true if already closed.
relationExists( $table, $types, $schema=false)
Query whether a given relation exists (in the given schema, or the default mw one if not given)
setSearchPath( $search_path)
Update search_path, values should already be sanitized Values may contain magic keywords like "$user"...
lock( $lockName, $method, $timeout=5)
See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS.
doQuery( $sql)
The DBMS-dependent part of query()
int $mAffectedRows
The number of rows affected as an integer.
tableExists( $table, $fname=__METHOD__, $schema=false)
For backward compatibility, this function checks both tables and views.
lockIsFree( $lockName, $method)
Check to see if a named lock is available.
decodeBlob( $b)
Some DBMSs return a special placeholder object representing blob fields in result objects.
remappedTableName( $name)
getSearchPath()
Return search patch for schemas This is different from getSchemas() since it contain magic keywords (...
ruleExists( $table, $rule)
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
Creates a new table with structure copied from existing table Note that unlike most database abstract...
sequenceExists( $sequence, $schema=false)
Relational database abstraction object.
makeList( $a, $mode=self::LIST_COMMA)
Makes an encoded list of strings from an array.
close()
Closes a database connection.
resource null $mConn
Database connection.
indexName( $index)
Get the name of an index in a given table.
addIdentifierQuotes( $s)
Quotes an identifier using backticks or "double quotes" depending on the database type.
ignoreErrors( $ignoreErrors=null)
Turns on (false) or off (true) the automatic generation and sending of a "we're sorry,...
makeGroupByWithHaving( $options)
Returns an optional GROUP BY with an optional HAVING.
makeOrderBy( $options)
Returns an optional ORDER BY.
getBindingHandle()
Get the underlying binding handle, mConn.
selectField( $table, $var, $cond='', $fname=__METHOD__, $options=[])
A SELECT wrapper which returns a single field from a single result row.
commit( $fname=__METHOD__, $flush='')
Commits a transaction previously started using begin().
query( $sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
begin( $fname=__METHOD__, $mode=self::TRANSACTION_EXPLICIT)
Begin a transaction.
static fromText(DatabasePostgres $db, $table, $field)
Result wrapper for grabbing data queried from an IDatabase object.
Manage savepoints within a transaction.
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 select() and insert() are usually more convenient. They take care of things like table prefixes and escaping for you. If you really need to make your own SQL
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
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
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
the array() calling protocol came about after MediaWiki 1.4rc1.
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
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
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
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
presenting them properly to the user as errors is done by the caller return true use this to change the list i e rollback
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
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
Allows to change the fields on the form that will be generated $name
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
storage can be distributed across multiple and multiple web servers can use the same cache cluster *********************W A R N I N G ***********************Memcached has no security or authentication Please ensure that your server is appropriately and that the port(s) used for memcached servers are not publicly accessible. Otherwise
const TS_POSTGRES
Postgres format time.