]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/db/DatabaseSqlite.php
MediaWiki 1.17.0
[autoinstalls/mediawiki.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         static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
48                 return new DatabaseSqlite( $server, $user, $password, $dbName, $flags );
49         }
50
51         /** Open an SQLite database and return a resource handle to it
52          *  NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
53          */
54         function open( $server, $user, $pass, $dbName ) {
55                 global $wgSQLiteDataDir;
56
57                 $fileName = self::generateFileName( $wgSQLiteDataDir, $dbName );
58                 if ( !is_readable( $fileName ) ) {
59                         $this->mConn = false;
60                         throw new DBConnectionError( $this, "SQLite database not accessible" );
61                 }
62                 $this->openFile( $fileName );
63                 return $this->mConn;
64         }
65
66         /**
67          * Opens a database file
68          * @return SQL connection or false if failed
69          */
70         function openFile( $fileName ) {
71                 $this->mDatabaseFile = $fileName;
72                 try {
73                         if ( $this->mFlags & DBO_PERSISTENT ) {
74                                 $this->mConn = new PDO( "sqlite:$fileName", '', '',
75                                         array( PDO::ATTR_PERSISTENT => true ) );
76                         } else {
77                                 $this->mConn = new PDO( "sqlite:$fileName", '', '' );
78                         }
79                 } catch ( PDOException $e ) {
80                         $err = $e->getMessage();
81                 }
82                 if ( !$this->mConn ) {
83                         wfDebug( "DB connection error: $err\n" );
84                         throw new DBConnectionError( $this, $err );
85                 }
86                 $this->mOpened = !!$this->mConn;
87                 # set error codes only, don't raise exceptions
88                 if ( $this->mOpened ) {
89                         $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
90                         return true;
91                 }
92         }
93
94         /**
95          * Close an SQLite database
96          */
97         function close() {
98                 $this->mOpened = false;
99                 if ( is_object( $this->mConn ) ) {
100                         if ( $this->trxLevel() ) $this->commit();
101                         $this->mConn = null;
102                 }
103                 return true;
104         }
105
106         /**
107          * Generates a database file name. Explicitly public for installer.
108          * @param $dir String: Directory where database resides
109          * @param $dbName String: Database name
110          * @return String
111          */
112         public static function generateFileName( $dir, $dbName ) {
113                 return "$dir/$dbName.sqlite";
114         }
115
116         /**
117          * Check if the searchindext table is FTS enabled.
118          * @returns false if not enabled.
119          */
120         function checkForEnabledSearch() {
121                 if ( self::$fulltextEnabled === null ) {
122                         self::$fulltextEnabled = false;
123                         $table = $this->tableName( 'searchindex' );
124                         $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__ );
125                         if ( $res ) {
126                                 $row = $res->fetchRow();
127                                 self::$fulltextEnabled = stristr($row['sql'], 'fts' ) !== false;
128                         }
129                 }
130                 return self::$fulltextEnabled;
131         }
132
133         /**
134          * Returns version of currently supported SQLite fulltext search module or false if none present.
135          * @return String
136          */
137         static function getFulltextSearchModule() {
138                 static $cachedResult = null;
139                 if ( $cachedResult !== null ) {
140                         return $cachedResult;
141                 }
142                 $cachedResult = false;
143                 $table = 'dummy_search_test';
144                 
145                 $db = new DatabaseSqliteStandalone( ':memory:' );
146
147                 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__, true ) ) {
148                         $cachedResult = 'FTS3';
149                 }
150                 $db->close();
151                 return $cachedResult;
152         }
153
154         /**
155          * Attaches external database to our connection, see http://sqlite.org/lang_attach.html
156          * for details.
157          * @param $name String: database name to be used in queries like SELECT foo FROM dbname.table
158          * @param $file String: database file name. If omitted, will be generated using $name and $wgSQLiteDataDir
159          * @param $fname String: calling function name
160          */
161         function attachDatabase( $name, $file = false, $fname = 'DatabaseSqlite::attachDatabase' ) {
162                 global $wgSQLiteDataDir;
163                 if ( !$file ) {
164                         $file = self::generateFileName( $wgSQLiteDataDir, $name );
165                 }
166                 $file = $this->addQuotes( $file );
167                 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
168         }
169
170         /**
171          * @see DatabaseBase::isWriteQuery()
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 ) {
262                 // table names starting with sqlite_ are reserved
263                 if ( strpos( $name, 'sqlite_' ) === 0 ) return $name;
264                 return str_replace( '`', '', parent::tableName( $name ) );
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          * Based on generic method (parent) with some prior SQLite-sepcific adjustments
371          */
372         function insert( $table, $a, $fname = 'DatabaseSqlite::insert', $options = array() ) {
373                 if ( !count( $a ) ) {
374                         return true;
375                 }
376                 if ( !is_array( $options ) ) {
377                         $options = array( $options );
378                 }
379
380                 # SQLite uses OR IGNORE not just IGNORE
381                 foreach ( $options as $k => $v ) {
382                         if ( $v == 'IGNORE' ) {
383                                 $options[$k] = 'OR IGNORE';
384                         }
385                 }
386
387                 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
388                 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
389                         $ret = true;
390                         foreach ( $a as $v ) {
391                                 if ( !parent::insert( $table, $v, "$fname/multi-row", $options ) ) {
392                                         $ret = false;
393                                 }
394                         }
395                 } else {
396                         $ret = parent::insert( $table, $a, "$fname/single-row", $options );
397                 }
398
399                 return $ret;
400         }
401
402         function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseSqlite::replace' ) {
403                 if ( !count( $rows ) ) return true;
404
405                 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
406                 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
407                         $ret = true;
408                         foreach ( $rows as $v ) {
409                                 if ( !parent::replace( $table, $uniqueIndexes, $v, "$fname/multi-row" ) ) {
410                                         $ret = false;
411                                 }
412                         }
413                 } else {
414                         $ret = parent::replace( $table, $uniqueIndexes, $rows, "$fname/single-row" );
415                 }
416
417                 return $ret;
418         }
419
420         /**
421          * Returns the size of a text field, or -1 for "unlimited"
422          * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
423          */
424         function textFieldSize( $table, $field ) {
425                 return - 1;
426         }
427
428         function unionSupportsOrderAndLimit() {
429                 return false;
430         }
431
432         function unionQueries( $sqls, $all ) {
433                 $glue = $all ? ' UNION ALL ' : ' UNION ';
434                 return implode( $glue, $sqls );
435         }
436
437         public function unixTimestamp( $field ) {
438                 return $field;
439         }
440
441         function wasDeadlock() {
442                 return $this->lastErrno() == 5; // SQLITE_BUSY
443         }
444
445         function wasErrorReissuable() {
446                 return $this->lastErrno() ==  17; // SQLITE_SCHEMA;
447         }
448
449         function wasReadOnlyError() {
450                 return $this->lastErrno() == 8; // SQLITE_READONLY;
451         }
452
453         /**
454          * @return string wikitext of a link to the server software's web site
455          */
456         public static function getSoftwareLink() {
457                 return "[http://sqlite.org/ SQLite]";
458         }
459
460         /**
461          * @return string Version information from the database
462          */
463         function getServerVersion() {
464                 $ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
465                 return $ver;
466         }
467
468         /**
469          * @return string User-friendly database information
470          */
471         public function getServerInfo() {
472                 return wfMsg( self::getFulltextSearchModule() ? 'sqlite-has-fts' : 'sqlite-no-fts', $this->getServerVersion() );
473         }
474
475         /**
476          * Get information about a given field
477          * Returns false if the field does not exist.
478          */
479         function fieldInfo( $table, $field ) {
480                 $tableName = $this->tableName( $table );
481                 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
482                 $res = $this->query( $sql, __METHOD__ );
483                 foreach ( $res as $row ) {
484                         if ( $row->name == $field ) {
485                                 return new SQLiteField( $row, $tableName );
486                         }
487                 }
488                 return false;
489         }
490
491         function begin( $fname = '' ) {
492                 if ( $this->mTrxLevel == 1 ) $this->commit();
493                 $this->mConn->beginTransaction();
494                 $this->mTrxLevel = 1;
495         }
496
497         function commit( $fname = '' ) {
498                 if ( $this->mTrxLevel == 0 ) return;
499                 $this->mConn->commit();
500                 $this->mTrxLevel = 0;
501         }
502
503         function rollback( $fname = '' ) {
504                 if ( $this->mTrxLevel == 0 ) return;
505                 $this->mConn->rollBack();
506                 $this->mTrxLevel = 0;
507         }
508
509         function limitResultForUpdate( $sql, $num ) {
510                 return $this->limitResult( $sql, $num );
511         }
512
513         function strencode( $s ) {
514                 return substr( $this->addQuotes( $s ), 1, - 1 );
515         }
516
517         function encodeBlob( $b ) {
518                 return new Blob( $b );
519         }
520
521         function decodeBlob( $b ) {
522                 if ( $b instanceof Blob ) {
523                         $b = $b->fetch();
524                 }
525                 return $b;
526         }
527
528         function addQuotes( $s ) {
529                 if ( $s instanceof Blob ) {
530                         return "x'" . bin2hex( $s->fetch() ) . "'";
531                 } else {
532                         return $this->mConn->quote( $s );
533                 }
534         }
535
536         function buildLike() {
537                 $params = func_get_args();
538                 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
539                         $params = $params[0];
540                 }
541                 return parent::buildLike( $params ) . "ESCAPE '\' ";
542         }
543
544         public function getSearchEngine() {
545                 return "SearchSqlite";
546         }
547
548         /**
549          * No-op version of deadlockLoop
550          */
551         public function deadlockLoop( /*...*/ ) {
552                 $args = func_get_args();
553                 $function = array_shift( $args );
554                 return call_user_func_array( $function, $args );
555         }
556
557         protected function replaceVars( $s ) {
558                 $s = parent::replaceVars( $s );
559                 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
560                         // CREATE TABLE hacks to allow schema file sharing with MySQL
561
562                         // binary/varbinary column type -> blob
563                         $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
564                         // no such thing as unsigned
565                         $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
566                         // INT -> INTEGER
567                         $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
568                         // floating point types -> REAL
569                         $s = preg_replace( '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i', 'REAL', $s );
570                         // varchar -> TEXT
571                         $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
572                         // TEXT normalization
573                         $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
574                         // BLOB normalization
575                         $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
576                         // BOOL -> INTEGER
577                         $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
578                         // DATETIME -> TEXT
579                         $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
580                         // No ENUM type
581                         $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
582                         // binary collation type -> nothing
583                         $s = preg_replace( '/\bbinary\b/i', '', $s );
584                         // auto_increment -> autoincrement
585                         $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
586                         // No explicit options
587                         $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
588                         // AUTOINCREMENT should immedidately follow PRIMARY KEY
589                         $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
590                 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
591                         // No truncated indexes
592                         $s = preg_replace( '/\(\d+\)/', '', $s );
593                         // No FULLTEXT
594                         $s = preg_replace( '/\bfulltext\b/i', '', $s );
595                 }
596                 return $s;
597         }
598
599         /*
600          * Build a concatenation list to feed into a SQL query
601          */
602         function buildConcat( $stringList ) {
603                 return '(' . implode( ') || (', $stringList ) . ')';
604         }
605
606         function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseSqlite::duplicateTableStructure' ) {
607                 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name='$oldName' AND type='table'", $fname );
608                 $obj = $this->fetchObject( $res );
609                 if ( !$obj ) {
610                         throw new MWException( "Couldn't retrieve structure for table $oldName" );
611                 }
612                 $sql = $obj->sql;
613                 $sql = preg_replace( '/\b' . preg_quote( $oldName ) . '\b/', $newName, $sql, 1 );
614                 return $this->query( $sql, $fname );
615         }
616
617 } // end DatabaseSqlite class
618
619 /**
620  * This class allows simple acccess to a SQLite database independently from main database settings
621  * @ingroup Database
622  */
623 class DatabaseSqliteStandalone extends DatabaseSqlite {
624         public function __construct( $fileName, $flags = 0 ) {
625                 $this->mFlags = $flags;
626                 $this->tablePrefix( null );
627                 $this->openFile( $fileName );
628         }
629 }
630
631 /**
632  * @ingroup Database
633  */
634 class SQLiteField implements Field {
635         private $info, $tableName;
636         function __construct( $info, $tableName ) {
637                 $this->info = $info;
638                 $this->tableName = $tableName;
639         }
640
641         function name() {
642                 return $this->info->name;
643         }
644
645         function tableName() {
646                 return $this->tableName;
647         }
648
649         function defaultValue() {
650                 if ( is_string( $this->info->dflt_value ) ) {
651                         // Typically quoted
652                         if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
653                                 return str_replace( "''", "'", $this->info->dflt_value );
654                         }
655                 }
656                 return $this->info->dflt_value;
657         }
658
659         function isNullable() {
660                 return !$this->info->notnull;
661         }
662
663         function type() {
664                 return $this->info->type;
665         }
666
667 } // end SQLiteField