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 if (!isset($wgOut)) $wgOut = NULL; # Can't get a reference if it hasn't been set yet
27 $this->mOut
=& $wgOut;
28 $this->mFailFunction
= $failFunction;
29 $this->mFlags
= $flags;
30 $this->mDatabaseFile
= "$wgSQLiteDataDir/$dbName.sqlite";
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
;
51 if ($this->mFlags
& DBO_PERSISTENT
) $this->mConn
= new PDO("sqlite:$file",$user,$pass,array(PDO
::ATTR_PERSISTENT
=> true));
52 else $this->mConn
= new PDO("sqlite:$file",$user,$pass);
53 if ($this->mConn
=== false) wfDebug("DB connection error: $err\n");;
54 $this->mOpened
= $this->mConn
;
55 $this->mConn
->setAttribute(PDO
::ATTR_ERRMODE
,PDO
::ERRMODE_SILENT
); # set error codes only, dont raise exceptions
61 * Close an SQLite database
64 $this->mOpened
= false;
65 if (is_object($this->mConn
)) {
66 if ($this->trxLevel()) $this->immediateCommit();
73 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
75 function doQuery($sql) {
76 $res = $this->mConn
->query($sql);
77 if ($res === false) $this->reportQueryError($this->lastError(),$this->lastErrno(),$sql,__FUNCTION__
);
79 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
80 $this->mAffectedRows
= $r->rowCount();
81 $res = new ResultWrapper($this,$r->fetchAll());
86 function freeResult(&$res) {
87 if ($res instanceof ResultWrapper
) $res->result
= NULL; else $res = NULL;
90 function fetchObject(&$res) {
91 if ($res instanceof ResultWrapper
) $r =& $res->result
; else $r =& $res;
96 foreach ($cur as $k => $v) if (!is_numeric($k)) $obj->$k = $v;
102 function fetchRow(&$res) {
103 if ($res instanceof ResultWrapper
) $r =& $res->result
; else $r =& $res;
105 if (is_array($cur)) {
113 * The PDO::Statement class implements the array interface so count() will work
115 function numRows(&$res) {
116 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
120 function numFields(&$res) {
121 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
122 return is_array($r) ?
count($r[0]) : 0;
125 function fieldName(&$res,$n) {
126 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
128 $keys = array_keys($r[0]);
135 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
137 function tableName($name) {
138 return str_replace('`','',parent
::tableName($name));
142 * This must be called after nextSequenceVal
144 function insertId() {
145 return $this->mConn
->lastInsertId();
148 function dataSeek(&$res,$row) {
149 if ($res instanceof ResultWrapper
) $r =& $res->result
; else $r =& $res;
151 if ($row > 0) for ($i = 0; $i < $row; $i++
) next($r);
154 function lastError() {
155 if (!is_object($this->mConn
)) return "Cannot return last error, no db connection";
156 $e = $this->mConn
->errorInfo();
157 return isset($e[2]) ?
$e[2] : '';
160 function lastErrno() {
161 if (!is_object($this->mConn
)) return "Cannot return last error, no db connection";
162 return $this->mConn
->errorCode();
165 function affectedRows() {
166 return $this->mAffectedRows
;
170 * Returns information about an index
171 * - if errors are explicitly ignored, returns NULL on failure
173 function indexInfo($table, $index, $fname = 'Database::indexExists') {
177 function indexUnique($table, $index, $fname = 'Database::indexUnique') {
182 * Filter the options used in SELECT statements
184 function makeSelectOptions($options) {
185 foreach ($options as $k => $v) if (is_numeric($k) && $v == 'FOR UPDATE') $options[$k] = '';
186 return parent
::makeSelectOptions($options);
190 * Based on MySQL method (parent) with some prior SQLite-sepcific adjustments
192 function insert($table, $a, $fname = 'DatabaseSqlite::insert', $options = array()) {
193 if (!count($a)) return true;
194 if (!is_array($options)) $options = array($options);
196 # SQLite uses OR IGNORE not just IGNORE
197 foreach ($options as $k => $v) if ($v == 'IGNORE') $options[$k] = 'OR IGNORE';
199 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
200 if (isset($a[0]) && is_array($a[0])) {
202 foreach ($a as $k => $v) if (!parent
::insert($table,$v,"$fname/multi-row",$options)) $ret = false;
204 else $ret = parent
::insert($table,$a,"$fname/single-row",$options);
210 * SQLite does not have a "USE INDEX" clause, so return an empty string
212 function useIndexClause($index) {
216 # Returns the size of a text field, or -1 for "unlimited"
217 function textFieldSize($table, $field) {
222 * No low priority option in SQLite
224 function lowPriorityOption() {
229 * Returns an SQL expression for a simple conditional.
230 * - uses CASE on SQLite
232 function conditional($cond, $trueVal, $falseVal) {
233 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
236 function wasDeadlock() {
237 return $this->lastErrno() == SQLITE_BUSY
;
241 * @return string wikitext of a link to the server software's web site
243 function getSoftwareLink() {
244 return "[http://sqlite.org/ SQLite]";
248 * @return string Version information from the database
250 function getServerVersion() {
252 $ver = $this->mConn
->getAttribute(PDO
::ATTR_SERVER_VERSION
);
253 $size = $wgContLang->formatSize(filesize($this->mDatabaseFile
));
254 $file = basename($this->mDatabaseFile
);
255 return $ver." ($file: $size)";
259 * Query whether a given column exists in the mediawiki schema
261 function fieldExists($table, $field) { return true; }
263 function fieldInfo($table, $field) { return SQLiteField
::fromText($this, $table, $field); }
266 if ($this->mTrxLevel
== 1) $this->commit();
267 $this->mConn
->beginTransaction();
268 $this->mTrxLevel
= 1;
272 if ($this->mTrxLevel
== 0) return;
273 $this->mConn
->commit();
274 $this->mTrxLevel
= 0;
277 function rollback() {
278 if ($this->mTrxLevel
== 0) return;
279 $this->mConn
->rollBack();
280 $this->mTrxLevel
= 0;
283 function limitResultForUpdate($sql, $num) {
287 function strencode($s) {
288 return substr($this->addQuotes($s),1,-1);
291 function encodeBlob($b) {
292 return $this->strencode($b);
295 function decodeBlob($b) {
299 function addQuotes($s) {
300 return $this->mConn
->quote($s);
303 function quote_ident($s) { return $s; }
306 * For now, does nothing
308 function selectDB($db) { return true; }
313 public function setTimeout($timeout) { return; }
316 wfDebug("Function ping() not written for SQLite yet");
321 * How lagged is this slave?
323 public function getLag() {
328 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
329 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
331 public function setup_database() {
332 global $IP,$wgSQLiteDataDir,$wgDBTableOptions;
333 $wgDBTableOptions = '';
334 $mysql_tmpl = "$IP/maintenance/tables.sql";
335 $mysql_iw = "$IP/maintenance/interwiki.sql";
336 $sqlite_tmpl = "$IP/maintenance/sqlite/tables.sql";
338 # Make an SQLite template file if it doesn't exist (based on the same one MySQL uses to create a new wiki db)
339 if (!file_exists($sqlite_tmpl)) {
340 $sql = file_get_contents($mysql_tmpl);
341 $sql = preg_replace('/^\s*--.*?$/m','',$sql); # strip comments
342 $sql = preg_replace('/^\s*(UNIQUE)?\s*(PRIMARY)?\s*KEY.+?$/m','',$sql);
343 $sql = preg_replace('/^\s*(UNIQUE )?INDEX.+?$/m','',$sql); # These indexes should be created with a CREATE INDEX query
344 $sql = preg_replace('/^\s*FULLTEXT.+?$/m','',$sql); # Full text indexes
345 $sql = preg_replace('/ENUM\(.+?\)/','TEXT',$sql); # Make ENUM's into TEXT's
346 $sql = preg_replace('/binary\(\d+\)/','BLOB',$sql);
347 $sql = preg_replace('/(TYPE|MAX_ROWS|AVG_ROW_LENGTH)=\w+/','',$sql);
348 $sql = preg_replace('/,\s*\)/s',')',$sql); # removing previous items may leave a trailing comma
349 $sql = str_replace('binary','',$sql);
350 $sql = str_replace('auto_increment','PRIMARY KEY AUTOINCREMENT',$sql);
351 $sql = str_replace(' unsigned','',$sql);
352 $sql = str_replace(' int ',' INTEGER ',$sql);
353 $sql = str_replace('NOT NULL','',$sql);
355 # Tidy up and write file
356 $sql = preg_replace('/^\s*^/m','',$sql); # Remove empty lines
357 $sql = preg_replace('/;$/m',";\n",$sql); # Separate each statement with an empty line
358 file_put_contents($sqlite_tmpl,$sql);
361 # Parse the SQLite template replacing inline variables such as /*$wgDBprefix*/
362 $err = $this->sourceFile($sqlite_tmpl);
363 if ($err !== true) $this->reportQueryError($err,0,$sql,__FUNCTION__
);
365 # Use DatabasePostgres's code to populate interwiki from MySQL template
366 $f = fopen($mysql_iw,'r');
367 if ($f == false) dieout("<li>Could not find the interwiki.sql file");
368 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
370 $line = fgets($f,1024);
372 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) continue;
373 $this->query("$sql $matches[1],$matches[2])");
378 * No-op lock functions
380 public function lock( $lockName, $method ) {
383 public function unlock( $lockName, $method ) {
387 public function getSearchEngine() {
388 return "SearchEngineDummy";
396 class SQLiteField
extends MySQLField
{
398 function __construct() {
401 static function fromText($db, $table, $field) {
402 $n = new SQLiteField
;
404 $n->tablename
= $table;
408 } // end DatabaseSqlite class