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