1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace LaravelFreelancerNL\Aranguent\Query\Concerns; |
6
|
|
|
|
7
|
|
|
use Illuminate\Database\Query\Builder as IlluminateBuilder; |
8
|
|
|
use LaravelFreelancerNL\Aranguent\Query\Builder; |
9
|
|
|
|
10
|
|
|
trait CompilesUnions |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Compile the "union" queries attached to the main query. |
14
|
|
|
* |
15
|
|
|
* @param Builder $query |
16
|
|
|
* @param string $firstQuery |
17
|
|
|
* @return string |
18
|
|
|
*/ |
19
|
5 |
|
protected function compileUnions(IlluminateBuilder $query, $firstQuery = '') |
20
|
|
|
{ |
21
|
5 |
|
if (!is_array($query->unions)) { |
22
|
|
|
return ''; |
23
|
|
|
} |
24
|
|
|
|
25
|
5 |
|
$unionResultsId = 'union' . $query->getQueryId() . 'Results'; |
26
|
5 |
|
$unionDocId = 'union' . $query->getQueryId() . 'Result'; |
27
|
|
|
|
28
|
5 |
|
$query->registerTableAlias($unionResultsId, $unionDocId); |
29
|
|
|
|
30
|
5 |
|
$firstQuery = $this->wrapSubquery($firstQuery); |
|
|
|
|
31
|
|
|
|
32
|
5 |
|
$unions = ''; |
33
|
|
|
|
34
|
5 |
|
foreach ($query->unions as $union) { |
35
|
5 |
|
$prefix = ($unions !== '') ? $unions : $firstQuery; |
36
|
5 |
|
$unions = $this->compileUnion($union, $prefix); |
37
|
|
|
} |
38
|
|
|
|
39
|
5 |
|
$aql = 'LET ' . $unionResultsId . ' = ' . $unions |
40
|
5 |
|
. ' FOR ' . $unionDocId . ' IN ' . $unionResultsId; |
41
|
|
|
|
42
|
|
|
// Union groups |
43
|
|
|
|
44
|
5 |
|
if (!empty($query->unionOrders)) { |
45
|
2 |
|
$aql .= ' ' . $this->compileOrders($query, $query->unionOrders, $unionResultsId); |
|
|
|
|
46
|
|
|
} |
47
|
|
|
|
48
|
5 |
|
if ($query->unionOffset) { |
|
|
|
|
49
|
1 |
|
$aql .= ' ' . $this->compileOffset($query, $query->unionOffset); |
|
|
|
|
50
|
|
|
} |
51
|
|
|
|
52
|
5 |
|
if ($query->unionLimit) { |
|
|
|
|
53
|
1 |
|
$aql .= ' ' . $this->compileLimit($query, $query->unionLimit); |
|
|
|
|
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
// Union aggregates? |
57
|
5 |
|
return $aql . ' RETURN ' . $unionDocId; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Compile a single union statement. |
62
|
|
|
* |
63
|
|
|
* @param array<mixed> $union |
64
|
|
|
* @param string $aql |
65
|
|
|
* @return string |
66
|
|
|
*/ |
67
|
5 |
|
protected function compileUnion(array $union, string $aql = '') |
68
|
|
|
{ |
69
|
5 |
|
$unionType = $union['all'] ? 'UNION' : 'UNION_DISTINCT'; |
70
|
|
|
|
71
|
5 |
|
return $unionType . '(' . $aql . ', ' . $this->wrapSubquery($union['query']->toSql()) . ')'; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|