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