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
|
10 |
|
protected function compileUnions(IlluminateBuilder $query, $firstQuery = '') |
20
|
|
|
{ |
21
|
10 |
|
if (!is_array($query->unions)) { |
22
|
|
|
return ''; |
23
|
|
|
} |
24
|
|
|
|
25
|
10 |
|
$unionResultsId = 'union' . $query->getQueryId() . 'Results'; |
26
|
10 |
|
$unionDocId = 'union' . $query->getQueryId() . 'Result'; |
27
|
|
|
|
28
|
10 |
|
$query->registerTableAlias($unionResultsId, $unionDocId); |
29
|
|
|
|
30
|
10 |
|
$firstQuery = $this->wrapSubquery($firstQuery); |
|
|
|
|
31
|
|
|
|
32
|
10 |
|
$unions = ''; |
33
|
|
|
|
34
|
10 |
|
foreach ($query->unions as $union) { |
35
|
10 |
|
$prefix = ($unions !== '') ? $unions : $firstQuery; |
36
|
10 |
|
$unions = $this->compileUnion($union, $prefix); |
37
|
|
|
} |
38
|
|
|
|
39
|
10 |
|
$aql = 'LET ' . $unionResultsId . ' = ' . $unions |
40
|
10 |
|
. ' FOR ' . $unionDocId . ' IN ' . $unionResultsId; |
41
|
|
|
|
42
|
10 |
|
if (!empty($query->unionOrders)) { |
43
|
2 |
|
$aql .= ' ' . $this->compileOrders($query, $query->unionOrders, $unionResultsId); |
|
|
|
|
44
|
|
|
} |
45
|
|
|
|
46
|
10 |
|
if ($query->unionOffset) { |
|
|
|
|
47
|
1 |
|
$aql .= ' ' . $this->compileOffset($query, $query->unionOffset); |
|
|
|
|
48
|
|
|
} |
49
|
|
|
|
50
|
10 |
|
if ($query->unionLimit) { |
|
|
|
|
51
|
1 |
|
$aql .= ' ' . $this->compileLimit($query, $query->unionLimit); |
|
|
|
|
52
|
|
|
} |
53
|
|
|
|
54
|
10 |
|
if ($query->aggregate !== null) { |
55
|
5 |
|
$originalFrom = $query->from; |
56
|
5 |
|
$query->from = $unionResultsId; |
57
|
|
|
|
58
|
5 |
|
$aql .= ' ' . $this->compileAggregate($query, $query->aggregate); |
|
|
|
|
59
|
|
|
|
60
|
5 |
|
$query->from = $originalFrom; |
61
|
|
|
|
62
|
5 |
|
return $aql . ' RETURN { `aggregate`: aggregateResult }'; |
63
|
|
|
} |
64
|
|
|
|
65
|
5 |
|
return $aql . ' RETURN ' . $unionDocId; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* Compile a single union statement. |
70
|
|
|
* |
71
|
|
|
* @param array<mixed> $union |
72
|
|
|
* @param string $aql |
73
|
|
|
* @return string |
74
|
|
|
*/ |
75
|
10 |
|
protected function compileUnion(array $union, string $aql = '') |
76
|
|
|
{ |
77
|
10 |
|
$unionType = $union['all'] ? 'UNION' : 'UNION_DISTINCT'; |
78
|
|
|
|
79
|
10 |
|
return $unionType . '(' . $aql . ', ' . $this->wrapSubquery($union['query']->toSql()) . ')'; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|