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