Add makeInsertOptions
[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, $quoted = true ) {
258 // table names starting with sqlite_ are reserved
259 if ( strpos( $name, 'sqlite_' ) === 0 ) return $name;
260 return str_replace( '"', '', parent::tableName( $name, $quoted ) );
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 * @param $options array
367 * @return string
368 */
369 function makeUpdateOptions( $options ) {
370 $options = self::fixIgnore( $options );
371 return parent::makeUpdateOptions( $options );
372 }
373
374 /**
375 * @param $options array
376 * @return array
377 */
378 static function fixIgnore( $options ) {
379 # SQLite uses OR IGNORE not just IGNORE
380 foreach ( $options as $k => $v ) {
381 if ( $v == 'IGNORE' ) {
382 $options[$k] = 'OR IGNORE';
383 }
384 }
385 return $options;
386 }
387
388 /**
389 * @param $options array
390 * @return string
391 */
392 function makeInsertOptions( &$options ) {
393 $options = self::fixIgnore( $options );
394 return parent::makeInsertOptions( $options );
395 }
396
397 /**
398 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
399 */
400 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
401 if ( !count( $a ) ) {
402 return true;
403 }
404
405 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
406 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
407 $ret = true;
408 foreach ( $a as $v ) {
409 if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) ) {
410 $ret = false;
411 }
412 }
413 } else {
414 $ret = parent::insert( $table, $a, "$fname/single-row", $options );
415 }
416
417 return $ret;
418 }
419
420 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
421 if ( !count( $rows ) ) return true;
422
423 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
424 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
425 $ret = true;
426 foreach ( $rows as $v ) {
427 if ( !parent::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) ) {
428 $ret = false;
429 }
430 }
431 } else {
432 $ret = parent::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
433 }
434
435 return $ret;
436 }
437
438 /**
439 * Returns the size of a text field, or -1 for "unlimited"
440 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
441 */
442 function textFieldSize( $table, $field ) {
443 return -1;
444 }
445
446 function unionSupportsOrderAndLimit() {
447 return false;
448 }
449
450 function unionQueries( $sqls, $all ) {
451 $glue = $all ? ' UNION ALL ' : ' UNION ';
452 return implode( $glue, $sqls );
453 }
454
455 function wasDeadlock() {
456 return $this->lastErrno() == 5; // SQLITE_BUSY
457 }
458
459 function wasErrorReissuable() {
460 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
461 }
462
463 function wasReadOnlyError() {
464 return $this->lastErrno() == 8; // SQLITE_READONLY;
465 }
466
467 /**
468 * @return string wikitext of a link to the server software's web site
469 */
470 public static function getSoftwareLink() {
471 return "[http://sqlite.org/ SQLite]";
472 }
473
474 /**
475 * @return string Version information from the database
476 */
477 function getServerVersion() {
478 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
479 return $ver;
480 }
481
482 /**
483 * @return string User-friendly database information
484 */
485 public function getServerInfo() {
486 return wfMsg( self::getFulltextSearchModule() ? 'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() );
487 }
488
489 /**
490 * Get information about a given field
491 * Returns false if the field does not exist.
492 */
493 function fieldInfo( $table, $field ) {
494 $tableName = $this->tableName( $table );
495 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
496 $res = $this->query( $sql, __METHOD__ );
497 foreach ( $res as $row ) {
498 if ( $row->name == $field ) {
499 return new SQLiteField( $row, $tableName );
500 }
501 }
502 return false;
503 }
504
505 function begin( $fname = '' ) {
506 if ( $this->mTrxLevel == 1 ) $this->commit();
507 $this->mConn->beginTransaction();
508 $this->mTrxLevel = 1;
509 }
510
511 function commit( $fname = '' ) {
512 if ( $this->mTrxLevel == 0 ) return;
513 $this->mConn->commit();
514 $this->mTrxLevel = 0;
515 }
516
517 function rollback( $fname = '' ) {
518 if ( $this->mTrxLevel == 0 ) return;
519 $this->mConn->rollBack();
520 $this->mTrxLevel = 0;
521 }
522
523 function limitResultForUpdate( $sql, $num ) {
524 return $this->limitResult( $sql, $num );
525 }
526
527 function strencode( $s ) {
528 return substr( $this->addQuotes( $s ), 1, - 1 );
529 }
530
531 function encodeBlob( $b ) {
532 return new Blob( $b );
533 }
534
535 function decodeBlob( $b ) {
536 if ( $b instanceof Blob ) {
537 $b = $b->fetch();
538 }
539 return $b;
540 }
541
542 function addQuotes( $s ) {
543 if ( $s instanceof Blob ) {
544 return "x'" . bin2hex( $s->fetch() ) . "'";
545 } else {
546 return $this->mConn->quote( $s );
547 }
548 }
549
550 function buildLike() {
551 $params = func_get_args();
552 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
553 $params = $params[0];
554 }
555 return parent::buildLike( $params ) . "ESCAPE '\' ";
556 }
557
558 public function getSearchEngine() {
559 return "SearchSqlite";
560 }
561
562 /**
563 * No-op version of deadlockLoop
564 */
565 public function deadlockLoop( /*...*/ ) {
566 $args = func_get_args();
567 $function = array_shift( $args );
568 return call_user_func_array( $function, $args );
569 }
570
571 protected function replaceVars( $s ) {
572 $s = parent::replaceVars( $s );
573 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
574 // CREATE TABLE hacks to allow schema file sharing with MySQL
575
576 // binary/varbinary column type -> blob
577 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
578 // no such thing as unsigned
579 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
580 // INT -> INTEGER
581 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
582 // floating point types -> REAL
583 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
584 // varchar -> TEXT
585 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
586 // TEXT normalization
587 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
588 // BLOB normalization
589 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
590 // BOOL -> INTEGER
591 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
592 // DATETIME -> TEXT
593 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
594 // No ENUM type
595 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
596 // binary collation type -> nothing
597 $s = preg_replace( '/\bbinary\b/i', '', $s );
598 // auto_increment -> autoincrement
599 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
600 // No explicit options
601 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
602 // AUTOINCREMENT should immedidately follow PRIMARY KEY
603 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
604 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
605 // No truncated indexes
606 $s = preg_replace( '/\(\d+\)/', '', $s );
607 // No FULLTEXT
608 $s = preg_replace( '/\bfulltext\b/i', '', $s );
609 }
610 return $s;
611 }
612
613 /*
614 * Build a concatenation list to feed into a SQL query
615 */
616 function buildConcat( $stringList ) {
617 return '(' . implode( ') || (', $stringList ) . ')';
618 }
619
620 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
621 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" . $this->addQuotes( $oldName ) . " AND type='table'", $fname );
622 $obj = $this->fetchObject( $res );
623 if ( !$obj ) {
624 throw new MWException( "Couldn't retrieve structure for table $oldName" );
625 }
626 $sql = $obj->sql;
627 $sql = preg_replace( '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/', $this->addIdentifierQuotes( $newName ), $sql, 1 );
628 if ( $temporary ) {
629 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
630 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
631 } else {
632 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
633 }
634 }
635 return $this->query( $sql, $fname );
636 }
637
638
639 /**
640 * List all tables on the database
641 *
642 * @param $prefix Only show tables with this prefix, e.g. mw_
643 * @param $fname String: calling function name
644 */
645 function listTables( $prefix = null, $fname = 'DatabaseSqlite::listTables' ) {
646 $result = $this->select(
647 'sqlite_master',
648 'name',
649 "type='table'"
650 );
651
652 $endArray = array();
653
654 foreach( $result as $table ) {
655 $vars = get_object_vars($table);
656 $table = array_pop( $vars );
657
658 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
659 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
660 $endArray[] = $table;
661 }
662
663 }
664 }
665
666 return $endArray;
667 }
668
669 } // end DatabaseSqlite class
670
671 /**
672 * This class allows simple acccess to a SQLite database independently from main database settings
673 * @ingroup Database
674 */
675 class DatabaseSqliteStandalone extends DatabaseSqlite {
676 public function __construct( $fileName, $flags = 0 ) {
677 $this->mFlags = $flags;
678 $this->tablePrefix( null );
679 $this->openFile( $fileName );
680 }
681 }
682
683 /**
684 * @ingroup Database
685 */
686 class SQLiteField implements Field {
687 private $info, $tableName;
688 function __construct( $info, $tableName ) {
689 $this->info = $info;
690 $this->tableName = $tableName;
691 }
692
693 function name() {
694 return $this->info->name;
695 }
696
697 function tableName() {
698 return $this->tableName;
699 }
700
701 function defaultValue() {
702 if ( is_string( $this->info->dflt_value ) ) {
703 // Typically quoted
704 if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
705 return str_replace( "''", "'", $this->info->dflt_value );
706 }
707 }
708 return $this->info->dflt_value;
709 }
710
711 function isNullable() {
712 return !$this->info->notnull;
713 }
714
715 function type() {
716 return $this->info->type;
717 }
718
719 } // end SQLiteField