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