doMaintenance.php -> DO_MAINTENANCE
[mediawiki.git] / includes / db / DatabaseSqlite.php
blobd48a7056150da569247baa7a61e909dceb759e0d
1 <?php
2 /**
3 * This script is the SQLite database abstraction layer
5 * See maintenance/sqlite/README for development notes and other specific information
6 * @ingroup Database
7 * @file
8 */
10 /**
11 * @ingroup Database
13 class DatabaseSqlite extends DatabaseBase {
15 var $mAffectedRows;
16 var $mLastResult;
17 var $mDatabaseFile;
18 var $mName;
20 /**
21 * Constructor
23 function __construct($server = false, $user = false, $password = false, $dbName = false, $failFunction = false, $flags = 0) {
24 global $wgSQLiteDataDir;
25 $this->mFailFunction = $failFunction;
26 $this->mFlags = $flags;
27 $this->mDatabaseFile = "$wgSQLiteDataDir/$dbName.sqlite";
28 if( !is_readable( $this->mDatabaseFile ) )
29 throw new DBConnectionError( $this, "SQLite database not accessible" );
30 $this->mName = $dbName;
31 $this->open($server, $user, $password, $dbName);
34 /**
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) {
48 $this->mConn = false;
49 if ($dbName) {
50 $file = $this->mDatabaseFile;
51 try {
52 if ( $this->mFlags & DBO_PERSISTENT ) {
53 $this->mConn = new PDO( "sqlite:$file", $user, $pass,
54 array( PDO::ATTR_PERSISTENT => true ) );
55 } else {
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 );
65 } else {
66 return false;
70 $this->mOpened = $this->mConn;
71 # set error codes only, don't raise exceptions
72 $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
74 return $this->mConn;
77 /**
78 * Close an SQLite database
80 function close() {
81 $this->mOpened = false;
82 if (is_object($this->mConn)) {
83 if ($this->trxLevel()) $this->immediateCommit();
84 $this->mConn = null;
86 return true;
89 /**
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);
94 if ($res === false) {
95 return false;
96 } else {
97 $r = $res instanceof ResultWrapper ? $res->result : $res;
98 $this->mAffectedRows = $r->rowCount();
99 $res = new ResultWrapper($this,$r->fetchAll());
101 return $res;
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;
110 $cur = current($r);
111 if (is_array($cur)) {
112 next($r);
113 $obj = new stdClass;
114 foreach ($cur as $k => $v) if (!is_numeric($k)) $obj->$k = $v;
115 return $obj;
117 return false;
120 function fetchRow($res) {
121 if ($res instanceof ResultWrapper) $r =& $res->result; else $r =& $res;
122 $cur = current($r);
123 if (is_array($cur)) {
124 next($r);
125 return $cur;
127 return false;
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;
135 return count($r);
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;
145 if (is_array($r)) {
146 $keys = array_keys($r[0]);
147 return $keys[$n];
149 return false;
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 * Index names have DB scope
162 function indexName( $index ) {
163 return $index;
167 * This must be called after nextSequenceVal
169 function insertId() {
170 return $this->mConn->lastInsertId();
173 function dataSeek($res,$row) {
174 if ($res instanceof ResultWrapper) $r =& $res->result; else $r =& $res;
175 reset($r);
176 if ($row > 0) for ($i = 0; $i < $row; $i++) next($r);
179 function lastError() {
180 if (!is_object($this->mConn)) return "Cannot return last error, no db connection";
181 $e = $this->mConn->errorInfo();
182 return isset($e[2]) ? $e[2] : '';
185 function lastErrno() {
186 if (!is_object($this->mConn)) {
187 return "Cannot return last error, no db connection";
188 } else {
189 $info = $this->mConn->errorInfo();
190 return $info[1];
194 function affectedRows() {
195 return $this->mAffectedRows;
199 * Returns information about an index
200 * Returns false if the index does not exist
201 * - if errors are explicitly ignored, returns NULL on failure
203 function indexInfo($table, $index, $fname = 'Database::indexExists') {
204 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
205 $res = $this->query( $sql, $fname );
206 if ( !$res ) {
207 return null;
209 if ( $res->numRows() == 0 ) {
210 return false;
212 $info = array();
213 foreach ( $res as $row ) {
214 $info[] = $row->name;
216 return $info;
219 function indexUnique($table, $index, $fname = 'Database::indexUnique') {
220 $row = $this->selectRow( 'sqlite_master', '*',
221 array(
222 'type' => 'index',
223 'name' => $this->indexName( $index ),
224 ), $fname );
225 if ( !$row || !isset( $row->sql ) ) {
226 return null;
229 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
230 $indexPos = strpos( $row->sql, 'INDEX' );
231 if ( $indexPos === false ) {
232 return null;
234 $firstPart = substr( $row->sql, 0, $indexPos );
235 $options = explode( ' ', $firstPart );
236 return in_array( 'UNIQUE', $options );
240 * Filter the options used in SELECT statements
242 function makeSelectOptions($options) {
243 foreach ($options as $k => $v) if (is_numeric($k) && $v == 'FOR UPDATE') $options[$k] = '';
244 return parent::makeSelectOptions($options);
248 * Based on MySQL method (parent) with some prior SQLite-sepcific adjustments
250 function insert($table, $a, $fname = 'DatabaseSqlite::insert', $options = array()) {
251 if (!count($a)) return true;
252 if (!is_array($options)) $options = array($options);
254 # SQLite uses OR IGNORE not just IGNORE
255 foreach ($options as $k => $v) if ($v == 'IGNORE') $options[$k] = 'OR IGNORE';
257 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
258 if (isset($a[0]) && is_array($a[0])) {
259 $ret = true;
260 foreach ($a as $k => $v) if (!parent::insert($table,$v,"$fname/multi-row",$options)) $ret = false;
262 else $ret = parent::insert($table,$a,"$fname/single-row",$options);
264 return $ret;
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) {
272 return -1;
275 function wasDeadlock() {
276 return $this->lastErrno() == SQLITE_BUSY;
279 function wasErrorReissuable() {
280 return $this->lastErrno() == SQLITE_SCHEMA;
283 function wasReadOnlyError() {
284 return $this->lastErrno() == SQLITE_READONLY;
288 * @return string wikitext of a link to the server software's web site
290 function getSoftwareLink() {
291 return "[http://sqlite.org/ SQLite]";
295 * @return string Version information from the database
297 function getServerVersion() {
298 global $wgContLang;
299 $ver = $this->mConn->getAttribute(PDO::ATTR_SERVER_VERSION);
300 return $ver;
304 * Query whether a given column exists in the mediawiki schema
306 function fieldExists($table, $field, $fname = '') {
307 $info = $this->fieldInfo( $table, $field );
308 return (bool)$info;
312 * Get information about a given field
313 * Returns false if the field does not exist.
315 function fieldInfo($table, $field) {
316 $tableName = $this->tableName( $table );
317 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
318 $res = $this->query( $sql, __METHOD__ );
319 foreach ( $res as $row ) {
320 if ( $row->name == $field ) {
321 return new SQLiteField( $row, $tableName );
324 return false;
327 function begin( $fname = '' ) {
328 if ($this->mTrxLevel == 1) $this->commit();
329 $this->mConn->beginTransaction();
330 $this->mTrxLevel = 1;
333 function commit( $fname = '' ) {
334 if ($this->mTrxLevel == 0) return;
335 $this->mConn->commit();
336 $this->mTrxLevel = 0;
339 function rollback( $fname = '' ) {
340 if ($this->mTrxLevel == 0) return;
341 $this->mConn->rollBack();
342 $this->mTrxLevel = 0;
345 function limitResultForUpdate($sql, $num) {
346 return $this->limitResult( $sql, $num );
349 function strencode($s) {
350 return substr($this->addQuotes($s),1,-1);
353 function encodeBlob($b) {
354 return new Blob( $b );
357 function decodeBlob($b) {
358 if ($b instanceof Blob) {
359 $b = $b->fetch();
361 return $b;
364 function addQuotes($s) {
365 if ( $s instanceof Blob ) {
366 return "x'" . bin2hex( $s->fetch() ) . "'";
367 } else {
368 return $this->mConn->quote($s);
372 function quote_ident($s) { return $s; }
375 * How lagged is this slave?
377 public function getLag() {
378 return 0;
382 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
383 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
385 public function setup_database() {
386 global $IP,$wgSQLiteDataDir,$wgDBTableOptions;
387 $wgDBTableOptions = '';
389 # Process common MySQL/SQLite table definitions
390 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
391 if ($err !== true) {
392 $this->reportQueryError($err,0,$sql,__FUNCTION__);
393 exit( 1 );
396 # Use DatabasePostgres's code to populate interwiki from MySQL template
397 $f = fopen("$IP/maintenance/interwiki.sql",'r');
398 if ($f == false) dieout("<li>Could not find the interwiki.sql file");
399 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
400 while (!feof($f)) {
401 $line = fgets($f,1024);
402 $matches = array();
403 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) continue;
404 $this->query("$sql $matches[1],$matches[2])");
408 public function getSearchEngine() {
409 return "SearchEngineDummy";
413 * No-op version of deadlockLoop
415 public function deadlockLoop( /*...*/ ) {
416 $args = func_get_args();
417 $function = array_shift( $args );
418 return call_user_func_array( $function, $args );
421 protected function replaceVars( $s ) {
422 $s = parent::replaceVars( $s );
423 if ( preg_match( '/^\s*CREATE TABLE/i', $s ) ) {
424 // CREATE TABLE hacks to allow schema file sharing with MySQL
426 // binary/varbinary column type -> blob
427 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'blob\1', $s );
428 // no such thing as unsigned
429 $s = preg_replace( '/\bunsigned\b/i', '', $s );
430 // INT -> INTEGER for primary keys
431 $s = preg_replacE( '/\bint\b/i', 'integer', $s );
432 // No ENUM type
433 $s = preg_replace( '/enum\([^)]*\)/i', 'blob', $s );
434 // binary collation type -> nothing
435 $s = preg_replace( '/\bbinary\b/i', '', $s );
436 // auto_increment -> autoincrement
437 $s = preg_replace( '/\bauto_increment\b/i', 'autoincrement', $s );
438 // No explicit options
439 $s = preg_replace( '/\)[^)]*$/', ')', $s );
440 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
441 // No truncated indexes
442 $s = preg_replace( '/\(\d+\)/', '', $s );
443 // No FULLTEXT
444 $s = preg_replace( '/\bfulltext\b/i', '', $s );
446 return $s;
450 * Build a concatenation list to feed into a SQL query
452 function buildConcat( $stringList ) {
453 return '(' . implode( ') || (', $stringList ) . ')';
456 } // end DatabaseSqlite class
459 * @ingroup Database
461 class SQLiteField {
462 private $info, $tableName;
463 function __construct( $info, $tableName ) {
464 $this->info = $info;
465 $this->tableName = $tableName;
468 function name() {
469 return $this->info->name;
472 function tableName() {
473 return $this->tableName;
476 function defaultValue() {
477 if ( is_string( $this->info->dflt_value ) ) {
478 // Typically quoted
479 if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
480 return str_replace( "''", "'", $this->info->dflt_value );
483 return $this->info->dflt_value;
486 function maxLength() {
487 return -1;
490 function nullable() {
491 // SQLite dynamic types are always nullable
492 return true;
495 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
496 # Suggest removal from base class [TS]
498 function type() {
499 return $this->info->type;
502 } // end SQLiteField