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