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