Fix function level comments that start with /* not /**
[lhc/web/wiklou.git] / includes / db / DatabaseSqlite.php
1 <?php
2 /**
3 * This is the SQLite database abstraction layer.
4 * See maintenance/sqlite/README for development notes and other specific information
5 *
6 * @file
7 * @ingroup Database
8 */
9
10 /**
11 * @ingroup Database
12 */
13 class DatabaseSqlite extends DatabaseBase {
14
15 private static $fulltextEnabled = null;
16
17 var $mAffectedRows;
18 var $mLastResult;
19 var $mDatabaseFile;
20 var $mName;
21
22 /**
23 * Constructor.
24 * Parameters $server, $user and $password are not used.
25 */
26 function __construct( $server = false, $user = false, $password = false, $dbName = false, $flags = 0 ) {
27 $this->mName = $dbName;
28 parent::__construct( $server, $user, $password, $dbName, $flags );
29 // parent doesn't open when $user is false, but we can work with $dbName
30 if( !$user && $dbName ) {
31 global $wgSharedDB;
32 if( $this->open( $server, $user, $password, $dbName ) && $wgSharedDB ) {
33 $this->attachDatabase( $wgSharedDB );
34 }
35 }
36 }
37
38 function getType() {
39 return 'sqlite';
40 }
41
42 /**
43 * @todo: check if it should be true like parent class
44 */
45 function implicitGroupby() { return false; }
46
47 /** Open an SQLite database and return a resource handle to it
48 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
49 */
50 function open( $server, $user, $pass, $dbName ) {
51 global $wgSQLiteDataDir;
52
53 $fileName = self::generateFileName( $wgSQLiteDataDir, $dbName );
54 if ( !is_readable( $fileName ) ) {
55 $this->mConn = false;
56 throw new DBConnectionError( $this, "SQLite database not accessible" );
57 }
58 $this->openFile( $fileName );
59 return $this->mConn;
60 }
61
62 /**
63 * Opens a database file
64 * @return SQL connection or false if failed
65 */
66 function openFile( $fileName ) {
67 $this->mDatabaseFile = $fileName;
68 try {
69 if ( $this->mFlags & DBO_PERSISTENT ) {
70 $this->mConn = new PDO( "sqlite:$fileName", '', '',
71 array( PDO::ATTR_PERSISTENT => true ) );
72 } else {
73 $this->mConn = new PDO( "sqlite:$fileName", '', '' );
74 }
75 } catch ( PDOException $e ) {
76 $err = $e->getMessage();
77 }
78 if ( !$this->mConn ) {
79 wfDebug( "DB connection error: $err\n" );
80 throw new DBConnectionError( $this, $err );
81 }
82 $this->mOpened = !!$this->mConn;
83 # set error codes only, don't raise exceptions
84 if ( $this->mOpened ) {
85 $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
86 return true;
87 }
88 }
89
90 /**
91 * Close an SQLite database
92 *
93 * @return bool
94 */
95 function close() {
96 $this->mOpened = false;
97 if ( is_object( $this->mConn ) ) {
98 if ( $this->trxLevel() ) $this->commit();
99 $this->mConn = null;
100 }
101 return true;
102 }
103
104 /**
105 * Generates a database file name. Explicitly public for installer.
106 * @param $dir String: Directory where database resides
107 * @param $dbName String: Database name
108 * @return String
109 */
110 public static function generateFileName( $dir, $dbName ) {
111 return "$dir/$dbName.sqlite";
112 }
113
114 /**
115 * Check if the searchindext table is FTS enabled.
116 * @return false if not enabled.
117 */
118 function checkForEnabledSearch() {
119 if ( self::$fulltextEnabled === null ) {
120 self::$fulltextEnabled = false;
121 $table = $this->tableName( 'searchindex' );
122 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
123 if ( $res ) {
124 $row = $res->fetchRow();
125 self::$fulltextEnabled = stristr($row['sql'], 'fts' ) !== false;
126 }
127 }
128 return self::$fulltextEnabled;
129 }
130
131 /**
132 * Returns version of currently supported SQLite fulltext search module or false if none present.
133 * @return String
134 */
135 static function getFulltextSearchModule() {
136 static $cachedResult = null;
137 if ( $cachedResult !== null ) {
138 return $cachedResult;
139 }
140 $cachedResult = false;
141 $table = 'dummy_search_test';
142
143 $db = new DatabaseSqliteStandalone( ':memory:' );
144
145 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
146 $cachedResult = 'FTS3';
147 }
148 $db->close();
149 return $cachedResult;
150 }
151
152 /**
153 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
154 * for details.
155 * @param $name String: database name to be used in queries like SELECT foo FROM dbname.table
156 * @param $file String: database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
157 * @param $fname String: calling function name
158 */
159 function attachDatabase( $name, $file = false, $fname = 'DatabaseSqlite::attachDatabase' ) {
160 global $wgSQLiteDataDir;
161 if ( !$file ) {
162 $file = self::generateFileName( $wgSQLiteDataDir, $name );
163 }
164 $file = $this->addQuotes( $file );
165 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
166 }
167
168 /**
169 * @see DatabaseBase::isWriteQuery()
170 *
171 * @return bool
172 */
173 function isWriteQuery( $sql ) {
174 return parent::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
175 }
176
177 /**
178 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
179 */
180 function doQuery( $sql ) {
181 $res = $this->mConn->query( $sql );
182 if ( $res === false ) {
183 return false;
184 } else {
185 $r = $res instanceof ResultWrapper ? $res->result : $res;
186 $this->mAffectedRows = $r->rowCount();
187 $res = new ResultWrapper( $this, $r->fetchAll() );
188 }
189 return $res;
190 }
191
192 function freeResult( $res ) {
193 if ( $res instanceof ResultWrapper ) {
194 $res->result = null;
195 } else {
196 $res = null;
197 }
198 }
199
200 function fetchObject( $res ) {
201 if ( $res instanceof ResultWrapper ) {
202 $r =& $res->result;
203 } else {
204 $r =& $res;
205 }
206
207 $cur = current( $r );
208 if ( is_array( $cur ) ) {
209 next( $r );
210 $obj = new stdClass;
211 foreach ( $cur as $k => $v ) {
212 if ( !is_numeric( $k ) ) {
213 $obj->$k = $v;
214 }
215 }
216
217 return $obj;
218 }
219 return false;
220 }
221
222 function fetchRow( $res ) {
223 if ( $res instanceof ResultWrapper ) {
224 $r =& $res->result;
225 } else {
226 $r =& $res;
227 }
228 $cur = current( $r );
229 if ( is_array( $cur ) ) {
230 next( $r );
231 return $cur;
232 }
233 return false;
234 }
235
236 /**
237 * The PDO::Statement class implements the array interface so count() will work
238 */
239 function numRows( $res ) {
240 $r = $res instanceof ResultWrapper ? $res->result : $res;
241 return count( $r );
242 }
243
244 function numFields( $res ) {
245 $r = $res instanceof ResultWrapper ? $res->result : $res;
246 return is_array( $r ) ? count( $r[0] ) : 0;
247 }
248
249 function fieldName( $res, $n ) {
250 $r = $res instanceof ResultWrapper ? $res->result : $res;
251 if ( is_array( $r ) ) {
252 $keys = array_keys( $r[0] );
253 return $keys[$n];
254 }
255 return false;
256 }
257
258 /**
259 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
260 */
261 function tableName( $name, $quoted = true ) {
262 // table names starting with sqlite_ are reserved
263 if ( strpos( $name, 'sqlite_' ) === 0 ) return $name;
264 return str_replace( '"', '', parent::tableName( $name, $quoted ) );
265 }
266
267 /**
268 * Index names have DB scope
269 */
270 function indexName( $index ) {
271 return $index;
272 }
273
274 /**
275 * This must be called after nextSequenceVal
276 */
277 function insertId() {
278 return $this->mConn->lastInsertId();
279 }
280
281 function dataSeek( $res, $row ) {
282 if ( $res instanceof ResultWrapper ) {
283 $r =& $res->result;
284 } else {
285 $r =& $res;
286 }
287 reset( $r );
288 if ( $row > 0 ) {
289 for ( $i = 0; $i < $row; $i++ ) {
290 next( $r );
291 }
292 }
293 }
294
295 function lastError() {
296 if ( !is_object( $this->mConn ) ) {
297 return "Cannot return last error, no db connection";
298 }
299 $e = $this->mConn->errorInfo();
300 return isset( $e[2] ) ? $e[2] : '';
301 }
302
303 function lastErrno() {
304 if ( !is_object( $this->mConn ) ) {
305 return "Cannot return last error, no db connection";
306 } else {
307 $info = $this->mConn->errorInfo();
308 return $info[1];
309 }
310 }
311
312 function affectedRows() {
313 return $this->mAffectedRows;
314 }
315
316 /**
317 * Returns information about an index
318 * Returns false if the index does not exist
319 * - if errors are explicitly ignored, returns NULL on failure
320 */
321 function indexInfo( $table, $index, $fname = 'DatabaseSqlite::indexExists' ) {
322 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
323 $res = $this->query( $sql, $fname );
324 if ( !$res ) {
325 return null;
326 }
327 if ( $res->numRows() == 0 ) {
328 return false;
329 }
330 $info = array();
331 foreach ( $res as $row ) {
332 $info[] = $row->name;
333 }
334 return $info;
335 }
336
337 function indexUnique( $table, $index, $fname = 'DatabaseSqlite::indexUnique' ) {
338 $row = $this->selectRow( 'sqlite_master', '*',
339 array(
340 'type' => 'index',
341 'name' => $this->indexName( $index ),
342 ), $fname );
343 if ( !$row || !isset( $row->sql ) ) {
344 return null;
345 }
346
347 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
348 $indexPos = strpos( $row->sql, 'INDEX' );
349 if ( $indexPos === false ) {
350 return null;
351 }
352 $firstPart = substr( $row->sql, 0, $indexPos );
353 $options = explode( ' ', $firstPart );
354 return in_array( 'UNIQUE', $options );
355 }
356
357 /**
358 * Filter the options used in SELECT statements
359 */
360 function makeSelectOptions( $options ) {
361 foreach ( $options as $k => $v ) {
362 if ( is_numeric( $k ) && $v == 'FOR UPDATE' ) {
363 $options[$k] = '';
364 }
365 }
366 return parent::makeSelectOptions( $options );
367 }
368
369 /**
370 * @param $options array
371 * @return string
372 */
373 function makeUpdateOptions( $options ) {
374 $options = self::fixIgnore( $options );
375 return parent::makeUpdateOptions( $options );
376 }
377
378 /**
379 * @param $options array
380 * @return array
381 */
382 static function fixIgnore( $options ) {
383 # SQLite uses OR IGNORE not just IGNORE
384 foreach ( $options as $k => $v ) {
385 if ( $v == 'IGNORE' ) {
386 $options[$k] = 'OR IGNORE';
387 }
388 }
389 return $options;
390 }
391
392 /**
393 * @param $options array
394 * @return string
395 */
396 function makeInsertOptions( $options ) {
397 $options = self::fixIgnore( $options );
398 return parent::makeInsertOptions( $options );
399 }
400
401 /**
402 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
403 */
404 function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
405 if ( !count( $a ) ) {
406 return true;
407 }
408
409 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
410 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
411 $ret = true;
412 foreach ( $a as $v ) {
413 if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) ) {
414 $ret = false;
415 }
416 }
417 } else {
418 $ret = parent::insert( $table, $a, "$fname/single-row", $options );
419 }
420
421 return $ret;
422 }
423
424 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
425 if ( !count( $rows ) ) return true;
426
427 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
428 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
429 $ret = true;
430 foreach ( $rows as $v ) {
431 if ( !parent::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) ) {
432 $ret = false;
433 }
434 }
435 } else {
436 $ret = parent::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
437 }
438
439 return $ret;
440 }
441
442 /**
443 * Returns the size of a text field, or -1 for "unlimited"
444 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
445 */
446 function textFieldSize( $table, $field ) {
447 return -1;
448 }
449
450 function unionSupportsOrderAndLimit() {
451 return false;
452 }
453
454 function unionQueries( $sqls, $all ) {
455 $glue = $all ? ' UNION ALL ' : ' UNION ';
456 return implode( $glue, $sqls );
457 }
458
459 function wasDeadlock() {
460 return $this->lastErrno() == 5; // SQLITE_BUSY
461 }
462
463 function wasErrorReissuable() {
464 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
465 }
466
467 function wasReadOnlyError() {
468 return $this->lastErrno() == 8; // SQLITE_READONLY;
469 }
470
471 /**
472 * @return string wikitext of a link to the server software's web site
473 */
474 public static function getSoftwareLink() {
475 return "[http://sqlite.org/ SQLite]";
476 }
477
478 /**
479 * @return string Version information from the database
480 */
481 function getServerVersion() {
482 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
483 return $ver;
484 }
485
486 /**
487 * @return string User-friendly database information
488 */
489 public function getServerInfo() {
490 return wfMsg( self::getFulltextSearchModule() ? 'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() );
491 }
492
493 /**
494 * Get information about a given field
495 * Returns false if the field does not exist.
496 *
497 * @return SQLiteField|false
498 */
499 function fieldInfo( $table, $field ) {
500 $tableName = $this->tableName( $table );
501 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
502 $res = $this->query( $sql, __METHOD__ );
503 foreach ( $res as $row ) {
504 if ( $row->name == $field ) {
505 return new SQLiteField( $row, $tableName );
506 }
507 }
508 return false;
509 }
510
511 function begin( $fname = '' ) {
512 if ( $this->mTrxLevel == 1 ) $this->commit();
513 $this->mConn->beginTransaction();
514 $this->mTrxLevel = 1;
515 }
516
517 function commit( $fname = '' ) {
518 if ( $this->mTrxLevel == 0 ) return;
519 $this->mConn->commit();
520 $this->mTrxLevel = 0;
521 }
522
523 function rollback( $fname = '' ) {
524 if ( $this->mTrxLevel == 0 ) return;
525 $this->mConn->rollBack();
526 $this->mTrxLevel = 0;
527 }
528
529 function limitResultForUpdate( $sql, $num ) {
530 return $this->limitResult( $sql, $num );
531 }
532
533 function strencode( $s ) {
534 return substr( $this->addQuotes( $s ), 1, - 1 );
535 }
536
537 function encodeBlob( $b ) {
538 return new Blob( $b );
539 }
540
541 function decodeBlob( $b ) {
542 if ( $b instanceof Blob ) {
543 $b = $b->fetch();
544 }
545 return $b;
546 }
547
548 function addQuotes( $s ) {
549 if ( $s instanceof Blob ) {
550 return "x'" . bin2hex( $s->fetch() ) . "'";
551 } else {
552 return $this->mConn->quote( $s );
553 }
554 }
555
556 function buildLike() {
557 $params = func_get_args();
558 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
559 $params = $params[0];
560 }
561 return parent::buildLike( $params ) . "ESCAPE '\' ";
562 }
563
564 public function getSearchEngine() {
565 return "SearchSqlite";
566 }
567
568 /**
569 * No-op version of deadlockLoop
570 */
571 public function deadlockLoop( /*...*/ ) {
572 $args = func_get_args();
573 $function = array_shift( $args );
574 return call_user_func_array( $function, $args );
575 }
576
577 /**
578 * @param $s string
579 * @return string
580 */
581 protected function replaceVars( $s ) {
582 $s = parent::replaceVars( $s );
583 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
584 // CREATE TABLE hacks to allow schema file sharing with MySQL
585
586 // binary/varbinary column type -> blob
587 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
588 // no such thing as unsigned
589 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
590 // INT -> INTEGER
591 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
592 // floating point types -> REAL
593 $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
594 // varchar -> TEXT
595 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
596 // TEXT normalization
597 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
598 // BLOB normalization
599 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
600 // BOOL -> INTEGER
601 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
602 // DATETIME -> TEXT
603 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
604 // No ENUM type
605 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
606 // binary collation type -> nothing
607 $s = preg_replace( '/\bbinary\b/i', '', $s );
608 // auto_increment -> autoincrement
609 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
610 // No explicit options
611 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
612 // AUTOINCREMENT should immedidately follow PRIMARY KEY
613 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
614 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
615 // No truncated indexes
616 $s = preg_replace( '/\(\d+\)/', '', $s );
617 // No FULLTEXT
618 $s = preg_replace( '/\bfulltext\b/i', '', $s );
619 }
620 return $s;
621 }
622
623 /**
624 * Build a concatenation list to feed into a SQL query
625 *
626 * @return string
627 */
628 function buildConcat( $stringList ) {
629 return '(' . implode( ') || (', $stringList ) . ')';
630 }
631
632 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
633 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" . $this->addQuotes( $oldName ) . " AND type='table'", $fname );
634 $obj = $this->fetchObject( $res );
635 if ( !$obj ) {
636 throw new MWException( "Couldn't retrieve structure for table $oldName" );
637 }
638 $sql = $obj->sql;
639 $sql = preg_replace( '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/', $this->addIdentifierQuotes( $newName ), $sql, 1 );
640 if ( $temporary ) {
641 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
642 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
643 } else {
644 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
645 }
646 }
647 return $this->query( $sql, $fname );
648 }
649
650
651 /**
652 * List all tables on the database
653 *
654 * @param $prefix Only show tables with this prefix, e.g. mw_
655 * @param $fname String: calling function name
656 *
657 * @return array
658 */
659 function listTables( $prefix = null, $fname = 'DatabaseSqlite::listTables' ) {
660 $result = $this->select(
661 'sqlite_master',
662 'name',
663 "type='table'"
664 );
665
666 $endArray = array();
667
668 foreach( $result as $table ) {
669 $vars = get_object_vars($table);
670 $table = array_pop( $vars );
671
672 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
673 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
674 $endArray[] = $table;
675 }
676
677 }
678 }
679
680 return $endArray;
681 }
682
683 } // end DatabaseSqlite class
684
685 /**
686 * This class allows simple acccess to a SQLite database independently from main database settings
687 * @ingroup Database
688 */
689 class DatabaseSqliteStandalone extends DatabaseSqlite {
690 public function __construct( $fileName, $flags = 0 ) {
691 $this->mFlags = $flags;
692 $this->tablePrefix( null );
693 $this->openFile( $fileName );
694 }
695 }
696
697 /**
698 * @ingroup Database
699 */
700 class SQLiteField implements Field {
701 private $info, $tableName;
702 function __construct( $info, $tableName ) {
703 $this->info = $info;
704 $this->tableName = $tableName;
705 }
706
707 function name() {
708 return $this->info->name;
709 }
710
711 function tableName() {
712 return $this->tableName;
713 }
714
715 function defaultValue() {
716 if ( is_string( $this->info->dflt_value ) ) {
717 // Typically quoted
718 if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
719 return str_replace( "''", "'", $this->info->dflt_value );
720 }
721 }
722 return $this->info->dflt_value;
723 }
724
725 function isNullable() {
726 return !$this->info->notnull;
727 }
728
729 function type() {
730 return $this->info->type;
731 }
732
733 } // end SQLiteField