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