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