Completed
Push — master ( e4d56c...8e58c0 )
by Ivan
02:47
created

TableQuery::order()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4.0092

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 11
cts 12
cp 0.9167
rs 9.6666
c 0
b 0
f 0
cc 4
nc 4
nop 2
crap 4.0092
1
<?php
2
namespace vakata\database\schema;
3
4
use vakata\collection\Collection;
5
use vakata\database\DBInterface;
6
use vakata\database\DBException;
7
use vakata\database\ResultInterface;
8
9
/**
10
 * A database query class
11
 */
12
class TableQuery implements \IteratorAggregate, \ArrayAccess, \Countable
13
{
14
    const SEP = '___';
15
    /**
16
     * @var DBInterface
17
     */
18
    protected $db;
19
    /**
20
     * @var Table
21
     */
22
    protected $definition;
23
    /**
24
     * @var TableQueryIterator|null
25
     */
26
    protected $qiterator;
27
28
    /**
29
     * @var array
30
     */
31
    protected $where = [];
32
    /**
33
     * @var array
34
     */
35
    protected $order = [];
36
    /**
37
     * @var array
38
     */
39
    protected $group = [];
40
    /**
41
     * @var array
42
     */
43
    protected $having = [];
44
    /**
45
     * @var int[]
46
     */
47
    protected $li_of = [0,0,0];
48
    /**
49
     * @var array
50
     */
51
    protected $fields = [];
52
    /**
53
     * @var array
54
     */
55
    protected $withr = [];
56
    /**
57
     * @var array
58
     */
59
    protected $joins = [];
60
    /**
61
     * @var array
62
     */
63
    protected $pkey = [];
64
    /**
65
     * @var array
66
     */
67
    protected $aliases = [];
68
69
    /**
70
     * Create an instance
71
     * @param  DBInterface    $db         the database connection
72
     * @param  Table|string   $table      the name or definition of the main table in the query
73
     */
74 117
    public function __construct(DBInterface $db, $table)
75
    {
76 117
        $this->db = $db;
77 117
        $this->definition = $table instanceof Table ? $table : $this->db->definition((string)$table);
78 117
        $primary = $this->definition->getPrimaryKey();
79 117
        $columns = $this->definition->getColumns();
80 117
        $this->pkey = count($primary) ? $primary : $columns;
81 117
        $this->columns($columns);
82 117
    }
83
    public function __clone()
84
    {
85
        $this->reset();
86
    }
87
    /**
88
     * Get the table definition of the queried table
89
     * @return Table        the definition
90
     */
91
    public function getDefinition() : Table
92
    {
93
        return $this->definition;
94
    }
95
96 117
    protected function getColumn($column)
97
    {
98 117
        $column = explode('.', $column);
99 117
        if (count($column) === 1) {
100 117
            $column = [ $this->definition->getName(), $column[0] ];
101 117
            $col = $this->definition->getColumn($column[1]);
102 117
            if (!$col) {
103 117
                throw new DBException('Invalid column name in own table');
104
            }
105 21
        } elseif (count($column) === 2) {
106 21
            if ($column[0] === $this->definition->getName()) {
107
                $col = $this->definition->getColumn($column[1]);
108
                if (!$col) {
109
                    throw new DBException('Invalid column name in own table');
110
                }
111
            } else {
112 21
                if ($this->definition->hasRelation($column[0])) {
113 18
                    $col = $this->definition->getRelation($column[0])->table->getColumn($column[1]);
114 18
                    if (!$col) {
115 18
                        throw new DBException('Invalid column name in related table');
116
                    }
117 3
                } elseif (isset($this->joins[$column[0]])) {
118 3
                    $col = $this->joins[$column[0]]->table->getColumn($column[1]);
119 3
                    if (!$col) {
120 3
                        throw new DBException('Invalid column name in related table');
121
                    }
122
                } else {
123 21
                    throw new DBException('Invalid foreign table name: ' . implode(',', $column));
124
                }
125
            }
126
        } else {
127
            $name = array_pop($column);
128
            $this->with(implode('.', $column));
129
            $table = $this->definition;
130
            $table = array_reduce(
131
                $column,
132
                function ($carry, $item) use (&$table) {
133
                    $table = $table->getRelation($item)->table;
134
                    return $table;
135
                }
136
            );
137
            $col = $table->getColumn($name);
138
            $column = [ implode(static::SEP, $column), $name ];
139
        }
140 117
        return [ 'name' => implode('.', $column), 'data' => $col ];
141
    }
142 57
    protected function normalizeValue(TableColumn $col, $value)
143
    {
144 57
        $strict = (int)$this->db->driverOption('strict', 0) > 0;
145 57
        if ($value === null && $col->isNullable()) {
146
            return null;
147
        }
148 57
        switch ($col->getBasicType()) {
149 57
            case 'date':
150
                if (is_string($value)) {
151
                    $temp = strtotime($value);
152
                    if (!$temp) {
153
                        if ($strict) {
154
                            throw new DBException('Invalid value for date column ' . $col->getName());
155
                        }
156
                        return null;
157
                    }
158
                    return date('Y-m-d', $temp);
159
                }
160
                if (is_int($value)) {
161
                    return date('Y-m-d', $value);
162
                }
163
                if ($value instanceof \DateTime) {
164
                    return $value->format('Y-m-d');
165
                }
166
                if ($strict) {
167
                    throw new DBException('Invalid value (unknown data type) for date column ' . $col->getName());
168
                }
169
                return $value;
170 57
            case 'datetime':
171
                if (is_string($value)) {
172
                    $temp = strtotime($value);
173
                    if (!$temp) {
174
                        if ($strict) {
175
                            throw new DBException('Invalid value for datetime column ' . $col->getName());
176
                        }
177
                        return null;
178
                    }
179
                    return date('Y-m-d H:i:s', $temp);
180
                }
181
                if (is_int($value)) {
182
                    return date('Y-m-d H:i:s', $value);
183
                }
184
                if ($value instanceof \DateTime) {
185
                    return $value->format('Y-m-d H:i:s');
186
                }
187
                if ($strict) {
188
                    throw new DBException('Invalid value (unknown data type) for datetime column ' . $col->getName());
189
                }
190
                return $value;
191 57
            case 'enum':
192
                $values = $col->getValues();
193
                if (is_int($value)) {
194
                    if (!isset($values[$value])) {
195
                        if ($strict) {
196
                            throw new DBException('Invalid value (using integer) for enum ' . $col->getName());
197
                        }
198
                        return $value;
199
                    }
200
                    return $values[$value];
201
                }
202
                if (!in_array($value, $col->getValues())) {
203
                    if ($strict) {
204
                        throw new DBException('Invalid value for enum ' . $col->getName());
205
                    }
206
                    return 0;
207
                }
208
                return $value;
209 57
            case 'int':
210 11
                $temp = preg_replace('([^+\-0-9]+)', '', $value);
211 11
                return is_string($temp) ? (int)$temp : 0;
212 50
            case 'float':
213
                $temp = preg_replace('([^+\-0-9.]+)', '', str_replace(',', '.', $value));
214
                return is_string($temp) ? (float)$temp : 0;
215 50
            case 'text':
216
                // check using strlen first, in order to avoid hitting mb_ functions which might be polyfilled
217
                // because the polyfill is quite slow
218 50
                if ($col->hasLength() && strlen($value) > $col->getLength() && mb_strlen($value) > $col->getLength()) {
219 6
                    if ($strict) {
220 3
                        throw new DBException('Invalid value for text column ' . $col->getName());
221
                    }
222 3
                    return mb_substr($value, 0, $col->getLength());
223
                }
224 46
                return $value;
225
            default: // time, blob, etc
226
                return $value;
227
        }
228
    }
229
230 45
    protected function filterSQL(string $column, $value, bool $negate = false) : array
231
    {
232 45
        list($name, $column) = array_values($this->getColumn($column));
233 45
        if (is_array($value) && count($value) === 1 && isset($value['not'])) {
234 3
            $negate = true;
235 3
            $value = $value['not'];
236
        }
237 45
        if (is_array($value) && count($value) === 1 && isset($value['like'])) {
238 3
            $value = $value['like'];
239
            // str_replace(['%', '_'], ['\\%','\\_'], $q)
240 3
            return $negate ?
241
                [
242
                    $name . ' NOT LIKE ?',
243
                    [ $this->normalizeValue($column, $value) ]
244
                ] :
245
                [
246 3
                    $name . ' LIKE ?',
247 3
                    [ $this->normalizeValue($column, $value) ]
248
                ];
249
        }
250 42
        if (is_null($value)) {
251
            return $negate ?
252
                [ $name . ' IS NOT NULL', [] ]:
253
                [ $name . ' IS NULL', [] ];
254
        }
255 42
        if (!is_array($value)) {
256 42
            return $negate ?
257
                [
258 3
                    $name . ' <> ?',
259 3
                    [ $this->normalizeValue($column, $value) ]
260
                ] :
261
                [
262 42
                    $name . ' = ?',
263 42
                    [ $this->normalizeValue($column, $value) ]
264
                ];
265
        }
266 9
        if (isset($value['beg']) && strlen($value['beg']) && (!isset($value['end']) || !strlen($value['end']))) {
267
            $value = [ 'gte' => $value['beg'] ];
268
        }
269 9
        if (isset($value['end']) && strlen($value['end']) && (!isset($value['beg']) || !strlen($value['beg']))) {
270
            $value = [ 'lte' => $value['end'] ];
271
        }
272 9
        if (isset($value['beg']) && isset($value['end'])) {
273
            return $negate ?
274
                [
275
                    $name.' NOT BETWEEN ? AND ?',
276
                    [
277
                        $this->normalizeValue($column, $value['beg']),
278
                        $this->normalizeValue($column, $value['end'])
279
                    ]
280
                ] :
281
                [
282
                    $name.' BETWEEN ? AND ?',
283
                    [
284
                        $this->normalizeValue($column, $value['beg']),
285
                        $this->normalizeValue($column, $value['end'])
286
                    ]
287
                ];
288
        }
289 9
        if (isset($value['gt']) || isset($value['lt']) || isset($value['gte']) || isset($value['lte'])) {
290 6
            $sql = [];
291 6
            $par = [];
292 6
            if (isset($value['gt'])) {
293 3
                $sql[] = $name. ' ' . ($negate ? '<=' : '>') . ' ?';
294 3
                $par[] = $this->normalizeValue($column, $value['gt']);
295
            }
296 6
            if (isset($value['gte'])) {
297 3
                $sql[] = $name. ' ' . ($negate ? '<' : '>=') . ' ?';
298 3
                $par[] = $this->normalizeValue($column, $value['gte']);
299
            }
300 6
            if (isset($value['lt'])) {
301 6
                $sql[] = $name. ' ' . ($negate ? '>=' : '<') . ' ?';
302 6
                $par[] = $this->normalizeValue($column, $value['lt']);
303
            }
304 6
            if (isset($value['lte'])) {
305 3
                $sql[] = $name. ' ' . ($negate ? '>' : '<=') . ' ?';
306 3
                $par[] = $this->normalizeValue($column, $value['lte']);
307
            }
308
            return [
309 6
                '(' . implode(' AND ', $sql) . ')',
310 6
                $par
311
            ];
312
        }
313 6
        return $negate ?
314
            [
315
                $name . ' NOT IN (??)',
316
                [ array_map(function ($v) use ($column) {
317
                    return $this->normalizeValue($column, $v);
318
                }, $value) ]
319
            ] :
320
            [
321 6
                $name . ' IN (??)',
322 6
                [ array_map(function ($v) use ($column) {
323 6
                    return $this->normalizeValue($column, $v);
324 6
                }, $value) ]
325
            ];
326
    }
327
    /**
328
     * Filter the results by a column and a value
329
     * @param  string $column  the column name to filter by (related columns can be used - for example: author.name)
330
     * @param  mixed  $value   a required value, array of values or range of values (range example: ['beg'=>1,'end'=>3])
331
     * @param  bool   $negate  optional boolean indicating that the filter should be negated
332
     * @return $this
333
     */
334 39
    public function filter(string $column, $value, bool $negate = false) : self
335
    {
336 39
        $sql = $this->filterSQL($column, $value, $negate);
337 39
        return strlen($sql[0]) ? $this->where($sql[0], $sql[1]) : $this;
338
    }
339
    /**
340
     * Filter the results matching any of the criteria
341
     * @param  array $criteria  each row is a column, value and optional negate flag (same as filter method)
342
     * @return $this
343
     */
344 12
    public function any(array $criteria) : self
345
    {
346 12
        $sql = [];
347 12
        $par = [];
348 12
        foreach ($criteria as $row) {
349 12
            if (isset($row[1])) {
350 12
                $temp = $this->filterSQL($row[0], $row[1] ?? null, $row[2] ?? false);
351 12
                $sql[] = $temp[0];
352 12
                $par = array_merge($par, $temp[1]);
353
            }
354
        }
355 12
        return $this->where('(' . implode(' OR ', $sql) . ')', $par);
356
    }
357
    /**
358
     * Filter the results matching all of the criteria
359
     * @param  array $criteria  each row is a column, value and optional negate flag (same as filter method)
360
     * @return $this
361
     */
362 9
    public function all(array $criteria) : self
363
    {
364 9
        $sql = [];
365 9
        $par = [];
366 9
        foreach ($criteria as $row) {
367 9
            if (isset($row[1])) {
368 9
                $temp = $this->filterSQL($row[0], $row[1] ?? null, $row[2] ?? false);
369 9
                $sql[] = $temp[0];
370 9
                $par = array_merge($par, $temp[1]);
371
            }
372
        }
373 9
        return $this->where('(' . implode(' AND ', $sql) . ')', $par);
374
    }
375
    /**
376
     * Sort by a column
377
     * @param  string       $column the column name to sort by (related columns can be used - for example: author.name)
378
     * @param  bool|boolean $desc   should the sorting be in descending order, defaults to `false`
379
     * @return $this
380
     */
381
    public function sort(string $column, bool $desc = false) : self
382
    {
383
        return $this->order($this->getColumn($column)['name'] . ' ' . ($desc ? 'DESC' : 'ASC'));
384
    }
385
    /**
386
     * Group by a column (or columns)
387
     * @param  string|array        $column the column name (or names) to group by
388
     * @return $this
389
     */
390 3
    public function group($column) : self
391
    {
392 3
        if (!is_array($column)) {
393 3
            $column = [ $column ];
394
        }
395 3
        foreach ($column as $k => $v) {
396 3
            $column[$k] = $this->getColumn($v)['name'];
397
        }
398 3
        return $this->groupBy(implode(', ', $column), []);
399
    }
400
    /**
401
     * Get a part of the data
402
     * @param  int|integer $page    the page number to get (1-based), defaults to 1
403
     * @param  int|integer $perPage the number of records per page - defaults to 25
404
     * @return $this
405
     */
406
    public function paginate(int $page = 1, int $perPage = 25) : self
407
    {
408
        return $this->limit($perPage, ($page - 1) * $perPage);
409
    }
410 3
    public function __call($name, $data)
411
    {
412 3
        if (strpos($name, 'filterBy') === 0) {
413
            return $this->filter(strtolower(substr($name, 8)), $data[0]);
414
        }
415 3
        if (strpos($name, 'sortBy') === 0) {
416
            return $this->sort(strtolower(substr($name, 6)), $data[0]);
417
        }
418 3
        if (strpos($name, 'groupBy') === 0) {
419 3
            return $this->group(strtolower(substr($name, 7)));
420
        }
421
    }
422
    /**
423
     * Remove all filters, sorting, etc
424
     * @return $this
425
     */
426 9
    public function reset() : self
427
    {
428 9
        $this->where = [];
429 9
        $this->joins = [];
430 9
        $this->group = [];
431 9
        $this->withr = [];
432 9
        $this->order = [];
433 9
        $this->having = [];
434 9
        $this->aliases = [];
435 9
        $this->li_of = [0,0,0];
436 9
        $this->qiterator = null;
437 9
        return $this;
438
    }
439
    /**
440
     * Apply advanced grouping
441
     * @param  string $sql    SQL statement to use in the GROUP BY clause
442
     * @param  array  $params optional params for the statement (defaults to an empty array)
443
     * @return $this
444
     */
445 3
    public function groupBy(string $sql, array $params = []) : self
446
    {
447 3
        $this->qiterator = null;
448 3
        $this->group = [ $sql, $params ];
449 3
        return $this;
450
    }
451
    /**
452
     * Join a table to the query (no need to do this for relations defined with foreign keys)
453
     * @param  Table|string $table     the table to join
454
     * @param  array        $fields    what to join on (joined_table_field => other_field)
455
     * @param  string|null  $name      alias for the join, defaults to the table name
456
     * @param  bool         $multiple  are multiple rows joined (results in a LEFT JOIN), default to true
457
     * @return $this
458
     */
459 3
    public function join($table, array $fields, string $name = null, bool $multiple = true)
460
    {
461 3
        $table = $table instanceof Table ? $table : $this->db->definition((string)$table);
462 3
        $name = $name ?? $table->getName();
463 3
        if (isset($this->joins[$name]) || $this->definition->hasRelation($name)) {
464
            throw new DBException('Alias / table name already in use');
465
        }
466 3
        $this->joins[$name] = new TableRelation($name, $table, [], $multiple);
467 3
        foreach ($fields as $k => $v) {
468 3
            $k = explode('.', $k, 2);
469 3
            $k = count($k) == 2 ? $k[1] : $k[0];
470 3
            $this->joins[$name]->keymap[$this->getColumn($name . '.' . $k)['name']] = $this->getColumn($v)['name'];
471
        }
472 3
        return $this;
473
    }
474
    /**
475
     * Apply an advanced filter (can be called multiple times)
476
     * @param  string $sql    SQL statement to be used in the where clause
477
     * @param  array  $params parameters for the SQL statement (defaults to an empty array)
478
     * @return $this
479
     */
480 48
    public function where(string $sql, array $params = []) : self
481
    {
482 48
        $this->qiterator = null;
483 48
        $this->where[] = [ $sql, $params ];
484 48
        return $this;
485
    }
486
    /**
487
     * Apply an advanced HAVING filter (can be called multiple times)
488
     * @param  string $sql    SQL statement to be used in the HAING clause
489
     * @param  array  $params parameters for the SQL statement (defaults to an empty array)
490
     * @return $this
491
     */
492 3
    public function having(string $sql, array $params = []) : self
493
    {
494 3
        $this->qiterator = null;
495 3
        $this->having[] = [ $sql, $params ];
496 3
        return $this;
497
    }
498
    /**
499
     * Apply advanced sorting
500
     * @param  string $sql    SQL statement to use in the ORDER clause
501
     * @param  array  $params optional params for the statement (defaults to an empty array)
502
     * @return $this
503
     */
504 6
    public function order(string $sql, array $params = []) : self
505
    {
506 6
        $this->qiterator = null;
507 6
        $name = null;
508 6
        if (!count($params)) {
509 6
            $name = preg_replace('(\s+(ASC|DESC)\s*$)i', '', $sql);
510
            try {
511 6
                if ($name === null) {
512
                    throw new \Exception();
513
                }
514 6
                $name = $this->getColumn(trim($name))['name'];
515 3
            } catch (\Exception $e) {
516 3
                $name = null;
517
            }
518
        }
519 6
        $this->order = [ $sql, $params, $name ];
520 6
        return $this;
521
    }
522
    /**
523
     * Apply an advanced limit
524
     * @param  int         $limit  number of rows to return
525
     * @param  int         $offset number of rows to skip from the beginning (defaults to 0)
526
     * @return $this
527
     */
528 3
    public function limit(int $limit, int $offset = 0, bool $limitOnMainTable = false) : self
529
    {
530 3
        $this->qiterator = null;
531 3
        $this->li_of = [ $limit, $offset, $limitOnMainTable ? 1 : 0 ];
532 3
        return $this;
533
    }
534
    /**
535
     * Get the number of records
536
     * @return int the total number of records (does not respect pagination)
537
     */
538 33
    public function count() : int
539
    {
540 33
        $aliases = [];
541 33
        $getAlias = function ($name) use (&$aliases) {
542
            // to bypass use: return $name;
543 9
            return $aliases[$name] = $aliases[$name] ?? 'alias' . static::SEP . count($aliases);
544 33
        };
545 33
        $table = $this->definition->getName();
546 33
        $sql = 'SELECT COUNT(DISTINCT '.$table.'.'.implode(', '.$table.'.', $this->pkey).') FROM '.$table.' ';
547 33
        $par = [];
548
        
549 33
        $relations = $this->withr;
550 33
        foreach ($relations as $k => $v) {
551
            $getAlias($k);
552
        }
553 33
        $w = $this->where;
554 33
        $h = $this->having;
555 33
        $o = $this->order;
556 33
        $g = $this->group;
557 33
        $j = array_map(function ($v) {
558
            return clone $v;
559 33
        }, $this->joins);
560 33
        foreach ($this->definition->getRelations() as $k => $v) {
561 33
            foreach ($w as $kk => $vv) {
562 18
                if (preg_match('(\b'.preg_quote($k . '.'). ')i', $vv[0])) {
563 9
                    $relations[$k] = [ $v, $table ];
564 9
                    $w[$kk][0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $vv[0]);
565
                }
566
            }
567 33
            if (isset($o[0]) && preg_match('(\b'.preg_quote($k . '.'). ')i', $o[0])) {
568
                $relations[$k] = [ $v, $table ];
569
            }
570 33
            foreach ($h as $kk => $vv) {
571
                if (preg_match('(\b'.preg_quote($k . '.'). ')i', $vv[0])) {
572
                    $relations[$k] = [ $v, $table ];
573
                    $h[$kk][0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $vv[0]);
574
                }
575
            }
576 33
            if (isset($g[0]) && preg_match('(\b'.preg_quote($k . '.'). ')i', $g[0])) {
577
                $relations[$k] = [ $v, $table ];
578
                $g[0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $g[0]);
579
            }
580 33
            foreach ($j as $kk => $vv) {
581
                foreach ($vv->keymap as $kkk => $vvv) {
582
                    if (preg_match('(\b'.preg_quote($k . '.'). ')i', $vvv)) {
583
                        $relations[$k] = [ $v, $table ];
584
                        $j[$kk]->keymap[$kkk] =
585
                            preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $vvv);
586
                    }
587
                }
588
            }
589
        }
590
591 33
        foreach ($j as $k => $v) {
592
            $sql .= ($v->many ? 'LEFT ' : '' ) . 'JOIN '.$v->table->getName().' '.$k.' ON ';
593
            $tmp = [];
594
            foreach ($v->keymap as $kk => $vv) {
595
                $tmp[] = $kk.' = '.$vv;
596
            }
597
            $sql .= implode(' AND ', $tmp) . ' ';
598
        }
599 33
        foreach ($relations as $k => $v) {
600 9
            $table = $v[1] !== $this->definition->getName() ? $getAlias($v[1]) : $v[1];
601 9
            $v = $v[0];
602 9
            if ($v->pivot) {
603 9
                $alias = $getAlias($k.'_pivot');
604 9
                $sql .= 'LEFT JOIN '.$v->pivot->getName().' '.$alias.' ON ';
605 9
                $tmp = [];
606 9
                foreach ($v->keymap as $kk => $vv) {
607 9
                    $tmp[] = $table.'.'.$kk.' = '.$alias.'.'.$vv.' ';
608
                }
609 9
                $sql .= implode(' AND ', $tmp) . ' ';
610 9
                $sql .= 'LEFT JOIN '.$v->table->getName().' '.$getAlias($k).' ON ';
611 9
                $tmp = [];
612 9
                foreach ($v->pivot_keymap as $kk => $vv) {
613 9
                    $tmp[] = $getAlias($k).'.'.$vv.' = '.$alias.'.'.$kk.' ';
614
                }
615 9
                $sql .= implode(' AND ', $tmp) . ' ';
616
            } else {
617 9
                $alias = $getAlias($k);
618 9
                $sql .= 'LEFT JOIN '.$v->table->getName().' '.$alias.' ON ';
619 9
                $tmp = [];
620 9
                foreach ($v->keymap as $kk => $vv) {
621 9
                    $tmp[] = $table.'.'.$kk.' = '.$alias.'.'.$vv.' ';
622
                }
623 9
                if ($v->sql) {
624
                    $tmp[] = $v->sql . ' ';
625
                    $par = array_merge($par, $v->par ?? []);
626
                }
627 9
                $sql .= implode(' AND ', $tmp) . ' ';
628
            }
629
        }
630 33
        if (count($w)) {
631 18
            $sql .= 'WHERE ';
632 18
            $tmp = [];
633 18
            foreach ($w as $v) {
634 18
                $tmp[] = '(' . $v[0] . ')';
635 18
                $par = array_merge($par, $v[1]);
636
            }
637 18
            $sql .= implode(' AND ', $tmp).' ';
638
        }
639 33
        if (count($g)) {
640
            $sql .= 'GROUP BY ' . $g[0] . ' ';
641
            $par = array_merge($par, $g[1]);
642
        }
643 33
        if (count($h)) {
644
            $sql .= 'HAVING ';
645
            $tmp = [];
646
            foreach ($h as $v) {
647
                $tmp[] = '(' . $v[0] . ')';
648
                $par = array_merge($par, $v[1]);
649
            }
650
            $sql .= implode(' AND ', $tmp).' ';
651
        }
652 33
        return $this->db->one($sql, $par);
653
    }
654
    /**
655
     * Specify which columns to fetch (be default all table columns are fetched)
656
     * @param  array $fields optional array of columns to select (related columns can be used too)
657
     * @return $this
658
     */
659 117
    public function columns(array $fields) : self
660
    {
661 117
        foreach ($fields as $k => $v) {
662 117
            if (strpos($v, '*') !== false) {
663
                $temp = explode('.', $v);
664
                if (count($temp) === 1) {
665
                    $table = $this->definition->getName();
666
                    $cols = $this->definition->getColumns();
667
                } elseif (count($temp) === 2) {
668
                    $table = $temp[0];
669
                    if ($this->definition->hasRelation($table)) {
670
                        $cols = $this->definition->getRelation($table)->table->getColumns();
671
                    } elseif (isset($this->joins[$table])) {
672
                        $cols = $this->joins[$table]->table->getColumns();
673
                    } else {
674
                        throw new DBException('Invalid foreign table name');
675
                    }
676
                } else {
677
                    array_pop($temp);
678
                    $this->with(implode('.', $temp));
679
                    $table = array_reduce(
680
                        $temp,
681
                        function ($carry, $item) use (&$table) {
682
                            return $table->getRelation($item)->table;
683
                        }
684
                    );
685
                    $cols = $table->getColumns();
686
                    $table = implode(static::SEP, $temp);
687
                }
688
                unset($fields[$k]);
689
                foreach ($cols as $col) {
690
                    $fields[] = $table . '.' . $col;
691
                }
692
            }
693
        }
694 117
        $primary = $this->definition->getPrimaryKey();
695 117
        foreach ($fields as $k => $v) {
696
            try {
697 117
                $fields[$k] = $this->getColumn($v)['name'];
698 3
            } catch (DBException $e) {
699 3
                $fields[$k] = $v;
700
            }
701
        }
702 117
        foreach ($primary as $field) {
703 117
            $field = $this->getColumn($field)['name'];
704 117
            if (!in_array($field, $fields)) {
705
                $fields[] = $field;
706
            }
707
        }
708 117
        $this->fields = $fields;
709 117
        return $this;
710
    }
711
    /**
712
     * Perform the actual fetch
713
     * @param  array|null $fields optional array of columns to select (related columns can be used too)
714
     * @return mixed               the query result as an iterator (with array access)
715
     */
716 90
    public function iterator(array $fields = null)
717
    {
718 90
        if ($this->qiterator) {
719 60
            return $this->qiterator;
720
        }
721 90
        $aliases = [];
722 90
        $getAlias = function ($name) use (&$aliases) {
723
            // to bypass use: return $name;
724 24
            return $aliases[$name] = $aliases[$name] ?? 'alias' . static::SEP . count($aliases);
725 90
        };
726 90
        $table = $this->definition->getName();
727 90
        if ($fields !== null) {
728 3
            $this->columns($fields);
729
        }
730 90
        $relations = $this->withr;
731 90
        foreach ($relations as $k => $v) {
732 18
            $getAlias($k);
733
        }
734
735 90
        $f = $this->fields;
736 90
        $w = $this->where;
737 90
        $h = $this->having;
738 90
        $o = $this->order;
739 90
        $g = $this->group;
740 90
        $j = array_map(function ($v) {
741 3
            return clone $v;
742 90
        }, $this->joins);
743
744 90
        $porder = [];
745 90
        foreach ($this->definition->getPrimaryKey() as $field) {
746 90
            $porder[] = $this->getColumn($field)['name'];
747
        }
748
749 90
        foreach ($this->definition->getRelations() as $k => $relation) {
750 90
            foreach ($f as $kk => $field) {
751 90
                if (strpos($field, $k . '.') === 0) {
752
                    $relations[$k] = [ $relation, $table ];
753
                    $f[$kk] = str_replace($k . '.', $getAlias($k) . '.', $field);
754
                }
755
            }
756 90
            foreach ($w as $kk => $v) {
757 12
                if (preg_match('(\b'.preg_quote($k . '.'). ')i', $v[0])) {
758 6
                    $relations[$k] = [ $relation, $table ];
759 6
                    $w[$kk][0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $v[0]);
760
                }
761
            }
762 90
            foreach ($h as $kk => $v) {
763 3
                if (preg_match('(\b'.preg_quote($k . '.'). ')i', $v[0])) {
764
                    $relations[$k] = [ $relation, $table ];
765
                    $h[$kk][0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $v[0]);
766
                }
767
            }
768 90
            if (isset($o[0]) && preg_match('(\b'.preg_quote($k . '.'). ')i', $o[0])) {
769
                $relations[$k] = [ $relation, $table ];
770
                $o[0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $o[0]);
771
            }
772 90
            if (isset($g[0]) && preg_match('(\b'.preg_quote($k . '.'). ')i', $g[0])) {
773
                $relations[$k] = [ $relation, $table ];
774
                $g[0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $g[0]);
775
            }
776 90
            foreach ($j as $kk => $v) {
777 3
                foreach ($v->keymap as $kkk => $vv) {
778 3
                    if (preg_match('(\b'.preg_quote($k . '.'). ')i', $vv)) {
779
                        $relations[$k] = [ $relation, $table ];
780
                        $j[$k]->keymap[$kkk] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $vv);
781
                    }
782
                }
783
            }
784
        }
785 90
        $select = [];
786 90
        foreach ($f as $k => $field) {
787 90
            $select[] = $field . (!is_numeric($k) ? ' ' . $k : '');
788
        }
789 90
        foreach ($this->withr as $name => $relation) {
790 18
            foreach ($relation[0]->table->getColumns() as $column) {
791 18
                $select[] = $getAlias($name) . '.' . $column . ' ' . $getAlias($name . static::SEP . $column);
792
            }
793
        }
794 90
        $sql = 'SELECT '.implode(', ', $select).' FROM '.$table.' ';
795 90
        $par = [];
796 90
        $many = false;
797 90
        foreach ($j as $k => $v) {
798 3
            if ($v->many) {
799 3
                $many = true;
800
            }
801 3
            $sql .= ($v->many ? 'LEFT ' : '' ) . 'JOIN '.$v->table->getName().' '.$k.' ON ';
802 3
            $tmp = [];
803 3
            foreach ($v->keymap as $kk => $vv) {
804 3
                $tmp[] = $kk.' = '.$vv;
805
            }
806 3
            $sql .= implode(' AND ', $tmp) . ' ';
807
        }
808 90
        foreach ($relations as $relation => $v) {
809 24
            $table = $v[1] !== $this->definition->getName() ? $getAlias($v[1]) : $v[1];
810 24
            $v = $v[0];
811 24
            if ($v->many || $v->pivot) {
812 18
                $many = true;
813
            }
814 24
            if ($v->pivot) {
815 15
                $alias = $getAlias($relation.'_pivot');
816 15
                $sql .= 'LEFT JOIN '.$v->pivot->getName().' '.$alias.' ON ';
817 15
                $tmp = [];
818 15
                foreach ($v->keymap as $kk => $vv) {
819 15
                    $tmp[] = $table.'.'.$kk.' = '.$alias.'.'.$vv.' ';
820
                }
821 15
                $sql .= implode(' AND ', $tmp) . ' ';
822 15
                $sql .= 'LEFT JOIN '.$v->table->getName().' '.$getAlias($relation).' ON ';
823 15
                $tmp = [];
824 15
                foreach ($v->pivot_keymap as $kk => $vv) {
825 15
                    $tmp[] = $getAlias($relation).'.'.$vv.' = '.$alias.'.'.$kk.' ';
826
                }
827 15
                $sql .= implode(' AND ', $tmp) . ' ';
828
            } else {
829 18
                $alias = $getAlias($relation);
830
831 18
                $sql .= 'LEFT JOIN '.$v->table->getName().' '.$alias.' ON ';
832 18
                $tmp = [];
833 18
                foreach ($v->keymap as $kk => $vv) {
834 18
                    $tmp[] = $table.'.'.$kk.' = '.$alias.'.'.$vv.' ';
835
                }
836 18
                if ($v->sql) {
837
                    $tmp[] = $v->sql . ' ';
838
                    $par = array_merge($par, $v->par ?? []);
839
                }
840 18
                $sql .= implode(' AND ', $tmp) . ' ';
841
            }
842
        }
843
844 90
        if ($many && count($porder) && $this->li_of[2] === 1) {
845
            $ids = $this->ids();
846
            if (count($ids)) {
847
                if (count($porder) > 1) {
848
                    $pkw = [];
849
                    foreach ($porder as $name) {
850
                        $pkw[] = $name . ' = ?';
851
                    }
852
                    $pkw = '(' . implode(' AND ', $pkw) . ')';
853
                    $pkp = [];
854
                    foreach ($ids as $id) {
855
                        foreach ($id as $p) {
856
                            $pkp[] = $p;
857
                        }
858
                    }
859
                    $w[] = [
860
                        implode(' OR ', array_fill(0, count($ids), $pkw)),
861
                        $pkp
862
                    ];
863
                } else {
864
                    $w[] = [ $porder[0] . ' IN ('.implode(',', array_fill(0, count($ids), '?')).')', $ids ];
865
                }
866
            } else {
867
                $w[] = [ '1=0', [] ];
868
            }
869
        }
870 90
        if (count($w)) {
871 12
            $sql .= 'WHERE ';
872 12
            $tmp = [];
873 12
            foreach ($w as $v) {
874 12
                $tmp[] = '(' . $v[0] . ')';
875 12
                $par = array_merge($par, $v[1]);
876
            }
877 12
            $sql .= implode(' AND ', $tmp).' ';
878
        }
879 90
        if (count($g)) {
880 3
            $sql .= 'GROUP BY ' . $g[0] . ' ';
881 3
            $par = array_merge($par, $g[1]);
882
        }
883 90
        if (count($h)) {
884 3
            $sql .= 'HAVING ';
885 3
            $tmp = [];
886 3
            foreach ($h as $v) {
887 3
                $tmp[] = '(' . $v[0] . ')';
888 3
                $par = array_merge($par, $v[1]);
889
            }
890 3
            $sql .= implode(' AND ', $tmp).' ';
891
        }
892 90
        if (count($o)) {
893 3
            $sql .= 'ORDER BY ' . $o[0] . ' ';
894 3
            $par = array_merge($par, $o[1]);
895
        }
896 90
        if (count($porder)) {
897 90
            $pdir = (count($o) && strpos($o[0], 'DESC') !== false) ? 'DESC' : 'ASC';
898 90
            $porder = array_map(function ($v) use ($pdir) {
899 90
                return $v . ' ' . $pdir;
900 90
            }, $porder);
901 90
            $sql .= (count($o) ? ', ' : 'ORDER BY ') . implode(', ', $porder) . ' ';
902
        }
903 90
        if ((!$many || $this->li_of[2] === 0 || !count($porder)) && $this->li_of[0]) {
904 3
            if ($this->db->driverName() === 'oracle') {
905
                if ((int)$this->db->driverOption('version', 0) >= 12) {
906
                    $sql .= 'OFFSET ' . $this->li_of[1] . ' ROWS FETCH NEXT ' . $this->li_of[0] . ' ROWS ONLY';
907
                } else {
908
                    $f = array_map(function ($v) {
909
                        $v = explode(' ', trim($v), 2);
910
                        if (count($v) === 2) {
911
                            return $v[1];
912
                        }
913
                        $v = explode('.', $v[0], 2);
914
                        return count($v) === 2 ? $v[1] : $v[0];
915
                    }, $select);
916
                    $sql = "SELECT " . implode(', ', $f) . " 
917
                            FROM (
918
                                SELECT tbl__.*, rownum rnum__ FROM (
919
                                    " . $sql . "
920
                                ) tbl__ 
921
                                WHERE rownum <= " . ($this->li_of[0] + $this->li_of[1]) . "
922
                            ) WHERE rnum__ > " . $this->li_of[1];
923
                }
924
            } else {
925 3
                $sql .= 'LIMIT ' . $this->li_of[0] . ' OFFSET ' . $this->li_of[1];
926
            }
927
        }
928 90
        return $this->qiterator = new TableQueryIterator(
929 90
            $this->db->get($sql, $par, null, false, false),
930 90
            $this->pkey,
931 90
            $this->withr,
932 90
            $aliases
933
        );
934
    }
935
    /**
936
     * Perform the actual fetch
937
     * @param  array|null $fields optional array of columns to select (related columns can be used too)
938
     * @return array               the query result as an array
939
     */
940 3
    public function select(array $fields = null) : array
941
    {
942 3
        return iterator_to_array($this->iterator($fields));
943
    }
944
    /**
945
     * Insert a new row in the table
946
     * @param  array   $data   key value pairs, where each key is the column name and the value is the value to insert
947
     * @return array           the inserted ID where keys are column names and values are column values
948
     */
949 12
    public function insert(array $data) : array
950
    {
951 12
        $table = $this->definition->getName();
952 12
        $columns = $this->definition->getFullColumns();
953 12
        $insert = [];
954 12
        foreach ($data as $column => $value) {
955 12
            if (isset($columns[$column])) {
956 12
                $insert[$column] = $this->normalizeValue($columns[$column], $value);
957
            }
958
        }
959 9
        if (!count($insert)) {
960
            throw new DBException('No valid columns to insert');
961
        }
962 9
        $sql = 'INSERT INTO '.$table.' ('.implode(', ', array_keys($insert)).') VALUES (??)';
963 9
        $par = [$insert];
964 9
        $primary = $this->definition->getPrimaryKey();
965 9
        if (!count($primary)) {
966
            $this->db->query($sql, $par);
967
            return [];
968
        }
969 9
        if ($this->db->driverName() === 'oracle') {
970
            $ret = [];
971
            foreach ($primary as $k) {
972
                $ret[$k] = str_repeat(' ', 255);
973
                $par[] = &$ret[$k];
974
            }
975
            $sql .= ' RETURNING ' . implode(',', $primary) .
976
                ' INTO ' . implode(',', array_fill(0, count($primary), '?'));
977
            $this->db->query($sql, $par);
978
            return $ret;
979
        } else {
980 9
            $ret = [];
981 9
            $ins = $this->db->query($sql, $par)->insertID();
982 9
            foreach ($primary as $k) {
983 9
                $ret[$k] = $data[$k] ?? $ins;
984
            }
985 9
            return $ret;
986
        }
987
    }
988
    /**
989
     * Update the filtered rows with new data
990
     * @param  array  $data key value pairs, where each key is the column name and the value is the value to insert
991
     * @return int          the number of affected rows
992
     */
993 9
    public function update(array $data) : int
994
    {
995 9
        $table = $this->definition->getName();
996 9
        $columns = $this->definition->getFullColumns();
997 9
        $update = [];
998 9
        foreach ($data as $column => $value) {
999 9
            if (isset($columns[$column])) {
1000 9
                $update[$column] = $this->normalizeValue($columns[$column], $value);
1001
            }
1002
        }
1003 9
        if (!count($update)) {
1004
            throw new DBException('No valid columns to update');
1005
        }
1006 9
        $sql = 'UPDATE '.$table.' SET ';
1007 9
        $par = [];
1008 9
        $sql .= implode(', ', array_map(function ($v) {
1009 9
            return $v . ' = ?';
1010 9
        }, array_keys($update))) . ' ';
1011 9
        $par = array_merge($par, array_values($update));
1012 9
        if (count($this->where)) {
1013 9
            $sql .= 'WHERE ';
1014 9
            $tmp = [];
1015 9
            foreach ($this->where as $v) {
1016 9
                $tmp[] = $v[0];
1017 9
                $par = array_merge($par, $v[1]);
1018
            }
1019 9
            $sql .= implode(' AND ', $tmp) . ' ';
1020
        }
1021 9
        if (count($this->order)) {
1022
            $sql .= $this->order[0];
1023
            $par = array_merge($par, $this->order[1]);
1024
        }
1025 9
        return $this->db->query($sql, $par)->affected();
1026
    }
1027
    /**
1028
     * Delete the filtered rows from the DB
1029
     * @return int the number of deleted rows
1030
     */
1031 6
    public function delete() : int
1032
    {
1033 6
        $table = $this->definition->getName();
1034 6
        $sql = 'DELETE FROM '.$table.' ';
1035 6
        $par = [];
1036 6
        if (count($this->where)) {
1037 6
            $sql .= 'WHERE ';
1038 6
            $tmp = [];
1039 6
            foreach ($this->where as $v) {
1040 6
                $tmp[] = $v[0];
1041 6
                $par = array_merge($par, $v[1]);
1042
            }
1043 6
            $sql .= implode(' AND ', $tmp) . ' ';
1044
        }
1045 6
        if (count($this->order)) {
1046
            $sql .= $this->order[0];
1047
            $par = array_merge($par, $this->order[1]);
1048
        }
1049 6
        return $this->db->query($sql, $par)->affected();
1050
    }
1051
    /**
1052
     * Solve the n+1 queries problem by prefetching a relation by name
1053
     * @param  string $relation the relation name to fetch along with the data
1054
     * @return $this
1055
     */
1056 21
    public function with(string $relation) : self
1057
    {
1058 21
        $this->qiterator = null;
1059 21
        $parts = explode('.', $relation);
1060 21
        $table = $this->definition;
1061 21
        array_reduce(
1062 21
            $parts,
1063 21
            function ($carry, $item) use (&$table) {
1064 21
                if (!$table->hasRelation($item)) {
1065
                    throw new DBException('Invalid relation name');
1066
                }
1067 21
                $relation = $table->getRelation($item);
1068 21
                $name = $carry ? $carry . static::SEP . $item : $item;
1069 21
                $this->withr[$name] = [ $relation, $carry ?? $table->getName() ];
1070 21
                $table = $relation->table;
1071 21
                return $name;
1072 21
            }
1073
        );
1074 21
        return $this;
1075
    }
1076
1077 15
    public function getIterator()
1078
    {
1079 15
        return $this->iterator();
1080
    }
1081
1082 78
    public function offsetGet($offset)
1083
    {
1084 78
        return $this->iterator()->offsetGet($offset);
1085
    }
1086
    public function offsetExists($offset)
1087
    {
1088
        return $this->iterator()->offsetExists($offset);
1089
    }
1090
    public function offsetUnset($offset)
1091
    {
1092
        $this->iterator()->offsetUnset($offset);
1093
    }
1094
    public function offsetSet($offset, $value)
1095
    {
1096
        $this->iterator()->offsetSet($offset, $value);
1097
    }
1098
1099
    public function collection(array $fields = null) : Collection
1100
    {
1101
        return new Collection($this->iterator($fields));
1102
    }
1103
1104 3
    public function ids()
1105
    {
1106 3
        if (count($this->group)) {
1107
            throw new DBException('Can not LIMIT result set by master table when GROUP BY is used');
1108
        }
1109 3
        if (count($this->order) && !isset($this->order[2])) {
1110
            throw new DBException('Can not LIMIT result set by master table with a complex ORDER BY query');
1111
        }
1112
1113 3
        $aliases = [];
1114 3
        $getAlias = function ($name) use (&$aliases) {
1115
            // to bypass use: return $name;
1116 3
            return $aliases[$name] = $aliases[$name] ?? 'alias' . static::SEP . count($aliases);
1117 3
        };
1118
        
1119 3
        $table = $this->definition->getName();
1120 3
        $relations = $this->withr;
1121 3
        foreach ($relations as $k => $v) {
1122 3
            $getAlias($k);
1123
        }
1124 3
        $w = $this->where;
1125 3
        $h = $this->having;
1126 3
        $o = $this->order;
1127 3
        $g = $this->group;
1128 3
        $j = array_map(function ($v) {
1129
            return clone $v;
1130 3
        }, $this->joins);
1131 3
        foreach ($this->definition->getRelations() as $k => $v) {
1132 3
            foreach ($w as $kk => $vv) {
1133 3
                if (preg_match('(\b'.preg_quote($k . '.'). ')i', $vv[0])) {
1134 3
                    $relations[$k] = [ $v, $table ];
1135 3
                    $w[$kk][0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $vv[0]);
1136
                }
1137
            }
1138 3
            if (isset($o[0]) && preg_match('(\b'.preg_quote($k . '.'). ')i', $o[0])) {
1139 3
                $relations[$k] = [ $v, $table ];
1140 3
                $o[0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $o[0]);
1141 3
                $o[2] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $o[2]);
1142
            }
1143 3
            foreach ($h as $kk => $vv) {
1144
                if (preg_match('(\b'.preg_quote($k . '.'). ')i', $vv[0])) {
1145
                    $relations[$k] = [ $v, $table ];
1146
                    $h[$kk][0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $vv[0]);
1147
                }
1148
            }
1149 3
            if (isset($g[0]) && preg_match('(\b'.preg_quote($k . '.'). ')i', $g[0])) {
1150
                $relations[$k] = [ $v, $table ];
1151
                $g[0] = preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $g[0]);
1152
            }
1153 3
            foreach ($j as $kk => $vv) {
1154
                foreach ($vv->keymap as $kkk => $vvv) {
1155
                    if (preg_match('(\b'.preg_quote($k . '.'). ')i', $vvv)) {
1156
                        $relations[$k] = [ $v, $table ];
1157
                        $j[$kk]->keymap[$kkk] =
1158
                            preg_replace('(\b'.preg_quote($k . '.'). ')i', $getAlias($k) . '.', $vvv);
1159
                    }
1160
                }
1161
            }
1162
        }
1163
1164 3
        $key = array_map(function ($v) use ($table) {
1165 3
            return $table . '.' . $v;
1166 3
        }, $this->pkey);
1167 3
        $own = false;
1168 3
        $dir = 'ASC';
1169 3
        if (count($o)) {
1170 3
            $dir = strpos($o[0], ' DESC') ? 'DESC' : 'ASC';
1171 3
            $own = strpos($o[2], $table . '.') === 0;
1172
        }
1173
1174 3
        $dst = $key;
1175 3
        if ($own) {
1176
            // if using own table - do not use max/min in order - that will prevent index usage
1177
            $dst[] = $o[2] . ' orderbyfix___';
1178
        } else {
1179 3
            $dst[] = 'MAX(' . $o[2] . ') orderbyfix___';
1180
        }
1181 3
        $dst = array_unique($dst);
1182
1183 3
        $par = [];
1184 3
        $sql  = 'SELECT DISTINCT '.implode(', ', $dst).' FROM '.$table.' ';
1185 3
        foreach ($j as $k => $v) {
1186
            $sql .= ($v->many ? 'LEFT ' : '' ) . 'JOIN '.$v->table->getName().' '.$k.' ON ';
1187
            $tmp = [];
1188
            foreach ($v->keymap as $kk => $vv) {
1189
                $tmp[] = $kk.' = '.$vv;
1190
            }
1191
            $sql .= implode(' AND ', $tmp) . ' ';
1192
        }
1193 3
        foreach ($relations as $k => $v) {
1194 3
            $table = $v[1] !== $this->definition->getName() ? $getAlias($v[1]) : $v[1];
1195 3
            $v = $v[0];
1196 3
            if ($v->pivot) {
1197
                $alias = $getAlias($k.'_pivot');
1198
                $sql .= 'LEFT JOIN '.$v->pivot->getName().' '.$alias.' ON ';
1199
                $tmp = [];
1200
                foreach ($v->keymap as $kk => $vv) {
1201
                    $tmp[] = $table.'.'.$kk.' = '.$alias.'.'.$vv.' ';
1202
                }
1203
                $sql .= implode(' AND ', $tmp) . ' ';
1204
                $sql .= 'LEFT JOIN '.$v->table->getName().' '.$getAlias($k).' ON ';
1205
                $tmp = [];
1206
                foreach ($v->pivot_keymap as $kk => $vv) {
1207
                    $tmp[] = $getAlias($k).'.'.$vv.' = '.$alias.'.'.$kk.' ';
1208
                }
1209
                $sql .= implode(' AND ', $tmp) . ' ';
1210
            } else {
1211 3
                $alias = $getAlias($k);
1212 3
                $sql .= 'LEFT JOIN '.$v->table->getName().' '.$alias.' ON ';
1213 3
                $tmp = [];
1214 3
                foreach ($v->keymap as $kk => $vv) {
1215 3
                    $tmp[] = $table.'.'.$kk.' = '.$alias.'.'.$vv.' ';
1216
                }
1217 3
                if ($v->sql) {
1218
                    $tmp[] = $v->sql . ' ';
1219
                    $par = array_merge($par, $v->par ?? []);
1220
                }
1221 3
                $sql .= implode(' AND ', $tmp) . ' ';
1222
            }
1223
        }
1224 3
        if (count($w)) {
1225 3
            $sql .= 'WHERE ';
1226 3
            $tmp = [];
1227 3
            foreach ($w as $v) {
1228 3
                $tmp[] = '(' . $v[0] . ')';
1229 3
                $par = array_merge($par, $v[1]);
1230
            }
1231 3
            $sql .= implode(' AND ', $tmp).' ';
1232
        }
1233 3
        if (!$own) {
1234 3
            $sql .= 'GROUP BY ' . implode(', ', $key) . ' ';
1235
        }
1236 3
        if (count($h)) {
1237
            $sql .= 'HAVING ';
1238
            $tmp = [];
1239
            foreach ($h as $v) {
1240
                $tmp[] = '(' . $v[0] . ')';
1241
                $par = array_merge($par, $v[1]);
1242
            }
1243
            $sql .= implode(' AND ', $tmp).' ';
1244
        }
1245 3
        if (count($o)) {
1246 3
            $sql .= 'ORDER BY ';
1247 3
            if ($own) {
1248
                $sql .= $o[2] . ' ' . $dir;
1249
            } else {
1250 3
                $sql .= 'MAX('.$o[2].') ' . $dir;
1251
            }
1252
        }
1253 3
        $porder = [];
1254 3
        $pdir = (count($o) && strpos($o[0], 'DESC') !== false) ? 'DESC' : 'ASC';
1255 3
        foreach ($this->definition->getPrimaryKey() as $field) {
1256 3
            $porder[] = $this->getColumn($field)['name'] . ' ' . $pdir;
1257
        }
1258 3
        if (count($porder)) {
1259 3
            $sql .= (count($o) ? ', ' : 'ORDER BY ') . implode(', ', $porder) . ' ';
1260
        }
1261
1262 3
        if ($this->li_of[0]) {
1263
            if ($this->db->driverName() === 'oracle') {
1264
                if ((int)$this->db->driverOption('version', 0) >= 12) {
1265
                    $sql .= 'OFFSET ' . $this->li_of[1] . ' ROWS FETCH NEXT ' . $this->li_of[0] . ' ROWS ONLY';
1266
                } else {
1267
                    $sql = "SELECT " . implode(', ', $dst) . " 
1268
                            FROM (
1269
                                SELECT tbl__.*, rownum rnum__ FROM (
1270
                                    " . $sql . "
1271
                                ) tbl__ 
1272
                                WHERE rownum <= " . ($this->li_of[0] + $this->li_of[1]) . "
1273
                            ) WHERE rnum__ > " . $this->li_of[1];
1274
                }
1275
            } else {
1276
                $sql .= 'LIMIT ' . $this->li_of[0] . ' OFFSET ' . $this->li_of[1];
1277
            }
1278
        }
1279 3
        return array_map(function ($v) {
1280 3
            if (isset($v['orderbyfix___'])) {
1281 3
                unset($v['orderbyfix___']);
1282
            }
1283 3
            return count($v) === 1 ? array_values($v)[0] : $v;
1284 3
        }, $this->db->all($sql, $par, null, false, false));
1285
    }
1286
    public function find($primary)
1287
    {
1288
        $columns = $this->definition->getPrimaryKey();
1289
        if (!count($columns)) {
1290
            throw new DBException('Missing primary key');
1291
        }
1292
        if (!is_array($primary)) {
1293
            $temp = [];
1294
            $temp[$columns[0]] = $primary;
1295
            $primary = $temp;
1296
        }
1297
        foreach ($columns as $k) {
1298
            if (!isset($primary[$k])) {
1299
                throw new DBException('Missing primary key component');
1300
            }
1301
            $this->filter($k, $primary[$k]);
1302
        }
1303
        return $this->iterator()[0];
1304
    }
1305
}
1306