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