Refactored Database*::getLag(): moved the default implementation to MySQL, replaced...
[lhc/web/wiklou.git] / includes / db / DatabaseSqlite.php
1 <?php
2 /**
3 * This script is the SQLite database abstraction layer
4 *
5 * See maintenance/sqlite/README for development notes and other specific information
6 * @ingroup Database
7 * @file
8 */
9
10 /**
11 * @ingroup Database
12 */
13 class DatabaseSqlite extends DatabaseBase {
14
15 private static $fulltextEnabled = null;
16
17 var $mAffectedRows;
18 var $mLastResult;
19 var $mDatabaseFile;
20 var $mName;
21
22 /**
23 * Constructor.
24 * Parameters $server, $user and $password are not used.
25 */
26 function __construct( $server = false, $user = false, $password = false, $dbName = false, $failFunction = false, $flags = 0 ) {
27 global $wgSharedDB;
28 $this->mFailFunction = $failFunction;
29 $this->mFlags = $flags;
30 $this->mName = $dbName;
31
32 if ( $this->open( $server, $user, $password, $dbName ) && $wgSharedDB ) {
33 $this->attachDatabase( $wgSharedDB );
34 }
35 }
36
37 function getType() {
38 return 'sqlite';
39 }
40
41 /**
42 * @todo: check if it should be true like parent class
43 */
44 function implicitGroupby() { return false; }
45
46 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 ) {
47 return new DatabaseSqlite( $server, $user, $password, $dbName, $failFunction, $flags );
48 }
49
50 /** Open an SQLite database and return a resource handle to it
51 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
52 */
53 function open( $server, $user, $pass, $dbName ) {
54 global $wgSQLiteDataDir;
55
56 $fileName = self::generateFileName( $wgSQLiteDataDir, $dbName );
57 if ( !is_readable( $fileName ) ) {
58 throw new DBConnectionError( $this, "SQLite database not accessible" );
59 $this->mConn = false;
60 }
61 $this->openFile( $fileName );
62 return $this->mConn;
63 }
64
65 /**
66 * Opens a database file
67 * @return SQL connection or false if failed
68 */
69 function openFile( $fileName ) {
70 $this->mDatabaseFile = $fileName;
71 try {
72 if ( $this->mFlags & DBO_PERSISTENT ) {
73 $this->mConn = new PDO( "sqlite:$fileName", '', '',
74 array( PDO::ATTR_PERSISTENT => true ) );
75 } else {
76 $this->mConn = new PDO( "sqlite:$fileName", '', '' );
77 }
78 } catch ( PDOException $e ) {
79 $err = $e->getMessage();
80 }
81 if ( $this->mConn === false ) {
82 wfDebug( "DB connection error: $err\n" );
83 if ( !$this->mFailFunction ) {
84 throw new DBConnectionError( $this, $err );
85 } else {
86 return false;
87 }
88
89 }
90 $this->mOpened = !!$this->mConn;
91 # set error codes only, don't raise exceptions
92 if ( $this->mOpened ) {
93 $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
94 return true;
95 }
96 }
97
98 /**
99 * Close an SQLite database
100 */
101 function close() {
102 $this->mOpened = false;
103 if ( is_object( $this->mConn ) ) {
104 if ( $this->trxLevel() ) $this->commit();
105 $this->mConn = null;
106 }
107 return true;
108 }
109
110 /**
111 * Generates a database file name. Explicitly public for installer.
112 * @param $dir String: Directory where database resides
113 * @param $dbName String: Database name
114 * @return String
115 */
116 public static function generateFileName( $dir, $dbName ) {
117 return "$dir/$dbName.sqlite";
118 }
119
120 /**
121 * Check if the searchindext table is FTS enabled.
122 * @returns false if not enabled.
123 */
124 function checkForEnabledSearch() {
125 if ( self::$fulltextEnabled === null ) {
126 self::$fulltextEnabled = false;
127 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = 'searchindex'", __METHOD__ );
128 if ( $res ) {
129 $row = $res->fetchRow();
130 self::$fulltextEnabled = stristr($row['sql'], 'fts' ) !== false;
131 }
132 }
133 return self::$fulltextEnabled;
134 }
135
136 /**
137 * Returns version of currently supported SQLite fulltext search module or false if none present.
138 * @return String
139 */
140 function getFulltextSearchModule() {
141 $table = 'dummy_search_test';
142 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__ );
143
144 if ( $this->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
145 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__ );
146 return 'FTS3';
147 }
148 return false;
149 }
150
151 /**
152 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
153 * for details.
154 * @param $name: Database name to be used in queries like SELECT foo FROM dbname.table
155 * @param $file: Database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
156 */
157 function attachDatabase( $name, $file = false, $fname = 'DatabaseSqlite::attachDatabase' ) {
158 global $wgSQLiteDataDir;
159 if ( !$file ) {
160 $file = self::generateFileName( $wgSQLiteDataDir, $name );
161 }
162 $file = $this->addQuotes( $file );
163 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
164 }
165
166 /**
167 * @see DatabaseBase::isWriteQuery()
168 */
169 function isWriteQuery( $sql ) {
170 return parent::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
171 }
172
173 /**
174 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
175 */
176 function doQuery( $sql ) {
177 $res = $this->mConn->query( $sql );
178 if ( $res === false ) {
179 return false;
180 } else {
181 $r = $res instanceof ResultWrapper ? $res->result : $res;
182 $this->mAffectedRows = $r->rowCount();
183 $res = new ResultWrapper( $this, $r->fetchAll() );
184 }
185 return $res;
186 }
187
188 function freeResult( $res ) {
189 if ( $res instanceof ResultWrapper )
190 $res->result = null;
191 else
192 $res = null;
193 }
194
195 function fetchObject( $res ) {
196 if ( $res instanceof ResultWrapper )
197 $r =& $res->result;
198 else
199 $r =& $res;
200
201 $cur = current( $r );
202 if ( is_array( $cur ) ) {
203 next( $r );
204 $obj = new stdClass;
205 foreach ( $cur as $k => $v )
206 if ( !is_numeric( $k ) )
207 $obj->$k = $v;
208
209 return $obj;
210 }
211 return false;
212 }
213
214 function fetchRow( $res ) {
215 if ( $res instanceof ResultWrapper )
216 $r =& $res->result;
217 else
218 $r =& $res;
219
220 $cur = current( $r );
221 if ( is_array( $cur ) ) {
222 next( $r );
223 return $cur;
224 }
225 return false;
226 }
227
228 /**
229 * The PDO::Statement class implements the array interface so count() will work
230 */
231 function numRows( $res ) {
232 $r = $res instanceof ResultWrapper ? $res->result : $res;
233 return count( $r );
234 }
235
236 function numFields( $res ) {
237 $r = $res instanceof ResultWrapper ? $res->result : $res;
238 return is_array( $r ) ? count( $r[0] ) : 0;
239 }
240
241 function fieldName( $res, $n ) {
242 $r = $res instanceof ResultWrapper ? $res->result : $res;
243 if ( is_array( $r ) ) {
244 $keys = array_keys( $r[0] );
245 return $keys[$n];
246 }
247 return false;
248 }
249
250 /**
251 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
252 */
253 function tableName( $name ) {
254 return str_replace( '`', '', parent::tableName( $name ) );
255 }
256
257 /**
258 * Index names have DB scope
259 */
260 function indexName( $index ) {
261 return $index;
262 }
263
264 /**
265 * This must be called after nextSequenceVal
266 */
267 function insertId() {
268 return $this->mConn->lastInsertId();
269 }
270
271 function dataSeek( $res, $row ) {
272 if ( $res instanceof ResultWrapper )
273 $r =& $res->result;
274 else
275 $r =& $res;
276 reset( $r );
277 if ( $row > 0 )
278 for ( $i = 0; $i < $row; $i++ )
279 next( $r );
280 }
281
282 function lastError() {
283 if ( !is_object( $this->mConn ) )
284 return "Cannot return last error, no db connection";
285 $e = $this->mConn->errorInfo();
286 return isset( $e[2] ) ? $e[2] : '';
287 }
288
289 function lastErrno() {
290 if ( !is_object( $this->mConn ) ) {
291 return "Cannot return last error, no db connection";
292 } else {
293 $info = $this->mConn->errorInfo();
294 return $info[1];
295 }
296 }
297
298 function affectedRows() {
299 return $this->mAffectedRows;
300 }
301
302 /**
303 * Returns information about an index
304 * Returns false if the index does not exist
305 * - if errors are explicitly ignored, returns NULL on failure
306 */
307 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
308 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
309 $res = $this->query( $sql, $fname );
310 if ( !$res ) {
311 return null;
312 }
313 if ( $res->numRows() == 0 ) {
314 return false;
315 }
316 $info = array();
317 foreach ( $res as $row ) {
318 $info[] = $row->name;
319 }
320 return $info;
321 }
322
323 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
324 $row = $this->selectRow( 'sqlite_master', '*',
325 array(
326 'type' => 'index',
327 'name' => $this->indexName( $index ),
328 ), $fname );
329 if ( !$row || !isset( $row->sql ) ) {
330 return null;
331 }
332
333 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
334 $indexPos = strpos( $row->sql, 'INDEX' );
335 if ( $indexPos === false ) {
336 return null;
337 }
338 $firstPart = substr( $row->sql, 0, $indexPos );
339 $options = explode( ' ', $firstPart );
340 return in_array( 'UNIQUE', $options );
341 }
342
343 /**
344 * Filter the options used in SELECT statements
345 */
346 function makeSelectOptions( $options ) {
347 foreach ( $options as $k => $v )
348 if ( is_numeric( $k ) && $v == 'FOR UPDATE' )
349 $options[$k] = '';
350 return parent::makeSelectOptions( $options );
351 }
352
353 /**
354 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
355 */
356 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
357 if ( !count( $a ) ) return true;
358 if ( !is_array( $options ) ) $options = array( $options );
359
360 # SQLite uses OR IGNORE not just IGNORE
361 foreach ( $options as $k => $v )
362 if ( $v == 'IGNORE' )
363 $options[$k] = 'OR IGNORE';
364
365 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
366 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
367 $ret = true;
368 foreach ( $a as $k => $v )
369 if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) )
370 $ret = false;
371 } else {
372 $ret = parent::insert( $table, $a, "$fname/single-row", $options );
373 }
374
375 return $ret;
376 }
377
378 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
379 if ( !count( $rows ) ) return true;
380
381 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
382 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
383 $ret = true;
384 foreach ( $rows as $k => $v )
385 if ( !parent::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) )
386 $ret = false;
387 } else {
388 $ret = parent::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
389 }
390
391 return $ret;
392 }
393
394 /**
395 * Returns the size of a text field, or -1 for "unlimited"
396 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
397 */
398 function textFieldSize( $table, $field ) {
399 return - 1;
400 }
401
402 function unionSupportsOrderAndLimit() {
403 return false;
404 }
405
406 function unionQueries( $sqls, $all ) {
407 $glue = $all ? ' UNION ALL ' : ' UNION ';
408 return implode( $glue, $sqls );
409 }
410
411 function wasDeadlock() {
412 return $this->lastErrno() == 5; // SQLITE_BUSY
413 }
414
415 function wasErrorReissuable() {
416 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
417 }
418
419 function wasReadOnlyError() {
420 return $this->lastErrno() == 8; // SQLITE_READONLY;
421 }
422
423 /**
424 * @return string wikitext of a link to the server software's web site
425 */
426 function getSoftwareLink() {
427 return "[http://sqlite.org/ SQLite]";
428 }
429
430 /**
431 * @return string Version information from the database
432 */
433 function getServerVersion() {
434 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
435 return $ver;
436 }
437
438 /**
439 * Get information about a given field
440 * Returns false if the field does not exist.
441 */
442 function fieldInfo( $table, $field ) {
443 $tableName = $this->tableName( $table );
444 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
445 $res = $this->query( $sql, __METHOD__ );
446 foreach ( $res as $row ) {
447 if ( $row->name == $field ) {
448 return new SQLiteField( $row, $tableName );
449 }
450 }
451 return false;
452 }
453
454 function begin( $fname = '' ) {
455 if ( $this->mTrxLevel == 1 ) $this->commit();
456 $this->mConn->beginTransaction();
457 $this->mTrxLevel = 1;
458 }
459
460 function commit( $fname = '' ) {
461 if ( $this->mTrxLevel == 0 ) return;
462 $this->mConn->commit();
463 $this->mTrxLevel = 0;
464 }
465
466 function rollback( $fname = '' ) {
467 if ( $this->mTrxLevel == 0 ) return;
468 $this->mConn->rollBack();
469 $this->mTrxLevel = 0;
470 }
471
472 function limitResultForUpdate( $sql, $num ) {
473 return $this->limitResult( $sql, $num );
474 }
475
476 function strencode( $s ) {
477 return substr( $this->addQuotes( $s ), 1, - 1 );
478 }
479
480 function encodeBlob( $b ) {
481 return new Blob( $b );
482 }
483
484 function decodeBlob( $b ) {
485 if ( $b instanceof Blob ) {
486 $b = $b->fetch();
487 }
488 return $b;
489 }
490
491 function addQuotes( $s ) {
492 if ( $s instanceof Blob ) {
493 return "x'" . bin2hex( $s->fetch() ) . "'";
494 } else {
495 return $this->mConn->quote( $s );
496 }
497 }
498
499 function quote_ident( $s ) {
500 return $s;
501 }
502
503 function buildLike() {
504 $params = func_get_args();
505 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
506 $params = $params[0];
507 }
508 return parent::buildLike( $params ) . "ESCAPE '\' ";
509 }
510
511 /**
512 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
513 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
514 */
515 public function setup_database() {
516 global $IP;
517
518 # Process common MySQL/SQLite table definitions
519 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
520 if ( $err !== true ) {
521 echo " <b>FAILED</b></li>";
522 dieout( htmlspecialchars( $err ) );
523 }
524 echo " done.</li>";
525
526 # Use DatabasePostgres's code to populate interwiki from MySQL template
527 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
528 if ( !$f ) {
529 dieout( "Could not find the interwiki.sql file." );
530 }
531
532 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
533 while ( !feof( $f ) ) {
534 $line = fgets( $f, 1024 );
535 $matches = array();
536 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
537 $this->query( "$sql $matches[1],$matches[2])" );
538 }
539 }
540
541 public function getSearchEngine() {
542 return "SearchSqlite";
543 }
544
545 /**
546 * No-op version of deadlockLoop
547 */
548 public function deadlockLoop( /*...*/ ) {
549 $args = func_get_args();
550 $function = array_shift( $args );
551 return call_user_func_array( $function, $args );
552 }
553
554 protected function replaceVars( $s ) {
555 $s = parent::replaceVars( $s );
556 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
557 // CREATE TABLE hacks to allow schema file sharing with MySQL
558
559 // binary/varbinary column type -> blob
560 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
561 // no such thing as unsigned
562 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
563 // INT -> INTEGER
564 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\([\s\d]*\)|\b)/i', 'INTEGER', $s );
565 // varchar -> TEXT
566 $s = preg_replace( '/\bvarchar\(\d+\)/i', 'TEXT', $s );
567 // TEXT normalization
568 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
569 // BLOB normalization
570 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
571 // BOOL -> INTEGER
572 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
573 // DATETIME -> TEXT
574 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
575 // No ENUM type
576 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
577 // binary collation type -> nothing
578 $s = preg_replace( '/\bbinary\b/i', '', $s );
579 // auto_increment -> autoincrement
580 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
581 // No explicit options
582 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
583 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
584 // No truncated indexes
585 $s = preg_replace( '/\(\d+\)/', '', $s );
586 // No FULLTEXT
587 $s = preg_replace( '/\bfulltext\b/i', '', $s );
588 }
589 return $s;
590 }
591
592 /*
593 * Build a concatenation list to feed into a SQL query
594 */
595 function buildConcat( $stringList ) {
596 return '(' . implode( ') || (', $stringList ) . ')';
597 }
598
599 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
600 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
601 $obj = $this->fetchObject( $res );
602 if ( !$obj ) {
603 throw new MWException( "Couldn't retrieve structure for table $oldName" );
604 }
605 $sql = $obj->sql;
606 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
607 return $this->query( $sql, $fname );
608 }
609
610 } // end DatabaseSqlite class
611
612 /**
613 * This class allows simple acccess to a SQLite database independently from main database settings
614 * @ingroup Database
615 */
616 class DatabaseSqliteStandalone extends DatabaseSqlite {
617 public function __construct( $fileName, $flags = 0 ) {
618 $this->mFlags = $flags;
619 $this->openFile( $fileName );
620 }
621 }
622
623 /**
624 * @ingroup Database
625 */
626 class SQLiteField {
627 private $info, $tableName;
628 function __construct( $info, $tableName ) {
629 $this->info = $info;
630 $this->tableName = $tableName;
631 }
632
633 function name() {
634 return $this->info->name;
635 }
636
637 function tableName() {
638 return $this->tableName;
639 }
640
641 function defaultValue() {
642 if ( is_string( $this->info->dflt_value ) ) {
643 // Typically quoted
644 if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
645 return str_replace( "''", "'", $this->info->dflt_value );
646 }
647 }
648 return $this->info->dflt_value;
649 }
650
651 function maxLength() {
652 return -1;
653 }
654
655 function nullable() {
656 // SQLite dynamic types are always nullable
657 return true;
658 }
659
660 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
661 # Suggest removal from base class [TS]
662
663 function type() {
664 return $this->info->type;
665 }
666
667 } // end SQLiteField