25use Wikimedia\Timestamp\ConvertibleTimestamp;
26use Wikimedia\WaitConditionLoop;
58 $this->keywordTableMap =
$params[
'keywordTableMap'] ?? [];
77 $sql =
"SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
78 "WHERE c.connamespace = n.oid AND conname = " .
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"
108 'dbname' => strlen( $dbName ) ? $dbName :
'postgres',
113 $connectVars[
'host'] =
$server;
115 if ( (
int)$this->
port > 0 ) {
116 $connectVars[
'port'] = (int)$this->
port;
118 if ( $this->flags & self::DBO_SSL ) {
119 $connectVars[
'sslmode'] =
'require';
128 $this->conn = pg_connect( $this->connectString, PGSQL_CONNECT_FORCE_NEW );
129 }
catch ( Exception $ex ) {
136 if ( !$this->conn ) {
137 $this->queryLogger->debug(
138 "DB connection error\n" .
139 "Server: $server, Database: $dbName, User: $user, Password: " .
142 $this->queryLogger->debug( $this->
lastError() .
"\n" );
146 $this->opened =
true;
148 # If called from the command-line (e.g. importDump), only show errors
149 if ( $this->cliMode ) {
150 $this->
doQuery(
"SET client_min_messages = 'ERROR'" );
153 $this->
query(
"SET client_encoding='UTF8'", __METHOD__ );
154 $this->
query(
"SET datestyle = 'ISO, YMD'", __METHOD__ );
155 $this->
query(
"SET timezone = 'GMT'", __METHOD__ );
156 $this->
query(
"SET standard_conforming_strings = on", __METHOD__ );
157 $this->
query(
"SET bytea_output = 'escape'", __METHOD__ );
160 $this->currentDomain =
new DatabaseDomain( $dbName, $schema, $tablePrefix );
166 if ( $this->coreSchema === $this->currentDomain->getSchema() ) {
171 return parent::relationSchemaQualifier();
191 $this->currentDomain = $domain;
204 $s .=
"$name='" . str_replace(
"'",
"\\'",
$value ) .
"' ";
211 return $this->conn ? pg_close( $this->conn ) :
true;
215 return parent::isTransactableQuery( $sql ) &&
216 !preg_match(
'/^SELECT\s+pg_(try_|)advisory_\w+\(/', $sql );
226 $sql = mb_convert_encoding( $sql,
'UTF-8' );
228 while (
$res = pg_get_result(
$conn ) ) {
229 pg_free_result(
$res );
231 if ( pg_send_query(
$conn, $sql ) ===
false ) {
232 throw new DBUnexpectedError( $this,
"Unable to post new query to PostgreSQL\n" );
234 $this->lastResultHandle = pg_get_result(
$conn );
235 if ( pg_result_error( $this->lastResultHandle ) ) {
246 PGSQL_DIAG_MESSAGE_PRIMARY,
247 PGSQL_DIAG_MESSAGE_DETAIL,
248 PGSQL_DIAG_MESSAGE_HINT,
249 PGSQL_DIAG_STATEMENT_POSITION,
250 PGSQL_DIAG_INTERNAL_POSITION,
251 PGSQL_DIAG_INTERNAL_QUERY,
253 PGSQL_DIAG_SOURCE_FILE,
254 PGSQL_DIAG_SOURCE_LINE,
255 PGSQL_DIAG_SOURCE_FUNCTION
257 foreach ( $diags
as $d ) {
258 $this->queryLogger->debug( sprintf(
"PgSQL ERROR(%d): %s\n",
259 $d, pg_result_error_field( $this->lastResultHandle, $d ) ) );
267 Wikimedia\suppressWarnings();
268 $ok = pg_free_result(
$res );
269 Wikimedia\restoreWarnings();
279 Wikimedia\suppressWarnings();
280 $row = pg_fetch_object(
$res );
281 Wikimedia\restoreWarnings();
282 # @todo FIXME: HACK HACK HACK HACK debug
284 # @todo hashar: not sure if the following test really trigger if the object
287 if ( pg_last_error(
$conn ) ) {
290 'SQL error: ' . htmlspecialchars( pg_last_error(
$conn ) )
301 Wikimedia\suppressWarnings();
302 $row = pg_fetch_array(
$res );
303 Wikimedia\restoreWarnings();
306 if ( pg_last_error(
$conn ) ) {
309 'SQL error: ' . htmlspecialchars( pg_last_error(
$conn ) )
317 if (
$res ===
false ) {
324 Wikimedia\suppressWarnings();
325 $n = pg_num_rows(
$res );
326 Wikimedia\restoreWarnings();
329 if ( pg_last_error(
$conn ) ) {
332 'SQL error: ' . htmlspecialchars( pg_last_error(
$conn ) )
344 return pg_num_fields(
$res );
352 return pg_field_name(
$res, $n );
356 $res = $this->
query(
"SELECT lastval()" );
358 return is_null( $row[0] ) ?
null : (int)$row[0];
366 return pg_result_seek(
$res, $row );
371 if ( $this->lastResultHandle ) {
372 return pg_result_error( $this->lastResultHandle );
374 return pg_last_error();
382 if ( $this->lastResultHandle ) {
383 return pg_result_error_field( $this->lastResultHandle, PGSQL_DIAG_SQLSTATE );
390 if ( !$this->lastResultHandle ) {
394 return pg_affected_rows( $this->lastResultHandle );
417 if ( is_string( $column ) && !in_array( $column, [
'*',
'1' ] ) ) {
418 $conds[] =
"$column IS NOT NULL";
427 if ( preg_match(
'/rows=(\d+)/', $row[0], $count ) ) {
428 $rows = (int)$count[1];
436 $sql =
"SELECT indexname FROM pg_indexes WHERE tablename='$table'";
441 foreach (
$res as $row ) {
442 if ( $row->indexname == $this->indexName( $index ) ) {
451 if ( $schema ===
false ) {
454 $schemas = [ $schema ];
459 foreach ( $schemas
as $schema ) {
465 $sql = <<<__INDEXATTR__
469 i.indoption[s.g]
as option,
472 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
476 ON cis.oid=isub.indexrelid
478 ON cis.relnamespace = ns.oid
479 WHERE cis.relname=$eindex AND ns.nspname=$eschema) AS s,
485 ON ci.oid=i.indexrelid
487 ON ct.oid = i.indrelid
489 ON ci.relnamespace =
n.oid
491 ci.relname=$eindex AND
n.nspname=$eschema
492 AND attrelid = ct.oid
493 AND i.indkey[s.g] = attnum
494 AND i.indclass[s.g] = opcls.oid
495 AND pg_am.oid = opcls.opcmethod
500 foreach (
$res as $row ) {
514 $sql =
"SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
515 " AND indexdef LIKE 'CREATE UNIQUE%(" .
523 return $res->numRows() > 0;
541 $forUpdateKey = array_search(
'FOR UPDATE',
$options,
true );
542 if ( $forUpdateKey !==
false && $join_conds ) {
549 $alias =
key( $toCheck );
550 $name = $toCheck[$alias];
551 unset( $toCheck[$alias] );
553 $hasAlias = !is_numeric( $alias );
554 if ( !$hasAlias && is_string(
$name ) ) {
558 if ( !isset( $join_conds[$alias] ) ||
559 !preg_match(
'/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_conds[$alias][0] )
561 if ( is_array(
$name ) ) {
563 $toCheck = array_merge( $toCheck,
$name );
582 if ( !count(
$args ) ) {
587 if ( !isset( $this->numericVersion ) ) {
595 if ( isset(
$args[0] ) && is_array(
$args[0] ) ) {
603 $ignore = in_array(
'IGNORE',
$options );
605 $sql =
"INSERT INTO $table (" . implode(
',',
$keys ) .
') VALUES ';
607 if ( $this->numericVersion >= 9.5 || !$ignore ) {
616 $sql .=
'(' . $this->
makeList( $row ) .
')';
619 $sql .=
' ON CONFLICT DO NOTHING';
625 $numrowsinserted = 0;
627 $tok = $this->
startAtomic(
"$fname (outer)", self::ATOMIC_CANCELABLE );
631 $tempsql .=
'(' . $this->
makeList( $row ) .
')';
633 $this->
startAtomic(
"$fname (inner)", self::ATOMIC_CANCELABLE );
642 if ( $e->errno !==
'23505' ) {
647 }
catch ( Exception
$e ) {
654 $this->affectedRowCount = $numrowsinserted;
669 return parent::makeUpdateOptionsArray(
$options );
691 $destTable, $srcTable, $varMap, $conds,
$fname = __METHOD__,
692 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
694 if ( !is_array( $insertOptions ) ) {
695 $insertOptions = [ $insertOptions ];
698 if ( in_array(
'IGNORE', $insertOptions ) ) {
701 $destTable = $this->
tableName( $destTable );
705 array_values( $varMap ),
712 $sql =
"INSERT INTO $destTable (" . implode(
',', array_keys( $varMap ) ) .
') ' .
713 $selectSql .
' ON CONFLICT DO NOTHING';
719 $destTable, $srcTable, $varMap, $conds,
$fname,
720 $insertOptions, $selectOptions, $selectJoinConds
724 parent::nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
$fname,
725 $insertOptions, $selectOptions, $selectJoinConds );
729 public function tableName( $name, $format =
'quoted' ) {
733 return parent::tableName(
$name, $format );
741 return $this->keywordTableMap[
$name] ??
$name;
750 return parent::tableName(
$name, $format );
764 $safeseq = str_replace(
"'",
"''", $seqName );
765 $res = $this->
query(
"SELECT currval('$safeseq')" );
774 $sql =
"SELECT t.typname as ftype,a.atttypmod as size
775 FROM pg_class c, pg_attribute a, pg_type t
776 WHERE relname='$table' AND a.attrelid=c.oid AND
777 a.atttypid=t.oid and a.attname='$field'";
780 if ( $row->ftype ==
'varchar' ) {
781 $size = $row->size - 4;
790 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " :
'' );
805 static $codes = [
'08000',
'08003',
'08006',
'08001',
'08004',
'57P01',
'57P03',
'53300' ];
807 return in_array( $errno, $codes,
true );
815 $oldName, $newName, $temporary =
false,
$fname = __METHOD__
820 $temporary = $temporary ?
'TEMPORARY' :
'';
823 "CREATE $temporary TABLE $newNameE " .
824 "(LIKE $oldNameE INCLUDING DEFAULTS INCLUDING INDEXES)",
826 $this::QUERY_PSEUDO_PERMANENT
832 $res = $this->
query(
'SELECT attname FROM pg_class c'
833 .
' JOIN pg_namespace n ON (n.oid = c.relnamespace)'
834 .
' JOIN pg_attribute a ON (a.attrelid = c.oid)'
835 .
' JOIN pg_attrdef d ON (c.oid=d.adrelid and a.attnum=d.adnum)'
836 .
' WHERE relkind = \'r\''
838 .
' AND relname = ' . $this->
addQuotes( $oldName )
839 .
' AND pg_get_expr(adbin, adrelid) LIKE \'nextval(%\'',
844 $field = $row->attname;
845 $newSeq =
"{$newName}_{$field}_seq";
850 "CREATE $temporary SEQUENCE $newSeqE OWNED BY $newNameE.$fieldE",
854 "ALTER TABLE $newNameE ALTER COLUMN $fieldE SET DEFAULT nextval({$newSeqQ}::regclass)",
863 $table = $this->
tableName( $table,
'raw' );
866 'SELECT c.oid FROM pg_class c JOIN pg_namespace n ON (n.oid = c.relnamespace)'
867 .
' WHERE relkind = \'r\''
868 .
' AND nspname = ' . $this->
addQuotes( $schema )
869 .
' AND relname = ' . $this->
addQuotes( $table ),
877 $res = $this->
query(
'SELECT pg_get_expr(adbin, adrelid) AS adsrc FROM pg_attribute a'
878 .
' JOIN pg_attrdef d ON (a.attrelid=d.adrelid and a.attnum=d.adnum)'
879 .
" WHERE a.attrelid = $oid"
880 .
' AND pg_get_expr(adbin, adrelid) LIKE \'nextval(%\'',
886 'SELECT ' . preg_replace(
'/^nextval\((.+)\)$/',
'setval($1,1,false)', $row->adsrc ),
901 $eschemas = implode(
',', array_map( [ $this,
'addQuotes' ], $this->
getCoreSchemas() ) );
903 "SELECT DISTINCT tablename FROM pg_tables WHERE schemaname IN ($eschemas)",
$fname );
907 $vars = get_object_vars( $table );
908 $table = array_pop(
$vars );
909 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
910 $endArray[] = $table;
918 $ct =
new ConvertibleTimestamp( $ts );
920 return $ct->getTimestamp( TS_POSTGRES );
942 if ( $limit ===
false ) {
943 $limit = strlen( $text ) - 1;
946 if ( $text ==
'{}' ) {
950 if ( $text[$offset] !=
'{' ) {
951 preg_match(
"/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
952 $text, $match, 0, $offset );
953 $offset += strlen( $match[0] );
954 $output[] = ( $match[1][0] !=
'"'
956 : stripcslashes( substr( $match[1], 1, -1 ) ) );
957 if ( $match[3] ==
'},' ) {
963 }
while ( $limit > $offset );
973 return '[{{int:version-db-postgres-url}} PostgreSQL]';
984 $res = $this->
query(
"SELECT current_schema()", __METHOD__ );
1001 $res = $this->
query(
"SELECT current_schemas(false)", __METHOD__ );
1020 $res = $this->
query(
"SHOW search_path", __METHOD__ );
1025 return explode(
",", $row[0] );
1036 $this->
query(
"SET search_path = " . implode(
", ", $search_path ) );
1054 $this->
begin( __METHOD__, self::TRANSACTION_INTERNAL );
1056 if ( in_array( $desiredSchema, $this->
getSchemas() ) ) {
1057 $this->coreSchema = $desiredSchema;
1058 $this->queryLogger->debug(
1059 "Schema \"" . $desiredSchema .
"\" already in the search path\n" );
1067 array_unshift( $search_path,
1070 $this->coreSchema = $desiredSchema;
1071 $this->queryLogger->debug(
1072 "Schema \"" . $desiredSchema .
"\" added to the search path\n" );
1076 $this->queryLogger->debug(
1077 "Schema \"" . $desiredSchema .
"\" not found, using current \"" .
1078 $this->coreSchema .
"\"\n" );
1081 $this->
commit( __METHOD__, self::FLUSHING_INTERNAL );
1101 if ( $this->tempSchema ) {
1106 "SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = pg_my_temp_schema()", __METHOD__
1110 $this->tempSchema = $row->nspname;
1118 if ( !isset( $this->numericVersion ) ) {
1120 $versionInfo = pg_version(
$conn );
1121 if ( version_compare( $versionInfo[
'client'],
'7.4.0',
'lt' ) ) {
1123 $this->numericVersion =
'7.3 or earlier';
1124 } elseif ( isset( $versionInfo[
'server'] ) ) {
1126 $this->numericVersion = $versionInfo[
'server'];
1129 $this->numericVersion = pg_parameter_status(
$conn,
'server_version' );
1145 if ( !is_array( $types ) ) {
1146 $types = [ $types ];
1148 if ( $schema ===
false ) {
1151 $schemas = [ $schema ];
1155 foreach ( $schemas
as $schema ) {
1157 $sql =
"SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1158 .
"WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1159 .
"AND c.relkind IN ('" . implode(
"','", $types ) .
"')";
1186 SELECT 1
FROM pg_class, pg_namespace, pg_trigger
1187 WHERE relnamespace=pg_namespace.oid AND relkind=
'r'
1188 AND tgrelid=pg_class.oid
1189 AND nspname=%s AND relname=%s AND tgname=%s
1209 $exists = $this->
selectField(
'pg_rules',
'rulename',
1211 'rulename' => $rule,
1212 'tablename' => $table,
1217 return $exists === $rule;
1222 $sql = sprintf(
"SELECT 1 FROM information_schema.table_constraints " .
1223 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1242 if ( !strlen( $schema ) ) {
1247 '"pg_catalog"."pg_namespace"', 1, [
'nspname' => $schema ], __METHOD__ );
1249 return (
bool)$exists;
1258 $exists = $this->
selectField(
'"pg_catalog"."pg_roles"', 1,
1259 [
'rolname' => $roleName ], __METHOD__ );
1261 return (
bool)$exists;
1284 return pg_field_type(
$res, $index );
1294 } elseif ( $b instanceof
Blob ) {
1298 return pg_unescape_bytea( $b );
1309 if ( is_null(
$s ) ) {
1311 } elseif ( is_bool(
$s ) ) {
1312 return intval(
$s );
1313 } elseif (
$s instanceof
Blob ) {
1317 $s = pg_escape_bytea(
$conn,
$s->fetch() );
1324 return "'" . pg_escape_string(
$conn, (
string)
$s ) .
"'";
1328 $preLimitTail = $postLimitTail =
'';
1329 $startOpts = $useIndex = $ignoreIndex =
'';
1333 if ( is_numeric( $key ) ) {
1334 $noKeyOptions[$option] =
true;
1342 if ( isset(
$options[
'FOR UPDATE'] ) ) {
1343 $postLimitTail .=
' FOR UPDATE OF ' .
1344 implode(
', ', array_map( [ $this,
'tableName' ],
$options[
'FOR UPDATE'] ) );
1345 } elseif ( isset( $noKeyOptions[
'FOR UPDATE'] ) ) {
1346 $postLimitTail .=
' FOR UPDATE';
1349 if ( isset( $noKeyOptions[
'DISTINCT'] ) || isset( $noKeyOptions[
'DISTINCTROW'] ) ) {
1350 $startOpts .=
'DISTINCT';
1353 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1357 return implode(
' || ', $stringList );
1365 return '(' . $this->
selectSQLText( $table, $fld, $conds,
null, [], $join_conds ) .
')';
1369 return $field .
'::text';
1373 # Allow dollar quoting for function declarations
1374 if ( substr( $newLine, 0, 4 ) ==
'$mw$' ) {
1375 if ( $this->delimiter ) {
1376 $this->delimiter =
false;
1378 $this->delimiter =
';';
1382 return parent::streamStatementEnd( $sql, $newLine );
1387 foreach ( $write
as $table ) {
1388 $tablesWrite[] = $this->
tableName( $table );
1391 foreach ( $read
as $table ) {
1392 $tablesRead[] = $this->
tableName( $table );
1396 if ( $tablesWrite ) {
1398 'LOCK TABLE ONLY ' . implode(
',', $tablesWrite ) .
' IN EXCLUSIVE MODE',
1402 if ( $tablesRead ) {
1404 'LOCK TABLE ONLY ' . implode(
',', $tablesRead ) .
' IN SHARE MODE',
1413 if ( !parent::lockIsFree( $lockName, $method ) ) {
1418 $result = $this->
query(
"SELECT (CASE(pg_try_advisory_lock($key))
1419 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1422 return ( $row->lockstatus ===
't' );
1425 public function lock( $lockName, $method, $timeout = 5 ) {
1428 $loop =
new WaitConditionLoop(
1429 function ()
use ( $lockName, $key, $timeout, $method ) {
1430 $res = $this->
query(
"SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1432 if ( $row->lockstatus ===
't' ) {
1433 parent::lock( $lockName, $method, $timeout );
1437 return WaitConditionLoop::CONDITION_CONTINUE;
1442 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1445 public function unlock( $lockName, $method ) {
1448 $result = $this->
query(
"SELECT pg_advisory_unlock($key) as lockstatus", $method );
1451 if ( $row->lockstatus ===
't' ) {
1452 parent::unlock( $lockName, $method );
1456 $this->queryLogger->debug( __METHOD__ .
" failed to release lock\n" );
1462 $res = $this->
query(
"SHOW default_transaction_read_only", __METHOD__ );
1465 return $row ? ( strtolower( $row->default_transaction_read_only ) ===
'on' ) :
false;
1469 return [ self::ATTR_SCHEMAS_AS_TABLE_GROUPS =>
true ];
1477 return \Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1484class_alias( DatabasePostgres::class,
'DatabasePostgres' );
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Class to handle database/prefix specification for IDatabase domains.
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 query result.
fieldInfo( $table, $field)
fetchRow( $res)
Fetch the next row from the given result object, in associative array form.
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"...
relationSchemaQualifier()
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.
doSelectDomain(DatabaseDomain $domain)
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__)
@suppress SecurityCheck-SQLInjection array_map not recognized T204911
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.
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)
open( $server, $user, $password, $dbName, $schema, $tablePrefix)
Open a new connection to the database (closing any existing one)
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.
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.
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.
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
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
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 and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same so they can t rely on Unix and must forbid reads to even standard directories like tmp lest users read each others files We cannot assume that the user has the ability to install or run any programs not written as web accessible PHP scripts Since anything that works on cheap shared hosting will work if you have shell or root access MediaWiki s design is based around catering to the lowest common denominator Although we support higher end setups as the way many things work by default is tailored toward shared hosting These defaults are unconventional from the point of view of and they certainly aren t ideal for someone who s installing MediaWiki as MediaWiki does not conform to normal Unix filesystem layout Hopefully we ll offer direct support for standard layouts in the but for now *any change to the location of files is unsupported *Moving things and leaving symlinks will *probably *not break but it is *strongly *advised not to try any more intrusive changes to get MediaWiki to conform more closely to your filesystem hierarchy Any such attempt will almost certainly result in unnecessary bugs The standard recommended location to install relative to the web is it should be possible to enable the appropriate rewrite rules by if you can reconfigure the web server
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 and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same user
Wikitext formatted, in the key only.
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
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. '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 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name '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. '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 '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:Array with elements of the form "language:title" in the order that they will be output. & $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 since 1.28! 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
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
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message key
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
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 just before the function returns a value If you return true
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
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place $output
returning false will NOT prevent logging $e
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
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))