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