Bug 28478: database error in DatabaseSqlite::getFulltextSearchModule().
[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 $this->mName = $dbName;
28 parent::__construct( $server, $user, $password, $dbName, $flags );
29 // parent doesn't open when $user is false, but we can work with $dbName
30 if( !$user && $dbName ) {
31 global $wgSharedDB;
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 static function getFulltextSearchModule() {
134 static $cachedResult = null;
135 if ( $cachedResult !== null ) {
136 return $cachedResult;
137 }
138 $cachedResult = false;
139 $table = 'dummy_search_test';
140
141 $db = new DatabaseSqliteStandalone( ':memory:' );
142
143 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
144 $cachedResult = 'FTS3';
145 }
146 $db->close();
147 return $cachedResult;
148 }
149
150 /**
151 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
152 * for details.
153 * @param $name String: database name to be used in queries like SELECT foo FROM dbname.table
154 * @param $file String: database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
155 * @param $fname String: calling function name
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
196 function fetchObject( $res ) {
197 if ( $res instanceof ResultWrapper ) {
198 $r =& $res->result;
199 } else {
200 $r =& $res;
201 }
202
203 $cur = current( $r );
204 if ( is_array( $cur ) ) {
205 next( $r );
206 $obj = new stdClass;
207 foreach ( $cur as $k => $v ) {
208 if ( !is_numeric( $k ) ) {
209 $obj->$k = $v;
210 }
211 }
212
213 return $obj;
214 }
215 return false;
216 }
217
218 function fetchRow( $res ) {
219 if ( $res instanceof ResultWrapper ) {
220 $r =& $res->result;
221 } else {
222 $r =& $res;
223 }
224 $cur = current( $r );
225 if ( is_array( $cur ) ) {
226 next( $r );
227 return $cur;
228 }
229 return false;
230 }
231
232 /**
233 * The PDO::Statement class implements the array interface so count() will work
234 */
235 function numRows( $res ) {
236 $r = $res instanceof ResultWrapper ? $res->result : $res;
237 return count( $r );
238 }
239
240 function numFields( $res ) {
241 $r = $res instanceof ResultWrapper ? $res->result : $res;
242 return is_array( $r ) ? count( $r[0] ) : 0;
243 }
244
245 function fieldName( $res, $n ) {
246 $r = $res instanceof ResultWrapper ? $res->result : $res;
247 if ( is_array( $r ) ) {
248 $keys = array_keys( $r[0] );
249 return $keys[$n];
250 }
251 return false;
252 }
253
254 /**
255 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
256 */
257 function tableName( $name ) {
258 // table names starting with sqlite_ are reserved
259 if ( strpos( $name, 'sqlite_' ) === 0 ) return $name;
260 return str_replace( '`', '', parent::tableName( $name ) );
261 }
262
263 /**
264 * Index names have DB scope
265 */
266 function indexName( $index ) {
267 return $index;
268 }
269
270 /**
271 * This must be called after nextSequenceVal
272 */
273 function insertId() {
274 return $this->mConn->lastInsertId();
275 }
276
277 function dataSeek( $res, $row ) {
278 if ( $res instanceof ResultWrapper ) {
279 $r =& $res->result;
280 } else {
281 $r =& $res;
282 }
283 reset( $r );
284 if ( $row > 0 ) {
285 for ( $i = 0; $i < $row; $i++ ) {
286 next( $r );
287 }
288 }
289 }
290
291 function lastError() {
292 if ( !is_object( $this->mConn ) ) {
293 return "Cannot return last error, no db connection";
294 }
295 $e = $this->mConn->errorInfo();
296 return isset( $e[2] ) ? $e[2] : '';
297 }
298
299 function lastErrno() {
300 if ( !is_object( $this->mConn ) ) {
301 return "Cannot return last error, no db connection";
302 } else {
303 $info = $this->mConn->errorInfo();
304 return $info[1];
305 }
306 }
307
308 function affectedRows() {
309 return $this->mAffectedRows;
310 }
311
312 /**
313 * Returns information about an index
314 * Returns false if the index does not exist
315 * - if errors are explicitly ignored, returns NULL on failure
316 */
317 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
318 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
319 $res = $this->query( $sql, $fname );
320 if ( !$res ) {
321 return null;
322 }
323 if ( $res->numRows() == 0 ) {
324 return false;
325 }
326 $info = array();
327 foreach ( $res as $row ) {
328 $info[] = $row->name;
329 }
330 return $info;
331 }
332
333 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
334 $row = $this->selectRow( 'sqlite_master', '*',
335 array(
336 'type' => 'index',
337 'name' => $this->indexName( $index ),
338 ), $fname );
339 if ( !$row || !isset( $row->sql ) ) {
340 return null;
341 }
342
343 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
344 $indexPos = strpos( $row->sql, 'INDEX' );
345 if ( $indexPos === false ) {
346 return null;
347 }
348 $firstPart = substr( $row->sql, 0, $indexPos );
349 $options = explode( ' ', $firstPart );
350 return in_array( 'UNIQUE', $options );
351 }
352
353 /**
354 * Filter the options used in SELECT statements
355 */
356 function makeSelectOptions( $options ) {
357 foreach ( $options as $k => $v ) {
358 if ( is_numeric( $k ) && $v == 'FOR UPDATE' ) {
359 $options[$k] = '';
360 }
361 }
362 return parent::makeSelectOptions( $options );
363 }
364
365 /**
366 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
367 */
368 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
369 if ( !count( $a ) ) {
370 return true;
371 }
372 if ( !is_array( $options ) ) {
373 $options = array( $options );
374 }
375
376 # SQLite uses OR IGNORE not just IGNORE
377 foreach ( $options as $k => $v ) {
378 if ( $v == 'IGNORE' ) {
379 $options[$k] = 'OR IGNORE';
380 }
381 }
382
383 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
384 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
385 $ret = true;
386 foreach ( $a as $v ) {
387 if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) ) {
388 $ret = false;
389 }
390 }
391 } else {
392 $ret = parent::insert( $table, $a, "$fname/single-row", $options );
393 }
394
395 return $ret;
396 }
397
398 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
399 if ( !count( $rows ) ) return true;
400
401 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
402 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
403 $ret = true;
404 foreach ( $rows as $v ) {
405 if ( !parent::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) ) {
406 $ret = false;
407 }
408 }
409 } else {
410 $ret = parent::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
411 }
412
413 return $ret;
414 }
415
416 /**
417 * Returns the size of a text field, or -1 for "unlimited"
418 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
419 */
420 function textFieldSize( $table, $field ) {
421 return -1;
422 }
423
424 function unionSupportsOrderAndLimit() {
425 return false;
426 }
427
428 function unionQueries( $sqls, $all ) {
429 $glue = $all ? ' UNION ALL ' : ' UNION ';
430 return implode( $glue, $sqls );
431 }
432
433 function wasDeadlock() {
434 return $this->lastErrno() == 5; // SQLITE_BUSY
435 }
436
437 function wasErrorReissuable() {
438 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
439 }
440
441 function wasReadOnlyError() {
442 return $this->lastErrno() == 8; // SQLITE_READONLY;
443 }
444
445 /**
446 * @return string wikitext of a link to the server software's web site
447 */
448 public static function getSoftwareLink() {
449 return "[http://sqlite.org/ SQLite]";
450 }
451
452 /**
453 * @return string Version information from the database
454 */
455 function getServerVersion() {
456 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
457 return $ver;
458 }
459
460 /**
461 * @return string User-friendly database information
462 */
463 public function getServerInfo() {
464 return wfMsg( self::getFulltextSearchModule() ? 'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() );
465 }
466
467 /**
468 * Get information about a given field
469 * Returns false if the field does not exist.
470 */
471 function fieldInfo( $table, $field ) {
472 $tableName = $this->tableName( $table );
473 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
474 $res = $this->query( $sql, __METHOD__ );
475 foreach ( $res as $row ) {
476 if ( $row->name == $field ) {
477 return new SQLiteField( $row, $tableName );
478 }
479 }
480 return false;
481 }
482
483 function begin( $fname = '' ) {
484 if ( $this->mTrxLevel == 1 ) $this->commit();
485 $this->mConn->beginTransaction();
486 $this->mTrxLevel = 1;
487 }
488
489 function commit( $fname = '' ) {
490 if ( $this->mTrxLevel == 0 ) return;
491 $this->mConn->commit();
492 $this->mTrxLevel = 0;
493 }
494
495 function rollback( $fname = '' ) {
496 if ( $this->mTrxLevel == 0 ) return;
497 $this->mConn->rollBack();
498 $this->mTrxLevel = 0;
499 }
500
501 function limitResultForUpdate( $sql, $num ) {
502 return $this->limitResult( $sql, $num );
503 }
504
505 function strencode( $s ) {
506 return substr( $this->addQuotes( $s ), 1, - 1 );
507 }
508
509 function encodeBlob( $b ) {
510 return new Blob( $b );
511 }
512
513 function decodeBlob( $b ) {
514 if ( $b instanceof Blob ) {
515 $b = $b->fetch();
516 }
517 return $b;
518 }
519
520 function addQuotes( $s ) {
521 if ( $s instanceof Blob ) {
522 return "x'" . bin2hex( $s->fetch() ) . "'";
523 } else {
524 return $this->mConn->quote( $s );
525 }
526 }
527
528 function buildLike() {
529 $params = func_get_args();
530 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
531 $params = $params[0];
532 }
533 return parent::buildLike( $params ) . "ESCAPE '\' ";
534 }
535
536 public function getSearchEngine() {
537 return "SearchSqlite";
538 }
539
540 /**
541 * No-op version of deadlockLoop
542 */
543 public function deadlockLoop( /*...*/ ) {
544 $args = func_get_args();
545 $function = array_shift( $args );
546 return call_user_func_array( $function, $args );
547 }
548
549 protected function replaceVars( $s ) {
550 $s = parent::replaceVars( $s );
551 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
552 // CREATE TABLE hacks to allow schema file sharing with MySQL
553
554 // binary/varbinary column type -> blob
555 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
556 // no such thing as unsigned
557 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
558 // INT -> INTEGER
559 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
560 // floating point types -> REAL
561 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
562 // varchar -> TEXT
563 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
564 // TEXT normalization
565 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
566 // BLOB normalization
567 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
568 // BOOL -> INTEGER
569 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
570 // DATETIME -> TEXT
571 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
572 // No ENUM type
573 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
574 // binary collation type -> nothing
575 $s = preg_replace( '/\bbinary\b/i', '', $s );
576 // auto_increment -> autoincrement
577 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
578 // No explicit options
579 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
580 // AUTOINCREMENT should immedidately follow PRIMARY KEY
581 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
582 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
583 // No truncated indexes
584 $s = preg_replace( '/\(\d+\)/', '', $s );
585 // No FULLTEXT
586 $s = preg_replace( '/\bfulltext\b/i', '', $s );
587 }
588 return $s;
589 }
590
591 /*
592 * Build a concatenation list to feed into a SQL query
593 */
594 function buildConcat( $stringList ) {
595 return '(' . implode( ') || (', $stringList ) . ')';
596 }
597
598 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
599
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 if ( $temporary ) {
608 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
609 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
610 } else {
611 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
612 }
613 }
614 return $this->query( $sql, $fname );
615 }
616
617
618 /**
619 * List all tables on the database
620 *
621 * @param $prefix Only show tables with this prefix, e.g. mw_
622 * @param $fname String: calling function name
623 */
624 function listTables( $prefix = null, $fname = 'DatabaseSqlite::listTables' ) {
625 $result = $this->select(
626 'sqlite_master',
627 'name',
628 "type='table'"
629 );
630
631 $endArray = array();
632
633 foreach( $result as $table ) {
634 $vars = get_object_vars($table);
635 $table = array_pop( $vars );
636
637 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
638 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
639 $endArray[] = $table;
640 }
641
642 }
643 }
644
645 return $endArray;
646 }
647
648 } // end DatabaseSqlite class
649
650 /**
651 * This class allows simple acccess to a SQLite database independently from main database settings
652 * @ingroup Database
653 */
654 class DatabaseSqliteStandalone extends DatabaseSqlite {
655 public function __construct( $fileName, $flags = 0 ) {
656 $this->mFlags = $flags;
657 $this->tablePrefix( null );
658 $this->openFile( $fileName );
659 }
660 }
661
662 /**
663 * @ingroup Database
664 */
665 class SQLiteField implements Field {
666 private $info, $tableName;
667 function __construct( $info, $tableName ) {
668 $this->info = $info;
669 $this->tableName = $tableName;
670 }
671
672 function name() {
673 return $this->info->name;
674 }
675
676 function tableName() {
677 return $this->tableName;
678 }
679
680 function defaultValue() {
681 if ( is_string( $this->info->dflt_value ) ) {
682 // Typically quoted
683 if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
684 return str_replace( "''", "'", $this->info->dflt_value );
685 }
686 }
687 return $this->info->dflt_value;
688 }
689
690 function isNullable() {
691 return !$this->info->notnull;
692 }
693
694 function type() {
695 return $this->info->type;
696 }
697
698 } // end SQLiteField