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