-
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathSelectQuery.php
More file actions
454 lines (389 loc) · 11.6 KB
/
SelectQuery.php
File metadata and controls
454 lines (389 loc) · 11.6 KB
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
<?php
/**
* This file is part of Cycle ORM package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Cycle\Database\Query;
use Cycle\Database\Injection\Expression;
use Cycle\Database\Injection\Fragment;
use Cycle\Database\Query\Traits\WhereJsonTrait;
use Cycle\Database\Driver\CompilerInterface;
use Cycle\Database\Injection\FragmentInterface;
use Cycle\Database\Query\Traits\HavingTrait;
use Cycle\Database\Query\Traits\JoinTrait;
use Cycle\Database\Query\Traits\TokenTrait;
use Cycle\Database\Query\Traits\WhereTrait;
use Cycle\Database\StatementInterface;
use Spiral\Pagination\PaginableInterface;
/**
* Builds select sql statements.
*/
class SelectQuery extends ActiveQuery implements
\Countable,
\IteratorAggregate,
PaginableInterface
{
use HavingTrait;
use JoinTrait;
use TokenTrait;
use WhereJsonTrait;
use WhereTrait;
// sort directions
public const SORT_ASC = 'ASC';
public const SORT_DESC = 'DESC';
protected array $tables = [];
protected array $unionTokens = [];
protected array $exceptTokens = [];
protected array $intersectTokens = [];
protected bool|string|array $distinct = false;
protected array $columns = ['*'];
/** @var FragmentInterface[][]|string[][] */
protected array $orderBy = [];
protected array $groupBy = [];
protected bool $forUpdate = false;
private ?int $limit = null;
private ?int $offset = null;
/**
* @param array $from Initial set of table names.
* @param array $columns Initial set of columns to fetch.
*/
public function __construct(array $from = [], array $columns = [])
{
$this->tables = $from;
if ($columns !== []) {
$this->columns = $this->fetchIdentifiers($columns);
}
}
/**
* Mark query to return only distinct results.
*
* @param bool|FragmentInterface|string $distinct You are only allowed to use string value for
* Postgres databases.
*/
public function distinct(bool|string|FragmentInterface $distinct = true): self
{
$this->distinct = $distinct;
return $this;
}
/**
* Set table names SELECT query should be performed for. Table names can be provided with
* specified alias (AS construction).
*/
public function from(mixed $tables): self
{
$this->tables = $this->fetchIdentifiers(\func_get_args());
return $this;
}
public function getTables(): array
{
return $this->tables;
}
/**
* Set columns should be fetched as result of SELECT query. Columns can be provided with
* specified alias (AS construction).
*/
public function columns(mixed $columns): self
{
$this->columns = $this->fetchIdentifiers(\func_get_args());
return $this;
}
public function getColumns(): array
{
return $this->columns;
}
/**
* Select entities for the following update.
*/
public function forUpdate(): self
{
$this->forUpdate = true;
return $this;
}
/**
* Sort result by column/expression. You can apply multiple sortings to query via calling method
* few times or by specifying values using array of sort parameters.
*
* $select->orderBy([
* 'id' => SelectQuery::SORT_DESC,
* 'name' => SelectQuery::SORT_ASC,
*
* // The following options below have the same effect (Direction will be ignored)
* new Fragment('RAND()') => null,
* new Fragment('RAND()')
* ]);
*
* $select->orderBy('name', SelectQuery::SORT_ASC);
*
* $select->orderBy(new Fragment('RAND()'), null); // direction will be ignored
* $select->orderBy(new Fragment('RAND()'), 'ASC NULLS LAST'); // Postgres specific directions are also supported
*
* @param 'ASC'|'DESC'|null $direction Sorting direction
*/
public function orderBy(string|FragmentInterface|array $expression, ?string $direction = self::SORT_ASC): self
{
if (!\is_array($expression)) {
$this->addOrder($expression, $direction);
return $this;
}
foreach ($expression as $nested => $dir) {
// support for orderBy([new Fragment('RAND()')]) without passing direction
if (\is_int($nested)) {
$nested = $dir;
$dir = null;
}
$this->addOrder($nested, $dir);
}
return $this;
}
/**
* Column or expression to group query by.
*/
public function groupBy(string|Fragment|Expression $expression): self
{
$this->groupBy[] = $expression;
return $this;
}
/**
* Add select query to be united with.
*/
public function union(FragmentInterface $query): self
{
$this->unionTokens[] = ['', $query];
return $this;
}
/**
* Add select query to be united with. Duplicate values will be included in result.
*/
public function unionAll(FragmentInterface $query): self
{
$this->unionTokens[] = ['ALL', $query];
return $this;
}
/**
* Add select query to be intersected with.
*/
public function intersect(FragmentInterface $query): self
{
$this->intersectTokens[] = ['', $query];
return $this;
}
/**
* Add select query to be intersected with. Duplicate values will be included in result.
*/
public function intersectAll(FragmentInterface $query): self
{
$this->intersectTokens[] = ['ALL', $query];
return $this;
}
/**
* Add select query to be excepted with.
*/
public function except(FragmentInterface $query): self
{
$this->exceptTokens[] = ['', $query];
return $this;
}
/**
* Add select query to be excepted with. Duplicate values will be included in result.
*/
public function exceptAll(FragmentInterface $query): self
{
$this->exceptTokens[] = ['ALL', $query];
return $this;
}
/**
* Set selection limit. Attention, this limit value does not affect values set in paginator but
* only changes pagination window. Set to 0 to disable limiting.
*/
public function limit(?int $limit = null): self
{
$this->limit = $limit;
return $this;
}
public function getLimit(): ?int
{
return $this->limit;
}
/**
* Set selection offset. Attention, this value does not affect associated paginator but only
* changes pagination window.
*/
public function offset(?int $offset = null): self
{
$this->offset = $offset;
return $this;
}
public function getOffset(): ?int
{
return $this->offset;
}
public function run(): StatementInterface
{
$params = new QueryParameters();
$queryString = $this->sqlStatement($params);
return $this->driver->query($queryString, $params->getParameters());
}
/**
* Iterate thought result using smaller data chinks with defined size and walk function.
*
* Example:
* $select->chunked(100, function(PDOResult $result, $offset, $count) {
* dump($result);
* });
*
* You must return FALSE from walk function to stop chunking.
*
* @throws \Throwable
*/
public function runChunks(int $limit, callable $callback): void
{
$count = $this->count();
// to keep original query untouched
$select = clone $this;
$select->limit($limit);
$offset = 0;
while ($offset + $limit <= $count) {
$result = $callback(
$select->offset($offset)->getIterator(),
$offset,
$count,
);
// stop iteration
if ($result === false) {
return;
}
$offset += $limit;
}
}
/**
* Count number of rows in query. Limit, offset, order by, group by values will be ignored.
*
* @psalm-param non-empty-string $column Column to count by (every column by default).
*/
public function count(string $column = '*'): int
{
$select = clone $this;
//To be escaped in compiler
$select->columns = ["COUNT({$column})"];
$select->orderBy = [];
$select->groupBy = [];
$st = $select->run();
try {
return (int) $st->fetchColumn();
} finally {
$st->close();
}
}
/**
* @psalm-param non-empty-string $column
*/
public function avg(string $column): mixed
{
return $this->runAggregate('AVG', $column);
}
/**
* @psalm-param non-empty-string $column
*/
public function max(string $column): mixed
{
return $this->runAggregate('MAX', $column);
}
/**
* @psalm-param non-empty-string $column
*/
public function min(string $column): mixed
{
return $this->runAggregate('MIN', $column);
}
/**
* @psalm-param non-empty-string $column
*/
public function sum(string $column): mixed
{
return $this->runAggregate('SUM', $column);
}
public function getIterator(): StatementInterface
{
return $this->run();
}
/**
* Request the first result as array (when you know that you have just one result).
*/
public function fetch(int $mode = StatementInterface::FETCH_ASSOC): array
{
$st = $this->run();
try {
return $st->fetch($mode);
} finally {
$st->close();
}
}
/**
* Request all results as array.
*/
public function fetchAll(int $mode = StatementInterface::FETCH_ASSOC): array
{
$st = $this->run();
try {
return $st->fetchAll($mode);
} finally {
$st->close();
}
}
public function getType(): int
{
return CompilerInterface::SELECT_QUERY;
}
public function getTokens(): array
{
return [
'forUpdate' => $this->forUpdate,
'from' => $this->tables,
'join' => $this->joinTokens,
'columns' => $this->columns,
'distinct' => $this->distinct,
'where' => $this->whereTokens,
'having' => $this->havingTokens,
'groupBy' => $this->groupBy,
'orderBy' => \array_values($this->orderBy),
'limit' => $this->limit,
'offset' => $this->offset,
'union' => $this->unionTokens,
'intersect' => $this->intersectTokens,
'except' => $this->exceptTokens,
];
}
/**
* @param string|null $order Sorting direction, ASC|DESC|null.
*
* @return $this|self
*/
private function addOrder(string|FragmentInterface $field, ?string $order): self
{
if (!\is_string($field)) {
$this->orderBy[] = [$field, $order];
} elseif (!\array_key_exists($field, $this->orderBy)) {
$this->orderBy[$field] = [$field, $order];
}
return $this;
}
/**
* @psalm-param non-empty-string $method
* @psalm-param non-empty-string $column
*/
private function runAggregate(string $method, string $column): mixed
{
$select = clone $this;
//To be escaped in compiler
$select->columns = ["{$method}({$column})"];
$st = $select->run();
try {
return $st->fetchColumn();
} finally {
$st->close();
}
}
}