/
Query.php
727 lines (672 loc) · 19.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
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace Cake\ORM;
use Cake\Database\Query as DatabaseQuery;
use Cake\Datasource\QueryTrait;
use Cake\ORM\EagerLoader;
use Cake\ORM\ResultSet;
use Cake\ORM\Table;
/**
* Extends the base Query class to provide new methods related to association
* loading, automatic fields selection, automatic type casting and to wrap results
* into an specific iterator that will be responsible for hydrating results if
* required.
*
*/
class Query extends DatabaseQuery {
use QueryTrait {
cache as private _cache;
all as private _all;
__call as private _call;
}
/**
* Indicates that the operation should append to the list
*
* @var integer
*/
const APPEND = 0;
/**
* Indicates that the operation should prepend to the list
*
* @var integer
*/
const PREPEND = 1;
/**
* Indicates that the operation should overwrite the list
*
* @var boolean
*/
const OVERWRITE = true;
/**
* Whether the user select any fields before being executed, this is used
* to determined if any fields should be automatically be selected.
*
* @var boolean
*/
protected $_hasFields;
/**
* Boolean for tracking whether or not buffered results
* are enabled.
*
* @var boolean
*/
protected $_useBufferedResults = true;
/**
* Whether to hydrate results into entity objects
*
* @var boolean
*/
protected $_hydrate = true;
/**
* A callable function that can be used to calculate the total amount of
* records this query will match when not using `limit`
*
* @var callable
*/
protected $_counter;
/**
* Instance of a class responsible for storing association containments and
* for eager loading them when this query is executed
*
* @var \Cake\ORM\EagerLoader
*/
protected $_eagerLoader;
/**
* Constuctor
*
* @param \Cake\Database\Connection $connection
* @param \Cake\ORM\Table $table
*/
public function __construct($connection, $table) {
$this->connection($connection);
$this->repository($table);
if ($this->_repository) {
$this->addDefaultTypes($this->_repository);
}
}
/**
* Hints this object to associate the correct types when casting conditions
* for the database. This is done by extracting the field types from the schema
* associated to the passed table object. This prevents the user from repeating
* himself when specifying conditions.
*
* This method returns the same query object for chaining.
*
* @param \Cake\ORM\Table $table
* @return Query
*/
public function addDefaultTypes(Table $table) {
$alias = $table->alias();
$schema = $table->schema();
$fields = [];
foreach ($schema->columns() as $f) {
$fields[$f] = $fields[$alias . '.' . $f] = $schema->columnType($f);
}
$this->defaultTypes($this->defaultTypes() + $fields);
return $this;
}
/**
* Sets the instance of the eager loader class to use for loading associations
* and storing containments. If called with no arguments, it will return the
* currently configured instance.
*
* @param \Cake\ORM\EagerLoader $instance
* @return \Cake\ORM\EagerLoader|\Cake\ORM\Query
*/
public function eagerLoader(EagerLoader $instance = null) {
if ($instance === null) {
if ($this->_eagerLoader === null) {
$this->_eagerLoader = new EagerLoader;
}
return $this->_eagerLoader;
}
$this->_eagerLoader = $instance;
return $this;
}
/**
* Sets the list of associations that should be eagerly loaded along with this
* query. The list of associated tables passed must have been previously set as
* associations using the Table API.
*
* ### Example:
*
* {{{
* // Bring articles' author information
* $query->contain('Author');
*
* // Also bring the category and tags associated to each article
* $query->contain(['Category', 'Tag']);
* }}}
*
* Associations can be arbitrarily nested using dot notation or nested arrays,
* this allows this object to calculate joins or any additional queries that
* must be executed to bring the required associated data.
*
* ### Example:
*
* {{{
* // Eager load the product info, and for each product load other 2 associations
* $query->contain(['Product' => ['Manufacturer', 'Distributor']);
*
* // Which is equivalent to calling
* $query->contain(['Products.Manufactures', 'Products.Distributors']);
*
* // For an author query, load his region, state and country
* $query->contain('Regions.States.Countries');
* }}}
*
* It is possible to control the conditions and fields selected for each of the
* contained associations:
*
* ### Example:
*
* {{{
* $query->contain(['Tags' => function($q) {
* return $q->where(['Tags.is_popular' => true]);
* }]);
*
* $query->contain(['Products.Manufactures' => function($q) {
* return $q->select(['name'])->where(['Manufactures.active' => true]);
* }]);
* }}}
*
* Each association might define special options when eager loaded, the allowed
* options that can be set per association are:
*
* - foreignKey: Used to set a different field to match both tables, if set to false
* no join conditions will be generated automatically
* - fields: An array with the fields that should be fetched from the association
* - queryBuilder: Equivalent to passing a callable instead of an options array
*
* ### Example:
*
* {{{
* // Set options for the articles that will be eagerly loaded for an author
* $query->contain([
* 'Articles' => [
* 'fields' => ['title']
* ]
* ]);
*
* // Use special join conditions for getting an article author's 'likes'
* $query->contain([
* 'Likes' => [
* 'foreignKey' => false,
* 'queryBuilder' => function($q) {
* return $q->where(...); // Add full filtering conditions
* }
* ]
* ]);
*
* If called with no arguments, this function will return an array with
* with the list of previously configured associations to be contained in the
* result.
*
* If called with an empty first argument and $override is set to true, the
* previous list will be emptied.
*
* @param array|string $associations list of table aliases to be queried
* @param boolean $override whether override previous list with the one passed
* defaults to merging previous list with the new one.
* @return array|\Cake\ORM\Query
*/
public function contain($associations = null, $override = false) {
if (empty($associations) && $override) {
$this->_eagerLoader = null;
}
$result = $this->eagerLoader()->contain($associations);
if ($associations !== null || $override) {
$this->_dirty();
}
if ($associations === null) {
return $result;
}
return $this;
}
/**
* Adds filtering conditions to this query to only bring rows that have a relation
* to another from an associated table, based on conditions in the associated table.
*
* This function will add entries in the ``contain`` graph.
*
* ### Example:
*
* {{{
* // Bring only articles that were tagged with 'cake'
* $query->matching('Tags', function($q) {
* return $q->where(['name' => 'cake']);
* );
* }}}
*
* It is possible to filter by deep associations by using dot notation:
*
* ### Example:
*
* {{{
* // Bring only articles that were commented by 'markstory'
* $query->matching('Comments.Users', function($q) {
* return $q->where(['username' => 'markstory']);
* );
* }}}
*
* As this function will create ``INNER JOIN``, you might want to consider
* calling ``distinct`` on this query as you might get duplicate rows if
* your conditions don't filter them already. This might be the case, for example,
* of the same user commenting more than once in the same article.
*
* ### Example:
*
* {{{
* // Bring unique articles that were commented by 'markstory'
* $query->distinct(['Articles.id'])
* ->matching('Comments.Users', function($q) {
* return $q->where(['username' => 'markstory']);
* );
* }}}
*
* Please note that the query passed to the closure will only accept calling
* ``select``, ``where``, ``andWhere`` and ``orWhere`` on it. If you wish to
* add more complex clauses you can do it directly in the main query.
*
* @param string $assoc The association to filter by
* @param callable $builder a function that will receive a pre-made query object
* that can be used to add custom conditions or selecting some fields
* @return Query
*/
public function matching($assoc, callable $builder = null) {
$this->eagerLoader()->matching($assoc, $builder);
$this->_dirty();
return $this;
}
/**
* Enable/Disable buffered results.
*
* When enabled the ResultSet returned by this Query will be
* buffered. This enables you to iterate a ResultSet multiple times, or
* both cache and iterate the ResultSet.
*
* When disabled it will consume less memory as fetched results are not
* remembered in the ResultSet.
*
* If called with no arguments, it will return whether or not buffering is
* enabled.
*
* @param boolean $enable whether or not to enable buffering
* @return boolean|Query
*/
public function bufferResults($enable = null) {
if ($enable === null) {
return $this->_useBufferedResults;
}
$this->_dirty();
$this->_useBufferedResults = (bool)$enable;
return $this;
}
/**
* Returns a key => value array representing a single aliased field
* that can be passed directly to the select() method.
* The key will contain the alias and the value the actual field name.
*
* If the field is already aliased, then it will not be changed.
* If no $alias is passed, the default table for this query will be used.
*
* @param string $field
* @param string $alias the alias used to prefix the field
* @return array
*/
public function aliasField($field, $alias = null) {
$namespaced = strpos($field, '.') !== false;
$aliasedField = $field;
if ($namespaced) {
list($alias, $field) = explode('.', $field);
}
if (!$alias) {
$alias = $this->repository()->alias();
}
$key = sprintf('%s__%s', $alias, $field);
if (!$namespaced) {
$aliasedField = $alias . '.' . $field;
}
return [$key => $aliasedField];
}
/**
* Runs `aliasfield()` for each field in the provided list and returns
* the result under a single array.
*
* @param array $fields
* @param string $defaultAlias
* @return array
*/
public function aliasFields($fields, $defaultAlias = null) {
$aliased = [];
foreach ($fields as $alias => $field) {
if (is_numeric($alias) && is_string($field)) {
$aliased += $this->aliasField($field, $defaultAlias);
continue;
}
$aliased[$alias] = $field;
}
return $aliased;
}
/**
* Populates or adds parts to current query clauses using an array.
* This is handy for passing all query clauses at once.
*
* ## Example:
*
* {{{
* $query->applyOptions([
* 'fields' => ['id', 'name'],
* 'conditions' => [
* 'created >=' => '2013-01-01'
* ],
* 'limit' => 10
* ]);
* }}}
*
* Is equivalent to:
*
* {{{
* $query
* ->select(['id', 'name'])
* ->where(['created >=' => '2013-01-01'])
* ->limit(10)
* }}}
*
* @param array $options list of query clauses to apply new parts to. Accepts:
*
* - fields: Maps to the select method
* - conditions: Maps to the where method
* - limit: Maps to the limit method
* - order: Maps to the order method
* - offset: Maps to the offset method
* - group: Maps to the group method
* - having: Maps to the having method
* - contain: Maps to the contain options for eager loading
* - join: Maps to the join method
* - page: Maps to the page method
*
* @return \Cake\ORM\Query
*/
public function applyOptions(array $options) {
$valid = [
'fields' => 'select',
'conditions' => 'where',
'join' => 'join',
'order' => 'order',
'limit' => 'limit',
'offset' => 'offset',
'group' => 'group',
'having' => 'having',
'contain' => 'contain',
'page' => 'page',
];
foreach ($options as $option => $values) {
if (isset($valid[$option]) && isset($values)) {
$this->{$valid[$option]}($values);
} else {
$this->_options[$option] = $values;
}
}
return $this;
}
/**
* Return the COUNT(*) for for the query.
*
* @return integer
*/
public function count() {
$query = clone $this;
$query->limit(null);
$query->order([], true);
$query->offset(null);
$query->mapReduce(null, null, true);
$query->formatResults(null, true);
$counter = $this->_counter;
if ($counter) {
$query->counter(null);
return (int)$counter($query);
}
$count = ['count' => $query->func()->count('*')];
if (!count($query->clause('group')) && !$query->clause('distinct')) {
$statement = $query
->select($count, true)
->execute();
} else {
// Forcing at least one field to be selected
$query->select($query->newExpr()->add('1'));
$statement = $this->connection()->newQuery()
->select($count)
->from(['count_source' => $query])
->execute();
}
$result = $statement->fetch('assoc')['count'];
$statement->closeCursor();
return (int)$result;
}
/**
* Registers a callable function that will be executed when the `count` method in
* this query is called. The return value for the function will be set as the
* return value of the `count` method.
*
* This is particularly useful when you need to optimize a query for returning the
* count, for example removing unnecessary joins, removing group by or just return
* an estimated number of rows.
*
* The callback will receive as first argument a clone of this query and not this
* query itself.
*
* @param callable $counter
* @return \Cake\ORM\Query
*/
public function counter($counter) {
$this->_counter = $counter;
return $this;
}
/**
* Toggle hydrating entites.
*
* If set to false array results will be returned
*
* @param boolean|null $enable Use a boolean to set the hydration mode.
* Null will fetch the current hydration mode.
* @return boolean|Query A boolean when reading, and $this when setting the mode.
*/
public function hydrate($enable = null) {
if ($enable === null) {
return $this->_hydrate;
}
$this->_dirty();
$this->_hydrate = (bool)$enable;
return $this;
}
/**
* {@inheritdoc}
*
* @return Query The query instance.
* @throws \RuntimeException When you attempt to cache a non-select query.
*/
public function cache($key, $config = 'default') {
if ($this->_type !== 'select' && $this->_type !== null) {
throw new \RuntimeException('You cannot cache the results of non-select queries.');
}
return $this->_cache($key, $config);
}
/**
* {@inheritdoc}
*
* @throws \RuntimeException if this method is called on a non-select Query.
*/
public function all() {
if ($this->_type !== 'select' && $this->_type !== null) {
throw new \RuntimeException(
'You cannot call all() on a non-select query. Use execute() instead.'
);
}
return $this->_all();
}
/**
* Executes this query and returns a ResultSet object containing the results.
* This will also setup the correct statement class in order to eager load deep
* associations.
*
* @return \Cake\ORM\ResultSet
*/
protected function _execute() {
$statement = $this->eagerLoader()->loadExternal($this, $this->execute());
return new ResultSet($this, $statement);
}
/**
* Applies some defaults to the query object before it is executed.
*
* Specifically add the FROM clause, adds default table fields if none are
* specified and applies the joins required to eager load associations defined
* using `contain`
*
* @see \Cake\Database\Query::execute()
* @return Query
*/
protected function _transformQuery() {
if (!$this->_dirty) {
return parent::_transformQuery();
}
if ($this->_type === 'select') {
if (empty($this->_parts['from'])) {
$this->from([$this->_repository->alias() => $this->_repository->table()]);
}
$this->_addDefaultFields();
$this->eagerLoader()->attachAssociations($this, $this->_repository, !$this->_hasFields);
}
return parent::_transformQuery();
}
/**
* Inspects if there are any set fields for selecting, otherwise adds all
* the fields for the default table.
*
* @return void
*/
protected function _addDefaultFields() {
$select = $this->clause('select');
$this->_hasFields = true;
if (!count($select)) {
$this->_hasFields = false;
$this->select($this->repository()->schema()->columns());
$select = $this->clause('select');
}
$aliased = $this->aliasFields($select, $this->repository()->alias());
$this->select($aliased, true);
}
/**
* Apply custom finds to against an existing query object.
*
* Allows custom find methods to be combined and applied to each other.
*
* {{{
* $table->find('all')->find('recent');
* }}}
*
* The above is an example of stacking multiple finder methods onto
* a single query.
*
* @param string $finder The finder method to use.
* @param array $options The options for the finder.
* @return \Cake\ORM\Query Returns a modified query.
* @see \Cake\ORM\Table::find()
*/
public function find($finder, $options = []) {
return $this->repository()->callFinder($finder, $this, $options);
}
/**
* Marks a query as dirty, removing any preprocessed information
* from in memory caching such as previous results
*
* @return void
*/
protected function _dirty() {
$this->_results = null;
parent::_dirty();
}
/**
* Create an update query.
*
* This changes the query type to be 'update'.
* Can be combined with set() and where() methods to create update queries.
*
* @param string $table Unused parameter.
* @return Query
*/
public function update($table = null) {
$table = $this->repository()->table();
return parent::update($table);
}
/**
* Create a delete query.
*
* This changes the query type to be 'delete'.
* Can be combined with the where() method to create delete queries.
*
* @param string $table Unused parameter.
* @return Query
*/
public function delete($table = null) {
$table = $this->repository()->table();
return parent::delete($table);
}
/**
* Create an insert query.
*
* This changes the query type to be 'insert'.
* Note calling this method will reset any data previously set
* with Query::values()
*
* Can be combined with the where() method to create delete queries.
*
* @param array $columns The columns to insert into.
* @param array $types A map between columns & their datatypes.
* @return Query
*/
public function insert($columns, $types = []) {
$table = $this->repository()->table();
$this->into($table);
return parent::insert($columns, $types);
}
/**
* {@inheritdoc}
*
* @throws \BadMethodCallException if the method is called for a non-select query
*/
public function __call($method, $arguments) {
if ($this->type() === 'select') {
return $this->_call($method, $arguments);
}
throw new \BadMethodCallException(
sprintf('Cannot call method "%s" on a "%s" query', $method, $this->type())
);
}
/**
* {@inheritdoc}
*/
public function __debugInfo() {
return parent::__debugInfo() + [
'hydrate' => $this->_hydrate,
'buffered' => $this->_useBufferedResults,
'formatters' => count($this->_formatters),
'mapReducers' => count($this->_mapReduce),
'contain' => $this->contain(),
'extraOptions' => $this->_options,
'repository' => $this->_repository
];
}
}