1 <?php
defined('SYSPATH') OR die('No direct access allowed.');
3 * Class: Database_PdoSqlite_Driver
4 * Provides specific database items for Sqlite.
6 * Connection string should be, eg: "pdosqlite://path/to/database.db"
9 * author - Doutu, updated by gregmac
14 class Database_Pdosqlite_Driver
extends Database_Driver
{
16 // Database connection link
21 * Constructor: __construct
22 * Sets up the config for the class.
25 * config - database configuration
28 public function __construct($config)
30 $this->db_config
= $config;
32 Kohana
::log('debug', 'PDO:Sqlite Database Driver Initialized');
35 public function connect()
37 // Import the connect variables
38 extract($this->db_config
['connection']);
42 $this->link
= new PDO('sqlite:'.$socket.$database, $user, $pass,
43 array(PDO
::ATTR_PERSISTENT
=> $this->db_config
['persistent']));
45 $this->link
->setAttribute(PDO
::ATTR_CASE
, PDO
::CASE_NATURAL
);
46 $this->link
->query('PRAGMA count_changes=1;');
48 if ($charset = $this->db_config
['character_set'])
50 $this->set_charset($charset);
53 catch (PDOException
$e)
55 throw new Kohana_Database_Exception('database.error', $e->getMessage());
58 // Clear password after successful connect
59 $this->db_config
['connection']['pass'] = NULL;
64 public function query($sql)
68 $sth = $this->link
->prepare($sql);
70 catch (PDOException
$e)
72 throw new Kohana_Database_Exception('database.error', $e->getMessage());
74 return new Pdosqlite_Result($sth, $this->link
, $this->db_config
['object'], $sql);
77 public function set_charset($charset)
79 $this->link
->query('PRAGMA encoding = '.$this->escape_str($charset));
82 public function escape_table($table)
84 if ( ! $this->db_config
['escape'])
87 return '`'.str_replace('.', '`.`', $table).'`';
90 public function escape_column($column)
92 if ( ! $this->db_config
['escape'])
95 if (strtolower($column) == 'count(*)' OR $column == '*')
98 // This matches any modifiers we support to SELECT.
99 if ( ! preg_match('/\b(?:rand|all|distinct(?:row)?|high_priority|sql_(?:small_result|b(?:ig_result|uffer_result)|no_cache|ca(?:che|lc_found_rows)))\s/i', $column))
101 if (stripos($column, ' AS ') !== FALSE)
103 // Force 'AS' to uppercase
104 $column = str_ireplace(' AS ', ' AS ', $column);
106 // Runs escape_column on both sides of an AS statement
107 $column = array_map(array($this, __FUNCTION__
), explode(' AS ', $column));
109 // Re-create the AS statement
110 return implode(' AS ', $column);
113 return preg_replace('/[^.*]+/', '`$0`', $column);
116 $parts = explode(' ', $column);
119 for ($i = 0, $c = count($parts); $i < $c; $i++
)
121 // The column is always last
124 $column .= preg_replace('/[^.*]+/', '`$0`', $parts[$i]);
126 else // otherwise, it's a modifier
128 $column .= $parts[$i].' ';
134 public function limit($limit, $offset = 0)
136 return 'LIMIT '.$offset.', '.$limit;
139 public function compile_select($database)
141 $sql = ($database['distinct'] == TRUE) ?
'SELECT DISTINCT ' : 'SELECT ';
142 $sql .= (count($database['select']) > 0) ?
implode(', ', $database['select']) : '*';
144 if (count($database['from']) > 0)
147 $sql .= implode(', ', $database['from']);
150 if (count($database['join']) > 0)
152 foreach($database['join'] AS $join)
154 $sql .= "\n".$join['type'].'JOIN '.implode(', ', $join['tables']).' ON '.$join['conditions'];
158 if (count($database['where']) > 0)
163 $sql .= implode("\n", $database['where']);
165 if (count($database['groupby']) > 0)
167 $sql .= "\nGROUP BY ";
168 $sql .= implode(', ', $database['groupby']);
171 if (count($database['having']) > 0)
174 $sql .= implode("\n", $database['having']);
177 if (count($database['orderby']) > 0)
179 $sql .= "\nORDER BY ";
180 $sql .= implode(', ', $database['orderby']);
183 if (is_numeric($database['limit']))
186 $sql .= $this->limit($database['limit'], $database['offset']);
192 public function escape_str($str)
194 if ( ! $this->db_config
['escape'])
197 if (function_exists('sqlite_escape_string'))
199 $res = sqlite_escape_string($str);
203 $res = str_replace("'", "''", $str);
208 public function list_tables(Database
$db)
210 $sql = "SELECT `name` FROM `sqlite_master` WHERE `type`='table' ORDER BY `name`;";
213 $result = $db->query($sql)->result(FALSE, PDO
::FETCH_ASSOC
);
215 foreach ($result as $row)
217 $tables[] = current($row);
220 catch (PDOException
$e)
222 throw new Kohana_Database_Exception('database.error', $e->getMessage());
227 public function show_error()
229 $err = $this->link
->errorInfo();
230 return isset($err[2]) ?
$err[2] : 'Unknown error!';
233 public function list_fields($table, $query = FALSE)
236 if (is_object($query))
238 if (empty($tables[$table]))
240 $tables[$table] = array();
242 foreach ($query->result() as $row)
244 $tables[$table][] = $row->name
;
248 return $tables[$table];
252 $result = $this->link
->query( 'PRAGMA table_info('.$this->escape_table($table).')' );
254 foreach ($result as $row)
256 $tables[$table][$row['name']] = $this->sql_type($row['type']);
259 return $tables[$table];
263 public function field_data($table)
265 Kohana
::log('error', 'This method is under developing');
268 * Version number query string
275 return $this->link
->getAttribute(constant("PDO::ATTR_SERVER_VERSION"));
278 } // End Database_PdoSqlite_Driver Class
283 class Pdosqlite_Result
extends Database_Result
{
285 // Data fetching types
286 protected $fetch_type = PDO
::FETCH_OBJ
;
287 protected $return_type = PDO
::FETCH_ASSOC
;
290 * Sets up the result variables.
292 * @param resource query result
293 * @param resource database link
294 * @param boolean return objects or arrays
295 * @param string SQL query that was run
297 public function __construct($result, $link, $object = TRUE, $sql)
299 if (is_object($result) OR $result = $link->prepare($sql))
306 catch (PDOException
$e)
308 throw new Kohana_Database_Exception('database.error', $e->getMessage());
311 if (preg_match('/^SELECT|PRAGMA|EXPLAIN/i', $sql))
313 $this->result
= $result;
314 $this->current_row
= 0;
316 $this->total_rows
= $this->sqlite_row_count();
318 $this->fetch_type
= ($object === TRUE) ? PDO
::FETCH_OBJ
: PDO
::FETCH_ASSOC
;
320 elseif (preg_match('/^DELETE|INSERT|UPDATE/i', $sql))
322 $this->insert_id
= $link->lastInsertId();
328 throw new Kohana_Database_Exception('database.error', $link->errorInfo().' - '.$sql);
332 $this->result($object);
338 private function sqlite_row_count()
341 while ($this->result
->fetch())
346 // The query must be re-fetched now.
347 $this->result
->execute();
353 * Destructor: __destruct
354 * Magic __destruct function, frees the result.
356 public function __destruct()
358 if (is_object($this->result
))
360 $this->result
->closeCursor();
361 $this->result
= NULL;
365 public function result($object = TRUE, $type = PDO
::FETCH_BOTH
)
367 $this->fetch_type
= (bool) $object ? PDO
::FETCH_OBJ
: PDO
::FETCH_BOTH
;
369 if ($this->fetch_type
== PDO
::FETCH_OBJ
)
371 $this->return_type
= (is_string($type) AND Kohana
::auto_load($type)) ?
$type : 'stdClass';
375 $this->return_type
= $type;
381 public function as_array($object = NULL, $type = PDO
::FETCH_ASSOC
)
383 return $this->result_array($object, $type);
386 public function result_array($object = NULL, $type = PDO
::FETCH_ASSOC
)
390 if (is_string($object))
394 elseif (is_bool($object))
396 if ($object === TRUE)
398 $fetch = PDO
::FETCH_OBJ
;
400 // NOTE - The class set by $type must be defined before fetching the result,
401 // autoloading is disabled to save a lot of stupid overhead.
402 $type = (is_string($type) AND Kohana
::auto_load($type)) ?
$type : 'stdClass';
406 $fetch = PDO
::FETCH_OBJ
;
411 // Use the default config values
412 $fetch = $this->fetch_type
;
414 if ($fetch == PDO
::FETCH_OBJ
)
416 $type = (is_string($type) AND Kohana
::auto_load($type)) ?
$type : 'stdClass';
421 while ($row = $this->result
->fetch($fetch))
426 catch(PDOException
$e)
428 throw new Kohana_Database_Exception('database.error', $e->getMessage());
434 public function list_fields()
436 $field_names = array();
437 for ($i = 0, $max = $this->result
->columnCount(); $i < $max; $i++
)
439 $info = $this->result
->getColumnMeta($i);
440 $field_names[] = $info['name'];
445 public function seek($offset)
447 // To request a scrollable cursor for your PDOStatement object, you must
448 // set the PDO::ATTR_CURSOR attribute to PDO::CURSOR_SCROLL when you
449 // prepare the statement.
450 Kohana
::log('error', get_class($this).' does not support scrollable cursors, '.__FUNCTION__
.' call ignored');
455 public function offsetGet($offset)
459 return $this->result
->fetch($this->fetch_type
, PDO
::FETCH_ORI_ABS
, $offset);
461 catch(PDOException
$e)
463 throw new Kohana_Database_Exception('database.error', $e->getMessage());
467 public function rewind()
469 // Same problem that seek() has, see above.
470 return $this->seek(0);
473 } // End PdoSqlite_Result Class