* Fixed a bug causing the engine and charset settings to not be properly preserved when adding new tables on upgrade.
* Fixed total breakage of SQLite upgrade, by reusing the administrative connection to the SQLite database instead of creating a new one when wfGetDB() is called. Added LBFactory_Single to support this.
* Introduced a "schema variable" concept to DatabaseBase to avoid the use of globals for communication between the installer and the Database. Removed a lot of old global variable names from Database::replaceVars(), most were only added on a whim and were never used.
* Introduced DatabaseInstaller::getSchemaVars(), to allow schema variables to be supplied by the DatabaseInstaller child classes.
* Removed messages config-mysql-egine-mismatch [sic] and config-mysql-charset-mismatch. In the old installer it was possible for users to request a certain character set for an upgrade, but in the new installer the question is never asked. So these warnings were shown whenever a non-default character set or engine was used in the old database.
* In MysqlInstaller::preUpgrade(), fixed the incorrect strings used to identify the MySQL character sets: mysql5 instead of utf8 and mysql5-binary instead of binary.
* On install, initialise the site_stats table, using code copied from the old installer. Unlike the old installer, use SiteStats to increment the user count when the initial user is added.
* Fixed several instances of inappropriate call-by-reference.
* Replaced call_user_func_array() with call_user_func() where possible, it is shorter and simpler.
* Moved the caching boilerplate for DatabaseInstaller::getConnection() to the base class, and have the derived classes override an uncached function openConnection() instead. Updates r80892.
* In MysqlInstaller::getLocalSettings(), escape PHP strings correctly with LocalSettingsGenerator::escapePhpString().
* Reduce timeout for checks in dirIsExecutable() to 3 seconds, so that it doesn't take 30s to run when apache is in single-threaded mode for debugging.
* MySQL and SQLite have been tested and they appear to work. PostgreSQL upgrade is totally broken, apparently it was like that before I started. The Oracle code is untested.
'LBFactory' => 'includes/db/LBFactory.php',
'LBFactory_Multi' => 'includes/db/LBFactory_Multi.php',
'LBFactory_Simple' => 'includes/db/LBFactory.php',
+ 'LBFactory_Single' => 'includes/db/LBFactory_Single.php',
'LikeMatch' => 'includes/db/Database.php',
'LoadBalancer' => 'includes/db/LoadBalancer.php',
+ 'LoadBalancer_Single' => 'includes/db/LBFactory_Single.php',
'LoadMonitor' => 'includes/db/LoadMonitor.php',
'LoadMonitor_MySQL' => 'includes/db/LoadMonitor.php',
'MySQLField' => 'includes/db/DatabaseMysql.php',
protected $mLBInfo = array();
protected $mFakeSlaveLag = null, $mFakeMaster = false;
protected $mDefaultBigSelects = null;
+ protected $mSchemaVars = false;
# ------------------------------------------------------------------------------
# Accessors
}
}
+ /**
+ * Set variables to be used in sourceFile/sourceStream, in preference to the
+ * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
+ * all. If it's set to false, $GLOBALS will be used.
+ *
+ * @param $vars False, or array mapping variable name to value.
+ */
+ function setSchemaVars( $vars ) {
+ $this->mSchemaVars = $vars;
+ }
+
/**
* Read and execute commands from an open file handle
* Returns true on success, error string or exception on failure (depending on object's error ignore settings)
}
/**
- * Database independent variable replacement, replaces a set of named variables
- * in a sql statement with the contents of their global variables.
+ * Database independent variable replacement, replaces a set of variables
+ * in a sql statement with their contents as given by $this->getSchemaVars().
* Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables
*
* '{$var}' should be used for text and is passed through the database's addQuotes method
* / *$var* / is just encoded, besides traditional dbprefix and tableoptions it's use should be avoided
*
* @param $ins String: SQL statement to replace variables in
- * @param $varnames Array: Array of global variable names to replace
* @return String The new SQL statement with variables replaced
*/
- protected function replaceGlobalVars( $ins, $varnames ) {
- foreach ( $varnames as $var ) {
- if ( isset( $GLOBALS[$var] ) ) {
- $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $GLOBALS[$var] ), $ins ); // replace '{$var}'
- $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $GLOBALS[$var] ), $ins ); // replace `{$var}`
- $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $GLOBALS[$var] ) , $ins ); // replace /*$var*/
- }
+ protected function replaceSchemaVars( $ins ) {
+ $vars = $this->getSchemaVars();
+ foreach ( $vars as $var => $value ) {
+ // replace '{$var}'
+ $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
+ // replace `{$var}`
+ $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
+ // replace /*$var*/
+ $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
}
return $ins;
}
* Replace variables in sourced SQL
*/
protected function replaceVars( $ins ) {
- $varnames = array(
- 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
- 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
- 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
- );
-
- $ins = $this->replaceGlobalVars( $ins, $varnames );
+ $ins = $this->replaceSchemaVars( $ins );
// Table prefixes
$ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
return $ins;
}
+ /**
+ * Get schema variables. If none have been set via setSchemaVars(), then
+ * use some defaults from the current object.
+ */
+ protected function getSchemaVars() {
+ if ( $this->mSchemaVars ) {
+ return $this->mSchemaVars;
+ } else {
+ return $this->getDefaultSchemaVars();
+ }
+ }
+
+ /**
+ * Get schema variables to use if none have been set via setSchemaVars().
+ * Override this in derived classes to provide variables for tables.sql
+ * and SQL patch files.
+ */
+ protected function getDefaultSchemaVars() {
+ return array();
+ }
+
/**
* Table name callback
* @private
return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
}
+ protected function getDefaultSchemaVars() {
+ $vars = parent::getDefaultSchemaVars();
+ $vars['wgDBTableOptions'] = $GLOBALS['wgDBTableOptions'];
+ return $vars;
+ }
}
/**
return $this->mServer;
}
- public function replaceVars( $ins ) {
- $varnames = array( 'wgDBprefix' );
- if ( $this->mFlags & DBO_SYSDBA ) {
- $varnames[] = '_OracleDefTS';
- $varnames[] = '_OracleTempTS';
- }
-
- $ins = $this->replaceGlobalVars( $ins, $varnames );
-
- return parent::replaceVars( $ins );
- }
-
public function getSearchEngine() {
return 'SearchOracle';
}
}
}
+ /**
+ * Set the instance to be the given object
+ */
+ static function setInstance( $instance ) {
+ self::destroyInstance();
+ self::$instance = $instance;
+ }
+
/**
* Construct a factory based on a configuration array (typically from $wgLBFactoryConf)
*/
--- /dev/null
+<?php
+
+/**
+ * An LBFactory class that always returns a single database object.
+ */
+class LBFactory_Single extends LBFactory {
+ protected $lb;
+
+ /**
+ * @param $conf An associative array with one member:
+ * - connection: The DatabaseBase connection object
+ */
+ function __construct( $conf ) {
+ $this->lb = new LoadBalancer_Single( $conf );
+ }
+
+ function newMainLB( $wiki = false ) {
+ return $this->lb;
+ }
+
+ function getMainLB( $wiki = false ) {
+ return $this->lb;
+ }
+
+ function newExternalLB( $cluster, $wiki = false ) {
+ return $this->lb;
+ }
+
+ function &getExternalLB( $cluster, $wiki = false ) {
+ return $this->lb;
+ }
+
+ function forEachLB( $callback, $params = array() ) {
+ call_user_func_array( $callback, array_merge( array( $this->lb ), $params ) );
+ }
+}
+
+/**
+ * Helper class for LBFactory_Single.
+ */
+class LoadBalancer_Single extends LoadBalancer {
+ var $db;
+
+ function __construct( $params ) {
+ $this->db = $params['connection'];
+ parent::__construct( array( 'servers' => array( array(
+ 'type' => $this->db->getType(),
+ 'host' => $this->db->getServer(),
+ 'dbname' => $this->db->getDBname(),
+ 'load' => 1,
+ ) ) ) );
+ }
+
+ function reallyOpenConnection( $server, $dbNameOverride = false ) {
+ return $this->db;
+ }
+}
}
/**
- * Connect to the database using the administrative user/password currently
- * defined in the session. On success, return the connection, on failure,
- *
- * This may be called multiple times, so the result should be cached.
+ * Open a connection to the database using the administrative user/password
+ * currently defined in the session, without any caching. Returns a status
+ * object. On success, the status object will contain a Database object in
+ * its value member.
*
* @return Status
*/
- public abstract function getConnection();
+ public abstract function openConnection();
/**
* Create the database and return a Status object indicating success or
*/
public abstract function setupDatabase();
+ /**
+ * Connect to the database using the administrative user/password currently
+ * defined in the session. Returns a status object. On success, the status
+ * object will contain a Database object in its value member.
+ *
+ * This will return a cached connection if one is available.
+ *
+ * @return DatabaseBase
+ */
+ public function getConnection() {
+ if ( $this->db ) {
+ return Status::newGood( $this->db );
+ }
+ $status = $this->openConnection();
+ if ( $status->isOK() ) {
+ $this->db = $status->value;
+ // Enable autocommit
+ $this->db->clearFlag( DBO_TRX );
+ $this->db->commit();
+ }
+ return $status;
+ }
+
/**
* Create database tables from scratch.
*
}
// Resume normal operations
if( $status->isOk() ) {
- LBFactory::enableBackend();
+ $this->enableLB();
}
return $status;
}
*/
public abstract function getLocalSettings();
+ /**
+ * Override this to provide DBMS-specific schema variables, to be
+ * substituted into tables.sql and other schema files.
+ */
+ public function getSchemaVars() {
+ return array();
+ }
+
+ /**
+ * Set appropriate schema variables in the current database connection.
+ *
+ * This should be called after any request data has been imported, but before
+ * any write operations to the database.
+ */
+ public function setupSchemaVars() {
+ $status = $this->getConnection();
+ if ( $status->isOK() ) {
+ $status->value->setSchemaVars( $this->getSchemaVars() );
+ }
+ }
+
+ /**
+ * Set up LBFactory so that wfGetDB() etc. works.
+ * We set up a special LBFactory instance which returns the current
+ * installer connection.
+ */
+ public function enableLB() {
+ $status = $this->getConnection();
+ if ( !$status->isOK() ) {
+ throw new MWException( __METHOD__.': unexpected DB connection error' );
+ }
+ LBFactory::setInstance( new LBFactory_Single( array(
+ 'connection' => $status->value ) ) );
+ }
+
+ /**
+ * Get a Database connection object. Throw an exception if we can't get one.
+ *
+ * @return DatabaseBase
+ */
+ public function getConnectionOrDie() {
+ }
+
/**
* Perform database upgrades
*
* @return Boolean
*/
public function doUpgrade() {
- # Maintenance scripts like wfGetDB()
- LBFactory::enableBackend();
+ $this->setupSchemaVars();
+ $this->enableLB();
$ret = true;
ob_start( array( $this, 'outputHandler' ) );
return $this->globalNames;
}
- /**
- * Return any table options to be applied to all tables that don't
- * override them.
- *
- * @return Array
- */
- public function getTableOptions() {
- return array();
- }
-
/**
* Construct and initialise parent.
* This is typically only called from Installer::getDBInstaller()
'''MyISAM''' may be faster in single-user or read-only installations.
MyISAM databases tend to get corrupted more often than InnoDB databases.",
- 'config-mysql-egine-mismatch' => "'''Warning:''' you requested the $1 storage engine, but the existing database uses the $2 engine.
-This upgrade script can't convert it, so it will remain $2.",
'config-mysql-charset' => 'Database character set:',
'config-mysql-binary' => 'Binary',
'config-mysql-utf8' => 'UTF-8',
This is more efficient than MySQL's UTF-8 mode, and allows you to use the full range of Unicode characters.
In '''UTF-8 mode''', MySQL will know what character set your data is in, and can present and convert it appropriately, but it will not let you store characters above the [http://en.wikipedia.org/wiki/Mapping_of_Unicode_character_planes Basic Multilingual Plane].",
- 'config-mysql-charset-mismatch' => "'''Warning:''' you requested the $1 schema, but the existing database has the $2 schema.
- This upgrade script can't convert it, so it will remain $2.",
'config-site-name' => 'Name of wiki:',
'config-site-name-help' => "This will appear in the title bar of the browser and in various other places.",
'config-site-name-blank' => 'Enter a site name.',
'config-install-interwiki-sql' => 'Could not find file <code>interwiki.sql</code>.',
'config-install-interwiki-exists' => "'''Warning''': The interwiki table seems to already have entries.
Skipping default list.",
+ 'config-install-stats' => 'Initializing statistics',
'config-install-secretkey' => 'Generating secret key',
'config-insecure-secret' => "'''Warning:''' Unable to create a secure <code>$1</code>.
Consider changing it manually.",
'''MyISAM''' можа быць хутчэйшай у вікі з адным удзельнікам, ці толькі для чытаньня.
Базы зьвестак на MyISAM вядомыя тым, што ў іх зьвесткі шкодзяцца нашмат часьцей за InnoDB.",
- 'config-mysql-egine-mismatch' => "'''Папярэджаньне:''' Вы зрабілі запыт на рухавік сховішча $1, але існуючая база зьвестак выкарыстоўвае рухавік $2.
-Гэтае абнаўленьне ня можа вырашыць гэтую праблему, рухавік сховішча застанецца $2.",
'config-mysql-charset' => 'Кадаваньне базы зьвестак:',
'config-mysql-binary' => 'Двайковае',
'config-mysql-utf8' => 'UTF-8',
Гэта болей эфэктыўна за рэжым MySQL UTF-8, і дазваляе Вам выкарыстоўваць увесь дыяпазон сымбаляў Unicode.
У '''рэжыме UTF-8''', MySQL ведае, якая табліцы сымбаляў выкарыстоўваецца ў Вашых зьвестках, і можа адпаведна прадстаўляць і канвэртаваць іх, але гэта не дазволіць Вам захоўваць сымбалі па-за межамі [http://en.wikipedia.org/wiki/Mapping_of_Unicode_character_planes Базавага шматмоўнага дыяпазону].",
- 'config-mysql-charset-mismatch' => "'''Папярэджаньне:''' Вы зрабілі запыт на схему $1, але існуючая база зьвестак выкарыстоўвае схему $2.
-Гэтае абнаўленьне ня можа вырашыць гэтую праблему, таму будзе пакінутая $2.",
'config-site-name' => 'Назва вікі:',
'config-site-name-help' => 'Назва будзе паказвацца ў загалоўку браўзэра і ў некаторых іншых месцах.',
'config-site-name-blank' => 'Увядзіце назву сайта.',
Това е по-ефективно от UTF-8 режима на MySQL и позволява използването на пълния набор от символи в Уникод.
В '''UTF-8 режим''' MySQL ще знае в кой набор от символи са данните от уикито и ще може да ги показва и променя по подходящ начин, но няма да позволява складиране на символи извън [http://en.wikipedia.org/wiki/Mapping_of_Unicode_character_planes Основния многоезичен набор].",
- 'config-mysql-charset-mismatch' => "'''Предупреждение:''' заявена е $1 схема, но съществуващата база от данни е с $2 схема.
- Скриптът за надграждане не може да я преобразува, затова тя ще остане $2.",
'config-site-name' => 'Име на уикито:',
'config-site-name-help' => 'Това име ще се показва в заглавната лента на браузъра и на различни други места.',
'config-site-name-blank' => 'Необходимо е да се въведе име на уикито.',
'''MyISAM''' ist in Einzelnutzerumgebungen sowie bei schreibgeschützten Wikis schneller.
Bei MyISAM-Datenbanken treten tendenziell häufiger Fehler auf als bei InnoDB-Datenbanken.",
- 'config-mysql-egine-mismatch' => "'''Warnung:''' Als Speicher-Engine wurde $1 ausgewählt, während die Datenbank $2 verwendet.
-Das Aktualisierungsskript kann die Speicher-Engine nicht konvertieren, so dass weiterhin $2 verwendet wird.",
'config-mysql-charset' => 'Datenbankzeichensatz:',
'config-mysql-binary' => 'binär',
'config-mysql-utf8' => 'UTF-8',
Im '''UTF-8-Modus''' wird MySQL den Zeichensatz der Daten erkennen und sie richtig anzeigen und konvertieren,
allerdings können keine Zeichen außerhalb des [http://de.wikipedia.org/wiki/Basic_Multilingual_Plane#Gliederung_in_Ebenen_und_Bl.C3.B6cke ''Basic Multilingual Plane'' (BMP)] gespeichert werden.",
- 'config-mysql-charset-mismatch' => "'''Warnung:''' Als Datenbankzeichensatz wurde $1 ausgewählt, während die Datenbank $2 verwendet.
-Das Aktualisierungsskript kann den Datenbankzeichensatz nicht konvertieren, so dass weiterhin $2 verwendet wird.",
'config-site-name' => 'Name des Wikis:',
'config-site-name-help' => 'Er wird in der Titelleiste des Browsers, wie auch verschiedenen anderen Stellen, genutzt.',
'config-site-name-blank' => 'Sitenamen angeben.',
'''MyISAM''' es más rápido en instalaciones de usuario único o de sólo lectura.
Las bases de datos MyISAM tienden a corromperse más a menudo que las bases de datos InnoDB.",
- 'config-mysql-egine-mismatch' => "'''Atención:''' Solicitó el motor de almacenamento $1, pero el existente en la base de datos es el motor $2.
-Este código de actualización no lo puede convertir, de modo que permanecerá como $2.",
'config-mysql-charset' => 'Conjunto de caracteres de la base de datos:',
'config-mysql-binary' => 'Binario',
'config-mysql-utf8' => 'UTF-8',
- 'config-mysql-charset-mismatch' => "'''Advertencia:''' Has solicitado el esquema $1, pero la base de datos existente tiene el esquema $2.
-Este script de actualización no puede convertirlo, de modo que permanecerá como $2.",
'config-site-name' => 'Nombre del wiki:',
'config-site-name-help' => 'Esto aparecerá en la barra de título del navegador y en varios otros lugares.',
'config-site-name-blank' => 'Ingresar un nombre de sitio.',
'config-mysql-engine-help' => "'''InnoDB''' est presque toujours la meilleure option, car il supporte bien l'[http://fr.wikipedia.org/wiki/Ordonnancement_dans_les_syst%C3%A8mes_d%27exploitation ordonnancement].
'''MyISAM''' peut être plus rapide dans les installations monoposte ou en lecture seule. Les bases de données MyISAM ont tendance à se corrompre plus souvent que celles d'InnoDB.",
- 'config-mysql-egine-mismatch' => "'''Attention:''' Vous avez demandé le moteur de stockage $1, mais la base de données existante utilise le moteur $2.
-Ce script de mise à niveau ne peut pas le convertir, il restera $2.",
'config-mysql-charset' => 'Jeu de caractères de la base de données :',
'config-mysql-binary' => 'Binaire',
'config-mysql-utf8' => 'UTF-8',
En ''mode binaire'', MediaWiki stocke le texte UTF-8 dans des champs binaires de la base de données. C'est plus efficace que le ''mode UTF-8'' de MySQL, et vous permet d'utiliser toute la gamme des caractères Unicode.
En ''mode UTF-8'', MySQL connaîtra le jeu de caractères de vos données et pourra présenter et convertir les données de manière appropriée, mais il ne vous laissera pas stocker les caractères au-dessus du [http://en.wikipedia.org/wiki/Mapping_of_Unicode_character_planes plan multilingue de base] (en anglais).",
- 'config-mysql-charset-mismatch' => "'''Attention:''' Vous avez demandé le schéma $1, mais la base de données existante a le schéma $2.
-Ce script de mise à niveau ne peut pas le convertir, il restera $2.",
'config-site-name' => 'Nom du wiki :',
'config-site-name-help' => 'Il apparaîtra dans la barre de titre du navigateur et en divers autres endroits.',
'config-site-name-blank' => 'Entrez un nom de site.',
'''MyISAM''' é máis rápido en instalacións de usuario único e de só lectura.
As bases de datos MyISAM tenden a se corromper máis a miúdo ca as bases de datos InnoDB.",
- 'config-mysql-egine-mismatch' => "'''Atención:''' Solicitou o motor de almacenamento $1, mais o existente na base de datos é o motor $2.
-Esta escritura de actualización non o pode converter, de modo que permanecerá $2.",
'config-mysql-charset' => 'Conxunto de caracteres da base de datos:',
'config-mysql-binary' => 'Binario',
'config-mysql-utf8' => 'UTF-8',
No '''modo UTF-8''', MySQL saberá o xogo de caracteres dos seus datos e pode presentar e converter os datos de maneira axeitada,
pero non lle deixará gardar caracteres por riba do [http://en.wikipedia.org/wiki/Mapping_of_Unicode_character_planes plan multilingüe básico].",
- 'config-mysql-charset-mismatch' => "'''Atención:''' Solicitou o esquema $1, mais o existente na base de datos é o esquema $2.
-Esta escritura de actualización non o pode converter, de modo que permanecerá $2.",
'config-site-name' => 'Nome do wiki:',
'config-site-name-help' => 'Isto aparecerá na barra de títulos do navegador e noutros lugares.',
'config-site-name-blank' => 'Escriba o nome do sitio.',
'''MyISAM''' pote esser plus rapide in installationes a usator singule o a lectura solmente.
Le bases de datos MyISAM tende a esser corrumpite plus frequentemente que le base de datos InnoDB.",
- 'config-mysql-egine-mismatch' => "'''Aviso:''' tu requestava le motor de immagazinage $1, ma le base de datos existente usa le motor $2.
-Iste script de actualisation non pote converter lo, dunque illo remanera $2.",
'config-mysql-charset' => 'Codification de characteres in le base de datos:',
'config-mysql-binary' => 'Binari',
'config-mysql-utf8' => 'UTF-8',
Isto es plus efficiente que le modo UTF-8 de MySQL, e permitte usar le rango complete de characteres Unicode.
In '''modo UTF-8''', MySQL cognoscera le codification de characteres usate pro tu dats, e pote presentar e converter lo appropriatemente, ma illo non permittera immagazinar characteres supra le [http://en.wikipedia.org/wiki/Mapping_of_Unicode_character_planes Plano Multilingue Basic].",
- 'config-mysql-charset-mismatch' => "'''Aviso:''' tu requestava le schema $1, ma le base de datos existente ha le schema $2.
-Iste script de actualisation non pote converter lo, dunque illo remanera $2.",
'config-site-name' => 'Nomine del wiki:',
'config-site-name-help' => 'Isto apparera in le barra de titulo del navigator e in varie altere locos.',
'config-site-name-blank' => 'Entra un nomine de sito.',
'''MyISAM''' mungkin lebih cepat dalam instalasi pengguna-tunggal atau hanya-baca.
Basis data MyISAM cenderung lebih sering rusak daripada basis data InnoDB.",
- 'config-mysql-egine-mismatch' => "'''Peringatan:''' Anda meminta mesin penyimpanan $1, tapi basis data yang ada menggunakan mesin $2.
-Skrip pemutakhiran ini tidak dapat mengubahnya, sehingga akan tetap $2.",
'config-mysql-charset' => 'Set karakter basis data:',
'config-mysql-binary' => 'Biner',
'config-mysql-utf8' => 'UTF-8',
Ini lebih efisien daripada modus UTF-8 MySQL dan memungkinkan Anda untuk menggunakan ragam penuh karakter Unicode.
Dalam '''modus UTF-8''', MySQL akan tahu apa set karakter data dan dapat menampilkan dan mengubahnya sesuai keperluan, tetapi tidak akan mengizinkan Anda menyimpan karakter di atas [http://en.wikipedia.org/wiki/Mapping_of_Unicode_character_planes Basic Multilingual Plane].",
- 'config-mysql-charset-mismatch' => "'''Peringatan:''' Anda meminta skema $1, tapi basis data yang ada menggunakan skema $2.
-Skrip pemutakhiran ini tidak dapat mengubahnya, sehingga akan tetap $2.",
'config-site-name' => 'Nama wiki:',
'config-site-name-help' => 'Ini akan muncul di bilah judul peramban dan di berbagai tempat lainnya.',
'config-site-name-blank' => 'Masukkan nama situs.',
'''MyISAM'''は、利用者が1人の場合、あるいは読み込み専用でインストールする場合に、より処理が早くなるでしょう。
ただし、MyISAMのデータベースは、InnoDBより高頻度で破損する傾向があります。",
- 'config-mysql-egine-mismatch' => "'''警告:'''$1ストレージエンジンが要求されましたが、既存のデータベースは$2エンジンを使用します。
-この更新スクリプトは、これに対応していません、$2のままになります。",
'config-mysql-charset' => 'データベースの文字セット:',
'config-mysql-binary' => 'バイナリ',
'config-mysql-utf8' => 'UTF-8',
'''UTF-8形式'''では、MySQLは、なんの文字集合がデータのなかに含まれているかを知り、それに対して適切な提示と変換をするでしょうが、
[http://ja.wikipedia.org/wiki/%E5%9F%BA%E6%9C%AC%E5%A4%9A%E8%A8%80%E8%AA%9E%E9%9D%A2 基本多言語面]の外にある文字を格納できるようにはなりません。",
- 'config-mysql-charset-mismatch' => "'''警告:'''$1スキーマが要求されましたが、既存のデータベースは$2スキーマです。
-この更新スクリプトは、これに対応していませんので、$2のままになります。",
'config-site-name' => 'ウィキの名前:',
'config-site-name-help' => 'この事象はブラウザのタイトルバーと他の様々な場所において出現する。',
'config-site-name-blank' => 'サイト名を入力してください。',
'''MyISAM''' може да е побрз кај инсталациите наменети за само еден корисник или незаписни инсталации (само читање).
Базите на податоци од MyISAM почесто се расипуваат од базите на InnoDB.",
- 'config-mysql-egine-mismatch' => "'''Предупредување:''' го побаравте складишниот погон $1, но постоечката база на податоци го користи погонот $2.
-Оваа надградбена скрипта не може да го претвори, и затоа ќе остане на $2.",
'config-mysql-charset' => 'Збир знаци за базата:',
'config-mysql-binary' => 'Бинарен',
'config-mysql-utf8' => 'UTF-8',
Ова е поефикасно отколку TF-8 режимот на MySQL, и ви овозможува да ја користите целата палета на уникодни знаци.
Во '''UTF-8 режим''', MySQL ќе знае на кој збир знаци припаѓаат вашите податоци, и може соодветно да ги претстави и претвори, но нема да ви дозволи да складиратезнаци над [http://en.wikipedia.org/wiki/Mapping_of_Unicode_character_planes Основната повеќејазична рамнина].",
- 'config-mysql-charset-mismatch' => "'''Предупредување:''' ја побаравте шемата $1, но постоечката база на податоци ја има шемата $2.
-Оваа надградбена скрипта не може да ја претвори, па затоа ќе остане на $2.",
'config-site-name' => 'Име на викито:',
'config-site-name-help' => 'Ова ќе се појавува во заглавната лента на прелистувачот и на разни други места.',
'config-site-name-blank' => 'Внесете име на мрежното место.',
'''MyISAM''' is bij een zeer beperkt aantal gebruikers mogelijk sneller, of als de wiki alleen-lezen is.
MyISAM-databases raken vaker corrupt dan InnoDB-databases.",
- 'config-mysql-egine-mismatch' => "'''Waarschuwing:''' u wilt de opslagwijze $1 gebruiken, maar de bestaande database gebruikt de opslagwijze $2.
-Dit upgradescript kan de opslagwijze niet converteren, dus het blijft $2.",
'config-mysql-charset' => 'Tekenset voor de database:',
'config-mysql-binary' => 'Binair',
'config-mysql-utf8' => 'UTF-8',
In '''UTF-8-modus''' kent MySQL de tekenset van uw gegevens en kan de databaseserver ze juist weergeven en converteren.
Het is dat niet mogelijk tekens op te slaan die de \"[http://nl.wikipedia.org/wiki/Lijst_van_Unicode-subbereiken#Basic_Multilingual_Plane Basic Multilingual Plane]\" te boven gaan.",
- 'config-mysql-charset-mismatch' => "'''Waarschuwing:''' u wilt het schema $1 gebruiken, maar de bestaande database gebruikt het schema $2.
-Dit upgradescript kan het schema niet converteren, dus het blijft $2.",
'config-site-name' => 'Naam van de wiki:',
'config-site-name-help' => 'Deze naam verschijnt in de titelbalk van browsers en op andere plaatsen.',
'config-site-name-blank' => 'Geef een naam op voor de site.',
'''MyISAM''' kan være raskere i enbruker- eller les-bare-installasjoner.
MyISAM-databaser har en tendens til å bli ødelagt oftere enn InnoDB-databaser.",
- 'config-mysql-egine-mismatch' => "'''Advarsel:''' du ba om lagringsmotoren $1, men den eksisterende databasen bruker motoren $2.
-Dette oppgraderingsskriptet kan ikke konvertere den, så den vil forbli $2.",
'config-mysql-charset' => 'Databasetegnsett:',
'config-mysql-binary' => 'Binær',
'config-mysql-utf8' => 'UTF-8',
I '''UTF-8 mode''' vil MySQL vite hvilket tegnsett dataene dine er i og kan presentere og konvertere det på en riktig måte,
men det vil ikke la deg lagre tegn over «[http://en.wikipedia.org/wiki/Mapping_of_Unicode_character_planes the Basic Multilingual Plane]».",
- 'config-mysql-charset-mismatch' => "'''Advarsel:''' du ba om skjemaet $1, men den eksisterende databasen bruker skjemaet $2.
-Dette oppgraderingsskriptet kan ikke konvertere det, så det vil forbli $2.",
'config-site-name' => 'Navn på wiki:',
'config-site-name-help' => 'Dette vil vises i tittellinjen i nettleseren og diverse andre steder.',
'config-site-name-blank' => 'Skriv inn et nettstedsnavn.',
'''MyISAM''' a peul esse pi lest an instalassion për n'utent sol o mach an letura.
La base ëd dàit MyISAM a tira a corompse pi 'd soens che la base ëd dàit InnoDB.",
- 'config-mysql-egine-mismatch' => "'''Avis:''' it l'has ciamà ël motor ëd memorisassion $1, ma la base ëd dàit esistenta a deuvra ël motor $2.
-Cost senari d'agiornament a peul pa convertilo, parèj a restrà $2.",
'config-mysql-charset' => 'Ansem ëd caràter dla base ëd dàit:',
'config-mysql-binary' => 'Binari',
'config-mysql-utf8' => 'UTF-8',
Sòn a l'é pi eficient che la manera UTF-8 ëd MySQL, e a-j përmët ëd dovré l'ansema antregh ëd caràter Unicode.
An '''manera UTF-8''', MySQL a conossrà an che ansem ëd caràter a son ij sò dat, e a peul presenteje e convertije apropriatament, ma a-j lassa pa memorisé ij caràter ëdzora al [http://en.wikipedia.org/wiki/Mapping_of_Unicode_character_planes pian multilenghìstich ëd base].",
- 'config-mysql-charset-mismatch' => "'''Avis:''' a l'ha ciamà lë schema $1, ma la base ëd dàit esistenta a l'ha lë schema $2.
-Cost senari d'agiornament a peul pa convertilo, parèj a restrà $2.",
'config-site-name' => 'Nòm ëd la wiki:',
'config-site-name-help' => "Sòn a comparirà ant la bara dël tìtol dël navigador e an vàire d'àutri pòst.",
'config-site-name-blank' => "Ch'a buta un nòm ëd sit.",
'''MyISAM''' pode ser mais rápido no modo de utilizador único ou em instalações somente para leitura.
As bases de dados MyISAM tendem a ficar corrompidas com maior frequência do que as bases de dados InnoDB.",
- 'config-mysql-egine-mismatch' => "'''Aviso:''' pediu a plataforma de armazenamento $1, mas a base de dados existente usa a plataforma $2. Este código de actualização não pode fazer a conversão, por isso permanecerá como $2.",
'config-mysql-charset' => 'Conjunto de caracteres da base de dados:',
'config-mysql-binary' => 'Binary',
'config-mysql-utf8' => 'UTF-8',
No modo '''UTF-8''', o MySQL saberá em que conjunto de caracteres os seus dados estão e pode apresentá-los e convertê-los da forma mais adequada,
mas não lhe permitirá armazenar caracteres acima do [http://en.wikipedia.org/wiki/Mapping_of_Unicode_character_planes Plano Multilingue Básico].",
- 'config-mysql-charset-mismatch' => "'''Aviso:''' pediu o esquema ''(schema)'' $1, mas a base de dados existente usa o esquema $2. Este código de actualização não pode fazer a conversão, por isso permanecerá como $2.",
'config-site-name' => 'Nome da wiki:',
'config-site-name-help' => 'Este nome aparecerá no título da janela do seu browser e em vários outros sítios.',
'config-site-name-blank' => 'Introduza o nome do site.',
'config-mysql-engine-help' => "'''InnoDB''' почти всегда предпочтительнее, так как он лучше справляется с параллельным доступом.
'''MyISAM''' может оказаться быстрее для вики с одним пользователем или с минимальным количеством поступающих правок, однако базы данных на нём портятся чаще, чем на InnoDB.",
- 'config-mysql-egine-mismatch' => "'''Внимание:''' Вы запросили метод хранения $1, однако существующая база данных использует $2.
-Этот сценарий обновления не может изменить преобразовать его и поэтому метод хранения останется $2.",
'config-mysql-charset' => 'Набор символов (кодовая таблица) базы данных:',
'config-mysql-binary' => 'Двоичный',
'config-mysql-utf8' => 'UTF-8',
Это более эффективно, чем ''UTF-8 режим'' MySQL, и позволяет использовать полный набор символов Unicode.
В '''режиме UTF-8''' MySQL будет знать в какой кодировке находятся Ваши данные и может отображать и преобразовывать их соответствующим образом, но это не позволит вам хранить символы выше [http://en.wikipedia.org/wiki/Mapping_of_Unicode_character_planes Базовой Многоязыковой Плоскости].",
- 'config-mysql-charset-mismatch' => "'''Внимание.''' Вы запросили схему $1, но существующая база данных имеет схему $2.
-Этот сценарий обновления не сможет преобразовать схему, она останется типа $2.",
'config-site-name' => 'Название вики:',
'config-site-name-help' => 'Название будет отображаться в заголовке окна браузера и в некоторых других местах вики.',
'config-site-name-blank' => 'Введите название сайта.',
'config-mysql-engine-help' => "'''InnoDB'''通常是最佳选项,因为它对并发操作有着良好的支持。
'''MyISAM'''在单用户或只读环境下可能会有更快的性能表现。但MyISAM数据库出错的概率一般要大于InnoDB数据库。",
- 'config-mysql-egine-mismatch' => "'''警告:'''您选择了使用$1存储引擎,但现有的数据库使用了$2引擎。升级脚本无法转换它,故将保持$2。",
'config-mysql-charset' => '数据库字符集:',
'config-mysql-binary' => '二进制',
'config-mysql-utf8' => 'UTF-8',
'config-mysql-charset-help' => "在'''二进制模式'''下,MediaWiki会将UTF-8编码的文本存于数据库的二进制字段中。相对于MySQL的UTF-8模式,这种方法效率更高,并允许您使用全范围的Unicode字符。
在'''UTF-8模式'''下,MySQL将知道您数据使用的字符集,并能适当地提供和转换内容。但这样做您将无法在数据库中存储[http://zh.wikipedia.org/wiki/基本多文种平面 基本多文种平面]以外的字符。",
- 'config-mysql-charset-mismatch' => "'''警告:'''您选择了使用$1模式,但现有的数据库使用了$2模式。升级脚本无法转换它,故将保持$2。",
'config-site-name' => 'Wiki的名称:',
'config-site-name-help' => '填入的内容会出现在浏览器的标题栏以及其他多处位置中。',
'config-site-name-blank' => '输入网站的名称。',
$this->parserOptions->setExternalLinkTarget( $wgExternalLinkTarget );
}
+ /**
+ * Install step which adds a row to the site_stats table with appropriate
+ * initial values.
+ */
+ public function populateSiteStats( DatabaseInstaller $installer ) {
+ $status = $installer->getConnection();
+ if ( !$status->isOK() ) {
+ return $status;
+ }
+ $status->value->insert( 'site_stats', array(
+ 'ss_row_id' => 1,
+ 'ss_total_views' => 0,
+ 'ss_total_edits' => 0,
+ 'ss_good_articles' => 0,
+ 'ss_total_pages' => 0,
+ 'ss_users' => 0,
+ 'ss_admins' => 0,
+ 'ss_images' => 0 ) );
+ return Status::newGood();
+ }
+
/**
* Exports all wg* variables stored by the installer into global scope.
*/
break;
}
- $text = Http::get( $url . $file );
+ $text = Http::get( $url . $file, array( 'timeout' => 3 ) );
unlink( $dir . $file );
if ( $text == 'exec' ) {
* @param $installer DatabaseInstaller so we can make callbacks
* @return array
*/
- protected function getInstallSteps( DatabaseInstaller &$installer ) {
+ protected function getInstallSteps( DatabaseInstaller $installer ) {
$coreInstallSteps = array(
array( 'name' => 'database', 'callback' => array( $installer, 'setupDatabase' ) ),
array( 'name' => 'tables', 'callback' => array( $installer, 'createTables' ) ),
array( 'name' => 'interwiki', 'callback' => array( $installer, 'populateInterwikiTable' ) ),
+ array( 'name' => 'stats', 'callback' => array( $this, 'populateSiteStats' ) ),
array( 'name' => 'secretkey', 'callback' => array( $this, 'generateSecretKey' ) ),
array( 'name' => 'upgradekey', 'callback' => array( $this, 'generateUpgradeKey' ) ),
array( 'name' => 'sysop', 'callback' => array( $this, 'createSysop' ) ),
$installResults = array();
$installer = $this->getDBInstaller();
$installer->preInstall();
+ $installer->setupSchemaVars();
$steps = $this->getInstallSteps( $installer );
foreach( $steps as $stepObj ) {
$name = $stepObj['name'];
call_user_func_array( $startCB, array( $name ) );
// Perform the callback step
- $status = call_user_func_array( $stepObj['callback'], array( &$installer ) );
+ $status = call_user_func( $stepObj['callback'], $installer );
// Output and save the results
- call_user_func_array( $endCB, array( $name, $status ) );
+ call_user_func( $endCB, $name, $status );
$installResults[$name] = $status;
// If we've hit some sort of fatal, we need to bail.
$user->setEmail( $this->getVar( '_AdminEmail' ) );
}
$user->saveSettings();
+
+ // Update user count
+ $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
+ $ssUpdate->doUpdate();
}
$status = Status::newGood();
*
* @return Status
*/
- protected function createMainpage( DatabaseInstaller &$installer ) {
+ protected function createMainpage( DatabaseInstaller $installer ) {
$status = Status::newGood();
try {
// STUPID STUPID $wgTitle. PST calls getUserSig(), which joyfully
return $status;
}
- public function getConnection() {
+ public function openConnection() {
$status = Status::newGood();
- if( is_null( $this->db ) ) {
- try {
- $this->db = new DatabaseMysql(
- $this->getVar( 'wgDBserver' ),
- $this->getVar( '_InstallUser' ),
- $this->getVar( '_InstallPassword' ),
- false,
- false,
- 0,
- $this->getVar( 'wgDBprefix' )
- );
- $status->value = $this->db;
- } catch ( DBConnectionError $e ) {
- $status->fatal( 'config-connection-error', $e->getMessage() );
- }
- } else {
- $status->value = $this->db;
+ try {
+ $db = new DatabaseMysql(
+ $this->getVar( 'wgDBserver' ),
+ $this->getVar( '_InstallUser' ),
+ $this->getVar( '_InstallPassword' ),
+ false,
+ false,
+ 0,
+ $this->getVar( 'wgDBprefix' )
+ );
+ $status->value = $db;
+ } catch ( DBConnectionError $e ) {
+ $status->fatal( 'config-connection-error', $e->getMessage() );
}
return $status;
}
if ( preg_match( '/^latin1/', $row->Collation ) ) {
$existingSchema = 'mysql4';
} elseif ( preg_match( '/^utf8/', $row->Collation ) ) {
- $existingSchema = 'mysql5';
+ $existingSchema = 'utf8';
} elseif ( preg_match( '/^binary/', $row->Collation ) ) {
- $existingSchema = 'mysql5-binary';
+ $existingSchema = 'binary';
} else {
$existingSchema = false;
$this->parent->showMessage( 'config-unknown-collation' );
}
if ( $existingSchema && $existingSchema != $this->getVar( '_MysqlCharset' ) ) {
- $this->parent->showMessage( 'config-mysql-charset-mismatch', $this->getVar( '_MysqlCharset' ), $existingSchema );
$this->setVar( '_MysqlCharset', $existingSchema );
}
if ( $existingEngine && $existingEngine != $this->getVar( '_MysqlEngine' ) ) {
- $this->parent->showMessage( 'config-mysql-egine-mismatch', $this->getVar( '_MysqlEngine' ), $existingEngine );
$this->setVar( '_MysqlEngine', $existingEngine );
}
return $status;
}
- public function getTableOptions() {
- return array( 'engine' => $this->getVar( '_MysqlEngine' ),
- 'default charset' => $this->getVar( '_MysqlCharset' ) );
+ /**
+ * Return any table options to be applied to all tables that don't
+ * override them.
+ *
+ * @return String
+ */
+ protected function getTableOptions() {
+ $options = array();
+ if ( $this->getVar( '_MysqlEngine' ) !== null ) {
+ $options[] = "ENGINE=" . $this->getVar( '_MysqlEngine' );
+ }
+ if ( $this->getVar( '_MysqlCharset' ) !== null ) {
+ $options[] = 'DEFAULT CHARSET=' . $this->getVar( '_MysqlCharset' );
+ }
+ return implode( ', ', $options );
+ }
+
+ /**
+ * Get variables to substitute into tables.sql and the SQL patch files.
+ */
+ public function getSchemaVars() {
+ return array(
+ 'wgDBTableOptions' => $this->getTableOptions(),
+ );
}
public function getLocalSettings() {
$dbmysql5 = wfBoolToStr( $this->getVar( 'wgDBmysql5', true ) );
- $prefix = $this->getVar( 'wgDBprefix' );
- $opts = $this->getTableOptions();
- $tblOpts = "ENGINE=" . $opts['engine'] . ', DEFAULT CHARSET=' . $opts['default charset'];
+ $prefix = LocalSettingsGenerator::escapePhpString( $this->getVar( 'wgDBprefix' ) );
+ $tblOpts = LocalSettingsGenerator::escapePhpString( $this->getTableOptions() );
return
"# MySQL specific settings
\$wgDBprefix = \"{$prefix}\";
return $status;
}
- public function getConnection() {
+ public function openConnection() {
$status = Status::newGood();
try {
if ( $this->useSysDBA ) {
- $this->db = new DatabaseOracle(
+ $db = new DatabaseOracle(
$this->getVar( 'wgDBserver' ),
$this->getVar( '_InstallUser' ),
$this->getVar( '_InstallPassword' ),
$this->getVar( 'wgDBprefix' )
);
} else {
- $this->db = new DatabaseOracle(
+ $db = new DatabaseOracle(
$this->getVar( 'wgDBserver' ),
$this->getVar( 'wgDBuser' ),
$this->getVar( 'wgDBpassword' ),
$this->getVar( 'wgDBprefix' )
);
}
- $status->value = $this->db;
+ $status->value = $db;
} catch ( DBConnectionError $e ) {
$status->fatal( 'config-connection-error', $e->getMessage() );
}
}
if ( !$this->db->selectDB( $this->getVar( 'wgDBuser' ) ) ) {
- /**
- * The variables $_OracleDefTS, $_OracleTempTS are used by maintenance/oracle/user.sql
- * Set here for fetching in DatabaseOracle::replaceVars()
- */
- $GLOBALS['_OracleDefTS'] = $this->getVar( '_OracleDefTS' );
- $GLOBALS['_OracleTempTS'] = $this->getVar( '_OracleTempTS' );
$this->db->setFlag( DBO_DDLMODE );
$error = $this->db->sourceFile( "$IP/maintenance/oracle/user.sql" );
if ( $error !== true || !$this->db->selectDB( $this->getVar( 'wgDBuser' ) ) ) {
return $status;
}
+ public function getSchemaVars() {
+ /**
+ * The variables $_OracleDefTS, $_OracleTempTS are used by maintenance/oracle/user.sql
+ */
+ return array(
+ '_OracleDefTS' => $this->getVar( '_OracleDefTS' ),
+ '_OracleTempTS' => $this->getVar( '_OracleTempTS' ),
+ );
+ }
public function getLocalSettings() {
$prefix = $this->getVar( 'wgDBprefix' );
return $status;
}
- function getConnection($database = 'template1') {
+ function openConnection( $database = 'template1' ) {
$status = Status::newGood();
- if( is_null( $this->db ) ) {
- try {
- $this->db = new DatabasePostgres(
- $this->getVar( 'wgDBserver' ),
- $this->getVar( '_InstallUser' ),
- $this->getVar( '_InstallPassword' ),
- $database );
- $status->value = $this->db;
- } catch ( DBConnectionError $e ) {
- $status->fatal( 'config-connection-error', $e->getMessage() );
- }
- } else {
- $status->value = $this->db;
+ try {
+ $db = new DatabasePostgres(
+ $this->getVar( 'wgDBserver' ),
+ $this->getVar( '_InstallUser' ),
+ $this->getVar( '_InstallPassword' ),
+ $database );
+ $status->value = $db;
+ } catch ( DBConnectionError $e ) {
+ $status->fatal( 'config-connection-error', $e->getMessage() );
}
return $status;
}
return Status::newGood();
}
- public function getConnection() {
+ public function openConnection() {
global $wgSQLiteDataDir;
$status = Status::newGood();
- if( is_null( $this->db ) ) {
- $dir = $this->getVar( 'wgSQLiteDataDir' );
- $dbName = $this->getVar( 'wgDBname' );
-
- try {
- # FIXME: need more sensible constructor parameters, e.g. single associative array
- # Setting globals kind of sucks
- $wgSQLiteDataDir = $dir;
- $this->db = new DatabaseSqlite( false, false, false, $dbName );
- $status->value = $this->db;
- } catch ( DBConnectionError $e ) {
- $status->fatal( 'config-sqlite-connection-error', $e->getMessage() );
- }
- } else {
- $status->value = $this->db;
+ $dir = $this->getVar( 'wgSQLiteDataDir' );
+ $dbName = $this->getVar( 'wgDBname' );
+ try {
+ # FIXME: need more sensible constructor parameters, e.g. single associative array
+ # Setting globals kind of sucks
+ $wgSQLiteDataDir = $dir;
+ $db = new DatabaseSqlite( false, false, false, $dbName );
+ $status->value = $db;
+ } catch ( DBConnectionError $e ) {
+ $status->fatal( 'config-sqlite-connection-error', $e->getMessage() );
}
return $status;
}