blob: 1f2d8f0a09b97d723fec34f8b928258d90450c37 [file] [log] [blame]
Andrey Andreev8ae24c52012-01-16 13:05:23 +02001<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2/**
3 * CodeIgniter
4 *
5 * An open source application development framework for PHP 5.1.6 or newer
6 *
7 * NOTICE OF LICENSE
8 *
9 * Licensed under the Open Software License version 3.0
10 *
11 * This source file is subject to the Open Software License (OSL 3.0) that is
Andrey Andreevf20fb982012-01-24 15:26:01 +020012 * bundled with this package in the files license.txt / license.rst. It is
Andrey Andreev8ae24c52012-01-16 13:05:23 +020013 * also available through the world wide web at this URL:
14 * http://opensource.org/licenses/OSL-3.0
15 * If you did not receive a copy of the license and are unable to obtain it
16 * through the world wide web, please send an email to
17 * licensing@ellislab.com so we can send you a copy immediately.
18 *
19 * @package CodeIgniter
20 * @author EllisLab Dev Team
21 * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
22 * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
23 * @link http://codeigniter.com
24 * @since Version 1.0
25 * @filesource
26 */
27
28/**
29 * SQLite3 Database Adapter Class
30 *
31 * Note: _DB is an extender class that the app controller
32 * creates dynamically based on whether the active record
33 * class is being used or not.
34 *
35 * @package CodeIgniter
36 * @subpackage Drivers
37 * @category Database
38 * @author Andrey Andreev
39 * @link http://codeigniter.com/user_guide/database/
40 */
41class CI_DB_sqlite3_driver extends CI_DB {
42
43 public $dbdriver = 'sqlite3';
44
45 // The character used for escaping
Andrey Andreevcb9f3612012-01-26 02:06:48 +020046 protected $_escape_char = '"';
Andrey Andreev8ae24c52012-01-16 13:05:23 +020047
48 // clause and character used for LIKE escape sequences
Andrey Andreevcb9f3612012-01-26 02:06:48 +020049 protected $_like_escape_str = ' ESCAPE \'%s\' ';
50 protected $_like_escape_chr = '!';
Andrey Andreev8ae24c52012-01-16 13:05:23 +020051
52 /**
53 * The syntax to count rows is slightly different across different
54 * database engines, so this string appears in each driver and is
55 * used for the count_all() and count_all_results() functions.
56 */
Andrey Andreevcb9f3612012-01-26 02:06:48 +020057 protected $_count_string = 'SELECT COUNT(*) AS ';
58 protected $_random_keyword = ' RANDOM()';
Andrey Andreev8ae24c52012-01-16 13:05:23 +020059
60 /**
61 * Non-persistent database connection
62 *
63 * @return object type SQLite3
64 */
65 public function db_connect()
66 {
67 try
68 {
69 return ( ! $this->password)
70 ? new SQLite3($this->database)
71 : new SQLite3($this->database, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, $this->password);
72 }
73 catch (Exception $e)
74 {
75 return FALSE;
76 }
77 }
78
79 // --------------------------------------------------------------------
80
81 /**
82 * Persistent database connection
83 *
84 * @return object type SQLite3
85 */
86 public function db_pconnect()
87 {
88 log_message('debug', 'SQLite3 doesn\'t support persistent connections');
89 return $this->db_pconnect();
90 }
91
92 // --------------------------------------------------------------------
93
94 /**
95 * Reconnect
96 *
97 * Keep / reestablish the db connection if no queries have been
98 * sent for a length of time exceeding the server's idle timeout
99 *
100 * @return void
101 */
102 public function reconnect()
103 {
104 // Not supported
105 }
106
107 // --------------------------------------------------------------------
108
109 /**
110 * Select the database
111 *
112 * @return bool
113 */
114 public function db_select()
115 {
116 // Not needed, in SQLite every pseudo-connection is a database
117 return TRUE;
118 }
119
120 // --------------------------------------------------------------------
121
122 /**
Andrey Andreev8ae24c52012-01-16 13:05:23 +0200123 * Version number query string
124 *
125 * @return string
126 */
127 protected function _version()
128 {
129 return implode(' (', $this->conn_id->version()).')';
130 }
131
132 // --------------------------------------------------------------------
133
134 /**
135 * Execute the query
136 *
137 * @param string an SQL query
138 * @return mixed SQLite3Result object or bool
139 */
140 protected function _execute($sql)
141 {
142 if ( ! preg_match('/^(SELECT|EXPLAIN).+$/i', ltrim($sql)))
143 {
144 return $this->conn_id->exec($sql);
145 }
146
147 // TODO: Implement use of SQLite3::querySingle(), if needed
148 // TODO: Use $this->_prep_query(), if needed
149 return $this->conn_id->query($sql);
150 }
151
152 // --------------------------------------------------------------------
153
154 /**
155 * Prep the query
156 *
157 * If needed, each database adapter can prep the query string
158 *
159 * @param string an SQL query
160 * @return string
161 */
Andrey Andreeva3ed0862012-01-25 14:46:52 +0200162 protected function _prep_query($sql)
Andrey Andreev8ae24c52012-01-16 13:05:23 +0200163 {
164 return $this->conn_id->prepare($sql);
165 }
166
167 // --------------------------------------------------------------------
168
169 /**
170 * Begin Transaction
171 *
172 * @return bool
173 */
174 public function trans_begin($test_mode = FALSE)
175 {
Andrey Andreev8ae24c52012-01-16 13:05:23 +0200176 // When transactions are nested we only begin/commit/rollback the outermost ones
Andrey Andreev72d7a6e2012-01-19 16:02:32 +0200177 if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
Andrey Andreev8ae24c52012-01-16 13:05:23 +0200178 {
179 return TRUE;
180 }
181
182 // Reset the transaction failure flag.
183 // If the $test_mode flag is set to TRUE transactions will be rolled back
184 // even if the queries produce a successful result.
185 $this->_trans_failure = ($test_mode === TRUE);
186
187 return $this->conn_id->exec('BEGIN TRANSACTION');
188 }
189
190 // --------------------------------------------------------------------
191
192 /**
193 * Commit Transaction
194 *
195 * @return bool
196 */
197 public function trans_commit()
198 {
Andrey Andreev8ae24c52012-01-16 13:05:23 +0200199 // When transactions are nested we only begin/commit/rollback the outermost ones
Andrey Andreev72d7a6e2012-01-19 16:02:32 +0200200 if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
Andrey Andreev8ae24c52012-01-16 13:05:23 +0200201 {
202 return TRUE;
203 }
204
205 return $this->conn_id->exec('END TRANSACTION');
206 }
207
208 // --------------------------------------------------------------------
209
210 /**
211 * Rollback Transaction
212 *
213 * @return bool
214 */
215 public function trans_rollback()
216 {
Andrey Andreev8ae24c52012-01-16 13:05:23 +0200217 // When transactions are nested we only begin/commit/rollback the outermost ones
Andrey Andreev72d7a6e2012-01-19 16:02:32 +0200218 if ( ! $this->trans_enabled OR $this->_trans_depth > 0)
Andrey Andreev8ae24c52012-01-16 13:05:23 +0200219 {
220 return TRUE;
221 }
222
223 return $this->conn_id->exec('ROLLBACK');
224 }
225
226 // --------------------------------------------------------------------
227
228 /**
229 * Escape String
230 *
231 * @param string
232 * @param bool whether or not the string will be used in a LIKE condition
233 * @return string
234 */
235 public function escape_str($str, $like = FALSE)
236 {
237 if (is_array($str))
238 {
239 foreach ($str as $key => $val)
240 {
241 $str[$key] = $this->escape_str($val, $like);
242 }
243
244 return $str;
245 }
246
247 $str = $this->conn_id->escapeString(remove_invisible_characters($str));
248
249 // escape LIKE condition wildcards
250 if ($like === TRUE)
251 {
252 return str_replace(array('%', '_', $this->_like_escape_chr),
253 array($this->_like_escape_chr.'%', $this->_like_escape_chr.'_', $this->_like_escape_chr.$this->_like_escape_chr),
254 $str);
255 }
256
257 return $str;
258 }
259
260 // --------------------------------------------------------------------
261
262 /**
263 * Affected Rows
264 *
265 * @return int
266 */
267 public function affected_rows()
268 {
269 return $this->conn_id->changes();
270 }
271
272 // --------------------------------------------------------------------
273
274 /**
275 * Insert ID
276 *
277 * @return int
278 */
279 public function insert_id()
280 {
281 return $this->conn_id->lastInsertRowID();
282 }
283
284 // --------------------------------------------------------------------
285
286 /**
287 * "Count All" query
288 *
289 * Generates a platform-specific query string that counts all records in
290 * the specified database
291 *
292 * @param string
293 * @return int
294 */
295 public function count_all($table = '')
296 {
297 if ($table == '')
298 {
299 return 0;
300 }
301
302 $result = $this->conn_id->querySingle($this->_count_string.$this->_protect_identifiers('numrows')
303 .' FROM '.$this->_protect_identifiers($table, TRUE, NULL, FALSE));
304
305 return empty($result) ? 0 : (int) $result;
306 }
307
308 // --------------------------------------------------------------------
309
310 /**
311 * Show table query
312 *
313 * Generates a platform-specific query string so that the table names can be fetched
314 *
315 * @param bool
316 * @return string
317 */
318 protected function _list_tables($prefix_limit = FALSE)
319 {
320 return 'SELECT "NAME" FROM "SQLITE_MASTER" WHERE "TYPE" = \'table\''
321 .(($prefix_limit !== FALSE && $this->dbprefix != '')
322 ? ' AND "NAME" LIKE \''.$this->escape_like_str($this->dbprefix).'%\' '.sprintf($this->_like_escape_str, $this->_like_escape_chr)
323 : '');
324 }
325
326 // --------------------------------------------------------------------
327
328 /**
329 * Show column query
330 *
331 * Generates a platform-specific query string so that the column names can be fetched
332 *
333 * @param string the table name
334 * @return string
335 */
336 protected function _list_columns($table = '')
337 {
338 // Not supported
339 return FALSE;
340 }
341
342 // --------------------------------------------------------------------
343
344 /**
345 * Field data query
346 *
347 * Generates a platform-specific query so that the column data can be retrieved
348 *
349 * @param string the table name
350 * @return string
351 */
352 protected function _field_data($table)
353 {
354 return 'SELECT * FROM '.$table.' LIMIT 0,1';
355 }
356
357 // --------------------------------------------------------------------
358
359 /**
360 * The error message string
361 *
362 * @return string
363 */
364 protected function _error_message()
365 {
366 return $this->conn_id->lastErrorMsg();
367 }
368
369 // --------------------------------------------------------------------
370
371 /**
372 * The error message number
373 *
374 * @return int
375 */
376 protected function _error_number()
377 {
378 return $this->conn_id->lastErrorCode();
379 }
380
381 // --------------------------------------------------------------------
382
383 /**
384 * Escape the SQL Identifiers
385 *
386 * This function escapes column and table names
387 *
388 * @param string
389 * @return string
390 */
Andrey Andreevcb9f3612012-01-26 02:06:48 +0200391 public function _escape_identifiers($item)
Andrey Andreev8ae24c52012-01-16 13:05:23 +0200392 {
393 if ($this->_escape_char == '')
394 {
395 return $item;
396 }
397
398 foreach ($this->_reserved_identifiers as $id)
399 {
400 if (strpos($item, '.'.$id) !== FALSE)
401 {
402 $item = str_replace('.', $this->_escape_char.'.', $item);
403
404 // remove duplicates if the user already included the escape
405 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $this->_escape_char.$item);
406 }
407 }
408
409 if (strpos($item, '.') !== FALSE)
410 {
411 $item = str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item);
412 }
413
414 // remove duplicates if the user already included the escape
415 return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $this->_escape_char.$item.$this->_escape_char);
416 }
417
418 // --------------------------------------------------------------------
419
420 /**
421 * From Tables
422 *
423 * This function implicitly groups FROM tables so there is no confusion
424 * about operator precedence in harmony with SQL standards
425 *
426 * @param string
427 * @return string
428 */
429 protected function _from_tables($tables)
430 {
431 if ( ! is_array($tables))
432 {
433 $tables = array($tables);
434 }
435
436 return '('.implode(', ', $tables).')';
437 }
438
439 // --------------------------------------------------------------------
440
441 /**
442 * Insert statement
443 *
444 * Generates a platform-specific insert string from the supplied data
445 *
446 * @param string the table name
447 * @param array the insert keys
448 * @param array the insert values
449 * @return string
450 */
451 protected function _insert($table, $keys, $values)
452 {
453 return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
454 }
455
456 // --------------------------------------------------------------------
457
458 /**
459 * Update statement
460 *
461 * Generates a platform-specific update string from the supplied data
462 *
463 * @param string the table name
464 * @param array the update data
465 * @param array the where clause
466 * @param array the orderby clause
467 * @param array the limit clause
468 * @return string
469 */
470 protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE)
471 {
472 foreach ($values as $key => $val)
473 {
474 $valstr[] = $key.' = '.$val;
475 }
476
477 return 'UPDATE '.$table.' SET '.implode(', ', $valstr)
478 .(($where != '' && count($where) > 0) ? ' WHERE '.implode(' ', $where) : '')
479 .(count($orderby) > 0 ? ' ORDER BY '.implode(', ', $orderby) : '')
480 .( ! $limit ? '' : ' LIMIT '.$limit);
481 }
482
483 // --------------------------------------------------------------------
484
485 /**
486 * Truncate statement
487 *
488 * Generates a platform-specific truncate string from the supplied data
489 * If the database does not support the truncate() command, then
490 * this method maps to "DELETE FROM table"
491 *
492 * @param string the table name
493 * @return string
494 */
495 protected function _truncate($table)
496 {
497 return $this->_delete($table);
498 }
499
500 // --------------------------------------------------------------------
501
502 /**
503 * Delete statement
504 *
505 * Generates a platform-specific delete string from the supplied data
506 *
507 * @param string the table name
508 * @param array the where clause
509 * @param string the limit clause
510 * @return string
511 */
512 protected function _delete($table, $where = array(), $like = array(), $limit = FALSE)
513 {
514 $conditions = '';
515 if (count($where) > 0 OR count($like) > 0)
516 {
517 $conditions .= "\nWHERE ".implode("\n", $this->ar_where);
518
519 if (count($where) > 0 && count($like) > 0)
520 {
521 $conditions .= ' AND ';
522 }
523 $conditions .= implode("\n", $like);
524 }
525
526 return 'DELETE FROM '.$table.$conditions.( ! $limit ? '' : ' LIMIT '.$limit);
527 }
528
529 // --------------------------------------------------------------------
530
531 /**
532 * Limit string
533 *
534 * Generates a platform-specific LIMIT clause
535 *
536 * @param string the sql query string
537 * @param int the number of rows to limit the query to
538 * @param int the offset value
539 * @return string
540 */
541 protected function _limit($sql, $limit, $offset)
542 {
543 return $sql.($offset ? $offset.',' : '').$limit;
544 }
545
546 // --------------------------------------------------------------------
547
548 /**
549 * Close DB Connection
550 *
551 * @return void
552 */
553 protected function _close()
554 {
555 $this->conn_id->close();
556 }
557
558}
559
560/* End of file sqlite3_driver.php */
561/* Location: ./system/database/drivers/sqlite3/sqlite3_driver.php */