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