25use Wikimedia\Timestamp\ConvertibleTimestamp;
26use Wikimedia\WaitConditionLoop;
58 $this->keywordTableMap = isset(
$params[
'keywordTableMap'] )
79 $sql =
"SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
80 "WHERE c.connamespace = n.oid AND conname = " .
81 $this->
addQuotes( $name ) .
" AND n.nspname = " .
92 # Test for Postgres support, to avoid suppressed fatal error
93 if ( !function_exists(
'pg_connect' ) ) {
96 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
97 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
98 "webserver and database)\n"
116 $connectVars[
'host'] =
$server;
118 if ( (
int)$this->port > 0 ) {
119 $connectVars[
'port'] = (int)$this->port;
121 if ( $this->
flags & self::DBO_SSL ) {
122 $connectVars[
'sslmode'] =
'require';
131 $this->conn = pg_connect( $this->connectString, PGSQL_CONNECT_FORCE_NEW );
132 }
catch ( Exception $ex ) {
139 if ( !$this->conn ) {
140 $this->queryLogger->debug(
141 "DB connection error\n" .
142 "Server: $server, Database: $dbName, User: $user, Password: " .
145 $this->queryLogger->debug( $this->
lastError() .
"\n" );
149 $this->opened =
true;
151 # If called from the command-line (e.g. importDump), only show errors
152 if ( $this->cliMode ) {
153 $this->
doQuery(
"SET client_min_messages = 'ERROR'" );
156 $this->
query(
"SET client_encoding='UTF8'", __METHOD__ );
157 $this->
query(
"SET datestyle = 'ISO, YMD'", __METHOD__ );
158 $this->
query(
"SET timezone = 'GMT'", __METHOD__ );
159 $this->
query(
"SET standard_conforming_strings = on", __METHOD__ );
160 $this->
query(
"SET bytea_output = 'escape'", __METHOD__ );
181 if ( $this->dbName !== $db ) {
182 return (
bool)$this->
open( $this->server, $this->user, $this->password, $db );
195 $s .=
"$name='" . str_replace(
"'",
"\\'",
$value ) .
"' ";
202 return $this->conn ? pg_close( $this->conn ) :
true;
206 return parent::isTransactableQuery( $sql ) &&
207 !preg_match(
'/^SELECT\s+pg_(try_|)advisory_\w+\(/', $sql );
213 $sql = mb_convert_encoding( $sql,
'UTF-8' );
215 while (
$res = pg_get_result(
$conn ) ) {
216 pg_free_result(
$res );
218 if ( pg_send_query(
$conn, $sql ) ===
false ) {
219 throw new DBUnexpectedError( $this,
"Unable to post new query to PostgreSQL\n" );
221 $this->lastResultHandle = pg_get_result(
$conn );
222 if ( pg_result_error( $this->lastResultHandle ) ) {
233 PGSQL_DIAG_MESSAGE_PRIMARY,
234 PGSQL_DIAG_MESSAGE_DETAIL,
235 PGSQL_DIAG_MESSAGE_HINT,
236 PGSQL_DIAG_STATEMENT_POSITION,
237 PGSQL_DIAG_INTERNAL_POSITION,
238 PGSQL_DIAG_INTERNAL_QUERY,
240 PGSQL_DIAG_SOURCE_FILE,
241 PGSQL_DIAG_SOURCE_LINE,
242 PGSQL_DIAG_SOURCE_FUNCTION
244 foreach ( $diags as $d ) {
245 $this->queryLogger->debug( sprintf(
"PgSQL ERROR(%d): %s\n",
246 $d, pg_result_error_field( $this->lastResultHandle, $d ) ) );
254 Wikimedia\suppressWarnings();
255 $ok = pg_free_result(
$res );
256 Wikimedia\restoreWarnings();
266 Wikimedia\suppressWarnings();
267 $row = pg_fetch_object(
$res );
268 Wikimedia\restoreWarnings();
269 # @todo FIXME: HACK HACK HACK HACK debug
271 # @todo hashar: not sure if the following test really trigger if the object
274 if ( pg_last_error(
$conn ) ) {
277 'SQL error: ' . htmlspecialchars( pg_last_error(
$conn ) )
288 Wikimedia\suppressWarnings();
289 $row = pg_fetch_array(
$res );
290 Wikimedia\restoreWarnings();
293 if ( pg_last_error(
$conn ) ) {
296 'SQL error: ' . htmlspecialchars( pg_last_error(
$conn ) )
307 Wikimedia\suppressWarnings();
308 $n = pg_num_rows(
$res );
309 Wikimedia\restoreWarnings();
312 if ( pg_last_error(
$conn ) ) {
315 'SQL error: ' . htmlspecialchars( pg_last_error(
$conn ) )
327 return pg_num_fields(
$res );
335 return pg_field_name(
$res, $n );
339 $res = $this->
query(
"SELECT lastval()" );
341 return is_null( $row[0] ) ? null : (int)$row[0];
349 return pg_result_seek(
$res, $row );
354 if ( $this->lastResultHandle ) {
355 return pg_result_error( $this->lastResultHandle );
357 return pg_last_error();
365 if ( $this->lastResultHandle ) {
366 return pg_result_error_field( $this->lastResultHandle, PGSQL_DIAG_SQLSTATE );
373 if ( !$this->lastResultHandle ) {
377 return pg_affected_rows( $this->lastResultHandle );
400 if ( is_string( $column ) && !in_array( $column, [
'*',
'1' ] ) ) {
401 $conds[] =
"$column IS NOT NULL";
410 if ( preg_match(
'/rows=(\d+)/', $row[0], $count ) ) {
411 $rows = (int)$count[1];
419 $sql =
"SELECT indexname FROM pg_indexes WHERE tablename='$table'";
424 foreach (
$res as $row ) {
425 if ( $row->indexname == $this->indexName( $index ) ) {
442 foreach ( $schemas as
$schema ) {
448 $sql = <<<__INDEXATTR__
452 i.indoption[s.g] as option,
455 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
459 ON cis.oid=isub.indexrelid
461 ON cis.relnamespace = ns.oid
462 WHERE cis.relname=$eindex AND ns.nspname=$eschema) AS s,
468 ON ci.oid=i.indexrelid
470 ON ct.oid = i.indrelid
472 ON ci.relnamespace = n.oid
474 ci.relname=$eindex AND n.nspname=$eschema
475 AND attrelid = ct.oid
476 AND i.indkey[s.g] = attnum
477 AND i.indclass[s.g] = opcls.oid
478 AND pg_am.oid = opcls.opcmethod
483 foreach (
$res as $row ) {
497 $sql =
"SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
498 " AND indexdef LIKE 'CREATE UNIQUE%(" .
506 return $res->numRows() > 0;
524 $forUpdateKey = array_search(
'FOR UPDATE',
$options,
true );
525 if ( $forUpdateKey !==
false && $join_conds ) {
532 $alias =
key( $toCheck );
533 $name = $toCheck[$alias];
534 unset( $toCheck[$alias] );
536 $hasAlias = !is_numeric( $alias );
537 if ( !$hasAlias && is_string( $name ) ) {
541 if ( !isset( $join_conds[$alias] ) ||
542 !preg_match(
'/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_conds[$alias][0] )
544 if ( is_array( $name ) ) {
546 $toCheck = array_merge( $toCheck, $name );
565 if ( !count(
$args ) ) {
570 if ( !isset( $this->numericVersion ) ) {
578 if ( isset(
$args[0] ) && is_array(
$args[0] ) ) {
586 $ignore = in_array(
'IGNORE',
$options );
588 $sql =
"INSERT INTO $table (" . implode(
',',
$keys ) .
') VALUES ';
590 if ( $this->numericVersion >= 9.5 || !$ignore ) {
593 foreach (
$rows as $row ) {
599 $sql .=
'(' . $this->
makeList( $row ) .
')';
602 $sql .=
' ON CONFLICT DO NOTHING';
608 $numrowsinserted = 0;
610 $tok = $this->
startAtomic(
"$fname (outer)", self::ATOMIC_CANCELABLE );
612 foreach (
$rows as $row ) {
614 $tempsql .=
'(' . $this->
makeList( $row ) .
')';
616 $this->
startAtomic(
"$fname (inner)", self::ATOMIC_CANCELABLE );
625 if ( $e->errno !==
'23505' ) {
630 }
catch ( Exception
$e ) {
637 $this->affectedRowCount = $numrowsinserted;
652 return parent::makeUpdateOptionsArray(
$options );
675 $destTable, $srcTable, $varMap, $conds,
$fname = __METHOD__,
676 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
678 if ( !is_array( $insertOptions ) ) {
679 $insertOptions = [ $insertOptions ];
682 if ( in_array(
'IGNORE', $insertOptions ) ) {
685 $destTable = $this->
tableName( $destTable );
689 array_values( $varMap ),
696 $sql =
"INSERT INTO $destTable (" . implode(
',', array_keys( $varMap ) ) .
') ' .
697 $selectSql .
' ON CONFLICT DO NOTHING';
703 $destTable, $srcTable, $varMap, $conds,
$fname,
704 $insertOptions, $selectOptions, $selectJoinConds
709 return parent::nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
$fname,
710 $insertOptions, $selectOptions, $selectJoinConds );
713 public function tableName( $name, $format =
'quoted' ) {
717 return parent::tableName( $name, $format );
725 return isset( $this->keywordTableMap[$name] ) ? $this->keywordTableMap[
$name] :
$name;
734 return parent::tableName( $name, $format );
748 $safeseq = str_replace(
"'",
"''", $seqName );
749 $res = $this->
query(
"SELECT currval('$safeseq')" );
758 $sql =
"SELECT t.typname as ftype,a.atttypmod as size
759 FROM pg_class c, pg_attribute a, pg_type t
760 WHERE relname='$table' AND a.attrelid=c.oid AND
761 a.atttypid=t.oid and a.attname='$field'";
764 if ( $row->ftype ==
'varchar' ) {
765 $size = $row->size - 4;
774 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " :
'' );
789 static $codes = [
'08000',
'08003',
'08006',
'08001',
'08004',
'57P01',
'57P03',
'53300' ];
791 return in_array( $errno, $codes,
true );
799 $oldName, $newName, $temporary =
false,
$fname = __METHOD__
804 $temporary = $temporary ?
'TEMPORARY' :
'';
806 $ret = $this->
query(
"CREATE $temporary TABLE $newNameE " .
807 "(LIKE $oldNameE INCLUDING DEFAULTS INCLUDING INDEXES)",
$fname );
812 $res = $this->
query(
'SELECT attname FROM pg_class c'
813 .
' JOIN pg_namespace n ON (n.oid = c.relnamespace)'
814 .
' JOIN pg_attribute a ON (a.attrelid = c.oid)'
815 .
' JOIN pg_attrdef d ON (c.oid=d.adrelid and a.attnum=d.adnum)'
816 .
' WHERE relkind = \'r\''
818 .
' AND relname = ' . $this->
addQuotes( $oldName )
819 .
' AND pg_get_expr(adbin, adrelid) LIKE \'nextval(%\'',
824 $field = $row->attname;
825 $newSeq =
"{$newName}_{$field}_seq";
829 $this->
query(
"CREATE $temporary SEQUENCE $newSeqE OWNED BY $newNameE.$fieldE",
$fname );
831 "ALTER TABLE $newNameE ALTER COLUMN $fieldE SET DEFAULT nextval({$newSeqQ}::regclass)",
840 $table = $this->
tableName( $table,
'raw' );
843 'SELECT c.oid FROM pg_class c JOIN pg_namespace n ON (n.oid = c.relnamespace)'
844 .
' WHERE relkind = \'r\''
845 .
' AND nspname = ' . $this->
addQuotes( $schema )
846 .
' AND relname = ' . $this->
addQuotes( $table ),
854 $res = $this->
query(
'SELECT pg_get_expr(adbin, adrelid) AS adsrc FROM pg_attribute a'
855 .
' JOIN pg_attrdef d ON (a.attrelid=d.adrelid and a.attnum=d.adnum)'
856 .
" WHERE a.attrelid = $oid"
857 .
' AND pg_get_expr(adbin, adrelid) LIKE \'nextval(%\'',
863 'SELECT ' . preg_replace(
'/^nextval\((.+)\)$/',
'setval($1,1,false)', $row->adsrc ),
875 $eschemas = implode(
',', array_map( [ $this,
'addQuotes' ], $this->
getCoreSchemas() ) );
876 $result = $this->
query(
877 "SELECT DISTINCT tablename FROM pg_tables WHERE schemaname IN ($eschemas)",
$fname );
880 foreach ( $result as $table ) {
881 $vars = get_object_vars( $table );
882 $table = array_pop(
$vars );
883 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
884 $endArray[] = $table;
892 $ct =
new ConvertibleTimestamp( $ts );
894 return $ct->getTimestamp( TS_POSTGRES );
916 if (
false === $limit ) {
917 $limit = strlen( $text ) - 1;
920 if (
'{}' == $text ) {
924 if (
'{' != $text[$offset] ) {
925 preg_match(
"/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
926 $text, $match, 0, $offset );
927 $offset += strlen( $match[0] );
928 $output[] = (
'"' != $match[1][0]
930 : stripcslashes( substr( $match[1], 1, -1 ) ) );
931 if (
'},' == $match[3] ) {
937 }
while ( $limit > $offset );
947 return '[{{int:version-db-postgres-url}} PostgreSQL]';
958 $res = $this->
query(
"SELECT current_schema()", __METHOD__ );
975 $res = $this->
query(
"SELECT current_schemas(false)", __METHOD__ );
994 $res = $this->
query(
"SHOW search_path", __METHOD__ );
999 return explode(
",", $row[0] );
1010 $this->
query(
"SET search_path = " . implode(
", ", $search_path ) );
1028 $this->
begin( __METHOD__, self::TRANSACTION_INTERNAL );
1030 if ( in_array( $desiredSchema, $this->
getSchemas() ) ) {
1031 $this->coreSchema = $desiredSchema;
1032 $this->queryLogger->debug(
1033 "Schema \"" . $desiredSchema .
"\" already in the search path\n" );
1041 array_unshift( $search_path,
1044 $this->coreSchema = $desiredSchema;
1045 $this->queryLogger->debug(
1046 "Schema \"" . $desiredSchema .
"\" added to the search path\n" );
1050 $this->queryLogger->debug(
1051 "Schema \"" . $desiredSchema .
"\" not found, using current \"" .
1052 $this->coreSchema .
"\"\n" );
1055 $this->
commit( __METHOD__, self::FLUSHING_INTERNAL );
1075 if ( $this->tempSchema ) {
1080 "SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = pg_my_temp_schema()", __METHOD__
1084 $this->tempSchema = $row->nspname;
1092 if ( !isset( $this->numericVersion ) ) {
1094 $versionInfo = pg_version(
$conn );
1095 if ( version_compare( $versionInfo[
'client'],
'7.4.0',
'lt' ) ) {
1097 $this->numericVersion =
'7.3 or earlier';
1098 } elseif ( isset( $versionInfo[
'server'] ) ) {
1100 $this->numericVersion = $versionInfo[
'server'];
1103 $this->numericVersion = pg_parameter_status(
$conn,
'server_version' );
1119 if ( !is_array( $types ) ) {
1120 $types = [ $types ];
1129 foreach ( $schemas as
$schema ) {
1131 $sql =
"SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1132 .
"WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1133 .
"AND c.relkind IN ('" . implode(
"','", $types ) .
"')";
1160 SELECT 1
FROM pg_class, pg_namespace, pg_trigger
1161 WHERE relnamespace=pg_namespace.oid AND relkind=
'r'
1162 AND tgrelid=pg_class.oid
1163 AND nspname=%s AND relname=%s AND tgname=%s
1183 $exists = $this->
selectField(
'pg_rules',
'rulename',
1185 'rulename' => $rule,
1186 'tablename' => $table,
1191 return $exists === $rule;
1196 $sql = sprintf(
"SELECT 1 FROM information_schema.table_constraints " .
1197 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1221 '"pg_catalog"."pg_namespace"', 1, [
'nspname' =>
$schema ], __METHOD__ );
1223 return (
bool)$exists;
1232 $exists = $this->
selectField(
'"pg_catalog"."pg_roles"', 1,
1233 [
'rolname' => $roleName ], __METHOD__ );
1235 return (
bool)$exists;
1258 return pg_field_type(
$res, $index );
1268 } elseif ( $b instanceof
Blob ) {
1272 return pg_unescape_bytea( $b );
1283 if ( is_null(
$s ) ) {
1285 } elseif ( is_bool(
$s ) ) {
1286 return intval(
$s );
1287 } elseif (
$s instanceof
Blob ) {
1291 $s = pg_escape_bytea(
$conn,
$s->fetch() );
1298 return "'" . pg_escape_string(
$conn, (
string)
$s ) .
"'";
1302 $preLimitTail = $postLimitTail =
'';
1303 $startOpts = $useIndex = $ignoreIndex =
'';
1306 foreach (
$options as $key => $option ) {
1307 if ( is_numeric( $key ) ) {
1308 $noKeyOptions[$option] =
true;
1316 if ( isset(
$options[
'FOR UPDATE'] ) ) {
1317 $postLimitTail .=
' FOR UPDATE OF ' .
1318 implode(
', ', array_map( [ $this,
'tableName' ],
$options[
'FOR UPDATE'] ) );
1319 } elseif ( isset( $noKeyOptions[
'FOR UPDATE'] ) ) {
1320 $postLimitTail .=
' FOR UPDATE';
1323 if ( isset( $noKeyOptions[
'DISTINCT'] ) || isset( $noKeyOptions[
'DISTINCTROW'] ) ) {
1324 $startOpts .=
'DISTINCT';
1327 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1339 return implode(
' || ', $stringList );
1347 return '(' . $this->
selectSQLText( $table, $fld, $conds,
null, [], $join_conds ) .
')';
1351 return $field .
'::text';
1355 # Allow dollar quoting for function declarations
1356 if ( substr( $newLine, 0, 4 ) ==
'$mw$' ) {
1357 if ( $this->delimiter ) {
1358 $this->delimiter =
false;
1360 $this->delimiter =
';';
1364 return parent::streamStatementEnd( $sql, $newLine );
1369 foreach ( $write as $table ) {
1370 $tablesWrite[] = $this->
tableName( $table );
1373 foreach ( $read as $table ) {
1374 $tablesRead[] = $this->
tableName( $table );
1378 if ( $tablesWrite ) {
1380 'LOCK TABLE ONLY ' . implode(
',', $tablesWrite ) .
' IN EXCLUSIVE MODE',
1384 if ( $tablesRead ) {
1386 'LOCK TABLE ONLY ' . implode(
',', $tablesRead ) .
' IN SHARE MODE',
1395 if ( !parent::lockIsFree( $lockName, $method ) ) {
1400 $result = $this->
query(
"SELECT (CASE(pg_try_advisory_lock($key))
1401 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1404 return ( $row->lockstatus ===
't' );
1407 public function lock( $lockName, $method, $timeout = 5 ) {
1410 $loop =
new WaitConditionLoop(
1411 function () use ( $lockName, $key, $timeout, $method ) {
1412 $res = $this->
query(
"SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1414 if ( $row->lockstatus ===
't' ) {
1415 parent::lock( $lockName, $method, $timeout );
1419 return WaitConditionLoop::CONDITION_CONTINUE;
1424 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1427 public function unlock( $lockName, $method ) {
1430 $result = $this->
query(
"SELECT pg_advisory_unlock($key) as lockstatus", $method );
1433 if ( $row->lockstatus ===
't' ) {
1434 parent::unlock( $lockName, $method );
1438 $this->queryLogger->debug( __METHOD__ .
" failed to release lock\n" );
1444 $res = $this->
query(
"SHOW default_transaction_read_only", __METHOD__ );
1447 return $row ? ( strtolower( $row->default_transaction_read_only ) ===
'on' ) :
false;
1455 return \Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1459class_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( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
getCoreSchemas()
Return schema names for temporary tables and core application tables.
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)
Run a query and return a DBMS-dependent wrapper (that has all IResultWrapper methods)
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.
resource $lastResultHandle
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=[])
makeUpdateOptionsArray( $options)
Make UPDATE options array for Database::makeUpdateOptions.
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.
estimateRowCount( $table, $var=' *', $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Estimate rows in dataset Returns estimated count, based on EXPLAIN output This is not necessarily an ...
lastError()
Get a description of the last error.
wasConnectionError( $errno)
Do not use this method outside of Database/DBError classes.
addQuotes( $s)
Adds quotes and backslashes.
wasKnownStatementRollbackError()
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 new connection to the database (closing any existing one)
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=[])
@inheritDoc
wasDeadlock()
Determines if the last failure was due to a deadlock.
lockIsFree( $lockName, $method)
Check to see if a named lock is not locked by any thread (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.
getCoreSchema()
Return schema name for core application tables.
strencode( $s)
Wrapper for addslashes()
isTransactableQuery( $sql)
Determine whether a SQL statement is sensitive to isolation level.
resetSequenceForTable( $table, $fname=__METHOD__)
wasLockTimeout()
Determines if the last failure was due to a lock timeout.
triggerExists( $table, $trigger)
indexUnique( $table, $index, $fname=__METHOD__)
fieldName( $res, $n)
Get a field name in a result object.
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)
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
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database etc For and for historical it also represents a few features of articles that don t involve their such as access rights See also title txt Article Encapsulates access to the page table of the database The object represents a an and maintains state such as flags
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database key
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
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
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 noclasses & $ret
Allows to change the fields on the form that will be generated $name
returning false will NOT prevent logging $e