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