nyroFwk  0.2
db/abstract.class.php
Go to the documentation of this file.
1 <?php
10 abstract class db_abstract extends object {
11 
17  protected $connection;
18 
24  public function getInstanceCfg() {
25  return $this->cfg->getInstanceCfg;
26  }
27 
34  public function getConnection() {
35  $this->_connect();
36  return $this->connection;
37  }
38 
45  public function query($sql, array $bind=array()) {
46  $this->_connect();
47  $stmt = $this->prepare($sql);
48  db::log($sql, $bind);
49  $stmt->execute($bind);
50  return $stmt;
51  }
52 
58  public function beginTransaction() {
59  $this->_connect();
60  $this->_beginTransaction();
61  return true;
62  }
63 
69  public function commit() {
70  $this->_connect();
71  $this->_commit();
72  return true;
73  }
74 
80  public function rollBack() {
81  $this->_connect();
82  $this->_rollBack();
83  return true;
84  }
85 
94  public function insert(array $prm) {
95  if (config::initTab($prm, Array(
96  'table'=>null,
97  'values'=>null
98  ))) {
99 
100  $cols = array_map(array($this, 'quoteIdentifier'), array_keys($prm['values']));
101  $vals = count($cols) > 0? array_fill(0, count($cols), '?') : array();
102 
103  $sql = 'INSERT INTO '.$this->quoteIdentifier($prm['table']);
104  $sql.= ' ('.implode(',',$cols).') VALUES ('.implode(',',$vals).')';
105 
106  $stmt = $this->query($sql, array_values($prm['values']));
107  return $this->lastInsertId();
108  } else
109  throw new nException('db_abstract - insert: The table or the values is missing.');
110  }
111 
120  public function replace(array $prm) {
121  if (config::initTab($prm, Array(
122  'table'=>null,
123  'values'=>null
124  ))) {
125 
126  $cols = array_map(array($this, 'quoteIdentifier'), array_keys($prm['values']));
127  $vals = array_fill(0, count($cols), '?');
128 
129  $sql = 'REPLACE INTO '.$this->quoteIdentifier($prm['table']);
130  $sql.= ' ('.implode(',',$cols).') VALUES ('.implode(',',$vals).')';
131 
132  $stmt = $this->query($sql, array_values($prm['values']));
133  return $this->lastInsertId();
134  } else
135  throw new nException('db_abstract - replace: The table or the values is missing.');
136  }
137 
149  public function update(array $prm) {
150  if (config::initTab($prm, Array(
151  'table'=>null,
152  'values'=>null,
153  'where'=>'',
154  'whereOp'=>'AND'
155  ))) {
156 
157  $set = array();
158  foreach($prm['values'] as $col=>$val)
159  $set[] = $this->quoteIdentifier($col).'=?';
160 
161  $sql = 'UPDATE '.$this->quoteIdentifier($prm['table']);
162  $sql.= ' SET '.implode(',',$set);
163  $sql.= $this->makeWhere($prm['where'], $prm['whereOp']);
164  $stmt = $this->query($sql, array_values($prm['values']));
165  return $stmt->rowCount();
166  } else
167  throw new nException('db_abstract - update : The table or the values is missing.');
168  }
169 
180  public function delete(array $prm) {
181  if (config::initTab($prm, Array(
182  'table'=>null,
183  'where'=>'',
184  'whereOp'=>'AND',
185  'optim'=>true
186  ))) {
187 
188  $sql = 'DELETE FROM '.$this->quoteIdentifier($prm['table'])
189  .$this->makeWhere($prm['where'], $prm['whereOp']);
190 
191  $stmt = $this->query($sql);
192  $nb = $stmt->rowCount();
193 
194  if ($prm['optim'])
195  $this->optimize($prm['table']);
196 
197  return $nb;
198  } else
199  throw new nException('db_abstract - delete : The table is missing.');
200  }
201 
210  public function makeWhere($where, $whereOp='AND', $incWhere=true) {
211  $query = null;
212  if (!empty($where)) {
213  if ($where instanceof db_where)
214  $query = $where->toString();
215  else if (is_array($where)) {
216  $tmp = array();
217  $where = array_filter($where);
218  if (empty($where))
219  return $query;
220  foreach($where as $k=>$v) {
221  $tmp[] = is_numeric($k) ? $v : $this->quoteIdentifier($k).'="'.$v.'"';
222  }
223  $query = '('.implode(' '.$whereOp.' ', $tmp).')';
224  } else
225  $query = $where;
226  $query = ($incWhere && $query? ' WHERE ' : null).$query;
227  }
228  return $query;
229  }
230 
236  public function getFetchMode() {
237  return $this->cfg->fetchMode;
238  }
239 
245  public function setFetchMode($mode) {
246  $this->cfg->fetchMode = (int) $mode;
247  }
248 
274  public function selectQuery(array $prm) {
275  if (config::initTab($prm, array(
276  'fields'=>'*',
277  'i18nFields'=>'',
278  'table'=>null,
279  'moreTables'=>false,
280  'join'=>'',
281  'bind'=>array(),
282  'bindData'=>false,
283  'where'=>'',
284  'whereOp'=>'AND',
285  'order'=>'',
286  'start'=>0,
287  'nb'=>'',
288  'group'=>'',
289  'groupAfter'=>'',
290  'having'=>''
291  ))) {
292 
293  $table = db::get('table', $prm['table']);
294  $tableName = $this->quoteIdentifier($prm['table']);
295  if (is_array($prm['fields'])) {
296  $f = implode(',', array_map(array($this, 'quoteIdentifier'), $prm['fields']));
297  } else {
298  if (strpos($prm['fields'], $this->cfg->quoteIdentifier) === false) {
299  $f = implode(',', array_map(array($this, 'quoteIdentifier'), explode(',', $prm['fields'])));
300  } else
301  $f = $prm['fields'];
302  }
303 
304  if (!empty($prm['i18nFields'])) {
305  $i18nTable = db::get('table', $prm['table'].db::getCfg('i18n'));
306  $i18nTableName = $this->quoteIdentifier($i18nTable->getRawName());
307  $primary = $i18nTable->getPrimary();
308  $prm['join'][] = array(
309  'table'=>$i18nTable->getRawName(),
310  'on'=>$tableName.'.'.$table->getIdent().'='.$i18nTableName.'.'.$primary[0].
311  ' AND '.$i18nTableName.'.'.$primary[1].'="'.request::get('lang').'"'
312  );
313  if (is_array($prm['i18nFields'])) {
314  array_walk($prm['i18nFields'], array($this, 'quoteIdentifier'));
315  $f.= ','.$i18nTableName.'.'.implode(','.$i18nTableName.'.', $prm['fields']);
316  } else if ($prm['i18nFields']) {
317  foreach(explode(',', $prm['i18nFields']) as $t) {
318  $f.= ','.$i18nTableName.'.'.$t;
319  }
320  }
321  }
322 
323  $query = 'SELECT '.$f.' FROM '.$tableName;
324 
325  if ($prm['moreTables']) {
326  if (is_array($prm['moreTables'])) {
327  foreach($prm['moreTables'] as $k=>$v) {
328  if (is_numeric($k)) {
329  $query.= ', '.$this->quoteIdentifier($v);
330  } else {
331  $query.= ', '.$this->quoteIdentifier($v).' '.$this->quoteIdentifier($k);
332  }
333  }
334  } else {
335  $query.= ', '.$prm['moreTables'];
336  }
337  }
338 
339  $tblAlias = array();
340  if (is_array($prm['join'])) {
341  $join = array();
342  foreach($prm['join'] as &$v) {
343  $v = array_merge(array('dir'=>'left', 'on'=>1, 'alias'=>''), $v);
344  $alias = null;
345  if (!empty($v['alias'])) {
346  $alias = ' AS '.$this->quoteIdentifier($v['alias']);
347  if ($v['table'] != $table->getRawName())
348  $tblAlias[$v['table']] = $v['alias'];
349  }
350  $join[] = strtoupper($v['dir']).' JOIN '.$this->quoteIdentifier($v['table']).$alias.' ON '.$v['on'];
351  }
352  $query.= ' '.implode(' ', $join).' ';
353  }
354 
355  $query.= $this->makeWhere($prm['where'], $prm['whereOp']);
356 
357  if (!empty($prm['group']))
358  $query.= ' GROUP BY '.$prm['group'];
359 
360  if (!empty($prm['having']))
361  $query.= ' HAVING '.$prm['having'];
362 
363  if (!empty($prm['order']))
364  $query.= ' ORDER BY '.$prm['order'];
365 
366  if (!empty($prm['nb'])) {
367  if (empty($prm['start']))
368  $prm['start'] = 0;
369  $query.= ' LIMIT '.$prm['start'].','.$prm['nb'];
370  }
371 
372  if ($prm['bindData'] && !empty($prm['bind']) && is_array($prm['bind'])) {
373  $tmp = explode('?', $query, count($prm['bind'])+1);
374  array_splice($prm['bind'], count($tmp));
375 
376  $query = '';
377  while($tmp2 = array_shift($tmp)) {
378  $query.= $tmp2.array_shift($prm['bind']);
379  }
380  }
381 
382  if ($prm['groupAfter'])
383  $query = 'SELECT * FROM ('.$query.') AS res GROUP BY '.$prm['groupAfter'];
384 
385  return $this->tableAlias($query, $tblAlias);
386  } else
387  throw new nException('db_abstract - selectQuery : The table is missing.');
388  }
389 
397  protected function tableAlias($query, array $tblAlias) {
398  $search = array();
399  $replace = array();
400  foreach($tblAlias as $tbl=>$alias) {
401  $search = array_merge($search, array(
402  ' '.$tbl.'.',
403  ' '.$this->quoteIdentifier($tbl).'.',
404  '('.$this->quoteIdentifier($tbl).'.'
405  ));
406  $replace = array_merge($replace, array(
407  ' '.$alias.'.',
408  ' '.$this->quoteIdentifier($alias).'.',
409  '('.$this->quoteIdentifier($alias).'.'
410  ));
411  }
412  return str_replace($search, $replace, $query);
413  }
414 
422  public function select($prm) {
423  if (is_array($prm)) {
424  config::initTab($prm, array(
425  'bind'=>array(),
426  'forceFetchMode'=>0,
427  ));
428  $stmt = $this->query($this->selectQuery($prm), $prm['bind']);
429  $fetchMode = $prm['forceFetchMode'] ? $prm['forceFetchMode'] : $this->cfg->fetchMode;
430  } else {
431  $stmt = $this->query($prm);
432  $fetchMode = $this->cfg->fetchMode;
433  }
434 
435  if ($fetchMode == PDO::FETCH_CLASS) {
436  $tmp = $stmt->fetchAll(PDO::FETCH_ASSOC);
437  return $tmp;
438 
439  $cfg = array(
440  'db'=>$this,
441  'table'=>$prm['table'],
442  'props'=>array_keys($tmp[0])
443  );
444  foreach($tmp as $t) {
445  $row = factory::get($className, $cfg);
446  $row->setValues($t);
447  $ret[] = $row;
448  }
449  return $ret;
450  } else {
451  return $stmt->fetchAll($fetchMode);
452  }
453  }
454 
462  public function count(array $prm) {
463  $subQuery = $this->selectQuery(array_merge($prm, array('bindData'=>true)));
464  $stmt = $this->query('SELECT COUNT(*) AS count FROM ('.$subQuery.') AS subquerycount');
465  $tmp = $stmt->fetch(PDO::FETCH_ASSOC);
466  $count = $tmp['count'];
467  $stmt->fetchAll();
468  $stmt->closeCursor();
469  $stmt = null;
470  return $count;
471  }
472 
487  public function fetchAssoc(array $prm) {
488  $prm['forceFetchMode'] = PDO::FETCH_ASSOC;
489  return $this->select($prm);
490  }
491 
502  public function fetchPairs(array $prm) {
503  $prm['forceFetchMode'] = PDO::FETCH_NUM;
504  return $this->select($prm);
505  }
506 
515  public function fetchRow(array $prm) {
516  $prm['nb'] = 1;
517  $prm['start'] = 0;
518  return array_pop($this->select($prm));
519  }
520 
527  public function quoteIdentifier($ident) {
528  if (strpos($ident, '(') !== false)
529  return $ident;
530  $tmpSpace = explode(' ', $ident);
531  $tmp = explode('.', $tmpSpace[0]);
532  if (count($tmp) == 1 && $tmp[0] == '*')
533  return '*';
534  else if (count($tmp) == 2 && $tmp[1] == '*')
535  return $this->cfg->quoteIdentifier.$tmp[0].$this->cfg->quoteIdentifier.'.*';
536  $tmpSpace[0] = $this->cfg->quoteIdentifier
537  .implode($this->cfg->quoteIdentifier.'.'.$this->cfg->quoteIdentifier, $tmp)
538  .$this->cfg->quoteIdentifier;
539  return implode(' ', $tmpSpace);
540  }
541 
548  public function quoteValue($value) {
549  return $this->cfg->quoteValue.addcslashes($value, $this->cfg->quoteValue).$this->cfg->quoteValue;
550  }
551 
557  public function optimize($table) {
558  $this->query('OPTIMIZE TABLE '.$table);
559  }
560 
570  public function getTablesWith(array $prm) {
571  $tmp = array_fill(0, 3, '');
572 
573  if (array_key_exists('start', $prm))
574  $tmp[0] = $prm['start'];
575 
576  if (array_key_exists('contains', $prm))
577  $tmp[1] = $prm['contains'];
578 
579  if (array_key_exists('end', $prm))
580  $tmp[2]= $prm['end'];
581 
582  $regex = '/^'.implode('(.*)', $tmp).'$/';
583 
584  return array_merge(array_filter($this->getTables(),
585  create_function('$val', 'return preg_match("'.$regex.'", $val);')));
586  }
587 
594  public function getI18nTable($table) {
595  $tmp = $this->getTablesWith(array(
596  'end'=>$table.db::getCfg('i18n')
597  ));
598  if (count($tmp) == 1)
599  return $tmp[0];
600  return null;
601  }
602 
609  public function getWhere(array $prm = array()) {
610  return factory::get('db_where', array_merge(array(
611  'db'=>$this
612  ), $prm));
613  }
614 
620  public function getCache() {
621  return cache::getInstance($this->cfg->cache);
622  }
623 
629  public function __sleep() {
630  return array('cfg');
631  }
632 
643  abstract public function getTables($unPrefix = true);
644 
651  abstract public function prefixTable($table);
652 
659  abstract public function fields($table);
660 
664  abstract protected function _connect();
665 
671  abstract public function closeConnection();
672 
679  abstract public function prepare($sql);
680 
686  abstract public function lastInsertId();
687 
691  abstract protected function _beginTransaction();
692 
696  abstract protected function _commit();
697 
701  abstract protected function _rollBack();
702 
703 }
getWhere(array $prm=array())
static get($get=null)
count(array $prm)
static getInstance(array $cfg=array())
Definition: cache.class.php:30
replace(array $prm)
fields($table)
prepare($sql)
fetchAssoc(array $prm)
getTables($unPrefix=true)
fetchPairs(array $prm)
query($sql, array $bind=array())
static initTab(array &$vars, array $init)
insert(array $prm)
quoteIdentifier($ident)
getTablesWith(array $prm)
static getCfg($key)
Definition: db.class.php:125
makeWhere($where, $whereOp='AND', $incWhere=true)
prefixTable($table)
static log($sql=null, $bind=null)
Definition: db.class.php:156
update(array $prm)
static get($type, $table, array $prm=array())
Definition: db.class.php:87
tableAlias($query, array $tblAlias)
fetchRow(array $prm)
$f
Definition: list.php:6
static get($className, array $cfg=array())
selectQuery(array $prm)
Generated on Sun Oct 15 2017 22:25:20 for nyroFwk by doxygen 1.8.13