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