Added some lock()/unlock() support for SQLite using lock file emulation
[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 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 * @ingroup Database
23 */
24
25 /**
26 * @ingroup Database
27 */
28 class DatabaseSqlite extends DatabaseBase {
29 /** @var bool Whether full text is enabled */
30 private static $fulltextEnabled = null;
31
32 /** @var string File name for SQLite database file */
33 public $mDatabaseFile;
34
35 /** @var int The number of rows affected as an integer */
36 protected $mAffectedRows;
37
38 /** @var resource */
39 protected $mLastResult;
40
41 /** @var PDO */
42 protected $mConn;
43
44 /** @var FSLockManager (hopefully on the same server as the DB) */
45 protected $lockMgr;
46
47 function __construct( $p = null ) {
48 global $wgSharedDB, $wgSQLiteDataDir;
49
50 if ( !is_array( $p ) ) { // legacy calling pattern
51 wfDeprecated( __METHOD__ . " method called without parameter array.", "1.22" );
52 $args = func_get_args();
53 $p = array(
54 'host' => isset( $args[0] ) ? $args[0] : false,
55 'user' => isset( $args[1] ) ? $args[1] : false,
56 'password' => isset( $args[2] ) ? $args[2] : false,
57 'dbname' => isset( $args[3] ) ? $args[3] : false,
58 'flags' => isset( $args[4] ) ? $args[4] : 0,
59 'tablePrefix' => isset( $args[5] ) ? $args[5] : 'get from global',
60 'foreign' => isset( $args[6] ) ? $args[6] : false
61 );
62 }
63 $this->mDBname = $p['dbname'];
64 parent::__construct( $p );
65 // parent doesn't open when $user is false, but we can work with $dbName
66 if ( $p['dbname'] && !$this->isOpen() ) {
67 if ( $this->open( $p['host'], $p['user'], $p['password'], $p['dbname'] ) ) {
68 if ( $wgSharedDB ) {
69 $this->attachDatabase( $wgSharedDB );
70 }
71 }
72 }
73
74 $this->lockMgr = new FSLockManager( array( 'lockDirectory' => "$wgSQLiteDataDir/locks" ) );
75 }
76
77 /**
78 * @return string
79 */
80 function getType() {
81 return 'sqlite';
82 }
83
84 /**
85 * @todo Check if it should be true like parent class
86 *
87 * @return bool
88 */
89 function implicitGroupby() {
90 return false;
91 }
92
93 /** Open an SQLite database and return a resource handle to it
94 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
95 *
96 * @param string $server
97 * @param string $user
98 * @param string $pass
99 * @param string $dbName
100 *
101 * @throws DBConnectionError
102 * @return PDO
103 */
104 function open( $server, $user, $pass, $dbName ) {
105 global $wgSQLiteDataDir;
106
107 $this->close();
108 $fileName = self::generateFileName( $wgSQLiteDataDir, $dbName );
109 if ( !is_readable( $fileName ) ) {
110 $this->mConn = false;
111 throw new DBConnectionError( $this, "SQLite database not accessible" );
112 }
113 $this->openFile( $fileName );
114
115 return $this->mConn;
116 }
117
118 /**
119 * Opens a database file
120 *
121 * @param string $fileName
122 * @throws DBConnectionError
123 * @return PDO|bool SQL connection or false if failed
124 */
125 function openFile( $fileName ) {
126 $err = false;
127
128 $this->mDatabaseFile = $fileName;
129 try {
130 if ( $this->mFlags & DBO_PERSISTENT ) {
131 $this->mConn = new PDO( "sqlite:$fileName", '', '',
132 array( PDO::ATTR_PERSISTENT => true ) );
133 } else {
134 $this->mConn = new PDO( "sqlite:$fileName", '', '' );
135 }
136 } catch ( PDOException $e ) {
137 $err = $e->getMessage();
138 }
139
140 if ( !$this->mConn ) {
141 wfDebug( "DB connection error: $err\n" );
142 throw new DBConnectionError( $this, $err );
143 }
144
145 $this->mOpened = !!$this->mConn;
146 # set error codes only, don't raise exceptions
147 if ( $this->mOpened ) {
148 $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
149 # Enforce LIKE to be case sensitive, just like MySQL
150 $this->query( 'PRAGMA case_sensitive_like = 1' );
151
152 return $this->mConn;
153 }
154
155 return false;
156 }
157
158 /**
159 * Does not actually close the connection, just destroys the reference for GC to do its work
160 * @return bool
161 */
162 protected function closeConnection() {
163 $this->mConn = null;
164
165 return true;
166 }
167
168 /**
169 * Generates a database file name. Explicitly public for installer.
170 * @param string $dir Directory where database resides
171 * @param string $dbName Database name
172 * @return string
173 */
174 public static function generateFileName( $dir, $dbName ) {
175 return "$dir/$dbName.sqlite";
176 }
177
178 /**
179 * Check if the searchindext table is FTS enabled.
180 * @return bool False if not enabled.
181 */
182 function checkForEnabledSearch() {
183 if ( self::$fulltextEnabled === null ) {
184 self::$fulltextEnabled = false;
185 $table = $this->tableName( 'searchindex' );
186 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
187 if ( $res ) {
188 $row = $res->fetchRow();
189 self::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
190 }
191 }
192
193 return self::$fulltextEnabled;
194 }
195
196 /**
197 * Returns version of currently supported SQLite fulltext search module or false if none present.
198 * @return string
199 */
200 static function getFulltextSearchModule() {
201 static $cachedResult = null;
202 if ( $cachedResult !== null ) {
203 return $cachedResult;
204 }
205 $cachedResult = false;
206 $table = 'dummy_search_test';
207
208 $db = new DatabaseSqliteStandalone( ':memory:' );
209
210 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
211 $cachedResult = 'FTS3';
212 }
213 $db->close();
214
215 return $cachedResult;
216 }
217
218 /**
219 * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
220 * for details.
221 *
222 * @param string $name Database name to be used in queries like
223 * SELECT foo FROM dbname.table
224 * @param bool|string $file Database file name. If omitted, will be generated
225 * using $name and $wgSQLiteDataDir
226 * @param string $fname Calling function name
227 * @return ResultWrapper
228 */
229 function attachDatabase( $name, $file = false, $fname = __METHOD__ ) {
230 global $wgSQLiteDataDir;
231 if ( !$file ) {
232 $file = self::generateFileName( $wgSQLiteDataDir, $name );
233 }
234 $file = $this->addQuotes( $file );
235
236 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
237 }
238
239 /**
240 * @see DatabaseBase::isWriteQuery()
241 *
242 * @param $sql string
243 * @return bool
244 */
245 function isWriteQuery( $sql ) {
246 return parent::isWriteQuery( $sql ) && !preg_match( '/^ATTACH\b/i', $sql );
247 }
248
249 /**
250 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
251 *
252 * @param string $sql
253 * @return bool|ResultWrapper
254 */
255 protected function doQuery( $sql ) {
256 $res = $this->mConn->query( $sql );
257 if ( $res === false ) {
258 return false;
259 } else {
260 $r = $res instanceof ResultWrapper ? $res->result : $res;
261 $this->mAffectedRows = $r->rowCount();
262 $res = new ResultWrapper( $this, $r->fetchAll() );
263 }
264
265 return $res;
266 }
267
268 /**
269 * @param ResultWrapper|mixed $res
270 */
271 function freeResult( $res ) {
272 if ( $res instanceof ResultWrapper ) {
273 $res->result = null;
274 } else {
275 $res = null;
276 }
277 }
278
279 /**
280 * @param ResultWrapper|array $res
281 * @return stdClass|bool
282 */
283 function fetchObject( $res ) {
284 if ( $res instanceof ResultWrapper ) {
285 $r =& $res->result;
286 } else {
287 $r =& $res;
288 }
289
290 $cur = current( $r );
291 if ( is_array( $cur ) ) {
292 next( $r );
293 $obj = new stdClass;
294 foreach ( $cur as $k => $v ) {
295 if ( !is_numeric( $k ) ) {
296 $obj->$k = $v;
297 }
298 }
299
300 return $obj;
301 }
302
303 return false;
304 }
305
306 /**
307 * @param ResultWrapper|mixed $res
308 * @return array|bool
309 */
310 function fetchRow( $res ) {
311 if ( $res instanceof ResultWrapper ) {
312 $r =& $res->result;
313 } else {
314 $r =& $res;
315 }
316 $cur = current( $r );
317 if ( is_array( $cur ) ) {
318 next( $r );
319
320 return $cur;
321 }
322
323 return false;
324 }
325
326 /**
327 * The PDO::Statement class implements the array interface so count() will work
328 *
329 * @param ResultWrapper|array $res
330 * @return int
331 */
332 function numRows( $res ) {
333 $r = $res instanceof ResultWrapper ? $res->result : $res;
334
335 return count( $r );
336 }
337
338 /**
339 * @param ResultWrapper $res
340 * @return int
341 */
342 function numFields( $res ) {
343 $r = $res instanceof ResultWrapper ? $res->result : $res;
344
345 return is_array( $r ) ? count( $r[0] ) : 0;
346 }
347
348 /**
349 * @param ResultWrapper $res
350 * @param $n
351 * @return bool
352 */
353 function fieldName( $res, $n ) {
354 $r = $res instanceof ResultWrapper ? $res->result : $res;
355 if ( is_array( $r ) ) {
356 $keys = array_keys( $r[0] );
357
358 return $keys[$n];
359 }
360
361 return false;
362 }
363
364 /**
365 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
366 *
367 * @param string $name
368 * @param string $format
369 * @return string
370 */
371 function tableName( $name, $format = 'quoted' ) {
372 // table names starting with sqlite_ are reserved
373 if ( strpos( $name, 'sqlite_' ) === 0 ) {
374 return $name;
375 }
376
377 return str_replace( '"', '', parent::tableName( $name, $format ) );
378 }
379
380 /**
381 * Index names have DB scope
382 *
383 * @param string $index
384 * @return string
385 */
386 function indexName( $index ) {
387 return $index;
388 }
389
390 /**
391 * This must be called after nextSequenceVal
392 *
393 * @return int
394 */
395 function insertId() {
396 // PDO::lastInsertId yields a string :(
397 return intval( $this->mConn->lastInsertId() );
398 }
399
400 /**
401 * @param ResultWrapper|array $res
402 * @param int $row
403 */
404 function dataSeek( $res, $row ) {
405 if ( $res instanceof ResultWrapper ) {
406 $r =& $res->result;
407 } else {
408 $r =& $res;
409 }
410 reset( $r );
411 if ( $row > 0 ) {
412 for ( $i = 0; $i < $row; $i++ ) {
413 next( $r );
414 }
415 }
416 }
417
418 /**
419 * @return string
420 */
421 function lastError() {
422 if ( !is_object( $this->mConn ) ) {
423 return "Cannot return last error, no db connection";
424 }
425 $e = $this->mConn->errorInfo();
426
427 return isset( $e[2] ) ? $e[2] : '';
428 }
429
430 /**
431 * @return string
432 */
433 function lastErrno() {
434 if ( !is_object( $this->mConn ) ) {
435 return "Cannot return last error, no db connection";
436 } else {
437 $info = $this->mConn->errorInfo();
438
439 return $info[1];
440 }
441 }
442
443 /**
444 * @return int
445 */
446 function affectedRows() {
447 return $this->mAffectedRows;
448 }
449
450 /**
451 * Returns information about an index
452 * Returns false if the index does not exist
453 * - if errors are explicitly ignored, returns NULL on failure
454 *
455 * @param string $table
456 * @param string $index
457 * @param string $fname
458 * @return array
459 */
460 function indexInfo( $table, $index, $fname = __METHOD__ ) {
461 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
462 $res = $this->query( $sql, $fname );
463 if ( !$res ) {
464 return null;
465 }
466 if ( $res->numRows() == 0 ) {
467 return false;
468 }
469 $info = array();
470 foreach ( $res as $row ) {
471 $info[] = $row->name;
472 }
473
474 return $info;
475 }
476
477 /**
478 * @param string $table
479 * @param string $index
480 * @param string $fname
481 * @return bool|null
482 */
483 function indexUnique( $table, $index, $fname = __METHOD__ ) {
484 $row = $this->selectRow( 'sqlite_master', '*',
485 array(
486 'type' => 'index',
487 'name' => $this->indexName( $index ),
488 ), $fname );
489 if ( !$row || !isset( $row->sql ) ) {
490 return null;
491 }
492
493 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
494 $indexPos = strpos( $row->sql, 'INDEX' );
495 if ( $indexPos === false ) {
496 return null;
497 }
498 $firstPart = substr( $row->sql, 0, $indexPos );
499 $options = explode( ' ', $firstPart );
500
501 return in_array( 'UNIQUE', $options );
502 }
503
504 /**
505 * Filter the options used in SELECT statements
506 *
507 * @param array $options
508 * @return array
509 */
510 function makeSelectOptions( $options ) {
511 foreach ( $options as $k => $v ) {
512 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' || $v == 'LOCK IN SHARE MODE' ) ) {
513 $options[$k] = '';
514 }
515 }
516
517 return parent::makeSelectOptions( $options );
518 }
519
520 /**
521 * @param array $options
522 * @return string
523 */
524 protected function makeUpdateOptions( $options ) {
525 $options = self::fixIgnore( $options );
526
527 return parent::makeUpdateOptions( $options );
528 }
529
530 /**
531 * @param array $options
532 * @return array
533 */
534 static function fixIgnore( $options ) {
535 # SQLite uses OR IGNORE not just IGNORE
536 foreach ( $options as $k => $v ) {
537 if ( $v == 'IGNORE' ) {
538 $options[$k] = 'OR IGNORE';
539 }
540 }
541
542 return $options;
543 }
544
545 /**
546 * @param array $options
547 * @return string
548 */
549 function makeInsertOptions( $options ) {
550 $options = self::fixIgnore( $options );
551
552 return parent::makeInsertOptions( $options );
553 }
554
555 /**
556 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
557 * @param string $table
558 * @param array $a
559 * @param string $fname
560 * @param array $options
561 * @return bool
562 */
563 function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
564 if ( !count( $a ) ) {
565 return true;
566 }
567
568 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
569 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
570 $ret = true;
571 foreach ( $a as $v ) {
572 if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) ) {
573 $ret = false;
574 }
575 }
576 } else {
577 $ret = parent::insert( $table, $a, "$fname/single-row", $options );
578 }
579
580 return $ret;
581 }
582
583 /**
584 * @param string $table
585 * @param array $uniqueIndexes Unused
586 * @param string|array $rows
587 * @param string $fname
588 * @return bool|ResultWrapper
589 */
590 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
591 if ( !count( $rows ) ) {
592 return true;
593 }
594
595 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
596 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
597 $ret = true;
598 foreach ( $rows as $v ) {
599 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
600 $ret = false;
601 }
602 }
603 } else {
604 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
605 }
606
607 return $ret;
608 }
609
610 /**
611 * Returns the size of a text field, or -1 for "unlimited"
612 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
613 *
614 * @param string $table
615 * @param string $field
616 * @return int
617 */
618 function textFieldSize( $table, $field ) {
619 return -1;
620 }
621
622 /**
623 * @return bool
624 */
625 function unionSupportsOrderAndLimit() {
626 return false;
627 }
628
629 /**
630 * @param string $sqls
631 * @param bool $all Whether to "UNION ALL" or not
632 * @return string
633 */
634 function unionQueries( $sqls, $all ) {
635 $glue = $all ? ' UNION ALL ' : ' UNION ';
636
637 return implode( $glue, $sqls );
638 }
639
640 /**
641 * @return bool
642 */
643 function wasDeadlock() {
644 return $this->lastErrno() == 5; // SQLITE_BUSY
645 }
646
647 /**
648 * @return bool
649 */
650 function wasErrorReissuable() {
651 return $this->lastErrno() == 17; // SQLITE_SCHEMA;
652 }
653
654 /**
655 * @return bool
656 */
657 function wasReadOnlyError() {
658 return $this->lastErrno() == 8; // SQLITE_READONLY;
659 }
660
661 /**
662 * @return string wikitext of a link to the server software's web site
663 */
664 public function getSoftwareLink() {
665 return "[{{int:version-db-sqlite-url}} SQLite]";
666 }
667
668 /**
669 * @return string Version information from the database
670 */
671 function getServerVersion() {
672 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
673
674 return $ver;
675 }
676
677 /**
678 * @return string User-friendly database information
679 */
680 public function getServerInfo() {
681 return wfMessage( self::getFulltextSearchModule()
682 ? 'sqlite-has-fts'
683 : 'sqlite-no-fts', $this->getServerVersion() )->text();
684 }
685
686 /**
687 * Get information about a given field
688 * Returns false if the field does not exist.
689 *
690 * @param string $table
691 * @param string $field
692 * @return SQLiteField|bool False on failure
693 */
694 function fieldInfo( $table, $field ) {
695 $tableName = $this->tableName( $table );
696 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
697 $res = $this->query( $sql, __METHOD__ );
698 foreach ( $res as $row ) {
699 if ( $row->name == $field ) {
700 return new SQLiteField( $row, $tableName );
701 }
702 }
703
704 return false;
705 }
706
707 protected function doBegin( $fname = '' ) {
708 if ( $this->mTrxLevel == 1 ) {
709 $this->commit( __METHOD__ );
710 }
711 try {
712 $this->mConn->beginTransaction();
713 } catch ( PDOException $e ) {
714 throw new DBUnexpectedError( $this, 'Error in BEGIN query: ' . $e->getMessage() );
715 }
716 $this->mTrxLevel = 1;
717 }
718
719 protected function doCommit( $fname = '' ) {
720 if ( $this->mTrxLevel == 0 ) {
721 return;
722 }
723 try {
724 $this->mConn->commit();
725 } catch ( PDOException $e ) {
726 throw new DBUnexpectedError( $this, 'Error in COMMIT query: ' . $e->getMessage() );
727 }
728 $this->mTrxLevel = 0;
729 }
730
731 protected function doRollback( $fname = '' ) {
732 if ( $this->mTrxLevel == 0 ) {
733 return;
734 }
735 $this->mConn->rollBack();
736 $this->mTrxLevel = 0;
737 }
738
739 /**
740 * @param string $s
741 * @return string
742 */
743 function strencode( $s ) {
744 return substr( $this->addQuotes( $s ), 1, -1 );
745 }
746
747 /**
748 * @param $b
749 * @return Blob
750 */
751 function encodeBlob( $b ) {
752 return new Blob( $b );
753 }
754
755 /**
756 * @param $b Blob|string
757 * @return string
758 */
759 function decodeBlob( $b ) {
760 if ( $b instanceof Blob ) {
761 $b = $b->fetch();
762 }
763
764 return $b;
765 }
766
767 /**
768 * @param Blob|string $s
769 * @return string
770 */
771 function addQuotes( $s ) {
772 if ( $s instanceof Blob ) {
773 return "x'" . bin2hex( $s->fetch() ) . "'";
774 } elseif ( is_bool( $s ) ) {
775 return (int)$s;
776 } elseif ( strpos( $s, "\0" ) !== false ) {
777 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
778 // This is a known limitation of SQLite's mprintf function which PDO should work around,
779 // but doesn't. I have reported this to php.net as bug #63419:
780 // https://bugs.php.net/bug.php?id=63419
781 // There was already a similar report for SQLite3::escapeString, bug #62361:
782 // https://bugs.php.net/bug.php?id=62361
783 return "x'" . bin2hex( $s ) . "'";
784 } else {
785 return $this->mConn->quote( $s );
786 }
787 }
788
789 /**
790 * @return string
791 */
792 function buildLike() {
793 $params = func_get_args();
794 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
795 $params = $params[0];
796 }
797
798 return parent::buildLike( $params ) . "ESCAPE '\' ";
799 }
800
801 /**
802 * @return string
803 */
804 public function getSearchEngine() {
805 return "SearchSqlite";
806 }
807
808 /**
809 * No-op version of deadlockLoop
810 *
811 * @return mixed
812 */
813 public function deadlockLoop( /*...*/ ) {
814 $args = func_get_args();
815 $function = array_shift( $args );
816
817 return call_user_func_array( $function, $args );
818 }
819
820 /**
821 * @param string $s
822 * @return string
823 */
824 protected function replaceVars( $s ) {
825 $s = parent::replaceVars( $s );
826 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
827 // CREATE TABLE hacks to allow schema file sharing with MySQL
828
829 // binary/varbinary column type -> blob
830 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
831 // no such thing as unsigned
832 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
833 // INT -> INTEGER
834 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
835 // floating point types -> REAL
836 $s = preg_replace(
837 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
838 'REAL',
839 $s
840 );
841 // varchar -> TEXT
842 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
843 // TEXT normalization
844 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
845 // BLOB normalization
846 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
847 // BOOL -> INTEGER
848 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
849 // DATETIME -> TEXT
850 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
851 // No ENUM type
852 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
853 // binary collation type -> nothing
854 $s = preg_replace( '/\bbinary\b/i', '', $s );
855 // auto_increment -> autoincrement
856 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
857 // No explicit options
858 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
859 // AUTOINCREMENT should immedidately follow PRIMARY KEY
860 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
861 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
862 // No truncated indexes
863 $s = preg_replace( '/\(\d+\)/', '', $s );
864 // No FULLTEXT
865 $s = preg_replace( '/\bfulltext\b/i', '', $s );
866 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
867 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
868 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
869 }
870
871 return $s;
872 }
873
874 public function lock( $lockName, $method, $timeout = 5 ) {
875 global $wgSQLiteDataDir;
876
877 if ( !is_dir( "$wgSQLiteDataDir/locks" ) ) { // create dir as needed
878 if ( !is_writable( $wgSQLiteDataDir ) || !mkdir( "$wgSQLiteDataDir/locks" ) ) {
879 throw new DBError( "Cannot create directory \"$wgSQLiteDataDir/locks\"." );
880 }
881 }
882
883 return $this->lockMgr->lock( array( $lockName ), LockManager::LOCK_EX, $timeout )->isOK();
884 }
885
886 public function unlock( $lockName, $method ) {
887 return $this->lockMgr->unlock( array( $lockName ), LockManager::LOCK_EX )->isOK();
888 }
889
890 /**
891 * Build a concatenation list to feed into a SQL query
892 *
893 * @param string[] $stringList
894 * @return string
895 */
896 function buildConcat( $stringList ) {
897 return '(' . implode( ') || (', $stringList ) . ')';
898 }
899
900 public function buildGroupConcatField(
901 $delim, $table, $field, $conds = '', $join_conds = array()
902 ) {
903 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
904
905 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
906 }
907
908 /**
909 * @throws MWException
910 * @param string $oldName
911 * @param string $newName
912 * @param bool $temporary
913 * @param string $fname
914 * @return bool|ResultWrapper
915 */
916 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
917 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
918 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
919 $obj = $this->fetchObject( $res );
920 if ( !$obj ) {
921 throw new MWException( "Couldn't retrieve structure for table $oldName" );
922 }
923 $sql = $obj->sql;
924 $sql = preg_replace(
925 '/(?<=\W)"?' . preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ) ) . '"?(?=\W)/',
926 $this->addIdentifierQuotes( $newName ),
927 $sql,
928 1
929 );
930 if ( $temporary ) {
931 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
932 wfDebug( "Table $oldName is virtual, can't create a temporary duplicate.\n" );
933 } else {
934 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
935 }
936 }
937
938 return $this->query( $sql, $fname );
939 }
940
941 /**
942 * List all tables on the database
943 *
944 * @param string $prefix Only show tables with this prefix, e.g. mw_
945 * @param string $fname Calling function name
946 *
947 * @return array
948 */
949 function listTables( $prefix = null, $fname = __METHOD__ ) {
950 $result = $this->select(
951 'sqlite_master',
952 'name',
953 "type='table'"
954 );
955
956 $endArray = array();
957
958 foreach ( $result as $table ) {
959 $vars = get_object_vars( $table );
960 $table = array_pop( $vars );
961
962 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
963 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
964 $endArray[] = $table;
965 }
966 }
967 }
968
969 return $endArray;
970 }
971 } // end DatabaseSqlite class
972
973 /**
974 * This class allows simple acccess to a SQLite database independently from main database settings
975 * @ingroup Database
976 */
977 class DatabaseSqliteStandalone extends DatabaseSqlite {
978 public function __construct( $fileName, $flags = 0 ) {
979 $this->mFlags = $flags;
980 $this->tablePrefix( null );
981 $this->openFile( $fileName );
982 }
983 }
984
985 /**
986 * @ingroup Database
987 */
988 class SQLiteField implements Field {
989 private $info, $tableName;
990
991 function __construct( $info, $tableName ) {
992 $this->info = $info;
993 $this->tableName = $tableName;
994 }
995
996 function name() {
997 return $this->info->name;
998 }
999
1000 function tableName() {
1001 return $this->tableName;
1002 }
1003
1004 function defaultValue() {
1005 if ( is_string( $this->info->dflt_value ) ) {
1006 // Typically quoted
1007 if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
1008 return str_replace( "''", "'", $this->info->dflt_value );
1009 }
1010 }
1011
1012 return $this->info->dflt_value;
1013 }
1014
1015 /**
1016 * @return bool
1017 */
1018 function isNullable() {
1019 return !$this->info->notnull;
1020 }
1021
1022 function type() {
1023 return $this->info->type;
1024 }
1025 } // end SQLiteField