Go to the documentation of this file.
48 global $wgSharedDB, $wgSQLiteDataDir;
50 if ( !is_array( $p ) ) {
51 wfDeprecated( __METHOD__ .
" method called without parameter array.",
"1.22" );
52 $args = func_get_args();
54 'host' => isset(
$args[0] ) ?
$args[0] :
false,
55 'user' => isset(
$args[1] ) ?
$args[1] :
false,
56 'password' => isset(
$args[2] ) ?
$args[2] :
false,
57 'dbname' => isset(
$args[3] ) ?
$args[3] :
false,
59 'tablePrefix' => isset(
$args[5] ) ?
$args[5] :
'get from global',
60 'schema' =>
'get from global',
61 'foreign' => isset(
$args[6] ) ?
$args[6] :
false
64 $this->mDBname = $p[
'dbname'];
65 parent::__construct( $p );
67 if ( $p[
'dbname'] && !$this->
isOpen() ) {
68 if ( $this->
open( $p[
'host'], $p[
'user'], $p[
'password'], $p[
'dbname'] ) ) {
75 $this->lockMgr =
new FSLockManager(
array(
'lockDirectory' =>
"$wgSQLiteDataDir/locks" ) );
110 if ( !is_readable( $fileName ) ) {
111 $this->mConn =
false;
129 $this->mDatabaseFile = $fileName;
132 $this->mConn =
new PDO(
"sqlite:$fileName",
'',
'',
133 array( PDO::ATTR_PERSISTENT =>
true ) );
135 $this->mConn =
new PDO(
"sqlite:$fileName",
'',
'' );
137 }
catch ( PDOException
$e ) {
138 $err =
$e->getMessage();
141 if ( !$this->mConn ) {
142 wfDebug(
"DB connection error: $err\n" );
147 # set error codes only, don't raise exceptions
148 if ( $this->mOpened ) {
149 $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
150 # Enforce LIKE to be case sensitive, just like MySQL
151 $this->
query(
'PRAGMA case_sensitive_like = 1' );
176 return "$dir/$dbName.sqlite";
184 if ( self::$fulltextEnabled ===
null ) {
185 self::$fulltextEnabled =
false;
186 $table = $this->
tableName(
'searchindex' );
187 $res = $this->
query(
"SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
189 $row =
$res->fetchRow();
190 self::$fulltextEnabled = stristr( $row[
'sql'],
'fts' ) !==
false;
202 static $cachedResult =
null;
203 if ( $cachedResult !==
null ) {
204 return $cachedResult;
206 $cachedResult =
false;
207 $table =
'dummy_search_test';
211 if ( $db->query(
"CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__,
true ) ) {
212 $cachedResult =
'FTS3';
216 return $cachedResult;
237 return $this->
query(
"ATTACH DATABASE $file AS $name",
$fname );
247 return parent::isWriteQuery( $sql ) && !preg_match(
'/^ATTACH\b/i', $sql );
256 protected function doQuery( $sql ) {
257 $res = $this->mConn->query( $sql );
258 if (
$res ===
false ) {
262 $this->mAffectedRows = $r->rowCount();
291 $cur = current( $r );
292 if ( is_array( $cur ) ) {
295 foreach ( $cur
as $k => $v ) {
296 if ( !is_numeric( $k ) ) {
317 $cur = current( $r );
318 if ( is_array( $cur ) ) {
346 return is_array( $r ) ? count( $r[0] ) : 0;
356 if ( is_array( $r ) ) {
357 $keys = array_keys( $r[0] );
374 if ( strpos(
$name,
'sqlite_' ) === 0 ) {
398 return intval( $this->mConn->lastInsertId() );
413 for ( $i = 0; $i < $row; $i++ ) {
423 if ( !is_object( $this->mConn ) ) {
424 return "Cannot return last error, no db connection";
426 $e = $this->mConn->errorInfo();
428 return isset(
$e[2] ) ?
$e[2] :
'';
435 if ( !is_object( $this->mConn ) ) {
436 return "Cannot return last error, no db connection";
438 $info = $this->mConn->errorInfo();
467 if (
$res->numRows() == 0 ) {
471 foreach (
$res as $row ) {
472 $info[] = $row->name;
485 $row = $this->
selectRow(
'sqlite_master',
'*',
490 if ( !$row || !isset( $row->sql ) ) {
495 $indexPos = strpos( $row->sql,
'INDEX' );
496 if ( $indexPos ===
false ) {
499 $firstPart = substr( $row->sql, 0, $indexPos );
500 $options = explode(
' ', $firstPart );
502 return in_array(
'UNIQUE',
$options );
513 if ( is_numeric( $k ) && ( $v ==
'FOR UPDATE' || $v ==
'LOCK IN SHARE MODE' ) ) {
518 return parent::makeSelectOptions(
$options );
537 # SQLite uses OR IGNORE not just IGNORE
539 if ( $v ==
'IGNORE' ) {
554 return parent::makeInsertOptions(
$options );
566 if ( !count( $a ) ) {
570 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
571 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
573 foreach ( $a
as $v ) {
592 function replace( $table, $uniqueIndexes, $rows,
$fname = __METHOD__ ) {
593 if ( !count( $rows ) ) {
597 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
598 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
600 foreach ( $rows
as $v ) {
601 if ( !$this->
nativeReplace( $table, $v,
"$fname/multi-row" ) ) {
637 $glue = $all ?
' UNION ALL ' :
' UNION ';
639 return implode( $glue, $sqls );
667 return "[{{int:version-db-sqlite-url}} SQLite]";
674 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
683 return wfMessage( self::getFulltextSearchModule()
698 $sql =
'PRAGMA table_info(' . $this->
addQuotes( $tableName ) .
')';
700 foreach (
$res as $row ) {
701 if ( $row->name == $field ) {
710 if ( $this->mTrxLevel == 1 ) {
711 $this->
commit( __METHOD__ );
714 $this->mConn->beginTransaction();
715 }
catch ( PDOException
$e ) {
718 $this->mTrxLevel = 1;
722 if ( $this->mTrxLevel == 0 ) {
726 $this->mConn->commit();
727 }
catch ( PDOException
$e ) {
730 $this->mTrxLevel = 0;
734 if ( $this->mTrxLevel == 0 ) {
737 $this->mConn->rollBack();
738 $this->mTrxLevel = 0;
754 return new Blob( $b );
762 if ( $b instanceof
Blob ) {
774 if (
$s instanceof
Blob ) {
775 return "x'" . bin2hex(
$s->fetch() ) .
"'";
776 } elseif ( is_bool(
$s ) ) {
778 } elseif ( strpos(
$s,
"\0" ) !==
false ) {
785 return "x'" . bin2hex(
$s ) .
"'";
787 return $this->mConn->quote(
$s );
800 return parent::buildLike(
$params ) .
"ESCAPE '\' ";
807 return "SearchSqlite";
816 $args = func_get_args();
817 $function = array_shift(
$args );
819 return call_user_func_array( $function,
$args );
827 $s = parent::replaceVars(
$s );
828 if ( preg_match(
'/^\s*(CREATE|ALTER) TABLE/i',
$s ) ) {
832 $s = preg_replace(
'/\b(var)?binary(\(\d+\))/i',
'BLOB',
$s );
834 $s = preg_replace(
'/\b(un)?signed\b/i',
'',
$s );
836 $s = preg_replace(
'/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i',
'INTEGER',
$s );
839 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
844 $s = preg_replace(
'/\b(var)?char\s*\(.*?\)/i',
'TEXT',
$s );
846 $s = preg_replace(
'/\b(tiny|medium|long)text\b/i',
'TEXT',
$s );
848 $s = preg_replace(
'/\b(tiny|small|medium|long|)blob\b/i',
'BLOB',
$s );
850 $s = preg_replace(
'/\bbool(ean)?\b/i',
'INTEGER',
$s );
852 $s = preg_replace(
'/\b(datetime|timestamp)\b/i',
'TEXT',
$s );
854 $s = preg_replace(
'/\benum\s*\([^)]*\)/i',
'TEXT',
$s );
856 $s = preg_replace(
'/\bbinary\b/i',
'',
$s );
858 $s = preg_replace(
'/\bauto_increment\b/i',
'AUTOINCREMENT',
$s );
860 $s = preg_replace(
'/\)[^);]*(;?)\s*$/',
')\1',
$s );
862 $s = preg_replace(
'/primary key (.*?) autoincrement/i',
'PRIMARY KEY AUTOINCREMENT $1',
$s );
863 } elseif ( preg_match(
'/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i',
$s ) ) {
865 $s = preg_replace(
'/\(\d+\)/',
'',
$s );
867 $s = preg_replace(
'/\bfulltext\b/i',
'',
$s );
868 } elseif ( preg_match(
'/^\s*DROP INDEX/i',
$s ) ) {
870 $s = preg_replace(
'/\sON\s+[^\s]*/i',
'',
$s );
876 public function lock( $lockName, $method, $timeout = 5 ) {
879 if ( !is_dir(
"$wgSQLiteDataDir/locks" ) ) {
880 if ( !is_writable( $wgSQLiteDataDir ) || !mkdir(
"$wgSQLiteDataDir/locks" ) ) {
881 throw new DBError(
"Cannot create directory \"$wgSQLiteDataDir/locks\"." );
888 public function unlock( $lockName, $method ) {
899 return '(' . implode(
') || (', $stringList ) .
')';
903 $delim, $table, $field, $conds =
'', $join_conds =
array()
905 $fld =
"group_concat($field," . $this->
addQuotes( $delim ) .
')';
907 return '(' . $this->
selectSQLText( $table, $fld, $conds,
null,
array(), $join_conds ) .
')';
919 $res = $this->
query(
"SELECT sql FROM sqlite_master WHERE tbl_name=" .
923 throw new MWException(
"Couldn't retrieve structure for table $oldName" );
927 '/(?<=\W)"?' . preg_quote( trim( $this->
addIdentifierQuotes( $oldName ),
'"' ) ) .
'"?(?=\W)/',
933 if ( preg_match(
'/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
934 wfDebug(
"Table $oldName is virtual, can't create a temporary duplicate.\n" );
936 $sql = str_replace(
'CREATE TABLE',
'CREATE TEMPORARY TABLE', $sql );
961 $vars = get_object_vars( $table );
962 $table = array_pop(
$vars );
964 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
965 if ( strpos( $table,
'sqlite_' ) !== 0 ) {
966 $endArray[] = $table;
999 return $this->info->name;
1007 if ( is_string( $this->info->dflt_value ) ) {
1009 if ( preg_match(
'/^\'(.*)\'$', $this->info->dflt_value ) ) {
1010 return str_replace(
"''",
"'", $this->info->dflt_value );
1014 return $this->info->dflt_value;
1021 return !$this->info->notnull;
1025 return $this->info->type;
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. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. $reader:XMLReader object $logInfo:Array of information Return false to stop further processing of the tag 'ImportHandlePageXMLTag':When parsing a XML tag in a page. $reader:XMLReader object $pageInfo:Array of information Return false to stop further processing of the tag 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information Return false to stop further processing of the tag 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. $reader:XMLReader object Return false to stop further processing of the tag 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. $reader:XMLReader object $revisionInfo:Array of information Return false to stop further processing of the tag '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 '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. '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 '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 '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 wfIsTrustedProxy() $ip:IP being check $result:Change this value to override the result of wfIsTrustedProxy() '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 User::isValidEmailAddr(), 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 'LanguageGetMagic':DEPRECATED, use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetSpecialPageAliases':DEPRECATED, use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language $specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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:Associative array mapping language codes to prefixed links of the form "language:title". & $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. 'LinkBegin':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
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
attachDatabase( $name, $file=false, $fname=__METHOD__)
Attaches external database to our connection, see http://sqlite.org/lang_attach.html for details.
unlock( $lockName, $method)
Release a lock.
Simple version of LockManager based on using FS lock files.
unionSupportsOrderAndLimit()
Base for all database-specific classes representing information about database fields.
FSLockManager $lockMgr
(hopefully on the same server as the DB) *
doQuery( $sql)
SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result.
close()
Closes a database connection.
query( $sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
replace( $table, $uniqueIndexes, $rows, $fname=__METHOD__)
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
This class allows simple acccess to a SQLite database independently from main database settings.
indexName( $index)
Index names have DB scope.
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
closeConnection()
Does not actually close the connection, just destroys the reference for GC to do its work.
tableName( $name, $format='quoted')
Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks.
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 an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form externallinks including delete and insert
open( $server, $user, $pass, $dbName)
Open an SQLite database and return a resource handle to it NOTE: only $dbName is used,...
it s the revision text itself In either if gzip is the revision text is gzipped $flags
selectRow( $table, $vars, $conds, $fname=__METHOD__, $options=array(), $join_conds=array())
Single row SELECT wrapper.
static generateFileName( $dir, $dbName)
Generates a database file name.
doCommit( $fname='')
Issues the COMMIT command to the database server.
makeSelectOptions( $options)
Filter the options used in SELECT statements.
tablePrefix( $prefix=null)
Get/set the table prefix.
insert( $table, $a, $fname=__METHOD__, $options=array())
Based on generic method (parent) with some prior SQLite-sepcific adjustments.
doRollback( $fname='')
Issues the ROLLBACK command to the database server.
selectSQLText( $table, $vars, $conds='', $fname=__METHOD__, $options=array(), $join_conds=array())
The equivalent of DatabaseBase::select() except that the constructed SQL is returned,...
__construct( $p=null)
Constructor.
int $mAffectedRows
The number of rows affected as an integer *.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
select( $table, $vars, $conds='', $fname=__METHOD__, $options=array(), $join_conds=array())
Execute a SELECT query constructed using the various parameters provided.
insertId()
This must be called after nextSequenceVal.
deadlockLoop()
No-op version of deadlockLoop.
__construct( $fileName, $flags=0)
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
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 an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form externallinks including delete and has completed for all link tables 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 additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "<
nativeReplace( $table, $rows, $fname)
REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE statement.
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
checkForEnabledSearch()
Check if the searchindext table is FTS enabled.
when a variable name is used in a it is silently declared as a new masking the global
Database error base class.
makeUpdateOptionsArray( $options)
doBegin( $fname='')
Issues the BEGIN command to the database server.
makeInsertOptions( $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 & $options
unionQueries( $sqls, $all)
wfDebug( $text, $dest='all')
Sends a line to the debug log if enabled or, optionally, to a comment in output.
fieldInfo( $table, $field)
Get information about a given field Returns false if the field does not exist.
Allows to change the fields on the form that will be generated $name
Database abstraction object.
lock( $lockName, $method, $timeout=5)
Acquire a named lock.
buildConcat( $stringList)
Build a concatenation list to feed into a SQL query.
textFieldSize( $table, $field)
Returns the size of a text field, or -1 for "unlimited" In SQLite this is SQLITE_MAX_LENGTH,...
openFile( $fileName)
Opens a database file.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
commit( $fname=__METHOD__, $flush='')
Commits a transaction previously started using begin().
if(PHP_SAPI !='cli') $file
tableName()
Name of table this field belongs to.
string $mDatabaseFile
File name for SQLite database file *.
addIdentifierQuotes( $s)
Quotes an identifier using backticks or "double quotes" depending on the database type.
isOpen()
Is a connection to the database open?
if(count( $args)==0) $dir
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
indexUnique( $table, $index, $fname=__METHOD__)
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
__construct( $info, $tableName)
numRows( $res)
The PDO::Statement class implements the array interface so count() will work.
static fixIgnore( $options)
static getFulltextSearchModule()
Returns version of currently supported SQLite fulltext search module or false if none present.
Result wrapper for grabbing data queried by someone else.
buildGroupConcatField( $delim, $table, $field, $conds='', $join_conds=array())
Build a GROUP_CONCAT or equivalent statement for a query.
indexInfo( $table, $index, $fname=__METHOD__)
Returns information about an index Returns false if the index does not exist.