b963a2f7242856238f9dff6f96e6251ef2eabef8
[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, $fileame = false ) {
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 generic 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 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
323 if ( !count( $rows ) ) return true;
324
325 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
326 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
327 $ret = true;
328 foreach ( $rows as $k => $v )
329 if ( !parent::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) )
330 $ret = false;
331 } else {
332 $ret = parent::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
333 }
334
335 return $ret;
336 }
337
338 /**
339 * Returns the size of a text field, or -1 for "unlimited"
340 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
341 */
342 function textFieldSize( $table, $field ) {
343 return - 1;
344 }
345
346 function unionSupportsOrderAndLimit() {
347 return false;
348 }
349
350 function unionQueries( $sqls, $all ) {
351 $glue = $all ? ' UNION ALL ' : ' UNION ';
352 return implode( $glue, $sqls );
353 }
354
355 function wasDeadlock() {
356 return $this->lastErrno() == 5; // SQLITE_BUSY
357 }
358
359 function wasErrorReissuable() {
360 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
361 }
362
363 function wasReadOnlyError() {
364 return $this->lastErrno() == 8; // SQLITE_READONLY;
365 }
366
367 /**
368 * @return string wikitext of a link to the server software's web site
369 */
370 function getSoftwareLink() {
371 return "[http://sqlite.org/ SQLite]";
372 }
373
374 /**
375 * @return string Version information from the database
376 */
377 function getServerVersion() {
378 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
379 return $ver;
380 }
381
382 /**
383 * Query whether a given column exists in the mediawiki schema
384 */
385 function fieldExists( $table, $field, $fname = '' ) {
386 $info = $this->fieldInfo( $table, $field );
387 return (bool)$info;
388 }
389
390 /**
391 * Get information about a given field
392 * Returns false if the field does not exist.
393 */
394 function fieldInfo( $table, $field ) {
395 $tableName = $this->tableName( $table );
396 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
397 $res = $this->query( $sql, __METHOD__ );
398 foreach ( $res as $row ) {
399 if ( $row->name == $field ) {
400 return new SQLiteField( $row, $tableName );
401 }
402 }
403 return false;
404 }
405
406 function begin( $fname = '' ) {
407 if ( $this->mTrxLevel == 1 ) $this->commit();
408 $this->mConn->beginTransaction();
409 $this->mTrxLevel = 1;
410 }
411
412 function commit( $fname = '' ) {
413 if ( $this->mTrxLevel == 0 ) return;
414 $this->mConn->commit();
415 $this->mTrxLevel = 0;
416 }
417
418 function rollback( $fname = '' ) {
419 if ( $this->mTrxLevel == 0 ) return;
420 $this->mConn->rollBack();
421 $this->mTrxLevel = 0;
422 }
423
424 function limitResultForUpdate( $sql, $num ) {
425 return $this->limitResult( $sql, $num );
426 }
427
428 function strencode( $s ) {
429 return substr( $this->addQuotes( $s ), 1, - 1 );
430 }
431
432 function encodeBlob( $b ) {
433 return new Blob( $b );
434 }
435
436 function decodeBlob( $b ) {
437 if ( $b instanceof Blob ) {
438 $b = $b->fetch();
439 }
440 return $b;
441 }
442
443 function addQuotes( $s ) {
444 if ( $s instanceof Blob ) {
445 return "x'" . bin2hex( $s->fetch() ) . "'";
446 } else {
447 return $this->mConn->quote( $s );
448 }
449 }
450
451 function quote_ident( $s ) {
452 return $s;
453 }
454
455 function buildLike() {
456 $params = func_get_args();
457 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
458 $params = $params[0];
459 }
460 return parent::buildLike( $params ) . "ESCAPE '\' ";
461 }
462
463 /**
464 * How lagged is this slave?
465 */
466 public function getLag() {
467 return 0;
468 }
469
470 /**
471 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
472 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
473 */
474 public function setup_database() {
475 global $IP;
476
477 # Process common MySQL/SQLite table definitions
478 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
479 if ( $err !== true ) {
480 $this->reportQueryError( $err, 0, $sql, __FUNCTION__ );
481 exit( 1 );
482 }
483
484 # Use DatabasePostgres's code to populate interwiki from MySQL template
485 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
486 if ( $f == false ) dieout( "<li>Could not find the interwiki.sql file" );
487 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
488 while ( !feof( $f ) ) {
489 $line = fgets( $f, 1024 );
490 $matches = array();
491 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
492 $this->query( "$sql $matches[1],$matches[2])" );
493 }
494 }
495
496 public function getSearchEngine() {
497 return "SearchSqlite";
498 }
499
500 /**
501 * No-op version of deadlockLoop
502 */
503 public function deadlockLoop( /*...*/ ) {
504 $args = func_get_args();
505 $function = array_shift( $args );
506 return call_user_func_array( $function, $args );
507 }
508
509 protected function replaceVars( $s ) {
510 $s = parent::replaceVars( $s );
511 if ( preg_match( '/^\s*CREATE TABLE/i', $s ) ) {
512 // CREATE TABLE hacks to allow schema file sharing with MySQL
513
514 // binary/varbinary column type -> blob
515 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'blob\1', $s );
516 // no such thing as unsigned
517 $s = preg_replace( '/\bunsigned\b/i', '', $s );
518 // INT -> INTEGER for primary keys
519 $s = preg_replacE( '/\bint\b/i', 'integer', $s );
520 // No ENUM type
521 $s = preg_replace( '/enum\([^)]*\)/i', 'blob', $s );
522 // binary collation type -> nothing
523 $s = preg_replace( '/\bbinary\b/i', '', $s );
524 // auto_increment -> autoincrement
525 $s = preg_replace( '/\bauto_increment\b/i', 'autoincrement', $s );
526 // No explicit options
527 $s = preg_replace( '/\)[^)]*$/', ')', $s );
528 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
529 // No truncated indexes
530 $s = preg_replace( '/\(\d+\)/', '', $s );
531 // No FULLTEXT
532 $s = preg_replace( '/\bfulltext\b/i', '', $s );
533 }
534 return $s;
535 }
536
537 /*
538 * Build a concatenation list to feed into a SQL query
539 */
540 function buildConcat( $stringList ) {
541 return '(' . implode( ') || (', $stringList ) . ')';
542 }
543
544 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
545 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
546 $sql = $this->fetchObject( $res )->sql;
547 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
548 return $this->query( $sql, $fname );
549 }
550
551 } // end DatabaseSqlite class
552
553 /**
554 * @ingroup Database
555 */
556 class SQLiteField {
557 private $info, $tableName;
558 function __construct( $info, $tableName ) {
559 $this->info = $info;
560 $this->tableName = $tableName;
561 }
562
563 function name() {
564 return $this->info->name;
565 }
566
567 function tableName() {
568 return $this->tableName;
569 }
570
571 function defaultValue() {
572 if ( is_string( $this->info->dflt_value ) ) {
573 // Typically quoted
574 if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
575 return str_replace( "''", "'", $this->info->dflt_value );
576 }
577 }
578 return $this->info->dflt_value;
579 }
580
581 function maxLength() {
582 return -1;
583 }
584
585 function nullable() {
586 // SQLite dynamic types are always nullable
587 return true;
588 }
589
590 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
591 # Suggest removal from base class [TS]
592
593 function type() {
594 return $this->info->type;
595 }
596
597 } // end SQLiteField