-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathQuery.php
2386 lines (2184 loc) · 77.2 KB
/
Query.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
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Database;
use Cake\Database\Exception\DatabaseException;
use Cake\Database\Expression\CommonTableExpression;
use Cake\Database\Expression\IdentifierExpression;
use Cake\Database\Expression\OrderByExpression;
use Cake\Database\Expression\OrderClauseExpression;
use Cake\Database\Expression\QueryExpression;
use Cake\Database\Expression\ValuesExpression;
use Cake\Database\Expression\WindowExpression;
use Cake\Database\Statement\CallbackStatement;
use Closure;
use InvalidArgumentException;
use IteratorAggregate;
use RuntimeException;
/**
* This class represents a Relational database SQL Query. A query can be of
* different types like select, update, insert and delete. Exposes the methods
* for dynamically constructing each query part, execute it and transform it
* to a specific SQL dialect.
*/
class Query implements ExpressionInterface, IteratorAggregate
{
use TypeMapTrait;
/**
* @var string
*/
public const JOIN_TYPE_INNER = 'INNER';
/**
* @var string
*/
public const JOIN_TYPE_LEFT = 'LEFT';
/**
* @var string
*/
public const JOIN_TYPE_RIGHT = 'RIGHT';
/**
* Connection instance to be used to execute this query.
*
* @var \Cake\Database\Connection
*/
protected $_connection;
/**
* Type of this query (select, insert, update, delete).
*
* @var string
*/
protected $_type = 'select';
/**
* List of SQL parts that will be used to build this query.
*
* @var array
*/
protected $_parts = [
'delete' => true,
'update' => [],
'set' => [],
'insert' => [],
'values' => [],
'with' => [],
'select' => [],
'distinct' => false,
'modifier' => [],
'from' => [],
'join' => [],
'where' => null,
'group' => [],
'having' => null,
'window' => [],
'order' => null,
'limit' => null,
'offset' => null,
'union' => [],
'epilog' => null,
];
/**
* The list of query clauses to traverse for generating a SELECT statement
*
* @var string[]
*/
protected $_selectParts = [
'with', 'select', 'from', 'join', 'where', 'group', 'having', 'order', 'limit',
'offset', 'union', 'epilog',
];
/**
* The list of query clauses to traverse for generating an UPDATE statement
*
* @var string[]
*/
protected $_updateParts = ['with', 'update', 'set', 'where', 'epilog'];
/**
* The list of query clauses to traverse for generating a DELETE statement
*
* @var string[]
*/
protected $_deleteParts = ['with', 'delete', 'modifier', 'from', 'where', 'epilog'];
/**
* The list of query clauses to traverse for generating an INSERT statement
*
* @var string[]
*/
protected $_insertParts = ['with', 'insert', 'values', 'epilog'];
/**
* Indicates whether internal state of this query was changed, this is used to
* discard internal cached objects such as the transformed query or the reference
* to the executed statement.
*
* @var bool
*/
protected $_dirty = false;
/**
* A list of callback functions to be called to alter each row from resulting
* statement upon retrieval. Each one of the callback function will receive
* the row array as first argument.
*
* @var callable[]
*/
protected $_resultDecorators = [];
/**
* Statement object resulting from executing this query.
*
* @var \Cake\Database\StatementInterface|null
*/
protected $_iterator;
/**
* The object responsible for generating query placeholders and temporarily store values
* associated to each of those.
*
* @var \Cake\Database\ValueBinder|null
*/
protected $_valueBinder;
/**
* Instance of functions builder object used for generating arbitrary SQL functions.
*
* @var \Cake\Database\FunctionsBuilder|null
*/
protected $_functionsBuilder;
/**
* Boolean for tracking whether or not buffered results
* are enabled.
*
* @var bool
*/
protected $_useBufferedResults = true;
/**
* The Type map for fields in the select clause
*
* @var \Cake\Database\TypeMap|null
*/
protected $_selectTypeMap;
/**
* Tracking flag to disable casting
*
* @var bool
*/
protected $typeCastEnabled = true;
/**
* Constructor.
*
* @param \Cake\Database\Connection $connection The connection
* object to be used for transforming and executing this query
*/
public function __construct(Connection $connection)
{
$this->setConnection($connection);
}
/**
* Sets the connection instance to be used for executing and transforming this query.
*
* @param \Cake\Database\Connection $connection Connection instance
* @return $this
*/
public function setConnection(Connection $connection)
{
$this->_dirty();
$this->_connection = $connection;
return $this;
}
/**
* Gets the connection instance to be used for executing and transforming this query.
*
* @return \Cake\Database\Connection
*/
public function getConnection(): Connection
{
return $this->_connection;
}
/**
* Compiles the SQL representation of this query and executes it using the
* configured connection object. Returns the resulting statement object.
*
* Executing a query internally executes several steps, the first one is
* letting the connection transform this object to fit its particular dialect,
* this might result in generating a different Query object that will be the one
* to actually be executed. Immediately after, literal values are passed to the
* connection so they are bound to the query in a safe way. Finally, the resulting
* statement is decorated with custom objects to execute callbacks for each row
* retrieved if necessary.
*
* Resulting statement is traversable, so it can be used in any loop as you would
* with an array.
*
* This method can be overridden in query subclasses to decorate behavior
* around query execution.
*
* @return \Cake\Database\StatementInterface
*/
public function execute(): StatementInterface
{
$statement = $this->_connection->run($this);
$this->_iterator = $this->_decorateStatement($statement);
$this->_dirty = false;
return $this->_iterator;
}
/**
* Executes the SQL of this query and immediately closes the statement before returning the row count of records
* changed.
*
* This method can be used with UPDATE and DELETE queries, but is not recommended for SELECT queries and is not
* used to count records.
*
* ## Example
*
* ```
* $rowCount = $query->update('articles')
* ->set(['published'=>true])
* ->where(['published'=>false])
* ->rowCountAndClose();
* ```
*
* The above example will change the published column to true for all false records, and return the number of
* records that were updated.
*
* @return int
*/
public function rowCountAndClose(): int
{
$statement = $this->execute();
try {
return $statement->rowCount();
} finally {
$statement->closeCursor();
}
}
/**
* Returns the SQL representation of this object.
*
* This function will compile this query to make it compatible
* with the SQL dialect that is used by the connection, This process might
* add, remove or alter any query part or internal expression to make it
* executable in the target platform.
*
* The resulting query may have placeholders that will be replaced with the actual
* values when the query is executed, hence it is most suitable to use with
* prepared statements.
*
* @param \Cake\Database\ValueBinder|null $binder Value binder that generates parameter placeholders
* @return string
*/
public function sql(?ValueBinder $binder = null): string
{
if (!$binder) {
$binder = $this->getValueBinder();
$binder->resetCount();
}
return $this->getConnection()->compileQuery($this, $binder);
}
/**
* Will iterate over every specified part. Traversing functions can aggregate
* results using variables in the closure or instance variables. This function
* is commonly used as a way for traversing all query parts that
* are going to be used for constructing a query.
*
* The callback will receive 2 parameters, the first one is the value of the query
* part that is being iterated and the second the name of such part.
*
* ### Example
* ```
* $query->select(['title'])->from('articles')->traverse(function ($value, $clause) {
* if ($clause === 'select') {
* var_dump($value);
* }
* });
* ```
*
* @param callable $callback A function or callable to be executed for each part
* @return $this
*/
public function traverse($callback)
{
foreach ($this->_parts as $name => $part) {
$callback($part, $name);
}
return $this;
}
/**
* Will iterate over the provided parts.
*
* Traversing functions can aggregate results using variables in the closure
* or instance variables. This method can be used to traverse a subset of
* query parts in order to render a SQL query.
*
* The callback will receive 2 parameters, the first one is the value of the query
* part that is being iterated and the second the name of such part.
*
* ### Example
*
* ```
* $query->select(['title'])->from('articles')->traverse(function ($value, $clause) {
* if ($clause === 'select') {
* var_dump($value);
* }
* }, ['select', 'from']);
* ```
*
* @param callable $visitor A function or callable to be executed for each part
* @param string[] $parts The list of query parts to traverse
* @return $this
*/
public function traverseParts(callable $visitor, array $parts)
{
foreach ($parts as $name) {
$visitor($this->_parts[$name], $name);
}
return $this;
}
/**
* Adds a new common table expression (CTE) to the query.
*
* ### Examples:
*
* Common table expressions can either be passed as preconstructed expression
* objects:
*
* ```
* $cte = new \Cake\Database\Expression\CommonTableExpression(
* 'cte',
* $connection
* ->newQuery()
* ->select('*')
* ->from('articles')
* );
*
* $query->with($cte);
* ```
*
* or returned from a closure, which will receive a new common table expression
* object as the first argument, and a new blank query object as
* the second argument:
*
* ```
* $query->with(function (
* \Cake\Database\Expression\CommonTableExpression $cte,
* \Cake\Database\Query $query
* ) {
* $cteQuery = $query
* ->select('*')
* ->from('articles');
*
* return $cte
* ->name('cte')
* ->query($cteQuery);
* });
* ```
*
* @param \Closure|\Cake\Database\Expression\CommonTableExpression $cte The CTE to add.
* @param bool $overwrite Whether to reset the list of CTEs.
* @return $this
*/
public function with($cte, bool $overwrite = false)
{
if ($overwrite) {
$this->_parts['with'] = [];
}
if ($cte instanceof Closure) {
$query = $this->getConnection()->newQuery();
$cte = $cte(new CommonTableExpression(), $query);
if (!($cte instanceof CommonTableExpression)) {
throw new RuntimeException(
'You must return a `CommonTableExpression` from a Closure passed to `with()`.'
);
}
}
$this->_parts['with'][] = $cte;
$this->_dirty();
return $this;
}
/**
* Adds new fields to be returned by a `SELECT` statement when this query is
* executed. Fields can be passed as an array of strings, array of expression
* objects, a single expression or a single string.
*
* If an array is passed, keys will be used to alias fields using the value as the
* real field to be aliased. It is possible to alias strings, Expression objects or
* even other Query objects.
*
* If a callable function is passed, the returning array of the function will
* be used as the list of fields.
*
* By default this function will append any passed argument to the list of fields
* to be selected, unless the second argument is set to true.
*
* ### Examples:
*
* ```
* $query->select(['id', 'title']); // Produces SELECT id, title
* $query->select(['author' => 'author_id']); // Appends author: SELECT id, title, author_id as author
* $query->select('id', true); // Resets the list: SELECT id
* $query->select(['total' => $countQuery]); // SELECT id, (SELECT ...) AS total
* $query->select(function ($query) {
* return ['article_id', 'total' => $query->count('*')];
* })
* ```
*
* By default no fields are selected, if you have an instance of `Cake\ORM\Query` and try to append
* fields you should also call `Cake\ORM\Query::enableAutoFields()` to select the default fields
* from the table.
*
* @param array|\Cake\Database\ExpressionInterface|string|callable $fields fields to be added to the list.
* @param bool $overwrite whether to reset fields with passed list or not
* @return $this
*/
public function select($fields = [], bool $overwrite = false)
{
if (!is_string($fields) && is_callable($fields)) {
$fields = $fields($this);
}
if (!is_array($fields)) {
$fields = [$fields];
}
if ($overwrite) {
$this->_parts['select'] = $fields;
} else {
$this->_parts['select'] = array_merge($this->_parts['select'], $fields);
}
$this->_dirty();
$this->_type = 'select';
return $this;
}
/**
* Adds a `DISTINCT` clause to the query to remove duplicates from the result set.
* This clause can only be used for select statements.
*
* If you wish to filter duplicates based of those rows sharing a particular field
* or set of fields, you may pass an array of fields to filter on. Beware that
* this option might not be fully supported in all database systems.
*
* ### Examples:
*
* ```
* // Filters products with the same name and city
* $query->select(['name', 'city'])->from('products')->distinct();
*
* // Filters products in the same city
* $query->distinct(['city']);
* $query->distinct('city');
*
* // Filter products with the same name
* $query->distinct(['name'], true);
* $query->distinct('name', true);
* ```
*
* @param array|\Cake\Database\ExpressionInterface|string|bool $on Enable/disable distinct class
* or list of fields to be filtered on
* @param bool $overwrite whether to reset fields with passed list or not
* @return $this
*/
public function distinct($on = [], $overwrite = false)
{
if ($on === []) {
$on = true;
} elseif (is_string($on)) {
$on = [$on];
}
if (is_array($on)) {
$merge = [];
if (is_array($this->_parts['distinct'])) {
$merge = $this->_parts['distinct'];
}
$on = $overwrite ? array_values($on) : array_merge($merge, array_values($on));
}
$this->_parts['distinct'] = $on;
$this->_dirty();
return $this;
}
/**
* Adds a single or multiple `SELECT` modifiers to be used in the `SELECT`.
*
* By default this function will append any passed argument to the list of modifiers
* to be applied, unless the second argument is set to true.
*
* ### Example:
*
* ```
* // Ignore cache query in MySQL
* $query->select(['name', 'city'])->from('products')->modifier('SQL_NO_CACHE');
* // It will produce the SQL: SELECT SQL_NO_CACHE name, city FROM products
*
* // Or with multiple modifiers
* $query->select(['name', 'city'])->from('products')->modifier(['HIGH_PRIORITY', 'SQL_NO_CACHE']);
* // It will produce the SQL: SELECT HIGH_PRIORITY SQL_NO_CACHE name, city FROM products
* ```
*
* @param array|\Cake\Database\ExpressionInterface|string $modifiers modifiers to be applied to the query
* @param bool $overwrite whether to reset order with field list or not
* @return $this
*/
public function modifier($modifiers, $overwrite = false)
{
$this->_dirty();
if ($overwrite) {
$this->_parts['modifier'] = [];
}
$this->_parts['modifier'] = array_merge($this->_parts['modifier'], (array)$modifiers);
return $this;
}
/**
* Adds a single or multiple tables to be used in the FROM clause for this query.
* Tables can be passed as an array of strings, array of expression
* objects, a single expression or a single string.
*
* If an array is passed, keys will be used to alias tables using the value as the
* real field to be aliased. It is possible to alias strings, ExpressionInterface objects or
* even other Query objects.
*
* By default this function will append any passed argument to the list of tables
* to be selected from, unless the second argument is set to true.
*
* This method can be used for select, update and delete statements.
*
* ### Examples:
*
* ```
* $query->from(['p' => 'posts']); // Produces FROM posts p
* $query->from('authors'); // Appends authors: FROM posts p, authors
* $query->from(['products'], true); // Resets the list: FROM products
* $query->from(['sub' => $countQuery]); // FROM (SELECT ...) sub
* ```
*
* @param array|string $tables tables to be added to the list. This argument, can be
* passed as an array of strings, array of expression objects, or a single string. See
* the examples above for the valid call types.
* @param bool $overwrite whether to reset tables with passed list or not
* @return $this
*/
public function from($tables = [], $overwrite = false)
{
$tables = (array)$tables;
if ($overwrite) {
$this->_parts['from'] = $tables;
} else {
$this->_parts['from'] = array_merge($this->_parts['from'], $tables);
}
$this->_dirty();
return $this;
}
/**
* Adds a single or multiple tables to be used as JOIN clauses to this query.
* Tables can be passed as an array of strings, an array describing the
* join parts, an array with multiple join descriptions, or a single string.
*
* By default this function will append any passed argument to the list of tables
* to be joined, unless the third argument is set to true.
*
* When no join type is specified an `INNER JOIN` is used by default:
* `$query->join(['authors'])` will produce `INNER JOIN authors ON 1 = 1`
*
* It is also possible to alias joins using the array key:
* `$query->join(['a' => 'authors'])` will produce `INNER JOIN authors a ON 1 = 1`
*
* A join can be fully described and aliased using the array notation:
*
* ```
* $query->join([
* 'a' => [
* 'table' => 'authors',
* 'type' => 'LEFT',
* 'conditions' => 'a.id = b.author_id'
* ]
* ]);
* // Produces LEFT JOIN authors a ON a.id = b.author_id
* ```
*
* You can even specify multiple joins in an array, including the full description:
*
* ```
* $query->join([
* 'a' => [
* 'table' => 'authors',
* 'type' => 'LEFT',
* 'conditions' => 'a.id = b.author_id'
* ],
* 'p' => [
* 'table' => 'publishers',
* 'type' => 'INNER',
* 'conditions' => 'p.id = b.publisher_id AND p.name = "Cake Software Foundation"'
* ]
* ]);
* // LEFT JOIN authors a ON a.id = b.author_id
* // INNER JOIN publishers p ON p.id = b.publisher_id AND p.name = "Cake Software Foundation"
* ```
*
* ### Using conditions and types
*
* Conditions can be expressed, as in the examples above, using a string for comparing
* columns, or string with already quoted literal values. Additionally it is
* possible to use conditions expressed in arrays or expression objects.
*
* When using arrays for expressing conditions, it is often desirable to convert
* the literal values to the correct database representation. This is achieved
* using the second parameter of this function.
*
* ```
* $query->join(['a' => [
* 'table' => 'articles',
* 'conditions' => [
* 'a.posted >=' => new DateTime('-3 days'),
* 'a.published' => true,
* 'a.author_id = authors.id'
* ]
* ]], ['a.posted' => 'datetime', 'a.published' => 'boolean'])
* ```
*
* ### Overwriting joins
*
* When creating aliased joins using the array notation, you can override
* previous join definitions by using the same alias in consequent
* calls to this function or you can replace all previously defined joins
* with another list if the third parameter for this function is set to true.
*
* ```
* $query->join(['alias' => 'table']); // joins table with as alias
* $query->join(['alias' => 'another_table']); // joins another_table with as alias
* $query->join(['something' => 'different_table'], [], true); // resets joins list
* ```
*
* @param array|string $tables list of tables to be joined in the query
* @param array $types associative array of type names used to bind values to query
* @param bool $overwrite whether to reset joins with passed list or not
* @see \Cake\Database\TypeFactory
* @return $this
*/
public function join($tables, $types = [], $overwrite = false)
{
if (is_string($tables) || isset($tables['table'])) {
$tables = [$tables];
}
$joins = [];
$i = count($this->_parts['join']);
foreach ($tables as $alias => $t) {
if (!is_array($t)) {
$t = ['table' => $t, 'conditions' => $this->newExpr()];
}
if (!is_string($t['conditions']) && is_callable($t['conditions'])) {
$t['conditions'] = $t['conditions']($this->newExpr(), $this);
}
if (!($t['conditions'] instanceof ExpressionInterface)) {
$t['conditions'] = $this->newExpr()->add($t['conditions'], $types);
}
$alias = is_string($alias) ? $alias : null;
$joins[$alias ?: $i++] = $t + ['type' => static::JOIN_TYPE_INNER, 'alias' => $alias];
}
if ($overwrite) {
$this->_parts['join'] = $joins;
} else {
$this->_parts['join'] = array_merge($this->_parts['join'], $joins);
}
$this->_dirty();
return $this;
}
/**
* Remove a join if it has been defined.
*
* Useful when you are redefining joins or want to re-order
* the join clauses.
*
* @param string $name The alias/name of the join to remove.
* @return $this
*/
public function removeJoin(string $name)
{
unset($this->_parts['join'][$name]);
$this->_dirty();
return $this;
}
/**
* Adds a single `LEFT JOIN` clause to the query.
*
* This is a shorthand method for building joins via `join()`.
*
* The table name can be passed as a string, or as an array in case it needs to
* be aliased:
*
* ```
* // LEFT JOIN authors ON authors.id = posts.author_id
* $query->leftJoin('authors', 'authors.id = posts.author_id');
*
* // LEFT JOIN authors a ON a.id = posts.author_id
* $query->leftJoin(['a' => 'authors'], 'a.id = posts.author_id');
* ```
*
* Conditions can be passed as strings, arrays, or expression objects. When
* using arrays it is possible to combine them with the `$types` parameter
* in order to define how to convert the values:
*
* ```
* $query->leftJoin(['a' => 'articles'], [
* 'a.posted >=' => new DateTime('-3 days'),
* 'a.published' => true,
* 'a.author_id = authors.id'
* ], ['a.posted' => 'datetime', 'a.published' => 'boolean']);
* ```
*
* See `join()` for further details on conditions and types.
*
* @param string|string[] $table The table to join with
* @param string|array|\Cake\Database\ExpressionInterface $conditions The conditions
* to use for joining.
* @param array $types a list of types associated to the conditions used for converting
* values to the corresponding database representation.
* @return $this
*/
public function leftJoin($table, $conditions = [], $types = [])
{
$this->join($this->_makeJoin($table, $conditions, static::JOIN_TYPE_LEFT), $types);
return $this;
}
/**
* Adds a single `RIGHT JOIN` clause to the query.
*
* This is a shorthand method for building joins via `join()`.
*
* The arguments of this method are identical to the `leftJoin()` shorthand, please refer
* to that methods description for further details.
*
* @param string|string[] $table The table to join with
* @param string|array|\Cake\Database\ExpressionInterface $conditions The conditions
* to use for joining.
* @param array $types a list of types associated to the conditions used for converting
* values to the corresponding database representation.
* @return $this
*/
public function rightJoin($table, $conditions = [], $types = [])
{
$this->join($this->_makeJoin($table, $conditions, static::JOIN_TYPE_RIGHT), $types);
return $this;
}
/**
* Adds a single `INNER JOIN` clause to the query.
*
* This is a shorthand method for building joins via `join()`.
*
* The arguments of this method are identical to the `leftJoin()` shorthand, please refer
* to that methods description for further details.
*
* @param string|array $table The table to join with
* @param string|array|\Cake\Database\ExpressionInterface $conditions The conditions
* to use for joining.
* @param array $types a list of types associated to the conditions used for converting
* values to the corresponding database representation.
* @return $this
*/
public function innerJoin($table, $conditions = [], $types = [])
{
$this->join($this->_makeJoin($table, $conditions, static::JOIN_TYPE_INNER), $types);
return $this;
}
/**
* Returns an array that can be passed to the join method describing a single join clause
*
* @param string|string[] $table The table to join with
* @param string|array|\Cake\Database\ExpressionInterface $conditions The conditions
* to use for joining.
* @param string $type the join type to use
* @return array
* @psalm-suppress InvalidReturnType
*/
protected function _makeJoin($table, $conditions, $type): array
{
$alias = $table;
if (is_array($table)) {
$alias = key($table);
$table = current($table);
}
/**
* @psalm-suppress InvalidArrayOffset
* @psalm-suppress InvalidReturnStatement
*/
return [
$alias => [
'table' => $table,
'conditions' => $conditions,
'type' => $type,
],
];
}
/**
* Adds a condition or set of conditions to be used in the WHERE clause for this
* query. Conditions can be expressed as an array of fields as keys with
* comparison operators in it, the values for the array will be used for comparing
* the field to such literal. Finally, conditions can be expressed as a single
* string or an array of strings.
*
* When using arrays, each entry will be joined to the rest of the conditions using
* an `AND` operator. Consecutive calls to this function will also join the new
* conditions specified using the AND operator. Additionally, values can be
* expressed using expression objects which can include other query objects.
*
* Any conditions created with this methods can be used with any `SELECT`, `UPDATE`
* and `DELETE` type of queries.
*
* ### Conditions using operators:
*
* ```
* $query->where([
* 'posted >=' => new DateTime('3 days ago'),
* 'title LIKE' => 'Hello W%',
* 'author_id' => 1,
* ], ['posted' => 'datetime']);
* ```
*
* The previous example produces:
*
* `WHERE posted >= 2012-01-27 AND title LIKE 'Hello W%' AND author_id = 1`
*
* Second parameter is used to specify what type is expected for each passed
* key. Valid types can be used from the mapped with Database\Type class.
*
* ### Nesting conditions with conjunctions:
*
* ```
* $query->where([
* 'author_id !=' => 1,
* 'OR' => ['published' => true, 'posted <' => new DateTime('now')],
* 'NOT' => ['title' => 'Hello']
* ], ['published' => boolean, 'posted' => 'datetime']
* ```
*
* The previous example produces:
*
* `WHERE author_id = 1 AND (published = 1 OR posted < '2012-02-01') AND NOT (title = 'Hello')`
*
* You can nest conditions using conjunctions as much as you like. Sometimes, you
* may want to define 2 different options for the same key, in that case, you can
* wrap each condition inside a new array:
*
* `$query->where(['OR' => [['published' => false], ['published' => true]])`
*
* Would result in:
*
* `WHERE (published = false) OR (published = true)`
*
* Keep in mind that every time you call where() with the third param set to false
* (default), it will join the passed conditions to the previous stored list using
* the `AND` operator. Also, using the same array key twice in consecutive calls to
* this method will not override the previous value.
*
* ### Using expressions objects:
*
* ```
* $exp = $query->newExpr()->add(['id !=' => 100, 'author_id' != 1])->tieWith('OR');
* $query->where(['published' => true], ['published' => 'boolean'])->where($exp);
* ```
*
* The previous example produces:
*
* `WHERE (id != 100 OR author_id != 1) AND published = 1`
*
* Other Query objects that be used as conditions for any field.
*
* ### Adding conditions in multiple steps:
*
* You can use callable functions to construct complex expressions, functions
* receive as first argument a new QueryExpression object and this query instance
* as second argument. Functions must return an expression object, that will be
* added the list of conditions for the query using the `AND` operator.
*
* ```
* $query
* ->where(['title !=' => 'Hello World'])
* ->where(function ($exp, $query) {
* $or = $exp->or(['id' => 1]);
* $and = $exp->and(['id >' => 2, 'id <' => 10]);
* return $or->add($and);
* });
* ```
*
* * The previous example produces:
*
* `WHERE title != 'Hello World' AND (id = 1 OR (id > 2 AND id < 10))`
*
* ### Conditions as strings:
*
* ```
* $query->where(['articles.author_id = authors.id', 'modified IS NULL']);
* ```
*
* The previous example produces:
*
* `WHERE articles.author_id = authors.id AND modified IS NULL`
*
* Please note that when using the array notation or the expression objects, all
* *values* will be correctly quoted and transformed to the correspondent database
* data type automatically for you, thus securing your application from SQL injections.
* The keys however, are not treated as unsafe input, and should be validated/sanitized.
*
* If you use string conditions make sure that your values are correctly quoted.
* The safest thing you can do is to never use string conditions.
*
* @param string|array|\Cake\Database\ExpressionInterface|\Closure|null $conditions The conditions to filter on.
* @param array $types associative array of type names used to bind values to query
* @param bool $overwrite whether to reset conditions with passed list or not
* @see \Cake\Database\TypeFactory
* @see \Cake\Database\Expression\QueryExpression