-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathSelect.php
906 lines (835 loc) · 19.7 KB
/
Select.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
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
<?php
/**
*
* This file is part of Aura for PHP.
*
* @license http://opensource.org/licenses/bsd-license.php BSD
*
*/
namespace Aura\SqlQuery\Common;
use Aura\SqlQuery\AbstractQuery;
use Aura\SqlQuery\Exception;
/**
*
* An object for SELECT queries.
*
* @package Aura.SqlQuery
*
*/
class Select extends AbstractQuery implements SelectInterface
{
/**
*
* An array of union SELECT statements.
*
* @var array
*
*/
protected $union = array();
/**
*
* Is this a SELECT FOR UPDATE?
*
* @var
*
*/
protected $for_update = false;
/**
*
* The columns to be selected.
*
* @var array
*
*/
protected $cols = array();
/**
*
* Select from these tables; includes JOIN clauses.
*
* @var array
*
*/
protected $from = array();
/**
*
* The current key in the `$from` array.
*
* @var int
*
*/
protected $from_key = -1;
/**
*
* GROUP BY these columns.
*
* @var array
*
*/
protected $group_by = array();
/**
*
* The list of HAVING conditions.
*
* @var array
*
*/
protected $having = array();
/**
*
* The page number to select.
*
* @var int
*
*/
protected $page = 0;
/**
*
* The number of rows per page.
*
* @var int
*
*/
protected $paging = 10;
/**
*
* Tracks table references to avoid duplicate identifiers.
*
* @var array
*
*/
protected $table_refs = array();
/**
*
* Returns this query object as an SQL statement string.
*
* @return string An SQL statement string.
*
*/
public function getStatement()
{
$union = '';
if ($this->union) {
$union = implode(PHP_EOL, $this->union) . PHP_EOL;
}
return $union . $this->build();
}
/**
*
* Sets the number of rows per page.
*
* @param int $paging The number of rows to page at.
*
* @return self
*
*/
public function setPaging($paging)
{
$this->paging = (int) $paging;
if ($this->page) {
$this->setPagingLimitOffset();
}
return $this;
}
/**
*
* Gets the number of rows per page.
*
* @return int The number of rows per page.
*
*/
public function getPaging()
{
return $this->paging;
}
/**
*
* Makes the select FOR UPDATE (or not).
*
* @param bool $enable Whether or not the SELECT is FOR UPDATE (default
* true).
*
* @return self
*
*/
public function forUpdate($enable = true)
{
$this->for_update = (bool) $enable;
}
/**
*
* Makes the select DISTINCT (or not).
*
* @param bool $enable Whether or not the SELECT is DISTINCT (default
* true).
*
* @return self
*
*/
public function distinct($enable = true)
{
$this->setFlag('DISTINCT', $enable);
return $this;
}
/**
*
* Adds columns to the query.
*
* Multiple calls to cols() will append to the list of columns, not
* overwrite the previous columns.
*
* @param array $cols The column(s) to add to the query. The elements can be
* any mix of these: `array("col", "col AS alias", "col" => "alias")`
*
* @return self
*
*/
public function cols(array $cols)
{
foreach ($cols as $key => $val) {
$this->addCol($key, $val);
}
return $this;
}
/**
*
* Adds a column and alias to the columns to be selected.
*
* @param mixed $key If an integer, ignored. Otherwise, the column to be
* added.
*
* @param mixed $val If $key was an integer, the column to be added;
* otherwise, the column alias.
*
* @return null
*
*/
protected function addCol($key, $val)
{
if (is_string($key)) {
// [col => alias]
$this->cols[$val] = $key;
} else {
$this->addColWithAlias($val);
}
}
/**
*
* Adds a column with an alias to the columns to be selected.
*
* @param string $spec The column specification: "col alias",
* "col AS alias", or something else entirely.
*
* @return null
*
*/
protected function addColWithAlias($spec)
{
$parts = explode(' ', $spec);
$count = count($parts);
if ($count == 2) {
// "col alias"
$this->cols[$parts[1]] = $parts[0];
} elseif ($count == 3 && strtoupper($parts[1]) == 'AS') {
// "col AS alias"
$this->cols[$parts[2]] = $parts[0];
} else {
// no recognized alias
$this->cols[] = $spec;
}
}
/**
*
* Tracks table references.
*
* @param string $type FROM, JOIN, etc.
*
* @param string $spec The table and alias name.
*
* @return null
*
* @throws Exception when the reference has already been used.
*
*/
protected function addTableRef($type, $spec)
{
$name = $spec;
$pos = strripos($name, ' AS ');
if ($pos !== false) {
$name = trim(substr($name, $pos + 4));
}
if (isset($this->table_refs[$name])) {
$used = $this->table_refs[$name];
throw new Exception("Cannot reference '$type $spec' after '$used'");
}
$this->table_refs[$name] = "$type $spec";
}
/**
*
* Adds a FROM element to the query; quotes the table name automatically.
*
* @param string $spec The table specification; "foo" or "foo AS bar".
*
* @return self
*
*/
public function from($spec)
{
$this->addTableRef('FROM', $spec);
return $this->addFrom($this->quoter->quoteName($spec));
}
/**
*
* Adds a raw unquoted FROM element to the query; useful for adding FROM
* elements that are functions.
*
* @param string $spec The table specification, e.g. "function_name()".
*
* @return self
*
*/
public function fromRaw($spec)
{
$this->addTableRef('FROM', $spec);
return $this->addFrom($spec);
}
/**
*
* Adds to the $from property and increments the key count.
*
* @param string $spec The table specification.
*
* @return self
*
*/
protected function addFrom($spec)
{
$this->from[] = array($spec);
$this->from_key ++;
return $this;
}
/**
*
* Adds an aliased sub-select to the query.
*
* @param string|Select $spec If a Select object, use as the sub-select;
* if a string, the sub-select string.
*
* @param string $name The alias name for the sub-select.
*
* @return self
*
*/
public function fromSubSelect($spec, $name)
{
$this->addTableRef('FROM (SELECT ...) AS', $name);
$spec = $this->subSelect($spec, ' ');
$name = $this->quoter->quoteName($name);
$this->from[] = array("({$spec} ) AS $name");
$this->from_key ++;
return $this;
}
/**
*
* Formats a sub-SELECT statement, binding values from a Select object as
* needed.
*
* @param string|SelectInterface $spec A sub-SELECT specification.
*
* @param string $indent Indent each line with this string.
*
* @return string The sub-SELECT string.
*
*/
protected function subSelect($spec, $indent)
{
if ($spec instanceof SelectInterface) {
$this->bindValues($spec->getBindValues());
}
return PHP_EOL . $indent
. ltrim(preg_replace('/^/m', $indent, (string) $spec))
. PHP_EOL;
}
/**
*
* Adds a JOIN table and columns to the query.
*
* @param string $join The join type: inner, left, natural, etc.
*
* @param string $spec The table specification; "foo" or "foo AS bar".
*
* @param string $cond Join on this condition.
*
* @param array $bind Values to bind to ?-placeholders in the condition.
*
* @return self
*
* @throws Exception
*
*/
public function join($join, $spec, $cond = null, array $bind = array())
{
if (! $this->from) {
throw new Exception('Cannot join() without from() first.');
}
$join = strtoupper(ltrim("$join JOIN"));
$this->addTableRef($join, $spec);
$spec = $this->quoter->quoteName($spec);
$cond = $this->fixJoinCondition($cond, $bind);
$this->from[$this->from_key][] = rtrim("$join $spec $cond");
return $this;
}
/**
*
* Fixes a JOIN condition to quote names in the condition and prefix it
* with a condition type ('ON' is the default and 'USING' is recognized).
*
* @param string $cond Join on this condition.
*
* @param array $bind Values to bind to ?-placeholders in the condition.
*
* @return string
*
*/
protected function fixJoinCondition($cond, array $bind)
{
if (! $cond) {
return;
}
$cond = $this->quoter->quoteNamesIn($cond);
$cond = $this->rebuildCondAndBindValues($cond, $bind);
if (strtoupper(substr(ltrim($cond), 0, 3)) == 'ON ') {
return $cond;
}
if (strtoupper(substr(ltrim($cond), 0, 6)) == 'USING ') {
return $cond;
}
return 'ON ' . $cond;
}
/**
*
* Adds a INNER JOIN table and columns to the query.
*
* @param string $spec The table specification; "foo" or "foo AS bar".
*
* @param string $cond Join on this condition.
*
* @param array $bind Values to bind to ?-placeholders in the condition.
*
* @return self
*
* @throws Exception
*
*/
public function innerJoin($spec, $cond = null, array $bind = array())
{
return $this->join('INNER', $spec, $cond, $bind);
}
/**
*
* Adds a LEFT JOIN table and columns to the query.
*
* @param string $spec The table specification; "foo" or "foo AS bar".
*
* @param string $cond Join on this condition.
*
* @param array $bind Values to bind to ?-placeholders in the condition.
*
* @return self
*
* @throws Exception
*
*/
public function leftJoin($spec, $cond = null, array $bind = array())
{
return $this->join('LEFT', $spec, $cond, $bind);
}
/**
*
* Adds a JOIN to an aliased subselect and columns to the query.
*
* @param string $join The join type: inner, left, natural, etc.
*
* @param string|Select $spec If a Select
* object, use as the sub-select; if a string, the sub-select
* command string.
*
* @param string $name The alias name for the sub-select.
*
* @param string $cond Join on this condition.
*
* @param array $bind Values to bind to ?-placeholders in the condition.
*
* @return self
*
* @throws Exception
*
*/
public function joinSubSelect($join, $spec, $name, $cond = null, array $bind = array())
{
if (! $this->from) {
throw new Exception('Cannot join() without from() first.');
}
$join = strtoupper(ltrim("$join JOIN"));
$this->addTableRef("$join (SELECT ...) AS", $name);
$spec = $this->subSelect($spec, ' ');
$name = $this->quoter->quoteName($name);
$cond = $this->fixJoinCondition($cond, $bind);
$text = rtrim("$join ($spec ) AS $name $cond");
$this->from[$this->from_key][] = ' ' . $text ;
return $this;
}
/**
*
* Adds grouping to the query.
*
* @param array $spec The column(s) to group by.
*
* @return self
*
*/
public function groupBy(array $spec)
{
foreach ($spec as $col) {
$this->group_by[] = $this->quoter->quoteNamesIn($col);
}
return $this;
}
/**
*
* Adds a HAVING condition to the query by AND. If the condition has
* ?-placeholders, additional arguments to the method will be bound to
* those placeholders sequentially.
*
* @param string $cond The HAVING condition.
*
* @return self
*
*/
public function having($cond)
{
$this->addClauseCondWithBind('having', 'AND', func_get_args());
return $this;
}
/**
*
* Adds a HAVING condition to the query by AND. If the condition has
* ?-placeholders, additional arguments to the method will be bound to
* those placeholders sequentially.
*
* @param string $cond The HAVING condition.
*
* @return self
*
* @see having()
*
*/
public function orHaving($cond)
{
$this->addClauseCondWithBind('having', 'OR', func_get_args());
return $this;
}
/**
*
* Sets the limit and count by page number.
*
* @param int $page Limit results to this page number.
*
* @return self
*
*/
public function page($page)
{
$this->page = (int) $page;
$this->setPagingLimitOffset();
return $this;
}
/**
*
* Updates the limit and offset values when changing pagination.
*
* @return null
*
*/
protected function setPagingLimitOffset()
{
$this->limit = 0;
$this->offset = 0;
if ($this->page) {
$this->limit = $this->paging;
$this->offset = $this->paging * ($this->page - 1);
}
}
/**
*
* Returns the page number being selected.
*
* @return int
*
*/
public function getPage()
{
return $this->page;
}
/**
*
* Takes the current select properties and retains them, then sets
* UNION for the next set of properties.
*
* @return self
*
*/
public function union()
{
$this->union[] = $this->build() . PHP_EOL . 'UNION';
$this->reset();
return $this;
}
/**
*
* Takes the current select properties and retains them, then sets
* UNION ALL for the next set of properties.
*
* @return self
*
*/
public function unionAll()
{
$this->union[] = $this->build() . PHP_EOL . 'UNION ALL';
$this->reset();
return $this;
}
/**
*
* Returns the LIMIT value.
*
* @return int
*
*/
public function getLimit()
{
return $this->limit;
}
/**
*
* Returns the OFFSET value.
*
* @return int
*
*/
public function getOffset()
{
return $this->offset;
}
/**
*
* Clears the current select properties; generally used after adding a
* union.
*
* @return null
*
*/
protected function reset()
{
$this->resetFlags();
$this->cols = array();
$this->from = array();
$this->from_key = -1;
$this->where = array();
$this->group_by = array();
$this->having = array();
$this->order_by = array();
$this->limit = 0;
$this->offset = 0;
$this->page = 0;
$this->for_update = false;
}
/**
*
* Builds this query object into a string.
*
* @return string
*
*/
protected function build()
{
return 'SELECT'
. $this->buildFlags()
. $this->buildCols()
. $this->buildFrom() // includes JOIN
. $this->buildWhere()
. $this->buildGroupBy()
. $this->buildHaving()
. $this->buildOrderBy()
. $this->buildLimit()
. $this->buildForUpdate();
}
/**
*
* Builds the columns clause.
*
* @return string
*
* @throws Exception when there are no columns in the SELECT.
*
*/
protected function buildCols()
{
if (! $this->cols) {
throw new Exception('No columns in the SELECT.');
}
$cols = array();
foreach ($this->cols as $key => $val) {
if (is_int($key)) {
$cols[] = $this->quoter->quoteNamesIn($val);
} else {
$cols[] = $this->quoter->quoteNamesIn("$val AS $key");
}
}
return $this->indentCsv($cols);
}
/**
*
* Builds the FROM clause.
*
* @return string
*
*/
protected function buildFrom()
{
if (! $this->from) {
return ''; // not applicable
}
$refs = array();
foreach ($this->from as $from) {
$refs[] = implode(PHP_EOL, $from);
}
return PHP_EOL . 'FROM' . $this->indentCsv($refs);
}
/**
*
* Builds the GROUP BY clause.
*
* @return string
*
*/
protected function buildGroupBy()
{
if (! $this->group_by) {
return ''; // not applicable
}
return PHP_EOL . 'GROUP BY' . $this->indentCsv($this->group_by);
}
/**
*
* Builds the HAVING clause.
*
* @return string
*
*/
protected function buildHaving()
{
if (! $this->having) {
return ''; // not applicable
}
return PHP_EOL . 'HAVING' . $this->indent($this->having);
}
/**
*
* Builds the FOR UPDATE clause.
*
* @return string
*
*/
protected function buildForUpdate()
{
if (! $this->for_update) {
return ''; // not applicable
}
return PHP_EOL . 'FOR UPDATE';
}
/**
*
* Adds a WHERE condition to the query by AND. If the condition has
* ?-placeholders, additional arguments to the method will be bound to
* those placeholders sequentially.
*
* @param string $cond The WHERE condition.
* @param mixed ...$bind arguments to bind to placeholders
*
* @return self
*
*/
public function where($cond)
{
$this->addWhere('AND', func_get_args());
return $this;
}
/**
*
* Adds a WHERE condition to the query by OR. If the condition has
* ?-placeholders, additional arguments to the method will be bound to
* those placeholders sequentially.
*
* @param string $cond The WHERE condition.
* @param mixed ...$bind arguments to bind to placeholders
*
* @return self
*
* @see where()
*
*/
public function orWhere($cond)
{
$this->addWhere('OR', func_get_args());
return $this;
}
/**
*
* Sets a limit count on the query.
*
* @param int $limit The number of rows to select.
*
* @return self
*
*/
public function limit($limit)
{
$this->limit = (int) $limit;
if ($this->page) {
$this->page = 0;
$this->offset = 0;
}
return $this;
}
/**
*
* Sets a limit offset on the query.
*
* @param int $offset Start returning after this many rows.
*
* @return self
*
*/
public function offset($offset)
{
$this->offset = (int) $offset;
if ($this->page) {
$this->page = 0;
$this->limit = 0;
}
return $this;
}
/**
*
* Adds a column order to the query.
*
* @param array $spec The columns and direction to order by.
*
* @return self
*
*/
public function orderBy(array $spec)
{
return $this->addOrderBy($spec);
}
}