3 * This script is the SQLite database abstraction layer
5 * See maintenance/sqlite/README for development notes and other specific information
13 class DatabaseSqlite
extends Database
{
23 function __construct($server = false, $user = false, $password = false, $dbName = false, $failFunction = false, $flags = 0) {
24 global $wgSQLiteDataDir, $wgSQLiteDataDirMode;
25 if ("$wgSQLiteDataDir" == '') $wgSQLiteDataDir = dirname($_SERVER['DOCUMENT_ROOT']).'/data';
26 if (!is_dir($wgSQLiteDataDir)) wfMkdirParents( $wgSQLiteDataDir, $wgSQLiteDataDirMode );
27 $this->mFailFunction
= $failFunction;
28 $this->mFlags
= $flags;
29 $this->mDatabaseFile
= "$wgSQLiteDataDir/$dbName.sqlite";
30 $this->mName
= $dbName;
31 $this->open($server, $user, $password, $dbName);
35 * todo: check if these should be true like parent class
37 function implicitGroupby() { return false; }
38 function implicitOrderby() { return false; }
40 static function newFromParams($server, $user, $password, $dbName, $failFunction = false, $flags = 0) {
41 return new DatabaseSqlite($server, $user, $password, $dbName, $failFunction, $flags);
44 /** Open an SQLite database and return a resource handle to it
45 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
47 function open($server,$user,$pass,$dbName) {
50 $file = $this->mDatabaseFile
;
52 if ( $this->mFlags
& DBO_PERSISTENT
) {
53 $this->mConn
= new PDO( "sqlite:$file", $user, $pass,
54 array( PDO
::ATTR_PERSISTENT
=> true ) );
56 $this->mConn
= new PDO( "sqlite:$file", $user, $pass );
58 } catch ( PDOException
$e ) {
59 $err = $e->getMessage();
61 if ( $this->mConn
=== false ) {
62 wfDebug( "DB connection error: $err\n" );
63 if ( !$this->mFailFunction
) {
64 throw new DBConnectionError( $this, $err );
70 $this->mOpened
= $this->mConn
;
71 # set error codes only, don't raise exceptions
72 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
78 * Close an SQLite database
81 $this->mOpened
= false;
82 if (is_object($this->mConn
)) {
83 if ($this->trxLevel()) $this->immediateCommit();
90 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
92 function doQuery($sql) {
93 $res = $this->mConn
->query($sql);
97 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
98 $this->mAffectedRows
= $r->rowCount();
99 $res = new ResultWrapper($this,$r->fetchAll());
104 function freeResult($res) {
105 if ($res instanceof ResultWrapper
) $res->result
= NULL; else $res = NULL;
108 function fetchObject($res) {
109 if ($res instanceof ResultWrapper
) $r =& $res->result
; else $r =& $res;
111 if (is_array($cur)) {
114 foreach ($cur as $k => $v) if (!is_numeric($k)) $obj->$k = $v;
120 function fetchRow($res) {
121 if ($res instanceof ResultWrapper
) $r =& $res->result
; else $r =& $res;
123 if (is_array($cur)) {
131 * The PDO::Statement class implements the array interface so count() will work
133 function numRows($res) {
134 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
138 function numFields($res) {
139 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
140 return is_array($r) ?
count($r[0]) : 0;
143 function fieldName($res,$n) {
144 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
146 $keys = array_keys($r[0]);
153 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
155 function tableName($name) {
156 return str_replace('`','',parent
::tableName($name));
160 * Index names have DB scope
162 function indexName( $index ) {
167 * This must be called after nextSequenceVal
169 function insertId() {
170 return $this->mConn
->lastInsertId();
173 function dataSeek($res,$row) {
174 if ($res instanceof ResultWrapper
) $r =& $res->result
; else $r =& $res;
176 if ($row > 0) for ($i = 0; $i < $row; $i++
) next($r);
179 function lastError() {
180 if (!is_object($this->mConn
)) return "Cannot return last error, no db connection";
181 $e = $this->mConn
->errorInfo();
182 return isset($e[2]) ?
$e[2] : '';
185 function lastErrno() {
186 if (!is_object($this->mConn
)) {
187 return "Cannot return last error, no db connection";
189 $info = $this->mConn
->errorInfo();
194 function affectedRows() {
195 return $this->mAffectedRows
;
199 * Returns information about an index
200 * Returns false if the index does not exist
201 * - if errors are explicitly ignored, returns NULL on failure
203 function indexInfo($table, $index, $fname = 'Database::indexExists') {
204 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
205 $res = $this->query( $sql, $fname );
209 if ( $res->numRows() == 0 ) {
213 foreach ( $res as $row ) {
214 $info[] = $row->name
;
219 function indexUnique($table, $index, $fname = 'Database::indexUnique') {
220 $row = $this->selectRow( 'sqlite_master', '*',
223 'name' => $this->indexName( $index ),
225 if ( !$row ||
!isset( $row->sql
) ) {
229 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
230 $indexPos = strpos( $row->sql
, 'INDEX' );
231 if ( $indexPos === false ) {
234 $firstPart = substr( $row->sql
, 0, $indexPos );
235 $options = explode( ' ', $firstPart );
236 return in_array( 'UNIQUE', $options );
240 * Filter the options used in SELECT statements
242 function makeSelectOptions($options) {
243 foreach ($options as $k => $v) if (is_numeric($k) && $v == 'FOR UPDATE') $options[$k] = '';
244 return parent
::makeSelectOptions($options);
248 * Based on MySQL method (parent) with some prior SQLite-sepcific adjustments
250 function insert($table, $a, $fname = 'DatabaseSqlite::insert', $options = array()) {
251 if (!count($a)) return true;
252 if (!is_array($options)) $options = array($options);
254 # SQLite uses OR IGNORE not just IGNORE
255 foreach ($options as $k => $v) if ($v == 'IGNORE') $options[$k] = 'OR IGNORE';
257 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
258 if (isset($a[0]) && is_array($a[0])) {
260 foreach ($a as $k => $v) if (!parent
::insert($table,$v,"$fname/multi-row",$options)) $ret = false;
262 else $ret = parent
::insert($table,$a,"$fname/single-row",$options);
268 * SQLite does not have a "USE INDEX" clause, so return an empty string
270 function useIndexClause($index) {
275 * Returns the size of a text field, or -1 for "unlimited"
276 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
278 function textFieldSize($table, $field) {
283 * No low priority option in SQLite
285 function lowPriorityOption() {
290 * Returns an SQL expression for a simple conditional.
291 * - uses CASE on SQLite
293 function conditional($cond, $trueVal, $falseVal) {
294 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
297 function wasDeadlock() {
298 return $this->lastErrno() == SQLITE_BUSY
;
301 function wasErrorReissuable() {
302 return $this->lastErrno() == SQLITE_SCHEMA
;
306 * @return string wikitext of a link to the server software's web site
308 function getSoftwareLink() {
309 return "[http://sqlite.org/ SQLite]";
313 * @return string Version information from the database
315 function getServerVersion() {
317 $ver = $this->mConn
->getAttribute(PDO
::ATTR_SERVER_VERSION
);
322 * Query whether a given column exists in the mediawiki schema
324 function fieldExists($table, $field, $fname = '') {
325 $info = $this->fieldInfo( $table, $field );
330 * Get information about a given field
331 * Returns false if the field does not exist.
333 function fieldInfo($table, $field) {
334 $tableName = $this->tableName( $table );
335 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
336 $res = $this->query( $sql, __METHOD__
);
337 foreach ( $res as $row ) {
338 if ( $row->name
== $field ) {
339 return new SQLiteField( $row, $tableName );
345 function begin( $fname = '' ) {
346 if ($this->mTrxLevel
== 1) $this->commit();
347 $this->mConn
->beginTransaction();
348 $this->mTrxLevel
= 1;
351 function commit( $fname = '' ) {
352 if ($this->mTrxLevel
== 0) return;
353 $this->mConn
->commit();
354 $this->mTrxLevel
= 0;
357 function rollback( $fname = '' ) {
358 if ($this->mTrxLevel
== 0) return;
359 $this->mConn
->rollBack();
360 $this->mTrxLevel
= 0;
363 function limitResultForUpdate($sql, $num) {
364 return $this->limitResult( $sql, $num );
367 function strencode($s) {
368 return substr($this->addQuotes($s),1,-1);
371 function encodeBlob($b) {
372 return new Blob( $b );
375 function decodeBlob($b) {
376 if ($b instanceof Blob
) {
382 function addQuotes($s) {
383 if ( $s instanceof Blob
) {
384 return "x'" . bin2hex( $s->fetch() ) . "'";
386 return $this->mConn
->quote($s);
390 function quote_ident($s) { return $s; }
393 * Not possible in SQLite
394 * We have ATTACH_DATABASE but that requires database selectors before the
395 * table names and in any case is really a different concept to MySQL's USE
397 function selectDB($db) {
398 if ( $db != $this->mName
) {
399 throw new MWException( 'selectDB is not implemented in SQLite' );
406 public function setTimeout($timeout) { return; }
409 * No-op for a non-networked database
416 * How lagged is this slave?
418 public function getLag() {
423 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
424 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
426 public function setup_database() {
427 global $IP,$wgSQLiteDataDir,$wgDBTableOptions;
428 $wgDBTableOptions = '';
430 # Process common MySQL/SQLite table definitions
431 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
433 $this->reportQueryError($err,0,$sql,__FUNCTION__
);
437 # Use DatabasePostgres's code to populate interwiki from MySQL template
438 $f = fopen("$IP/maintenance/interwiki.sql",'r');
439 if ($f == false) dieout("<li>Could not find the interwiki.sql file");
440 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
442 $line = fgets($f,1024);
444 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) continue;
445 $this->query("$sql $matches[1],$matches[2])");
450 * No-op lock functions
452 public function lock( $lockName, $method ) {
455 public function unlock( $lockName, $method ) {
459 public function getSearchEngine() {
460 return "SearchEngineDummy";
464 * No-op version of deadlockLoop
466 public function deadlockLoop( /*...*/ ) {
467 $args = func_get_args();
468 $function = array_shift( $args );
469 return call_user_func_array( $function, $args );
472 protected function replaceVars( $s ) {
473 $s = parent
::replaceVars( $s );
474 if ( preg_match( '/^\s*CREATE TABLE/i', $s ) ) {
475 // CREATE TABLE hacks to allow schema file sharing with MySQL
477 // binary/varbinary column type -> blob
478 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'blob\1', $s );
479 // no such thing as unsigned
480 $s = preg_replace( '/\bunsigned\b/i', '', $s );
481 // INT -> INTEGER for primary keys
482 $s = preg_replacE( '/\bint\b/i', 'integer', $s );
484 $s = preg_replace( '/enum\([^)]*\)/i', 'blob', $s );
485 // binary collation type -> nothing
486 $s = preg_replace( '/\bbinary\b/i', '', $s );
487 // auto_increment -> autoincrement
488 $s = preg_replace( '/\bauto_increment\b/i', 'autoincrement', $s );
489 // No explicit options
490 $s = preg_replace( '/\)[^)]*$/', ')', $s );
491 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
492 // No truncated indexes
493 $s = preg_replace( '/\(\d+\)/', '', $s );
495 $s = preg_replace( '/\bfulltext\b/i', '', $s );
500 } // end DatabaseSqlite class
506 private $info, $tableName;
507 function __construct( $info, $tableName ) {
509 $this->tableName
= $tableName;
513 return $this->info
->name
;
516 function tableName() {
517 return $this->tableName
;
520 function defaultValue() {
521 if ( is_string( $this->info
->dflt_value
) ) {
523 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
524 return str_replace( "''", "'", $this->info
->dflt_value
);
527 return $this->info
->dflt_value
;
530 function maxLength() {
534 function nullable() {
535 // SQLite dynamic types are always nullable
539 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
540 # Suggest removal from base class [TS]
543 return $this->info
->type
;