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