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