-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMySQL.php
More file actions
540 lines (435 loc) · 16 KB
/
MySQL.php
File metadata and controls
540 lines (435 loc) · 16 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
539
540
<?php
namespace Utopia\Query\Builder;
use Utopia\Query\Builder\Feature\ConditionalAggregates;
use Utopia\Query\Builder\Feature\FullTextSearch;
use Utopia\Query\Builder\Feature\GroupByModifiers;
use Utopia\Query\Builder\Feature\Hints;
use Utopia\Query\Builder\Feature\InsertOrIgnore;
use Utopia\Query\Builder\Feature\Json;
use Utopia\Query\Builder\Feature\LateralJoins;
use Utopia\Query\Builder\Feature\Spatial;
use Utopia\Query\Builder\Feature\StringAggregates;
use Utopia\Query\Builder\Feature\Upsert;
use Utopia\Query\Builder\Feature\UpsertSelect;
use Utopia\Query\Exception\ValidationException;
use Utopia\Query\Method;
class MySQL extends SQL implements
Json,
Hints,
ConditionalAggregates,
LateralJoins,
StringAggregates,
GroupByModifiers,
Spatial,
FullTextSearch,
Upsert,
UpsertSelect,
InsertOrIgnore
{
use Trait\ConditionalAggregates;
use Trait\FullTextSearch;
use Trait\GroupByModifiers;
use Trait\Hints;
use Trait\LateralJoins;
use Trait\Spatial;
use Trait\StringAggregates;
use Trait\Upsert;
use Trait\UpsertSelect;
protected string $updateJoinTable = '';
protected string $updateJoinLeft = '';
protected string $updateJoinRight = '';
protected string $updateJoinAlias = '';
protected string $deleteAlias = '';
protected string $deleteJoinTable = '';
protected string $deleteJoinLeft = '';
protected string $deleteJoinRight = '';
#[\Override]
protected function compileRandom(): string
{
return 'RAND()';
}
/**
* @param array<mixed> $values
*/
#[\Override]
protected function compileRegex(string $attribute, array $values): string
{
$this->addBinding($values[0]);
return $attribute . ' REGEXP ?';
}
/**
* @param array<mixed> $values
*/
#[\Override]
protected function compileSearchExpr(string $attribute, array $values, bool $not): string
{
/** @var string $term */
$term = $values[0] ?? '';
$exact = \str_ends_with($term, '"') && \str_starts_with($term, '"');
$specialChars = '@,+,-,*,),(,<,>,~,"';
$sanitized = \str_replace(\explode(',', $specialChars), ' ', $term);
$sanitized = \preg_replace('/\s+/', ' ', $sanitized) ?? '';
$sanitized = \trim($sanitized);
if ($sanitized === '') {
return $not ? '1 = 1' : '1 = 0';
}
if ($exact) {
$sanitized = '"' . $sanitized . '"';
} else {
$sanitized .= '*';
}
$this->addBinding($sanitized);
if ($not) {
return 'NOT (MATCH(' . $attribute . ') AGAINST(? IN BOOLEAN MODE))';
}
return 'MATCH(' . $attribute . ') AGAINST(? IN BOOLEAN MODE)';
}
#[\Override]
protected function compileConflictHeader(): string
{
return 'ON DUPLICATE KEY UPDATE';
}
#[\Override]
protected function compileConflictAssignment(string $wrapped): string
{
return 'VALUES(' . $wrapped . ')';
}
#[\Override]
public function setJsonAppend(string $column, array $values): static
{
$this->jsonSets[$column] = new Condition(
'JSON_MERGE_PRESERVE(IFNULL(' . $this->resolveAndWrap($column) . ', JSON_ARRAY()), ?)',
[\json_encode($values)],
);
return $this;
}
#[\Override]
public function setJsonPrepend(string $column, array $values): static
{
$this->jsonSets[$column] = new Condition(
'JSON_MERGE_PRESERVE(?, IFNULL(' . $this->resolveAndWrap($column) . ', JSON_ARRAY()))',
[\json_encode($values)],
);
return $this;
}
#[\Override]
public function setJsonInsert(string $column, int $index, mixed $value): static
{
$this->jsonSets[$column] = new Condition(
'JSON_ARRAY_INSERT(' . $this->resolveAndWrap($column) . ', ?, ?)',
['$[' . $index . ']', $value],
);
return $this;
}
#[\Override]
public function setJsonRemove(string $column, mixed $value): static
{
$this->jsonSets[$column] = new Condition(
'JSON_REMOVE(' . $this->resolveAndWrap($column) . ', JSON_UNQUOTE(JSON_SEARCH(' . $this->resolveAndWrap($column) . ', \'one\', ?)))',
[$value],
);
return $this;
}
#[\Override]
public function setJsonIntersect(string $column, array $values): static
{
$this->setRaw($column, '(SELECT JSON_ARRAYAGG(val) FROM JSON_TABLE(' . $this->resolveAndWrap($column) . ', \'$[*]\' COLUMNS(val JSON PATH \'$\')) AS jt WHERE JSON_CONTAINS(?, val))', [\json_encode($values)]);
return $this;
}
#[\Override]
public function setJsonDiff(string $column, array $values): static
{
$this->setRaw($column, '(SELECT JSON_ARRAYAGG(val) FROM JSON_TABLE(' . $this->resolveAndWrap($column) . ', \'$[*]\' COLUMNS(val JSON PATH \'$\')) AS jt WHERE NOT JSON_CONTAINS(?, val))', [\json_encode($values)]);
return $this;
}
#[\Override]
public function setJsonUnique(string $column): static
{
$this->setRaw($column, '(SELECT JSON_ARRAYAGG(val) FROM (SELECT DISTINCT val FROM JSON_TABLE(' . $this->resolveAndWrap($column) . ', \'$[*]\' COLUMNS(val JSON PATH \'$\')) AS jt) AS dt)');
return $this;
}
#[\Override]
public function setJsonPath(string $column, string $path, mixed $value): static
{
if (! \str_starts_with($path, '$')) {
throw new ValidationException('JSON path must start with \'$\': ' . $path);
}
$this->jsonSets[$column] = new Condition(
'JSON_SET(' . $this->resolveAndWrap($column) . ', ?, ?)',
[$path, $value],
);
return $this;
}
public function maxExecutionTime(int $ms): static
{
return $this->hint("MAX_EXECUTION_TIME({$ms})");
}
#[\Override]
public function insertOrIgnore(): Statement
{
$this->bindings = [];
[$sql, $bindings] = $this->compileInsertBody();
$this->addBindings($bindings);
// Replace "INSERT INTO" with "INSERT IGNORE INTO"
$sql = \preg_replace('/^INSERT INTO/', 'INSERT IGNORE INTO', $sql, 1) ?? $sql;
return new Statement($sql, $this->bindings, executor: $this->executor);
}
#[\Override]
public function explain(bool $analyze = false, string $format = ''): Statement
{
$result = $this->build();
$prefix = 'EXPLAIN';
if ($analyze) {
$prefix .= ' ANALYZE';
}
if ($format !== '') {
$prefix .= ' FORMAT=' . \strtoupper($format);
}
return new Statement($prefix . ' ' . $result->query, $result->bindings, readOnly: true, executor: $this->executor);
}
#[\Override]
public function build(): Statement
{
$result = parent::build();
$query = $result->query;
if ($this->groupByModifier !== null) {
$groupByPos = \strpos($query, 'GROUP BY ');
if ($groupByPos !== false) {
$afterGroupBy = $groupByPos + 9;
$endPos = null;
foreach (['HAVING ', 'WINDOW ', 'ORDER BY ', 'LIMIT ', 'FOR '] as $keyword) {
$pos = \strpos($query, $keyword, $afterGroupBy);
if ($pos !== false && ($endPos === null || $pos < $endPos)) {
$endPos = $pos;
}
}
$insertAt = $endPos !== null ? $endPos : \strlen($query);
$query = \rtrim(\substr($query, 0, $insertAt)) . ' ' . $this->groupByModifier . ($endPos !== null ? ' ' . \substr($query, $endPos) : '');
}
}
if (! empty($this->hints)) {
$hintStr = '/*+ ' . \implode(' ', $this->hints) . ' */';
$query = \preg_replace('/^SELECT(\s+DISTINCT)?/', 'SELECT$1 ' . $hintStr, $query, 1) ?? $query;
}
if ($query !== $result->query) {
return new Statement($query, $result->bindings, $result->readOnly, $this->executor);
}
return $result;
}
public function updateJoin(string $table, string $left, string $right, string $alias = ''): static
{
$this->updateJoinTable = $table;
$this->updateJoinLeft = $left;
$this->updateJoinRight = $right;
$this->updateJoinAlias = $alias;
return $this;
}
#[\Override]
public function update(): Statement
{
foreach ($this->jsonSets as $col => $condition) {
$this->setRaw($col, $condition->expression, $condition->bindings);
}
if ($this->updateJoinTable !== '') {
$result = $this->buildUpdateJoin();
$this->jsonSets = [];
return $result;
}
$result = parent::update();
$this->jsonSets = [];
return $result;
}
private function buildUpdateJoin(): Statement
{
$this->bindings = [];
$this->validateTable();
$joinTable = $this->quote($this->updateJoinTable);
if ($this->updateJoinAlias !== '') {
$joinTable .= ' AS ' . $this->quote($this->updateJoinAlias);
}
$sql = 'UPDATE ' . $this->quote($this->table)
. ' JOIN ' . $joinTable
. ' ON ' . $this->resolveAndWrap($this->updateJoinLeft) . ' = ' . $this->resolveAndWrap($this->updateJoinRight);
$assignments = $this->compileAssignments();
if (empty($assignments)) {
throw new ValidationException('No assignments for UPDATE. Call set() or setRaw() before update().');
}
$sql .= ' SET ' . \implode(', ', $assignments);
$parts = [$sql];
$this->compileWhereClauses($parts);
return new Statement(\implode(' ', $parts), $this->bindings, executor: $this->executor);
}
public function deleteJoin(string $alias, string $table, string $left, string $right): static
{
$this->deleteAlias = $alias;
$this->deleteJoinTable = $table;
$this->deleteJoinLeft = $left;
$this->deleteJoinRight = $right;
return $this;
}
#[\Override]
public function delete(): Statement
{
if ($this->deleteAlias !== '') {
return $this->buildDeleteJoin();
}
return parent::delete();
}
private function buildDeleteJoin(): Statement
{
$this->bindings = [];
$this->validateTable();
$sql = 'DELETE ' . $this->quote($this->deleteAlias)
. ' FROM ' . $this->quote($this->table) . ' AS ' . $this->quote($this->deleteAlias)
. ' JOIN ' . $this->quote($this->deleteJoinTable)
. ' ON ' . $this->resolveAndWrap($this->deleteJoinLeft) . ' = ' . $this->resolveAndWrap($this->deleteJoinRight);
$parts = [$sql];
$this->compileWhereClauses($parts);
return new Statement(\implode(' ', $parts), $this->bindings, executor: $this->executor);
}
#[\Override]
protected function groupConcatExpr(string $column, string $orderBy): string
{
$suffix = $orderBy === '' ? '' : ' ' . $orderBy;
return 'GROUP_CONCAT(' . $column . $suffix . ' SEPARATOR ?)';
}
#[\Override]
protected function jsonArrayAggExpr(string $column): string
{
return 'JSON_ARRAYAGG(' . $column . ')';
}
#[\Override]
protected function jsonObjectAggExpr(string $keyColumn, string $valueColumn): string
{
return 'JSON_OBJECTAGG(' . $keyColumn . ', ' . $valueColumn . ')';
}
#[\Override]
public function insertDefaultValues(): Statement
{
$this->bindings = [];
$this->validateTable();
return new Statement('INSERT INTO ' . $this->quote($this->table) . ' () VALUES ()', $this->bindings, executor: $this->executor);
}
#[\Override]
public function withRollup(): static
{
$this->groupByModifier = 'WITH ROLLUP';
return $this;
}
#[\Override]
public function reset(): static
{
parent::reset();
$this->hints = [];
$this->jsonSets = [];
$this->resetGroupByModifier();
$this->updateJoinTable = '';
$this->updateJoinLeft = '';
$this->updateJoinRight = '';
$this->updateJoinAlias = '';
$this->deleteAlias = '';
$this->deleteJoinTable = '';
$this->deleteJoinLeft = '';
$this->deleteJoinRight = '';
return $this;
}
/**
* @param array<mixed> $values
*/
#[\Override]
protected function compileSpatialDistance(Method $method, string $attribute, array $values): string
{
/** @var array{0: string|array<mixed>, 1: float, 2: bool} $tuple */
$tuple = $values[0];
$filter = SpatialDistanceFilter::fromTuple($tuple);
$wkt = \is_array($filter->geometry) ? $this->geometryToWkt($filter->geometry) : $filter->geometry;
$operator = match ($method) {
Method::DistanceLessThan => '<',
Method::DistanceGreaterThan => '>',
Method::DistanceEqual => '=',
Method::DistanceNotEqual => '!=',
default => '<',
};
$this->addBinding($wkt);
$this->addBinding($filter->distance);
if ($filter->meters) {
return 'ST_Distance(ST_SRID(' . $attribute . ', 4326), ' . $this->geomFromText(4326) . ', \'metre\') ' . $operator . ' ?';
}
return 'ST_Distance(ST_SRID(' . $attribute . ', 0), ' . $this->geomFromText(0) . ') ' . $operator . ' ?';
}
/**
* @param array<mixed> $values
*/
#[\Override]
protected function compileSpatialPredicate(string $function, string $attribute, array $values, bool $not): string
{
/** @var array<mixed> $geometry */
$geometry = $values[0];
$wkt = $this->geometryToWkt($geometry);
$this->addBinding($wkt);
$expr = $function . '(' . $attribute . ', ' . $this->geomFromText(4326) . ')';
return $not ? 'NOT ' . $expr : $expr;
}
/**
* @param array<mixed> $values
*/
#[\Override]
protected function compileSpatialCoversPredicate(string $attribute, array $values, bool $not): string
{
return $this->compileSpatialPredicate('ST_Contains', $attribute, $values, $not);
}
protected function geomFromText(int $srid): string
{
return "ST_GeomFromText(?, {$srid}, 'axis-order=long-lat')";
}
/**
* @param array<mixed> $values
*/
#[\Override]
protected function compileJsonContainsExpr(string $attribute, array $values, bool $not): string
{
$this->addBinding($this->encodeJsonPayload($values[0]));
$expr = 'JSON_CONTAINS(' . $attribute . ', ?)';
return $not ? 'NOT ' . $expr : $expr;
}
/**
* @param array<mixed> $values
*/
#[\Override]
protected function compileJsonOverlapsExpr(string $attribute, array $values): string
{
/** @var array<mixed> $arr */
$arr = $values[0];
$this->addBinding($this->encodeJsonPayload($arr));
return 'JSON_OVERLAPS(' . $attribute . ', ?)';
}
private function encodeJsonPayload(mixed $payload): string
{
try {
return \json_encode($payload, JSON_THROW_ON_ERROR);
} catch (\JsonException $exception) {
throw new ValidationException('Invalid JSON payload: ' . $exception->getMessage());
}
}
/**
* @param array<mixed> $values
*/
#[\Override]
protected function compileJsonPathExpr(string $attribute, array $values): string
{
/** @var string $path */
$path = $values[0];
/** @var string $operator */
$operator = $values[1];
$value = $values[2];
if (!\preg_match('/^[a-zA-Z0-9_.\[\]]+$/', $path)) {
throw new ValidationException('Invalid JSON path: ' . $path);
}
$allowedOperators = ['=', '!=', '<', '>', '<=', '>=', '<>'];
if (!\in_array($operator, $allowedOperators, true)) {
throw new ValidationException('Invalid JSON path operator: ' . $operator);
}
$this->addBinding($value);
return 'JSON_EXTRACT(' . $attribute . ', \'$.' . $path . '\') ' . $operator . ' ?';
}
}