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