-
Notifications
You must be signed in to change notification settings - Fork 3
/
PartitionableSelectWithPivotLoader.php
352 lines (319 loc) · 12.3 KB
/
PartitionableSelectWithPivotLoader.php
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
<?php
declare(strict_types=1);
/**
* A set of partitionable associations for the CakePHP ORM.
*
* @see https://github.com/icings/partitionable
*/
namespace Icings\Partitionable\ORM\Association\Loader;
use Cake\Database\Expression\CommonTableExpression;
use Cake\ORM\Association;
use Cake\ORM\Association\Loader\SelectWithPivotLoader;
use Cake\ORM\Query\SelectQuery;
use RuntimeException;
/**
* @internal
*/
class PartitionableSelectWithPivotLoader extends SelectWithPivotLoader
{
use PartitionableSelectLoaderTrait;
/**
* Builds the rank query.
*
* @param SelectQuery $query The query to turn into the rank query.
* @return SelectQuery
*/
protected function _buildRankQuery(SelectQuery $query): SelectQuery
{
$primaryKeys = [];
foreach ((array)$this->junctionAssoc->getPrimaryKey() as $primaryKey) {
$primaryKeys[$primaryKey] = "{$this->junctionAssociationName}.{$primaryKey}";
}
$foreignKeys = [];
foreach ((array)$this->foreignKey as $foreignKey) {
$foreignKeys[$foreignKey] = "{$this->junctionAssociationName}.{$foreignKey}";
}
$order = $this->_getOrder($query);
if (!$order) {
throw new RuntimeException('Partitioning requires a sort order.');
}
return $query
->select($primaryKeys)
->select([
'__row_number' => $query
->func()
->rowNumber()
->over()
->partition($foreignKeys)
->orderBy($order),
]);
}
/**
* ```sql
* SELECT fields
* FROM target
* INNER JOIN junction ON junction.fk = target.pk
* WHERE junction.fk IN (bk list) AND junction.pk IN (
* WITH ranking AS (
* SELECT junction.pk pk, ROW_NUMBER() OVER (PARTITION BY junction.fk ORDER BY sort) rank
* FROM target
* INNER JOIN junction ON junction.fk = target.pk
* WHERE junction.fk IN (bk list)
* )
* SELECT ranking.pk
* FROM ranking
* WHERE ranking.rank <= limit
* )
* ORDER BY sort
* ```
*
* @param SelectQuery $fetchQuery The fetch query.
* @param SelectQuery $rankQuery The rank query.
* @param int $limit The partition limit.
* @return SelectQuery
*/
protected function _inSubqueryCTE(SelectQuery $fetchQuery, SelectQuery $rankQuery, int $limit): SelectQuery
{
$primaryKeys = [];
foreach ((array)$this->junctionAssoc->getPrimaryKey() as $primaryKey) {
$primaryKeys[$primaryKey] = "__ranked__{$this->targetAlias}.{$primaryKey}";
}
$filterSubquery = $rankQuery->getRepository()->getConnection()
->selectQuery()
->with(function (CommonTableExpression $cte) use ($rankQuery) {
return $cte
->name("__ranked__{$this->targetAlias}")
->query($rankQuery);
})
->select($primaryKeys)
->from("__ranked__{$this->targetAlias}")
->where(
["__ranked__{$this->targetAlias}.__row_number <=" => $limit],
["__ranked__{$this->targetAlias}.__row_number" => 'integer']
);
// Add conditions to filter the fetch query via the filter query.
// This will generate a `pk IN (subquery)` condition.
$primaryKeys = [];
foreach ((array)$this->junctionAssoc->getPrimaryKey() as $primaryKey) {
$primaryKeys[] = "{$this->junctionAssociationName}.{$primaryKey}";
}
$this->_addFilteringCondition($fetchQuery, $primaryKeys, $filterSubquery);
return $fetchQuery;
}
/**
* ```sql
* SELECT fields
* FROM target
* INNER JOIN junction ON junction.fk = target.pk
* WHERE junction.fk IN (bk list) AND junction.pk IN (
* SELECT junction.pk
* FROM junction
* INNER JOIN (
* SELECT junction.pk pk, ROW_NUMBER() OVER (PARTITION BY junction.fk ORDER BY sort) rank
* FROM target
* INNER JOIN junction ON junction.fk = target.pk
* WHERE junction.fk IN (bk list)
* ) ranking ON ranking.pk = junction.pk AND ranking.rank <= limit
* )
* ORDER BY sort
* ```
*
* @param SelectQuery $fetchQuery The fetch query.
* @param SelectQuery $rankQuery The rank query.
* @param int $limit The partition limit.
* @return SelectQuery
*/
protected function _inSubqueryJoin(SelectQuery $fetchQuery, SelectQuery $rankQuery, int $limit): SelectQuery
{
$primaryKeys = [];
foreach ((array)$this->junctionAssoc->getPrimaryKey() as $primaryKey) {
$primaryKeys[$primaryKey] = "__filter__{$this->junctionAssoc->getTable()}.{$primaryKey}";
}
$joinKeys = [];
foreach ((array)$this->junctionAssoc->getPrimaryKey() as $primaryKey) {
$joinKeys["__ranked__{$this->targetAlias}.{$primaryKey}"] =
$fetchQuery->identifier("__filter__{$this->junctionAssoc->getTable()}.{$primaryKey}");
}
$filterSubquery = $rankQuery->getRepository()->getConnection()
->selectQuery()
->select($primaryKeys)
// Need to use an alias different to the target alias, as for Sqlite
// and Sqlserver the tuple comparison will be rewritten, resulting in
// the outer conditions moving into the inner query, where the outer
// target alias would then match against the inner alias.
->from([
"__filter__{$this->junctionAssoc->getTable()}" => $this->junctionAssoc->getTable(),
])
->innerJoin(
["__ranked__{$this->targetAlias}" => $rankQuery],
$joinKeys + ["__ranked__{$this->targetAlias}.__row_number <=" => $limit],
["__ranked__{$this->targetAlias}.__row_number" => 'integer']
);
// Add conditions to filter the fetch query via the filter query.
// This will generate a `pk IN (subquery)` condition.
$primaryKeys = [];
foreach ((array)$this->junctionAssoc->getPrimaryKey() as $primaryKey) {
$primaryKeys[] = "{$this->junctionAssociationName}.{$primaryKey}";
}
$this->_addFilteringCondition($fetchQuery, $primaryKeys, $filterSubquery);
return $fetchQuery;
}
/**
* ```sql
* SELECT fields
* FROM target
* INNER JOIN junction ON junction.fk = target.pk
* WHERE junction.fk IN (bk list) AND junction.pk IN (
* SELECT ranking.pk
* FROM (
* SELECT junction.pk, ROW_NUMBER() OVER (PARTITION BY junction.fk ORDER BY sort) rank
* FROM target
* INNER JOIN junction ON junction.fk = target.pk
* WHERE target.fk IN (bk list)
* ) ranking
* WHERE ranking.rank <= limit
* )
* ORDER BY sort
* ```
*
* @param SelectQuery $fetchQuery The fetch query.
* @param SelectQuery $rankQuery The rank query.
* @param int $limit The partition limit.
* @return SelectQuery
*/
protected function _inSubqueryTable(SelectQuery $fetchQuery, SelectQuery $rankQuery, int $limit): SelectQuery
{
$primaryKeys = [];
foreach ((array)$this->junctionAssoc->getPrimaryKey() as $primaryKey) {
$primaryKeys[$primaryKey] = "__ranked__{$this->targetAlias}.{$primaryKey}";
}
$filterSubquery = $rankQuery->getRepository()->getConnection()
->selectQuery()
->select($primaryKeys)
->from(["__ranked__{$this->targetAlias}" => $rankQuery])
->where(
["__ranked__{$this->targetAlias}.__row_number <=" => $limit],
["__ranked__{$this->targetAlias}.__row_number" => 'integer']
);
// Add conditions to filter the fetch query via the filter query.
// This will generate a `pk IN (subquery)` condition.
$primaryKeys = [];
foreach ((array)$this->junctionAssoc->getPrimaryKey() as $primaryKey) {
$primaryKeys[] = "{$this->junctionAssociationName}.{$primaryKey}";
}
$this->_addFilteringCondition($fetchQuery, $primaryKeys, $filterSubquery);
return $fetchQuery;
}
/**
* ```sql
* WITH ranking AS (
* SELECT junction.pk pk, ROW_NUMBER() OVER (PARTITION BY junction.fk ORDER BY sort) rank
* FROM target
* INNER JOIN junction ON junction.fk = target.pk
* WHERE junction.fk IN (bk list)
* )
* SELECT fields
* FROM target
* INNER JOIN junction ON junction.fk = target.pk
* INNER JOIN ranking ON ranking.pk = junction.pk AND ranking.rank <= limit
* ORDER BY sort
* ```
*
* @param SelectQuery $fetchQuery The fetch query.
* @param SelectQuery $rankQuery The rank query.
* @param int $limit The partition limit.
* @return SelectQuery
*/
protected function _innerJoinCTE(SelectQuery $fetchQuery, SelectQuery $rankQuery, int $limit): SelectQuery
{
$fetchQuery
->with(function (CommonTableExpression $cte) use ($rankQuery) {
return $cte
->name("__ranked__{$this->targetAlias}")
->query($rankQuery);
});
$primaryKeys = [];
foreach ((array)$this->junctionAssoc->getPrimaryKey() as $primaryKey) {
$primaryKeys["__ranked__{$this->targetAlias}.{$primaryKey}"] =
$fetchQuery->identifier("{$this->junctionAssociationName}.{$primaryKey}");
}
$fetchQuery
->innerJoin(
"__ranked__{$this->targetAlias}",
$primaryKeys + ["__ranked__{$this->targetAlias}.__row_number <=" => $limit],
["__ranked__{$this->targetAlias}.__row_number" => 'integer']
);
return $fetchQuery;
}
/**
* ```sql
* SELECT fields
* FROM target
* INNER JOIN junction ON junction.fk = target.pk
* INNER JOIN (
* SELECT junction.pk pk, ROW_NUMBER() OVER (PARTITION BY junction.fk ORDER BY sort) rank
* FROM target
* INNER JOIN junction ON junction.fk = target.pk
* WHERE target.fk IN (bk list)
* ) ranking ON ranking.pk = junction.pk AND ranking.rank <= limit
* WHERE target.fk IN (bk list)
* ORDER BY sort
* ```
*
* @param SelectQuery $fetchQuery The fetch query.
* @param SelectQuery $rankQuery The rank query.
* @param int $limit The partition limit.
* @return SelectQuery
*/
protected function _innerJoinSubquery(SelectQuery $fetchQuery, SelectQuery $rankQuery, int $limit): SelectQuery
{
$primaryKeys = [];
foreach ((array)$this->junctionAssoc->getPrimaryKey() as $primaryKey) {
$primaryKeys["__ranked__{$this->targetAlias}.{$primaryKey}"] =
$fetchQuery->identifier("{$this->junctionAssociationName}.{$primaryKey}");
}
$fetchQuery
->innerJoin(
["__ranked__{$this->targetAlias}" => $rankQuery],
$primaryKeys + ["__ranked__{$this->targetAlias}.__row_number <=" => $limit],
["__ranked__{$this->targetAlias}.__row_number" => 'integer']
);
return $fetchQuery;
}
/**
* @inheritDoc
*/
protected function _buildResultMap(SelectQuery $fetchQuery, array $options): array
{
$resultMap = parent::_buildResultMap($fetchQuery, $options);
// Reduce the result map to the single result format in case the
// association is of a one-to-one type.
//
// Turns
//
// [
// '1' => [
// [/* result data */]
// ],
// '2' => [
// [/* result data */]
// ]
// ]
//
// into
//
// [
// '1' => [/* result data */],
// '2' => [/* result data */]
// ]
if ($this->associationType === Association::ONE_TO_ONE) {
$resultMap = array_combine(
array_keys($resultMap),
array_column($resultMap, 0)
);
/** @var array<string, mixed> $resultMap */
$resultMap = array_filter($resultMap);
}
return $resultMap;
}
}