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