d7d2571522c9213d99f22d31eb44eda739600f2b
3 * This script is the SQLite database abstraction layer
5 * See maintenance/sqlite/README for development notes and other specific information
11 class DatabaseSqlite
extends Database
{
20 function __construct($server = false, $user = false, $password = false, $dbName = false, $failFunction = false, $flags = 0) {
21 global $wgOut,$wgSQLiteDataDir;
22 if ("$wgSQLiteDataDir" == '') $wgSQLiteDataDir = dirname($_SERVER['DOCUMENT_ROOT']).'/data';
23 if (!is_dir($wgSQLiteDataDir)) mkdir($wgSQLiteDataDir,0700);
24 if (!isset($wgOut)) $wgOut = NULL; # Can't get a reference if it hasn't been set yet
25 $this->mOut
=& $wgOut;
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
;
49 if ($this->mFlags
& DBO_PERSISTENT
) $this->mConn
= new PDO("sqlite:$file",$user,$pass,array(PDO
::ATTR_PERSISTENT
=> true));
50 else $this->mConn
= new PDO("sqlite:$file",$user,$pass);
51 if ($this->mConn
=== false) wfDebug("DB connection error: $err\n");;
52 $this->mOpened
= $this->mConn
;
53 $this->mConn
->setAttribute(PDO
::ATTR_ERRMODE
,PDO
::ERRMODE_SILENT
); # set error codes only, dont raise exceptions
59 * Close an SQLite database
62 $this->mOpened
= false;
63 if (is_object($this->mConn
)) {
64 if ($this->trxLevel()) $this->immediateCommit();
71 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
73 function doQuery($sql) {
74 $res = $this->mConn
->query($sql);
75 if ($res === false) $this->reportQueryError($this->lastError(),$this->lastErrno(),$sql,__FUNCTION__
);
77 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
78 $this->mAffectedRows
= $r->rowCount();
79 $res = new ResultWrapper($this,$r->fetchAll());
84 function freeResult(&$res) {
85 if ($res instanceof ResultWrapper
) $res->result
= NULL; else $res = NULL;
88 function fetchObject(&$res) {
89 if ($res instanceof ResultWrapper
) $r =& $res->result
; else $r =& $res;
94 foreach ($cur as $k => $v) if (!is_numeric($k)) $obj->$k = $v;
100 function fetchRow(&$res) {
101 if ($res instanceof ResultWrapper
) $r =& $res->result
; else $r =& $res;
103 if (is_array($cur)) {
111 * The PDO::Statement class implements the array interface so count() will work
113 function numRows(&$res) {
114 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
118 function numFields(&$res) {
119 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
120 return is_array($r) ?
count($r[0]) : 0;
123 function fieldName(&$res,$n) {
124 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
126 $keys = array_keys($r[0]);
133 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
135 function tableName($name) {
136 return str_replace('`','',parent
::tableName($name));
140 * This must be called after nextSequenceVal
142 function insertId() {
143 return $this->mConn
->lastInsertId();
146 function dataSeek(&$res,$row) {
147 if ($res instanceof ResultWrapper
) $r =& $res->result
; else $r =& $res;
149 if ($row > 0) for ($i = 0; $i < $row; $i++
) next($r);
152 function lastError() {
153 if (!is_object($this->mConn
)) return "Cannot return last error, no db connection";
154 $e = $this->mConn
->errorInfo();
155 return isset($e[2]) ?
$e[2] : '';
158 function lastErrno() {
159 if (!is_object($this->mConn
)) return "Cannot return last error, no db connection";
160 return $this->mConn
->errorCode();
163 function affectedRows() {
164 return $this->mAffectedRows
;
168 * Returns information about an index
169 * - if errors are explicitly ignored, returns NULL on failure
171 function indexInfo($table, $index, $fname = 'Database::indexExists') {
175 function indexUnique($table, $index, $fname = 'Database::indexUnique') {
180 * Filter the options used in SELECT statements
182 function makeSelectOptions($options) {
183 foreach ($options as $k => $v) if (is_numeric($k) && $v == 'FOR UPDATE') $options[$k] = '';
184 return parent
::makeSelectOptions($options);
188 * Based on MySQL method (parent) with some prior SQLite-sepcific adjustments
190 function insert($table, $a, $fname = 'DatabaseSqlite::insert', $options = array()) {
191 if (!count($a)) return true;
192 if (!is_array($options)) $options = array($options);
194 # SQLite uses OR IGNORE not just IGNORE
195 foreach ($options as $k => $v) if ($v == 'IGNORE') $options[$k] = 'OR IGNORE';
197 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
198 if (isset($a[0]) && is_array($a[0])) {
200 foreach ($a as $k => $v) if (!parent
::insert($table,$v,"$fname/multi-row",$options)) $ret = false;
202 else $ret = parent
::insert($table,$a,"$fname/single-row",$options);
208 * SQLite does not have a "USE INDEX" clause, so return an empty string
210 function useIndexClause($index) {
214 # Returns the size of a text field, or -1 for "unlimited"
215 function textFieldSize($table, $field) {
220 * No low priority option in SQLite
222 function lowPriorityOption() {
227 * Returns an SQL expression for a simple conditional.
228 * - uses CASE on SQLite
230 function conditional($cond, $trueVal, $falseVal) {
231 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
234 function wasDeadlock() {
235 return $this->lastErrno() == SQLITE_BUSY
;
239 * @return string wikitext of a link to the server software's web site
241 function getSoftwareLink() {
242 return "[http://sqlite.org/ SQLite]";
246 * @return string Version information from the database
248 function getServerVersion() {
250 $ver = $this->mConn
->getAttribute(PDO
::ATTR_SERVER_VERSION
);
251 $size = $wgContLang->formatSize(filesize($this->mDatabaseFile
));
252 $file = basename($this->mDatabaseFile
);
253 return $ver." ($file: $size)";
257 * Query whether a given column exists in the mediawiki schema
259 function fieldExists($table, $field) { return true; }
261 function fieldInfo($table, $field) { return SQLiteField
::fromText($this, $table, $field); }
264 if ($this->mTrxLevel
== 1) $this->commit();
265 $this->mConn
->beginTransaction();
266 $this->mTrxLevel
= 1;
270 if ($this->mTrxLevel
== 0) return;
271 $this->mConn
->commit();
272 $this->mTrxLevel
= 0;
275 function rollback() {
276 if ($this->mTrxLevel
== 0) return;
277 $this->mConn
->rollBack();
278 $this->mTrxLevel
= 0;
281 function limitResultForUpdate($sql, $num) {
285 function strencode($s) {
286 return substr($this->addQuotes($s),1,-1);
289 function encodeBlob($b) {
290 return $this->strencode($b);
293 function decodeBlob($b) {
297 function addQuotes($s) {
298 return $this->mConn
->quote($s);
301 function quote_ident($s) { return $s; }
304 * For now, does nothing
306 function selectDB($db) { return true; }
311 public function setTimeout($timeout) { return; }
314 wfDebug("Function ping() not written for SQLite yet");
319 * How lagged is this slave?
321 public function getLag() {
326 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
327 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
329 public function setup_database() {
330 global $IP,$wgSQLiteDataDir,$wgDBTableOptions;
331 $wgDBTableOptions = '';
332 $mysql_tmpl = "$IP/maintenance/tables.sql";
333 $mysql_iw = "$IP/maintenance/interwiki.sql";
334 $sqlite_tmpl = "$IP/maintenance/sqlite/tables.sql";
336 # Make an SQLite template file if it doesn't exist (based on the same one MySQL uses to create a new wiki db)
337 if (!file_exists($sqlite_tmpl)) {
338 $sql = file_get_contents($mysql_tmpl);
339 $sql = preg_replace('/^\s*--.*?$/m','',$sql); # strip comments
340 $sql = preg_replace('/^\s*(UNIQUE)?\s*(PRIMARY)?\s*KEY.+?$/m','',$sql);
341 $sql = preg_replace('/^\s*(UNIQUE )?INDEX.+?$/m','',$sql); # These indexes should be created with a CREATE INDEX query
342 $sql = preg_replace('/^\s*FULLTEXT.+?$/m','',$sql); # Full text indexes
343 $sql = preg_replace('/ENUM\(.+?\)/','TEXT',$sql); # Make ENUM's into TEXT's
344 $sql = preg_replace('/binary\(\d+\)/','BLOB',$sql);
345 $sql = preg_replace('/(TYPE|MAX_ROWS|AVG_ROW_LENGTH)=\w+/','',$sql);
346 $sql = preg_replace('/,\s*\)/s',')',$sql); # removing previous items may leave a trailing comma
347 $sql = str_replace('binary','',$sql);
348 $sql = str_replace('auto_increment','PRIMARY KEY AUTOINCREMENT',$sql);
349 $sql = str_replace(' unsigned','',$sql);
350 $sql = str_replace(' int ',' INTEGER ',$sql);
351 $sql = str_replace('NOT NULL','',$sql);
353 # Tidy up and write file
354 $sql = preg_replace('/^\s*^/m','',$sql); # Remove empty lines
355 $sql = preg_replace('/;$/m',";\n",$sql); # Separate each statement with an empty line
356 file_put_contents($sqlite_tmpl,$sql);
359 # Parse the SQLite template replacing inline variables such as /*$wgDBprefix*/
360 $err = $this->sourceFile($sqlite_tmpl);
361 if ($err !== true) $this->reportQueryError($err,0,$sql,__FUNCTION__
);
363 # Use DatabasePostgres's code to populate interwiki from MySQL template
364 $f = fopen($mysql_iw,'r');
365 if ($f == false) dieout("<li>Could not find the interwiki.sql file");
366 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
368 $line = fgets($f,1024);
370 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) continue;
371 $this->query("$sql $matches[1],$matches[2])");
378 * @addtogroup Database
380 class SQLiteField
extends MySQLField
{
382 function __construct() {
385 static function fromText($db, $table, $field) {
386 $n = new SQLiteField
;
388 $n->tablename
= $table;
392 } // end DatabaseSqlite class