1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5 * An open source application development framework for PHP 5.1.6 or newer
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
10 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
16 // ------------------------------------------------------------------------
21 * This is the platform-independent base Active Record implementation class.
23 * @package CodeIgniter
26 * @author ExpressionEngine Dev Team
27 * @link http://codeigniter.com/user_guide/database/
29 class CI_DB_active_record extends CI_DB_driver {
31 var $ar_select = array();
32 var $ar_distinct = FALSE;
33 var $ar_from = array();
34 var $ar_join = array();
35 var $ar_where = array();
36 var $ar_like = array();
37 var $ar_groupby = array();
38 var $ar_having = array();
39 var $ar_keys = array();
40 var $ar_limit = FALSE;
41 var $ar_offset = FALSE;
42 var $ar_order = FALSE;
43 var $ar_orderby = array();
44 var $ar_set = array();
45 var $ar_wherein = array();
46 var $ar_aliased_tables = array();
47 var $ar_store_array = array();
49 // Active Record Caching variables
50 var $ar_caching = FALSE;
51 var $ar_cache_exists = array();
52 var $ar_cache_select = array();
53 var $ar_cache_from = array();
54 var $ar_cache_join = array();
55 var $ar_cache_where = array();
56 var $ar_cache_like = array();
57 var $ar_cache_groupby = array();
58 var $ar_cache_having = array();
59 var $ar_cache_orderby = array();
60 var $ar_cache_set = array();
63 // --------------------------------------------------------------------
68 * Generates the SELECT portion of the query
74 function select($select = '*', $escape = NULL)
76 // Set the global value if this was sepecified
79 $this->_protect_identifiers = $escape;
82 if (is_string($select))
84 $select = explode(',', $select);
87 foreach ($select as $val)
93 $this->ar_select[] = $val;
95 if ($this->ar_caching === TRUE)
97 $this->ar_cache_select[] = $val;
98 $this->ar_cache_exists[] = 'select';
105 // --------------------------------------------------------------------
110 * Generates a SELECT MAX(field) portion of a query
113 * @param string the field
114 * @param string an alias
117 function select_max($select = '', $alias = '')
119 return $this->_max_min_avg_sum($select, $alias, 'MAX');
122 // --------------------------------------------------------------------
127 * Generates a SELECT MIN(field) portion of a query
130 * @param string the field
131 * @param string an alias
134 function select_min($select = '', $alias = '')
136 return $this->_max_min_avg_sum($select, $alias, 'MIN');
139 // --------------------------------------------------------------------
144 * Generates a SELECT AVG(field) portion of a query
147 * @param string the field
148 * @param string an alias
151 function select_avg($select = '', $alias = '')
153 return $this->_max_min_avg_sum($select, $alias, 'AVG');
156 // --------------------------------------------------------------------
161 * Generates a SELECT SUM(field) portion of a query
164 * @param string the field
165 * @param string an alias
168 function select_sum($select = '', $alias = '')
170 return $this->_max_min_avg_sum($select, $alias, 'SUM');
173 // --------------------------------------------------------------------
176 * Processing Function for the four functions above:
184 * @param string the field
185 * @param string an alias
188 function _max_min_avg_sum($select = '', $alias = '', $type = 'MAX')
190 if ( ! is_string($select) OR $select == '')
192 $this->display_error('db_invalid_query');
195 $type = strtoupper($type);
197 if ( ! in_array($type, array('MAX', 'MIN', 'AVG', 'SUM')))
199 show_error('Invalid function type: '.$type);
204 $alias = $this->_create_alias_from_table(trim($select));
207 $sql = $type.'('.$this->_protect_identifiers(trim($select)).') AS '.$alias;
209 $this->ar_select[] = $sql;
211 if ($this->ar_caching === TRUE)
213 $this->ar_cache_select[] = $sql;
214 $this->ar_cache_exists[] = 'select';
220 // --------------------------------------------------------------------
223 * Determines the alias name based on the table
229 function _create_alias_from_table($item)
231 if (strpos($item, '.') !== FALSE)
233 return end(explode('.', $item));
239 // --------------------------------------------------------------------
244 * Sets a flag which tells the query string compiler to add DISTINCT
250 function distinct($val = TRUE)
252 $this->ar_distinct = (is_bool($val)) ? $val : TRUE;
256 // --------------------------------------------------------------------
261 * Generates the FROM portion of the query
264 * @param mixed can be a string or array
269 foreach ((array)$from as $val)
271 if (strpos($val, ',') !== FALSE)
273 foreach (explode(',', $val) as $v)
276 $this->_track_aliases($v);
278 $this->ar_from[] = $this->_protect_identifiers($v, TRUE, NULL, FALSE);
280 if ($this->ar_caching === TRUE)
282 $this->ar_cache_from[] = $this->_protect_identifiers($v, TRUE, NULL, FALSE);
283 $this->ar_cache_exists[] = 'from';
292 // Extract any aliases that might exist. We use this information
293 // in the _protect_identifiers to know whether to add a table prefix
294 $this->_track_aliases($val);
296 $this->ar_from[] = $this->_protect_identifiers($val, TRUE, NULL, FALSE);
298 if ($this->ar_caching === TRUE)
300 $this->ar_cache_from[] = $this->_protect_identifiers($val, TRUE, NULL, FALSE);
301 $this->ar_cache_exists[] = 'from';
309 // --------------------------------------------------------------------
314 * Generates the JOIN portion of the query
318 * @param string the join condition
319 * @param string the type of join
322 function join($table, $cond, $type = '')
326 $type = strtoupper(trim($type));
328 if ( ! in_array($type, array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER')))
338 // Extract any aliases that might exist. We use this information
339 // in the _protect_identifiers to know whether to add a table prefix
340 $this->_track_aliases($table);
342 // Strip apart the condition and protect the identifiers
343 if (preg_match('/([\w\.]+)([\W\s]+)(.+)/', $cond, $match))
345 $match[1] = $this->_protect_identifiers($match[1]);
346 $match[3] = $this->_protect_identifiers($match[3]);
348 $cond = $match[1].$match[2].$match[3];
351 // Assemble the JOIN statement
352 $join = $type.'JOIN '.$this->_protect_identifiers($table, TRUE, NULL, FALSE).' ON '.$cond;
354 $this->ar_join[] = $join;
355 if ($this->ar_caching === TRUE)
357 $this->ar_cache_join[] = $join;
358 $this->ar_cache_exists[] = 'join';
364 // --------------------------------------------------------------------
369 * Generates the WHERE portion of the query. Separates
370 * multiple calls with AND
377 function where($key, $value = NULL, $escape = TRUE)
379 return $this->_where($key, $value, 'AND ', $escape);
382 // --------------------------------------------------------------------
387 * Generates the WHERE portion of the query. Separates
388 * multiple calls with OR
395 function or_where($key, $value = NULL, $escape = TRUE)
397 return $this->_where($key, $value, 'OR ', $escape);
400 // --------------------------------------------------------------------
405 * Called by where() or orwhere()
413 function _where($key, $value = NULL, $type = 'AND ', $escape = NULL)
415 if ( ! is_array($key))
417 $key = array($key => $value);
420 // If the escape value was not set will will base it on the global setting
421 if ( ! is_bool($escape))
423 $escape = $this->_protect_identifiers;
426 foreach ($key as $k => $v)
428 $prefix = (count($this->ar_where) == 0 AND count($this->ar_cache_where) == 0) ? '' : $type;
430 if (is_null($v) && ! $this->_has_operator($k))
432 // value appears not to have been set, assign the test to IS NULL
438 if ($escape === TRUE)
440 $k = $this->_protect_identifiers($k, FALSE, $escape);
442 $v = ' '.$this->escape($v);
445 if ( ! $this->_has_operator($k))
452 $k = $this->_protect_identifiers($k, FALSE, $escape);
455 $this->ar_where[] = $prefix.$k.$v;
457 if ($this->ar_caching === TRUE)
459 $this->ar_cache_where[] = $prefix.$k.$v;
460 $this->ar_cache_exists[] = 'where';
468 // --------------------------------------------------------------------
473 * Generates a WHERE field IN ('item', 'item') SQL query joined with
477 * @param string The field to search
478 * @param array The values searched on
481 function where_in($key = NULL, $values = NULL)
483 return $this->_where_in($key, $values);
486 // --------------------------------------------------------------------
491 * Generates a WHERE field IN ('item', 'item') SQL query joined with
495 * @param string The field to search
496 * @param array The values searched on
499 function or_where_in($key = NULL, $values = NULL)
501 return $this->_where_in($key, $values, FALSE, 'OR ');
504 // --------------------------------------------------------------------
509 * Generates a WHERE field NOT IN ('item', 'item') SQL query joined
510 * with AND if appropriate
513 * @param string The field to search
514 * @param array The values searched on
517 function where_not_in($key = NULL, $values = NULL)
519 return $this->_where_in($key, $values, TRUE);
522 // --------------------------------------------------------------------
527 * Generates a WHERE field NOT IN ('item', 'item') SQL query joined
528 * with OR if appropriate
531 * @param string The field to search
532 * @param array The values searched on
535 function or_where_not_in($key = NULL, $values = NULL)
537 return $this->_where_in($key, $values, TRUE, 'OR ');
540 // --------------------------------------------------------------------
545 * Called by where_in, where_in_or, where_not_in, where_not_in_or
548 * @param string The field to search
549 * @param array The values searched on
550 * @param boolean If the statement would be IN or NOT IN
554 function _where_in($key = NULL, $values = NULL, $not = FALSE, $type = 'AND ')
556 if ($key === NULL OR $values === NULL)
561 if ( ! is_array($values))
563 $values = array($values);
566 $not = ($not) ? ' NOT' : '';
568 foreach ($values as $value)
570 $this->ar_wherein[] = $this->escape($value);
573 $prefix = (count($this->ar_where) == 0) ? '' : $type;
575 $where_in = $prefix . $this->_protect_identifiers($key) . $not . " IN (" . implode(", ", $this->ar_wherein) . ") ";
577 $this->ar_where[] = $where_in;
578 if ($this->ar_caching === TRUE)
580 $this->ar_cache_where[] = $where_in;
581 $this->ar_cache_exists[] = 'where';
584 // reset the array for multiple calls
585 $this->ar_wherein = array();
589 // --------------------------------------------------------------------
594 * Generates a %LIKE% portion of the query. Separates
595 * multiple calls with AND
602 function like($field, $match = '', $side = 'both')
604 return $this->_like($field, $match, 'AND ', $side);
607 // --------------------------------------------------------------------
612 * Generates a NOT LIKE portion of the query. Separates
613 * multiple calls with AND
620 function not_like($field, $match = '', $side = 'both')
622 return $this->_like($field, $match, 'AND ', $side, 'NOT');
625 // --------------------------------------------------------------------
630 * Generates a %LIKE% portion of the query. Separates
631 * multiple calls with OR
638 function or_like($field, $match = '', $side = 'both')
640 return $this->_like($field, $match, 'OR ', $side);
643 // --------------------------------------------------------------------
648 * Generates a NOT LIKE portion of the query. Separates
649 * multiple calls with OR
656 function or_not_like($field, $match = '', $side = 'both')
658 return $this->_like($field, $match, 'OR ', $side, 'NOT');
661 // --------------------------------------------------------------------
666 * Called by like() or orlike()
674 function _like($field, $match = '', $type = 'AND ', $side = 'both', $not = '')
676 if ( ! is_array($field))
678 $field = array($field => $match);
681 foreach ($field as $k => $v)
683 $k = $this->_protect_identifiers($k);
685 $prefix = (count($this->ar_like) == 0) ? '' : $type;
687 $v = $this->escape_like_str($v);
689 if ($side == 'before')
691 $like_statement = $prefix." $k $not LIKE '%{$v}'";
693 elseif ($side == 'after')
695 $like_statement = $prefix." $k $not LIKE '{$v}%'";
699 $like_statement = $prefix." $k $not LIKE '%{$v}%'";
702 // some platforms require an escape sequence definition for LIKE wildcards
703 if ($this->_like_escape_str != '')
705 $like_statement = $like_statement.sprintf($this->_like_escape_str, $this->_like_escape_chr);
708 $this->ar_like[] = $like_statement;
709 if ($this->ar_caching === TRUE)
711 $this->ar_cache_like[] = $like_statement;
712 $this->ar_cache_exists[] = 'like';
719 // --------------------------------------------------------------------
728 function group_by($by)
732 $by = explode(',', $by);
735 foreach ($by as $val)
741 $this->ar_groupby[] = $this->_protect_identifiers($val);
743 if ($this->ar_caching === TRUE)
745 $this->ar_cache_groupby[] = $this->_protect_identifiers($val);
746 $this->ar_cache_exists[] = 'groupby';
753 // --------------------------------------------------------------------
756 * Sets the HAVING value
758 * Separates multiple calls with AND
765 function having($key, $value = '', $escape = TRUE)
767 return $this->_having($key, $value, 'AND ', $escape);
770 // --------------------------------------------------------------------
773 * Sets the OR HAVING value
775 * Separates multiple calls with OR
782 function or_having($key, $value = '', $escape = TRUE)
784 return $this->_having($key, $value, 'OR ', $escape);
787 // --------------------------------------------------------------------
790 * Sets the HAVING values
792 * Called by having() or or_having()
799 function _having($key, $value = '', $type = 'AND ', $escape = TRUE)
801 if ( ! is_array($key))
803 $key = array($key => $value);
806 foreach ($key as $k => $v)
808 $prefix = (count($this->ar_having) == 0) ? '' : $type;
810 if ($escape === TRUE)
812 $k = $this->_protect_identifiers($k);
815 if ( ! $this->_has_operator($k))
822 $v = ' '.$this->escape_str($v);
825 $this->ar_having[] = $prefix.$k.$v;
826 if ($this->ar_caching === TRUE)
828 $this->ar_cache_having[] = $prefix.$k.$v;
829 $this->ar_cache_exists[] = 'having';
836 // --------------------------------------------------------------------
839 * Sets the ORDER BY value
843 * @param string direction: asc or desc
846 function order_by($orderby, $direction = '')
848 if (strtolower($direction) == 'random')
850 $orderby = ''; // Random results want or don't need a field name
851 $direction = $this->_random_keyword;
853 elseif (trim($direction) != '')
855 $direction = (in_array(strtoupper(trim($direction)), array('ASC', 'DESC'), TRUE)) ? ' '.$direction : ' ASC';
859 if (strpos($orderby, ',') !== FALSE)
862 foreach (explode(',', $orderby) as $part)
865 if ( ! in_array($part, $this->ar_aliased_tables))
867 $part = $this->_protect_identifiers(trim($part));
873 $orderby = implode(', ', $temp);
875 else if ($direction != $this->_random_keyword)
877 $orderby = $this->_protect_identifiers($orderby);
880 $orderby_statement = $orderby.$direction;
882 $this->ar_orderby[] = $orderby_statement;
883 if ($this->ar_caching === TRUE)
885 $this->ar_cache_orderby[] = $orderby_statement;
886 $this->ar_cache_exists[] = 'orderby';
892 // --------------------------------------------------------------------
895 * Sets the LIMIT value
898 * @param integer the limit value
899 * @param integer the offset value
902 function limit($value, $offset = '')
904 $this->ar_limit = $value;
908 $this->ar_offset = $offset;
914 // --------------------------------------------------------------------
917 * Sets the OFFSET value
920 * @param integer the offset value
923 function offset($offset)
925 $this->ar_offset = $offset;
929 // --------------------------------------------------------------------
932 * The "set" function. Allows key/value pairs to be set for inserting or updating
940 function set($key, $value = '', $escape = TRUE)
942 $key = $this->_object_to_array($key);
944 if ( ! is_array($key))
946 $key = array($key => $value);
949 foreach ($key as $k => $v)
951 if ($escape === FALSE)
953 $this->ar_set[$this->_protect_identifiers($k)] = $v;
957 $this->ar_set[$this->_protect_identifiers($k, FALSE, TRUE)] = $this->escape($v);
964 // --------------------------------------------------------------------
969 * Compiles the select statement based on the other functions called
973 * @param string the table
974 * @param string the limit clause
975 * @param string the offset clause
978 function get($table = '', $limit = null, $offset = null)
982 $this->_track_aliases($table);
986 if ( ! is_null($limit))
988 $this->limit($limit, $offset);
991 $sql = $this->_compile_select();
993 $result = $this->query($sql);
994 $this->_reset_select();
999 * "Count All Results" query
1001 * Generates a platform-specific query string that counts all records
1002 * returned by an Active Record query.
1008 function count_all_results($table = '')
1012 $this->_track_aliases($table);
1013 $this->from($table);
1016 $sql = $this->_compile_select($this->_count_string . $this->_protect_identifiers('numrows'));
1018 $query = $this->query($sql);
1019 $this->_reset_select();
1021 if ($query->num_rows() == 0)
1026 $row = $query->row();
1027 return (int) $row->numrows;
1030 // --------------------------------------------------------------------
1035 * Allows the where clause, limit and offset to be added directly
1038 * @param string the where clause
1039 * @param string the limit clause
1040 * @param string the offset clause
1043 function get_where($table = '', $where = null, $limit = null, $offset = null)
1047 $this->from($table);
1050 if ( ! is_null($where))
1052 $this->where($where);
1055 if ( ! is_null($limit))
1057 $this->limit($limit, $offset);
1060 $sql = $this->_compile_select();
1062 $result = $this->query($sql);
1063 $this->_reset_select();
1067 // --------------------------------------------------------------------
1072 * Compiles batch insert strings and runs the queries
1075 * @param string the table to retrieve the results from
1076 * @param array an associative array of insert values
1079 function insert_batch($table = '', $set = NULL)
1081 if ( ! is_null($set))
1083 $this->set_insert_batch($set);
1086 if (count($this->ar_set) == 0)
1088 if ($this->db_debug)
1090 //No valid data array. Folds in cases where keys and values did not match up
1091 return $this->display_error('db_must_use_set');
1098 if ( ! isset($this->ar_from[0]))
1100 if ($this->db_debug)
1102 return $this->display_error('db_must_set_table');
1107 $table = $this->ar_from[0];
1111 for ($i = 0, $total = count($this->ar_set); $i < $total; $i = $i + 100)
1114 $sql = $this->_insert_batch($this->_protect_identifiers($table, TRUE, NULL, FALSE), $this->ar_keys, array_slice($this->ar_set, $i, 100));
1121 $this->_reset_write();
1127 // --------------------------------------------------------------------
1130 * The "set_insert_batch" function. Allows key/value pairs to be set for batch inserts
1139 function set_insert_batch($key, $value = '', $escape = TRUE)
1141 $key = $this->_object_to_array_batch($key);
1143 if ( ! is_array($key))
1145 $key = array($key => $value);
1148 $keys = array_keys(current($key));
1151 foreach ($key as $row)
1153 if (count(array_diff($keys, array_keys($row))) > 0 OR count(array_diff(array_keys($row), $keys)) > 0)
1155 // batch function above returns an error on an empty array
1156 $this->ar_set[] = array();
1160 ksort($row); // puts $row in the same order as our keys
1162 if ($escape === FALSE)
1164 $this->ar_set[] = '('.implode(',', $row).')';
1170 foreach ($row as $value)
1172 $clean[] = $this->escape($value);
1175 $this->ar_set[] = '('.implode(',', $clean).')';
1179 foreach ($keys as $k)
1181 $this->ar_keys[] = $this->_protect_identifiers($k);
1187 // --------------------------------------------------------------------
1192 * Compiles an insert string and runs the query
1195 * @param string the table to retrieve the results from
1196 * @param array an associative array of insert values
1199 function insert($table = '', $set = NULL)
1201 if ( ! is_null($set))
1206 if (count($this->ar_set) == 0)
1208 if ($this->db_debug)
1210 return $this->display_error('db_must_use_set');
1217 if ( ! isset($this->ar_from[0]))
1219 if ($this->db_debug)
1221 return $this->display_error('db_must_set_table');
1226 $table = $this->ar_from[0];
1229 $sql = $this->_insert($this->_protect_identifiers($table, TRUE, NULL, FALSE), array_keys($this->ar_set), array_values($this->ar_set));
1231 $this->_reset_write();
1232 return $this->query($sql);
1235 function replace($table = '', $set = NULL)
1237 if ( ! is_null($set))
1242 if (count($this->ar_set) == 0)
1244 if ($this->db_debug)
1246 return $this->display_error('db_must_use_set');
1253 if ( ! isset($this->ar_from[0]))
1255 if ($this->db_debug)
1257 return $this->display_error('db_must_set_table');
1262 $table = $this->ar_from[0];
1265 $sql = $this->_replace($this->_protect_identifiers($table, TRUE, NULL, FALSE), array_keys($this->ar_set), array_values($this->ar_set));
1267 $this->_reset_write();
1268 return $this->query($sql);
1271 // --------------------------------------------------------------------
1276 * Compiles an update string and runs the query
1279 * @param string the table to retrieve the results from
1280 * @param array an associative array of update values
1281 * @param mixed the where clause
1284 function update($table = '', $set = NULL, $where = NULL, $limit = NULL)
1286 // Combine any cached components with the current statements
1287 $this->_merge_cache();
1289 if ( ! is_null($set))
1294 if (count($this->ar_set) == 0)
1296 if ($this->db_debug)
1298 return $this->display_error('db_must_use_set');
1305 if ( ! isset($this->ar_from[0]))
1307 if ($this->db_debug)
1309 return $this->display_error('db_must_set_table');
1314 $table = $this->ar_from[0];
1319 $this->where($where);
1324 $this->limit($limit);
1327 $sql = $this->_update($this->_protect_identifiers($table, TRUE, NULL, FALSE), $this->ar_set, $this->ar_where, $this->ar_orderby, $this->ar_limit);
1329 $this->_reset_write();
1330 return $this->query($sql);
1334 // --------------------------------------------------------------------
1339 * Compiles an update string and runs the query
1342 * @param string the table to retrieve the results from
1343 * @param array an associative array of update values
1344 * @param string the where key
1347 function update_batch($table = '', $set = NULL, $index = NULL)
1349 // Combine any cached components with the current statements
1350 $this->_merge_cache();
1352 if (is_null($index))
1354 if ($this->db_debug)
1356 return $this->display_error('db_myst_use_index');
1362 if ( ! is_null($set))
1364 $this->set_update_batch($set, $index);
1367 if (count($this->ar_set) == 0)
1369 if ($this->db_debug)
1371 return $this->display_error('db_must_use_set');
1379 if ( ! isset($this->ar_from[0]))
1381 if ($this->db_debug)
1383 return $this->display_error('db_must_set_table');
1388 $table = $this->ar_from[0];
1392 for ($i = 0, $total = count($this->ar_set); $i < $total; $i = $i + 100)
1394 $sql = $this->_update_batch($this->_protect_identifiers($table, TRUE, NULL, FALSE), array_slice($this->ar_set, $i, 100), $this->_protect_identifiers($index), $this->ar_where);
1399 $this->_reset_write();
1402 // --------------------------------------------------------------------
1405 * The "set_update_batch" function. Allows key/value pairs to be set for batch updating
1414 function set_update_batch($key, $index = '', $escape = TRUE)
1416 $key = $this->_object_to_array_batch($key);
1418 if ( ! is_array($key))
1423 foreach ($key as $k => $v)
1428 foreach ($v as $k2 => $v2)
1439 if ($escape === FALSE)
1441 $clean[$this->_protect_identifiers($k2)] = $v2;
1445 $clean[$this->_protect_identifiers($k2)] = $this->escape($v2);
1449 if ($index_set == FALSE)
1451 return $this->display_error('db_batch_missing_index');
1454 $this->ar_set[] = $clean;
1460 // --------------------------------------------------------------------
1465 * Compiles a delete string and runs "DELETE FROM table"
1468 * @param string the table to empty
1471 function empty_table($table = '')
1475 if ( ! isset($this->ar_from[0]))
1477 if ($this->db_debug)
1479 return $this->display_error('db_must_set_table');
1484 $table = $this->ar_from[0];
1488 $table = $this->_protect_identifiers($table, TRUE, NULL, FALSE);
1491 $sql = $this->_delete($table);
1493 $this->_reset_write();
1495 return $this->query($sql);
1498 // --------------------------------------------------------------------
1503 * Compiles a truncate string and runs the query
1504 * If the database does not support the truncate() command
1505 * This function maps to "DELETE FROM table"
1508 * @param string the table to truncate
1511 function truncate($table = '')
1515 if ( ! isset($this->ar_from[0]))
1517 if ($this->db_debug)
1519 return $this->display_error('db_must_set_table');
1524 $table = $this->ar_from[0];
1528 $table = $this->_protect_identifiers($table, TRUE, NULL, FALSE);
1531 $sql = $this->_truncate($table);
1533 $this->_reset_write();
1535 return $this->query($sql);
1538 // --------------------------------------------------------------------
1543 * Compiles a delete string and runs the query
1546 * @param mixed the table(s) to delete from. String or array
1547 * @param mixed the where clause
1548 * @param mixed the limit clause
1552 function delete($table = '', $where = '', $limit = NULL, $reset_data = TRUE)
1554 // Combine any cached components with the current statements
1555 $this->_merge_cache();
1559 if ( ! isset($this->ar_from[0]))
1561 if ($this->db_debug)
1563 return $this->display_error('db_must_set_table');
1568 $table = $this->ar_from[0];
1570 elseif (is_array($table))
1572 foreach ($table as $single_table)
1574 $this->delete($single_table, $where, $limit, FALSE);
1577 $this->_reset_write();
1582 $table = $this->_protect_identifiers($table, TRUE, NULL, FALSE);
1587 $this->where($where);
1592 $this->limit($limit);
1595 if (count($this->ar_where) == 0 && count($this->ar_wherein) == 0 && count($this->ar_like) == 0)
1597 if ($this->db_debug)
1599 return $this->display_error('db_del_must_use_where');
1605 $sql = $this->_delete($table, $this->ar_where, $this->ar_like, $this->ar_limit);
1609 $this->_reset_write();
1612 return $this->query($sql);
1615 // --------------------------------------------------------------------
1620 * Prepends a database prefix if one exists in configuration
1623 * @param string the table
1626 function dbprefix($table = '')
1630 $this->display_error('db_table_name_required');
1633 return $this->dbprefix.$table;
1636 // --------------------------------------------------------------------
1641 * Used to track SQL statements written with aliased tables.
1644 * @param string The table to inspect
1647 function _track_aliases($table)
1649 if (is_array($table))
1651 foreach ($table as $t)
1653 $this->_track_aliases($t);
1658 // Does the string contain a comma? If so, we need to separate
1659 // the string into discreet statements
1660 if (strpos($table, ',') !== FALSE)
1662 return $this->_track_aliases(explode(',', $table));
1665 // if a table alias is used we can recognize it by a space
1666 if (strpos($table, " ") !== FALSE)
1668 // if the alias is written with the AS keyword, remove it
1669 $table = preg_replace('/ AS /i', ' ', $table);
1672 $table = trim(strrchr($table, " "));
1674 // Store the alias, if it doesn't already exist
1675 if ( ! in_array($table, $this->ar_aliased_tables))
1677 $this->ar_aliased_tables[] = $table;
1682 // --------------------------------------------------------------------
1685 * Compile the SELECT statement
1687 * Generates a query string based on which functions were used.
1688 * Should not be called directly. The get() function calls it.
1693 function _compile_select($select_override = FALSE)
1695 // Combine any cached components with the current statements
1696 $this->_merge_cache();
1698 // ----------------------------------------------------------------
1700 // Write the "select" portion of the query
1702 if ($select_override !== FALSE)
1704 $sql = $select_override;
1708 $sql = ( ! $this->ar_distinct) ? 'SELECT ' : 'SELECT DISTINCT ';
1710 if (count($this->ar_select) == 0)
1716 // Cycle through the "select" portion of the query and prep each column name.
1717 // The reason we protect identifiers here rather then in the select() function
1718 // is because until the user calls the from() function we don't know if there are aliases
1719 foreach ($this->ar_select as $key => $val)
1721 $this->ar_select[$key] = $this->_protect_identifiers($val);
1724 $sql .= implode(', ', $this->ar_select);
1728 // ----------------------------------------------------------------
1730 // Write the "FROM" portion of the query
1732 if (count($this->ar_from) > 0)
1736 $sql .= $this->_from_tables($this->ar_from);
1739 // ----------------------------------------------------------------
1741 // Write the "JOIN" portion of the query
1743 if (count($this->ar_join) > 0)
1747 $sql .= implode("\n", $this->ar_join);
1750 // ----------------------------------------------------------------
1752 // Write the "WHERE" portion of the query
1754 if (count($this->ar_where) > 0 OR count($this->ar_like) > 0)
1761 $sql .= implode("\n", $this->ar_where);
1763 // ----------------------------------------------------------------
1765 // Write the "LIKE" portion of the query
1767 if (count($this->ar_like) > 0)
1769 if (count($this->ar_where) > 0)
1774 $sql .= implode("\n", $this->ar_like);
1777 // ----------------------------------------------------------------
1779 // Write the "GROUP BY" portion of the query
1781 if (count($this->ar_groupby) > 0)
1783 $sql .= "\nGROUP BY ";
1785 $sql .= implode(', ', $this->ar_groupby);
1788 // ----------------------------------------------------------------
1790 // Write the "HAVING" portion of the query
1792 if (count($this->ar_having) > 0)
1794 $sql .= "\nHAVING ";
1795 $sql .= implode("\n", $this->ar_having);
1798 // ----------------------------------------------------------------
1800 // Write the "ORDER BY" portion of the query
1802 if (count($this->ar_orderby) > 0)
1804 $sql .= "\nORDER BY ";
1805 $sql .= implode(', ', $this->ar_orderby);
1807 if ($this->ar_order !== FALSE)
1809 $sql .= ($this->ar_order == 'desc') ? ' DESC' : ' ASC';
1813 // ----------------------------------------------------------------
1815 // Write the "LIMIT" portion of the query
1817 if (is_numeric($this->ar_limit))
1820 $sql = $this->_limit($sql, $this->ar_limit, $this->ar_offset);
1826 // --------------------------------------------------------------------
1831 * Takes an object as input and converts the class variables to array key/vals
1837 function _object_to_array($object)
1839 if ( ! is_object($object))
1845 foreach (get_object_vars($object) as $key => $val)
1847 // There are some built in keys we need to ignore for this conversion
1848 if ( ! is_object($val) && ! is_array($val) && $key != '_parent_name')
1850 $array[$key] = $val;
1857 // --------------------------------------------------------------------
1862 * Takes an object as input and converts the class variables to array key/vals
1868 function _object_to_array_batch($object)
1870 if ( ! is_object($object))
1876 $out = get_object_vars($object);
1877 $fields = array_keys($out);
1879 foreach ($fields as $val)
1881 // There are some built in keys we need to ignore for this conversion
1882 if ($val != '_parent_name')
1886 foreach ($out[$val] as $data)
1888 $array[$i][$val] = $data;
1897 // --------------------------------------------------------------------
1907 function start_cache()
1909 $this->ar_caching = TRUE;
1912 // --------------------------------------------------------------------
1922 function stop_cache()
1924 $this->ar_caching = FALSE;
1927 // --------------------------------------------------------------------
1932 * Empties the AR cache
1937 function flush_cache()
1941 'ar_cache_select' => array(),
1942 'ar_cache_from' => array(),
1943 'ar_cache_join' => array(),
1944 'ar_cache_where' => array(),
1945 'ar_cache_like' => array(),
1946 'ar_cache_groupby' => array(),
1947 'ar_cache_having' => array(),
1948 'ar_cache_orderby' => array(),
1949 'ar_cache_set' => array(),
1950 'ar_cache_exists' => array()
1955 // --------------------------------------------------------------------
1960 * When called, this function merges any cached AR arrays with
1961 * locally called ones.
1966 function _merge_cache()
1968 if (count($this->ar_cache_exists) == 0)
1973 foreach ($this->ar_cache_exists as $val)
1975 $ar_variable = 'ar_'.$val;
1976 $ar_cache_var = 'ar_cache_'.$val;
1978 if (count($this->$ar_cache_var) == 0)
1983 $this->$ar_variable = array_unique(array_merge($this->$ar_cache_var, $this->$ar_variable));
1986 // If we are "protecting identifiers" we need to examine the "from"
1987 // portion of the query to determine if there are any aliases
1988 if ($this->_protect_identifiers === TRUE AND count($this->ar_cache_from) > 0)
1990 $this->_track_aliases($this->ar_from);
1994 // --------------------------------------------------------------------
1997 * Resets the active record values. Called by the get() function
2000 * @param array An array of fields to reset
2003 function _reset_run($ar_reset_items)
2005 foreach ($ar_reset_items as $item => $default_value)
2007 if ( ! in_array($item, $this->ar_store_array))
2009 $this->$item = $default_value;
2014 // --------------------------------------------------------------------
2017 * Resets the active record values. Called by the get() function
2022 function _reset_select()
2024 $ar_reset_items = array(
2025 'ar_select' => array(),
2026 'ar_from' => array(),
2027 'ar_join' => array(),
2028 'ar_where' => array(),
2029 'ar_like' => array(),
2030 'ar_groupby' => array(),
2031 'ar_having' => array(),
2032 'ar_orderby' => array(),
2033 'ar_wherein' => array(),
2034 'ar_aliased_tables' => array(),
2035 'ar_distinct' => FALSE,
2036 'ar_limit' => FALSE,
2037 'ar_offset' => FALSE,
2038 'ar_order' => FALSE,
2041 $this->_reset_run($ar_reset_items);
2044 // --------------------------------------------------------------------
2047 * Resets the active record "write" values.
2049 * Called by the insert() update() insert_batch() update_batch() and delete() functions
2054 function _reset_write()
2056 $ar_reset_items = array(
2057 'ar_set' => array(),
2058 'ar_from' => array(),
2059 'ar_where' => array(),
2060 'ar_like' => array(),
2061 'ar_orderby' => array(),
2062 'ar_keys' => array(),
2063 'ar_limit' => FALSE,
2067 $this->_reset_run($ar_reset_items);
2072 /* End of file DB_active_rec.php */
2073 /* Location: ./system/database/DB_active_rec.php */