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