-
-
Notifications
You must be signed in to change notification settings - Fork 436
/
Select.php
1389 lines (1263 loc) · 44.2 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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Select
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Db_Adapter_Abstract
*/
#require_once 'Zend/Db/Adapter/Abstract.php';
/**
* @see Zend_Db_Expr
*/
#require_once 'Zend/Db/Expr.php';
/**
* Class for SQL SELECT generation and results.
*
* @category Zend
* @package Zend_Db
* @subpackage Select
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Select
{
const DISTINCT = 'distinct';
const COLUMNS = 'columns';
const FROM = 'from';
const UNION = 'union';
const WHERE = 'where';
const GROUP = 'group';
const HAVING = 'having';
const ORDER = 'order';
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_UNION = 'UNION';
const SQL_UNION_ALL = 'UNION ALL';
const SQL_FROM = 'FROM';
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_FOR_UPDATE = 'FOR UPDATE';
const SQL_AND = 'AND';
const SQL_AS = 'AS';
const SQL_OR = 'OR';
const SQL_ON = 'ON';
const SQL_ASC = 'ASC';
const SQL_DESC = 'DESC';
/**
* Bind variables for query
*
* @var array
*/
protected $_bind = array();
/**
* Zend_Db_Adapter_Abstract object.
*
* @var Zend_Db_Adapter_Abstract
*/
protected $_adapter;
/**
* The initial values for the $_parts array.
* NOTE: It is important for the 'FOR_UPDATE' part to be last to ensure
* meximum compatibility with database adapters.
*
* @var array
*/
protected static $_partsInit = array(
self::DISTINCT => false,
self::COLUMNS => array(),
self::UNION => array(),
self::FROM => array(),
self::WHERE => array(),
self::GROUP => array(),
self::HAVING => array(),
self::ORDER => array(),
self::LIMIT_COUNT => null,
self::LIMIT_OFFSET => null,
self::FOR_UPDATE => false
);
/**
* Specify legal join types.
*
* @var array
*/
protected static $_joinTypes = array(
self::INNER_JOIN,
self::LEFT_JOIN,
self::RIGHT_JOIN,
self::FULL_JOIN,
self::CROSS_JOIN,
self::NATURAL_JOIN,
);
/**
* Specify legal union types.
*
* @var array
*/
protected static $_unionTypes = array(
self::SQL_UNION,
self::SQL_UNION_ALL
);
/**
* The component parts of a SELECT statement.
* Initialized to the $_partsInit array in the constructor.
*
* @var array
*/
protected $_parts = array();
/**
* Tracks which columns are being select from each table and join.
*
* @var array
*/
protected $_tableCols = array();
/**
* List of MySql specific control characters
*
* @var array
*/
protected $_controlCharacters = array(
';',
'--',
'#',
'/*',
'*/',
);
/**
* Class constructor
*
* @param Zend_Db_Adapter_Abstract $adapter
*/
public function __construct(Zend_Db_Adapter_Abstract $adapter)
{
$this->_adapter = $adapter;
$this->_parts = self::$_partsInit;
}
/**
* Get bind variables
*
* @return array
*/
public function getBind()
{
return $this->_bind;
}
/**
* Set bind variables
*
* @param mixed $bind
* @return $this
*/
public function bind($bind)
{
$this->_bind = $bind;
return $this;
}
/**
* Makes the query SELECT DISTINCT.
*
* @param bool $flag Whether or not the SELECT is DISTINCT (default true).
* @return $this This Zend_Db_Select object.
*/
public function distinct($flag = true)
{
$this->_parts[self::DISTINCT] = (bool) $flag;
return $this;
}
/**
* Adds a FROM table and optional columns to the query.
*
* The first parameter $name can be a simple string, in which case the
* correlation name is generated automatically. If you want to specify
* the correlation name, the first parameter must be an associative
* array in which the key is the correlation name, and the value is
* the physical table name. For example, array('alias' => 'table').
* The correlation name is prepended to all columns fetched for this
* table.
*
* The second parameter can be a single string or Zend_Db_Expr object,
* or else an array of strings or Zend_Db_Expr objects.
*
* The first parameter can be null or an empty string, in which case
* no correlation name is generated or prepended to the columns named
* in the second parameter.
*
* @param array|string|Zend_Db_Expr $name The table name or an associative array
* relating correlation name to table name.
* @param array|string|Zend_Db_Expr $cols The columns to select from this table.
* @param string $schema The schema name to specify, if any.
* @return $this This Zend_Db_Select object.
*/
public function from($name, $cols = '*', $schema = null)
{
return $this->_join(self::FROM, $name, null, $cols, $schema);
}
/**
* Specifies the columns used in the FROM clause.
*
* The parameter can be a single string or Zend_Db_Expr object,
* or else an array of strings or Zend_Db_Expr objects.
*
* @param array|string|Zend_Db_Expr $cols The columns to select from this table.
* @param string $correlationName Correlation name of target table. OPTIONAL
* @return $this This Zend_Db_Select object.
*/
public function columns($cols = '*', $correlationName = null)
{
if ($correlationName === null && count($this->_parts[self::FROM])) {
$correlationNameKeys = array_keys($this->_parts[self::FROM]);
$correlationName = current($correlationNameKeys);
}
if (!array_key_exists($correlationName, $this->_parts[self::FROM])) {
/**
* @see Zend_Db_Select_Exception
*/
#require_once 'Zend/Db/Select/Exception.php';
throw new Zend_Db_Select_Exception("No table has been specified for the FROM clause");
}
$this->_tableCols($correlationName, $cols);
return $this;
}
/**
* Adds a UNION clause to the query.
*
* The first parameter has to be an array of Zend_Db_Select or
* sql query strings.
*
* <code>
* $sql1 = $db->select();
* $sql2 = "SELECT ...";
* $select = $db->select()
* ->union(array($sql1, $sql2))
* ->order("id");
* </code>
*
* @param array $select Array of select clauses for the union.
* @return $this This Zend_Db_Select object.
*/
public function union($select = array(), $type = self::SQL_UNION)
{
if (!is_array($select)) {
#require_once 'Zend/Db/Select/Exception.php';
throw new Zend_Db_Select_Exception(
"union() only accepts an array of Zend_Db_Select instances of sql query strings."
);
}
if (!in_array($type, self::$_unionTypes)) {
#require_once 'Zend/Db/Select/Exception.php';
throw new Zend_Db_Select_Exception("Invalid union type '{$type}'");
}
foreach ($select as $target) {
$this->_parts[self::UNION][] = array($target, $type);
}
return $this;
}
/**
* Adds a JOIN table and columns to the query.
*
* The $name and $cols parameters follow the same logic
* as described in the from() method.
*
* @param array|string|Zend_Db_Expr $name The table name.
* @param string $cond Join on this condition.
* @param array|string $cols The columns to select from the joined table.
* @param string $schema The database name to specify, if any.
* @return $this This Zend_Db_Select object.
*/
public function join($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
{
return $this->joinInner($name, $cond, $cols, $schema);
}
/**
* Add an INNER JOIN table and colums to the query
* Rows in both tables are matched according to the expression
* in the $cond argument. The result set is comprised
* of all cases where rows from the left table match
* rows from the right table.
*
* The $name and $cols parameters follow the same logic
* as described in the from() method.
*
* @param array|string|Zend_Db_Expr $name The table name.
* @param string $cond Join on this condition.
* @param array|string $cols The columns to select from the joined table.
* @param string $schema The database name to specify, if any.
* @return $this This Zend_Db_Select object.
*/
public function joinInner($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
{
return $this->_join(self::INNER_JOIN, $name, $cond, $cols, $schema);
}
/**
* Add a LEFT OUTER JOIN table and colums to the query
* All rows from the left operand table are included,
* matching rows from the right operand table included,
* and the columns from the right operand table are filled
* with NULLs if no row exists matching the left table.
*
* The $name and $cols parameters follow the same logic
* as described in the from() method.
*
* @param array|string|Zend_Db_Expr $name The table name.
* @param string $cond Join on this condition.
* @param array|string $cols The columns to select from the joined table.
* @param string $schema The database name to specify, if any.
* @return $this This Zend_Db_Select object.
*/
public function joinLeft($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
{
return $this->_join(self::LEFT_JOIN, $name, $cond, $cols, $schema);
}
/**
* Add a RIGHT OUTER JOIN table and colums to the query.
* Right outer join is the complement of left outer join.
* All rows from the right operand table are included,
* matching rows from the left operand table included,
* and the columns from the left operand table are filled
* with NULLs if no row exists matching the right table.
*
* The $name and $cols parameters follow the same logic
* as described in the from() method.
*
* @param array|string|Zend_Db_Expr $name The table name.
* @param string $cond Join on this condition.
* @param array|string $cols The columns to select from the joined table.
* @param string $schema The database name to specify, if any.
* @return $this This Zend_Db_Select object.
*/
public function joinRight($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
{
return $this->_join(self::RIGHT_JOIN, $name, $cond, $cols, $schema);
}
/**
* Add a FULL OUTER JOIN table and colums to the query.
* A full outer join is like combining a left outer join
* and a right outer join. All rows from both tables are
* included, paired with each other on the same row of the
* result set if they satisfy the join condition, and otherwise
* paired with NULLs in place of columns from the other table.
*
* The $name and $cols parameters follow the same logic
* as described in the from() method.
*
* @param array|string|Zend_Db_Expr $name The table name.
* @param string $cond Join on this condition.
* @param array|string $cols The columns to select from the joined table.
* @param string $schema The database name to specify, if any.
* @return $this This Zend_Db_Select object.
*/
public function joinFull($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
{
return $this->_join(self::FULL_JOIN, $name, $cond, $cols, $schema);
}
/**
* Add a CROSS JOIN table and colums to the query.
* A cross join is a cartesian product; there is no join condition.
*
* The $name and $cols parameters follow the same logic
* as described in the from() method.
*
* @param array|string|Zend_Db_Expr $name The table name.
* @param array|string $cols The columns to select from the joined table.
* @param string $schema The database name to specify, if any.
* @return $this This Zend_Db_Select object.
*/
public function joinCross($name, $cols = self::SQL_WILDCARD, $schema = null)
{
return $this->_join(self::CROSS_JOIN, $name, null, $cols, $schema);
}
/**
* Add a NATURAL JOIN table and colums to the query.
* A natural join assumes an equi-join across any column(s)
* that appear with the same name in both tables.
* Only natural inner joins are supported by this API,
* even though SQL permits natural outer joins as well.
*
* The $name and $cols parameters follow the same logic
* as described in the from() method.
*
* @param array|string|Zend_Db_Expr $name The table name.
* @param array|string $cols The columns to select from the joined table.
* @param string $schema The database name to specify, if any.
* @return $this This Zend_Db_Select object.
*/
public function joinNatural($name, $cols = self::SQL_WILDCARD, $schema = null)
{
return $this->_join(self::NATURAL_JOIN, $name, null, $cols, $schema);
}
/**
* Adds a WHERE condition to the query by AND.
*
* If a value is passed as the second param, it will be quoted
* and replaced into the condition wherever a question-mark
* appears. Array values are quoted and comma-separated.
*
* <code>
* // simplest but non-secure
* $select->where("id = $id");
*
* // secure (ID is quoted but matched anyway)
* $select->where('id = ?', $id);
*
* // alternatively, with named binding
* $select->where('id = :id');
* </code>
*
* Note that it is more correct to use named bindings in your
* queries for values other than strings. When you use named
* bindings, don't forget to pass the values when actually
* making a query:
*
* <code>
* $db->fetchAll($select, array('id' => 5));
* </code>
*
* @param string $cond The WHERE condition.
* @param mixed $value OPTIONAL The value to quote into the condition.
* @param int $type OPTIONAL The type of the given value
* @return $this This Zend_Db_Select object.
*/
public function where($cond, $value = null, $type = null)
{
$this->_parts[self::WHERE][] = $this->_where($cond, $value, $type, true);
return $this;
}
/**
* Adds a WHERE condition to the query by OR.
*
* Otherwise identical to where().
*
* @param string $cond The WHERE condition.
* @param mixed $value OPTIONAL The value to quote into the condition.
* @param int $type OPTIONAL The type of the given value
* @return $this This Zend_Db_Select object.
*
* @see where()
*/
public function orWhere($cond, $value = null, $type = null)
{
$this->_parts[self::WHERE][] = $this->_where($cond, $value, $type, false);
return $this;
}
/**
* Adds grouping to the query.
*
* @param array|string $spec The column(s) to group by.
* @return $this This Zend_Db_Select object.
*/
public function group($spec)
{
if (!is_array($spec)) {
$spec = array($spec);
}
foreach ($spec as $val) {
if (preg_match('/\(.*\)/', (string) $val)
&& !$this->isContainControlCharacters((string) $val)
) {
$val = new Zend_Db_Expr($val);
}
$this->_parts[self::GROUP][] = $val;
}
return $this;
}
/**
* Check is expression contains some MySql control characters
*
* @param string $expression
* @return bool
*/
public function isContainControlCharacters($expression) {
foreach ($this->_controlCharacters as $controlChar) {
if (strpos($expression, $controlChar) !== false) {
return true;
}
}
return false;
}
/**
* Adds a HAVING condition to the query by AND.
*
* If a value is passed as the second param, it will be quoted
* and replaced into the condition wherever a question-mark
* appears. See {@link where()} for an example
*
* @param string $cond The HAVING condition.
* @param mixed $value OPTIONAL The value to quote into the condition.
* @param int $type OPTIONAL The type of the given value
* @return $this This Zend_Db_Select object.
*/
public function having($cond, $value = null, $type = null)
{
if ($value !== null) {
$cond = $this->_adapter->quoteInto($cond, $value, $type);
}
if ($this->_parts[self::HAVING]) {
$this->_parts[self::HAVING][] = self::SQL_AND . " ($cond)";
} else {
$this->_parts[self::HAVING][] = "($cond)";
}
return $this;
}
/**
* Adds a HAVING condition to the query by OR.
*
* Otherwise identical to orHaving().
*
* @param string $cond The HAVING condition.
* @param mixed $value OPTIONAL The value to quote into the condition.
* @param int $type OPTIONAL The type of the given value
* @return $this This Zend_Db_Select object.
*
* @see having()
*/
public function orHaving($cond, $value = null, $type = null)
{
if ($value !== null) {
$cond = $this->_adapter->quoteInto($cond, $value, $type);
}
if ($this->_parts[self::HAVING]) {
$this->_parts[self::HAVING][] = self::SQL_OR . " ($cond)";
} else {
$this->_parts[self::HAVING][] = "($cond)";
}
return $this;
}
/**
* Adds a row order to the query.
*
* @param mixed $spec The column(s) and direction to order by.
* @return $this This Zend_Db_Select object.
*/
public function order($spec)
{
if (!is_array($spec)) {
$spec = array($spec);
}
// force 'ASC' or 'DESC' on each order spec, default is ASC.
foreach ($spec as $val) {
if ($val instanceof Zend_Db_Expr) {
$expr = $val->__toString();
if (empty($expr)) {
continue;
}
$this->_parts[self::ORDER][] = $val;
} else {
if (empty($val)) {
continue;
}
$direction = self::SQL_ASC;
if (preg_match('/(.*\W)(' . self::SQL_ASC . '|' . self::SQL_DESC . ')\b/si', $val, $matches)) {
$val = trim($matches[1]);
$direction = $matches[2];
}
if (preg_match('/\(.*\)/', (string) $val)
&& !$this->isContainControlCharacters((string) $val)
) {
$val = new Zend_Db_Expr($val);
}
$this->_parts[self::ORDER][] = array($val, $direction);
}
}
return $this;
}
/**
* Sets a limit count and offset to the query.
*
* @param int $count OPTIONAL The number of rows to return.
* @param int $offset OPTIONAL Start returning after this many rows.
* @return $this This Zend_Db_Select object.
*/
public function limit($count = null, $offset = null)
{
$this->_parts[self::LIMIT_COUNT] = (int) $count;
$this->_parts[self::LIMIT_OFFSET] = (int) $offset;
return $this;
}
/**
* Sets the limit and count by page number.
*
* @param int $page Limit results to this page number.
* @param int $rowCount Use this many rows per page.
* @return $this This Zend_Db_Select object.
*/
public function limitPage($page, $rowCount)
{
$page = ($page > 0) ? $page : 1;
$rowCount = ($rowCount > 0) ? $rowCount : 1;
$this->_parts[self::LIMIT_COUNT] = (int) $rowCount;
$this->_parts[self::LIMIT_OFFSET] = (int) $rowCount * ($page - 1);
return $this;
}
/**
* Makes the query SELECT FOR UPDATE.
*
* @param bool $flag Whether or not the SELECT is FOR UPDATE (default true).
* @return $this This Zend_Db_Select object.
*/
public function forUpdate($flag = true)
{
$this->_parts[self::FOR_UPDATE] = (bool) $flag;
return $this;
}
/**
* Get part of the structured information for the current query.
*
* @param string $part
* @return mixed
* @throws Zend_Db_Select_Exception
*/
public function getPart($part)
{
$part = strtolower($part);
if (!array_key_exists($part, $this->_parts)) {
#require_once 'Zend/Db/Select/Exception.php';
throw new Zend_Db_Select_Exception("Invalid Select part '$part'");
}
return $this->_parts[$part];
}
/**
* Executes the current select object and returns the result
*
* @param integer $fetchMode OPTIONAL
* @param mixed $bind An array of data to bind to the placeholders.
* @return Zend_Db_Statement
*/
public function query($fetchMode = null, $bind = array())
{
if (!empty($bind)) {
$this->bind($bind);
}
$stmt = $this->_adapter->query($this);
if ($fetchMode == null) {
$fetchMode = $this->_adapter->getFetchMode();
}
$stmt->setFetchMode($fetchMode);
return $stmt;
}
/**
* Converts this object to an SQL SELECT string.
*
* @return string|null This object as a SELECT string. (or null if a string cannot be produced.)
*/
public function assemble()
{
$sql = self::SQL_SELECT;
foreach (array_keys(self::$_partsInit) as $part) {
$method = '_render' . ucfirst($part);
if (method_exists($this, $method)) {
$sql = $this->$method($sql);
}
}
return $sql;
}
/**
* Clear parts of the Select object, or an individual part.
*
* @param string $part OPTIONAL
* @return $this
*/
public function reset($part = null)
{
if ($part == null) {
$this->_parts = self::$_partsInit;
} elseif (array_key_exists($part, self::$_partsInit)) {
$this->_parts[$part] = self::$_partsInit[$part];
}
return $this;
}
/**
* Gets the Zend_Db_Adapter_Abstract for this
* particular Zend_Db_Select object.
*
* @return Zend_Db_Adapter_Abstract
*/
public function getAdapter()
{
return $this->_adapter;
}
/**
* Populate the {@link $_parts} 'join' key
*
* Does the dirty work of populating the join key.
*
* The $name and $cols parameters follow the same logic
* as described in the from() method.
*
* @param null|string $type Type of join; inner, left, and null are currently supported
* @param array|string|Zend_Db_Expr $name Table name
* @param string $cond Join on this condition
* @param array|string $cols The columns to select from the joined table
* @param string $schema The database name to specify, if any.
* @return $this This Zend_Db_Select object
* @throws Zend_Db_Select_Exception
*/
protected function _join($type, $name, $cond, $cols, $schema = null)
{
if (!in_array($type, self::$_joinTypes) && $type != self::FROM) {
/**
* @see Zend_Db_Select_Exception
*/
#require_once 'Zend/Db/Select/Exception.php';
throw new Zend_Db_Select_Exception("Invalid join type '$type'");
}
if (count($this->_parts[self::UNION])) {
#require_once 'Zend/Db/Select/Exception.php';
throw new Zend_Db_Select_Exception("Invalid use of table with " . self::SQL_UNION);
}
if (empty($name)) {
$correlationName = $tableName = '';
} elseif (is_array($name)) {
// Must be array($correlationName => $tableName) or array($ident, ...)
foreach ($name as $_correlationName => $_tableName) {
if (is_string($_correlationName)) {
// We assume the key is the correlation name and value is the table name
$tableName = $_tableName;
$correlationName = $_correlationName;
} else {
// We assume just an array of identifiers, with no correlation name
$tableName = $_tableName;
$correlationName = $this->_uniqueCorrelation($tableName);
}
break;
}
} elseif ($name instanceof Zend_Db_Expr|| $name instanceof Zend_Db_Select) {
$tableName = $name;
$correlationName = $this->_uniqueCorrelation('t');
} elseif (preg_match('/^(.+)\s+AS\s+(.+)$/i', $name, $m)) {
$tableName = $m[1];
$correlationName = $m[2];
} else {
$tableName = $name;
$correlationName = $this->_uniqueCorrelation($tableName);
}
// Schema from table name overrides schema argument
if (!is_object($tableName) && false !== strpos($tableName, '.')) {
list($schema, $tableName) = explode('.', $tableName);
}
$lastFromCorrelationName = null;
if (!empty($correlationName)) {
if (array_key_exists($correlationName, $this->_parts[self::FROM])) {
/**
* @see Zend_Db_Select_Exception
*/
#require_once 'Zend/Db/Select/Exception.php';
throw new Zend_Db_Select_Exception(
"You cannot define a correlation name '$correlationName' more than once"
);
}
if ($type == self::FROM) {
// append this from after the last from joinType
$tmpFromParts = $this->_parts[self::FROM];
$this->_parts[self::FROM] = array();
// move all the froms onto the stack
while ($tmpFromParts) {
$currentCorrelationName = key($tmpFromParts);
if ($tmpFromParts[$currentCorrelationName]['joinType'] != self::FROM) {
break;
}
$lastFromCorrelationName = $currentCorrelationName;
$this->_parts[self::FROM][$currentCorrelationName] = array_shift($tmpFromParts);
}
} else {
$tmpFromParts = array();
}
$this->_parts[self::FROM][$correlationName] = array(
'joinType' => $type,
'schema' => $schema,
'tableName' => $tableName,
'joinCondition' => $cond
);
while ($tmpFromParts) {
$currentCorrelationName = key($tmpFromParts);
$this->_parts[self::FROM][$currentCorrelationName] = array_shift($tmpFromParts);
}
}
// add to the columns from this joined table
if ($type == self::FROM && $lastFromCorrelationName == null) {
$lastFromCorrelationName = true;
}
$this->_tableCols($correlationName, $cols, $lastFromCorrelationName);
return $this;
}
/**
* Handle JOIN... USING... syntax
*
* This is functionality identical to the existing JOIN methods, however
* the join condition can be passed as a single column name. This method
* then completes the ON condition by using the same field for the FROM
* table and the JOIN table.
*
* <code>
* $select = $db->select()->from('table1')
* ->joinUsing('table2', 'column1');
*
* // SELECT * FROM table1 JOIN table2 ON table1.column1 = table2.column2
* </code>
*
* These joins are called by the developer simply by adding 'Using' to the
* method name. E.g.
* * joinUsing
* * joinInnerUsing
* * joinFullUsing
* * joinRightUsing
* * joinLeftUsing
*
* @return $this This Zend_Db_Select object.
*/
public function _joinUsing($type, $name, $cond, $cols = '*', $schema = null)
{
if (empty($this->_parts[self::FROM])) {
#require_once 'Zend/Db/Select/Exception.php';
throw new Zend_Db_Select_Exception("You can only perform a joinUsing after specifying a FROM table");
}
$join = $this->_adapter->quoteIdentifier(key($this->_parts[self::FROM]), true);
$from = $this->_adapter->quoteIdentifier($this->_uniqueCorrelation($name), true);
$joinCond = array();
foreach ((array)$cond as $fieldName) {
$cond1 = $from . '.' . $fieldName;
$cond2 = $join . '.' . $fieldName;
$joinCond[] = $cond1 . ' = ' . $cond2;
}
$cond = implode(' '.self::SQL_AND.' ', $joinCond);
return $this->_join($type, $name, $cond, $cols, $schema);
}
/**
* Generate a unique correlation name
*
* @param string|array $name A qualified identifier.
* @return string A unique correlation name.
*/
private function _uniqueCorrelation($name)
{
if (is_array($name)) {
$k = key($name);
$c = is_string($k) ? $k : end($name);
} else {
// Extract just the last name of a qualified table name
$dot = strrpos($name,'.');
$c = ($dot === false) ? $name : substr($name, $dot+1);
}
for ($i = 2; array_key_exists($c, $this->_parts[self::FROM]); ++$i) {
$c = $name . '_' . (string) $i;
}
return $c;
}
/**
* Adds to the internal table-to-column mapping array.
*
* @param string $tbl The table/join the columns come from.
* @param array|string $cols The list of columns; preferably as
* an array, but possibly as a string containing one column.
* @param bool|string True if it should be prepended, a correlation name if it should be inserted
* @return void
*/
protected function _tableCols($correlationName, $cols, $afterCorrelationName = null)
{
if (!is_array($cols)) {
$cols = array($cols);
}
if ($correlationName == null) {
$correlationName = '';
}
$columnValues = array();
foreach (array_filter($cols) as $alias => $col) {
$currentCorrelationName = $correlationName;
if (is_string($col)) {
// Check for a column matching "<column> AS <alias>" and extract the alias name
if (preg_match('/^(.+)\s+' . self::SQL_AS . '\s+(.+)$/i', $col, $m)) {
$col = $m[1];
$alias = $m[2];
}
// Check for columns that look like functions and convert to Zend_Db_Expr
if (preg_match('/\(.*\)/', (string) $col)
&& !$this->isContainControlCharacters((string) $col)
) {
$col = new Zend_Db_Expr($col);
} elseif (preg_match('/(.+)\.(.+)/', $col, $m)) {
$currentCorrelationName = $m[1];
$col = $m[2];
}
}
$columnValues[] = array($currentCorrelationName, $col, is_string($alias) ? $alias : null);
}
if ($columnValues) {
// should we attempt to prepend or insert these values?
if ($afterCorrelationName === true || is_string($afterCorrelationName)) {
$tmpColumns = $this->_parts[self::COLUMNS];
$this->_parts[self::COLUMNS] = array();
} else {
$tmpColumns = array();
}
// find the correlation name to insert after