Manuel:Accès à la base de données

Jump to navigation Jump to search
This page is a translated version of the page Manual:Database access and the translation is 1% complete.
Other languages:
Deutsch • ‎English • ‎Nederlands • ‎español • ‎français • ‎lietuvių • ‎polski • ‎português • ‎čeština • ‎русский • ‎中文 • ‎日本語


When coding in MediaWiki, you will normally access the database only through MediaWiki's functions for the purpose.

Database layout

For information about the MediaWiki database layout, such as a description of the tables and their contents, please see Schéma de base de données and maintenance/tables.sql.

Logging into MySQL

Using sql.php

MediaWiki provides a maintenance script to access the database. From the maintenance directory run:

php sql.php

You can then write out database queries. Alternatively you can provide a filename, and MediaWiki will execute it, substituting any MW special variables as appropriate. For more information, see Manual:Sql.php .

This will work for all database backends. However, the prompt is not as full features as the command line clients that come with your database.

Using the mysql command line client

## Database settings
$wgDBtype           = "mysql";
$wgDBserver         = "localhost";
$wgDBname           = "your-database-name";
$wgDBuser           = "your-database-username";  // Default: root
$wgDBpassword       = "your-password";


With SSH, login by entering the following:



Database Abstraction Layer


The abstraction layer is accessed through the Wikimedia\Rdbms\Database class. An instance of this class can be acquired by calling getConnection() on an injected ILoadBalancer, or using the wfGetDB() function. Either is typically called with a single parameter, which can be the DB_REPLICA (for read queries) or DB_MASTER (for write queries and read queries that need to have absolutely newest information) constant. The distinction between master and slave is important in a multi-database environment, such as Wikimedia. See the Wrapper functions section below for what you can do with the returned Database object.


$dbr = wfGetDB( DB_REPLICA );
foreach( $res as $row ) {

For a write query, use something like:

$dbw = wfGetDB( DB_MASTER );


Wrapper functions

We provide a query() function for raw SQL, but the wrapper functions like select() and insert() are usually more convenient. They can take care of things like table prefixes and escaping for you under some circumstances. If you really need to make your own SQL, please read the documentation for tableName() and addQuotes(). You will need both of them. Please keep in mind that failing to use addQuotes() properly can introduce severe security holes into your wiki.

Another important reason to use the high level methods rather than constructing your own queries is to ensure that your code will run properly regardless of the database type. Currently the best support is for MySQL/MariaDB. There is also good support for SQlite, however it is much slower than MySQL or MariaDB. There is support for PostgreSQL, but it is not as stable as MySQL. MediaWiki has experimental support for Oracle and MSSQL.

In the following, the available wrapper functions are listed. For a detailed description of the parameters of the wrapper functions, please refer to class Database's docs. Particularly see Database::select for an explanation of the $table, $vars, $conds, $fname, $options, and $join_conds parameters that are used by many of the other wrapper functions.

function buildLike(/*...*/);

Wrapper function: select()


$dbr = wfGetDB( DB_REPLICA );
$res = $dbr->select(
	'category',                                   // $table The table to query FROM (or array of tables)
	array( 'cat_title', 'cat_pages' ),            // $vars (columns of the table to SELECT)
	'cat_pages > 0',                              // $conds (The WHERE conditions)
	__METHOD__,                                   // $fname The current __METHOD__ (for performance tracking)

This example corresponds to the query


JOINs are also possible; for example:

$res = $dbw->select(
	array( 'watchlist', 'user_properties' ),
	array( 'wl_user' ),
		'wl_user != 1' ,
		'wl_namespace' => '0',
		'wl_title' => 'Main_page',
		'up_property' => 'enotifwatchlistpages',
		'user_properties' => array( 'INNER JOIN', array( 'wl_user=up_user' ) )

This example corresponds to the query

AND up_property = 'enotifwatchlistpages'

Extension:OrphanedTalkPages provides an example of how to use table aliases in queries.

Arguments are either single values (such as 'category' and 'cat_pages > 0') or arrays, if more than one value is passed for an argument position (such as array('cat_pages > 0', $myNextCond)). If you pass in strings to the third or fifth argument, you must manually use Database::addQuotes() on your values as you construct the string, as the wrapper will not do this for you. The values for table names (1st argument) or field names (2nd argument) must not be user controlled. The array construction for $conds is somewhat limited; it can only do equality and IS NULL relationships (i.e. WHERE key = 'value').


$dbr = wfGetDB( DB_REPLICA );
$res = $dbr->select(
	'category',                                   // $table
	'cat_pages > 0',                              // $conds
$output = '';
foreach( $res as $row ) {

Which will put an alphabetical list of categories with how many entries each category has in the variable $output. If you are outputting as HTML, ensure to escape values from the database with htmlspecialchars()

Convenience functions

Version de MediaWiki : 1.30


$id = $dbw->insertId();


Basic query optimization



Large installations of MediaWiki such as Wikipedia, use a large set of replica MySQL servers replicating writes made to a master MySQL server. It is important to understand the issues associated with this setup if you want to write code destined for Wikipedia.





If all slaves are lagged by more than 30 seconds (according to $wgDBservers ), MediaWiki will stop writing to the database. All edits and other write operations will be refused, with an error returned to the user. This gives the slaves a chance to catch up. Before we had this mechanism, the slaves would regularly lag by several minutes, making review of recent edits difficult.


Shell users can check replication lag with getLagTimes.php ; the other users with the siteinfo API.

Databases often have their own monitoring systems in place as well, see for instance wikitech:MariaDB#Replication lag (Wikimedia) and wikitech:Help:Toolforge/Database#Identifying lag (Wikimedia Cloud VPS).

Lag avoidance


Working with lag




Lock contention



$factory = \MediaWiki\MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
/* Do queries */



Database schema


For naming conventions, see Manual:Coding conventions/Database.

SQLite compatibility


Wrong Right
CREATE TABLE /*_*/foo (
    foo_text VARCHAR(256),
    PRIMARY KEY(foo_id),
CREATE TABLE /*_*/foo (
    foo_text VARCHAR(256)
) /*$wgDBTableOptions*/;



CREATE TABLE /*_*/foo (
    foo_id INT NOT NULL,
    foo_text VARCHAR(256),
    PRIMARY KEY(foo_id, foo_text)
) /*$wgDBTableOptions*/;

  • Don't add more than one column per statement:
Wrong Right
ALTER TABLE /*_*/foo
    ADD foo_bar BLOB,
    ADD foo_baz INT;
ALTER TABLE /*_*/foo ADD foo_bar BLOB;
ALTER TABLE /*_*/foo ADD foo_baz INT;
  • Set explicit defaults when adding NOT NULL columns:
Wrong Right
ALTER TABLE /*_*/foo ADD COLUMN foo_bar varchar(32) BINARY NOT NULL;
ALTER TABLE /*_*/foo ADD COLUMN foo_bar varchar(32) BINARY NOT NULL DEFAULT '';

You can run basic compatibility checks with:

Or, if you need to test an update patch, both:

  • php sqlite.php --check-syntax tables.sql (with the new tables.sql)
  • php sqlite.php --check-syntax tables.sql filename.sql
    • Since DB patches update the tables.sql file as well, for this one you should pass in the pre-commit version of tables.sql (the file with the full DB definition). Otherwise, you can get an error if you e.g. drop an index (since it already doesn't exist in tables.sql because you just removed it).

The above assumes you're in $IP/maintenance/, otherwise, pass the full path of the file. For extension patches, use the extension's equivalent of these files.

See also