Avail feature updated
[ninja.git] / system / libraries / Database.php
blob7be6e4d36ae4e981f654023c9e96107d8e5f965d
1 <?php defined('SYSPATH') OR die('No direct access allowed.');
2 /**
3 * Provides database access in a platform agnostic way, using simple query building blocks.
5 * $Id: Database.php 3917 2009-01-21 03:06:22Z zombor $
7 * @package Core
8 * @author Kohana Team
9 * @copyright (c) 2007-2008 Kohana Team
10 * @license http://kohanaphp.com/license.html
12 class Database {
14 // Database instances
15 public static $instances = array();
17 // Global benchmark
18 public static $benchmarks = array();
20 // Configuration
21 protected $config = array
23 'benchmark' => TRUE,
24 'persistent' => FALSE,
25 'connection' => '',
26 'character_set' => 'utf8',
27 'table_prefix' => '',
28 'object' => TRUE,
29 'cache' => FALSE,
30 'escape' => TRUE,
33 // Database driver object
34 protected $driver;
35 protected $link;
37 // Un-compiled parts of the SQL query
38 protected $select = array();
39 protected $set = array();
40 protected $from = array();
41 protected $join = array();
42 protected $where = array();
43 protected $orderby = array();
44 protected $order = array();
45 protected $groupby = array();
46 protected $having = array();
47 protected $distinct = FALSE;
48 protected $limit = FALSE;
49 protected $offset = FALSE;
50 protected $last_query = '';
52 // Stack of queries for push/pop
53 protected $query_history = array();
55 /**
56 * Returns a singleton instance of Database.
58 * @param mixed configuration array or DSN
59 * @return Database
61 public static function & instance($name = 'default', $config = NULL)
63 if ( ! isset(Database::$instances[$name]))
65 // Create a new instance
66 Database::$instances[$name] = new Database($config === NULL ? $name : $config);
69 return Database::$instances[$name];
72 /**
73 * Returns the name of a given database instance.
75 * @param Database instance of Database
76 * @return string
78 public static function instance_name(Database $db)
80 return array_search($db, Database::$instances, TRUE);
83 /**
84 * Sets up the database configuration, loads the Database_Driver.
86 * @throws Kohana_Database_Exception
88 public function __construct($config = array())
90 if (empty($config))
92 // Load the default group
93 $config = Kohana::config('database.default');
95 elseif (is_array($config) AND count($config) > 0)
97 if ( ! array_key_exists('connection', $config))
99 $config = array('connection' => $config);
102 elseif (is_string($config))
104 // The config is a DSN string
105 if (strpos($config, '://') !== FALSE)
107 $config = array('connection' => $config);
109 // The config is a group name
110 else
112 $name = $config;
114 // Test the config group name
115 if (($config = Kohana::config('database.'.$config)) === NULL)
116 throw new Kohana_Database_Exception('database.undefined_group', $name);
120 // Merge the default config with the passed config
121 $this->config = array_merge($this->config, $config);
123 if (is_string($this->config['connection']))
125 // Make sure the connection is valid
126 if (strpos($this->config['connection'], '://') === FALSE)
127 throw new Kohana_Database_Exception('database.invalid_dsn', $this->config['connection']);
129 // Parse the DSN, creating an array to hold the connection parameters
130 $db = array
132 'type' => FALSE,
133 'user' => FALSE,
134 'pass' => FALSE,
135 'host' => FALSE,
136 'port' => FALSE,
137 'socket' => FALSE,
138 'database' => FALSE
141 // Get the protocol and arguments
142 list ($db['type'], $connection) = explode('://', $this->config['connection'], 2);
144 if (strpos($connection, '@') !== FALSE)
146 // Get the username and password
147 list ($db['pass'], $connection) = explode('@', $connection, 2);
148 // Check if a password is supplied
149 $logindata = explode(':', $db['pass'], 2);
150 $db['pass'] = (count($logindata) > 1) ? $logindata[1] : '';
151 $db['user'] = $logindata[0];
153 // Prepare for finding the database
154 $connection = explode('/', $connection);
156 // Find the database name
157 $db['database'] = array_pop($connection);
159 // Reset connection string
160 $connection = implode('/', $connection);
162 // Find the socket
163 if (preg_match('/^unix\([^)]++\)/', $connection))
165 // This one is a little hairy: we explode based on the end of
166 // the socket, removing the 'unix(' from the connection string
167 list ($db['socket'], $connection) = explode(')', substr($connection, 5), 2);
169 elseif (strpos($connection, ':') !== FALSE)
171 // Fetch the host and port name
172 list ($db['host'], $db['port']) = explode(':', $connection, 2);
174 else
176 $db['host'] = $connection;
179 else
181 // File connection
182 $connection = explode('/', $connection);
184 // Find database file name
185 $db['database'] = array_pop($connection);
187 // Find database directory name
188 $db['socket'] = implode('/', $connection).'/';
191 // Reset the connection array to the database config
192 $this->config['connection'] = $db;
194 // Set driver name
195 $driver = 'Database_'.ucfirst($this->config['connection']['type']).'_Driver';
197 // Load the driver
198 if ( ! Kohana::auto_load($driver))
199 throw new Kohana_Database_Exception('core.driver_not_found', $this->config['connection']['type'], get_class($this));
201 // Initialize the driver
202 $this->driver = new $driver($this->config);
204 // Validate the driver
205 if ( ! ($this->driver instanceof Database_Driver))
206 throw new Kohana_Database_Exception('core.driver_implements', $this->config['connection']['type'], get_class($this), 'Database_Driver');
210 * Simple connect method to get the database queries up and running.
212 * @return void
214 public function connect()
216 // A link can be a resource or an object
217 if ( ! is_resource($this->link) AND ! is_object($this->link))
219 $this->link = $this->driver->connect();
220 if ( ! is_resource($this->link) AND ! is_object($this->link))
221 throw new Kohana_Database_Exception('database.connection', $this->driver->show_error());
223 // Clear password after successful connect
224 $this->config['connection']['pass'] = NULL;
229 Returns the last error message available from the underlying
230 driver, or an unspecified non-empty string if this object has
231 no driver.
233 @return string
235 public function error_message()
237 return $this->driver
238 ? $this->driver->show_error()
239 : "No driver loaded - no error information available."
244 * Runs a query into the driver and returns the result.
246 * @param string SQL query to execute
247 * @return Database_Result
249 public function query($sql = '')
251 if ($sql == '') return FALSE;
253 // No link? Connect!
254 $this->link or $this->connect();
256 // Start the benchmark
257 $start = microtime(TRUE);
259 if (func_num_args() > 1) //if we have more than one argument ($sql)
261 $argv = func_get_args();
262 $binds = (is_array(next($argv))) ? current($argv) : array_slice($argv, 1);
265 // Compile binds if needed
266 if (isset($binds))
268 $sql = $this->compile_binds($sql, $binds);
271 // Fetch the result
272 $result = $this->driver->query($this->last_query = $sql);
274 // Stop the benchmark
275 $stop = microtime(TRUE);
277 if ($this->config['benchmark'] == TRUE)
279 // Benchmark the query
280 self::$benchmarks[] = array('query' => $sql, 'time' => $stop - $start, 'rows' => count($result));
283 return $result;
287 * Selects the column names for a database query.
289 * @param string string or array of column names to select
290 * @return Database This Database object.
292 public function select($sql = '*')
294 if (func_num_args() > 1)
296 $sql = func_get_args();
298 elseif (is_string($sql))
300 $sql = explode(',', $sql);
302 else
304 $sql = (array) $sql;
307 foreach ($sql as $val)
309 if (($val = trim($val)) === '') continue;
311 if (strpos($val, '(') === FALSE AND $val !== '*')
313 if (preg_match('/^DISTINCT\s++(.+)$/i', $val, $matches))
315 $val = $this->config['table_prefix'].$matches[1];
316 $this->distinct = TRUE;
318 else
320 $val = (strpos($val, '.') !== FALSE) ? $this->config['table_prefix'].$val : $val;
323 $val = $this->driver->escape_column($val);
326 $this->select[] = $val;
329 return $this;
333 * Selects the from table(s) for a database query.
335 * @param string string or array of tables to select
336 * @return Database This Database object.
338 public function from($sql)
340 if (func_num_args() > 1)
342 $sql = func_get_args();
344 elseif (is_string($sql))
346 $sql = explode(',', $sql);
348 else
350 $sql = (array) $sql;
353 foreach ($sql as $val)
355 if (($val = trim($val)) === '') continue;
357 $this->from[] = $this->config['table_prefix'].$val;
360 return $this;
364 * Generates the JOIN portion of the query.
366 * @param string table name
367 * @param string|array where key or array of key => value pairs
368 * @param string where value
369 * @param string type of join
370 * @return Database This Database object.
372 public function join($table, $key, $value = NULL, $type = '')
374 $join = array();
376 if ( ! empty($type))
378 $type = strtoupper(trim($type));
380 if ( ! in_array($type, array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER'), TRUE))
382 $type = '';
384 else
386 $type .= ' ';
390 $cond = array();
391 $keys = is_array($key) ? $key : array($key => $value);
392 foreach ($keys as $key => $value)
394 $key = (strpos($key, '.') !== FALSE) ? $this->config['table_prefix'].$key : $key;
395 $cond[] = $this->driver->where($key, $this->driver->escape_column($this->config['table_prefix'].$value), 'AND ', count($cond), FALSE);
398 if( ! is_array($this->join)) { $this->join = array(); }
400 foreach ((array) $table as $t)
402 $join['tables'][] = $this->driver->escape_column($this->config['table_prefix'].$t);
405 $join['conditions'] = '('.trim(implode(' ', $cond)).')';
406 $join['type'] = $type;
408 $this->join[] = $join;
410 return $this;
415 * Selects the where(s) for a database query.
417 * @param string|array key name or array of key => value pairs
418 * @param string value to match with key
419 * @param boolean disable quoting of WHERE clause
420 * @return Database This Database object.
422 public function where($key, $value = NULL, $quote = TRUE)
424 $quote = (func_num_args() < 2 AND ! is_array($key)) ? -1 : $quote;
425 $keys = is_array($key) ? $key : array($key => $value);
427 foreach ($keys as $key => $value)
429 $key = (strpos($key, '.') !== FALSE) ? $this->config['table_prefix'].$key : $key;
430 $this->where[] = $this->driver->where($key, $value, 'AND ', count($this->where), $quote);
433 return $this;
437 * Selects the or where(s) for a database query.
439 * @param string|array key name or array of key => value pairs
440 * @param string value to match with key
441 * @param boolean disable quoting of WHERE clause
442 * @return Database This Database object.
444 public function orwhere($key, $value = NULL, $quote = TRUE)
446 $quote = (func_num_args() < 2 AND ! is_array($key)) ? -1 : $quote;
447 $keys = is_array($key) ? $key : array($key => $value);
449 foreach ($keys as $key => $value)
451 $key = (strpos($key, '.') !== FALSE) ? $this->config['table_prefix'].$key : $key;
452 $this->where[] = $this->driver->where($key, $value, 'OR ', count($this->where), $quote);
455 return $this;
459 * Selects the like(s) for a database query.
461 * @param string|array field name or array of field => match pairs
462 * @param string like value to match with field
463 * @param boolean automatically add starting and ending wildcards
464 * @return Database This Database object.
466 public function like($field, $match = '', $auto = TRUE)
468 $fields = is_array($field) ? $field : array($field => $match);
470 foreach ($fields as $field => $match)
472 $field = (strpos($field, '.') !== FALSE) ? $this->config['table_prefix'].$field : $field;
473 $this->where[] = $this->driver->like($field, $match, $auto, 'AND ', count($this->where));
476 return $this;
480 * Selects the or like(s) for a database query.
482 * @param string|array field name or array of field => match pairs
483 * @param string like value to match with field
484 * @param boolean automatically add starting and ending wildcards
485 * @return Database This Database object.
487 public function orlike($field, $match = '', $auto = TRUE)
489 $fields = is_array($field) ? $field : array($field => $match);
491 foreach ($fields as $field => $match)
493 $field = (strpos($field, '.') !== FALSE) ? $this->config['table_prefix'].$field : $field;
494 $this->where[] = $this->driver->like($field, $match, $auto, 'OR ', count($this->where));
497 return $this;
501 * Selects the not like(s) for a database query.
503 * @param string|array field name or array of field => match pairs
504 * @param string like value to match with field
505 * @param boolean automatically add starting and ending wildcards
506 * @return Database This Database object.
508 public function notlike($field, $match = '', $auto = TRUE)
510 $fields = is_array($field) ? $field : array($field => $match);
512 foreach ($fields as $field => $match)
514 $field = (strpos($field, '.') !== FALSE) ? $this->config['table_prefix'].$field : $field;
515 $this->where[] = $this->driver->notlike($field, $match, $auto, 'AND ', count($this->where));
518 return $this;
522 * Selects the or not like(s) for a database query.
524 * @param string|array field name or array of field => match pairs
525 * @param string like value to match with field
526 * @return Database This Database object.
528 public function ornotlike($field, $match = '', $auto = TRUE)
530 $fields = is_array($field) ? $field : array($field => $match);
532 foreach ($fields as $field => $match)
534 $field = (strpos($field, '.') !== FALSE) ? $this->config['table_prefix'].$field : $field;
535 $this->where[] = $this->driver->notlike($field, $match, $auto, 'OR ', count($this->where));
538 return $this;
542 * Selects the like(s) for a database query.
544 * @param string|array field name or array of field => match pairs
545 * @param string like value to match with field
546 * @return Database This Database object.
548 public function regex($field, $match = '')
550 $fields = is_array($field) ? $field : array($field => $match);
552 foreach ($fields as $field => $match)
554 $field = (strpos($field, '.') !== FALSE) ? $this->config['table_prefix'].$field : $field;
555 $this->where[] = $this->driver->regex($field, $match, 'AND ', count($this->where));
558 return $this;
562 * Selects the or like(s) for a database query.
564 * @param string|array field name or array of field => match pairs
565 * @param string like value to match with field
566 * @return Database This Database object.
568 public function orregex($field, $match = '')
570 $fields = is_array($field) ? $field : array($field => $match);
572 foreach ($fields as $field => $match)
574 $field = (strpos($field, '.') !== FALSE) ? $this->config['table_prefix'].$field : $field;
575 $this->where[] = $this->driver->regex($field, $match, 'OR ', count($this->where));
578 return $this;
582 * Selects the not regex(s) for a database query.
584 * @param string|array field name or array of field => match pairs
585 * @param string regex value to match with field
586 * @return Database This Database object.
588 public function notregex($field, $match = '')
590 $fields = is_array($field) ? $field : array($field => $match);
592 foreach ($fields as $field => $match)
594 $field = (strpos($field, '.') !== FALSE) ? $this->config['table_prefix'].$field : $field;
595 $this->where[] = $this->driver->notregex($field, $match, 'AND ', count($this->where));
598 return $this;
602 * Selects the or not regex(s) for a database query.
604 * @param string|array field name or array of field => match pairs
605 * @param string regex value to match with field
606 * @return Database This Database object.
608 public function ornotregex($field, $match = '')
610 $fields = is_array($field) ? $field : array($field => $match);
612 foreach ($fields as $field => $match)
614 $field = (strpos($field, '.') !== FALSE) ? $this->config['table_prefix'].$field : $field;
615 $this->where[] = $this->driver->notregex($field, $match, 'OR ', count($this->where));
618 return $this;
622 * Chooses the column to group by in a select query.
624 * @param string column name to group by
625 * @return Database This Database object.
627 public function groupby($by)
629 if ( ! is_array($by))
631 $by = explode(',', (string) $by);
634 foreach ($by as $val)
636 $val = trim($val);
638 if ($val != '')
640 // Add the table prefix if we are using table.column names
641 if(strpos($val, '.'))
643 $val = $this->config['table_prefix'].$val;
646 $this->groupby[] = $this->driver->escape_column($val);
650 return $this;
654 * Selects the having(s) for a database query.
656 * @param string|array key name or array of key => value pairs
657 * @param string value to match with key
658 * @param boolean disable quoting of WHERE clause
659 * @return Database This Database object.
661 public function having($key, $value = '', $quote = TRUE)
663 $this->having[] = $this->driver->where($key, $value, 'AND', count($this->having), TRUE);
664 return $this;
668 * Selects the or having(s) for a database query.
670 * @param string|array key name or array of key => value pairs
671 * @param string value to match with key
672 * @param boolean disable quoting of WHERE clause
673 * @return Database This Database object.
675 public function orhaving($key, $value = '', $quote = TRUE)
677 $this->having[] = $this->driver->where($key, $value, 'OR', count($this->having), TRUE);
678 return $this;
682 * Chooses which column(s) to order the select query by.
684 * @param string|array column(s) to order on, can be an array, single column, or comma seperated list of columns
685 * @param string direction of the order
686 * @return Database This Database object.
688 public function orderby($orderby, $direction = NULL)
690 if ( ! is_array($orderby))
692 $orderby = array($orderby => $direction);
695 foreach ($orderby as $column => $direction)
697 $direction = strtoupper(trim($direction));
699 // Add a direction if the provided one isn't valid
700 if ( ! in_array($direction, array('ASC', 'DESC', 'RAND()', 'RANDOM()', 'NULL')))
702 $direction = 'ASC';
705 // Add the table prefix if a table.column was passed
706 if (strpos($column, '.'))
708 $column = $this->config['table_prefix'].$column;
711 $this->orderby[] = $this->driver->escape_column($column).' '.$direction;
714 return $this;
718 * Selects the limit section of a query.
720 * @param integer number of rows to limit result to
721 * @param integer offset in result to start returning rows from
722 * @return Database This Database object.
724 public function limit($limit, $offset = NULL)
726 $this->limit = (int) $limit;
728 if ($offset !== NULL OR ! is_int($this->offset))
730 $this->offset($offset);
733 return $this;
737 * Sets the offset portion of a query.
739 * @param integer offset value
740 * @return Database This Database object.
742 public function offset($value)
744 $this->offset = (int) $value;
746 return $this;
750 * Allows key/value pairs to be set for inserting or updating.
752 * @param string|array key name or array of key => value pairs
753 * @param string value to match with key
754 * @return Database This Database object.
756 public function set($key, $value = '')
758 if ( ! is_array($key))
760 $key = array($key => $value);
763 foreach ($key as $k => $v)
765 // Add a table prefix if the column includes the table.
766 if (strpos($k, '.'))
767 $k = $this->config['table_prefix'].$k;
769 $this->set[$k] = $this->driver->escape($v);
772 return $this;
776 * Compiles the select statement based on the other functions called and runs the query.
778 * @param string table name
779 * @param string limit clause
780 * @param string offset clause
781 * @return Database_Result
783 public function get($table = '', $limit = NULL, $offset = NULL)
785 if ($table != '')
787 $this->from($table);
790 if ( ! is_null($limit))
792 $this->limit($limit, $offset);
795 $sql = $this->driver->compile_select(get_object_vars($this));
797 $this->reset_select();
799 $result = $this->query($sql);
801 $this->last_query = $sql;
803 return $result;
807 * Compiles the select statement based on the other functions called and runs the query.
809 * @param string table name
810 * @param array where clause
811 * @param string limit clause
812 * @param string offset clause
813 * @return Database This Database object.
815 public function getwhere($table = '', $where = NULL, $limit = NULL, $offset = NULL)
817 if ($table != '')
819 $this->from($table);
822 if ( ! is_null($where))
824 $this->where($where);
827 if ( ! is_null($limit))
829 $this->limit($limit, $offset);
832 $sql = $this->driver->compile_select(get_object_vars($this));
834 $this->reset_select();
836 $result = $this->query($sql);
838 return $result;
842 * Compiles the select statement based on the other functions called and returns the query string.
844 * @param string table name
845 * @param string limit clause
846 * @param string offset clause
847 * @return string sql string
849 public function compile($table = '', $limit = NULL, $offset = NULL)
851 if ($table != '')
853 $this->from($table);
856 if ( ! is_null($limit))
858 $this->limit($limit, $offset);
861 $sql = $this->driver->compile_select(get_object_vars($this));
863 $this->reset_select();
865 return $sql;
869 * Compiles an insert string and runs the query.
871 * @param string table name
872 * @param array array of key/value pairs to insert
873 * @return Database_Result Query result
875 public function insert($table = '', $set = NULL)
877 if ( ! is_null($set))
879 $this->set($set);
882 if ($this->set == NULL)
883 throw new Kohana_Database_Exception('database.must_use_set');
885 if ($table == '')
887 if ( ! isset($this->from[0]))
888 throw new Kohana_Database_Exception('database.must_use_table');
890 $table = $this->from[0];
893 // If caching is enabled, clear the cache before inserting
894 ($this->config['cache'] === TRUE) and $this->clear_cache();
896 $sql = $this->driver->insert($this->config['table_prefix'].$table, array_keys($this->set), array_values($this->set));
898 $this->reset_write();
900 return $this->query($sql);
904 * Adds an "IN" condition to the where clause
906 * @param string Name of the column being examined
907 * @param mixed An array or string to match against
908 * @param bool Generate a NOT IN clause instead
909 * @return Database This Database object.
911 public function in($field, $values, $not = FALSE)
913 if (is_array($values))
915 $escaped_values = array();
916 foreach ($values as $v)
918 if (is_numeric($v))
920 $escaped_values[] = $v;
922 else
924 $escaped_values[] = "'".$this->driver->escape_str($v)."'";
927 $values = implode(",", $escaped_values);
930 $where = $this->driver->escape_column(((strpos($field,'.') !== FALSE) ? $this->config['table_prefix'] : ''). $field).' '.($not === TRUE ? 'NOT ' : '').'IN ('.$values.')';
931 $this->where[] = $this->driver->where($where, '', 'AND ', count($this->where), -1);
933 return $this;
937 * Adds a "NOT IN" condition to the where clause
939 * @param string Name of the column being examined
940 * @param mixed An array or string to match against
941 * @return Database This Database object.
943 public function notin($field, $values)
945 return $this->in($field, $values, TRUE);
949 * Compiles a merge string and runs the query.
951 * @param string table name
952 * @param array array of key/value pairs to merge
953 * @return Database_Result Query result
955 public function merge($table = '', $set = NULL)
957 if ( ! is_null($set))
959 $this->set($set);
962 if ($this->set == NULL)
963 throw new Kohana_Database_Exception('database.must_use_set');
965 if ($table == '')
967 if ( ! isset($this->from[0]))
968 throw new Kohana_Database_Exception('database.must_use_table');
970 $table = $this->from[0];
973 $sql = $this->driver->merge($this->config['table_prefix'].$table, array_keys($this->set), array_values($this->set));
975 $this->reset_write();
976 return $this->query($sql);
980 * Compiles an update string and runs the query.
982 * @param string table name
983 * @param array associative array of update values
984 * @param array where clause
985 * @return Database_Result Query result
987 public function update($table = '', $set = NULL, $where = NULL)
989 if ( is_array($set))
991 $this->set($set);
994 if ( ! is_null($where))
996 $this->where($where);
999 if ($this->set == FALSE)
1000 throw new Kohana_Database_Exception('database.must_use_set');
1002 if ($table == '')
1004 if ( ! isset($this->from[0]))
1005 throw new Kohana_Database_Exception('database.must_use_table');
1007 $table = $this->from[0];
1010 $sql = $this->driver->update($this->config['table_prefix'].$table, $this->set, $this->where);
1012 $this->reset_write();
1013 return $this->query($sql);
1017 * Compiles a delete string and runs the query.
1019 * @param string table name
1020 * @param array where clause
1021 * @return Database_Result Query result
1023 public function delete($table = '', $where = NULL)
1025 if ($table == '')
1027 if ( ! isset($this->from[0]))
1028 throw new Kohana_Database_Exception('database.must_use_table');
1030 $table = $this->from[0];
1032 else
1034 $table = $this->config['table_prefix'].$table;
1037 if (! is_null($where))
1039 $this->where($where);
1042 if (count($this->where) < 1)
1043 throw new Kohana_Database_Exception('database.must_use_where');
1045 $sql = $this->driver->delete($table, $this->where);
1047 $this->reset_write();
1048 return $this->query($sql);
1052 * Returns the last query run.
1054 * @return string SQL
1056 public function last_query()
1058 return $this->last_query;
1062 * Count query records.
1064 * @param string table name
1065 * @param array where clause
1066 * @return integer
1068 public function count_records($table = FALSE, $where = NULL)
1070 if (count($this->from) < 1)
1072 if ($table == FALSE)
1073 throw new Kohana_Database_Exception('database.must_use_table');
1075 $this->from($table);
1078 if ($where !== NULL)
1080 $this->where($where);
1083 $query = $this->select('COUNT(*) AS '.$this->escape_column('records_found'))->get()->result(TRUE);
1085 return (int) $query->current()->records_found;
1089 * Resets all private select variables.
1091 * @return void
1093 protected function reset_select()
1095 $this->select = array();
1096 $this->from = array();
1097 $this->join = array();
1098 $this->where = array();
1099 $this->orderby = array();
1100 $this->groupby = array();
1101 $this->having = array();
1102 $this->distinct = FALSE;
1103 $this->limit = FALSE;
1104 $this->offset = FALSE;
1108 * Resets all private insert and update variables.
1110 * @return void
1112 protected function reset_write()
1114 $this->set = array();
1115 $this->from = array();
1116 $this->where = array();
1120 * Lists all the tables in the current database.
1122 * @return array
1124 public function list_tables()
1126 $this->link or $this->connect();
1128 return $this->driver->list_tables($this);
1132 * See if a table exists in the database.
1134 * @param string table name
1135 * @return boolean
1137 public function table_exists($table_name)
1139 return in_array($this->config['table_prefix'].$table_name, $this->list_tables());
1143 * Combine a SQL statement with the bind values. Used for safe queries.
1145 * @param string query to bind to the values
1146 * @param array array of values to bind to the query
1147 * @return string
1149 public function compile_binds($sql, $binds)
1151 foreach ((array) $binds as $val)
1153 // If the SQL contains no more bind marks ("?"), we're done.
1154 if (($next_bind_pos = strpos($sql, '?')) === FALSE)
1155 break;
1157 // Properly escape the bind value.
1158 $val = $this->driver->escape($val);
1160 // Temporarily replace possible bind marks ("?"), in the bind value itself, with a placeholder.
1161 $val = str_replace('?', '{%B%}', $val);
1163 // Replace the first bind mark ("?") with its corresponding value.
1164 $sql = substr($sql, 0, $next_bind_pos).$val.substr($sql, $next_bind_pos + 1);
1167 // Restore placeholders.
1168 return str_replace('{%B%}', '?', $sql);
1172 * Get the field data for a database table, along with the field's attributes.
1174 * @param string table name
1175 * @return array
1177 public function field_data($table = '')
1179 $this->link or $this->connect();
1181 return $this->driver->field_data($this->config['table_prefix'].$table);
1185 * Get the field data for a database table, along with the field's attributes.
1187 * @param string table name
1188 * @return array
1190 public function list_fields($table = '')
1192 $this->link or $this->connect();
1194 return $this->driver->list_fields($this->config['table_prefix'].$table);
1198 * Escapes a value for a query.
1200 * @param mixed value to escape
1201 * @return string
1203 public function escape($value)
1205 return $this->driver->escape($value);
1209 * Escapes a string for a query.
1211 * @param string string to escape
1212 * @return string
1214 public function escape_str($str)
1216 return $this->driver->escape_str($str);
1220 * Escapes a table name for a query.
1222 * @param string string to escape
1223 * @return string
1225 public function escape_table($table)
1227 return $this->driver->escape_table($table);
1231 * Escapes a column name for a query.
1233 * @param string string to escape
1234 * @return string
1236 public function escape_column($table)
1238 return $this->driver->escape_column($table);
1242 * Returns table prefix of current configuration.
1244 * @return string
1246 public function table_prefix()
1248 return $this->config['table_prefix'];
1252 * Clears the query cache.
1254 * @param string|TRUE clear cache by SQL statement or TRUE for last query
1255 * @return Database This Database object.
1257 public function clear_cache($sql = NULL)
1259 if ($sql === TRUE)
1261 $this->driver->clear_cache($this->last_query);
1263 elseif (is_string($sql))
1265 $this->driver->clear_cache($sql);
1267 else
1269 $this->driver->clear_cache();
1272 return $this;
1276 * Create a prepared statement (experimental).
1278 * @param string SQL query
1279 * @return object
1281 public function stmt_prepare($sql)
1283 return $this->driver->stmt_prepare($sql, $this->config);
1287 * Pushes existing query space onto the query stack. Use push
1288 * and pop to prevent queries from clashing before they are
1289 * executed
1291 * @return Database This Databaes object
1293 public function push()
1295 array_push($this->query_history, array(
1296 $this->select,
1297 $this->from,
1298 $this->join,
1299 $this->where,
1300 $this->orderby,
1301 $this->order,
1302 $this->groupby,
1303 $this->having,
1304 $this->distinct,
1305 $this->limit,
1306 $this->offset
1309 $this->reset_select();
1311 return $this;
1315 * Pops from query stack into the current query space.
1317 * @return Database This Databaes object
1319 public function pop()
1321 if (count($this->query_history) == 0)
1323 // No history
1324 return $this;
1327 list(
1328 $this->select,
1329 $this->from,
1330 $this->join,
1331 $this->where,
1332 $this->orderby,
1333 $this->order,
1334 $this->groupby,
1335 $this->having,
1336 $this->distinct,
1337 $this->limit,
1338 $this->offset
1339 ) = array_pop($this->query_history);
1341 return $this;
1345 } // End Database Class
1349 * Sets the code for a Database exception.
1351 class Kohana_Database_Exception extends Kohana_Exception {
1353 protected $code = E_DATABASE_ERROR;
1355 } // End Kohana Database Exception