summaryrefslogtreecommitdiffstats
path: root/vendor/ipl/sql/src/Select.php
blob: f56a1317a282c17e816598183e58006b380b3f3f (plain)
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
<?php

namespace ipl\Sql;

/**
 * SQL SELECT query
 */
class Select implements CommonTableExpressionInterface, LimitOffsetInterface, OrderByInterface, WhereInterface
{
    use CommonTableExpression;
    use LimitOffset;
    use OrderBy;
    use Where;

    /** @var bool Whether the query is DISTINCT */
    protected $distinct = false;

    /** @var array|null The columns for the SELECT query */
    protected $columns;

    /** @var array|null FROM part of the query, i.e. the table names to select data from */
    protected $from;

    /**
     * The tables to JOIN
     *
     * [
     *   [ $joinType, $tableName, $condition ],
     *   ...
     * ]
     *
     * @var ?array
     */
    protected $join;

    /** @var array|null The columns for the GROUP BY part of the query */
    protected $groupBy;

    /** @var array|null Internal representation for the HAVING part of the query */
    protected $having;

    /**
     * The queries to UNION
     *
     * [
     *   [ new Select(), (bool) 'UNION ALL' ],
     *   ...
     * ]
     *
     * @var ?array
     */
    protected $union;

    /**
     * Get whether to SELECT DISTINCT
     *
     * @return bool
     */
    public function getDistinct()
    {
        return $this->distinct;
    }

    /**
     * Set whether to SELECT DISTINCT
     *
     * @param bool $distinct
     *
     * @return $this
     */
    public function distinct($distinct = true)
    {
        $this->distinct = $distinct;

        return $this;
    }

    /**
     * Get the columns for the SELECT query
     *
     * @return array
     */
    public function getColumns()
    {
        return $this->columns ?: [];
    }

    /**
     * Add columns to the SELECT query
     *
     * Multiple calls to this method will not overwrite the previous set columns but append the columns to the query.
     *
     * Note that this method does NOT quote the columns you specify for the SELECT.
     * If you allow user input here, you must protected yourself against SQL injection using
     * {@link Connection::quoteIdentifier()} for the column names passed to this method.
     * If you are using special column names, e.g. reserved keywords for your DBMS, you are required to use
     * {@link Connection::quoteIdentifier()} as well.
     *
     * @param string|ExpressionInterface|Select|array $columns The column(s) to add to the SELECT.
     *                                                         The items can be any mix of the following: 'column',
     *                                                         'column as alias', ['alias' => 'column']
     *
     * @return $this
     */
    public function columns($columns)
    {
        if (! is_array($columns)) {
            $columns = [$columns];
        }

        $this->columns = array_merge($this->columns ?: [], $columns);

        return $this;
    }

    /**
     * Get the FROM part of the query
     *
     * @return array|null
     */
    public function getFrom()
    {
        return $this->from;
    }

    /**
     * Add a FROM part to the query
     *
     * Multiple calls to this method will not overwrite the previous set FROM part but append the tables to the FROM.
     *
     * Note that this method does NOT quote the tables you specify for the FROM.
     * If you allow user input here, you must protected yourself against SQL injection using
     * {@link Connection::quoteIdentifier()} for the table names passed to this method.
     * If you are using special table names, e.g. reserved keywords for your DBMS, you are required to use
     * {@link Connection::quoteIdentifier()} as well.
     *
     * @param string|Select|array $tables The table(s) to add to the FROM part. The items can be any mix of the
     *                                    following: ['table', 'table alias', 'alias' => 'table']
     *
     * @return $this
     */
    public function from($tables)
    {
        if (! is_array($tables)) {
            $tables = [$tables];
        }

        $this->from = array_merge($this->from ?: [], $tables);

        return $this;
    }

    /**
     * Get the JOIN part(s) of the query
     *
     * @return array|null
     */
    public function getJoin()
    {
        return $this->join;
    }

    /**
     * Add a INNER JOIN part to the query
     *
     * @param string|Select|array                     $table     The table to be joined, can be any of the following:
     *                                                           'table'  'table alias'  ['alias' => 'table']
     * @param string|ExpressionInterface|Select|array $condition The join condition, i.e. the ON part of the JOIN.
     *                                                           Please see {@link WhereInterface::where()}
     *                                                           for the supported formats and
     *                                                           restrictions regarding quoting of the field names.
     * @param string                                  $operator  The operator to combine multiple conditions with,
     *                                                           if the condition is in the array format
     *
     * @return $this
     */
    public function join($table, $condition, $operator = Sql::ALL)
    {
        $this->join[] = ['INNER', $table, $this->buildCondition($condition, $operator)];

        return $this;
    }

    /**
     * Add a LEFT JOIN part to the query
     *
     * @param string|Select|array                     $table     The table to be joined, can be any of the following:
     *                                                           'table'  'table alias'  ['alias' => 'table']
     * @param string|ExpressionInterface|Select|array $condition The join condition, i.e. the ON part of the JOIN.
     *                                                           Please see {@link WhereInterface::where()}
     *                                                           for the supported formats and
     *                                                           restrictions regarding quoting of the field names.
     * @param string                                  $operator  The operator to combine multiple conditions with,
     *                                                           if the condition is in the array format
     *
     * @return $this
     */
    public function joinLeft($table, $condition, $operator = Sql::ALL)
    {
        $this->join[] = ['LEFT', $table, $this->buildCondition($condition, $operator)];

        return $this;
    }

    /**
     * Add a RIGHT JOIN part to the query
     *
     * @param string|Select|array                     $table     The table to be joined, can be any of the following:
     *                                                           'table'  'table alias'  ['alias' => 'table']
     * @param string|ExpressionInterface|Select|array $condition The join condition, i.e. the ON part of the JOIN.
     *                                                           Please see {@link WhereInterface::where()}
     *                                                           for the supported formats and
     *                                                           restrictions regarding quoting of the field names.
     * @param string                                  $operator  The operator to combine multiple conditions with,
     *                                                           if the condition is in the array format
     *
     * @return $this
     */
    public function joinRight($table, $condition, $operator = Sql::ALL)
    {
        $this->join[] = ['RIGHT', $table, $this->buildCondition($condition, $operator)];

        return $this;
    }

    /**
     * Get the GROUP BY part of the query
     *
     * @return array|null
     */
    public function getGroupBy()
    {
        return $this->groupBy;
    }

    /**
     * Add a GROUP BY part to the query - either plain columns or expressions or scalar subqueries
     *
     * This method does NOT quote the columns you specify for the GROUP BY.
     * If you allow user input here, you must protected yourself against SQL injection using
     * {@link Connection::quoteIdentifier()} for the field names passed to this method.
     * If you are using special field names, e.g. reserved keywords for your DBMS, you are required to use
     * {@link Connection::quoteIdentifier()} as well.
     *
     * Note that this method does not override an already set GROUP BY part. Instead, multiple calls to this function
     * add the specified GROUP BY part.
     *
     * @param string|ExpressionInterface|Select|array $groupBy
     *
     * @return $this
     */
    public function groupBy($groupBy)
    {
        $this->groupBy = array_merge(
            $this->groupBy === null ? [] : $this->groupBy,
            is_array($groupBy) ? $groupBy : [$groupBy]
        );

        return $this;
    }

    /**
     * Get the HAVING part of the query
     *
     * @return array|null
     */
    public function getHaving()
    {
        return $this->having;
    }

    /**
     * Add a HAVING part of the query
     *
     * This method lets you specify the HAVING part of the query using one of the two following supported formats:
     * * String format, e.g. 'id = 1'
     * * Array format, e.g. ['id' => 1, ...]
     *
     * This method does NOT quote the columns you specify for the HAVING.
     * If you allow user input here, you must protected yourself against SQL injection using
     * {@link Connection::quoteIdentifier()} for the field names passed to this method.
     * If you are using special field names, e.g. reserved keywords for your DBMS, you are required to use
     * {@link Connection::quoteIdentifier()} as well.
     *
     * Note that this method does not override an already set HAVING part. Instead, multiple calls to this function add
     * the specified HAVING part using the AND operator.
     *
     * @param string|ExpressionInterface|Select|array $condition The HAVING condition
     * @param string                                  $operator  The operator to combine multiple conditions with,
     *                                                           if the condition is in the array format
     *
     * @return $this
     */
    public function having($condition, $operator = Sql::ALL)
    {
        $this->mergeCondition($this->having, $this->buildCondition($condition, $operator), Sql::ALL);

        return $this;
    }

    /**
     * Add a OR part to the HAVING part of the query
     *
     * Please see {@link having()} for the supported formats and restrictions regarding quoting of the field names.
     *
     * @param string|ExpressionInterface|Select|array $condition The HAVING condition
     * @param string                                  $operator  The operator to combine multiple conditions with,
     *                                                           if the condition is in the array format
     *
     * @return $this
     */
    public function orHaving($condition, $operator = Sql::ALL)
    {
        $this->mergeCondition($this->having, $this->buildCondition($condition, $operator), Sql::ANY);

        return $this;
    }

    /**
     * Add a AND NOT part to the HAVING part of the query
     *
     * Please see {@link having()} for the supported formats and restrictions regarding quoting of the field names.
     *
     * @param   string|ExpressionInterface|Select|array $condition  The HAVING condition
     * @param   string                                  $operator   The operator to combine multiple conditions with,
     *                                                              if the condition is in the array format
     *
     * @return  $this
     */
    public function notHaving($condition, $operator = Sql::ALL)
    {
        $this->mergeCondition($this->having, $this->buildCondition($condition, $operator), Sql::NOT_ALL);

        return $this;
    }

    /**
     * Add a OR NOT part to the HAVING part of the query
     *
     * Please see {@link having()} for the supported formats and restrictions regarding quoting of the field names.
     *
     * @param string|ExpressionInterface|Select|array $condition The HAVING condition
     * @param string                                  $operator  The operator to combine multiple conditions with,
     *                                                           if the condition is in the array format
     *
     * @return $this
     */
    public function orNotHaving($condition, $operator = Sql::ALL)
    {
        $this->mergeCondition($this->having, $this->buildCondition($condition, $operator), Sql::NOT_ANY);

        return $this;
    }

    /**
     * Get the UNION parts of the query
     *
     * @return array|null
     */
    public function getUnion()
    {
        return $this->union;
    }

    /**
     * Combine a query with UNION
     *
     * @param Select|string $query
     *
     * @return $this
     */
    public function union($query)
    {
        $this->union[] = [$query, false];

        return $this;
    }

    /**
     * Combine a query with UNION ALL
     *
     * @param Select|string $query
     *
     * @return $this
     */
    public function unionAll($query)
    {
        $this->union[] = [$query, true];

        return $this;
    }

    /**
     * Reset the DISTINCT part of the query
     *
     * @return $this
     */
    public function resetDistinct()
    {
        $this->distinct = false;

        return $this;
    }

    /**
     * Reset the columns of the query
     *
     * @return $this
     */
    public function resetColumns()
    {
        $this->columns = null;

        return $this;
    }

    /**
     * Reset the FROM part of the query
     *
     * @return $this
     */
    public function resetFrom()
    {
        $this->from = null;

        return $this;
    }

    /**
     * Reset the JOIN parts of the query
     *
     * @return $this
     */
    public function resetJoin()
    {
        $this->join = null;

        return $this;
    }

    /**
     * Reset the GROUP BY part of the query
     *
     * @return $this
     */
    public function resetGroupBy()
    {
        $this->groupBy = null;

        return $this;
    }

    /**
     * Reset the HAVING part of the query
     *
     * @return $this
     */
    public function resetHaving()
    {
        $this->having = null;

        return $this;
    }

    /**
     * Reset queries combined with UNION and UNION ALL
     *
     * @return $this
     */
    public function resetUnion()
    {
        $this->union = null;

        return $this;
    }

    /**
     * Get the count query
     *
     * @return Select
     */
    public function getCountQuery()
    {
        $countQuery = clone $this;

        $countQuery->orderBy = null;
        $countQuery->limit = null;
        $countQuery->offset = null;

        if (! empty($countQuery->groupBy) || $countQuery->getDistinct()) {
            $countQuery = (new Select())->from(['s' => $countQuery]);
            $countQuery->distinct(false);
        }

        $countQuery->columns = ['cnt' => 'COUNT(*)'];

        return $countQuery;
    }

    public function __clone()
    {
        $this->cloneCte();
        $this->cloneOrderBy();
        $this->cloneWhere();

        if ($this->columns !== null) {
            foreach ($this->columns as &$value) {
                if ($value instanceof ExpressionInterface || $value instanceof Select) {
                    $value = clone $value;
                }
            }
            unset($value);
        }

        if ($this->from !== null) {
            foreach ($this->from as &$from) {
                if ($from instanceof Select) {
                    $from = clone $from;
                }
            }
            unset($from);
        }

        if ($this->join !== null) {
            foreach ($this->join as &$join) {
                if (is_array($join[1])) {
                    foreach ($join[1] as &$table) {
                        if ($table instanceof Select) {
                            $table = clone $table;
                        }
                    }
                    unset($table);
                } elseif ($join[1] instanceof Select) {
                    $join[1] = clone $join[1];
                }

                $this->cloneCondition($join[2]);
            }
            unset($join);
        }

        if ($this->groupBy !== null) {
            foreach ($this->groupBy as &$value) {
                if ($value instanceof ExpressionInterface || $value instanceof Select) {
                    $value = clone $value;
                }
            }
            unset($value);
        }

        if ($this->having !== null) {
            $this->cloneCondition($this->having);
        }

        if ($this->union !== null) {
            foreach ($this->union as &$union) {
                $union[0] = clone $union[0];
            }
            unset($union);
        }
    }
}