]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/db/DatabaseSqlite.php
MediaWiki 1.15.5
[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 Database {
14
15         var $mAffectedRows;
16         var $mLastResult;
17         var $mDatabaseFile;
18         var $mName;
19
20         /**
21          * Constructor
22          */
23         function __construct($server = false, $user = false, $password = false, $dbName = false, $failFunction = false, $flags = 0) {
24                 global $wgOut,$wgSQLiteDataDir, $wgSQLiteDataDirMode;
25                 if ("$wgSQLiteDataDir" == '') $wgSQLiteDataDir = dirname($_SERVER['DOCUMENT_ROOT']).'/data';
26                 if (!is_dir($wgSQLiteDataDir)) wfMkdirParents( $wgSQLiteDataDir, $wgSQLiteDataDirMode );
27                 $this->mFailFunction = $failFunction;
28                 $this->mFlags = $flags;
29                 $this->mDatabaseFile = "$wgSQLiteDataDir/$dbName.sqlite";
30                 $this->mName = $dbName;
31                 $this->open($server, $user, $password, $dbName);
32         }
33
34         /**
35          * todo: check if these should be true like parent class
36          */
37         function implicitGroupby()   { return false; }
38         function implicitOrderby()   { 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                 $this->mConn = false;
49                 if ($dbName) {
50                         $file = $this->mDatabaseFile;
51                         try {
52                                 if ( $this->mFlags & DBO_PERSISTENT ) {
53                                         $this->mConn = new PDO( "sqlite:$file", $user, $pass, 
54                                                 array( PDO::ATTR_PERSISTENT => true ) );
55                                 } else {
56                                         $this->mConn = new PDO( "sqlite:$file", $user, $pass );
57                                 }
58                         } catch ( PDOException $e ) {
59                                 $err = $e->getMessage();
60                         }
61                         if ( $this->mConn === false ) {
62                                 wfDebug( "DB connection error: $err\n" );
63                                 if ( !$this->mFailFunction ) {
64                                         throw new DBConnectionError( $this, $err );
65                                 } else {
66                                         return false;
67                                 }
68
69                         }
70                         $this->mOpened = $this->mConn;
71                         # set error codes only, don't raise exceptions
72                         $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT ); 
73                 }
74                 return $this->mConn;
75         }
76
77         /**
78          * Close an SQLite database
79          */
80         function close() {
81                 $this->mOpened = false;
82                 if (is_object($this->mConn)) {
83                         if ($this->trxLevel()) $this->immediateCommit();
84                         $this->mConn = null;
85                 }
86                 return true;
87         }
88
89         /**
90          * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
91          */
92         function doQuery($sql) {
93                 $res = $this->mConn->query($sql);
94                 if ($res === false) {
95                         return false;
96                 } else {
97                         $r = $res instanceof ResultWrapper ? $res->result : $res;
98                         $this->mAffectedRows = $r->rowCount();
99                         $res = new ResultWrapper($this,$r->fetchAll());
100                 }
101                 return $res;
102         }
103
104         function freeResult($res) {
105                 if ($res instanceof ResultWrapper) $res->result = NULL; else $res = NULL;
106         }
107
108         function fetchObject($res) {
109                 if ($res instanceof ResultWrapper) $r =& $res->result; else $r =& $res;
110                 $cur = current($r);
111                 if (is_array($cur)) {
112                         next($r);
113                         $obj = new stdClass;
114                         foreach ($cur as $k => $v) if (!is_numeric($k)) $obj->$k = $v;
115                         return $obj;
116                 }
117                 return false;
118         }
119
120         function fetchRow($res) {
121                 if ($res instanceof ResultWrapper) $r =& $res->result; else $r =& $res;
122                 $cur = current($r);
123                 if (is_array($cur)) {
124                         next($r);
125                         return $cur;
126                 }
127                 return false;
128         }
129
130         /**
131          * The PDO::Statement class implements the array interface so count() will work
132          */
133         function numRows($res) {
134                 $r = $res instanceof ResultWrapper ? $res->result : $res;
135                 return count($r);
136         }
137
138         function numFields($res) {
139                 $r = $res instanceof ResultWrapper ? $res->result : $res;
140                 return is_array($r) ? count($r[0]) : 0;
141         }
142
143         function fieldName($res,$n) {
144                 $r = $res instanceof ResultWrapper ? $res->result : $res;
145                 if (is_array($r)) {
146                         $keys = array_keys($r[0]);
147                         return $keys[$n];
148                 }
149                 return  false;
150         }
151
152         /**
153          * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
154          */
155         function tableName($name) {
156                 return str_replace('`','',parent::tableName($name));
157         }
158
159         /**
160          * Index names have DB scope
161          */
162         function indexName( $index ) {
163                 return $index;
164         }
165
166         /**
167          * This must be called after nextSequenceVal
168          */
169         function insertId() {
170                 return $this->mConn->lastInsertId();
171         }
172
173         function dataSeek($res,$row) {
174                 if ($res instanceof ResultWrapper) $r =& $res->result; else $r =& $res;
175                 reset($r);
176                 if ($row > 0) for ($i = 0; $i < $row; $i++) next($r);
177         }
178
179         function lastError() {
180                 if (!is_object($this->mConn)) return "Cannot return last error, no db connection";
181                 $e = $this->mConn->errorInfo();
182                 return isset($e[2]) ? $e[2] : '';
183         }
184
185         function lastErrno() {
186                 if (!is_object($this->mConn)) {
187                         return "Cannot return last error, no db connection";
188                 } else {
189                         $info = $this->mConn->errorInfo();
190                         return $info[1];
191                 }
192         }
193
194         function affectedRows() {
195                 return $this->mAffectedRows;
196         }
197
198         /**
199          * Returns information about an index
200          * Returns false if the index does not exist
201          * - if errors are explicitly ignored, returns NULL on failure
202          */
203         function indexInfo($table, $index, $fname = 'Database::indexExists') {
204                 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
205                 $res = $this->query( $sql, $fname );
206                 if ( !$res ) {
207                         return null;
208                 }
209                 if ( $res->numRows() == 0 ) {
210                         return false;
211                 }
212                 $info = array();
213                 foreach ( $res as $row ) {
214                         $info[] = $row->name;
215                 }
216                 return $info;
217         }
218
219         function indexUnique($table, $index, $fname = 'Database::indexUnique') {
220                 $row = $this->selectRow( 'sqlite_master', '*', 
221                         array(
222                                 'type' => 'index',
223                                 'name' => $this->indexName( $index ),
224                         ), $fname );
225                 if ( !$row || !isset( $row->sql ) ) {
226                         return null;
227                 }
228
229                 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
230                 $indexPos = strpos( $row->sql, 'INDEX' );
231                 if ( $indexPos === false ) {
232                         return null;
233                 }
234                 $firstPart = substr( $row->sql, 0, $indexPos );
235                 $options = explode( ' ', $firstPart );
236                 return in_array( 'UNIQUE', $options );
237         }
238
239         /**
240          * Filter the options used in SELECT statements
241          */
242         function makeSelectOptions($options) {
243                 foreach ($options as $k => $v) if (is_numeric($k) && $v == 'FOR UPDATE') $options[$k] = '';
244                 return parent::makeSelectOptions($options);
245         }
246
247         /**
248          * Based on MySQL method (parent) with some prior SQLite-sepcific adjustments
249          */
250         function insert($table, $a, $fname = 'DatabaseSqlite::insert', $options = array()) {
251                 if (!count($a)) return true;
252                 if (!is_array($options)) $options = array($options);
253
254                 # SQLite uses OR IGNORE not just IGNORE
255                 foreach ($options as $k => $v) if ($v == 'IGNORE') $options[$k] = 'OR IGNORE';
256
257                 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
258                 if (isset($a[0]) && is_array($a[0])) {
259                         $ret = true;
260                         foreach ($a as $k => $v) if (!parent::insert($table,$v,"$fname/multi-row",$options)) $ret = false;
261                 }
262                 else $ret = parent::insert($table,$a,"$fname/single-row",$options);
263
264                 return $ret;
265         }
266
267         /**
268          * SQLite does not have a "USE INDEX" clause, so return an empty string
269          */
270         function useIndexClause($index) {
271                 return '';
272         }
273
274         /**
275          * Returns the size of a text field, or -1 for "unlimited"
276          * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
277          */
278         function textFieldSize($table, $field) {
279                 return -1;
280         }
281
282         /**
283          * No low priority option in SQLite
284          */
285         function lowPriorityOption() {
286                 return '';
287         }
288
289         /**
290          * Returns an SQL expression for a simple conditional.
291          * - uses CASE on SQLite
292          */
293         function conditional($cond, $trueVal, $falseVal) {
294                 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
295         }
296
297         function wasDeadlock() {
298                 return $this->lastErrno() == SQLITE_BUSY;
299         }
300
301         function wasErrorReissuable() {
302                 return $this->lastErrno() ==  SQLITE_SCHEMA;
303         }
304
305         /**
306          * @return string wikitext of a link to the server software's web site
307          */
308         function getSoftwareLink() {
309                 return "[http://sqlite.org/ SQLite]";
310         }
311
312         /**
313          * @return string Version information from the database
314          */
315         function getServerVersion() {
316                 global $wgContLang;
317                 $ver = $this->mConn->getAttribute(PDO::ATTR_SERVER_VERSION);
318                 return $ver;
319         }
320
321         /**
322          * Query whether a given column exists in the mediawiki schema
323          */
324         function fieldExists($table, $field, $fname = '') {
325                 $info = $this->fieldInfo( $table, $field );
326                 return (bool)$info;
327         }
328
329         /**
330          * Get information about a given field
331          * Returns false if the field does not exist.
332          */
333         function fieldInfo($table, $field) {
334                 $tableName = $this->tableName( $table );
335                 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
336                 $res = $this->query( $sql, __METHOD__ );
337                 foreach ( $res as $row ) {
338                         if ( $row->name == $field ) {
339                                 return new SQLiteField( $row, $tableName );
340                         }
341                 }
342                 return false;
343         }
344
345         function begin( $fname = '' ) {
346                 if ($this->mTrxLevel == 1) $this->commit();
347                 $this->mConn->beginTransaction();
348                 $this->mTrxLevel = 1;
349         }
350
351         function commit( $fname = '' ) {
352                 if ($this->mTrxLevel == 0) return;
353                 $this->mConn->commit();
354                 $this->mTrxLevel = 0;
355         }
356
357         function rollback( $fname = '' ) {
358                 if ($this->mTrxLevel == 0) return;
359                 $this->mConn->rollBack();
360                 $this->mTrxLevel = 0;
361         }
362
363         function limitResultForUpdate($sql, $num) {
364                 return $this->limitResult( $sql, $num );
365         }
366
367         function strencode($s) {
368                 return substr($this->addQuotes($s),1,-1);
369         }
370
371         function encodeBlob($b) {
372                 return new Blob( $b );
373         }
374
375         function decodeBlob($b) {
376                 if ($b instanceof Blob) {
377                         $b = $b->fetch();
378                 }
379                 return $b;
380         }
381
382         function addQuotes($s) {
383                 if ( $s instanceof Blob ) {
384                         return "x'" . bin2hex( $s->fetch() ) . "'";
385                 } else {
386                         return $this->mConn->quote($s);
387                 }
388         }
389
390         function quote_ident($s) { return $s; }
391
392         /**
393          * Not possible in SQLite
394          * We have ATTACH_DATABASE but that requires database selectors before the 
395          * table names and in any case is really a different concept to MySQL's USE
396          */
397         function selectDB($db) {
398                 if ( $db != $this->mName ) {
399                         throw new MWException( 'selectDB is not implemented in SQLite' );
400                 }
401         }
402
403         /**
404          * not done
405          */
406         public function setTimeout($timeout) { return; }
407
408         /**
409          * No-op for a non-networked database
410          */
411         function ping() {
412                 return true;
413         }
414
415         /**
416          * How lagged is this slave?
417          */
418         public function getLag() {
419                 return 0;
420         }
421
422         /**
423          * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
424          * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
425          */
426         public function setup_database() {
427                 global $IP,$wgSQLiteDataDir,$wgDBTableOptions;
428                 $wgDBTableOptions = '';
429
430                 # Process common MySQL/SQLite table definitions
431                 $err = $this->sourceFile( "$IP/maintenance/tables.sql" );
432                 if ($err !== true) {
433                         $this->reportQueryError($err,0,$sql,__FUNCTION__);
434                         exit( 1 );
435                 }
436
437                 # Use DatabasePostgres's code to populate interwiki from MySQL template
438                 $f = fopen("$IP/maintenance/interwiki.sql",'r');
439                 if ($f == false) dieout("<li>Could not find the interwiki.sql file");
440                 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
441                 while (!feof($f)) {
442                         $line = fgets($f,1024);
443                         $matches = array();
444                         if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) continue;
445                         $this->query("$sql $matches[1],$matches[2])");
446                 }
447         }
448         
449         /** 
450          * No-op lock functions
451          */
452         public function lock( $lockName, $method ) {
453                 return true;
454         }
455         public function unlock( $lockName, $method ) {
456                 return true;
457         }
458         
459         public function getSearchEngine() {
460                 return "SearchEngineDummy";
461         }
462
463         /**
464          * No-op version of deadlockLoop
465          */
466         public function deadlockLoop( /*...*/ ) {
467                 $args = func_get_args();
468                 $function = array_shift( $args );
469                 return call_user_func_array( $function, $args );
470         }
471
472         protected function replaceVars( $s ) {
473                 $s = parent::replaceVars( $s );
474                 if ( preg_match( '/^\s*CREATE TABLE/i', $s ) ) {
475                         // CREATE TABLE hacks to allow schema file sharing with MySQL
476                         
477                         // binary/varbinary column type -> blob
478                         $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'blob\1', $s );
479                         // no such thing as unsigned
480                         $s = preg_replace( '/\bunsigned\b/i', '', $s );
481                         // INT -> INTEGER for primary keys
482                         $s = preg_replacE( '/\bint\b/i', 'integer', $s );
483                         // No ENUM type
484                         $s = preg_replace( '/enum\([^)]*\)/i', 'blob', $s );
485                         // binary collation type -> nothing
486                         $s = preg_replace( '/\bbinary\b/i', '', $s );
487                         // auto_increment -> autoincrement
488                         $s = preg_replace( '/\bauto_increment\b/i', 'autoincrement', $s );
489                         // No explicit options
490                         $s = preg_replace( '/\)[^)]*$/', ')', $s );
491                 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
492                         // No truncated indexes
493                         $s = preg_replace( '/\(\d+\)/', '', $s );
494                         // No FULLTEXT
495                         $s = preg_replace( '/\bfulltext\b/i', '', $s );
496                 }
497                 return $s;
498         }
499
500         /*
501          * Build a concatenation list to feed into a SQL query
502          */
503         function buildConcat( $stringList ) {
504                 return '(' . implode( ') || (', $stringList ) . ')';
505         }
506
507 } // end DatabaseSqlite class
508
509 /**
510  * @ingroup Database
511  */
512 class SQLiteField {
513         private $info, $tableName;
514         function __construct( $info, $tableName ) {
515                 $this->info = $info;
516                 $this->tableName = $tableName;
517         }
518
519         function name() {
520                 return $this->info->name;
521         }
522
523         function tableName() {
524                 return $this->tableName;
525         }
526
527         function defaultValue() {
528                 if ( is_string( $this->info->dflt_value ) ) {
529                         // Typically quoted
530                         if ( preg_match( '/^\'(.*)\'$', $this->info->dflt_value ) ) {
531                                 return str_replace( "''", "'", $this->info->dflt_value );
532                         }
533                 }
534                 return $this->info->dflt_value;
535         }
536
537         function maxLength() {
538                 return -1;
539         }
540
541         function nullable() {
542                 // SQLite dynamic types are always nullable
543                 return true;
544         }
545
546         # isKey(),  isMultipleKey() not implemented, MySQL-specific concept. 
547         # Suggest removal from base class [TS]
548         
549         function type() {
550                 return $this->info->type;
551         }
552
553 } // end SQLiteField
554