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