-
Notifications
You must be signed in to change notification settings - Fork 290
/
terms.py
1601 lines (1222 loc) · 54 KB
/
terms.py
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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import inspect
import re
import uuid
from datetime import date
from enum import Enum
from typing import Any, Iterable, Iterator, List, Optional, Sequence, Set, TYPE_CHECKING, Type, TypeVar, Union
from pypika.enums import Arithmetic, Boolean, Comparator, Dialects, Equality, JSONOperators, Matching, Order
from pypika.utils import (
CaseException,
FunctionException,
builder,
format_alias_sql,
format_quotes,
ignore_copy,
resolve_is_aggregate,
)
if TYPE_CHECKING:
from pypika.queries import Table, QueryBuilder, Selectable
__author__ = "Timothy Heys"
__email__ = "theys@kayak.com"
NodeT = TypeVar("NodeT", bound="Node")
class Node:
is_aggregate = None
def nodes_(self) -> Iterator[NodeT]:
yield self
def find_(self, type: Type[NodeT]) -> List[NodeT]:
return [node for node in self.nodes_() if isinstance(node, type)]
class Term(Node):
is_aggregate = False
def __init__(self, alias: Optional[str] = None) -> None:
self.alias = alias
@builder
def as_(self, alias: str) -> "Term":
self.alias = alias
@property
def tables_(self) -> Set["Table"]:
from pypika import Table
return set(self.find_(Table))
def fields_(self) -> Set["Field"]:
return set(self.find_(Field))
@staticmethod
def wrap_constant(
val, wrapper_cls: Optional[Type["Term"]] = None
) -> Union[ValueError, NodeT, "LiteralValue", "Array", "Tuple", "ValueWrapper"]:
"""
Used for wrapping raw inputs such as numbers in Criterions and Operator.
For example, the expression F('abc')+1 stores the integer part in a ValueWrapper object.
:param val:
Any value.
:param wrapper_cls:
A pypika class which wraps a constant value so it can be handled as a component of the query.
:return:
Raw string, number, or decimal values will be returned in a ValueWrapper. Fields and other parts of the
querybuilder will be returned as inputted.
"""
if isinstance(val, Node):
return val
if val is None:
return NullValue()
if isinstance(val, list):
return Array(*val)
if isinstance(val, tuple):
return Tuple(*val)
# Need to default here to avoid the recursion. ValueWrapper extends this class.
wrapper_cls = wrapper_cls or ValueWrapper
return wrapper_cls(val)
@staticmethod
def wrap_json(
val: Union["Term", "QueryBuilder", "Interval", None, str, int, bool], wrapper_cls=None
) -> Union["Term", "QueryBuilder", "Interval", "NullValue", "ValueWrapper", "JSON"]:
from .queries import QueryBuilder
if isinstance(val, (Term, QueryBuilder, Interval)):
return val
if val is None:
return NullValue()
if isinstance(val, (str, int, bool)):
wrapper_cls = wrapper_cls or ValueWrapper
return wrapper_cls(val)
return JSON(val)
def replace_table(self, current_table: Optional["Table"], new_table: Optional["Table"]) -> "Term":
"""
Replaces all occurrences of the specified table with the new table. Useful when reusing fields across queries.
The base implementation returns self because not all terms have a table property.
:param current_table:
The table to be replaced.
:param new_table:
The table to replace with.
:return:
Self.
"""
return self
def eq(self, other: Any) -> "BasicCriterion":
return self == other
def isnull(self) -> "NullCriterion":
return NullCriterion(self)
def notnull(self) -> "Not":
return self.isnull().negate()
def bitwiseand(self, value: int) -> "BitwiseAndCriterion":
return BitwiseAndCriterion(self, self.wrap_constant(value))
def gt(self, other: Any) -> "BasicCriterion":
return self > other
def gte(self, other: Any) -> "BasicCriterion":
return self >= other
def lt(self, other: Any) -> "BasicCriterion":
return self < other
def lte(self, other: Any) -> "BasicCriterion":
return self <= other
def ne(self, other: Any) -> "BasicCriterion":
return self != other
def glob(self, expr: str) -> "BasicCriterion":
return BasicCriterion(Matching.glob, self, self.wrap_constant(expr))
def like(self, expr: str) -> "BasicCriterion":
return BasicCriterion(Matching.like, self, self.wrap_constant(expr))
def not_like(self, expr: str) -> "BasicCriterion":
return BasicCriterion(Matching.not_like, self, self.wrap_constant(expr))
def ilike(self, expr: str) -> "BasicCriterion":
return BasicCriterion(Matching.ilike, self, self.wrap_constant(expr))
def not_ilike(self, expr: str) -> "BasicCriterion":
return BasicCriterion(Matching.not_ilike, self, self.wrap_constant(expr))
def rlike(self, expr: str) -> "BasicCriterion":
return BasicCriterion(Matching.rlike, self, self.wrap_constant(expr))
def regex(self, pattern: str) -> "BasicCriterion":
return BasicCriterion(Matching.regex, self, self.wrap_constant(pattern))
def between(self, lower: Any, upper: Any) -> "BetweenCriterion":
return BetweenCriterion(self, self.wrap_constant(lower), self.wrap_constant(upper))
def from_to(self, start: Any, end: Any) -> "PeriodCriterion":
return PeriodCriterion(self, self.wrap_constant(start), self.wrap_constant(end))
def as_of(self, expr: str) -> "BasicCriterion":
return BasicCriterion(Matching.as_of, self, self.wrap_constant(expr))
def all_(self) -> "All":
return All(self)
def isin(self, arg: Union[list, tuple, set, "Term"]) -> "ContainsCriterion":
if isinstance(arg, (list, tuple, set)):
return ContainsCriterion(self, Tuple(*[self.wrap_constant(value) for value in arg]))
return ContainsCriterion(self, arg)
def notin(self, arg: Union[list, tuple, set, "Term"]) -> "ContainsCriterion":
return self.isin(arg).negate()
def bin_regex(self, pattern: str) -> "BasicCriterion":
return BasicCriterion(Matching.bin_regex, self, self.wrap_constant(pattern))
def negate(self) -> "Not":
return Not(self)
def __invert__(self) -> "Not":
return Not(self)
def __pos__(self) -> "Term":
return self
def __neg__(self) -> "Negative":
return Negative(self)
def __add__(self, other: Any) -> "ArithmeticExpression":
return ArithmeticExpression(Arithmetic.add, self, self.wrap_constant(other))
def __sub__(self, other: Any) -> "ArithmeticExpression":
return ArithmeticExpression(Arithmetic.sub, self, self.wrap_constant(other))
def __mul__(self, other: Any) -> "ArithmeticExpression":
return ArithmeticExpression(Arithmetic.mul, self, self.wrap_constant(other))
def __truediv__(self, other: Any) -> "ArithmeticExpression":
return ArithmeticExpression(Arithmetic.div, self, self.wrap_constant(other))
def __pow__(self, other: Any) -> "Pow":
return Pow(self, other)
def __mod__(self, other: Any) -> "Mod":
return Mod(self, other)
def __radd__(self, other: Any) -> "ArithmeticExpression":
return ArithmeticExpression(Arithmetic.add, self.wrap_constant(other), self)
def __rsub__(self, other: Any) -> "ArithmeticExpression":
return ArithmeticExpression(Arithmetic.sub, self.wrap_constant(other), self)
def __rmul__(self, other: Any) -> "ArithmeticExpression":
return ArithmeticExpression(Arithmetic.mul, self.wrap_constant(other), self)
def __rtruediv__(self, other: Any) -> "ArithmeticExpression":
return ArithmeticExpression(Arithmetic.div, self.wrap_constant(other), self)
def __eq__(self, other: Any) -> "BasicCriterion":
return BasicCriterion(Equality.eq, self, self.wrap_constant(other))
def __ne__(self, other: Any) -> "BasicCriterion":
return BasicCriterion(Equality.ne, self, self.wrap_constant(other))
def __gt__(self, other: Any) -> "BasicCriterion":
return BasicCriterion(Equality.gt, self, self.wrap_constant(other))
def __ge__(self, other: Any) -> "BasicCriterion":
return BasicCriterion(Equality.gte, self, self.wrap_constant(other))
def __lt__(self, other: Any) -> "BasicCriterion":
return BasicCriterion(Equality.lt, self, self.wrap_constant(other))
def __le__(self, other: Any) -> "BasicCriterion":
return BasicCriterion(Equality.lte, self, self.wrap_constant(other))
def __getitem__(self, item: slice) -> "BetweenCriterion":
if not isinstance(item, slice):
raise TypeError("Field' object is not subscriptable")
return self.between(item.start, item.stop)
def __str__(self) -> str:
return self.get_sql(quote_char='"', secondary_quote_char="'")
def __hash__(self) -> int:
return hash(self.get_sql(with_alias=True))
def get_sql(self, **kwargs: Any) -> str:
raise NotImplementedError()
class Parameter(Term):
is_aggregate = None
def __init__(self, placeholder: Union[str, int]) -> None:
super().__init__()
self.placeholder = placeholder
def get_sql(self, **kwargs: Any) -> str:
return str(self.placeholder)
class QmarkParameter(Parameter):
"""Question mark style, e.g. ...WHERE name=?"""
def __init__(self) -> None:
pass
def get_sql(self, **kwargs: Any) -> str:
return "?"
class NumericParameter(Parameter):
"""Numeric, positional style, e.g. ...WHERE name=:1"""
def get_sql(self, **kwargs: Any) -> str:
return ":{placeholder}".format(placeholder=self.placeholder)
class NamedParameter(Parameter):
"""Named style, e.g. ...WHERE name=:name"""
def get_sql(self, **kwargs: Any) -> str:
return ":{placeholder}".format(placeholder=self.placeholder)
class FormatParameter(Parameter):
"""ANSI C printf format codes, e.g. ...WHERE name=%s"""
def __init__(self) -> None:
pass
def get_sql(self, **kwargs: Any) -> str:
return "%s"
class PyformatParameter(Parameter):
"""Python extended format codes, e.g. ...WHERE name=%(name)s"""
def get_sql(self, **kwargs: Any) -> str:
return "%({placeholder})s".format(placeholder=self.placeholder)
class Negative(Term):
def __init__(self, term: Term) -> None:
super().__init__()
self.term = term
@property
def is_aggregate(self) -> Optional[bool]:
return self.term.is_aggregate
def get_sql(self, **kwargs: Any) -> str:
return "-{term}".format(term=self.term.get_sql(**kwargs))
class ValueWrapper(Term):
is_aggregate = None
def __init__(self, value: Any, alias: Optional[str] = None) -> None:
super().__init__(alias)
self.value = value
def get_value_sql(self, **kwargs: Any) -> str:
return self.get_formatted_value(self.value, **kwargs)
@classmethod
def get_formatted_value(cls, value: Any, **kwargs):
quote_char = kwargs.get("secondary_quote_char") or ""
# FIXME escape values
if isinstance(value, Term):
return value.get_sql(**kwargs)
if isinstance(value, Enum):
return cls.get_formatted_value(value.value, **kwargs)
if isinstance(value, date):
return cls.get_formatted_value(value.isoformat(), **kwargs)
if isinstance(value, str):
value = value.replace(quote_char, quote_char * 2)
return format_quotes(value, quote_char)
if isinstance(value, bool):
return str.lower(str(value))
if isinstance(value, uuid.UUID):
return cls.get_formatted_value(str(value), **kwargs)
if value is None:
return "null"
return str(value)
def get_sql(self, quote_char: Optional[str] = None, secondary_quote_char: str = "'", **kwargs: Any) -> str:
sql = self.get_value_sql(quote_char=quote_char, secondary_quote_char=secondary_quote_char, **kwargs)
return format_alias_sql(sql, self.alias, quote_char=quote_char, **kwargs)
class JSON(Term):
table = None
def __init__(self, value: Any = None, alias: Optional[str] = None) -> None:
super().__init__(alias)
self.value = value
def _recursive_get_sql(self, value: Any, **kwargs: Any) -> str:
if isinstance(value, dict):
return self._get_dict_sql(value, **kwargs)
if isinstance(value, list):
return self._get_list_sql(value, **kwargs)
if isinstance(value, str):
return self._get_str_sql(value, **kwargs)
return str(value)
def _get_dict_sql(self, value: dict, **kwargs: Any) -> str:
pairs = [
"{key}:{value}".format(
key=self._recursive_get_sql(k, **kwargs),
value=self._recursive_get_sql(v, **kwargs),
)
for k, v in value.items()
]
return "".join(["{", ",".join(pairs), "}"])
def _get_list_sql(self, value: list, **kwargs: Any) -> str:
pairs = [self._recursive_get_sql(v, **kwargs) for v in value]
return "".join(["[", ",".join(pairs), "]"])
@staticmethod
def _get_str_sql(value: str, quote_char: str = '"', **kwargs: Any) -> str:
return format_quotes(value, quote_char)
def get_sql(self, secondary_quote_char: str = "'", **kwargs: Any) -> str:
sql = format_quotes(self._recursive_get_sql(self.value), secondary_quote_char)
return format_alias_sql(sql, self.alias, **kwargs)
def get_json_value(self, key_or_index: Union[str, int]) -> "BasicCriterion":
return BasicCriterion(JSONOperators.GET_JSON_VALUE, self, self.wrap_constant(key_or_index))
def get_text_value(self, key_or_index: Union[str, int]) -> "BasicCriterion":
return BasicCriterion(JSONOperators.GET_TEXT_VALUE, self, self.wrap_constant(key_or_index))
def get_path_json_value(self, path_json: str) -> "BasicCriterion":
return BasicCriterion(JSONOperators.GET_PATH_JSON_VALUE, self, self.wrap_json(path_json))
def get_path_text_value(self, path_json: str) -> "BasicCriterion":
return BasicCriterion(JSONOperators.GET_PATH_TEXT_VALUE, self, self.wrap_json(path_json))
def has_key(self, other: Any) -> "BasicCriterion":
return BasicCriterion(JSONOperators.HAS_KEY, self, self.wrap_json(other))
def contains(self, other: Any) -> "BasicCriterion":
return BasicCriterion(JSONOperators.CONTAINS, self, self.wrap_json(other))
def contained_by(self, other: Any) -> "BasicCriterion":
return BasicCriterion(JSONOperators.CONTAINED_BY, self, self.wrap_json(other))
def has_keys(self, other: Iterable) -> "BasicCriterion":
return BasicCriterion(JSONOperators.HAS_KEYS, self, Array(*other))
def has_any_keys(self, other: Iterable) -> "BasicCriterion":
return BasicCriterion(JSONOperators.HAS_ANY_KEYS, self, Array(*other))
class Values(Term):
def __init__(self, field: Union[str, "Field"]) -> None:
super().__init__(None)
self.field = Field(field) if not isinstance(field, Field) else field
def get_sql(self, quote_char: Optional[str] = None, **kwargs: Any) -> str:
return "VALUES({value})".format(value=self.field.get_sql(quote_char=quote_char, **kwargs))
class LiteralValue(Term):
def __init__(self, value, alias: Optional[str] = None) -> None:
super().__init__(alias)
self._value = value
def get_sql(self, **kwargs: Any) -> str:
return format_alias_sql(self._value, self.alias, **kwargs)
class NullValue(LiteralValue):
def __init__(self, alias: Optional[str] = None) -> None:
super().__init__("NULL", alias)
class SystemTimeValue(LiteralValue):
def __init__(self, alias: Optional[str] = None) -> None:
super().__init__("SYSTEM_TIME", alias)
class Criterion(Term):
def __and__(self, other: Any) -> "ComplexCriterion":
return ComplexCriterion(Boolean.and_, self, other)
def __or__(self, other: Any) -> "ComplexCriterion":
return ComplexCriterion(Boolean.or_, self, other)
def __xor__(self, other: Any) -> "ComplexCriterion":
return ComplexCriterion(Boolean.xor_, self, other)
@staticmethod
def any(terms: Iterable[Term] = ()) -> "EmptyCriterion":
crit = EmptyCriterion()
for term in terms:
crit |= term
return crit
@staticmethod
def all(terms: Iterable[Any] = ()) -> "EmptyCriterion":
crit = EmptyCriterion()
for term in terms:
crit &= term
return crit
def get_sql(self) -> str:
raise NotImplementedError()
class EmptyCriterion:
is_aggregate = None
tables_ = set()
def fields_(self) -> Set["Field"]:
return set()
def __and__(self, other: Any) -> Any:
return other
def __or__(self, other: Any) -> Any:
return other
def __xor__(self, other: Any) -> Any:
return other
class Field(Criterion, JSON):
def __init__(
self, name: str, alias: Optional[str] = None, table: Optional[Union[str, "Selectable"]] = None
) -> None:
super().__init__(alias=alias)
self.name = name
self.table = table
def nodes_(self) -> Iterator[NodeT]:
yield self
if self.table is not None:
yield from self.table.nodes_()
@builder
def replace_table(self, current_table: Optional["Table"], new_table: Optional["Table"]) -> "Field":
"""
Replaces all occurrences of the specified table with the new table. Useful when reusing fields across queries.
:param current_table:
The table to be replaced.
:param new_table:
The table to replace with.
:return:
A copy of the field with the tables replaced.
"""
self.table = new_table if self.table == current_table else self.table
def get_sql(self, **kwargs: Any) -> str:
with_alias = kwargs.pop("with_alias", False)
with_namespace = kwargs.pop("with_namespace", False)
quote_char = kwargs.pop("quote_char", None)
field_sql = format_quotes(self.name, quote_char)
# Need to add namespace if the table has an alias
if self.table and (with_namespace or self.table.alias):
table_name = self.table.get_table_name()
field_sql = "{namespace}.{name}".format(
namespace=format_quotes(table_name, quote_char),
name=field_sql,
)
field_alias = getattr(self, "alias", None)
if with_alias:
return format_alias_sql(field_sql, field_alias, quote_char=quote_char, **kwargs)
return field_sql
class Index(Term):
def __init__(self, name: str, alias: Optional[str] = None) -> None:
super().__init__(alias)
self.name = name
def get_sql(self, quote_char: Optional[str] = None, **kwargs: Any) -> str:
return format_quotes(self.name, quote_char)
class Star(Field):
def __init__(self, table: Optional[Union[str, "Selectable"]] = None) -> None:
super().__init__("*", table=table)
def nodes_(self) -> Iterator[NodeT]:
yield self
if self.table is not None:
yield from self.table.nodes_()
def get_sql(
self, with_alias: bool = False, with_namespace: bool = False, quote_char: Optional[str] = None, **kwargs: Any
) -> str:
if self.table and (with_namespace or self.table.alias):
namespace = self.table.alias or getattr(self.table, "_table_name")
return "{}.*".format(format_quotes(namespace, quote_char))
return "*"
class Tuple(Criterion):
def __init__(self, *values: Any) -> None:
super().__init__()
self.values = [self.wrap_constant(value) for value in values]
def nodes_(self) -> Iterator[NodeT]:
yield self
for value in self.values:
yield from value.nodes_()
def get_sql(self, **kwargs: Any) -> str:
sql = "({})".format(",".join(term.get_sql(**kwargs) for term in self.values))
return format_alias_sql(sql, self.alias, **kwargs)
@property
def is_aggregate(self) -> bool:
return resolve_is_aggregate([val.is_aggregate for val in self.values])
@builder
def replace_table(self, current_table: Optional["Table"], new_table: Optional["Table"]) -> "Tuple":
"""
Replaces all occurrences of the specified table with the new table. Useful when reusing fields across queries.
:param current_table:
The table to be replaced.
:param new_table:
The table to replace with.
:return:
A copy of the field with the tables replaced.
"""
self.values = [value.replace_table(current_table, new_table) for value in self.values]
class Array(Tuple):
def get_sql(self, **kwargs: Any) -> str:
dialect = kwargs.get("dialect", None)
values = ",".join(term.get_sql(**kwargs) for term in self.values)
sql = "[{}]".format(values)
if dialect in (Dialects.POSTGRESQL, Dialects.REDSHIFT):
sql = "ARRAY[{}]".format(values) if len(values) > 0 else "'{}'"
return format_alias_sql(sql, self.alias, **kwargs)
class Bracket(Tuple):
def __init__(self, term: Any) -> None:
super().__init__(term)
class NestedCriterion(Criterion):
def __init__(
self,
comparator: Comparator,
nested_comparator: "ComplexCriterion",
left: Any,
right: Any,
nested: Any,
alias: Optional[str] = None,
) -> None:
super().__init__(alias)
self.left = left
self.comparator = comparator
self.nested_comparator = nested_comparator
self.right = right
self.nested = nested
def nodes_(self) -> Iterator[NodeT]:
yield self
yield from self.right.nodes_()
yield from self.left.nodes_()
yield from self.nested.nodes_()
@property
def is_aggregate(self) -> Optional[bool]:
return resolve_is_aggregate([term.is_aggregate for term in [self.left, self.right, self.nested]])
@builder
def replace_table(self, current_table: Optional["Table"], new_table: Optional["Table"]) -> "NestedCriterion":
"""
Replaces all occurrences of the specified table with the new table. Useful when reusing fields across queries.
:param current_table:
The table to be replaced.
:param new_table:
The table to replace with.
:return:
A copy of the criterion with the tables replaced.
"""
self.left = self.left.replace_table(current_table, new_table)
self.right = self.right.replace_table(current_table, new_table)
self.nested = self.right.replace_table(current_table, new_table)
def get_sql(self, with_alias: bool = False, **kwargs: Any) -> str:
sql = "{left}{comparator}{right}{nested_comparator}{nested}".format(
left=self.left.get_sql(**kwargs),
comparator=self.comparator.value,
right=self.right.get_sql(**kwargs),
nested_comparator=self.nested_comparator.value,
nested=self.nested.get_sql(**kwargs),
)
if with_alias:
return format_alias_sql(sql=sql, alias=self.alias, **kwargs)
return sql
class BasicCriterion(Criterion):
def __init__(self, comparator: Comparator, left: Term, right: Term, alias: Optional[str] = None) -> None:
"""
A wrapper for a basic criterion such as equality or inequality. This wraps three parts, a left and right term
and a comparator which defines the type of comparison.
:param comparator:
Type: Comparator
This defines the type of comparison, such as {quote}={quote} or {quote}>{quote}.
:param left:
The term on the left side of the expression.
:param right:
The term on the right side of the expression.
"""
super().__init__(alias)
self.comparator = comparator
self.left = left
self.right = right
def nodes_(self) -> Iterator[NodeT]:
yield self
yield from self.right.nodes_()
yield from self.left.nodes_()
@property
def is_aggregate(self) -> Optional[bool]:
return resolve_is_aggregate([term.is_aggregate for term in [self.left, self.right]])
@builder
def replace_table(self, current_table: Optional["Table"], new_table: Optional["Table"]) -> "BasicCriterion":
"""
Replaces all occurrences of the specified table with the new table. Useful when reusing fields across queries.
:param current_table:
The table to be replaced.
:param new_table:
The table to replace with.
:return:
A copy of the criterion with the tables replaced.
"""
self.left = self.left.replace_table(current_table, new_table)
self.right = self.right.replace_table(current_table, new_table)
def get_sql(self, quote_char: str = '"', with_alias: bool = False, **kwargs: Any) -> str:
sql = "{left}{comparator}{right}".format(
comparator=self.comparator.value,
left=self.left.get_sql(quote_char=quote_char, **kwargs),
right=self.right.get_sql(quote_char=quote_char, **kwargs),
)
if with_alias:
return format_alias_sql(sql, self.alias, **kwargs)
return sql
class ContainsCriterion(Criterion):
def __init__(self, term: Any, container: Term, alias: Optional[str] = None) -> None:
"""
A wrapper for a "IN" criterion. This wraps two parts, a term and a container. The term is the part of the
expression that is checked for membership in the container. The container can either be a list or a subquery.
:param term:
The term to assert membership for within the container.
:param container:
A list or subquery.
"""
super().__init__(alias)
self.term = term
self.container = container
self._is_negated = False
def nodes_(self) -> Iterator[NodeT]:
yield self
yield from self.term.nodes_()
yield from self.container.nodes_()
@property
def is_aggregate(self) -> Optional[bool]:
return self.term.is_aggregate
@builder
def replace_table(self, current_table: Optional["Table"], new_table: Optional["Table"]) -> "ContainsCriterion":
"""
Replaces all occurrences of the specified table with the new table. Useful when reusing fields across queries.
:param current_table:
The table to be replaced.
:param new_table:
The table to replace with.
:return:
A copy of the criterion with the tables replaced.
"""
self.term = self.term.replace_table(current_table, new_table)
def get_sql(self, subquery: Any = None, **kwargs: Any) -> str:
sql = "{term} {not_}IN {container}".format(
term=self.term.get_sql(**kwargs),
container=self.container.get_sql(subquery=True, **kwargs),
not_="NOT " if self._is_negated else "",
)
return format_alias_sql(sql, self.alias, **kwargs)
@builder
def negate(self) -> "ContainsCriterion":
self._is_negated = True
class RangeCriterion(Criterion):
def __init__(self, term: Term, start: Any, end: Any, alias: Optional[str] = None) -> str:
super().__init__(alias)
self.term = term
self.start = start
self.end = end
def nodes_(self) -> Iterator[NodeT]:
yield self
yield from self.term.nodes_()
yield from self.start.nodes_()
yield from self.end.nodes_()
@property
def is_aggregate(self) -> Optional[bool]:
return self.term.is_aggregate
class BetweenCriterion(RangeCriterion):
@builder
def replace_table(self, current_table: Optional["Table"], new_table: Optional["Table"]) -> "BetweenCriterion":
"""
Replaces all occurrences of the specified table with the new table. Useful when reusing fields across queries.
:param current_table:
The table to be replaced.
:param new_table:
The table to replace with.
:return:
A copy of the criterion with the tables replaced.
"""
self.term = self.term.replace_table(current_table, new_table)
def get_sql(self, **kwargs: Any) -> str:
# FIXME escape
sql = "{term} BETWEEN {start} AND {end}".format(
term=self.term.get_sql(**kwargs),
start=self.start.get_sql(**kwargs),
end=self.end.get_sql(**kwargs),
)
return format_alias_sql(sql, self.alias, **kwargs)
class PeriodCriterion(RangeCriterion):
def get_sql(self, **kwargs: Any) -> str:
sql = "{term} FROM {start} TO {end}".format(
term=self.term.get_sql(**kwargs),
start=self.start.get_sql(**kwargs),
end=self.end.get_sql(**kwargs),
)
return format_alias_sql(sql, self.alias, **kwargs)
class BitwiseAndCriterion(Criterion):
def __init__(self, term: Term, value: Any, alias: Optional[str] = None) -> None:
super().__init__(alias)
self.term = term
self.value = value
def nodes_(self) -> Iterator[NodeT]:
yield self
yield from self.term.nodes_()
yield from self.value.nodes_()
@builder
def replace_table(self, current_table: Optional["Table"], new_table: Optional["Table"]) -> "BitwiseAndCriterion":
"""
Replaces all occurrences of the specified table with the new table. Useful when reusing fields across queries.
:param current_table:
The table to be replaced.
:param new_table:
The table to replace with.
:return:
A copy of the criterion with the tables replaced.
"""
self.term = self.term.replace_table(current_table, new_table)
def get_sql(self, **kwargs: Any) -> str:
sql = "({term} & {value})".format(
term=self.term.get_sql(**kwargs),
value=self.value,
)
return format_alias_sql(sql, self.alias, **kwargs)
class NullCriterion(Criterion):
def __init__(self, term: Term, alias: Optional[str] = None) -> None:
super().__init__(alias)
self.term = term
def nodes_(self) -> Iterator[NodeT]:
yield self
yield from self.term.nodes_()
@builder
def replace_table(self, current_table: Optional["Table"], new_table: Optional["Table"]) -> "NullCriterion":
"""
Replaces all occurrences of the specified table with the new table. Useful when reusing fields across queries.
:param current_table:
The table to be replaced.
:param new_table:
The table to replace with.
:return:
A copy of the criterion with the tables replaced.
"""
self.term = self.term.replace_table(current_table, new_table)
def get_sql(self, with_alias: bool = False, **kwargs: Any) -> str:
sql = "{term} IS NULL".format(
term=self.term.get_sql(**kwargs),
)
return format_alias_sql(sql, self.alias, **kwargs)
class ComplexCriterion(BasicCriterion):
def get_sql(self, subcriterion: bool = False, **kwargs: Any) -> str:
sql = "{left} {comparator} {right}".format(
comparator=self.comparator.value,
left=self.left.get_sql(subcriterion=self.needs_brackets(self.left), **kwargs),
right=self.right.get_sql(subcriterion=self.needs_brackets(self.right), **kwargs),
)
if subcriterion:
return "({criterion})".format(criterion=sql)
return sql
def needs_brackets(self, term: Term) -> bool:
return isinstance(term, ComplexCriterion) and not term.comparator == self.comparator
class ArithmeticExpression(Term):
"""
Wrapper for an arithmetic function. Can be simple with two terms or complex with nested terms. Order of operations
are also preserved.
"""
add_order = [Arithmetic.add, Arithmetic.sub]
def __init__(self, operator: Arithmetic, left: Any, right: Any, alias: Optional[str] = None) -> None:
"""
Wrapper for an arithmetic expression.
:param operator:
Type: Arithmetic
An operator for the expression such as {quote}+{quote} or {quote}/{quote}
:param left:
The term on the left side of the expression.
:param right:
The term on the right side of the expression.
:param alias:
(Optional) an alias for the term which can be used inside a select statement.
:return:
"""
super().__init__(alias)
self.operator = operator
self.left = left
self.right = right
def nodes_(self) -> Iterator[NodeT]:
yield self
yield from self.left.nodes_()
yield from self.right.nodes_()
@property
def is_aggregate(self) -> Optional[bool]:
# True if both left and right terms are True or None. None if both terms are None. Otherwise, False
return resolve_is_aggregate([self.left.is_aggregate, self.right.is_aggregate])
@builder
def replace_table(self, current_table: Optional["Table"], new_table: Optional["Table"]) -> "ArithmeticExpression":
"""
Replaces all occurrences of the specified table with the new table. Useful when reusing fields across queries.
:param current_table:
The table to be replaced.
:param new_table:
The table to replace with.
:return:
A copy of the term with the tables replaced.
"""
self.left = self.left.replace_table(current_table, new_table)
self.right = self.right.replace_table(current_table, new_table)
def left_needs_parens(self, curr_op, left_op) -> bool:
"""
Returns true if the expression on the left of the current operator needs to be enclosed in parentheses.
:param current_op:
The current operator.
:param left_op:
The highest level operator of the left expression.
"""
if left_op is None: