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