-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery_builder.php
More file actions
820 lines (744 loc) · 17.3 KB
/
query_builder.php
File metadata and controls
820 lines (744 loc) · 17.3 KB
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
<?php
/**
* Class for building queries
*
* @package Controller
* @license AGPL1
* @version 0.1.1
* @author Roberto Pérez Nygaard - roberto@nygaard.es
*/
class QueryBuilder
{
//Constants
const COLUMNS = 'columns';
const FROM = 'from';
const JOIN = 'join';
const UNION = 'union';
const WHERE = 'where';
const GROUP = 'group';
const HAVING = 'having';
const ORDER = 'order';
const VALUES = 'values';
const INTO = 'into';
const LIMIT_COUNT = 'limitcount';
const LIMIT_OFFSET = 'limitoffset';
const FOR_UPDATE = 'forupdate';
const INNER_JOIN = 'inner join';
const LEFT_JOIN = 'left join';
const RIGHT_JOIN = 'right join';
const FULL_JOIN = 'full join';
const CROSS_JOIN = 'cross join';
const NATURAL_JOIN = 'natural join';
const SQL_WILDCARD = '*';
const SQL_SELECT = 'SELECT';
const SQL_INSERT = 'INSERT';
const SQL_UPDATE = 'UPDATE';
const SQL_DELETE = 'DELETE';
const SQL_UNION = 'UNION';
const SQL_UNION_ALL = 'UNION ALL';
const SQL_FROM = 'FROM';
const SQL_JOIN = 'INNER JOIN';
const SQL_INNER_JOIN = 'INNER JOIN';
const SQL_LEFT_JOIN = 'LEFT JOIN';
const SQL_WHERE = 'WHERE';
const SQL_DISTINCT = 'DISTINCT';
const SQL_GROUP_BY = 'GROUP BY';
const SQL_ORDER_BY = 'ORDER BY';
const SQL_HAVING = 'HAVING';
const SQL_LIMIT = 'LIMIT';
const SQL_FOR_UPDATE = 'FOR UPDATE';
const SQL_AND = 'AND';
const SQL_AS = 'AS';
const SQL_SET = 'SET';
const SQL_OR = 'OR';
const SQL_ON = 'ON';
const SQL_ASC = 'ASC';
const SQL_DESC = 'DESC';
const SQL_INTO = 'INTO';
const SQL_VALUES = 'VALUES';
const SQL_BEGIN = 'BEGIN';
const SQL_COMMIT = 'COMMIT';
const SQL_ROLLBACK = 'ROLLBACK';
const SQL_QUERY_DIVISOR = ';';
const CARRY_RETURN = "\n";
//private variables
private $_whereAmbit = 0;
private $_partsBuffer = array();
private $_lastQuery;
//Protected variables
protected $_adapter;
/**
* Specify legal join types.
*
* @var array
*/
protected static $_joinSQL = array(
self::FROM => self::SQL_FROM,
self::JOIN => self::SQL_JOIN,
self::INNER_JOIN => self::SQL_INNER_JOIN,
self::LEFT_JOIN => self::SQL_LEFT_JOIN
);
/**
* Specify legal union types.
*
* @var array
*/
protected static $_unionTypes = array(
self::SQL_UNION,
self::SQL_UNION_ALL
);
protected $_parts = array();
/**
* Class constructor
*/
public function __construct($adapter = null)
{
if (!$adapter)
{
$this->_exception('Empty adapter passed to ' . __CLASS__);
}
$this->_adapter = $adapter;
}
/**
* Forces a Variable to be as an Array
*
* @param mixed $var
* @param mixed $inverse
* @return array
*/
private function _getAsArray($var, $inverse = null)
{
if (!is_array($var))
{
$var = array($var);
if ($inverse)
{
$var = array($var => $inverse);
}
}
return $var;
}
/**
* Forces a variable to be the key of an
* array with the value as $defaultValue
*
* @param type $var
* @param type $defaultValue
* @return type
*/
private function _getAsInverseArray($var, $defaultValue = 1)
{
return $this->_getAsArray($var, $defaultValue);
}
/**
* DB escape function
*
* @param string|number $var
* @return string|number
*/
private function _escape($var)
{
if ($var === null)
{
return 'NULL';
}
return $this->_adapter->getConnection()->real_escape_string(str_replace(array('<', '>'), '',$var));
}
/**
* Saves the current _parts
*/
private function _pushParts()
{
$this->_partsBuffer[] = $this->_parts;
}
/**
* Restores the previous _parts
*/
private function _popParts()
{
if (is_array($this->_partsBuffer))
{
$this->_parts = array_pop($this->_partsBuffer);
}
}
/**
* Escapes and formats the function
*
* @param string|number $str
* @return string|number
*/
private function _escapeAndFormat($str)
{
if ($str === null)
{
return 'NULL';
}
$result = $this->_escape($str);
if (!is_numeric($result))
{
$result = '"' . $result . '"';
}
return $result;
}
/**
* Private function that prepares the joins and froms
*
* @param string $type
* @param string $name
* @param string $cond
* @param string $columns
* @return \QueryBuilder
*/
protected function _joiner($type, $name = array(), $cond = null, $columns = null)
{
//Defensive conditions
if (empty($name))
{
$this->_exception('No tables where selected');
}
if ($type != self::FROM && empty($cond))
{
$this->_exception('No condition specified for ' . self::JOIN);
}
//Defensive end
$name = $this->_getAsArray($name);
foreach ($name as $_alias => $_table)
{
if (strpos($_table, ',') === false)
{
$_table = '`' . $_table . '`';
}
$subQuery = $_table;
if (!is_int($_alias))
{
$subQuery .= ' ' . self::SQL_AS . ' ' . $_alias;
}
if ($cond)
{
$subQuery .= ' ' . self::SQL_ON . ' ' . $cond;
}
if (self::$_joinSQL[$type] == self::SQL_FROM)
{
$this->_parts[self::FROM][] = $subQuery;
}
else
{
$this->_parts[self::JOIN][] = self::$_joinSQL[$type] . ' ' . $subQuery;
}
if ($columns)
{
$this->columns($columns, $_alias);
}
}
return $this;
}
/**
* Private function that prepares the where part.
* If value is specified, it escapes it
*
* @param string $condition
* @param string $value
* @return string
*/
protected function _where($condition, $value = null)
{
if (count($this->_parts[self::UNION]))
{
$this->_exception('Invalid use of where clause with ' . self::SQL_UNION);
}
if ($value !== null) {
if ((strpos($value, self::SQL_SELECT) !== false) &&
strpos($value, self::SQL_FROM))
{
//We have a query inside a condition, therefore we should
//not escape it.
//do Nothing
}
else
{
$value = $this->_getAsArray($value);
foreach ($value as &$_value)
{
$_value = $this->_escapeAndFormat($_value);
}
$value = implode(', ', $value);
}
if (strpos($condition, '?') === false)
{
$this->_exception('Invalid use of where clause: No `?` found for escaped value');
}
$condition = str_replace('?', $value, $condition);
}
return $condition;
}
/**
* Inserts part in the array for
*
* @param type $key
* @param type $arrValues
*/
protected function _pushInParts($key,$arrValues)
{
$arrValues = $this->_getAsArray($arrValues);
foreach ($arrValues as $_value)
{
$this->_parts[$key][] = $this->_escape($_value);
}
}
/**
* Exception treatment
*
* @param type $message
* @param type $type
* @throws Exception
*/
protected function _exception($message, $type = null)
{
throw new Exception($message);
}
/* THE MAGIC BEGINS! */
/**
* SELECT SECTION
*/
/**
* Prepares the query for a select statement
*
* @return \QueryBuilder
*/
public function select()
{
$this->flush();
$columns = func_get_args();
$this->_parts['action'] = self::SQL_SELECT;
$this->columns($columns);
return $this;
}
public function columns($fields = array('*'), $prefix = null)
{
$columns = array();
if ($fields[0] && is_array($fields[0]))
{
$fields = $fields[0];
}
if (!is_array($fields))
{
$fields = $this->_getAsArray($fields);
}
foreach ($fields as $_key => $_field)
{
$_field = '' . $_field . '';
if ($prefix)
{
$_prefix = '`' . $_prefix . '`';
$_field = $prefix . '.' . $_field;
}
if (!is_int($_key))
{
$_field .= ' ' . self::SQL_AS . ' `' . $_key . '`';
}
$columns[] = $_field;
}
$this->_pushInParts(self::COLUMNS, $columns);
return $this;
}
public function from($tables = array(), $columns = null)
{
$this->_joiner(self::FROM, $tables, null, $columns);
return $this;
}
public function join($name, $cond, $columns = null)
{
$this->joinInner($name, $cond, $columns);
return $this;
}
public function joinInner($name, $cond, $columns = null)
{
$this->_joiner(self::INNER_JOIN, $name, $cond, $columns);
return $this;
}
public function joinLeft($name, $cond, $columns = null)
{
$this->_joiner(self::LEFT_JOIN, $name, $cond, $columns);
return $this;
}
public function where($cond, $value = null)
{
$this->_parts[self::WHERE][$this->_whereAmbit]['data'][self::SQL_AND][] = $this->_where($cond, $value);
return $this;
}
public function whereOr($cond, $value = null)
{
$this->_parts[self::WHERE][$this->_whereAmbit]['data'][self::SQL_OR][] = $this->_where($cond, $value);
return $this;
}
public function whereNewAmbit($typeCondition = self::SQL_AND)
{
$this->_whereAmbit++;
$this->_parts[self::WHERE][$this->_whereAmbit]['cond'] = $typeCondition;
return $this;
}
public function group($spec)
{
$this->_pushInParts(self::GROUP, $spec);
return $this;
}
public function having($cond)
{
$this->_parts[self::HAVING][] = $this->_escape($cond);
return $this;
}
public function order($cond)
{
$this->_parts[self::ORDER][] = $this->_escape($cond);
return $this;
}
public function limit($from, $number = null)
{
if ($number === null)
{
//From becomes count
$this->_parts[self::LIMIT_OFFSET] = 0;
$this->_parts[self::LIMIT_COUNT] = $this->_escape($from);
}
else
{
$this->_parts[self::LIMIT_OFFSET] = $this->_escape($from);
$this->_parts[self::LIMIT_COUNT] = $this->_escape($number);
}
return $this;
}
/**
* INSERT SECTION
*/
public function insert()
{
$this->flush();
$values = func_get_args();
$this->_parts['action'] = self::SQL_INSERT;
if ($values[0])
{
$this->into($values[0]);
}
if ($values[1])
{
$this->values($values[1]);
}
return $this;
}
public function into($name = null)
{
if ($name === null)
{
$this->_exception('No ' . self::SQL_INTO . ' statement specified.');
}
if (!is_string($name))
{
$this->_exception('Wrong ' . self::SQL_INTO . ' type passed to method. String expected.');
}
$this->_parts[self::INTO] = $name;
return $this;
}
public function values($fields = array())
{
$columns = array();
$values = array();
if ($fields[0] && is_array($fields[0]))
{
$fields = $fields[0];
}
if (!is_array($fields))
{
$fields = $this->_getAsArray($fields);
}
foreach ($fields as $_key => $_field)
{
if (!is_int($_key))
{
switch ($this->_parts['action'])
{
case self::SQL_INSERT:
$this->_parts[self::VALUES][$this->_escape($_key)] = $this->_escapeAndFormat($_field);
break;
case self::SQL_UPDATE:
$this->_parts[self::VALUES][] = '`' . $this->_escape($_key) . '` = ' . $this->_escapeAndFormat($_field);
break;
}
}
else
{
$this->_exception('Wrong "key" for ' . self::SQL_VALUES . ' construction. No column name specified.');
}
}
return $this;
}
/**
* UPDATE SECTION
*/
public function update()
{
$this->flush();
$values = func_get_args();
$this->_parts['action'] = self::SQL_UPDATE;
if ($values[0])
{
$this->table($values[0]);
}
return $this;
}
public function table($arg)
{
return $this->into($arg);
}
public function set($args = array())
{
return $this->values($args);
}
/*
* DELETE SECTION
*/
public function delete()
{
$this->flush();
$values = func_get_args();
$this->_parts['action'] = self::SQL_DELETE;
if ($values[0])
{
$this->from($values[0]);
}
return $this;
}
/*
* GET QUERY
*/
public function getQuery($returnAndClean = false, $partSeparator = self::CARRY_RETURN)
{
$query = '';
switch ($this->_parts['action'])
{
case self::SQL_SELECT:
$query .= self::SQL_SELECT;
//COLUMNS
if (empty($this->_parts[self::COLUMNS]))
{
$this->_parts[self::COLUMNS][] = self::SQL_WILDCARD;
}
$query .= ' ' . implode(', ', $this->_parts[self::COLUMNS]) . ' ' . $partSeparator;
//FROM and JOINs
$query .= self::SQL_FROM . ' ' . implode(', ', $this->_parts[self::FROM]) . ' ' . $partSeparator;
if ($this->_parts[self::JOIN])
{
$query .= implode( ' ' . $partSeparator, $this->_parts[self::JOIN]) . ' ' . $partSeparator;
}
//WHERE
if ($this->_parts[self::WHERE])
{
$query .= self::SQL_WHERE . ' ';
foreach ($this->_parts[self::WHERE] as $_ambit)
{
$query .= ($_ambit['cond']) ? $_ambit['cond'] . $partSeparator : '';
$query .= '(';
$partialWhere = array();
if ($_ambit['data'][self::SQL_AND])
{
$partialWhere[] .= implode(' ' . self::SQL_AND . ' ', $_ambit['data'][self::SQL_AND]);
}
if ($_ambit['data'][self::SQL_OR])
{
$partialWhere[] .= implode(' ' . self::SQL_OR . ' ', $_ambit['data'][self::SQL_OR]);
}
$query .= implode(' ' . self::SQL_OR . ' ', $partialWhere);
$query .= ') ';
}
$query .= $partSeparator;
}
//GROUP BY
if ($this->_parts[self::GROUP])
{
$query .= self::SQL_GROUP_BY . ' ' . implode(', ', $this->_parts[self::GROUP]) . $partSeparator;
}
//ORDER BY
if ($this->_parts[self::ORDER])
{
$query .= self::SQL_ORDER_BY . ' ' . implode(', ', $this->_parts[self::ORDER]) . $partSeparator;
}
//LIMIT
if ($this->_parts[self::LIMIT_COUNT])
{
$query .= self::SQL_LIMIT . ' ' . $this->_parts[self::LIMIT_OFFSET] . ', ' . $this->_parts[self::LIMIT_COUNT];
}
if ($partSeparator == self::CARRY_RETURN)
{
$query .= self::SQL_QUERY_DIVISOR;
}
break;
case self::SQL_INSERT:
//INSERT INTO
$query = self::SQL_INSERT . ' ' . self::SQL_INTO . $partSeparator;
$query .= '`' . $this->_parts[self::INTO] . '` (`' . implode('`, `', array_keys($this->_parts[self::VALUES])) . '`) ' . $partSeparator;
$query .= self::SQL_VALUES . ' (' . implode(', ', $this->_parts[self::VALUES]) . ')';
if ($partSeparator == self::CARRY_RETURN)
{
$query .= self::SQL_QUERY_DIVISOR;
}
break;
case self::SQL_UPDATE:
//UPDATE
$query = self::SQL_UPDATE . ' `' . $this->_parts[self::INTO] . '` ' . $partSeparator;
$query .= self::SQL_SET . ' ' . implode(', ', $this->_parts[self::VALUES]) . ' ' . $partSeparator;
if ($this->_parts[self::WHERE])
{
$query .= self::SQL_WHERE . ' ';
foreach ($this->_parts[self::WHERE] as $_ambit)
{
$query .= ($_ambit['cond']) ? $_ambit['cond'] . $partSeparator : '';
$query .= '(';
$partialWhere = array();
if ($_ambit['data'][self::SQL_AND])
{
$partialWhere[] .= implode(' ' . self::SQL_AND . ' ', $_ambit['data'][self::SQL_AND]);
}
if ($_ambit['data'][self::SQL_OR])
{
$partialWhere[] .= implode(' ' . self::SQL_OR . ' ', $_ambit['data'][self::SQL_OR]);
}
$query .= implode(' ' . self::SQL_OR . ' ', $partialWhere);
$query .= ') ';
}
}
if ($partSeparator == self::CARRY_RETURN)
{
$query .= self::SQL_QUERY_DIVISOR;
}
break;
case self::SQL_DELETE:
//DELETE
$query = self::SQL_DELETE . ' ' . self::SQL_FROM . ' ' . $this->_parts[self::FROM][0] . ' ' . $partSeparator;
if ($this->_parts[self::WHERE])
{
$query .= self::SQL_WHERE . ' ';
foreach ($this->_parts[self::WHERE] as $_ambit)
{
$query .= ($_ambit['cond']) ? $_ambit['cond'] . $partSeparator : '';
$query .= '(';
$partialWhere = array();
if ($_ambit['data'][self::SQL_AND])
{
$partialWhere[] .= implode(' ' . self::SQL_AND . ' ', $_ambit['data'][self::SQL_AND]);
}
if ($_ambit['data'][self::SQL_OR])
{
$partialWhere[] .= implode(' ' . self::SQL_OR . ' ', $_ambit['data'][self::SQL_OR]);
}
$query .= implode(' ' . self::SQL_OR . ' ', $partialWhere);
$query .= ') ';
}
}
if ($partSeparator == self::CARRY_RETURN)
{
$query .= self::SQL_QUERY_DIVISOR;
}
break;
}
if ($returnAndClean)
{
$this->_lastQuery = $query;
$this->_popParts();
}
return $query;
}
/**
* Cleans the _parts array preparing it
* for a new queryBuilder call
*/
public function flush()
{
if (!empty($this->_parts))
{
$this->_pushParts();
}
unset($this->_parts);
}
public function __toString()
{
return $this->getQuery();
}
/**
*
*
* @param string $cacheId
* @param int $cacheTime
* @return object
*/
public function queryExec($cacheId = NULL, $cacheTime = NULL)
{
$formatting = null;
if ($this->_parts['formatting'])
{
$formatting = $this->_parts['formatting'];
}
$result = $this->_adapter->query($this->getQuery(true), $cacheId, $cacheTime);
switch ($formatting)
{
case 'array':
foreach ($result as &$_value)
{
$_value = (array) $_value;
}
break;
}
return $result;
}
/**
* Returns the last query executed
*
* @return string
*/
public function getLastQuery()
{
return $this->_lastQuery;
}
public function subquery()
{
return $this->getQuery(false, '');
}
/**
* Specifies a format for the receiving data from DB
*
* @param string $type
* @return \QueryBuilder
*/
public function formatAs($type = null)
{
switch ($type)
{
case 'array':
case 'Array':
case 'arr':
$this->_parts['formatting'] = 'array';
break;
default:
$this->_exception('Invalid formatting type in `formatAs`');
break;
}
return $this;
}
public function toArray()
{
return $this->formatAs('array');
}
/*
* TRANSACTIONS
*/
public function begin()
{
return $this->_adapter->query(self::SQL_BEGIN . self::SQL_QUERY_DIVISOR);
}
public function commit()
{
return $this->_adapter->query(self::SQL_COMMIT . self::SQL_QUERY_DIVISOR);
}
public function rollback()
{
return $this->_adapter->query(self::SQL_ROLLBACK . self::SQL_QUERY_DIVISOR);
}
}