Kill some crappy "failFunction" stuff, marked as old in r14625
[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 /**
37 * Serialization handler, see http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.sleep
38 * for details. Instances of this class sometimes get serialized, e.g. with Title and its BacklinkCache
39 * Because attempts to serialize mConn end in "can't serialize PDO objects" exceptions, we simply disallow
40 * to serialize anything in this class.
41 */
42 function __sleep() {
43 return array();
44 }
45
46 function getType() {
47 return 'sqlite';
48 }
49
50 /**
51 * @todo: check if it should be true like parent class
52 */
53 function implicitGroupby() { return false; }
54
55 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
56 return new DatabaseSqlite( $server, $user, $password, $dbName, $flags );
57 }
58
59 /** Open an SQLite database and return a resource handle to it
60 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
61 */
62 function open( $server, $user, $pass, $dbName ) {
63 global $wgSQLiteDataDir;
64
65 $fileName = self::generateFileName( $wgSQLiteDataDir, $dbName );
66 if ( !is_readable( $fileName ) ) {
67 throw new DBConnectionError( $this, "SQLite database not accessible" );
68 $this->mConn = false;
69 }
70 $this->openFile( $fileName );
71 return $this->mConn;
72 }
73
74 /**
75 * Opens a database file
76 * @return SQL connection or false if failed
77 */
78 function openFile( $fileName ) {
79 $this->mDatabaseFile = $fileName;
80 try {
81 if ( $this->mFlags & DBO_PERSISTENT ) {
82 $this->mConn = new PDO( "sqlite:$fileName", '', '',
83 array( PDO::ATTR_PERSISTENT => true ) );
84 } else {
85 $this->mConn = new PDO( "sqlite:$fileName", '', '' );
86 }
87 } catch ( PDOException $e ) {
88 $err = $e->getMessage();
89 }
90 if ( $this->mConn === false ) {
91 wfDebug( "DB connection error: $err\n" );
92 return false;
93 }
94 $this->mOpened = !!$this->mConn;
95 # set error codes only, don't raise exceptions
96 if ( $this->mOpened ) {
97 $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
98 return true;
99 }
100 }
101
102 /**
103 * Close an SQLite database
104 */
105 function close() {
106 $this->mOpened = false;
107 if ( is_object( $this->mConn ) ) {
108 if ( $this->trxLevel() ) $this->commit();
109 $this->mConn = null;
110 }
111 return true;
112 }
113
114 /**
115 * Generates a database file name. Explicitly public for installer.
116 * @param $dir String: Directory where database resides
117 * @param $dbName String: Database name
118 * @return String
119 */
120 public static function generateFileName( $dir, $dbName ) {
121 return "$dir/$dbName.sqlite";
122 }
123
124 /**
125 * Check if the searchindext table is FTS enabled.
126 * @returns false if not enabled.
127 */
128 function checkForEnabledSearch() {
129 if ( self::$fulltextEnabled === null ) {
130 self::$fulltextEnabled = false;
131 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = 'searchindex'", __METHOD__ );
132 if ( $res ) {
133 $row = $res->fetchRow();
134 self::$fulltextEnabled = stristr($row['sql'], 'fts' ) !== false;
135 }
136 }
137 return self::$fulltextEnabled;
138 }
139
140 /**
141 * Returns version of currently supported SQLite fulltext search module or false if none present.
142 * @return String
143 */
144 function getFulltextSearchModule() {
145 $table = 'dummy_search_test';
146 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__ );
147
148 if ( $this->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
149 $this->query( "DROP TABLE IF EXISTS $table", __METHOD__ );
150 return 'FTS3';
151 }
152 return false;
153 }
154
155 /**
156 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
157 * for details.
158 * @param $name String: database name to be used in queries like SELECT foo FROM dbname.table
159 * @param $file String: database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
160 * @param $fname String: calling function name
161 */
162 function attachDatabase( $name, $file = false, $fname = 'DatabaseSqlite::attachDatabase' ) {
163 global $wgSQLiteDataDir;
164 if ( !$file ) {
165 $file = self::generateFileName( $wgSQLiteDataDir, $name );
166 }
167 $file = $this->addQuotes( $file );
168 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
169 }
170
171 /**
172 * @see DatabaseBase::isWriteQuery()
173 */
174 function isWriteQuery( $sql ) {
175 return parent::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
176 }
177
178 /**
179 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
180 */
181 function doQuery( $sql ) {
182 $res = $this->mConn->query( $sql );
183 if ( $res === false ) {
184 return false;
185 } else {
186 $r = $res instanceof ResultWrapper ? $res->result : $res;
187 $this->mAffectedRows = $r->rowCount();
188 $res = new ResultWrapper( $this, $r->fetchAll() );
189 }
190 return $res;
191 }
192
193 function freeResult( $res ) {
194 if ( $res instanceof ResultWrapper )
195 $res->result = null;
196 else
197 $res = null;
198 }
199
200 function fetchObject( $res ) {
201 if ( $res instanceof ResultWrapper )
202 $r =& $res->result;
203 else
204 $r =& $res;
205
206 $cur = current( $r );
207 if ( is_array( $cur ) ) {
208 next( $r );
209 $obj = new stdClass;
210 foreach ( $cur as $k => $v )
211 if ( !is_numeric( $k ) )
212 $obj->$k = $v;
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 return str_replace( '`', '', parent::tableName( $name ) );
260 }
261
262 /**
263 * Index names have DB scope
264 */
265 function indexName( $index ) {
266 return $index;
267 }
268
269 /**
270 * This must be called after nextSequenceVal
271 */
272 function insertId() {
273 return $this->mConn->lastInsertId();
274 }
275
276 function dataSeek( $res, $row ) {
277 if ( $res instanceof ResultWrapper )
278 $r =& $res->result;
279 else
280 $r =& $res;
281 reset( $r );
282 if ( $row > 0 )
283 for ( $i = 0; $i < $row; $i++ )
284 next( $r );
285 }
286
287 function lastError() {
288 if ( !is_object( $this->mConn ) )
289 return "Cannot return last error, no db connection";
290 $e = $this->mConn->errorInfo();
291 return isset( $e[2] ) ? $e[2] : '';
292 }
293
294 function lastErrno() {
295 if ( !is_object( $this->mConn ) ) {
296 return "Cannot return last error, no db connection";
297 } else {
298 $info = $this->mConn->errorInfo();
299 return $info[1];
300 }
301 }
302
303 function affectedRows() {
304 return $this->mAffectedRows;
305 }
306
307 /**
308 * Returns information about an index
309 * Returns false if the index does not exist
310 * - if errors are explicitly ignored, returns NULL on failure
311 */
312 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
313 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
314 $res = $this->query( $sql, $fname );
315 if ( !$res ) {
316 return null;
317 }
318 if ( $res->numRows() == 0 ) {
319 return false;
320 }
321 $info = array();
322 foreach ( $res as $row ) {
323 $info[] = $row->name;
324 }
325 return $info;
326 }
327
328 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
329 $row = $this->selectRow( 'sqlite_master', '*',
330 array(
331 'type' => 'index',
332 'name' => $this->indexName( $index ),
333 ), $fname );
334 if ( !$row || !isset( $row->sql ) ) {
335 return null;
336 }
337
338 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
339 $indexPos = strpos( $row->sql, 'INDEX' );
340 if ( $indexPos === false ) {
341 return null;
342 }
343 $firstPart = substr( $row->sql, 0, $indexPos );
344 $options = explode( ' ', $firstPart );
345 return in_array( 'UNIQUE', $options );
346 }
347
348 /**
349 * Filter the options used in SELECT statements
350 */
351 function makeSelectOptions( $options ) {
352 foreach ( $options as $k => $v )
353 if ( is_numeric( $k ) && $v == 'FOR UPDATE' )
354 $options[$k] = '';
355 return parent::makeSelectOptions( $options );
356 }
357
358 /**
359 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
360 */
361 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
362 if ( !count( $a ) ) return true;
363 if ( !is_array( $options ) ) $options = array( $options );
364
365 # SQLite uses OR IGNORE not just IGNORE
366 foreach ( $options as $k => $v )
367 if ( $v == 'IGNORE' )
368 $options[$k] = 'OR IGNORE';
369
370 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
371 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
372 $ret = true;
373 foreach ( $a as $k => $v )
374 if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) )
375 $ret = false;
376 } else {
377 $ret = parent::insert( $table, $a, "$fname/single-row", $options );
378 }
379
380 return $ret;
381 }
382
383 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
384 if ( !count( $rows ) ) return true;
385
386 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
387 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
388 $ret = true;
389 foreach ( $rows as $k => $v )
390 if ( !parent::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) )
391 $ret = false;
392 } else {
393 $ret = parent::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
394 }
395
396 return $ret;
397 }
398
399 /**
400 * Returns the size of a text field, or -1 for "unlimited"
401 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
402 */
403 function textFieldSize( $table, $field ) {
404 return - 1;
405 }
406
407 function unionSupportsOrderAndLimit() {
408 return false;
409 }
410
411 function unionQueries( $sqls, $all ) {
412 $glue = $all ? ' UNION ALL ' : ' UNION ';
413 return implode( $glue, $sqls );
414 }
415
416 function wasDeadlock() {
417 return $this->lastErrno() == 5; // SQLITE_BUSY
418 }
419
420 function wasErrorReissuable() {
421 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
422 }
423
424 function wasReadOnlyError() {
425 return $this->lastErrno() == 8; // SQLITE_READONLY;
426 }
427
428 /**
429 * @return string wikitext of a link to the server software's web site
430 */
431 function getSoftwareLink() {
432 return "[http://sqlite.org/ SQLite]";
433 }
434
435 /**
436 * @return string Version information from the database
437 */
438 function getServerVersion() {
439 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
440 return $ver;
441 }
442
443 /**
444 * Get information about a given field
445 * Returns false if the field does not exist.
446 */
447 function fieldInfo( $table, $field ) {
448 $tableName = $this->tableName( $table );
449 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
450 $res = $this->query( $sql, __METHOD__ );
451 foreach ( $res as $row ) {
452 if ( $row->name == $field ) {
453 return new SQLiteField( $row, $tableName );
454 }
455 }
456 return false;
457 }
458
459 function begin( $fname = '' ) {
460 if ( $this->mTrxLevel == 1 ) $this->commit();
461 $this->mConn->beginTransaction();
462 $this->mTrxLevel = 1;
463 }
464
465 function commit( $fname = '' ) {
466 if ( $this->mTrxLevel == 0 ) return;
467 $this->mConn->commit();
468 $this->mTrxLevel = 0;
469 }
470
471 function rollback( $fname = '' ) {
472 if ( $this->mTrxLevel == 0 ) return;
473 $this->mConn->rollBack();
474 $this->mTrxLevel = 0;
475 }
476
477 function limitResultForUpdate( $sql, $num ) {
478 return $this->limitResult( $sql, $num );
479 }
480
481 function strencode( $s ) {
482 return substr( $this->addQuotes( $s ), 1, - 1 );
483 }
484
485 function encodeBlob( $b ) {
486 return new Blob( $b );
487 }
488
489 function decodeBlob( $b ) {
490 if ( $b instanceof Blob ) {
491 $b = $b->fetch();
492 }
493 return $b;
494 }
495
496 function addQuotes( $s ) {
497 if ( $s instanceof Blob ) {
498 return "x'" . bin2hex( $s->fetch() ) . "'";
499 } else {
500 return $this->mConn->quote( $s );
501 }
502 }
503
504 function quote_ident( $s ) {
505 return $s;
506 }
507
508 function buildLike() {
509 $params = func_get_args();
510 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
511 $params = $params[0];
512 }
513 return parent::buildLike( $params ) . "ESCAPE '\' ";
514 }
515
516 /**
517 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
518 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
519 */
520 public function setup_database() {
521 global $IP;
522
523 # Process common MySQL/SQLite table definitions
524 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
525 if ( $err !== true ) {
526 echo " <b>FAILED</b></li>";
527 dieout( htmlspecialchars( $err ) );
528 }
529 echo " done.</li>";
530
531 # Use DatabasePostgres's code to populate interwiki from MySQL template
532 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
533 if ( !$f ) {
534 dieout( "Could not find the interwiki.sql file." );
535 }
536
537 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
538 while ( !feof( $f ) ) {
539 $line = fgets( $f, 1024 );
540 $matches = array();
541 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
542 $this->query( "$sql $matches[1],$matches[2])" );
543 }
544 }
545
546 public function getSearchEngine() {
547 return "SearchSqlite";
548 }
549
550 /**
551 * No-op version of deadlockLoop
552 */
553 public function deadlockLoop( /*...*/ ) {
554 $args = func_get_args();
555 $function = array_shift( $args );
556 return call_user_func_array( $function, $args );
557 }
558
559 protected function replaceVars( $s ) {
560 $s = parent::replaceVars( $s );
561 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
562 // CREATE TABLE hacks to allow schema file sharing with MySQL
563
564 // binary/varbinary column type -> blob
565 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
566 // no such thing as unsigned
567 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
568 // INT -> INTEGER
569 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\([\s\d]*\)|\b)/i', 'INTEGER', $s );
570 // varchar -> TEXT
571 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
572 // TEXT normalization
573 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
574 // BLOB normalization
575 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
576 // BOOL -> INTEGER
577 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
578 // DATETIME -> TEXT
579 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
580 // No ENUM type
581 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
582 // binary collation type -> nothing
583 $s = preg_replace( '/\bbinary\b/i', '', $s );
584 // auto_increment -> autoincrement
585 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
586 // No explicit options
587 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
588 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
589 // No truncated indexes
590 $s = preg_replace( '/\(\d+\)/', '', $s );
591 // No FULLTEXT
592 $s = preg_replace( '/\bfulltext\b/i', '', $s );
593 }
594 return $s;
595 }
596
597 /*
598 * Build a concatenation list to feed into a SQL query
599 */
600 function buildConcat( $stringList ) {
601 return '(' . implode( ') || (', $stringList ) . ')';
602 }
603
604 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
605 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
606 $obj = $this->fetchObject( $res );
607 if ( !$obj ) {
608 throw new MWException( "Couldn't retrieve structure for table $oldName" );
609 }
610 $sql = $obj->sql;
611 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
612 return $this->query( $sql, $fname );
613 }
614
615 } // end DatabaseSqlite class
616
617 /**
618 * This class allows simple acccess to a SQLite database independently from main database settings
619 * @ingroup Database
620 */
621 class DatabaseSqliteStandalone extends DatabaseSqlite {
622 public function __construct( $fileName, $flags = 0 ) {
623 $this->mFlags = $flags;
624 $this->openFile( $fileName );
625 }
626 }
627
628 /**
629 * @ingroup Database
630 */
631 class SQLiteField {
632 private $info, $tableName;
633 function __construct( $info, $tableName ) {
634 $this->info = $info;
635 $this->tableName = $tableName;
636 }
637
638 function name() {
639 return $this->info->name;
640 }
641
642 function tableName() {
643 return $this->tableName;
644 }
645
646 function defaultValue() {
647 if ( is_string( $this->info->dflt_value ) ) {
648 // Typically quoted
649 if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
650 return str_replace( "''", "'", $this->info->dflt_value );
651 }
652 }
653 return $this->info->dflt_value;
654 }
655
656 function maxLength() {
657 return -1;
658 }
659
660 function nullable() {
661 // SQLite dynamic types are always nullable
662 return true;
663 }
664
665 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
666 # Suggest removal from base class [TS]
667
668 function type() {
669 return $this->info->type;
670 }
671
672 } // end SQLiteField