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 $wgOut,$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 * This must be called after nextSequenceVal
162 function insertId() {
163 return $this->mConn
->lastInsertId();
166 function dataSeek($res,$row) {
167 if ($res instanceof ResultWrapper
) $r =& $res->result
; else $r =& $res;
169 if ($row > 0) for ($i = 0; $i < $row; $i++
) next($r);
172 function lastError() {
173 if (!is_object($this->mConn
)) return "Cannot return last error, no db connection";
174 $e = $this->mConn
->errorInfo();
175 return isset($e[2]) ?
$e[2] : '';
178 function lastErrno() {
179 if (!is_object($this->mConn
)) {
180 return "Cannot return last error, no db connection";
182 $info = $this->mConn
->errorInfo();
187 function affectedRows() {
188 return $this->mAffectedRows
;
192 * Returns information about an index
193 * Returns false if the index does not exist
194 * - if errors are explicitly ignored, returns NULL on failure
196 function indexInfo($table, $index, $fname = 'Database::indexExists') {
197 $sql = 'PRAGMA index_info(' . $this->addQuotes( $index ) . ')';
198 $res = $this->query( $sql, $fname );
202 if ( $res->numRows() == 0 ) {
206 foreach ( $res as $row ) {
207 $info[] = $row->name
;
212 function indexUnique($table, $index, $fname = 'Database::indexUnique') {
213 $row = $this->selectRow( 'sqlite_master', '*',
218 if ( !$row ||
!isset( $row->sql
) ) {
222 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
223 $indexPos = strpos( $row->sql
, 'INDEX' );
224 if ( $indexPos === false ) {
227 $firstPart = substr( $row->sql
, 0, $indexPos );
228 $options = explode( ' ', $firstPart );
229 return in_array( 'UNIQUE', $options );
233 * Filter the options used in SELECT statements
235 function makeSelectOptions($options) {
236 foreach ($options as $k => $v) if (is_numeric($k) && $v == 'FOR UPDATE') $options[$k] = '';
237 return parent
::makeSelectOptions($options);
241 * Based on MySQL method (parent) with some prior SQLite-sepcific adjustments
243 function insert($table, $a, $fname = 'DatabaseSqlite::insert', $options = array()) {
244 if (!count($a)) return true;
245 if (!is_array($options)) $options = array($options);
247 # SQLite uses OR IGNORE not just IGNORE
248 foreach ($options as $k => $v) if ($v == 'IGNORE') $options[$k] = 'OR IGNORE';
250 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
251 if (isset($a[0]) && is_array($a[0])) {
253 foreach ($a as $k => $v) if (!parent
::insert($table,$v,"$fname/multi-row",$options)) $ret = false;
255 else $ret = parent
::insert($table,$a,"$fname/single-row",$options);
261 * SQLite does not have a "USE INDEX" clause, so return an empty string
263 function useIndexClause($index) {
268 * Returns the size of a text field, or -1 for "unlimited"
269 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
271 function textFieldSize($table, $field) {
276 * No low priority option in SQLite
278 function lowPriorityOption() {
283 * Returns an SQL expression for a simple conditional.
284 * - uses CASE on SQLite
286 function conditional($cond, $trueVal, $falseVal) {
287 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
290 function wasDeadlock() {
291 return $this->lastErrno() == SQLITE_BUSY
;
294 function wasErrorReissuable() {
295 return $this->lastErrno() == SQLITE_SCHEMA
;
299 * @return string wikitext of a link to the server software's web site
301 function getSoftwareLink() {
302 return "[http://sqlite.org/ SQLite]";
306 * @return string Version information from the database
308 function getServerVersion() {
310 $ver = $this->mConn
->getAttribute(PDO
::ATTR_SERVER_VERSION
);
315 * Query whether a given column exists in the mediawiki schema
317 function fieldExists($table, $field, $fname = '') {
318 $info = $this->fieldInfo( $table, $field );
323 * Get information about a given field
324 * Returns false if the field does not exist.
326 function fieldInfo($table, $field) {
327 $tableName = $this->tableName( $table );
328 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
329 $res = $this->query( $sql, __METHOD__
);
330 foreach ( $res as $row ) {
331 if ( $row->name
== $field ) {
332 return new SQLiteField( $row, $tableName );
338 function begin( $fname = '' ) {
339 if ($this->mTrxLevel
== 1) $this->commit();
340 $this->mConn
->beginTransaction();
341 $this->mTrxLevel
= 1;
344 function commit( $fname = '' ) {
345 if ($this->mTrxLevel
== 0) return;
346 $this->mConn
->commit();
347 $this->mTrxLevel
= 0;
350 function rollback( $fname = '' ) {
351 if ($this->mTrxLevel
== 0) return;
352 $this->mConn
->rollBack();
353 $this->mTrxLevel
= 0;
356 function limitResultForUpdate($sql, $num) {
357 return $this->limitResult( $sql, $num );
360 function strencode($s) {
361 return substr($this->addQuotes($s),1,-1);
364 function encodeBlob($b) {
365 return new Blob( $b );
368 function decodeBlob($b) {
369 if ($b instanceof Blob
) {
375 function addQuotes($s) {
376 if ( $s instanceof Blob
) {
377 return "x'" . bin2hex( $s->fetch() ) . "'";
379 return $this->mConn
->quote($s);
383 function quote_ident($s) { return $s; }
386 * Not possible in SQLite
387 * We have ATTACH_DATABASE but that requires database selectors before the
388 * table names and in any case is really a different concept to MySQL's USE
390 function selectDB($db) {
391 if ( $db != $this->mName
) {
392 throw new MWException( 'selectDB is not implemented in SQLite' );
399 public function setTimeout($timeout) { return; }
402 * No-op for a non-networked database
409 * How lagged is this slave?
411 public function getLag() {
416 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
417 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
419 public function setup_database() {
420 global $IP,$wgSQLiteDataDir,$wgDBTableOptions;
421 $wgDBTableOptions = '';
423 # Process common MySQL/SQLite table definitions
424 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
426 $this->reportQueryError($err,0,$sql,__FUNCTION__
);
430 # Use DatabasePostgres's code to populate interwiki from MySQL template
431 $f = fopen("$IP/maintenance/interwiki.sql",'r');
432 if ($f == false) dieout("<li>Could not find the interwiki.sql file");
433 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
435 $line = fgets($f,1024);
437 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) continue;
438 $this->query("$sql $matches[1],$matches[2])");
443 * No-op lock functions
445 public function lock( $lockName, $method ) {
448 public function unlock( $lockName, $method ) {
452 public function getSearchEngine() {
453 return "SearchEngineDummy";
457 * No-op version of deadlockLoop
459 public function deadlockLoop( /*...*/ ) {
460 $args = func_get_args();
461 $function = array_shift( $args );
462 return call_user_func_array( $function, $args );
465 protected function replaceVars( $s ) {
466 $s = parent
::replaceVars( $s );
467 if ( preg_match( '/^\s*CREATE TABLE/i', $s ) ) {
468 // CREATE TABLE hacks to allow schema file sharing with MySQL
470 // binary/varbinary column type -> blob
471 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'blob\1', $s );
472 // no such thing as unsigned
473 $s = preg_replace( '/\bunsigned\b/i', '', $s );
474 // INT -> INTEGER for primary keys
475 $s = preg_replacE( '/\bint\b/i', 'integer', $s );
477 $s = preg_replace( '/enum\([^)]*\)/i', 'blob', $s );
478 // binary collation type -> nothing
479 $s = preg_replace( '/\bbinary\b/i', '', $s );
480 // auto_increment -> autoincrement
481 $s = preg_replace( '/\bauto_increment\b/i', 'autoincrement', $s );
482 // No explicit options
483 $s = preg_replace( '/\)[^)]*$/', ')', $s );
484 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
485 // No truncated indexes
486 $s = preg_replace( '/\(\d+\)/', '', $s );
488 $s = preg_replace( '/\bfulltext\b/i', '', $s );
493 } // end DatabaseSqlite class
499 private $info, $tableName;
500 function __construct( $info, $tableName ) {
502 $this->tableName
= $tableName;
506 return $this->info
->name
;
509 function tableName() {
510 return $this->tableName
;
513 function defaultValue() {
514 if ( is_string( $this->info
->dflt_value
) ) {
516 if ( preg_match( '/^\'(.*)\'$', $this->info
->dflt_value
) ) {
517 return str_replace( "''", "'", $this->info
->dflt_value
);
520 return $this->info
->dflt_value
;
523 function maxLength() {
527 function nullable() {
528 // SQLite dynamic types are always nullable
532 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
533 # Suggest removal from base class [TS]
536 return $this->info
->type
;