25use Wikimedia\Timestamp\ConvertibleTimestamp;
26use Wikimedia\WaitConditionLoop;
58 $this->keywordTableMap = isset(
$params[
'keywordTableMap'] )
80 $sql =
"SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
81 "WHERE c.connamespace = n.oid AND conname = '" .
82 pg_escape_string( $conn, $name ) .
"' AND n.nspname = '" .
89 public function open( $server, $user, $password, $dbName ) {
90 # Test for Postgres support, to avoid suppressed fatal error
91 if ( !function_exists(
'pg_connect' ) ) {
94 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
95 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
96 "webserver and database)\n"
100 $this->mServer = $server;
101 $this->mUser =
$user;
102 $this->mPassword = $password;
103 $this->mDBname = $dbName;
109 'dbname' => strlen( $dbName ) ? $dbName :
'postgres',
111 'password' => $password
113 if ( $server !=
false && $server !=
'' ) {
114 $connectVars[
'host'] = $server;
116 if ( (
int)$this->port > 0 ) {
117 $connectVars[
'port'] = (int)$this->port;
119 if ( $this->mFlags & self::DBO_SSL ) {
120 $connectVars[
'sslmode'] = 1;
129 $this->mConn = pg_connect( $this->connectString, PGSQL_CONNECT_FORCE_NEW );
130 }
catch ( Exception $ex ) {
137 if ( !$this->mConn ) {
138 $this->queryLogger->debug(
139 "DB connection error\n" .
140 "Server: $server, Database: $dbName, User: $user, Password: " .
141 substr( $password, 0, 3 ) .
"...\n"
143 $this->queryLogger->debug( $this->
lastError() .
"\n" );
147 $this->mOpened =
true;
149 # If called from the command-line (e.g. importDump), only show errors
150 if ( $this->cliMode ) {
151 $this->
doQuery(
"SET client_min_messages = 'ERROR'" );
154 $this->
query(
"SET client_encoding='UTF8'", __METHOD__ );
155 $this->
query(
"SET datestyle = 'ISO, YMD'", __METHOD__ );
156 $this->
query(
"SET timezone = 'GMT'", __METHOD__ );
157 $this->
query(
"SET standard_conforming_strings = on", __METHOD__ );
159 $this->
query(
"SET bytea_output = 'escape'", __METHOD__ );
181 if ( $this->mDBname !== $db ) {
182 return (
bool)$this->
open( $this->mServer, $this->mUser, $this->mPassword, $db );
195 $s .=
"$name='" . str_replace(
"'",
"\\'",
$value ) .
"' ";
202 return $this->mConn ? pg_close( $this->mConn ) :
true;
208 $sql = mb_convert_encoding( $sql,
'UTF-8' );
210 while (
$res = pg_get_result( $conn ) ) {
211 pg_free_result(
$res );
213 if ( pg_send_query( $conn, $sql ) ===
false ) {
214 throw new DBUnexpectedError( $this,
"Unable to post new query to PostgreSQL\n" );
216 $this->mLastResult = pg_get_result( $conn );
217 $this->mAffectedRows =
null;
218 if ( pg_result_error( $this->mLastResult ) ) {
229 PGSQL_DIAG_MESSAGE_PRIMARY,
230 PGSQL_DIAG_MESSAGE_DETAIL,
231 PGSQL_DIAG_MESSAGE_HINT,
232 PGSQL_DIAG_STATEMENT_POSITION,
233 PGSQL_DIAG_INTERNAL_POSITION,
234 PGSQL_DIAG_INTERNAL_QUERY,
236 PGSQL_DIAG_SOURCE_FILE,
237 PGSQL_DIAG_SOURCE_LINE,
238 PGSQL_DIAG_SOURCE_FUNCTION
240 foreach ( $diags as $d ) {
241 $this->queryLogger->debug( sprintf(
"PgSQL ERROR(%d): %s\n",
242 $d, pg_result_error_field( $this->mLastResult, $d ) ) );
249 if ( $errno ===
'23505' ) {
250 parent::reportQueryError( $error, $errno, $sql,
$fname, $tempIgnore );
256 if ( $this->mTrxLevel ) {
260 $this->
rollback( __METHOD__, self::FLUSHING_INTERNAL );
262 parent::reportQueryError( $error, $errno, $sql,
$fname,
false );
269 MediaWiki\suppressWarnings();
270 $ok = pg_free_result(
$res );
271 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 );
354 $res = $this->
query(
"SELECT lastval()" );
356 return is_null( $row[0] ) ? null : (int)$row[0];
364 return pg_result_seek(
$res, $row );
368 if ( $this->mConn ) {
369 if ( $this->mLastResult ) {
370 return pg_result_error( $this->mLastResult );
372 return pg_last_error();
380 if ( $this->mLastResult ) {
381 return pg_result_error_field( $this->mLastResult, PGSQL_DIAG_SQLSTATE );
388 if ( !is_null( $this->mAffectedRows ) ) {
392 if ( empty( $this->mLastResult ) ) {
396 return pg_affected_rows( $this->mLastResult );
422 if ( preg_match(
'/rows=(\d+)/', $row[0], $count ) ) {
423 $rows = (int)$count[1];
431 $sql =
"SELECT indexname FROM pg_indexes WHERE tablename='$table'";
436 foreach (
$res as $row ) {
437 if ( $row->indexname == $this->indexName( $index ) ) {
446 if ( $schema ===
false ) {
453 $sql = <<<__INDEXATTR__
457 i.indoption[s.g] as option,
460 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
464 ON cis.oid=isub.indexrelid
466 ON cis.relnamespace = ns.oid
467 WHERE cis.relname=
'$index' AND ns.nspname=
'$schema') AS s,
473 ON ci.oid=i.indexrelid
475 ON ct.oid = i.indrelid
477 ON ci.relnamespace = n.oid
479 ci.relname=
'$index' AND n.nspname=
'$schema'
480 AND attrelid = ct.oid
481 AND i.indkey[s.g] = attnum
482 AND i.indclass[s.g] = opcls.oid
483 AND pg_am.oid = opcls.opcmethod
488 foreach (
$res as $row ) {
503 $sql =
"SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
504 " AND indexdef LIKE 'CREATE UNIQUE%(" .
512 return $res->numRows() > 0;
530 $forUpdateKey = array_search(
'FOR UPDATE',
$options,
true );
531 if ( $forUpdateKey !==
false && $join_conds ) {
536 foreach ( $table as $alias => $name ) {
537 if ( is_numeric( $alias ) ) {
540 if ( !isset( $join_conds[$alias] ) ) {
545 foreach ( $join_conds as $table_cond => $join_cond ) {
546 if ( 0 === preg_match(
'/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_cond[0] ) ) {
547 $options[
'FOR UPDATE'][] = $table_cond;
552 $options[
'FOR UPDATE'] = array_map(
function ( $name ) use ( $table ) {
578 if ( !count(
$args ) ) {
583 if ( !isset( $this->numericVersion ) ) {
591 if ( isset(
$args[0] ) && is_array(
$args[0] ) ) {
600 $savepoint = $olde =
null;
601 $numrowsinserted = 0;
602 if ( in_array(
'IGNORE',
$options ) ) {
604 $olde = error_reporting( 0 );
609 $sql =
"INSERT INTO $table (" . implode(
',',
$keys ) .
') VALUES ';
612 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
614 foreach (
$args as $row ) {
620 $sql .=
'(' . $this->
makeList( $row ) .
')';
626 foreach (
$args as $row ) {
628 $tempsql .=
'(' . $this->
makeList( $row ) .
')';
631 $savepoint->savepoint();
634 $tempres = (bool)$this->
query( $tempsql,
$fname, $savepoint );
637 $bar = pg_result_error( $this->mLastResult );
638 if ( $bar !=
false ) {
639 $savepoint->rollback();
641 $savepoint->release();
656 $savepoint->savepoint();
662 $bar = pg_result_error( $this->mLastResult );
663 if ( $bar !=
false ) {
664 $savepoint->rollback();
666 $savepoint->release();
672 error_reporting( $olde );
673 $savepoint->commit();
676 $this->mAffectedRows = $numrowsinserted;
705 $destTable, $srcTable, $varMap, $conds,
$fname = __METHOD__,
706 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
708 if ( !is_array( $insertOptions ) ) {
709 $insertOptions = [ $insertOptions ];
716 $savepoint = $olde =
null;
717 $numrowsinserted = 0;
718 if ( in_array(
'IGNORE', $insertOptions ) ) {
720 $olde = error_reporting( 0 );
721 $savepoint->savepoint();
724 $res = parent::nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
$fname,
725 $insertOptions, $selectOptions, $selectJoinConds );
728 $bar = pg_result_error( $this->mLastResult );
729 if ( $bar !=
false ) {
730 $savepoint->rollback();
732 $savepoint->release();
735 error_reporting( $olde );
736 $savepoint->commit();
739 $this->mAffectedRows = $numrowsinserted;
748 public function tableName( $name, $format =
'quoted' ) {
752 return parent::tableName( $name, $format );
760 return isset( $this->keywordTableMap[$name] ) ? $this->keywordTableMap[
$name] :
$name;
769 return parent::tableName( $name, $format );
783 $safeseq = str_replace(
"'",
"''", $seqName );
784 $res = $this->
query(
"SELECT currval('$safeseq')" );
793 $sql =
"SELECT t.typname as ftype,a.atttypmod as size
794 FROM pg_class c, pg_attribute a, pg_type t
795 WHERE relname='$table' AND a.attrelid=c.oid AND
796 a.atttypid=t.oid and a.attname='$field'";
799 if ( $row->ftype ==
'varchar' ) {
800 $size = $row->size - 4;
809 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " :
'' );
817 $oldName, $newName, $temporary =
false,
$fname = __METHOD__
822 return $this->
query(
'CREATE ' . ( $temporary ?
'TEMPORARY ' :
'' ) .
" TABLE $newName " .
823 "(LIKE $oldName INCLUDING DEFAULTS INCLUDING INDEXES)",
$fname );
828 $result = $this->
query(
829 "SELECT tablename FROM pg_tables WHERE schemaname = $eschema",
$fname );
832 foreach ( $result as $table ) {
833 $vars = get_object_vars( $table );
834 $table = array_pop(
$vars );
835 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
836 $endArray[] = $table;
844 $ct =
new ConvertibleTimestamp( $ts );
846 return $ct->getTimestamp( TS_POSTGRES );
868 if (
false === $limit ) {
869 $limit = strlen( $text ) - 1;
872 if (
'{}' == $text ) {
876 if (
'{' != $text[$offset] ) {
877 preg_match(
"/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
878 $text, $match, 0, $offset );
879 $offset += strlen( $match[0] );
880 $output[] = (
'"' != $match[1][0]
882 : stripcslashes( substr( $match[1], 1, -1 ) ) );
883 if (
'},' == $match[3] ) {
889 }
while ( $limit > $offset );
899 return '[{{int:version-db-postgres-url}} PostgreSQL]';
910 $res = $this->
query(
"SELECT current_schema()", __METHOD__ );
927 $res = $this->
query(
"SELECT current_schemas(false)", __METHOD__ );
946 $res = $this->
query(
"SHOW search_path", __METHOD__ );
951 return explode(
",", $row[0] );
962 $this->
query(
"SET search_path = " . implode(
", ", $search_path ) );
980 $this->
begin( __METHOD__, self::TRANSACTION_INTERNAL );
982 if ( in_array( $desiredSchema, $this->
getSchemas() ) ) {
983 $this->mCoreSchema = $desiredSchema;
984 $this->queryLogger->debug(
985 "Schema \"" . $desiredSchema .
"\" already in the search path\n" );
993 array_unshift( $search_path,
996 $this->mCoreSchema = $desiredSchema;
997 $this->queryLogger->debug(
998 "Schema \"" . $desiredSchema .
"\" added to the search path\n" );
1002 $this->queryLogger->debug(
1003 "Schema \"" . $desiredSchema .
"\" not found, using current \"" .
1004 $this->mCoreSchema .
"\"\n" );
1007 $this->
commit( __METHOD__, self::FLUSHING_INTERNAL );
1021 if ( !isset( $this->numericVersion ) ) {
1023 $versionInfo = pg_version( $conn );
1024 if ( version_compare( $versionInfo[
'client'],
'7.4.0',
'lt' ) ) {
1026 $this->numericVersion =
'7.3 or earlier';
1027 } elseif ( isset( $versionInfo[
'server'] ) ) {
1029 $this->numericVersion = $versionInfo[
'server'];
1032 $this->numericVersion = pg_parameter_status( $conn,
'server_version' );
1048 if ( !is_array( $types ) ) {
1049 $types = [ $types ];
1051 if ( $schema ===
false ) {
1057 $sql =
"SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1058 .
"WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1059 .
"AND c.relkind IN ('" . implode(
"','", $types ) .
"')";
1061 $count =
$res ?
$res->numRows() : 0;
1063 return (
bool)$count;
1083 SELECT 1
FROM pg_class, pg_namespace, pg_trigger
1084 WHERE relnamespace=pg_namespace.oid AND relkind=
'r'
1085 AND tgrelid=pg_class.oid
1086 AND nspname=%s AND relname=%s AND tgname=%s
1105 $exists = $this->
selectField(
'pg_rules',
'rulename',
1107 'rulename' => $rule,
1108 'tablename' => $table,
1113 return $exists === $rule;
1117 $sql = sprintf(
"SELECT 1 FROM information_schema.table_constraints " .
1118 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1138 if ( !strlen( $schema ) ) {
1143 '"pg_catalog"."pg_namespace"', 1, [
'nspname' => $schema ], __METHOD__ );
1145 return (
bool)$exists;
1154 $exists = $this->
selectField(
'"pg_catalog"."pg_roles"', 1,
1155 [
'rolname' => $roleName ], __METHOD__ );
1157 return (
bool)$exists;
1180 return pg_field_type(
$res, $index );
1190 } elseif ( $b instanceof
Blob ) {
1194 return pg_unescape_bytea( $b );
1205 if ( is_null(
$s ) ) {
1207 } elseif ( is_bool(
$s ) ) {
1208 return intval(
$s );
1209 } elseif (
$s instanceof
Blob ) {
1213 $s = pg_escape_bytea( $conn,
$s->fetch() );
1220 return "'" . pg_escape_string( $conn, (
string)
$s ) .
"'";
1231 $ins = parent::replaceVars( $ins );
1233 if ( $this->numericVersion >= 8.3 ) {
1235 $ins = preg_replace(
"/to_tsvector\s*\(\s*'default'\s*,/",
'to_tsvector(', $ins );
1238 if ( $this->numericVersion <= 8.1 ) {
1239 $ins = str_replace(
'USING gin',
'USING gist', $ins );
1246 $preLimitTail = $postLimitTail =
'';
1247 $startOpts = $useIndex = $ignoreIndex =
'';
1250 foreach (
$options as $key => $option ) {
1251 if ( is_numeric( $key ) ) {
1252 $noKeyOptions[$option] =
true;
1260 if ( isset(
$options[
'FOR UPDATE'] ) ) {
1261 $postLimitTail .=
' FOR UPDATE OF ' .
1262 implode(
', ', array_map( [ $this,
'tableName' ],
$options[
'FOR UPDATE'] ) );
1263 } elseif ( isset( $noKeyOptions[
'FOR UPDATE'] ) ) {
1264 $postLimitTail .=
' FOR UPDATE';
1267 if ( isset( $noKeyOptions[
'DISTINCT'] ) || isset( $noKeyOptions[
'DISTINCTROW'] ) ) {
1268 $startOpts .=
'DISTINCT';
1271 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1283 return implode(
' || ', $stringList );
1291 return '(' . $this->
selectSQLText( $table, $fld, $conds,
null, [], $join_conds ) .
')';
1295 return $field .
'::text';
1299 # Allow dollar quoting for function declarations
1300 if ( substr( $newLine, 0, 4 ) ==
'$mw$' ) {
1301 if ( $this->delimiter ) {
1302 $this->delimiter =
false;
1304 $this->delimiter =
';';
1308 return parent::streamStatementEnd( $sql, $newLine );
1313 foreach ( $write as $table ) {
1314 $tablesWrite[] = $this->
tableName( $table );
1317 foreach ( $read as $table ) {
1318 $tablesRead[] = $this->
tableName( $table );
1322 if ( $tablesWrite ) {
1324 'LOCK TABLE ONLY ' . implode(
',', $tablesWrite ) .
' IN EXCLUSIVE MODE',
1328 if ( $tablesRead ) {
1330 'LOCK TABLE ONLY ' . implode(
',', $tablesRead ) .
' IN SHARE MODE',
1341 $result = $this->
query(
"SELECT (CASE(pg_try_advisory_lock($key))
1342 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1345 return ( $row->lockstatus ===
't' );
1348 public function lock( $lockName, $method, $timeout = 5 ) {
1351 $loop =
new WaitConditionLoop(
1352 function () use ( $lockName, $key, $timeout, $method ) {
1353 $res = $this->
query(
"SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1355 if ( $row->lockstatus ===
't' ) {
1356 parent::lock( $lockName, $method, $timeout );
1360 return WaitConditionLoop::CONDITION_CONTINUE;
1365 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1368 public function unlock( $lockName, $method ) {
1371 $result = $this->
query(
"SELECT pg_advisory_unlock($key) as lockstatus", $method );
1374 if ( $row->lockstatus ===
't' ) {
1375 parent::unlock( $lockName, $method );
1379 $this->queryLogger->debug( __METHOD__ .
" failed to release lock\n" );
1385 $res = $this->
query(
"SHOW default_transaction_read_only", __METHOD__ );
1388 return $row ? ( strtolower( $row->default_transaction_read_only ) ===
'on' ) :
false;
1396 return \Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1400class_alias( DatabasePostgres::class,
'DatabasePostgres' );
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to and or sell copies of the and to permit persons to whom the Software is furnished to do subject to the following WITHOUT WARRANTY OF ANY EXPRESS OR INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY DAMAGES OR OTHER WHETHER IN AN ACTION OF TORT OR ARISING FROM
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
buildConcat( $stringList)
Build a concatenation list to feed into a SQL query.
numFields( $res)
Get the number of fields in a result object.
determineCoreSchema( $desiredSchema)
Determine default schema for the current application Adjust this session schema search path if desire...
lock( $lockName, $method, $timeout=5)
Acquire a named lock.
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
Creates a new table with structure copied from existing table.
numRows( $res)
Get the number of rows in a result object.
fieldInfo( $table, $field)
fetchRow( $res)
Fetch the next row from the given result object, in associative array form.
doQuery( $sql)
The DBMS-dependent part of query()
insertId()
Get the inserted value of an auto-increment row.
freeResult( $res)
Free a result object returned by query() or select().
dataSeek( $res, $row)
Change the position of the cursor in a result object.
indexAttributes( $index, $schema=false)
databasesAreIndependent()
Returns true if DBs are assumed to be on potentially different servers.
setSearchPath( $search_path)
Update search_path, values should already be sanitized Values may contain magic keywords like "$user"...
fetchObject( $res)
Fetch the next row from the given result object, in object form.
pg_array_parse( $text, &$output, $limit=false, $offset=1)
Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12 to https://secure.php.net/manual/en/ref....
streamStatementEnd(&$sql, &$newLine)
Called by sourceStream() to check if we've reached a statement end.
implicitOrderby()
Returns true if this database does an implicit order by when the column has an index For example: SEL...
nextSequenceValue( $seqName)
Deprecated method, calls should be removed.
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
roleExists( $roleName)
Returns true if a given role (i.e.
selectSQLText( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
The equivalent of IDatabase::select() except that the constructed SQL is returned,...
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...
indexInfo( $table, $index, $fname=__METHOD__)
Get information about an index into an object.
schemaExists( $schema)
Query whether a given schema exists.
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
lastError()
Get a description of the last error.
addQuotes( $s)
Adds quotes and backslashes.
limitResult( $sql, $limit, $offset=false)
Construct a LIMIT query with optional offset.
unlock( $lockName, $method)
Release a lock.
open( $server, $user, $password, $dbName)
Open a connection to the database.
sequenceExists( $sequence, $schema=false)
string[] $keywordTableMap
Map of (reserved table name => alternate table name)
nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=[], $selectOptions=[], $selectJoinConds=[])
INSERT SELECT wrapper $varMap must be an associative array of the form [ 'dest1' => 'source1',...
insert( $table, $args, $fname=__METHOD__, $options=[])
INSERT wrapper, inserts an array into a table.
wasDeadlock()
Determines if the last failure was due to a deadlock.
lockIsFree( $lockName, $method)
Check to see if a named lock is available (non-blocking)
__construct(array $params)
currentSequenceValue( $seqName)
Return the current value of a sequence.
string $connectString
Connect string to open a PostgreSQL connection.
lastErrno()
Get the last error number.
affectedRows()
Get the number of rows affected by the last write query.
getCoreSchema()
Return schema name for core application tables.
strencode( $s)
Wrapper for addslashes()
int $mAffectedRows
The number of rows affected as an integer.
replaceVars( $ins)
Postgres specific version of replaceVars.
reportQueryError( $error, $errno, $sql, $fname, $tempIgnore=false)
Report a query error.
triggerExists( $table, $trigger)
indexUnique( $table, $index, $fname=__METHOD__)
fieldName( $res, $n)
Get a field name in a result object.
estimateRowCount( $table, $vars=' *', $conds='', $fname=__METHOD__, $options=[])
Estimate rows in dataset Returns estimated count, based on EXPLAIN output This is not necessarily an ...
float string $numericVersion
getServerVersion()
A string describing the current software version, like from mysql_get_server_info().
fieldType( $res, $index)
pg_field_type() wrapper
doLockTables(array $read, array $write, $method)
Helper function for lockTables() that handles the actual table locking.
textFieldSize( $table, $field)
Returns the size of a text field, or -1 for "unlimited".
makeConnectionString( $vars)
getCurrentSchema()
Return current schema (executes SELECT current_schema()) Needs transaction.
getSearchPath()
Return search patch for schemas This is different from getSchemas() since it contain magic keywords (...
bigintFromLockName( $lockName)
tableExists( $table, $fname=__METHOD__, $schema=false)
For backward compatibility, this function checks both tables and views.
selectDB( $db)
Postgres doesn't support selectDB in the same way MySQL does.
ruleExists( $table, $rule)
remappedTableName( $name)
decodeBlob( $b)
Some DBMSs return a special placeholder object representing blob fields in result objects.
relationExists( $table, $types, $schema=false)
Query whether a given relation exists (in the given schema, or the default mw one if not given)
encodeBlob( $b)
Some DBMSs have a special format for inserting into blob fields, they don't allow simple quoted strin...
realTableName( $name, $format='quoted')
closeConnection()
Closes underlying database connection.
getServer()
Get the server hostname or IP address.
constraintExists( $table, $constraint)
getType()
Get the type of the DBMS, as it appears in $wgDBtype.
makeSelectOptions( $options)
Returns an optional USE INDEX clause to go after the table, and a string to go at the end of the quer...
implicitGroupby()
Returns true if this database does an implicit sort when doing GROUP BY.
getDBname()
Get the current DB name.
getSoftwareLink()
Returns a wikitext link to the DB's website, e.g., return "[https://www.mysql.com/ MySQL]"; Should at...
aggregateValue( $valuedata, $valuename='value')
Return aggregated value alias.
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.
static fromText(DatabasePostgres $db, $table, $field)
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
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place $output
presenting them properly to the user as errors is done by the caller return true use this to change the list i e rollback
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
Allows to change the fields on the form that will be generated $name
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