Repository navigation
Expand file tree
/
Copy pathAbstractSql.php
More file actions
478 lines (410 loc) · 16.3 KB
/
Copy pathAbstractSql.php
File metadata and controls
478 lines (410 loc) · 16.3 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
<?php
declare(strict_types=1);
namespace PhpDb\Sql;
use Override;
use PhpDb\Adapter\Driver\DriverInterface;
use PhpDb\Adapter\ParameterContainer;
use PhpDb\Adapter\Platform\PlatformInterface;
use PhpDb\Adapter\Platform\Sql92 as DefaultAdapterPlatform;
use PhpDb\Sql\Argument\Identifier;
use PhpDb\Sql\Argument\Identifiers;
use PhpDb\Sql\Argument\Literal;
use PhpDb\Sql\Argument\Select as SelectArgument;
use PhpDb\Sql\Argument\Value;
use PhpDb\Sql\Argument\Values;
use PhpDb\Sql\Platform\PlatformDecoratorInterface;
use ValueError;
use function count;
use function current;
use function get_object_vars;
use function implode;
use function is_array;
use function is_string;
use function key;
use function rtrim;
use function sprintf;
use function str_replace;
use function strtoupper;
use function vsprintf;
abstract class AbstractSql implements SqlInterface
{
protected SqlInterface|PreparableSqlInterface|null $subject = null;
/**
* Specifications for Sql String generation
*
* @var string[]|array[]
*/
protected array $specifications = [];
/**
* Information used during processing
*
* @var array{paramPrefix: string, subselectCount: int}
*/
protected array $processInfo = ['paramPrefix' => '', 'subselectCount' => 0];
protected array $instanceParameterIndex = [];
/**
* {@inheritDoc}
*/
#[Override]
public function getSqlString(?PlatformInterface $adapterPlatform = null): string
{
$adapterPlatform = $adapterPlatform ?: new DefaultAdapterPlatform();
return $this->buildSqlString($adapterPlatform);
}
protected function buildSqlString(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
): string {
$this->localizeVariables();
$sqls = [];
foreach ($this->specifications as $name => $specification) {
$result = $this->{'process' . $name}(
$platform,
$driver,
$parameterContainer
);
if (is_array($result)) {
$sqls[$name] = $this->createSqlFromSpecificationAndParameters($specification, $result);
} elseif ($result !== null) {
$sqls[$name] = $result;
}
}
return rtrim(implode(' ', $sqls), "\n ,");
}
/**
* Render table with alias in from/join parts
*
* @todo move TableIdentifier concatenation here
*/
protected function renderTable(string $table, ?string $alias = null): string
{
return $alias ? "{$table} AS {$alias}" : $table;
}
/**
* @staticvar int $runtimeExpressionPrefix
*/
protected function processExpression(
ExpressionInterface $expression,
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null,
?string $namedParameterPrefix = null
): string {
static $runtimeExpressionPrefix = 0;
$expressionData = $expression->getExpressionData();
$specification = $expressionData['spec'];
$expressionValues = $expressionData['values'];
if ($expressionValues === []) {
return str_replace('%%', '%', $specification);
}
if ($namedParameterPrefix === null || $namedParameterPrefix === '') {
$namedParameterPrefix = $parameterContainer
? 'expr' . $runtimeExpressionPrefix++ . 'Param'
: '';
} else {
$namedParameterPrefix = $this->processInfo['paramPrefix']
. str_replace([' ', "\t", "\n", "\r"], '__', $namedParameterPrefix);
}
if (! isset($this->instanceParameterIndex[$namedParameterPrefix])) {
$this->instanceParameterIndex[$namedParameterPrefix] = 1;
}
$expressionParamIndex = &$this->instanceParameterIndex[$namedParameterPrefix];
$expressionValues = $this->flattenExpressionValues($expressionValues);
$values = [];
foreach ($expressionValues as $vIndex => $argument) {
$values[] = match (true) {
$argument instanceof Value => $parameterContainer instanceof ParameterContainer
? $this->processExpressionParameterName(
$argument->getValue(),
$namedParameterPrefix,
$expressionParamIndex,
$driver,
$parameterContainer
)
: $platform->quoteValue((string) $argument->getValue()),
$argument instanceof Identifier => $platform->quoteIdentifierInFragment($argument->getValue()),
$argument instanceof Literal => $argument->getValue(),
$argument instanceof Identifiers => $this->processIdentifiersArgument($argument, $platform),
$argument instanceof SelectArgument => $this->processExpressionOrSelect(
$argument,
$namedParameterPrefix,
$vIndex,
$platform,
$driver,
$parameterContainer
),
default => throw new Exception\InvalidArgumentException('Unknown argument type'),
};
}
return vsprintf($specification, $values);
}
/**
* Flattens expression values, expanding Values arguments
*
* @param ArgumentInterface[] $arguments
* @return ArgumentInterface[]
*/
protected function flattenExpressionValues(array $arguments): array
{
$hasValues = false;
foreach ($arguments as $argument) {
if ($argument instanceof Values) {
$hasValues = true;
break;
}
}
if (! $hasValues) {
return $arguments;
}
$values = [];
foreach ($arguments as $argument) {
if ($argument instanceof Values) {
foreach ($argument->getValue() as $v) {
$values[] = new Value($v);
}
} else {
$values[] = $argument;
}
}
return $values;
}
protected function processExpressionOrSelect(
ArgumentInterface $argument,
string $namedParameterPrefix,
int $vIndex,
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
): string {
$value = $argument->getValue();
return match (true) {
$value instanceof Select => '('
. $this->processSubSelect($value, $platform, $driver, $parameterContainer)
. ')',
$value instanceof ExpressionInterface => $this->processExpression(
$value,
$platform,
$driver,
$parameterContainer,
"{$namedParameterPrefix}{$vIndex}subpart"
),
default => throw new ValueError('Invalid Argument type'),
};
}
protected function processIdentifiersArgument(
ArgumentInterface $argument,
PlatformInterface $platform
): string {
$identifiers = $argument->getValue();
$processedIdentifiers = [];
foreach ($identifiers as $identifier) {
$processedIdentifiers[] = $platform->quoteIdentifierInFragment($identifier);
}
return implode(', ', $processedIdentifiers);
}
protected function processExpressionParameterName(
int|float|string|bool $value,
string $namedParameterPrefix,
int &$expressionParamIndex,
DriverInterface $driver,
ParameterContainer $parameterContainer
): ?string {
$name = $namedParameterPrefix . $expressionParamIndex++;
$parameterContainer->offsetSet($name, $value);
return $driver->formatParameterName($name);
}
/**
* @throws Exception\RuntimeException
*/
protected function createSqlFromSpecificationAndParameters(array|string $specifications, array $parameters): string
{
if (is_string($specifications)) {
return vsprintf($specifications, $parameters);
}
$parametersCount = count($parameters);
foreach ($specifications as $specificationString => $paramSpecs) {
if ($parametersCount === count($paramSpecs)) {
break;
}
unset($specificationString, $paramSpecs);
}
if (! isset($specificationString)) {
throw new Exception\RuntimeException(
'A number of parameters was found that is not supported by this specification'
);
}
$topParameters = [];
foreach ($parameters as $position => $paramsForPosition) {
if (isset($paramSpecs[$position]['combinedby'])) {
$multiParamValues = [];
foreach ($paramsForPosition as $multiParamsForPosition) {
if (is_array($multiParamsForPosition)) {
$ppCount = count($multiParamsForPosition);
} else {
$ppCount = 1;
$multiParamsForPosition = [$multiParamsForPosition];
}
if (! isset($paramSpecs[$position][$ppCount])) {
throw new Exception\RuntimeException(sprintf(
'A number of parameters (%d) was found that is not supported by this specification',
$ppCount
));
}
$multiParamValues[] = vsprintf($paramSpecs[$position][$ppCount], $multiParamsForPosition);
}
$topParameters[] = implode($paramSpecs[$position]['combinedby'], $multiParamValues);
} elseif ($paramSpecs[$position] !== null) {
$ppCount = count($paramsForPosition);
if (! isset($paramSpecs[$position][$ppCount])) {
throw new Exception\RuntimeException(sprintf(
'A number of parameters (%d) was found that is not supported by this specification',
$ppCount
));
}
$topParameters[] = vsprintf($paramSpecs[$position][$ppCount], $paramsForPosition);
} else {
$topParameters[] = $paramsForPosition;
}
}
return vsprintf($specificationString, $topParameters);
}
protected function processSubSelect(
Select $subselect,
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
): string {
if ($this instanceof PlatformDecoratorInterface) {
$decorator = clone $this;
$decorator->setSubject($subselect);
} else {
$decorator = $subselect;
}
if ($parameterContainer instanceof ParameterContainer) {
$processInfoContext = $decorator instanceof PlatformDecoratorInterface ? $subselect : $decorator;
$this->processInfo['subselectCount']++;
$processInfoContext->processInfo['subselectCount'] = $this->processInfo['subselectCount'];
$processInfoContext->processInfo['paramPrefix'] = 'subselect'
. $processInfoContext->processInfo['subselectCount'];
$sql = $decorator->buildSqlString($platform, $driver, $parameterContainer);
$this->processInfo['subselectCount'] = $decorator->processInfo['subselectCount'];
return $sql;
}
return $decorator->buildSqlString($platform, $driver, $parameterContainer);
}
/**
* @return null|string[][][] Null if no joins present, array of JOIN statements otherwise
*/
protected function processJoin(
?Join $joins,
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
): array|null {
if ($joins === null || $joins->count() === 0) {
return null;
}
$joinSpecArgArray = [];
foreach ($joins->getJoins() as $j => $join) {
$joinAs = null;
$joinNameValue = $join['name'];
if (is_array($joinNameValue)) {
$joinName = current($joinNameValue);
$joinAs = $platform->quoteIdentifier(key($joinNameValue));
} else {
$joinName = $joinNameValue;
}
if ($joinName instanceof Expression) {
$joinName = $joinName->getExpression();
} elseif ($joinName instanceof TableIdentifier) {
$joinName = $joinName->getTableAndSchema();
$joinName = ($joinName[1]
? $platform->quoteIdentifier($joinName[1]) . $platform->getIdentifierSeparator()
: '') . $platform->quoteIdentifier($joinName[0]);
} elseif ($joinName instanceof Select) {
$joinName = '(' . $this->processSubSelect($joinName, $platform, $driver, $parameterContainer) . ')';
} else {
$joinName = $platform->quoteIdentifier($joinName);
}
$joinSpecArgArray[$j] = [
strtoupper($join['type']),
$this->renderTable($joinName, $joinAs),
];
if ($join['on'] instanceof ExpressionInterface) {
$joinSpecArgArray[$j][] = $this->processExpression(
$join['on'],
$platform,
$driver,
$parameterContainer,
'join' . ($j + 1) . 'part'
);
} else {
$joinSpecArgArray[$j][] = $platform->quoteIdentifierInFragment(
$join['on'],
['=', 'AND', 'OR', '(', ')', 'BETWEEN', '<', '>']
);
}
}
return [$joinSpecArgArray];
}
protected function resolveColumnValue(
Select|array|string|int|bool|ExpressionInterface|null $column,
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null,
?string $namedParameterPrefix = null
): string {
$namedParameterPrefix = $namedParameterPrefix
? $this->processInfo['paramPrefix'] . $namedParameterPrefix
: $namedParameterPrefix;
$isIdentifier = false;
$fromTable = '';
if (is_array($column)) {
$isIdentifier = (bool) ($column['isIdentifier'] ?? false);
$fromTable = $column['fromTable'] ?? '';
$column = $column['column'];
}
if ($column instanceof ExpressionInterface) {
return $this->processExpression($column, $platform, $driver, $parameterContainer, $namedParameterPrefix);
}
if ($column instanceof Select) {
return '(' . $this->processSubSelect($column, $platform, $driver, $parameterContainer) . ')';
}
if ($column === null) {
return 'NULL';
}
return $isIdentifier
? $fromTable . $platform->quoteIdentifierInFragment($column)
: $platform->quoteValue($column);
}
protected function resolveTable(
Select|string|TableIdentifier|null $table,
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null
): string|array|null {
$schema = null;
if ($table instanceof TableIdentifier) {
[$table, $schema] = $table->getTableAndSchema();
}
if ($table instanceof Select) {
$table = '(' . $this->processSubSelect($table, $platform, $driver, $parameterContainer) . ')';
} elseif ($table) {
$table = $platform->quoteIdentifier($table);
}
if ($schema && $table) {
$table = $platform->quoteIdentifier($schema) . $platform->getIdentifierSeparator() . $table;
}
return $table;
}
protected function localizeVariables(): void
{
if (! $this instanceof PlatformDecoratorInterface) {
return;
}
foreach (get_object_vars($this->subject) as $name => $value) {
$this->{$name} = $value;
}
}
}