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
{
22 function __construct($server = false, $user = false, $password = false, $dbName = false, $failFunction = false, $flags = 0) {
23 global $wgOut,$wgSQLiteDataDir, $wgSQLiteDataDirMode;
24 if ("$wgSQLiteDataDir" == '') $wgSQLiteDataDir = dirname($_SERVER['DOCUMENT_ROOT']).'/data';
25 if (!is_dir($wgSQLiteDataDir)) wfMkdirParents( $wgSQLiteDataDir, $wgSQLiteDataDirMode );
26 $this->mFailFunction
= $failFunction;
27 $this->mFlags
= $flags;
28 $this->mDatabaseFile
= "$wgSQLiteDataDir/$dbName.sqlite";
29 $this->open($server, $user, $password, $dbName);
33 * todo: check if these should be true like parent class
35 function implicitGroupby() { return false; }
36 function implicitOrderby() { return false; }
38 static function newFromParams($server, $user, $password, $dbName, $failFunction = false, $flags = 0) {
39 return new DatabaseSqlite($server, $user, $password, $dbName, $failFunction, $flags);
42 /** Open an SQLite database and return a resource handle to it
43 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
45 function open($server,$user,$pass,$dbName) {
48 $file = $this->mDatabaseFile
;
50 if ( $this->mFlags
& DBO_PERSISTENT
) {
51 $this->mConn
= new PDO( "sqlite:$file", $user, $pass,
52 array( PDO
::ATTR_PERSISTENT
=> true ) );
54 $this->mConn
= new PDO( "sqlite:$file", $user, $pass );
56 } catch ( PDOException
$e ) {
57 $err = $e->getMessage();
59 if ( $this->mConn
=== false ) {
60 wfDebug( "DB connection error: $err\n" );
61 if ( !$this->mFailFunction
) {
62 throw new DBConnectionError( $this, $err );
68 $this->mOpened
= $this->mConn
;
69 # set error codes only, don't raise exceptions
70 $this->mConn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
76 * Close an SQLite database
79 $this->mOpened
= false;
80 if (is_object($this->mConn
)) {
81 if ($this->trxLevel()) $this->immediateCommit();
88 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
90 function doQuery($sql) {
91 $res = $this->mConn
->query($sql);
92 if ($res === false) $this->reportQueryError($this->lastError(),$this->lastErrno(),$sql,__FUNCTION__
);
94 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
95 $this->mAffectedRows
= $r->rowCount();
96 $res = new ResultWrapper($this,$r->fetchAll());
101 function freeResult(&$res) {
102 if ($res instanceof ResultWrapper
) $res->result
= NULL; else $res = NULL;
105 function fetchObject(&$res) {
106 if ($res instanceof ResultWrapper
) $r =& $res->result
; else $r =& $res;
108 if (is_array($cur)) {
111 foreach ($cur as $k => $v) if (!is_numeric($k)) $obj->$k = $v;
117 function fetchRow(&$res) {
118 if ($res instanceof ResultWrapper
) $r =& $res->result
; else $r =& $res;
120 if (is_array($cur)) {
128 * The PDO::Statement class implements the array interface so count() will work
130 function numRows(&$res) {
131 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
135 function numFields(&$res) {
136 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
137 return is_array($r) ?
count($r[0]) : 0;
140 function fieldName(&$res,$n) {
141 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
143 $keys = array_keys($r[0]);
150 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
152 function tableName($name) {
153 return str_replace('`','',parent
::tableName($name));
157 * This must be called after nextSequenceVal
159 function insertId() {
160 return $this->mConn
->lastInsertId();
163 function dataSeek(&$res,$row) {
164 if ($res instanceof ResultWrapper
) $r =& $res->result
; else $r =& $res;
166 if ($row > 0) for ($i = 0; $i < $row; $i++
) next($r);
169 function lastError() {
170 if (!is_object($this->mConn
)) return "Cannot return last error, no db connection";
171 $e = $this->mConn
->errorInfo();
172 return isset($e[2]) ?
$e[2] : '';
175 function lastErrno() {
176 if (!is_object($this->mConn
)) return "Cannot return last error, no db connection";
177 return $this->mConn
->errorCode();
180 function affectedRows() {
181 return $this->mAffectedRows
;
185 * Returns information about an index
186 * - if errors are explicitly ignored, returns NULL on failure
188 function indexInfo($table, $index, $fname = 'Database::indexExists') {
192 function indexUnique($table, $index, $fname = 'Database::indexUnique') {
197 * Filter the options used in SELECT statements
199 function makeSelectOptions($options) {
200 foreach ($options as $k => $v) if (is_numeric($k) && $v == 'FOR UPDATE') $options[$k] = '';
201 return parent
::makeSelectOptions($options);
205 * Based on MySQL method (parent) with some prior SQLite-sepcific adjustments
207 function insert($table, $a, $fname = 'DatabaseSqlite::insert', $options = array()) {
208 if (!count($a)) return true;
209 if (!is_array($options)) $options = array($options);
211 # SQLite uses OR IGNORE not just IGNORE
212 foreach ($options as $k => $v) if ($v == 'IGNORE') $options[$k] = 'OR IGNORE';
214 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
215 if (isset($a[0]) && is_array($a[0])) {
217 foreach ($a as $k => $v) if (!parent
::insert($table,$v,"$fname/multi-row",$options)) $ret = false;
219 else $ret = parent
::insert($table,$a,"$fname/single-row",$options);
225 * SQLite does not have a "USE INDEX" clause, so return an empty string
227 function useIndexClause($index) {
231 # Returns the size of a text field, or -1 for "unlimited"
232 function textFieldSize($table, $field) {
237 * No low priority option in SQLite
239 function lowPriorityOption() {
244 * Returns an SQL expression for a simple conditional.
245 * - uses CASE on SQLite
247 function conditional($cond, $trueVal, $falseVal) {
248 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
251 function wasDeadlock() {
252 return $this->lastErrno() == SQLITE_BUSY
;
256 * @return string wikitext of a link to the server software's web site
258 function getSoftwareLink() {
259 return "[http://sqlite.org/ SQLite]";
263 * @return string Version information from the database
265 function getServerVersion() {
267 $ver = $this->mConn
->getAttribute(PDO
::ATTR_SERVER_VERSION
);
268 $size = $wgContLang->formatSize(filesize($this->mDatabaseFile
));
269 $file = basename($this->mDatabaseFile
);
270 return $ver." ($file: $size)";
274 * Query whether a given column exists in the mediawiki schema
276 function fieldExists($table, $field) { return true; }
278 function fieldInfo($table, $field) { return SQLiteField
::fromText($this, $table, $field); }
281 if ($this->mTrxLevel
== 1) $this->commit();
282 $this->mConn
->beginTransaction();
283 $this->mTrxLevel
= 1;
287 if ($this->mTrxLevel
== 0) return;
288 $this->mConn
->commit();
289 $this->mTrxLevel
= 0;
292 function rollback() {
293 if ($this->mTrxLevel
== 0) return;
294 $this->mConn
->rollBack();
295 $this->mTrxLevel
= 0;
298 function limitResultForUpdate($sql, $num) {
302 function strencode($s) {
303 return substr($this->addQuotes($s),1,-1);
306 function encodeBlob($b) {
307 return new Blob( $b );
310 function decodeBlob($b) {
311 if ($b instanceof Blob
) {
317 function addQuotes($s) {
318 if ( $s instanceof Blob
) {
319 return "x'" . bin2hex( $s->fetch() ) . "'";
321 return $this->mConn
->quote($s);
325 function quote_ident($s) { return $s; }
328 * For now, does nothing
330 function selectDB($db) { return true; }
335 public function setTimeout($timeout) { return; }
338 wfDebug("Function ping() not written for SQLite yet");
343 * How lagged is this slave?
345 public function getLag() {
350 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
351 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
353 public function setup_database() {
354 global $IP,$wgSQLiteDataDir,$wgDBTableOptions;
355 $wgDBTableOptions = '';
356 $mysql_tmpl = "$IP/maintenance/tables.sql";
357 $mysql_iw = "$IP/maintenance/interwiki.sql";
358 $sqlite_tmpl = "$IP/maintenance/sqlite/tables.sql";
360 # Make an SQLite template file if it doesn't exist (based on the same one MySQL uses to create a new wiki db)
361 if (!file_exists($sqlite_tmpl)) {
362 $sql = file_get_contents($mysql_tmpl);
363 $sql = preg_replace('/^\s*--.*?$/m','',$sql); # strip comments
364 $sql = preg_replace('/^\s*(UNIQUE)?\s*(PRIMARY)?\s*KEY.+?$/m','',$sql);
365 $sql = preg_replace('/^\s*(UNIQUE )?INDEX.+?$/m','',$sql); # These indexes should be created with a CREATE INDEX query
366 $sql = preg_replace('/^\s*FULLTEXT.+?$/m','',$sql); # Full text indexes
367 $sql = preg_replace('/ENUM\(.+?\)/','TEXT',$sql); # Make ENUM's into TEXT's
368 $sql = preg_replace('/binary\(\d+\)/','BLOB',$sql);
369 $sql = preg_replace('/(TYPE|MAX_ROWS|AVG_ROW_LENGTH)=\w+/','',$sql);
370 $sql = preg_replace('/,\s*\)/s',')',$sql); # removing previous items may leave a trailing comma
371 $sql = str_replace('binary','',$sql);
372 $sql = str_replace('auto_increment','PRIMARY KEY AUTOINCREMENT',$sql);
373 $sql = str_replace(' unsigned','',$sql);
374 $sql = str_replace(' int ',' INTEGER ',$sql);
375 $sql = str_replace('NOT NULL','',$sql);
377 # Tidy up and write file
378 $sql = preg_replace('/^\s*^/m','',$sql); # Remove empty lines
379 $sql = preg_replace('/;$/m',";\n",$sql); # Separate each statement with an empty line
380 file_put_contents($sqlite_tmpl,$sql);
383 # Parse the SQLite template replacing inline variables such as /*$wgDBprefix*/
384 $err = $this->sourceFile($sqlite_tmpl);
385 if ($err !== true) $this->reportQueryError($err,0,$sql,__FUNCTION__
);
387 # Use DatabasePostgres's code to populate interwiki from MySQL template
388 $f = fopen($mysql_iw,'r');
389 if ($f == false) dieout("<li>Could not find the interwiki.sql file");
390 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
392 $line = fgets($f,1024);
394 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) continue;
395 $this->query("$sql $matches[1],$matches[2])");
400 * No-op lock functions
402 public function lock( $lockName, $method ) {
405 public function unlock( $lockName, $method ) {
409 public function getSearchEngine() {
410 return "SearchEngineDummy";
418 class SQLiteField
extends MySQLField
{
420 function __construct() {
423 static function fromText($db, $table, $field) {
424 $n = new SQLiteField
;
426 $n->tablename
= $table;
430 } // end DatabaseSqlite class