dfc506ccd178e928edceab4d32dd1b0e5534ec14
[lhc/web/wiklou.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
19 /**
20 * Constructor
21 */
22 function __construct($server = false, $user = false, $password = false, $dbName = false, $failFunction = false, $flags = 0) {
23 global $wgOut,$wgSQLiteDataDir, $wgSQLiteDataDirMode;
24 if ("$wgSQLiteDataDir" == '') $wgSQLiteDataDir = dirname($_SERVER['DOCUMENT_ROOT']).'/data';
25 if (!is_dir($wgSQLiteDataDir)) wfMkdirParents( $wgSQLiteDataDir, $wgSQLiteDataDirMode );
26 $this->mFailFunction = $failFunction;
27 $this->mFlags = $flags;
28 $this->mDatabaseFile = "$wgSQLiteDataDir/$dbName.sqlite";
29 $this->open($server, $user, $password, $dbName);
30 }
31
32 /**
33 * todo: check if these should be true like parent class
34 */
35 function implicitGroupby() { return false; }
36 function implicitOrderby() { return false; }
37
38 static function newFromParams($server, $user, $password, $dbName, $failFunction = false, $flags = 0) {
39 return new DatabaseSqlite($server, $user, $password, $dbName, $failFunction, $flags);
40 }
41
42 /** Open an SQLite database and return a resource handle to it
43 * NOTE: only $dbName is used, the other parameters are irrelevant for SQLite databases
44 */
45 function open($server,$user,$pass,$dbName) {
46 $this->mConn = false;
47 if ($dbName) {
48 $file = $this->mDatabaseFile;
49 try {
50 if ( $this->mFlags & DBO_PERSISTENT ) {
51 $this->mConn = new PDO( "sqlite:$file", $user, $pass,
52 array( PDO::ATTR_PERSISTENT => true ) );
53 } else {
54 $this->mConn = new PDO( "sqlite:$file", $user, $pass );
55 }
56 } catch ( PDOException $e ) {
57 $err = $e->getMessage();
58 }
59 if ( $this->mConn === false ) {
60 wfDebug( "DB connection error: $err\n" );
61 if ( !$this->mFailFunction ) {
62 throw new DBConnectionError( $this, $err );
63 } else {
64 return false;
65 }
66
67 }
68 $this->mOpened = $this->mConn;
69 # set error codes only, don't raise exceptions
70 $this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
71 }
72 return $this->mConn;
73 }
74
75 /**
76 * Close an SQLite database
77 */
78 function close() {
79 $this->mOpened = false;
80 if (is_object($this->mConn)) {
81 if ($this->trxLevel()) $this->immediateCommit();
82 $this->mConn = null;
83 }
84 return true;
85 }
86
87 /**
88 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
89 */
90 function doQuery($sql) {
91 $res = $this->mConn->query($sql);
92 if ($res === false) $this->reportQueryError($this->lastError(),$this->lastErrno(),$sql,__FUNCTION__);
93 else {
94 $r = $res instanceof ResultWrapper ? $res->result : $res;
95 $this->mAffectedRows = $r->rowCount();
96 $res = new ResultWrapper($this,$r->fetchAll());
97 }
98 return $res;
99 }
100
101 function freeResult(&$res) {
102 if ($res instanceof ResultWrapper) $res->result = NULL; else $res = NULL;
103 }
104
105 function fetchObject(&$res) {
106 if ($res instanceof ResultWrapper) $r =& $res->result; else $r =& $res;
107 $cur = current($r);
108 if (is_array($cur)) {
109 next($r);
110 $obj = new stdClass;
111 foreach ($cur as $k => $v) if (!is_numeric($k)) $obj->$k = $v;
112 return $obj;
113 }
114 return false;
115 }
116
117 function fetchRow(&$res) {
118 if ($res instanceof ResultWrapper) $r =& $res->result; else $r =& $res;
119 $cur = current($r);
120 if (is_array($cur)) {
121 next($r);
122 return $cur;
123 }
124 return false;
125 }
126
127 /**
128 * The PDO::Statement class implements the array interface so count() will work
129 */
130 function numRows(&$res) {
131 $r = $res instanceof ResultWrapper ? $res->result : $res;
132 return count($r);
133 }
134
135 function numFields(&$res) {
136 $r = $res instanceof ResultWrapper ? $res->result : $res;
137 return is_array($r) ? count($r[0]) : 0;
138 }
139
140 function fieldName(&$res,$n) {
141 $r = $res instanceof ResultWrapper ? $res->result : $res;
142 if (is_array($r)) {
143 $keys = array_keys($r[0]);
144 return $keys[$n];
145 }
146 return false;
147 }
148
149 /**
150 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
151 */
152 function tableName($name) {
153 return str_replace('`','',parent::tableName($name));
154 }
155
156 /**
157 * This must be called after nextSequenceVal
158 */
159 function insertId() {
160 return $this->mConn->lastInsertId();
161 }
162
163 function dataSeek(&$res,$row) {
164 if ($res instanceof ResultWrapper) $r =& $res->result; else $r =& $res;
165 reset($r);
166 if ($row > 0) for ($i = 0; $i < $row; $i++) next($r);
167 }
168
169 function lastError() {
170 if (!is_object($this->mConn)) return "Cannot return last error, no db connection";
171 $e = $this->mConn->errorInfo();
172 return isset($e[2]) ? $e[2] : '';
173 }
174
175 function lastErrno() {
176 if (!is_object($this->mConn)) return "Cannot return last error, no db connection";
177 return $this->mConn->errorCode();
178 }
179
180 function affectedRows() {
181 return $this->mAffectedRows;
182 }
183
184 /**
185 * Returns information about an index
186 * - if errors are explicitly ignored, returns NULL on failure
187 */
188 function indexInfo($table, $index, $fname = 'Database::indexExists') {
189 return false;
190 }
191
192 function indexUnique($table, $index, $fname = 'Database::indexUnique') {
193 return false;
194 }
195
196 /**
197 * Filter the options used in SELECT statements
198 */
199 function makeSelectOptions($options) {
200 foreach ($options as $k => $v) if (is_numeric($k) && $v == 'FOR UPDATE') $options[$k] = '';
201 return parent::makeSelectOptions($options);
202 }
203
204 /**
205 * Based on MySQL method (parent) with some prior SQLite-sepcific adjustments
206 */
207 function insert($table, $a, $fname = 'DatabaseSqlite::insert', $options = array()) {
208 if (!count($a)) return true;
209 if (!is_array($options)) $options = array($options);
210
211 # SQLite uses OR IGNORE not just IGNORE
212 foreach ($options as $k => $v) if ($v == 'IGNORE') $options[$k] = 'OR IGNORE';
213
214 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
215 if (isset($a[0]) && is_array($a[0])) {
216 $ret = true;
217 foreach ($a as $k => $v) if (!parent::insert($table,$v,"$fname/multi-row",$options)) $ret = false;
218 }
219 else $ret = parent::insert($table,$a,"$fname/single-row",$options);
220
221 return $ret;
222 }
223
224 /**
225 * SQLite does not have a "USE INDEX" clause, so return an empty string
226 */
227 function useIndexClause($index) {
228 return '';
229 }
230
231 # Returns the size of a text field, or -1 for "unlimited"
232 function textFieldSize($table, $field) {
233 return -1;
234 }
235
236 /**
237 * No low priority option in SQLite
238 */
239 function lowPriorityOption() {
240 return '';
241 }
242
243 /**
244 * Returns an SQL expression for a simple conditional.
245 * - uses CASE on SQLite
246 */
247 function conditional($cond, $trueVal, $falseVal) {
248 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
249 }
250
251 function wasDeadlock() {
252 return $this->lastErrno() == SQLITE_BUSY;
253 }
254
255 /**
256 * @return string wikitext of a link to the server software's web site
257 */
258 function getSoftwareLink() {
259 return "[http://sqlite.org/ SQLite]";
260 }
261
262 /**
263 * @return string Version information from the database
264 */
265 function getServerVersion() {
266 global $wgContLang;
267 $ver = $this->mConn->getAttribute(PDO::ATTR_SERVER_VERSION);
268 $size = $wgContLang->formatSize(filesize($this->mDatabaseFile));
269 $file = basename($this->mDatabaseFile);
270 return $ver." ($file: $size)";
271 }
272
273 /**
274 * Query whether a given column exists in the mediawiki schema
275 */
276 function fieldExists($table, $field) { return true; }
277
278 function fieldInfo($table, $field) { return SQLiteField::fromText($this, $table, $field); }
279
280 function begin() {
281 if ($this->mTrxLevel == 1) $this->commit();
282 $this->mConn->beginTransaction();
283 $this->mTrxLevel = 1;
284 }
285
286 function commit() {
287 if ($this->mTrxLevel == 0) return;
288 $this->mConn->commit();
289 $this->mTrxLevel = 0;
290 }
291
292 function rollback() {
293 if ($this->mTrxLevel == 0) return;
294 $this->mConn->rollBack();
295 $this->mTrxLevel = 0;
296 }
297
298 function limitResultForUpdate($sql, $num) {
299 return $sql;
300 }
301
302 function strencode($s) {
303 return substr($this->addQuotes($s),1,-1);
304 }
305
306 function encodeBlob($b) {
307 return new Blob( $b );
308 }
309
310 function decodeBlob($b) {
311 if ($b instanceof Blob) {
312 $b = $b->fetch();
313 }
314 return $b;
315 }
316
317 function addQuotes($s) {
318 if ( $s instanceof Blob ) {
319 return "x'" . bin2hex( $s->fetch() ) . "'";
320 } else {
321 return $this->mConn->quote($s);
322 }
323 }
324
325 function quote_ident($s) { return $s; }
326
327 /**
328 * For now, does nothing
329 */
330 function selectDB($db) { return true; }
331
332 /**
333 * not done
334 */
335 public function setTimeout($timeout) { return; }
336
337 function ping() {
338 wfDebug("Function ping() not written for SQLite yet");
339 return true;
340 }
341
342 /**
343 * How lagged is this slave?
344 */
345 public function getLag() {
346 return 0;
347 }
348
349 /**
350 * Called by the installer script (when modified according to the MediaWikiLite installation instructions)
351 * - this is the same way PostgreSQL works, MySQL reads in tables.sql and interwiki.sql using dbsource (which calls db->sourceFile)
352 */
353 public function setup_database() {
354 global $IP,$wgSQLiteDataDir,$wgDBTableOptions;
355 $wgDBTableOptions = '';
356 $mysql_tmpl = "$IP/maintenance/tables.sql";
357 $mysql_iw = "$IP/maintenance/interwiki.sql";
358 $sqlite_tmpl = "$IP/maintenance/sqlite/tables.sql";
359
360 # Make an SQLite template file if it doesn't exist (based on the same one MySQL uses to create a new wiki db)
361 if (!file_exists($sqlite_tmpl)) {
362 $sql = file_get_contents($mysql_tmpl);
363 $sql = preg_replace('/^\s*--.*?$/m','',$sql); # strip comments
364 $sql = preg_replace('/^\s*(UNIQUE)?\s*(PRIMARY)?\s*KEY.+?$/m','',$sql);
365 $sql = preg_replace('/^\s*(UNIQUE )?INDEX.+?$/m','',$sql); # These indexes should be created with a CREATE INDEX query
366 $sql = preg_replace('/^\s*FULLTEXT.+?$/m','',$sql); # Full text indexes
367 $sql = preg_replace('/ENUM\(.+?\)/','TEXT',$sql); # Make ENUM's into TEXT's
368 $sql = preg_replace('/binary\(\d+\)/','BLOB',$sql);
369 $sql = preg_replace('/(TYPE|MAX_ROWS|AVG_ROW_LENGTH)=\w+/','',$sql);
370 $sql = preg_replace('/,\s*\)/s',')',$sql); # removing previous items may leave a trailing comma
371 $sql = str_replace('binary','',$sql);
372 $sql = str_replace('auto_increment','PRIMARY KEY AUTOINCREMENT',$sql);
373 $sql = str_replace(' unsigned','',$sql);
374 $sql = str_replace(' int ',' INTEGER ',$sql);
375 $sql = str_replace('NOT NULL','',$sql);
376
377 # Tidy up and write file
378 $sql = preg_replace('/^\s*^/m','',$sql); # Remove empty lines
379 $sql = preg_replace('/;$/m',";\n",$sql); # Separate each statement with an empty line
380 file_put_contents($sqlite_tmpl,$sql);
381 }
382
383 # Parse the SQLite template replacing inline variables such as /*$wgDBprefix*/
384 $err = $this->sourceFile($sqlite_tmpl);
385 if ($err !== true) $this->reportQueryError($err,0,$sql,__FUNCTION__);
386
387 # Use DatabasePostgres's code to populate interwiki from MySQL template
388 $f = fopen($mysql_iw,'r');
389 if ($f == false) dieout("<li>Could not find the interwiki.sql file");
390 $sql = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
391 while (!feof($f)) {
392 $line = fgets($f,1024);
393 $matches = array();
394 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) continue;
395 $this->query("$sql $matches[1],$matches[2])");
396 }
397 }
398
399 /**
400 * No-op lock functions
401 */
402 public function lock( $lockName, $method ) {
403 return true;
404 }
405 public function unlock( $lockName, $method ) {
406 return true;
407 }
408
409 public function getSearchEngine() {
410 return "SearchEngineDummy";
411 }
412
413 /**
414 * No-op version of deadlockLoop
415 */
416 public function deadlockLoop( /*...*/ ) {
417 $args = func_get_args();
418 $function = array_shift( $args );
419 return call_user_func_array( $function, $args );
420 }
421 }
422
423 /**
424 * @ingroup Database
425 */
426 class SQLiteField extends MySQLField {
427
428 function __construct() {
429 }
430
431 static function fromText($db, $table, $field) {
432 $n = new SQLiteField;
433 $n->name = $field;
434 $n->tablename = $table;
435 return $n;
436 }
437
438 } // end DatabaseSqlite class
439