31 private $_cacheRecords;
72 abstract function connect($database=
'', $host=
'', $user=
'', $password=
'');
100 if (func_num_args() == 4)
109 $this->
connect($args[0], $args[1], $args[2], $args[3]);
116 $this->
select($query, $cache);
123 return get_class($this).
'('.$this->currentQuery.
')';
143 function query($query, $appendCurrent =
false)
145 if ($appendCurrent) {
146 $this->currentQuery .= $query;
148 $this->currentQuery = $query;
150 $this->_currentRow = -1;
151 $this->_stmt = $this->_db->query($query);
152 if ($this->_stmt ===
false) {
154 throw new Ego_Sql_Exception(implode(
' ', $this->_db->errorInfo()), (
int) $this->_db->errorCode());
167 $this->Record = $this->_stmt?$this->_stmt->fetch(PDO::FETCH_ASSOC):
null;
168 if ($this->Record===
false) {
169 $this->Record =
null;
179 $this->_currentRow = -1;
180 $this->_stmt->closeCursor();
181 $this->_stmt->execute();
217 ++$this->_cacheIndex;
218 if (is_array($this->_cacheRecords) && $this->_cacheIndex<
sizeof($this->_cacheRecords))
220 return $this->Record = $this->_cacheRecords[$this->_cacheIndex];
234 return $this->_stmt?$this->_stmt->rowCount():0;
257 return $this->_cached?
sizeof($this->_cacheRecords):$this->
_numRecords();
262 if ($query[
'bitand']) {
263 if (empty($query[
'where'])) {
264 $query[
'where'] =
'1=1';
266 foreach ($query[
'bitand'] as $bit) {
267 $query[
'where'] .=
' AND '.$bit[0].
'&'.$bit[1].
'='.$bit[2];
270 return 'SELECT '.($query[
'no_cache']?
'SQL_NO_CACHE ':
'')
271 .($query[
'distinct']?
'DISTINCT ':
'')
272 .($query[
'fields']?:
'*').(isset($query[
'fields2'])&&!empty($query[
'fields2'])?
','.(is_array($query[
'fields2'])?implode(
',',$query[
'fields2']):$query[
'fields2']):
'')
273 .
' FROM ('.($query[
'table']?:$query[
'from'])
274 .($query[
'table2']?($query[
'table']?
',':
'').$query[
'table2']:
'').
')'
275 .($query[
'inner']?
' INNER JOIN '.(is_array($query[
'inner'])?
276 implode(
' INNER JOIN ', $query[
'inner']):$query[
'inner']):
'')
277 .($query[
'join']?
' LEFT JOIN '.(is_array($query[
'join'])?
278 implode(
' LEFT JOIN ', $query[
'join']):$query[
'join']):
'')
279 .($query[
'where']?
' WHERE '.$query[
'where']:
'')
280 .($query[
'group']?
' GROUP BY '.$query[
'group']:
'')
281 .($query[
'having']?
' HAVING '.$query[
'having']:
'')
282 .($query[
'order']?
' ORDER BY '.$query[
'order']:
'');
295 if ($query[
'field_as'])
297 foreach ($query[
'field_as'] as $k=>$v)
299 if ($query[
'field_as_bitand'][$k]) {
300 foreach ($query[
'field_as_bitand'][$k] as $bit) {
301 $v .=
' AND '.$bit[0].
'&'.$bit[1].
'='.$bit[2];
304 if ($query[
'field_as_limit'][$k]) {
305 $v .=
' LIMIT '.$query[
'field_as_limit'][$k];
307 $query[
'fields2'][] =
'('.$v.
') AS '.$k;
309 unset($query[
'field_as']);
311 if ($query[
'proposed_order'])
313 $query[
'order'] =
'FIELD('.$query[
'proposed_order'][
'field'].
','.implode(
',', $query[
'proposed_order'][
'values']).
')';
318 foreach ($query[
'union'] as $union)
320 $union = array_merge($query, $union);
321 $union[
'where'] = $query[
'where']?
'('.$query[
'where'].
') AND ('.$union[
'where'].
')':$union[
'where'];
322 $union[
'join'] = $query[
'join']?array_merge_recursive($query[
'join'], $union[
'join']):$union[
'join'];
323 $unions[] =
'('.$this->_selectString($union).
')';
325 $s = implode(
' UNION ', $unions).($query[
'order']?
' order by'.preg_replace(
'/([, ])[^, .]+?\./',
'$1',
' '.$query[
'order']):
'');
331 $limit = explode(
',', $query[
'limit']);
332 $s.=
' LIMIT '.$limit[0].(sizeof($limit)>1?
','.$limit[1]:
'');
336 $this->currentQuery = $s;
337 $this->currentBind = $query[
'bind'];
338 $this->_stmt = $this->_db->prepare($s);
339 if ($this->_stmt->execute($query[
'bind']) ===
false) {
341 throw new Ego_Sql_Exception(implode(
' ', $this->_stmt->errorInfo()), (
int) $this->_stmt->errorCode());
345 return $this->
query($s);
408 !(
bool)$query[
'limit'] || (
bool)$query[
'order'],
409 'You have to set an order to use limit! Otherwise databases like MS SQL don`t work.'.
410 print_r($query,
true));
412 if ($cache && $this->
_cacheInit($query, $cache))
416 $GLOBALS[
'stats'][
'db_select']++;
417 if ($GLOBALS[
'egotec_conf'][
'db'][
'log_select'])
419 $start = microtime(
true);
421 $return = $this->
_select($query);
422 if ($GLOBALS[
'egotec_conf'][
'db'][
'log_select'] || $query[
'log'])
424 $time = microtime(
true)-$start;
425 if ($time>$GLOBALS[
'egotec_conf'][
'db'][
'log_select_timeout'] || $query[
'log'])
427 $log =
'=== '.date(
'Y-m-d H:i:s').
' '.$_SERVER[
'REQUEST_URI'].
' '.$time.
"\n".$this->currentQuery.
"\n".print_r($query,
true);
428 if ($GLOBALS[
'egotec_conf'][
'db'][
'profiling'] || $query[
'profile'])
432 if ($GLOBALS[
'egotec_conf'][
'db'][
'log_select']==2)
434 $log.=
"\n".get_backtrace();
468 function delete($query)
470 assert($query[
'table']||$query[
'from']);
472 .($query[
'fields']?$query[
'fields'].
' ':
'')
474 .($query[
'table']?$query[
'table']:$query[
'from'])
475 .($query[
'inner']?
' INNER JOIN '.(is_array($query[
'inner'])?
476 implode(
' INNER JOIN ', $query[
'inner']):$query[
'inner']):
'')
477 .($query[
'join']?
' LEFT JOIN '.(is_array($query[
'join'])?
478 implode(
' LEFT JOIN ', $query[
'join']):$query[
'join']):
'')
479 .($query[
'where']?
' WHERE '.$query[
'where']:
'');
482 $this->currentQuery = $s;
483 $this->currentBind = $query[
'bind'];
484 $this->_stmt = $this->_db->prepare($s);
485 if ($this->_stmt->execute($query[
'bind']) ===
false) {
487 throw new Ego_Sql_Exception(implode(
' ', $this->_stmt->errorInfo()), (
int) $this->_stmt->errorCode());
491 return $this->
query($s);
533 if (isset($query[
'key']))
535 $set = array_combine($query[
'key'], $query[
'val']);
536 unset($query[
'val']);
537 } elseif (isset($query[
'set'])) {
538 $query[
'key'] = array_keys($query[
'set']);
539 $set = $query[
'set'];
540 unset($query[
'set']);
542 if (is_array($query[
'key'])) {
543 foreach ($query[
'key'] as $k) {
544 $field[] = $this->escapeChar . $k . $this->escapeChar .
'=:' . $k;
547 if (isset($query[
'set_f']))
549 foreach ($query[
'set_f'] as $k => $v)
551 $field[] = $this->escapeChar.$k.$this->escapeChar.
'='.$v;
554 $s =
'UPDATE '.($query[
'ignore']?
'IGNORE ':
'').
556 ' SET '.implode(
',', $field).
557 ($query[
'where']?
' WHERE '.$query[
'where']:
'');
558 $this->currentQuery = array(
'query' => $s);
559 $this->_stmt = $this->_db->prepare($s);
560 $this->currentQuery[
'set'] = $set;
561 if ($query[
'bind']) {
562 $set = array_merge($set, $query[
'bind']);
564 if ($this->_stmt ===
false) {
566 throw new Ego_Sql_Exception(implode(
' ', $this->_db->errorInfo()), (
int) $this->_db->errorCode());
568 if ($this->_stmt->execute($set) ===
false) {
570 throw new Ego_Sql_Exception(implode(
' ', $this->_stmt->errorInfo()), (
int) $this->_stmt->errorCode());
605 if (isset($query[
'key']))
607 $set = array_combine($query[
'key'], $query[
'val']);
608 unset($query[
'val']);
610 $query[
'key'] = array_keys($query[
'set']);
611 $set = $query[
'set'];
612 unset($query[
'set']);
614 $this->currentQuery = $query;
615 $insert_table = $query[
'table'].
'-'.
sizeof($query[
'key']).
'-'.$query[
'replace'];
616 if ($this->_insertTable != $insert_table)
618 $s = ($query[
'replace']?
'REPLACE':
'INSERT').
" INTO $query[table]".
619 " (".$this->escapeChar.implode($this->escapeChar.
','.$this->escapeChar, $query[
'key']).$this->escapeChar.
")".
620 " VALUES (:".implode(
',:', $query[
'key']).
")";
621 $this->_insertstmt = $this->_db->prepare($s);
622 $this->_insertTable = $insert_table;
624 $this->currentQuery[
'set'] = $set;
625 if ($this->_insertstmt ===
false) {
627 throw new Ego_Sql_Exception(implode(
' ', $this->_db->errorInfo()), (
int) $this->_db->errorCode());
629 if ($this->_insertstmt->execute($set) ===
false) {
631 throw new Ego_Sql_Exception(implode(
' ', $this->_insertstmt->errorInfo()), (
int) $this->_insertstmt->errorCode());
633 return $this->_insertstmt;
658 assert(!$query[
'replace'] || $query[
'primary']);
659 return $this->
insert(array_merge($query, array(
'replace' =>
true)));
711 return isset($this->Record);
723 $this->_currentRow = -1;
724 $this->_cacheIndex = -1;
728 return $this->
next();
752 if (!isset($GLOBALS[
'egotec_conf'][
'no_query_cache']) || $GLOBALS[
'egotec_conf'][
'no_query_cache']!=1)
754 $query_hash = $query[
'hash']?$query[
'hash']:md5(serialize($query));
755 $this->_cacheRecords = $cache->get($query_hash);
756 if ($this->_cacheRecords ===
null)
759 $this->_cacheRecords = array();
764 $cache->set($query_hash, $this->_cacheRecords);
766 $GLOBALS[
'stats'][
'db_cache']++;
768 $this->_cached =
true;
769 $this->_cacheIndex = -1;
770 $this->_currentRow = -1;
794 $db->select(array(
'table' => $table));
795 while ($db->nextRecord())
797 $content[] = $db->Record;
817 function import($table, $content, $primary=array(), $c_date_fieldname=
'', $c_date_value=
'')
819 if (!is_array($content))
830 $db->select(array(
'table' => $table));
831 $old_content = array();
832 while ($db->nextRecord())
834 $old_content[md5(serialize($db->Record))] = $db->Record;
837 foreach ($content as $record)
839 $md5 = md5(serialize($record));
840 if ($old_content[$md5])
843 unset($old_content[$md5]);
845 if (
sizeof($primary)==1)
847 $keys = array_keys($primary);
848 $insert[$record[$keys[0]]] = $record;
854 foreach ($old_content as $record)
856 if (!$c_date_fieldname || $record[$c_date_fieldname]<$c_date_value)
861 foreach ($record as $key=>$val)
867 if ($primary[$key]==
'string')
869 $where[] = $key.
'=\''.$val.
'\'';
871 $where[] = $key.
'='.$val;
875 if (is_numeric($val))
877 $where[] = $key.
'='.$val;
879 $where[] = $key.
'=\''.$val.
'\'';
883 $where = implode(
' AND ', $where);
889 $record[$c_date_fieldname] = date(
'Y-m-d H:i:s');
893 'primary' => $primary
895 if (
sizeof($primary)==1)
897 $keys = array_keys($primary);
898 unset($insert[$record[$keys[0]]]);
902 foreach ($insert as $record)
905 $db->insert(array(
'set' => $record,
'table' => $table));
906 }
catch (Exception $e)
908 egotec_error_log($e->getMessage());
982 $this->
query(
'DROP TABLE '.$table);
1050 $file = $GLOBALS[
'egotec_conf'][
'var_dir'].
'lib/db.php';
1052 require_once($file);
1053 $func =
'db_'.$action;
1054 if (function_exists($func)) {
1058 egotec_error_log(
'Connection failed');
1090 $this->
query(
"SHOW TABLES FROM ".$GLOBALS[
'egotec_conf'][
'db'][
'database'].
" LIKE '$like%'");
1092 $this->
query(
"SHOW TABLES FROM ".$GLOBALS[
'egotec_conf'][
'db'][
'database']);
1095 $all_table = array();
1099 $all_table[$count++] = array_pop($this->Record);
alterTable($table, $struct)
__construct($query=array(), $cache=false)
createTable($table, $struct, $drop_flag=true)
query($query, $appendCurrent=false)
connect($database='', $host='', $user='', $password='')
_cacheInit($query, $cache)
select($query, $cache=false)
static file_exists($file)
static log($file, $message)