ee859ec69f4332cce55ad97115aeb3e7f6564a1c
3 * This script is the SQLite database abstraction layer, see http://www.organicdesign.co.nz/Extension_talk:MediaWikiLite.php
4 * - Licenced under LGPL (http://www.gnu.org/copyleft/lesser.html){{php}}
5 * - Author: [http://www.organicdesign.co.nz/nad User:Nad]
6 * - Started: 2007-12-17
7 * - Last update: 2008-01-20
9 * {{php}}{{category:Extensions|DatabaseSqlite.php}}
13 * @addtogroup Database
15 class DatabaseSqlite
extends Database
{
24 function __construct($server = false, $user = false, $password = false, $dbName = false, $failFunction = false, $flags = 0) {
25 global $wgOut,$wgSQLiteDataDir;
26 if ("$wgSQLiteDataDir" == '') $wgSQLiteDataDir = dirname($_SERVER['DOCUMENT_ROOT']).'/data';
27 if (!is_dir($wgSQLiteDataDir)) mkdir($wgSQLiteDataDir,0700);
28 if (!isset($wgOut)) $wgOut = NULL; # Can't get a reference if it hasn't been set yet
29 $this->mOut
=& $wgOut;
30 $this->mFailFunction
= $failFunction;
31 $this->mFlags
= $flags;
32 $this->mDatabaseFile
= "$wgSQLiteDataDir/$dbName.sqlite";
33 $this->open($server, $user, $password, $dbName);
37 * todo: check if these should be true like parent class
39 function implicitGroupby() { return false; }
40 function implicitOrderby() { return false; }
42 static function newFromParams($server, $user, $password, $dbName, $failFunction = false, $flags = 0) {
43 return new DatabaseSqlite($server, $user, $password, $dbName, $failFunction, $flags);
46 /** Open an SQLite database and return a resource handle to it
47 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
49 function open($server,$user,$pass,$dbName) {
52 $file = $this->mDatabaseFile
;
53 if ($this->mFlags
& DBO_PERSISTENT
) $this->mConn
= new PDO("sqlite:$file",$user,$pass,array(PDO
::ATTR_PERSISTENT
=> true));
54 else $this->mConn
= new PDO("sqlite:$file",$user,$pass);
55 if ($this->mConn
=== false) wfDebug("DB connection error: $err\n");;
56 $this->mOpened
= $this->mConn
;
57 $this->mConn
->setAttribute(PDO
::ATTR_ERRMODE
,PDO
::ERRMODE_SILENT
); # set error codes only, dont raise exceptions
63 * Close an SQLite database
66 $this->mOpened
= false;
67 if (is_object($this->mConn
)) {
68 if ($this->trxLevel()) $this->immediateCommit();
75 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
77 function doQuery($sql) {
78 $res = $this->mConn
->query($sql);
79 if ($res === false) $this->reportQueryError($this->lastError(),$this->lastErrno(),$sql,__FUNCTION__
);
81 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
82 $this->mAffectedRows
= $r->rowCount();
83 $res = new ResultWrapper($this,$r->fetchAll());
88 function freeResult(&$res) {
89 if ($res instanceof ResultWrapper
) $res->result
= NULL; else $res = NULL;
92 function fetchObject(&$res) {
93 if ($res instanceof ResultWrapper
) $r =& $res->result
; else $r =& $res;
98 foreach ($cur as $k => $v) if (!is_numeric($k)) $obj->$k = $v;
104 function fetchRow(&$res) {
105 if ($res instanceof ResultWrapper
) $r =& $res->result
; else $r =& $res;
107 if (is_array($cur)) {
115 * The PDO::Statement class implements the array interface so count() will work
117 function numRows(&$res) {
118 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
122 function numFields(&$res) {
123 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
124 return is_array($r) ?
count($r[0]) : 0;
127 function fieldName(&$res,$n) {
128 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
130 $keys = array_keys($r[0]);
137 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
139 function tableName($name) {
140 return str_replace('`','',parent
::tableName($name));
144 * This must be called after nextSequenceVal
146 function insertId() {
147 return $this->mConn
->lastInsertId();
150 function dataSeek(&$res,$row) {
151 if ($res instanceof ResultWrapper
) $r =& $res->result
; else $r =& $res;
153 if ($row > 0) for ($i = 0; $i < $row; $i++
) next($r);
156 function lastError() {
157 if (!is_object($this->mConn
)) return "Cannot return last error, no db connection";
158 $e = $this->mConn
->errorInfo();
159 return isset($e[2]) ?
$e[2] : '';
162 function lastErrno() {
163 if (!is_object($this->mConn
)) return "Cannot return last error, no db connection";
164 return $this->mConn
->errorCode();
167 function affectedRows() {
168 return $this->mAffectedRows
;
172 * Returns information about an index
173 * - if errors are explicitly ignored, returns NULL on failure
175 function indexInfo($table, $index, $fname = 'Database::indexExists') {
179 function indexUnique($table, $index, $fname = 'Database::indexUnique') {
184 * Filter the options used in SELECT statements
186 function makeSelectOptions($options) {
187 foreach ($options as $k => $v) if (is_numeric($k) && $v == 'FOR UPDATE') $options[$k] = '';
188 return parent
::makeSelectOptions($options);
192 * Based on MySQL method (parent) with some prior SQLite-sepcific adjustments
194 function insert($table, $a, $fname = 'DatabaseSqlite::insert', $options = array()) {
195 if (!count($a)) return true;
196 if (!is_array($options)) $options = array($options);
198 # SQLite uses OR IGNORE not just IGNORE
199 foreach ($options as $k => $v) if ($v == 'IGNORE') $options[$k] = 'OR IGNORE';
201 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
202 if (isset($a[0]) && is_array($a[0])) {
204 foreach ($a as $k => $v) if (!parent
::insert($table,$v,"$fname/multi-row",$options)) $ret = false;
206 else $ret = parent
::insert($table,$a,"$fname/single-row",$options);
212 * SQLite does not have a "USE INDEX" clause, so return an empty string
214 function useIndexClause($index) {
218 # Returns the size of a text field, or -1 for "unlimited"
219 function textFieldSize($table, $field) {
224 * No low priority option in SQLite
226 function lowPriorityOption() {
231 * Returns an SQL expression for a simple conditional.
232 * - uses CASE on SQLite
234 function conditional($cond, $trueVal, $falseVal) {
235 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
238 function wasDeadlock() {
239 return $this->lastErrno() == SQLITE_BUSY
;
243 * @return string wikitext of a link to the server software's web site
245 function getSoftwareLink() {
246 return "[http://sqlite.org/ SQLite]";
250 * @return string Version information from the database
252 function getServerVersion() {
254 $ver = $this->mConn
->getAttribute(PDO
::ATTR_SERVER_VERSION
);
255 $size = $wgContLang->formatSize(filesize($this->mDatabaseFile
));
256 $file = basename($this->mDatabaseFile
);
257 return $ver." ($file: $size)";
261 * Query whether a given column exists in the mediawiki schema
263 function fieldExists($table, $field) { return true; }
265 function fieldInfo($table, $field) { return SQLiteField
::fromText($this, $table, $field); }
268 if ($this->mTrxLevel
== 1) $this->commit();
269 $this->mConn
->beginTransaction();
270 $this->mTrxLevel
= 1;
274 if ($this->mTrxLevel
== 0) return;
275 $this->mConn
->commit();
276 $this->mTrxLevel
= 0;
279 function rollback() {
280 if ($this->mTrxLevel
== 0) return;
281 $this->mConn
->rollBack();
282 $this->mTrxLevel
= 0;
285 function limitResultForUpdate($sql, $num) {
289 function strencode($s) {
290 return substr($this->addQuotes($s),1,-1);
293 function encodeBlob($b) {
294 return $this->strencode($b);
297 function decodeBlob($b) {
301 function addQuotes($s) {
302 return $this->mConn
->quote($s);
305 function quote_ident($s) { return $s; }
308 * For now, does nothing
310 function selectDB($db) { return true; }
315 public function setTimeout($timeout) { return; }
318 wfDebug("Function ping() not written for SQLite yet");
323 * How lagged is this slave?
325 public function getLag() {
330 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
331 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
333 public function setup_database() {
334 global $IP,$wgSQLiteDataDir,$wgDBTableOptions;
335 $wgDBTableOptions = '';
336 $mysql_tmpl = "$IP/maintenance/tables.sql";
337 $mysql_iw = "$IP/maintenance/interwiki.sql";
338 $sqlite_tmpl = "$wgSQLiteDataDir/tables.sql";
340 # Make an SQLite template file if it doesn't exist (based on the same one MySQL uses to create a new wiki db)
341 if (1 ||
!file_exists($sqlite_tmpl)) { # todo: make this conditional again
342 $sql = file_get_contents($mysql_tmpl);
343 $sql = preg_replace('/^\s*--.*?$/m','',$sql); # strip comments
344 $sql = preg_replace('/^\s*(UNIQUE)?\s*(PRIMARY)?\s*KEY.+?$/m','',$sql);
345 $sql = preg_replace('/^\s*(UNIQUE )?INDEX.+?$/m','',$sql); # These indexes should be created with a CREATE INDEX query
346 $sql = preg_replace('/^\s*FULLTEXT.+?$/m','',$sql); # Full text indexes
347 $sql = preg_replace('/ENUM\(.+?\)/','TEXT',$sql); # Make ENUM's into TEXT's
348 $sql = preg_replace('/ENUM\(.+?\)/','TEXT',$sql); # Make ENUM's into TEXT's
349 $sql = preg_replace('/binary\(\d+\)/','BLOB',$sql);
350 $sql = preg_replace('/(TYPE|MAX_ROWS|AVG_ROW_LENGTH)=\w+/','',$sql);
351 $sql = preg_replace('/,\s*\)/s',')',$sql); # removing previous items may leave a trailing comma
352 $sql = str_replace('binary','',$sql);
353 $sql = str_replace('auto_increment','PRIMARY KEY AUTOINCREMENT',$sql);
354 $sql = str_replace(' unsigned','',$sql);
355 $sql = str_replace(' int ',' INTEGER ',$sql);
356 $sql = str_replace('NOT NULL','',$sql);
357 file_put_contents($sqlite_tmpl,$sql);
360 # Parse the SQLite template replacing inline variables such as /*$wgDBprefix*/
361 $err = $this->sourceFile($sqlite_tmpl);
362 if ($err !== true) $this->reportQueryError($err,0,$sql,__FUNCTION__
);
364 # Use DatabasePostgres's code to populate interwiki from MySQL template
365 $f = fopen($mysql_iw,'r');
366 if ($f == false) dieout("<li>Could not find the interwiki.sql file");
367 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
369 $line = fgets($f,1024);
371 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) continue;
372 $this->query("$sql $matches[1],$matches[2])");
379 * @addtogroup Database
381 class SQLiteField
extends MySQLField
{
383 function __construct() {
386 static function fromText($db, $table, $field) {
387 $n = new SQLiteField
;
389 $n->tablename
= $table;
393 } // end DatabaseSqlite class