-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathFindObjectsFromRawSqlQueryFactory.php
More file actions
419 lines (370 loc) · 13.4 KB
/
FindObjectsFromRawSqlQueryFactory.php
File metadata and controls
419 lines (370 loc) · 13.4 KB
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
<?php
declare(strict_types=1);
namespace TheCodingMachine\TDBM\QueryFactory;
use Doctrine\Common\Cache\Cache;
use Doctrine\DBAL\Platforms\MySqlPlatform;
use Doctrine\DBAL\Schema\Schema;
use TheCodingMachine\TDBM\TDBMException;
use TheCodingMachine\TDBM\TDBMService;
use PHPSQLParser\PHPSQLCreator;
use PHPSQLParser\PHPSQLParser;
/**
* This class is in charge of formatting the SQL passed to findObjectsFromRawSql method.
*/
class FindObjectsFromRawSqlQueryFactory implements QueryFactory
{
/**
* @var array[]
*/
protected $columnDescriptors;
/**
* @var Schema
*/
private $schema;
/**
* @var string
*/
private $processedSql;
/**
* @var string
*/
private $processedSqlCount;
/**
* @var TDBMService
*/
private $tdbmService;
/**
* @var string
*/
private $mainTable;
/**
* @var Cache
*/
private $cache;
public function __construct(TDBMService $tdbmService, Schema $schema, string $mainTable, string $sql, ?string $sqlCount, Cache $cache)
{
$this->tdbmService = $tdbmService;
$this->schema = $schema;
$this->mainTable = $mainTable;
$this->cache = $cache;
[$this->processedSql, $this->processedSqlCount, $this->columnDescriptors] = $this->compute($sql, $sqlCount);
}
public function sort($orderBy): void
{
throw new TDBMException('sort not supported for raw sql queries');
}
public function getMagicSql(): string
{
return $this->processedSql;
}
public function getMagicSqlCount(): string
{
return $this->processedSqlCount;
}
public function getColumnDescriptors(): array
{
return $this->columnDescriptors;
}
/**
* @param string $sql
* @param null|string $sqlCount
* @return mixed[] An array of 3 elements: [$processedSql, $processedSqlCount, $columnDescriptors]
* @throws TDBMException
*/
private function compute(string $sql, ?string $sqlCount): array
{
$key = 'FindObjectsFromRawSqlQueryFactory_' . dechex(crc32(var_export($sqlCount, true) . $sql));
if ($this->cache->contains($key)) {
return $this->cache->fetch($key);
}
$parser = new PHPSQLParser();
$parsedSql = $parser->parse($sql);
if (isset($parsedSql['SELECT'])) {
[$processedSql, $processedSqlCount, $columnDescriptors] = $this->processParsedSelectQuery($parsedSql, $sqlCount);
} elseif (isset($parsedSql['UNION'])) {
[$processedSql, $processedSqlCount, $columnDescriptors] = $this->processParsedUnionQuery($parsedSql, $sqlCount);
} else {
throw new TDBMException('Unable to analyze query "'.$sql.'"');
}
$this->cache->save($key, [$processedSql, $processedSqlCount, $columnDescriptors]);
return [$processedSql, $processedSqlCount, $columnDescriptors];
}
/**
* @param mixed[] $parsedSql
* @param null|string $sqlCount
* @return mixed[] An array of 3 elements: [$processedSql, $processedSqlCount, $columnDescriptors]
* @throws \PHPSQLParser\exceptions\UnsupportedFeatureException
*/
private function processParsedUnionQuery(array $parsedSql, ?string $sqlCount): array
{
$selects = $parsedSql['UNION'];
$parsedSqlList = [];
$columnDescriptors = [];
foreach ($selects as $select) {
[$selectProcessedSql, $selectProcessedCountSql, $columnDescriptors] = $this->processParsedSelectQuery($select, '');
// Let's reparse the returned SQL (not the most efficient way of doing things)
$parser = new PHPSQLParser();
$parsedSql = $parser->parse($selectProcessedSql);
$parsedSqlList[] = $parsedSql;
}
// Let's rebuild the UNION query
$query = ['UNION' => $parsedSqlList];
// The count is the SUM of the count of the UNIONs
$countQuery = $this->generateWrappedSqlCount($query);
$generator = new PHPSQLCreator();
$processedSql = $generator->create($query);
$processedSqlCount = $generator->create($countQuery);
return [$processedSql, $sqlCount ?? $processedSqlCount, $columnDescriptors];
}
/**
* @param mixed[] $parsedSql
* @param null|string $sqlCount
* @return mixed[] An array of 3 elements: [$processedSql, $processedSqlCount, $columnDescriptors]
*/
private function processParsedSelectQuery(array $parsedSql, ?string $sqlCount): array
{
// 1: let's reformat the SELECT and construct our columns
list($select, $columnDescriptors) = $this->formatSelect($parsedSql['SELECT']);
$generator = new PHPSQLCreator();
$parsedSql['SELECT'] = $select;
$processedSql = $generator->create($parsedSql);
// 2: let's compute the count query if needed
if ($sqlCount === null) {
$parsedSqlCount = $this->generateParsedSqlCount($parsedSql);
$processedSqlCount = $generator->create($parsedSqlCount);
} else {
$processedSqlCount = $sqlCount;
}
return [$processedSql, $processedSqlCount, $columnDescriptors];
}
/**
* @param mixed[] $baseSelect
* @return mixed[] An array of 2 elements: [$formattedSelect, $columnDescriptors]
* @throws TDBMException
* @throws \Doctrine\DBAL\Schema\SchemaException
*/
private function formatSelect(array $baseSelect): array
{
$relatedTables = $this->tdbmService->_getRelatedTablesByInheritance($this->mainTable);
$tableGroup = $this->getTableGroupName($relatedTables);
$connection = $this->tdbmService->getConnection();
$formattedSelect = [];
$columnDescriptors = [];
$fetchedTables = [];
foreach ($baseSelect as $entry) {
if ($entry['expr_type'] !== 'colref') {
$formattedSelect[] = $entry;
continue;
}
$noQuotes = $entry['no_quotes'];
if ($noQuotes['delim'] !== '.' || count($noQuotes['parts']) !== 2) {
$formattedSelect[] = $entry;
continue;
}
$tableName = $noQuotes['parts'][0];
if (!in_array($tableName, $relatedTables)) {
$formattedSelect[] = $entry;
continue;
}
$columnName = $noQuotes['parts'][1];
if ($columnName !== '*') {
$formattedSelect[] = $entry;
continue;
}
$table = $this->schema->getTable($tableName);
foreach ($table->getColumns() as $column) {
$columnName = $column->getName();
$alias = "{$tableName}____{$columnName}";
$formattedSelect[] = [
'expr_type' => 'colref',
'base_expr' => $connection->quoteIdentifier($tableName).'.'.$connection->quoteIdentifier($columnName),
'no_quotes' => [
'delim' => '.',
'parts' => [
$tableName,
$columnName
]
],
'alias' => [
'as' => true,
'name' => $alias,
]
];
$columnDescriptors[$alias] = [
'as' => $alias,
'table' => $tableName,
'column' => $columnName,
'type' => $column->getType(),
'tableGroup' => $tableGroup,
];
}
$fetchedTables[] = $tableName;
}
$missingTables = array_diff($relatedTables, $fetchedTables);
if (!empty($missingTables)) {
throw new TDBMException('Missing tables '.implode(', ', $missingTables).' in SELECT statement');
}
for ($i = 0; $i < count($formattedSelect) - 1; $i++) {
if (!isset($formattedSelect[$i]['delim'])) {
$formattedSelect[$i]['delim'] = ',';
}
}
return [$formattedSelect, $columnDescriptors];
}
/**
* @param mixed[] $parsedSql
* @return mixed[]
*/
private function generateParsedSqlCount(array $parsedSql): array
{
if (isset($parsedSql['ORDER'])) {
unset($parsedSql['ORDER']);
}
if (!isset($parsedSql['GROUP'])) {
// most simple case:no GROUP BY in query
return $this->generateSimpleSqlCount($parsedSql);
} elseif (!isset($parsedSql['HAVING'])) {
// GROUP BY without HAVING statement: let's COUNT the DISTINCT grouped columns
return $this->generateGroupedSqlCount($parsedSql);
} else {
// GROUP BY with a HAVING statement: we'll have to wrap the query
return $this->generateWrappedSqlCount($parsedSql);
}
}
/**
* @param mixed[] $parsedSql The AST of the SQL query
* @return mixed[] An AST representing the matching COUNT query
*/
private function generateSimpleSqlCount(array $parsedSql): array
{
// If the query is a DISTINCT, we need to deal with the count.
// We need to count on the same columns: COUNT(DISTINCT country.id, country.label) ....
// but we need to remove the "alias" bit.
if ($this->isDistinctQuery($parsedSql)) {
// Only MySQL can do DISTINCT counts.
// Other databases should wrap the query
if (!$this->tdbmService->getConnection()->getSchemaManager()->getDatabasePlatform() instanceof MySqlPlatform) {
return $this->generateWrappedSqlCount($parsedSql);
}
$countSubExpr = array_map(function (array $item) {
unset($item['alias']);
return $item;
}, $parsedSql['SELECT']);
} else {
$countSubExpr = [
[
'expr_type' => 'colref',
'base_expr' => '*',
'sub_tree' => false
]
];
}
$parsedSql['SELECT'] = [[
'expr_type' => 'aggregate_function',
'alias' => [
'as' => true,
'name' => 'cnt',
],
'base_expr' => 'COUNT',
'sub_tree' => $countSubExpr,
'delim' => false,
]];
return $parsedSql;
}
/**
* @param mixed[] $parsedSql AST to analyze
* @return bool
*/
private function isDistinctQuery(array $parsedSql): bool
{
foreach ($parsedSql['SELECT'] as $item) {
if ($item['expr_type'] === 'reserved' && $item['base_expr'] === 'DISTINCT') {
return true;
}
}
return false;
}
/**
* @param mixed[] $parsedSql The AST of the SQL query
* @return mixed[] An AST representing the matching COUNT query
*/
private function generateGroupedSqlCount(array $parsedSql): array
{
$group = $parsedSql['GROUP'];
unset($parsedSql['GROUP']);
$parsedSql['SELECT'] = [[
'expr_type' => 'aggregate_function',
'alias' => [
'as' => true,
'name' => 'cnt',
],
'base_expr' => 'COUNT',
'sub_tree' => array_merge([[
'expr_type' => 'reserved',
'base_expr' => 'DISTINCT',
'delim' => ','
]], $group),
'delim' => false,
]];
return $parsedSql;
}
/**
* @param mixed[] $parsedSql The AST of the SQL query
* @return mixed[] An AST representing the matching COUNT query
*/
private function generateWrappedSqlCount(array $parsedSql): array
{
return [
'SELECT' => [[
'expr_type' => 'aggregate_function',
'alias' => [
'as' => true,
'name' => 'cnt',
],
'base_expr' => 'COUNT',
'sub_tree' => [
[
'expr_type' => 'colref',
'base_expr' => '*',
'sub_tree' => false
]
],
'delim' => false,
]],
'FROM' => [[
'expr_type' => 'subquery',
'alias' => [
'as' => true,
'name' => '____query'
],
'sub_tree' => $parsedSql,
]]
];
}
/**
* @param string[] $relatedTables
* @return string
*/
protected function getTableGroupName(array $relatedTables): string
{
sort($relatedTables);
return implode('_``_', $relatedTables);
}
/**
* Returns a sub-query to be used in another query.
* A sub-query is similar to a query except it returns only the primary keys of the table (to be used as filters)
*
* @return string
*/
public function getMagicSqlSubQuery(): string
{
throw new TDBMException('Using resultset generated from findFromRawSql as subqueries is unsupported for now.');
}
/**
* @return string[][] An array of column descriptors. Value is an array with those keys: table, column
*/
public function getSubQueryColumnDescriptors(): array
{
throw new TDBMException('Using resultset generated from findFromRawSql as subqueries is unsupported for now.');
}
}