This repository has been archived by the owner on Jul 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 83
/
dsql.php
1951 lines (1816 loc) · 51.9 KB
/
dsql.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 // vim:ts=4:sw=4:et:fdm=marker
/**
This file is part of Agile Toolkit 4 http://agiletoolkit.org/
(c) 2008-2013 Agile Toolkit Limited <info@agiletoolkit.org>
Distributed under Affero General Public License v3 and
commercial license.
See LICENSE or LICENSE_COM for more information
*/
/**
* Implementation of SQL Query Abstraction Layer for Agile Toolkit
*
* @link http://agiletoolkit.org/doc/dsql
*/
class DB_dsql extends AbstractModel implements Iterator {
/**
* Data accumulated by calling Definition methods, which is then
* used when rendering
*/
public $args=array();
/** List of PDO parametical arguments for a query. Used only during rendering. */
public $params=array();
/** Manually-specified params */
public $extra_params=array();
/** PDO Statement, if query is prepared. Used by iterator */
public $stmt=null;
/** Expression to use when converting to string */
public $template=null;
/**
* You can switch mode with select(), insert(), update() commands.
* Mode is initialized to "select" by default
*/
public $mode=null;
/** Used to determine main table. */
public $main_table=null;
/** If no fields are defined, this field is used */
public $default_field='*';
public $default_exception='Exception_DB';
/** call $q->debug() to turn on debugging or $q->debug(false) to turn ir off. */
public $debug = false;
/** prefix for all parameteric variables: a, a_2, a_3, etc */
public $param_base='a';
/** When you convert this object to string, the following happens: */
public $output_mode='getOne';
/** Backtics are added around all fields. Set this to blank string to avoid */
public $bt='`';
/**
* Templates are used to construct most common queries. Templates may be
* changed in vendor-specific implementation of dsql (extending this class)
*/
public $sql_templates=array(
'select'=>"select [options] [field] [from] [table] [join] [where] [group] [having] [order] [limit]",
'insert'=>"insert [options_insert] into [table_noalias] ([set_fields]) values ([set_values])",
'replace'=>"replace [options_replace] into [table_noalias] ([set_fields]) values ([set_values])",
'update'=>"update [table_noalias] set [set] [where]",
'delete'=>"delete from [table_noalias] [where]",
'truncate'=>'truncate table [table_noalias]',
'describe'=>'desc [table_noalias]',
);
/** required for non-id based tables */
public $id_field;
// {{{ Generic routines
function _unique(&$array,$desired=null)
{
$desired=preg_replace('/[^a-zA-Z0-9:]/', '_', $desired);
$desired=parent::_unique($array, $desired);
return $desired;
}
function __clone()
{
$this->stmt=null;
}
private $to_stringing=false;
function __toString()
{
if($this->to_stringing)return 'Recursive __toString';
$this->to_stringing=true;
try {
if ($this->output_mode==='render') {
$output=$this->render();
} else {
$output=(string)$this->getOne();
}
$this->to_stringing=false;
return $output;
} catch (Exception $e) {
$this->app->caughtException($e);
//return "Exception: ".$e->getMessage();
}
$output=$this->toString();
$this->to_stringing=false;
return $output;
}
/**
* Explicitly sets template to your query. Remember to change
* $this->mode if you switch this
*
* @param string $template New template to use by render
*
* @return DB_dsql $this
*/
function template($template)
{
$this->template=$template;
return $this;
}
/**
* Change prefix for parametric values. Not really useful.
*
* @param string $param_base prefix to use for param names
*
* @return DB_dsql $this
*/
function paramBase($param_base)
{
$this->param_base=$param_base;
return $this;
}
/**
* Create new dsql object linked with the same database connection and
* bearing same data-type. You can use this method to create sub-queries.
*
* @return DB_dsql Empty query for same database
*/
function dsql()
{
return $this->owner->dsql(get_class($this));
}
/**
* Converts value into parameter and returns reference. Use only during
* query rendering. Consider using `consume()` instead.
*
* @param string $val String literal containing input data
*
* @return string Safe and escapeed string
*/
function escape($val)
{
if ($val===UNDEFINED) {
return '';
}
if (is_array($val)) {
$out=array();
foreach ($val as $v) {
$out[]=$this->escape($v);
}
return $out;
}
$name=':'.$this->param_base;
$name=$this->_unique($this->params, $name);
$this->params[$name]=$val;
return $name;
}
/**
* Recursively renders sub-query or expression, combining parameters.
* If the argument is more likely to be a field, use tick=true
*
* @param object|string $dsql Expression
* @param boolean $tick Preferred quoted style
*
* @return string Quoted expression
*/
function consume($dsql, $tick = true)
{
if ($dsql===UNDEFINED) {
return '';
}
if ($dsql===null) {
return '';
}
if (is_object($dsql) && $dsql instanceof Field) {
$dsql=$dsql->getExpr();
}
if (!is_object($dsql) || !$dsql instanceof DB_dsql) {
return $tick?$this->bt($dsql):$dsql;
}
$dsql->params = &$this->params;
$ret = $dsql->_render();
if ($dsql->mode==='select') {
$ret='('.$ret.')';
}
unset($dsql->params);
$dsql->params=array();
return $ret;
}
/**
* Defines a custom tag variable. WARNING: always backtick / escaped
* argument if it's unsafe
*
* @param string $tag Corresponds to [tag] inside template
* @param string|object $value Value for the template tag
*
* @return DB_dsql $this
*/
function setCustom($tag, $value = null)
{
if (is_array($tag)) {
foreach ($tag as $key => $val) {
$this->setCustom($key, $val);
}
return $this;
}
$this->args['custom'][$tag]=$value;
return $this;
}
/**
* This is identical to AbstractObject::debug(), but as an object
* will refer to the $owner. This is to avoid string-casting and
* messing up with the DSQL string.
*
* @param bool|string $msg "true" to start debugging
*
* @return void
*/
function debug($msg = true)
{
if (is_bool($msg)) {
$this->debug = $msg;
return $this;
}
if(is_object($msg))throw $this->exception('Do not debug objects');
// The rest of this method is obsolete
if ((isset($this->debug) && $this->debug)
|| (isset($this->app->debug) && $this->app->debug)
) {
$this->app->outputDebug($this->owner, $msg);
}
}
/**
* Removes definition for argument. $q->del('where'), $q->del('fields') etc.
*
* @param string $args Could be 'field', 'where', 'order', 'limit', etc
*
* @return DB_dsql $this
*/
function del($args)
{
$this->args[$args]=array();
return $this;
}
/**
* Removes all definitions. Start from scratch
*
* @return DB_dsql $this
*/
function reset()
{
$this->args=array();
return $this;
}
// }}}
// {{{ Dynamic Query Definition methods
// {{{ Generic methods
/**
* Returns new dynamic query and initializes it to use specific template.
*
* @param string $expr SQL Expression. Don't pass unverified input
* @param array $tags Array of tags and values. @see setCustom()
*
* @return DB_dsql New dynamic query, won't affect $this
*/
function expr($expr, $tags = array())
{
return $this->dsql()->useExpr($expr, $tags);
}
/**
* Change template of existing query instead of creating new one. If unsure
* use expr()
*
* @param string $expr SQL Expression. Don't pass unverified input
* @param array $tags Obsolete, use templates / setCustom()
*
* @return DB_dsql $this
*/
function useExpr($expr, $tags = array())
{
foreach ($tags as $key => $value) {
if ($key[0] == ':') {
$this->extra_params[$key] = $value;
continue;
}
$this->args['custom'][$key]=$value;
}
$this->template=$expr;
if ($tags) {
$this->setCustom($tags);
}
$this->output_mode='render';
return $this;
}
/**
* Shortcut to produce expression which concatinates "where" clauses with
* "OR" operator
*
* @return DB_dsql New dynamic query, won't affect $this
*/
function orExpr()
{
return $this->expr('([orwhere])');
}
/**
* Shortcut to produce expression for series of conditions concatinated
* with "and". Useful to be passed inside where() or join()
*
* @return DB_dsql New dynamic query, won't affect $this
*/
function andExpr()
{
return $this->expr('([andwhere])');
}
/**
* Return expression containing a properly escaped field. Use make
* subquery condition reference parent query
*
* @param string $fld Field in SQL table
*
* @return DB_dsql Expression pointing to specified field
*/
function getField($fld)
{
if ($this->main_table===false ){
throw $this->exception(
'Cannot use getField() when multiple tables are queried'
);
}
return $this->expr(
$this->bt($this->main_table).
'.'.
$this->bt($fld)
);
}
// }}}
// {{{ table()
/**
* Specifies which table to use in this dynamic query. You may specify
* array to perform operation on multiple tables.
*
* Examples:
* $q->table('user');
* $q->table('user','u');
* $q->table('user')->table('salary')
* $q->table(array('user','salary'));
* $q->table(array('user','salary'),'user');
* $q->table(array('u'=>'user','s'=>'salary'));
*
* If you specify multiple tables, you still need to make sure to add
* proper "where" conditions. All the above examples return $q (for chaining)
*
* You can also call table without arguments, which will return current table:
*
* echo $q->table();
*
* If multiple tables are used, "false" is returned. Return is not quoted.
* Please avoid using table() without arguments as more tables may be
* dynamically added later.
*
* @param string $table Specify table to use
* @param string $alias Specify alias for the table
*
* @return DB_dsql $this
**/
function table($table = UNDEFINED, $alias = UNDEFINED)
{
if ($table===UNDEFINED) {
return $this->main_table;
}
if (is_array($table)) {
foreach ($table as $alias => $t) {
if (is_numeric($alias)) {
$alias=UNDEFINED;
}
$this->table($t, $alias);
}
return $this;
}
// main_table tracking allows us to
if ($this->main_table===null) {
$this->main_table=$alias===UNDEFINED||!$alias?$table:$alias;
} elseif ($this->main_table) {
$this->main_table=false; // query from multiple tables
}
$this->args['table'][]=array($table,$alias);
return $this;
}
/**
* Renders part of the template: [table]
* Do not call directly
*
* @return string Parsed template chunk
*/
function render_table()
{
$ret=array();
if (!is_array($this->args['table'])) {
return;
}
foreach ($this->args['table'] as $row) {
list($table, $alias)=$row;
$table=$this->bt($table);
if ($alias!==UNDEFINED && $alias) {
$table.=' '.$this->bt($alias);
}
$ret[]=$table;
}
return join(',', $ret);
}
/**
* Conditionally returns "from", only if table is Specified
* Do not call directly
*
* @return string Parsed template chunk
*/
function render_from()
{
if ($this->args['table']) {
return 'from';
}
return '';
}
/**
* Returns template component [table_noalias]
*
* @return string Parsed template chunk
*/
function render_table_noalias()
{
$ret=array();
foreach ($this->args['table'] as $row) {
list($table, $alias)=$row;
$table=$this->bt($table);
$ret[]=$table;
}
return join(', ', $ret);
}
// }}}
// {{{ field()
/**
* Adds new column to resulting select by querying $field.
*
* Examples:
* $q->field('name');
*
* Second argument specifies table for regular fields
* $q->field('name','user');
* $q->field('name','user')->field('line1','address');
*
* Array as a first argument will specify mulitple fields, same as calling field() multiple times
* $q->field(array('name','surname'));
*
* Associative array will assume that "key" holds the alias. Value may be object.
* $q->field(array('alias'=>'name','alias2'=>surname'));
* $q->field(array('alias'=>$q->expr(..), 'alias2'=>$q->dsql()->.. ));
*
* You may use array with aliases together with table specifier.
* $q->field(array('alias'=>'name','alias2'=>surname'),'user');
*
* You can specify $q->expr() for calculated fields. Alias is mandatory.
* $q->field( $q->expr('2+2'),'alias'); // must always use alias
*
* You can use $q->dsql() for subqueries. Alias is mandatory.
* $q->field( $q->dsql()->table('x')... , 'alias'); // must always use alias
*
* @param string|array $field Specifies field to select
* @param string $table Specify if not using primary table
* @param string $alias Specify alias for this field
*
* @return DB_dsql $this
*/
function field($field, $table = null, $alias = null)
{
if (is_string($field) && strpos($field, ',') !== false) {
$field = explode(',', $field);
} elseif (is_object($field)) {
$alias = $table;
$table = null;
}
if (is_array($field)) {
foreach ($field as $alias => $f) {
if (is_numeric($alias)) {
$alias = null;
}
$this->field($f, $table, $alias);
}
return $this;
}
$this->args['fields'][] = array($field, $table, $alias);
return $this;
}
/**
* Removes all field definitions and returns only field you specify
* as parameter to this method. Original query is not affected ($this)
* Same as for field() syntax
*
* @param string|array $field Specifies field to select
* @param string $table Specify if not using primary table
* @param string $alias Specify alias for this field
*
* @return DB_dsql Clone of $this with only one field
*/
function fieldQuery($field, $table = null, $alias = null)
{
$q=clone $this;
return $q->del('fields')->field($field, $table, $alias);
}
/**
* Returns template component [field]
*
* @return string Parsed template chunk
*/
function render_field()
{
$result=array();
if (!$this->args['fields']) {
if ($this->default_field instanceof DB_dsql) {
return $this->consume($this->default_field);
}
return (string)$this->default_field;
}
foreach ($this->args['fields'] as $row) {
list($field,$table,$alias)=$row;
if ($alias===$field) {
$alias=UNDEFINED;
}
/**/$this->app->pr->start('dsql/render/field/consume');
$field=$this->consume($field);
/**/$this->app->pr->stop();
if (!$field) {
$field=$table;
$table=UNDEFINED;
}
if ($table && $table!==UNDEFINED) {
$field=$this->bt($table).'.'.$field;
}
if ($alias && $alias!==UNDEFINED) {
$field.=' '.$this->bt($alias);
}
$result[]=$field;
}
return join(',', $result);
}
// }}}
// {{{ where() and having()
/**
* Adds condition to your query
*
* Examples:
* $q->where('id',1);
*
* Second argument specifies table for regular fields
* $q->where('id>','1');
* $q->where('id','>',1);
*
* You may use expressions
* $q->where($q->expr('a=b'));
* $q->where('date>',$q->expr('now()'));
* $q->where($q->expr('length(password)'),'>',5);
*
* Finally, subqueries can also be used
* $q->where('foo',$q->dsql()->table('foo')->field('name'));
*
* To specify OR conditions
* $q->where($q->orExpr()->where('a',1)->where('b',1));
*
* you can also use the shortcut:
*
* $q->where(array('a is null','b is null'));
*
* @param mixed $field Field, array for OR or Expression
* @param string $cond Condition such as '=', '>' or 'is not'
* @param string $value Value. Will be quoted unless you pass expression
* @param string $kind Do not use directly. Use having()
*
* @return DB_dsql $this
*/
function where($field, $cond = UNDEFINED, $value = UNDEFINED, $kind = 'where')
{
if (is_array($field)) {
// or conditions
$or=$this->orExpr();
foreach ($field as $row) {
if (is_array($row)) {
$or->where(
$row[0],
array_key_exists(1, $row) ? $row[1] : UNDEFINED,
array_key_exists(2, $row) ? $row[2] : UNDEFINED
);
} elseif (is_object($row)) {
$or->where($row);
} else {
$or->where($or->expr($row));
}
}
$field=$or;
}
if (is_string($field) && !preg_match('/^[.a-zA-Z0-9_]*$/', $field)) {
// field contains non-alphanumeric values. Look for condition
preg_match(
'/^([^ <>!=]*)([><!=]*|( *(not|is|in|like))*) *$/',
$field,
$matches
);
$value=$cond;
$cond=$matches[2];
if (!$cond) {
// IF COMPAT
$matches[1]=$this->expr($field);
if ($value && $value!==UNDEFINED) {
$cond='=';
} else {
$cond=UNDEFINED;
}
}
$field=$matches[1];
}
$this->args[$kind][]=array($field,$cond,$value);
return $this;
}
/**
* Same syntax as where()
*
* @param mixed $field Field, array for OR or Expression
* @param string $cond Condition such as '=', '>' or 'is not'
* @param string $value Value. Will be quoted unless you pass expression
*
* @return DB_dsql $this
*/
function having($field, $cond = UNDEFINED, $value = UNDEFINED)
{
return $this->where($field, $cond, $value, 'having');
}
/**
* Subroutine which renders either [where] or [having]
*
* @param string $kind 'where' or 'having'
*
* @return array Parsed chunks of query
*/
function _render_where($kind)
{
$ret=array();
foreach ($this->args[$kind] as $row) {
list($field,$cond,$value)=$row;
if (is_object($field)) {
// if first argument is object, condition must be explicitly
// specified
$field=$this->consume($field);
} else {
list($table, $field)=explode('.', $field, 2);
if ($field) {
if ($this->mode=='delete') {
$field=$this->bt($field);
} else {
$field=$this->bt($table).'.'.$this->bt($field);
}
} else {
$field=$this->bt($table);
}
}
// no value or condition passed, so this should be SQL chunk itself
if ($value===UNDEFINED && $cond===UNDEFINED) {
$r=$field;
$ret[]=$r;
continue;
}
// if no condition defined - set default condition
if ($value===UNDEFINED) {
$value = $cond;
if (is_array($value)) {
$cond = 'in';
} elseif (is_object($value) && @$value->mode==='select') {
$cond = 'in';
} else {
$cond = '=';
}
} else {
$cond = trim(strtolower($cond));
}
// special conditions if value is null
if ($value === null) {
if ($cond === '=') {
$cond = 'is';
} elseif (in_array($cond, array('!=', '<>', 'not'))) {
$cond = 'is not';
}
}
// value should be array for such conditions
if (($cond==='in' || $cond==='not in') && is_string($value)) {
$value = explode(',', $value);
}
// if value is array, then use IN or NOT IN as condition
if (is_array($value)) {
$v=array();
foreach ($value as $vv) {
$v[]=$this->escape($vv);
}
$value='('.join(',', $v).')';
$cond = in_array($cond, array('!=', '<>', 'not', 'not in')) ? 'not in' : 'in';
$r=$this->consume($field).' '.$cond.' '.$value;
$ret[]=$r;
continue;
}
// if value is object, then it should be DSQL itself
// otherwise just escape value
if (is_object($value)) {
$value=$this->consume($value);
} else {
$value=$this->escape($value);
}
$r=$field.' '.$cond.' '.$value;
$ret[]=$r;
}
return $ret;
}
/**
* Renders [where]
*
* @return string rendered SQL chunk
*/
function render_where()
{
if (!$this->args['where']) {
return;
}
return 'where '.join(' and ', $this->_render_where('where'));
}
/**
* Renders [orwhere]
*
* @return string rendered SQL chunk
*/
function render_orwhere()
{
if (!$this->args['where']) {
return;
}
return join(' or ', $this->_render_where('where'));
}
/**
* Renders [andwhere]
*
* @return string rendered SQL chunk
*/
function render_andwhere()
{
if (!$this->args['where']) {
return;
}
return join(' and ', $this->_render_where('where'));
}
/**
* Renders [having]
*
* @return string rendered SQL chunk
*/
function render_having()
{
if (!$this->args['having']) {
return;
}
return 'having '.join(' and ', $this->_render_where('having'));
}
// }}}
// {{{ join()
/**
* Joins your query with another table
*
* Examples:
* $q->join('address'); // on user.address_id=address.id
* $q->join('address.user_id'); // on address.user_id=user.id
* $q->join('address a'); // With alias
* $q->join(array('a'=>'address')); // Also alias
*
* Second argument may specify the field of the master table
* $q->join('address', 'billing_id');
* $q->join('address.code', 'code');
* $q->join('address.code', 'user.code');
*
* Third argument may specify which kind of join to use.
* $q->join('address', null, 'left');
* $q->join('address.code', 'user.code', 'inner');
*
* Using array syntax you can join multiple tables too
* $q->join(array('a'=>'address', 'p'=>'portfolio'));
*
* You can use expression for more complex joins
* $q->join('address',
* $q->orExpr()
* ->where('user.billing_id=address.id')
* ->where('user.technical_id=address.id')
* )
*
* @param string $foreign_table Table to join with
* @param string $master_field Field in master table
* @param string $join_kind 'left' or 'inner', etc
* @param string $_foreign_alias Internal, don't use
*
* @return DB_dsql $this
*/
function join(
$foreign_table,
$master_field = null,
$join_kind = null,
$_foreign_alias = null
) {
// Compatibility mode
if (isset($this->app->compat)) {
if (strpos($foreign_table, ' ')) {
list($foreign_table, $alias)=explode(' ', $foreign_table);
$foreign_table=array($alias => $foreign_table);
}
if (strpos($master_field, '=')) {
$master_field=$this->expr($master_field);
}
}
// If array - add recursively
if (is_array($foreign_table)) {
foreach ($foreign_table as $alias => $foreign) {
if (is_numeric($alias)) {
$alias=null;
}
$this->join($foreign, $master_field, $join_kind, $alias);
}
return $this;
}
$j=array();
// Split and deduce fields
list($f1, $f2)=explode('.', $foreign_table, 2);
if (is_object($master_field)) {
$j['expr']=$master_field;
} else {
// Split and deduce primary table
if (is_null($master_field)) {
list($m1, $m2)=array(null, null);
} else {
list($m1, $m2)=explode('.', $master_field, 2);
}
if (is_null($m2)) {
$m2=$m1;
$m1=null;
}
if (is_null($m1)) {
$m1=$this->main_table;
}
// Identify fields we use for joins
if (is_null($f2) && is_null($m2)) {
$m2=$f1.'_id';
}
if (is_null($m2)) {
$m2='id';
}
$j['m1']=$m1;
$j['m2']=$m2;
}
$j['f1']=$f1;
if (is_null($f2)) {
$f2='id';
}
$j['f2']=$f2;
$j['t']=$join_kind?:'left';
$j['fa']=$_foreign_alias;
$this->args['join'][]=$j;
return $this;
}
/**
* Renders [join]
*
* @return string rendered SQL chunk
*/
function render_join()
{
if (!$this->args['join']) {
return '';
}
$joins=array();
foreach ($this->args['join'] as $j) {
$jj='';
$jj.=$j['t'].' join ';
$jj.=$this->bt($j['f1']);
if (!is_null($j['fa'])) {
$jj.=' as '.$this->bt($j['fa']);
}
$jj.=' on ';
if ($j['expr']) {
$jj.=$this->consume($j['expr']);
} else {
$jj.=
$this->bt($j['fa']?:$j['f1']).'.'.
$this->bt($j['f2']).' = '.
$this->bt($j['m1']).'.'.
$this->bt($j['m2']);
}
$joins[]=$jj;
}
return implode(' ', $joins);
}
// }}}
// {{{ group()
/**
* Implemens GROUP BY functionality. Simply pass either string field
* or expression
*
* @param string|object $group Group by this
*
* @return DB_dsql $this
*/
function group($group)
{
return $this->_setArray($group, 'group');
}
/**
* Renders [group]
*
* @return string rendered SQL chunk
*/
function render_group()
{
if (!$this->args['group']) {
return'';
}