forked from utopia-php/database
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Query.php
831 lines (730 loc) · 23.4 KB
/
Query.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
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
<?php
namespace Utopia\Database;
use Utopia\Database\Exception\Query as QueryException;
class Query
{
// Filter methods
public const TYPE_EQUAL = 'equal';
public const TYPE_NOT_EQUAL = 'notEqual';
public const TYPE_LESSER = 'lessThan';
public const TYPE_LESSER_EQUAL = 'lessThanEqual';
public const TYPE_GREATER = 'greaterThan';
public const TYPE_GREATER_EQUAL = 'greaterThanEqual';
public const TYPE_CONTAINS = 'contains';
public const TYPE_SEARCH = 'search';
public const TYPE_IS_NULL = 'isNull';
public const TYPE_IS_NOT_NULL = 'isNotNull';
public const TYPE_BETWEEN = 'between';
public const TYPE_STARTS_WITH = 'startsWith';
public const TYPE_ENDS_WITH = 'endsWith';
public const TYPE_SELECT = 'select';
// Order methods
public const TYPE_ORDERDESC = 'orderDesc';
public const TYPE_ORDERASC = 'orderAsc';
// Pagination methods
public const TYPE_LIMIT = 'limit';
public const TYPE_OFFSET = 'offset';
public const TYPE_CURSORAFTER = 'cursorAfter';
public const TYPE_CURSORBEFORE = 'cursorBefore';
protected const CHAR_SINGLE_QUOTE = '\'';
protected const CHAR_DOUBLE_QUOTE = '"';
protected const CHAR_COMMA = ',';
protected const CHAR_SPACE = ' ';
protected const CHAR_BRACKET_START = '[';
protected const CHAR_BRACKET_END = ']';
protected const CHAR_PARENTHESES_START = '(';
protected const CHAR_PARENTHESES_END = ')';
protected const CHAR_BACKSLASH = '\\';
protected string $method = '';
protected string $attribute = '';
/**
* @var array<mixed>
*/
protected array $values = [];
/**
* Construct a new query object
*
* @param string $method
* @param string $attribute
* @param array<mixed> $values
*/
public function __construct(string $method, string $attribute = '', array $values = [])
{
$this->method = $method;
$this->attribute = $attribute;
$this->values = $values;
}
/**
* @return string
*/
public function getMethod(): string
{
return $this->method;
}
/**
* @return string
*/
public function getAttribute(): string
{
return $this->attribute;
}
/**
* @return array<mixed>
*/
public function getValues(): array
{
return $this->values;
}
/**
* @param mixed $default
* @return mixed
*/
public function getValue(mixed $default = null): mixed
{
return $this->values[0] ?? $default;
}
/**
* Sets method
*
* @param string $method
* @return self
*/
public function setMethod(string $method): self
{
$this->method = $method;
return $this;
}
/**
* Sets attribute
*
* @param string $attribute
* @return self
*/
public function setAttribute(string $attribute): self
{
$this->attribute = $attribute;
return $this;
}
/**
* Sets values
*
* @param array<mixed> $values
* @return self
*/
public function setValues(array $values): self
{
$this->values = $values;
return $this;
}
/**
* Sets value
* @param mixed $value
* @return self
*/
public function setValue(mixed $value): self
{
$this->values = [$value];
return $this;
}
/**
* Check if method is supported
*
* @param string $value
* @return bool
*/
public static function isMethod(string $value): bool
{
return match (static::getMethodFromAlias($value)) {
self::TYPE_EQUAL,
self::TYPE_NOT_EQUAL,
self::TYPE_LESSER,
self::TYPE_LESSER_EQUAL,
self::TYPE_GREATER,
self::TYPE_GREATER_EQUAL,
self::TYPE_CONTAINS,
self::TYPE_SEARCH,
self::TYPE_ORDERASC,
self::TYPE_ORDERDESC,
self::TYPE_LIMIT,
self::TYPE_OFFSET,
self::TYPE_CURSORAFTER,
self::TYPE_CURSORBEFORE,
self::TYPE_IS_NULL,
self::TYPE_IS_NOT_NULL,
self::TYPE_BETWEEN,
self::TYPE_STARTS_WITH,
self::TYPE_ENDS_WITH,
self::TYPE_SELECT => true,
default => false,
};
}
/**
* Parse query filter
*
* @param string $filter
* @return self
* @throws Exception
*/
public static function parse(string $filter): self
{
// Init empty vars we fill later
$method = '';
$params = [];
// Separate method from filter
$paramsStart = mb_strpos($filter, static::CHAR_PARENTHESES_START);
if ($paramsStart === false) {
throw new QueryException('Invalid query');
}
$method = mb_substr($filter, 0, $paramsStart);
// Separate params from filter
$paramsEnd = \strlen($filter) - 1; // -1 to ignore )
$parametersStart = $paramsStart + 1; // +1 to ignore (
// Check for deprecated query syntax
if (\str_contains($method, '.')) {
throw new QueryException('Invalid query method');
}
$currentParam = ""; // We build param here before pushing when it's ended
$currentArrayParam = []; // We build array param here before pushing when it's ended
$stack = []; // State for stack of parentheses
$stackCount = 0; // Length of stack array. Kept as variable to improve performance
$stringStackState = null; // State for string support
// Loop thorough all characters
for ($i = $parametersStart; $i < $paramsEnd; $i++) {
$char = $filter[$i];
$isStringStack = $stringStackState !== null;
$isArrayStack = !$isStringStack && $stackCount > 0;
if ($char === static::CHAR_BACKSLASH) {
if (!(static::isSpecialChar($filter[$i + 1]))) {
static::appendSymbol($isStringStack, $filter[$i], $i, $filter, $currentParam);
}
static::appendSymbol($isStringStack, $filter[$i + 1], $i, $filter, $currentParam);
$i++;
continue;
}
// String support + escaping support
if (
(self::isQuote($char)) && // Must be string indicator
($filter[$i - 1] !== static::CHAR_BACKSLASH || $filter[$i - 2] === static::CHAR_BACKSLASH) // Must not be escaped;
) {
if ($isStringStack) {
// Dont mix-up string symbols. Only allow the same as on start
if ($char === $stringStackState) {
// End of string
$stringStackState = null;
}
// Either way, add symbol to builder
static::appendSymbol($isStringStack, $char, $i, $filter, $currentParam);
} else {
// Start of string
$stringStackState = $char;
static::appendSymbol($isStringStack, $char, $i, $filter, $currentParam);
}
continue;
}
// Array support
if (!($isStringStack)) {
if ($char === static::CHAR_BRACKET_START) {
// Start of array
$stack[] = $char;
$stackCount++;
continue;
} elseif ($char === static::CHAR_BRACKET_END) {
// End of array
\array_pop($stack);
$stackCount--;
if (strlen($currentParam)) {
$currentArrayParam[] = $currentParam;
}
$params[] = $currentArrayParam;
$currentArrayParam = [];
$currentParam = "";
continue;
} elseif ($char === static::CHAR_COMMA) { // Params separation support
// If in array stack, dont merge yet, just mark it in array param builder
if ($isArrayStack) {
$currentArrayParam[] = $currentParam;
$currentParam = "";
} else {
// Append from parap builder. Either value, or array
if (empty($currentArrayParam)) {
if (strlen($currentParam)) {
$params[] = $currentParam;
}
$currentParam = "";
}
}
continue;
}
}
// Value, not relevant to syntax
static::appendSymbol($isStringStack, $char, $i, $filter, $currentParam);
}
if (strlen($currentParam)) {
$params[] = $currentParam;
$currentParam = "";
}
$parsedParams = [];
foreach ($params as $param) {
// If array, parse each child separatelly
if (\is_array($param)) {
foreach ($param as $element) {
$arr[] = self::parseValue($element);
}
$parsedParams[] = $arr ?? [];
} else {
$parsedParams[] = self::parseValue($param);
}
}
$method = static::getMethodFromAlias($method);
switch ($method) {
case self::TYPE_EQUAL:
case self::TYPE_NOT_EQUAL:
case self::TYPE_LESSER:
case self::TYPE_LESSER_EQUAL:
case self::TYPE_GREATER:
case self::TYPE_GREATER_EQUAL:
case self::TYPE_CONTAINS:
case self::TYPE_SEARCH:
case self::TYPE_IS_NULL:
case self::TYPE_IS_NOT_NULL:
case self::TYPE_STARTS_WITH:
case self::TYPE_ENDS_WITH:
$attribute = $parsedParams[0] ?? '';
if (count($parsedParams) < 2) {
return new self($method, $attribute);
}
return new self($method, $attribute, \is_array($parsedParams[1]) ? $parsedParams[1] : [$parsedParams[1]]);
case self::TYPE_BETWEEN:
return new self($method, $parsedParams[0], [$parsedParams[1], $parsedParams[2]]);
case self::TYPE_SELECT:
return new self($method, values: $parsedParams[0]);
case self::TYPE_ORDERASC:
case self::TYPE_ORDERDESC:
return new self($method, $parsedParams[0] ?? '');
case self::TYPE_LIMIT:
case self::TYPE_OFFSET:
case self::TYPE_CURSORAFTER:
case self::TYPE_CURSORBEFORE:
if (count($parsedParams) > 0) {
return new self($method, values: [$parsedParams[0]]);
}
return new self($method);
default:
return new self($method);
}
}
/**
* Utility method to only append symbol if relevant.
*
* @param bool $isStringStack
* @param string $char
* @param int $index
* @param string $filter
* @param string $currentParam
* @return void
*/
protected static function appendSymbol(bool $isStringStack, string $char, int $index, string $filter, string &$currentParam): void
{
// Ignore spaces and commas outside of string
$canBeIgnored = false;
if ($char === static::CHAR_SPACE) {
$canBeIgnored = true;
} elseif ($char === static::CHAR_COMMA) {
$canBeIgnored = true;
}
if ($canBeIgnored) {
if ($isStringStack) {
$currentParam .= $char;
}
} else {
$currentParam .= $char;
}
}
protected static function isQuote(string $char): bool
{
if ($char === self::CHAR_SINGLE_QUOTE) {
return true;
} elseif ($char === self::CHAR_DOUBLE_QUOTE) {
return true;
}
return false;
}
protected static function isSpecialChar(string $char): bool
{
if ($char === static::CHAR_COMMA) {
return true;
} elseif ($char === static::CHAR_BRACKET_END) {
return true;
} elseif ($char === static::CHAR_BRACKET_START) {
return true;
} elseif ($char === static::CHAR_DOUBLE_QUOTE) {
return true;
} elseif ($char === static::CHAR_SINGLE_QUOTE) {
return true;
}
return false;
}
/**
* Parses value.
*
* @param string $value
* @return mixed
*/
protected static function parseValue(string $value): mixed
{
$value = \trim($value);
if ($value === 'false') { // Boolean value
return false;
} elseif ($value === 'true') {
return true;
} elseif ($value === 'null') { // Null value
return null;
} elseif (\is_numeric($value)) { // Numeric value
// Cast to number
return $value + 0;
} elseif (\str_starts_with($value, static::CHAR_DOUBLE_QUOTE) || \str_starts_with($value, static::CHAR_SINGLE_QUOTE)) { // String param
$value = \substr($value, 1, -1); // Remove '' or ""
return $value;
}
// Unknown format
return $value;
}
/**
* Returns Method from Alias.
*
* @param string $method
* @return string
*/
protected static function getMethodFromAlias(string $method): string
{
return $method;
/*
Commented out as we didn't consider this important at the moment, since IDE autocomplete should do the job.
return match ($method) {
'lt' => self::TYPE_LESSER,
'lte' => self::TYPE_LESSEREQUAL,
'gt' => self::TYPE_GREATER,
'gte' => self::TYPE_GREATEREQUAL,
'eq' => self::TYPE_EQUAL,
default => $method
};
*/
}
/**
* Helper method to create Query with equal method
*
* @param string $attribute
* @param array<mixed> $values
* @return Query
*/
public static function equal(string $attribute, array $values): self
{
return new self(self::TYPE_EQUAL, $attribute, $values);
}
/**
* Helper method to create Query with notEqual method
*
* @param string $attribute
* @param mixed $value
* @return Query
*/
public static function notEqual(string $attribute, mixed $value): self
{
return new self(self::TYPE_NOT_EQUAL, $attribute, [$value]);
}
/**
* Helper method to create Query with lessThan method
*
* @param string $attribute
* @param mixed $value
* @return Query
*/
public static function lessThan(string $attribute, mixed $value): self
{
return new self(self::TYPE_LESSER, $attribute, [$value]);
}
/**
* Helper method to create Query with lessThanEqual method
*
* @param string $attribute
* @param mixed $value
* @return Query
*/
public static function lessThanEqual(string $attribute, mixed $value): self
{
return new self(self::TYPE_LESSER_EQUAL, $attribute, [$value]);
}
/**
* Helper method to create Query with greaterThan method
*
* @param string $attribute
* @param mixed $value
* @return Query
*/
public static function greaterThan(string $attribute, mixed $value): self
{
return new self(self::TYPE_GREATER, $attribute, [$value]);
}
/**
* Helper method to create Query with greaterThanEqual method
*
* @param string $attribute
* @param mixed $value
* @return Query
*/
public static function greaterThanEqual(string $attribute, mixed$value): self
{
return new self(self::TYPE_GREATER_EQUAL, $attribute, [$value]);
}
/**
* Helper method to create Query with contains method
*
* @param string $attribute
* @param array<mixed> $values
* @return Query
*/
public static function contains(string $attribute, array $values): self
{
return new self(self::TYPE_CONTAINS, $attribute, $values);
}
/**
* Helper method to create Query with between method
*
* @param string $attribute
* @param mixed $start
* @param mixed $end
* @return Query
*/
public static function between(string $attribute, mixed $start, mixed $end): self
{
return new self(self::TYPE_BETWEEN, $attribute, [$start, $end]);
}
/**
* Helper method to create Query with search method
*
* @param string $attribute
* @param mixed $value
* @return Query
*/
public static function search(string $attribute, mixed $value): self
{
return new self(self::TYPE_SEARCH, $attribute, [$value]);
}
/**
* Helper method to create Query with select method
*
* @param array<string> $attributes
* @return Query
*/
public static function select(array $attributes): self
{
return new self(self::TYPE_SELECT, values: $attributes);
}
/**
* Helper method to create Query with orderDesc method
*
* @param string $attribute
* @return Query
*/
public static function orderDesc(string $attribute): self
{
return new self(self::TYPE_ORDERDESC, $attribute);
}
/**
* Helper method to create Query with orderAsc method
*
* @param string $attribute
* @return Query
*/
public static function orderAsc(string $attribute): self
{
return new self(self::TYPE_ORDERASC, $attribute);
}
/**
* Helper method to create Query with limit method
*
* @param int $value
* @return Query
*/
public static function limit(int $value): self
{
return new self(self::TYPE_LIMIT, values: [$value]);
}
/**
* Helper method to create Query with offset method
*
* @param int $value
* @return Query
*/
public static function offset(int $value): self
{
return new self(self::TYPE_OFFSET, values: [$value]);
}
/**
* Helper method to create Query with cursorAfter method
*
* @param Document $value
* @return Query
*/
public static function cursorAfter(Document $value): self
{
return new self(self::TYPE_CURSORAFTER, values: [$value]);
}
/**
* Helper method to create Query with cursorBefore method
*
* @param Document $value
* @return Query
*/
public static function cursorBefore(Document $value): self
{
return new self(self::TYPE_CURSORBEFORE, values: [$value]);
}
/**
* Helper method to create Query with isNull method
*
* @param string $attribute
* @return Query
*/
public static function isNull(string $attribute): self
{
return new self(self::TYPE_IS_NULL, $attribute);
}
/**
* Helper method to create Query with isNotNull method
*
* @param string $attribute
* @return Query
*/
public static function isNotNull(string $attribute): self
{
return new self(self::TYPE_IS_NOT_NULL, $attribute);
}
public static function startsWith(string $attribute, string $value): self
{
return new self(self::TYPE_STARTS_WITH, $attribute, [$value]);
}
public static function endsWith(string $attribute, string $value): self
{
return new self(self::TYPE_ENDS_WITH, $attribute, [$value]);
}
/**
* Filters $queries for $types
*
* @param array<Query> $queries
* @param array<string> $types
* @return array<Query>
*/
public static function getByType(array $queries, array $types): array
{
$filtered = [];
foreach ($queries as $query) {
if (in_array($query->getMethod(), $types, true)) {
$filtered[] = clone $query;
}
}
return $filtered;
}
/**
* Iterates through queries are groups them by type
*
* @param array<Query> $queries
* @return array{
* filters: array<Query>,
* selections: array<Query>,
* limit: int|null,
* offset: int|null,
* orderAttributes: array<string>,
* orderTypes: array<string>,
* cursor: Document|null,
* cursorDirection: string|null
* }
*/
public static function groupByType(array $queries): array
{
$filters = [];
$selections = [];
$limit = null;
$offset = null;
$orderAttributes = [];
$orderTypes = [];
$cursor = null;
$cursorDirection = null;
foreach ($queries as $query) {
if (!$query instanceof Query) {
continue;
}
$method = $query->getMethod();
$attribute = $query->getAttribute();
$values = $query->getValues();
switch ($method) {
case Query::TYPE_ORDERASC:
case Query::TYPE_ORDERDESC:
if (!empty($attribute)) {
$orderAttributes[] = $attribute;
}
$orderTypes[] = $method === Query::TYPE_ORDERASC ? Database::ORDER_ASC : Database::ORDER_DESC;
break;
case Query::TYPE_LIMIT:
// keep the 1st limit encountered and ignore the rest
if ($limit !== null) {
break;
}
$limit = $values[0] ?? $limit;
break;
case Query::TYPE_OFFSET:
// keep the 1st offset encountered and ignore the rest
if ($offset !== null) {
break;
}
$offset = $values[0] ?? $limit;
break;
case Query::TYPE_CURSORAFTER:
case Query::TYPE_CURSORBEFORE:
// keep the 1st cursor encountered and ignore the rest
if ($cursor !== null) {
break;
}
$cursor = $values[0] ?? $limit;
$cursorDirection = $method === Query::TYPE_CURSORAFTER ? Database::CURSOR_AFTER : Database::CURSOR_BEFORE;
break;
case Query::TYPE_SELECT:
$selections[] = clone $query;
break;
default:
$filters[] = clone $query;
break;
}
}
return [
'filters' => $filters,
'selections' => $selections,
'limit' => $limit,
'offset' => $offset,
'orderAttributes' => $orderAttributes,
'orderTypes' => $orderTypes,
'cursor' => $cursor,
'cursorDirection' => $cursorDirection,
];
}
/**
* Iterate over $queries attempting to parse each
*
* @param array<string> $queries
*
* @return array<Query>
* @throws Exception
*/
public static function parseQueries(array $queries): array
{
$parsed = [];
foreach ($queries as $query) {
try {
$parsed[] = Query::parse($query);
} catch (\Throwable $th) {
throw new QueryException("Invalid query: ${query}", previous: $th);
}
}
return $parsed;
}
}