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