-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.php
846 lines (785 loc) · 25.5 KB
/
database.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
<?php
defined('SYS_PATH') or die('No direct access allowed.');
/**
* Provides database access in a platform agnostic way, using simple query building blocks.
*
* @package Core
* @author Ko Team
* @version $Id: database.php 91 2010-07-04 03:34:02Z eric $
* @copyright (c) 2008-2009 Ko Team
* @license http://kophp.com/license.html
*/
class Database
{
/*
* Database instances
*/
public static $instances = array();
protected $_config = array(
'persistent' => FALSE ,
'connection' => '' ,
'charset' => 'utf8' ,
'table_prefix' => '' ,
);
/**
* @var Database_Driver
*/
protected $_driver;
protected $_select = array();
protected $_from = array();
protected $_join = array();
protected $_where = array();
protected $_order = array();
protected $_group = array();
protected $_having = array();
protected $_distinct = FALSE;
protected $_limit = FALSE;
protected $_offset = FALSE;
protected $_set = array();
protected $_lastQuery = '';
/**
* Returns a singleton instance of Database.
*
* @param mixed configuration array
* @return Database
*/
public static function &instance ($database = 'default', $config = NULL)
{
if (! isset(self::$instances[$database])) {
self::$instances[$database] = new self($config === NULL ? $database : $config);
}
return self::$instances[$database];
}
/**
* Sets up the database configuration, loads the Database_Driver.
*
* @throws KoException
*/
public function __construct ($config = array())
{
if (empty($config)) {
$config = Ko::config('database.default');
} elseif (is_string($config)) {
$name = $config;
if (($config = Ko::config('database.' . $config)) === NULL)
throw new KoException('database.undefined_group :group', array(':group' => $name));
}
// Merge the default config with the passed config
$this->_config = array_merge($this->_config, $config);
$driver = 'Database_' . ucfirst($this->_config['type']);
if (! Ko::autoload($driver))
throw new KoException('core.driver_not_found :error', array(':error' => $this->_config['type'] . get_class($this)));
$this->_driver = new $driver($this->_config);
if (! ($this->_driver instanceof Database_Driver))
throw new KoException('core.driver_implements :error', array(':error' => $this->_config['type'] . get_class($this) . 'Database_Driver'));
}
/**
* Runs a query into the driver and returns the result.
*
* @param string $sql SQL Query to execute
* @param array|string $bind Data to bind into SELECT placeholders.
* @return Database_Result
*/
public function query ($sql = '', $binds = array())
{
if ($sql == '')
return FALSE;
// Compile binds if needed
if (isset($binds)) {
$sql = $this->bind($sql, $binds);
}
// Set the last query
$this->_lastQuery = $sql;
// Fetch the result
return $this->_driver->query($sql);
}
/**
* Selects the column names for a database query.
*
* @param string string or array of column names to select
* @return Database This Database object.
*/
public function select ($column = '*')
{
if (func_num_args() > 1) {
$column = func_get_args();
} elseif (is_string($column)) {
$column = explode(',', $column);
} else {
$column = (array) $column;
}
unset($this->_select);
foreach ($column as $val) {
if (($val = trim($val)) === '')
continue;
if (strpos($val, '(') === FALSE and $val !== '*') {
if (preg_match('/^DISTINCT\s++(.+)$/i', $val, $matches)) {
$this->_distinct = TRUE;
}
$val = $this->escapeColumn($val);
}
$this->_select[] = $val;
}
return $this;
}
/**
* Selects the from table(s) for a database query.
*
* @param string string or array of tables to select
* @return Database This Database object.
*/
public function from ($table)
{
if (func_num_args() > 1) {
$table = func_get_args();
} elseif (is_string($table)) {
$table = explode(',', $table);
} else {
$table = array($table);
}
foreach ($table as $val) {
if (is_string($val)) {
if (($val = trim($val)) === '')
continue;
if (stripos($val, ' AS ') !== FALSE) {
$val = str_ireplace(' as ', ' AS ', $val);
list ($table, $alias) = explode(' AS ', $val);
$this->_from[] = $this->_config['table_prefix'] . $table . ' AS ' . $this->_config['table_prefix'] . $alias;
} else {
$this->_from[] = $this->_config['table_prefix'] . $val;
}
}
}
return $this;
}
/**
* Generates the JOIN portion of the query.
*
* @param string table name
* @param string|array where key or array of key => value pairs
* @param string where value
* @param string type of join
* @return Database This Database object.
*/
public function join ($table, $key, $value = NULL, $type = '')
{
$join = array();
if (! empty($type)) {
$type = strtoupper(trim($type));
if (! in_array($type, array('LEFT' , 'RIGHT' , 'OUTER' , 'INNER' , 'LEFT OUTER' , 'RIGHT OUTER'), TRUE)) {
$type = '';
} else {
$type .= ' ';
}
}
$cond = array();
$keys = is_array($key) ? $key : array($key => $value);
foreach ($keys as $key => $value) {
if (is_string($value)) {
$value = $this->escapeColumn($this->_config['table_prefix'] . $value);
}
$cond[] = $this->_driver->where($key, $value, 'AND ', count($cond), FALSE);
}
if (! is_array($this->_join)) {
$this->_join = array();
}
if (! is_array($table)) {
$table = array($table);
}
foreach ($table as $t) {
if (is_string($t)) {
if (stripos($t, ' AS ') !== FALSE) {
$t = str_ireplace(' AS ', ' AS ', $t);
list ($table, $alias) = explode(' AS ', $t);
$t = $this->_config['table_prefix'] . $table . ' AS ' . $this->_config['table_prefix'] . $alias;
} else {
$t = $this->_config['table_prefix'] . $t;
}
}
$join['tables'][] = $this->escapeColumn($t);
}
$join['conditions'] = '(' . trim(implode(' ', $cond)) . ')';
$join['type'] = $type;
$this->_join[] = $join;
return $this;
}
/**
* Selects the where(s) for a database query.
*
* @param string|array key name or array of key => value pairs
* @param string value to match with key
* @param boolean disable quoting of WHERE clause
* @return Database This Database object.
*/
public function where ($key, $value = NULL, $quote = TRUE)
{
$quote = (func_num_args() < 2 and ! is_array($key)) ? - 1 : $quote;
if (is_object($key)) {
$keys = array((string) $key => '');
} elseif (! is_array($key)) {
$keys = array($key => $value);
} else {
$keys = $key;
}
foreach ($keys as $key => $value) {
$this->_where[] = $this->_driver->where($key, $value, 'AND ', count($this->_where), $quote);
}
return $this;
}
/**
* Selects the OR where(s) for a database query.
*
* @param string|array key name or array of key => value pairs
* @param string value to match with key
* @param boolean disable quoting of WHERE clause
* @return Database This Database object.
*/
public function orWhere ($key, $value = NULL, $quote = TRUE)
{
$quote = (func_num_args() < 2 and ! is_array($key)) ? - 1 : $quote;
if (is_object($key)) {
$keys = array((string) $key => '');
} elseif (! is_array($key)) {
$keys = array($key => $value);
} else {
$keys = $key;
}
foreach ($keys as $key => $value) {
$this->_where[] = $this->_driver->where($key, $value, 'OR ', count($this->_where), $quote);
}
return $this;
}
/**
* Selects the like(s) for a database query.
*
* @param string|array field name or array of field => match pairs
* @param string like value to match with field
* @param boolean automatically add starting and ending wildcards
* @return Database This Database object.
*/
public function like ($field, $match = '', $auto = TRUE)
{
$fields = is_array($field) ? $field : array($field => $match);
foreach ($fields as $field => $match) {
$this->_where[] = $this->_driver->like($field, $match, $auto, 'AND ', count($this->_where));
}
return $this;
}
/**
* Selects the or like(s) for a database query.
*
* @param string|array field name or array of field => match pairs
* @param string like value to match with field
* @param boolean automatically add starting and ending wildcards
* @return Database This Database object.
*/
public function orLike ($field, $match = '', $auto = TRUE)
{
$fields = is_array($field) ? $field : array($field => $match);
foreach ($fields as $field => $match) {
$this->_where[] = $this->_driver->like($field, $match, $auto, 'OR ', count($this->_where));
}
return $this;
}
/**
* Selects the not like(s) for a database query.
*
* @param string|array field name or array of field => match pairs
* @param string like value to match with field
* @param boolean automatically add starting and ending wildcards
* @return Database This Database object.
*/
public function notLike ($field, $match = '', $auto = TRUE)
{
$fields = is_array($field) ? $field : array($field => $match);
foreach ($fields as $field => $match) {
$this->_where[] = $this->_driver->notLike($field, $match, $auto, 'AND ', count($this->_where));
}
return $this;
}
/**
* Selects the or not like(s) for a database query.
*
* @param string|array field name or array of field => match pairs
* @param string like value to match with field
* @return Database This Database object.
*/
public function orNotLike ($field, $match = '', $auto = TRUE)
{
$fields = is_array($field) ? $field : array($field => $match);
foreach ($fields as $field => $match) {
$this->_where[] = $this->_driver->notLike($field, $match, $auto, 'OR ', count($this->_where));
}
return $this;
}
/**
* Adds an "IN" condition to the where clause
*
* @param string Name of the column being examined
* @param mixed An array or string to match against
* @param bool Generate a NOT IN clause instead
* @return Database This Database object.
*/
public function in ($field, $values, $not = FALSE)
{
$values = $this->escape($values);
$where = $this->escapeColumn($field) . ' ' . ($not === TRUE ? 'NOT ' : '') . 'IN (' . $values . ')';
$this->_where[] = $this->_driver->where($where, '', 'AND ', count($this->_where), - 1);
return $this;
}
/**
* Adds a "NOT IN" condition to the where clause
*
* @param string Name of the column being examined
* @param mixed An array or string to match against
* @return Database This Database object.
*/
public function notIn ($field, $values)
{
return $this->in($field, $values, TRUE);
}
/**
* Chooses the column to group by in a select query.
*
* @param string column name to group by
* @return Database This Database object.
*/
public function group ($by)
{
if (! is_array($by)) {
$by = explode(',', (string) $by);
}
foreach ($by as $val) {
$val = trim($val);
if ($val != '') {
$this->_group[] = $this->escapeColumn($val);
}
}
return $this;
}
/**
* Selects the having(s) for a database query.
*
* @param string|array key name or array of key => value pairs
* @param string value to match with key
* @param boolean disable quoting of WHERE clause
* @return Database This Database object.
*/
public function having ($key, $value = '', $quote = TRUE)
{
$this->_having[] = $this->_driver->where($key, $value, 'AND', count($this->_having), $quote);
return $this;
}
/**
* Selects the or having(s) for a database query.
*
* @param string|array key name or array of key => value pairs
* @param string value to match with key
* @param boolean disable quoting of WHERE clause
* @return Database This Database object.
*/
public function orHaving ($key, $value = '', $quote = TRUE)
{
$this->_having[] = $this->_driver->where($key, $value, 'OR', count($this->_having), $quote);
return $this;
}
/**
* Chooses which column(s) to order the select query by.
*
* @param string|array column(s) to order on, can be an array, single column, or comma seperated list of columns
* @param string direction of the order
* @return Database This Database object.
*/
public function order ($order, $direction = NULL)
{
if (! is_array($order)) {
$order = array($order => $direction);
}
foreach ($order as $column => $direction) {
$direction = strtoupper(trim($direction));
if (! in_array($direction, array('ASC' , 'DESC' , 'RAND()' , 'RANDOM()' , 'NULL'))) {
$direction = 'ASC';
}
$this->_order[] = $this->escapeColumn($column) . ' ' . $direction;
}
return $this;
}
/**
* Selects the limit section of a query.
*
* @param integer number of rows to limit result to
* @param integer offset in result to start returning rows from
* @return Database This Database object.
*/
public function limit ($limit, $offset = NULL)
{
$this->_limit = (int) $limit;
if ($offset !== NULL or ! is_int($this->_offset)) {
$this->offset($offset);
}
return $this;
}
/**
* Sets the offset portion of a query.
*
* @param integer offset value
* @return Database This Database object.
*/
public function offset ($value)
{
$this->_offset = (int) $value;
return $this;
}
/**
* Builds an array of query results.
*
* @return array
*/
public function fetchArray ($sql = '', $binds = array())
{
if ($sql == '') {
$sql = $this->compile();
}
$result = $this->query($sql, $binds);
if($result instanceof Database_Result){
return $result->fetchArray();
} else {
return $result;
}
}
/**
* Builds an Object of query results.
*
* @return Object
*/
public function fetchObject ($sql = '', $binds = array())
{
if ($sql == '') {
$sql = $this->compile();
}
$result = $this->query($sql, $binds);
if($result instanceof Database_Result){
return $result->fetchObject();
} else {
return $result;
}
}
/**
* Builds an array of one row query result.
*
* @return array
*/
public function fetchRow ($sql = '', $binds = array())
{
if ($sql == '') {
$sql = $this->limit(1)->compile();
}
$result = $this->query($sql, $binds);
if($result instanceof Database_Result){
$result = $result->fetchObject();
return $result ? current($result) : false;
} else {
return $result;
}
}
/**
* Compiles the select statement based on the other functions called and runs the query.
*
* @param string table name
* @param string limit clause
* @param string offset clause
* @return Database_Result
*/
public function execute ($table = '', $limit = NULL, $offset = NULL)
{
return $this->query($this->compile($table, $limit, $offset));
}
/**
* Compiles the select statement based on the other functions called and returns the query string.
*
* @param string table name
* @param string limit clause
* @param string offset clause
* @return string sql string
*/
public function compile ($table = '', $limit = NULL, $offset = NULL)
{
if ($table != '') {
$this->from($table);
}
if (! is_null($limit)) {
$this->limit($limit, $offset);
}
$sql = $this->_driver->select(get_object_vars($this));
$this->reset();
return $sql;
}
/**
* Compiles an insert string and runs the query.
*
* @param string table name
* @param array array of key/value pairs to insert
* @return Database_Result Query result
*/
public function insert ($table = '', $set = NULL)
{
if (! is_null($set)) {
$this->setValue($set);
}
if ($this->_set == NULL)
throw new KoException('database.must_use_set');
if ($table == '') {
if (! isset($this->_from[0]))
throw new KoException('database.must_use_table');
$table = $this->_from[0];
}
$sql = $this->_driver->insert($this->_config['table_prefix'] . $table, array_keys($this->_set), array_values($this->_set));
$this->reset();
return $this->query($sql);
}
/**
* Returns the insert id from the result.
*
* @return int
*/
public function lastInsertId ()
{
return $this->_driver->lastInsertId();
}
/**
* Compiles a replace string and runs the query.
*
* @param string table name
* @param array array of key/value pairs to replace
* @return Database_Result Query result
*/
public function replace ($table, $set = NULL)
{
if (! is_null($set)) {
$this->setValue($set);
}
if ($this->_set == NULL)
throw new KoException('database.must_use_set');
if ($table == '') {
if (! isset($this->_from[0]))
throw new KoException('database.must_use_table');
$table = $this->_from[0];
}
$sql = $this->_driver->replace($this->_config['table_prefix'] . $table, array_keys($this->_set), array_values($this->_set));
$this->reset();
return $this->query($sql);
}
/**
* Compiles an update string and runs the query.
*
* @param string table name
* @param array associative array of update values
* @param array where clause
* @return Database_Result Query result
*/
public function update ($table = '', $set = NULL, $where = NULL)
{
if (is_array($set)) {
$this->setValue($set);
}
if (! is_null($where)) {
$this->where ($where);
}
if ($this->_set == FALSE)
throw new KoException('database.must_use_set');
if ($table == '') {
if (! isset($this->_from[0]))
throw new KoException('database.must_use_table');
$table = $this->_from[0];
}
$sql = $this->_driver->update($this->_config['table_prefix'] . $table, $this->_set, $this->_where);
$this->reset();
return $this->query($sql);
}
/**
* Compiles a delete string and runs the query.
*
* @param string table name
* @param array where clause
* @return Database_Result Query result
*/
public function delete ($table = '', $where = NULL)
{
if ($table == '') {
if (! isset($this->_from[0]))
throw new KoException('database.must_use_table');
$table = $this->_from[0];
} else {
$table = $this->_config['table_prefix'] . $table;
}
if (! is_null($where)) {
$this->where ($where);
}
if (count($this->_where) < 1)
throw new KoException('database.must_use_where');
$sql = $this->_driver->delete($table, $this->_where);
$this->reset();
return $this->query($sql);
}
/**
* Returns the last query run.
*
* @return string SQL
*/
public function getLastQuery ()
{
return $this->_lastQuery;
}
/**
* Count query records of curent query.
*
* @param string table name
* @param array where clause
* @return integer
*/
public function count ($table = FALSE, $where = NULL)
{
if (count($this->_from) < 1) {
if ($table == FALSE)
throw new KoException('database.must_use_table');
$this->from($table);
}
if ($where !== NULL) {
$this->where ($where);
}
return (int) $this->select('COUNT(*) AS ' . $this->escapeColumn('count'))->fetchRow()->count;
}
/**
* Lists all the tables in the current database.
*
* @return array
*/
public function listTables ()
{
return $this->_driver->listTables();
}
/**
* Get the field data for a database table, along with the field's attributes.
*
* @param string table name
* @return array
*/
public function listFields ($table = '')
{
return $this->_driver->listFields($this->_config['table_prefix'] . $table);
}
/**
* Combine a SQL statement with the bind values. Used for safe queries.
*
* For example:
* <code>
* $text = "WHERE date < ?";
* $date = "2005-01-02";
* $safe = $sql->bind ($text, $date);
* // $safe = "WHERE date < '2005-01-02'"
* </code>
*
* @param string $text query to bind to the values
* @param array $value array of values to bind to the query
* @param bool $single whether this is a single bind.
* @return string
*/
public function bind ($text, $value, $single = FALSE)
{
if ($single == TRUE) {
return str_replace('?', $this->escape($value), $text);
} else {
foreach ((array) $value as $val) {
if (strpos($text, '?') != FALSE) {
$text = substr_replace($text, $this->escape($val), strpos($text, '?'), 1);
}
}
return $text;
}
}
/**
* Escapes a value for a query.
*
* @param mixed value to escape
* @return string
*/
public function escape ($value)
{
return $this->_driver->escape($value);
}
/**
* Escapes a string for a query.
*
* @param string string to escape
* @return string
*/
public function escapeStr ($str)
{
return $this->_driver->escapeStr($str);
}
/**
* Escapes a table name for a query.
*
* @param string string to escape
* @return string
*/
public function escapeTable ($table)
{
return $this->_driver->escapeTable($table);
}
/**
* Escapes a column name for a query.
*
* @param string string to escape
* @return string
*/
public function escapeColumn ($column)
{
return $this->_driver->escapeColumn($column);
}
/**
* Returns table prefix of current configuration.
*
* @return string
*/
public function tablePrefix ()
{
return $this->_config['table_prefix'];
}
/**
* Allows key/value pairs to be set for inserting or updating.
*
* @param string|array key name or array of key => value pairs
* @param string value to match with key
* @return Database This Database object.
*/
protected function setValue ($key, $value = '')
{
if (! is_array($key)) {
$key = array($key => $value);
}
foreach ($key as $k => $v) {
$this->_set[$k] = $this->escape($v);
}
return $this;
}
/**
* Resets all private select and insert variables.
*
* @return void
*/
protected function reset ()
{
$this->_select = array();
$this->_from = array();
$this->_join = array();
$this->_where = array();
$this->_order = array();
$this->_group = array();
$this->_having = array();
$this->_set = array();
$this->_distinct = FALSE;
$this->_limit = FALSE;
$this->_offset = FALSE;
}
} // End Database Class