-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathFindObjectsFromRawSqlQueryFactory.php
More file actions
538 lines (481 loc) · 18.6 KB
/
FindObjectsFromRawSqlQueryFactory.php
File metadata and controls
538 lines (481 loc) · 18.6 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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
<?php
declare(strict_types=1);
namespace TheCodingMachine\TDBM\QueryFactory;
use Doctrine\DBAL\Platforms\MySQLPlatform;
use Doctrine\DBAL\Schema\Schema;
use PHPSQLParser\builders\OrderByBuilder;
use PHPSQLParser\builders\SelectStatementBuilder;
use TheCodingMachine\TDBM\TDBMException;
use TheCodingMachine\TDBM\TDBMService;
use PHPSQLParser\PHPSQLCreator;
use PHPSQLParser\PHPSQLParser;
use function array_merge;
/**
* 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;
/**
* FindObjectsFromRawSqlQueryFactory constructor.
* @param TDBMService $tdbmService
* @param Schema $schema
* @param string $mainTable
* @param string $sql
* @param string $sqlCount
*/
public function __construct(TDBMService $tdbmService, Schema $schema, string $mainTable, string $sql, string $sqlCount = null)
{
$this->tdbmService = $tdbmService;
$this->schema = $schema;
$this->mainTable = $mainTable;
[$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
{
$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.'"');
}
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|\PHPSQLParser\exceptions\UnableToCreateSQLException
*/
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();
$parsedSelectSql = $parser->parse($selectProcessedSql);
$parsedSqlList[] = $parsedSelectSql;
}
// 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();
// Replaced the default generator by our own to add parenthesis around each SELECT
$processedSql = $this->buildUnion($query);
$processedSqlCount = $generator->create($countQuery);
// Let's add the ORDER BY if any
if (isset($parsedSql['0']['ORDER'])) {
$orderByBuilder = new OrderByBuilder();
$processedSql .= " " . $orderByBuilder->build($parsedSql['0']['ORDER']);
}
return [$processedSql, $sqlCount ?? $processedSqlCount, $columnDescriptors];
}
/**
* @param mixed[] $parsed
*/
private function buildUnion(array $parsed): string
{
$selectBuilder = new SelectStatementBuilder();
return implode(' UNION ', array_map(function ($clause) use ($selectBuilder) {
return '(' . $selectBuilder->build($clause) . ')';
}, $parsed['UNION']));
}
/**
* @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, $countSelect, $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) {
$parsedCountSql = $parsedSql;
$parsedCountSql['SELECT'] = $countSelect;
$parsedSqlCount = $this->generateParsedSqlCount($parsedCountSql);
$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 = [];
$formattedCountSelect = [];
$columnDescriptors = [];
$fetchedTables = [];
foreach ($baseSelect as $entry) {
if ($entry['expr_type'] !== 'colref') {
$formattedSelect[] = $entry;
$formattedCountSelect[] = $entry;
continue;
}
$noQuotes = $entry['no_quotes'];
if ($noQuotes['delim'] !== '.' || count($noQuotes['parts']) !== 2) {
$formattedSelect[] = $entry;
$formattedCountSelect[] = $entry;
continue;
}
$tableName = $noQuotes['parts'][0];
if (!in_array($tableName, $relatedTables)) {
$formattedSelect[] = $entry;
$formattedCountSelect[] = $entry;
continue;
}
$columnName = $noQuotes['parts'][1];
if ($columnName !== '*') {
$formattedSelect[] = $entry;
$formattedCountSelect[] = $entry;
continue;
}
$table = $this->schema->getTable($tableName);
$primaryKey = $table->getPrimaryKey();
assert($primaryKey !== null, 'TDBM Only works on tables with primary keys');
$pkColumns = $primaryKey->getUnquotedColumns();
foreach ($table->getColumns() as $column) {
$columnName = $column->getName();
$alias = AbstractQueryFactory::getColumnAlias($tableName, $columnName);
$astColumn = [
'expr_type' => 'colref',
'base_expr' => $connection->quoteIdentifier($tableName) . '.' . $connection->quoteIdentifier($columnName),
'no_quotes' => [
'delim' => '.',
'parts' => [
$tableName,
$columnName
]
],
'alias' => [
'as' => true,
'name' => $connection->quoteIdentifier($alias),
]
];
$formattedSelect[] = $astColumn;
if (in_array($columnName, $pkColumns, true)) {
$formattedCountSelect[] = $astColumn;
}
$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'] = ',';
}
}
for ($i = 0; $i < count($formattedCountSelect) - 1; $i++) {
if (!isset($formattedCountSelect[$i]['delim'])) {
$formattedCountSelect[$i]['delim'] = ',';
}
}
return [$formattedSelect, $formattedCountSelect, $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()->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']);
// Count(DISTINCT ...) on multiple columns is only valid in MySQL (unsupported on Pgsql or Oracle). For those, we need to do a subquery.
if (count($group) === 1 || $this->tdbmService->getConnection()->getDatabasePlatform() instanceof MySqlPlatform) {
$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,
]];
} else {
$innerColumns = [[
'expr_type' => 'reserved',
'base_expr' => 'DISTINCT',
'delim' => ' '
]];
foreach ($group as $item) {
$item['delim'] = ',';
$innerColumns[] = $item;
}
$innerColumns[count($innerColumns) - 1]['delim'] = false;
$parsedSql['SELECT'] = $innerColumns;
$parsedSql = [
'SELECT' =>
[
0 =>
[
'expr_type' => 'aggregate_function',
'alias' =>
[
'as' => true,
'name' => 'cnt',
'base_expr' => 'AS cnt',
'no_quotes' =>
[
'delim' => false,
'parts' =>
[
0 => 'cnt',
],
],
],
'base_expr' => 'COUNT',
'sub_tree' =>
[
0 =>
[
'expr_type' => 'colref',
'base_expr' => '*',
'sub_tree' => false,
],
],
'delim' => false,
],
],
'FROM' =>
[
0 =>
[
'expr_type' => 'subquery',
'alias' =>
[
'as' => false,
'name' => 'subquery',
'no_quotes' =>
[
'delim' => false,
'parts' =>
[
0 => 'subquery',
],
],
'base_expr' => 'subquery',
],
'hints' => false,
'join_type' => 'JOIN',
'ref_type' => false,
'ref_clause' => false,
//'base_expr' => 'SELECT id FROM country',
'sub_tree' => $parsedSql
],
],
];
}
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 array<int, array{table: string, column: string}> An array of column descriptors.
*/
public function getSubQueryColumnDescriptors(): array
{
throw new TDBMException('Using resultset generated from findFromRawSql as subqueries is unsupported for now.');
}
}