(bug 20256) Fixed SQL errors on Special:Recentchanges and Special:Recentchangeslinked...
[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 unionSupportsOrderAndLimit() {
303 return false;
304 }
305
306 function unionQueries( $sqls, $all ) {
307 $glue = $all ? ' UNION ALL ' : ' UNION ';
308 return implode( $glue, $sqls );
309 }
310
311 function wasDeadlock() {
312 return $this->lastErrno() == SQLITE_BUSY;
313 }
314
315 function wasErrorReissuable() {
316 return $this->lastErrno() == SQLITE_SCHEMA;
317 }
318
319 function wasReadOnlyError() {
320 return $this->lastErrno() == SQLITE_READONLY;
321 }
322
323 /**
324 * @return string wikitext of a link to the server software's web site
325 */
326 function getSoftwareLink() {
327 return "[http://sqlite.org/ SQLite]";
328 }
329
330 /**
331 * @return string Version information from the database
332 */
333 function getServerVersion() {
334 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
335 return $ver;
336 }
337
338 /**
339 * Query whether a given column exists in the mediawiki schema
340 */
341 function fieldExists( $table, $field, $fname = '' ) {
342 $info = $this->fieldInfo( $table, $field );
343 return (bool)$info;
344 }
345
346 /**
347 * Get information about a given field
348 * Returns false if the field does not exist.
349 */
350 function fieldInfo( $table, $field ) {
351 $tableName = $this->tableName( $table );
352 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
353 $res = $this->query( $sql, __METHOD__ );
354 foreach ( $res as $row ) {
355 if ( $row->name == $field ) {
356 return new SQLiteField( $row, $tableName );
357 }
358 }
359 return false;
360 }
361
362 function begin( $fname = '' ) {
363 if ( $this->mTrxLevel == 1 ) $this->commit();
364 $this->mConn->beginTransaction();
365 $this->mTrxLevel = 1;
366 }
367
368 function commit( $fname = '' ) {
369 if ( $this->mTrxLevel == 0 ) return;
370 $this->mConn->commit();
371 $this->mTrxLevel = 0;
372 }
373
374 function rollback( $fname = '' ) {
375 if ( $this->mTrxLevel == 0 ) return;
376 $this->mConn->rollBack();
377 $this->mTrxLevel = 0;
378 }
379
380 function limitResultForUpdate( $sql, $num ) {
381 return $this->limitResult( $sql, $num );
382 }
383
384 function strencode( $s ) {
385 return substr( $this->addQuotes( $s ), 1, - 1 );
386 }
387
388 function encodeBlob( $b ) {
389 return new Blob( $b );
390 }
391
392 function decodeBlob( $b ) {
393 if ( $b instanceof Blob ) {
394 $b = $b->fetch();
395 }
396 return $b;
397 }
398
399 function addQuotes( $s ) {
400 if ( $s instanceof Blob ) {
401 return "x'" . bin2hex( $s->fetch() ) . "'";
402 } else {
403 return $this->mConn->quote( $s );
404 }
405 }
406
407 function quote_ident( $s ) {
408 return $s;
409 }
410
411 /**
412 * How lagged is this slave?
413 */
414 public function getLag() {
415 return 0;
416 }
417
418 /**
419 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
420 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
421 */
422 public function setup_database() {
423 global $IP, $wgSQLiteDataDir, $wgDBTableOptions;
424 $wgDBTableOptions = '';
425
426 # Process common MySQL/SQLite table definitions
427 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
428 if ( $err !== true ) {
429 $this->reportQueryError( $err, 0, $sql, __FUNCTION__ );
430 exit( 1 );
431 }
432
433 # Use DatabasePostgres's code to populate interwiki from MySQL template
434 $f = fopen( "$IP/maintenance/interwiki.sql", 'r' );
435 if ( $f == false ) dieout( "<li>Could not find the interwiki.sql file" );
436 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
437 while ( !feof( $f ) ) {
438 $line = fgets( $f, 1024 );
439 $matches = array();
440 if ( !preg_match( '/^\s*(\(.+?),(\d)\)/', $line, $matches ) ) continue;
441 $this->query( "$sql $matches[1],$matches[2])" );
442 }
443 }
444
445 public function getSearchEngine() {
446 return "SearchEngineDummy";
447 }
448
449 /**
450 * No-op version of deadlockLoop
451 */
452 public function deadlockLoop( /*...*/ ) {
453 $args = func_get_args();
454 $function = array_shift( $args );
455 return call_user_func_array( $function, $args );
456 }
457
458 protected function replaceVars( $s ) {
459 $s = parent::replaceVars( $s );
460 if ( preg_match( '/^\s*CREATE TABLE/i', $s ) ) {
461 // CREATE TABLE hacks to allow schema file sharing with MySQL
462
463 // binary/varbinary column type -> blob
464 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'blob\1', $s );
465 // no such thing as unsigned
466 $s = preg_replace( '/\bunsigned\b/i', '', $s );
467 // INT -> INTEGER for primary keys
468 $s = preg_replacE( '/\bint\b/i', 'integer', $s );
469 // No ENUM type
470 $s = preg_replace( '/enum\([^)]*\)/i', 'blob', $s );
471 // binary collation type -> nothing
472 $s = preg_replace( '/\bbinary\b/i', '', $s );
473 // auto_increment -> autoincrement
474 $s = preg_replace( '/\bauto_increment\b/i', 'autoincrement', $s );
475 // No explicit options
476 $s = preg_replace( '/\)[^)]*$/', ')', $s );
477 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
478 // No truncated indexes
479 $s = preg_replace( '/\(\d+\)/', '', $s );
480 // No FULLTEXT
481 $s = preg_replace( '/\bfulltext\b/i', '', $s );
482 }
483 return $s;
484 }
485
486 /*
487 * Build a concatenation list to feed into a SQL query
488 */
489 function buildConcat( $stringList ) {
490 return '(' . implode( ') || (', $stringList ) . ')';
491 }
492
493 } // end DatabaseSqlite class
494
495 /**
496 * @ingroup Database
497 */
498 class SQLiteField {
499 private $info, $tableName;
500 function __construct( $info, $tableName ) {
501 $this->info = $info;
502 $this->tableName = $tableName;
503 }
504
505 function name() {
506 return $this->info->name;
507 }
508
509 function tableName() {
510 return $this->tableName;
511 }
512
513 function defaultValue() {
514 if ( is_string( $this->info->dflt_value ) ) {
515 // Typically quoted
516 if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
517 return str_replace( "''", "'", $this->info->dflt_value );
518 }
519 }
520 return $this->info->dflt_value;
521 }
522
523 function maxLength() {
524 return -1;
525 }
526
527 function nullable() {
528 // SQLite dynamic types are always nullable
529 return true;
530 }
531
532 # isKey(), isMultipleKey() not implemented, MySQL-specific concept.
533 # Suggest removal from base class [TS]
534
535 function type() {
536 return $this->info->type;
537 }
538
539 } // end SQLiteField