This repository was archived by the owner on Apr 1, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathbase.py
More file actions
1689 lines (1343 loc) · 55.1 KB
/
base.py
File metadata and controls
1689 lines (1343 loc) · 55.1 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
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
# Contains code from https://github.com/ibis-project/ibis/blob/9.2.0/ibis/backends/sql/compilers/base.py
from __future__ import annotations
import abc
import calendar
from functools import partial, reduce
import itertools
import math
import operator
import string
from typing import Any, ClassVar, TYPE_CHECKING
from bigframes_vendored.ibis.backends.sql.rewrites import (
add_one_to_nth_value_input,
add_order_by_to_empty_ranking_window_functions,
empty_in_values_right_side,
FirstValue,
LastValue,
lower_bucket,
lower_capitalize,
lower_sample,
one_to_zero_index,
sqlize,
)
import bigframes_vendored.ibis.common.exceptions as ibis_exceptions
import bigframes_vendored.ibis.common.patterns as pats
from bigframes_vendored.ibis.config import options
import bigframes_vendored.ibis.expr.datatypes as dt
import bigframes_vendored.ibis.expr.operations as ops
from bigframes_vendored.ibis.expr.operations.udf import InputType
from bigframes_vendored.ibis.expr.rewrites import lower_stringslice
import bigframes_vendored.sqlglot as sg
import bigframes_vendored.sqlglot.expressions as sge
from public import public
try:
from bigframes_vendored.sqlglot.expressions import Alter
except ImportError:
from bigframes_vendored.sqlglot.expressions import AlterTable
else:
def AlterTable(*args, kind="TABLE", **kwargs):
return Alter(*args, kind=kind, **kwargs)
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Mapping
from bigframes_vendored.ibis.backends.bigquery.datatypes import SqlglotType
import bigframes_vendored.ibis.expr.schema as sch
import bigframes_vendored.ibis.expr.types as ir
def get_leaf_classes(op):
for child_class in op.__subclasses__():
if not child_class.__subclasses__():
yield child_class
else:
yield from get_leaf_classes(child_class)
ALL_OPERATIONS = frozenset(get_leaf_classes(ops.Node))
class AggGen:
"""A descriptor for compiling aggregate functions.
Common cases can be handled by setting configuration flags,
special cases should override the `aggregate` method directly.
Parameters
----------
supports_filter
Whether the backend supports a FILTER clause in the aggregate.
Defaults to False.
supports_order_by
Whether the backend supports an ORDER BY clause in (relevant)
aggregates. Defaults to False.
"""
class _Accessor:
"""An internal type to handle getattr/getitem access."""
__slots__ = ("handler", "compiler")
def __init__(self, handler: Callable, compiler: SQLGlotCompiler):
self.handler = handler
self.compiler = compiler
def __getattr__(self, name: str) -> Callable:
return partial(self.handler, self.compiler, name)
__getitem__ = __getattr__
__slots__ = ("supports_filter", "supports_order_by")
def __init__(
self, *, supports_filter: bool = False, supports_order_by: bool = False
):
self.supports_filter = supports_filter
self.supports_order_by = supports_order_by
def __get__(self, instance, owner=None):
if instance is None:
return self
return AggGen._Accessor(self.aggregate, instance)
def aggregate(
self,
compiler: SQLGlotCompiler,
name: str,
*args: Any,
where: Any = None,
order_by: tuple = (),
):
"""Compile the specified aggregate.
Parameters
----------
compiler
The backend's compiler.
name
The aggregate name (e.g. `"sum"`).
args
Any arguments to pass to the aggregate.
where
An optional column filter to apply before performing the aggregate.
order_by
Optional ordering keys to use to order the rows before performing
the aggregate.
"""
func = compiler.f[name]
if order_by and not self.supports_order_by:
raise ibis_exceptions.UnsupportedOperationError(
"ordering of order-sensitive aggregations via `order_by` is "
f"not supported for the {compiler.dialect} backend"
)
if where is not None and not self.supports_filter:
args = tuple(compiler.if_(where, arg, NULL) for arg in args)
if order_by and self.supports_order_by:
*rest, last = args
out = func(*rest, sge.Order(this=last, expressions=order_by))
else:
out = func(*args)
if where is not None and self.supports_filter:
out = sge.Filter(this=out, expression=sge.Where(this=where))
return out
class VarGen:
__slots__ = ()
def __getattr__(self, name: str) -> sge.Var:
return sge.Var(this=name)
def __getitem__(self, key: str) -> sge.Var:
return sge.Var(this=key)
class AnonymousFuncGen:
__slots__ = ()
def __getattr__(self, name: str) -> Callable[..., sge.Anonymous]:
return lambda *args: sge.Anonymous(
this=name, expressions=list(map(sge.convert, args))
)
def __getitem__(self, key: str) -> Callable[..., sge.Anonymous]:
return getattr(self, key)
class FuncGen:
__slots__ = ("namespace", "anon", "copy")
def __init__(self, namespace: str | None = None, copy: bool = False) -> None:
self.namespace = namespace
self.anon = AnonymousFuncGen()
self.copy = copy
def __getattr__(self, name: str) -> Callable[..., sge.Func]:
name = ".".join(filter(None, (self.namespace, name)))
return lambda *args, **kwargs: sg.func(
name, *map(sge.convert, args), **kwargs, copy=self.copy
)
def __getitem__(self, key: str) -> Callable[..., sge.Func]:
return getattr(self, key)
def array(self, *args: Any) -> sge.Array:
if not args:
return sge.Array(expressions=[])
first, *rest = args
if isinstance(first, sge.Select):
assert (
not rest
), "only one argument allowed when `first` is a select statement"
return sge.Array(expressions=list(map(sge.convert, (first, *rest))))
def tuple(self, *args: Any) -> sge.Anonymous:
return self.anon.tuple(*args)
def exists(self, query: sge.Expression) -> sge.Exists:
return sge.Exists(this=query)
def concat(self, *args: Any) -> sge.Concat:
return sge.Concat(expressions=list(map(sge.convert, args)))
def map(self, keys: Iterable, values: Iterable) -> sge.Map:
return sge.Map(keys=keys, values=values)
class ColGen:
__slots__ = ("table",)
def __init__(self, table: str | None = None) -> None:
self.table = table
def __getattr__(self, name: str) -> sge.Column:
return sg.column(name, table=self.table, copy=False)
def __getitem__(self, key: str) -> sge.Column:
return sg.column(key, table=self.table, copy=False)
C = ColGen()
F = FuncGen()
NULL = sge.Null()
FALSE = sge.false()
TRUE = sge.true()
STAR = sge.Star()
def parenthesize_inputs(f):
"""Decorate a translation rule to parenthesize inputs."""
def wrapper(self, op, *, left, right):
return f(
self,
op,
left=self._add_parens(op.left, left),
right=self._add_parens(op.right, right),
)
return wrapper
@public
class SQLGlotCompiler(abc.ABC):
__slots__ = "f", "v"
agg = AggGen()
"""A generator for handling aggregate functions"""
rewrites: tuple[type[pats.Replace], ...] = (
empty_in_values_right_side,
add_order_by_to_empty_ranking_window_functions,
one_to_zero_index,
add_one_to_nth_value_input,
)
"""A sequence of rewrites to apply to the expression tree before SQL-specific transforms."""
post_rewrites: tuple[type[pats.Replace], ...] = ()
"""A sequence of rewrites to apply to the expression tree after SQL-specific transforms."""
no_limit_value: sge.Null | None = None
"""The value to use to indicate no limit."""
quoted: bool = True
"""Whether to always quote identifiers."""
copy_func_args: bool = False
"""Whether to copy function arguments when generating SQL."""
supports_qualify: bool = False
"""Whether the backend supports the QUALIFY clause."""
NAN: ClassVar[sge.Expression] = sge.Cast(
this=sge.convert("NaN"), to=sge.DataType(this=sge.DataType.Type.DOUBLE)
)
"""Backend's NaN literal."""
POS_INF: ClassVar[sge.Expression] = sge.Cast(
this=sge.convert("Inf"), to=sge.DataType(this=sge.DataType.Type.DOUBLE)
)
"""Backend's positive infinity literal."""
NEG_INF: ClassVar[sge.Expression] = sge.Cast(
this=sge.convert("-Inf"), to=sge.DataType(this=sge.DataType.Type.DOUBLE)
)
"""Backend's negative infinity literal."""
EXTRA_SUPPORTED_OPS: tuple[type[ops.Node], ...] = (
ops.Project,
ops.Filter,
ops.Sort,
ops.WindowFunction,
)
"""A tuple of ops classes that are supported, but don't have explicit
`visit_*` methods (usually due to being handled by rewrite rules). Used by
`has_operation`"""
UNSUPPORTED_OPS: tuple[type[ops.Node], ...] = ()
"""Tuple of operations the backend doesn't support."""
LOWERED_OPS: dict[type[ops.Node], pats.Replace | None] = {
ops.Bucket: lower_bucket,
ops.Capitalize: lower_capitalize,
ops.Sample: lower_sample,
ops.StringSlice: lower_stringslice,
}
"""A mapping from an operation class to either a rewrite rule for rewriting that
operation to one composed of lower-level operations ("lowering"), or `None` to
remove an existing rewrite rule for that operation added in a base class"""
SIMPLE_OPS = {
ops.Abs: "abs",
ops.Acos: "acos",
ops.All: "bool_and",
ops.Any: "bool_or",
ops.ApproxCountDistinct: "approx_distinct",
ops.ArgMax: "max_by",
ops.ArgMin: "min_by",
ops.ArrayContains: "array_contains",
ops.ArrayFlatten: "flatten",
ops.ArrayLength: "array_size",
ops.ArraySort: "array_sort",
ops.ArrayStringJoin: "array_to_string",
ops.Asin: "asin",
ops.Atan2: "atan2",
ops.Atan: "atan",
ops.Cos: "cos",
ops.Cot: "cot",
ops.Count: "count",
ops.CumeDist: "cume_dist",
ops.Date: "date",
ops.DateFromYMD: "datefromparts",
ops.Degrees: "degrees",
ops.DenseRank: "dense_rank",
ops.Exp: "exp",
FirstValue: "first_value",
ops.GroupConcat: "group_concat",
ops.IfElse: "if",
ops.IsInf: "isinf",
ops.IsNan: "isnan",
ops.JSONGetItem: "json_extract",
ops.LPad: "lpad",
LastValue: "last_value",
ops.Levenshtein: "levenshtein",
ops.Ln: "ln",
ops.Log10: "log",
ops.Log2: "log2",
ops.Lowercase: "lower",
ops.Map: "map",
ops.Median: "median",
ops.MinRank: "rank",
ops.NTile: "ntile",
ops.NthValue: "nth_value",
ops.NullIf: "nullif",
ops.PercentRank: "percent_rank",
ops.Pi: "pi",
ops.Power: "pow",
ops.RPad: "rpad",
ops.Radians: "radians",
ops.RegexSearch: "regexp_like",
ops.RegexSplit: "regexp_split",
ops.Repeat: "repeat",
ops.Reverse: "reverse",
ops.RowNumber: "row_number",
ops.Sign: "sign",
ops.Sin: "sin",
ops.Sqrt: "sqrt",
ops.StartsWith: "starts_with",
ops.StrRight: "right",
ops.StringAscii: "ascii",
ops.StringContains: "contains",
ops.StringLength: "length",
ops.StringReplace: "replace",
ops.StringSplit: "split",
ops.StringToDate: "str_to_date",
ops.StringToTimestamp: "str_to_time",
ops.Tan: "tan",
ops.Translate: "translate",
ops.Unnest: "explode",
ops.Uppercase: "upper",
}
BINARY_INFIX_OPS = (
# Binary operations
ops.Add,
ops.Subtract,
ops.Multiply,
ops.Divide,
ops.Modulus,
ops.Power,
# Comparisons
ops.GreaterEqual,
ops.Greater,
ops.LessEqual,
ops.Less,
ops.Equals,
ops.NotEquals,
# Boolean comparisons
ops.And,
ops.Or,
ops.Xor,
# Bitwise business
ops.BitwiseLeftShift,
ops.BitwiseRightShift,
ops.BitwiseAnd,
ops.BitwiseOr,
ops.BitwiseXor,
# Time arithmetic
ops.DateAdd,
ops.DateSub,
ops.DateDiff,
ops.TimestampAdd,
ops.TimestampSub,
ops.TimestampDiff,
# Interval Marginalia
ops.IntervalAdd,
ops.IntervalMultiply,
ops.IntervalSubtract,
)
NEEDS_PARENS = BINARY_INFIX_OPS + (ops.IsNull, ops.NotNull)
# Constructed dynamically in `__init_subclass__` from their respective
# UPPERCASE values to handle inheritance, do not modify directly here.
extra_supported_ops: ClassVar[frozenset[type[ops.Node]]] = frozenset()
lowered_ops: ClassVar[dict[type[ops.Node], pats.Replace]] = {}
def __init__(self) -> None:
self.f = FuncGen(copy=self.__class__.copy_func_args)
self.v = VarGen()
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
def methodname(op: type) -> str:
assert isinstance(type(op), type), type(op)
return f"visit_{op.__name__}"
def make_impl(op, target_name):
assert isinstance(type(op), type), type(op)
if issubclass(op, ops.Reduction):
def impl(
self, _, *, _name: str = target_name, where, order_by=(), **kw
):
return self.agg[_name](*kw.values(), where=where, order_by=order_by)
else:
def impl(self, _, *, _name: str = target_name, **kw):
return self.f[_name](*kw.values())
return impl
for op, target_name in cls.SIMPLE_OPS.items():
setattr(cls, methodname(op), make_impl(op, target_name))
# unconditionally raise an exception for unsupported operations
#
# these *must* be defined after SIMPLE_OPS to handle compilers that
# subclass other compilers
for op in cls.UNSUPPORTED_OPS:
# change to visit_Unsupported in a follow up
# TODO: handle geoespatial ops as a separate case?
setattr(cls, methodname(op), cls.visit_Undefined)
# raise on any remaining unsupported operations
for op in ALL_OPERATIONS:
name = methodname(op)
if not hasattr(cls, name):
setattr(cls, name, cls.visit_Undefined)
# Amend `lowered_ops` and `extra_supported_ops` using their
# respective UPPERCASE classvar values.
extra_supported_ops = set(cls.extra_supported_ops)
lowered_ops = dict(cls.lowered_ops)
extra_supported_ops.update(cls.EXTRA_SUPPORTED_OPS)
for op_cls, rewrite in cls.LOWERED_OPS.items():
if rewrite is not None:
lowered_ops[op_cls] = rewrite
extra_supported_ops.add(op_cls)
else:
lowered_ops.pop(op_cls, None)
extra_supported_ops.discard(op_cls)
cls.lowered_ops = lowered_ops
cls.extra_supported_ops = frozenset(extra_supported_ops)
@property
@abc.abstractmethod
def dialect(self) -> str:
"""Backend dialect."""
@property
@abc.abstractmethod
def type_mapper(self) -> type[SqlglotType]:
"""The type mapper for the backend."""
def _compile_builtin_udf(self, udf_node: ops.ScalarUDF) -> None: # noqa: B027
"""No-op."""
def _compile_python_udf(self, udf_node: ops.ScalarUDF) -> None:
raise NotImplementedError(
f"Python UDFs are not supported in the {self.dialect} backend"
)
def _compile_pyarrow_udf(self, udf_node: ops.ScalarUDF) -> None:
raise NotImplementedError(
f"PyArrow UDFs are not supported in the {self.dialect} backend"
)
def _compile_pandas_udf(self, udf_node: ops.ScalarUDF) -> str:
raise NotImplementedError(
f"pandas UDFs are not supported in the {self.dialect} backend"
)
# Concrete API
def if_(self, condition, true, false: sge.Expression | None = None) -> sge.If:
return sge.If(
this=sge.convert(condition),
true=sge.convert(true),
false=None if false is None else sge.convert(false),
)
def cast(self, arg, to: dt.DataType, format=None) -> sge.Cast:
return sge.Cast(
this=sge.convert(arg), to=self.type_mapper.from_ibis(to), copy=False
)
def _prepare_params(self, params):
result = {}
for param, value in params.items():
node = param.op()
if isinstance(node, ops.Alias):
node = node.arg
result[node] = value
return result
def to_sqlglot(
self,
expr: ir.Expr,
*,
limit: str | None = None,
params: Mapping[ir.Expr, Any] | None = None,
):
import bigframes_vendored.ibis
table_expr = expr.as_table()
if limit == "default":
limit = bigframes_vendored.ibis.options.sql.default_limit
if limit is not None:
table_expr = table_expr.limit(limit)
if params is None:
params = {}
sql = self.translate(table_expr.op(), params=params)
assert not isinstance(sql, sge.Subquery)
if isinstance(sql, sge.Table):
sql = sg.select(STAR, copy=False).from_(sql, copy=False)
assert not isinstance(sql, sge.Subquery)
return sql
def translate(self, op, *, params: Mapping[ir.Value, Any]) -> sge.Expression:
"""Translate an ibis operation to a sqlglot expression.
Parameters
----------
op
An ibis operation
params
A mapping of expressions to concrete values
compiler
An instance of SQLGlotCompiler
translate_rel
Relation node translator
translate_val
Value node translator
Returns
-------
sqlglot.expressions.Expression
A sqlglot expression
"""
# substitute parameters immediately to avoid having to define a
# ScalarParameter translation rule
params = self._prepare_params(params)
if self.lowered_ops:
op = op.replace(reduce(operator.or_, self.lowered_ops.values()))
op, ctes = sqlize(
op,
params=params,
rewrites=self.rewrites,
fuse_selects=options.sql.fuse_selects,
)
aliases = {}
counter = itertools.count()
def fn(node, _, **kwargs):
result = self.visit_node(node, **kwargs)
# if it's not a relation then we don't need to do anything special
if node is op or not isinstance(node, ops.Relation):
return result
# alias ops.Views to their explicitly assigned name otherwise generate
alias = node.name if isinstance(node, ops.View) else f"t{next(counter)}"
aliases[node] = alias
alias = sg.to_identifier(alias, quoted=self.quoted)
if isinstance(result, sge.Subquery):
return result.as_(alias, quoted=self.quoted)
else:
try:
return result.subquery(alias, copy=False)
except AttributeError:
return result.as_(alias, quoted=self.quoted)
# apply translate rules in topological order
results = op.map(fn)
# get the root node as a sqlglot select statement
out = results[op]
if isinstance(out, sge.Table):
out = sg.select(STAR, copy=False).from_(out, copy=False)
elif isinstance(out, sge.Subquery):
out = out.this
# add cte definitions to the select statement
for cte in ctes:
alias = sg.to_identifier(aliases[cte], quoted=self.quoted)
out = out.with_(
alias, as_=results[cte].this, dialect=self.dialect, copy=False
)
return out
def visit_node(self, op: ops.Node, **kwargs):
if isinstance(op, ops.ScalarUDF):
return self.visit_ScalarUDF(op, **kwargs)
elif isinstance(op, ops.AggUDF):
return self.visit_AggUDF(op, **kwargs)
else:
method = getattr(self, f"visit_{type(op).__name__}", None)
if method is not None:
return method(op, **kwargs)
else:
raise ibis_exceptions.OperationNotDefinedError(
f"No translation rule for {type(op).__name__}"
)
def visit_Field(self, op, *, rel, name):
return sg.column(
self._gen_valid_name(name), table=rel.alias_or_name, quoted=self.quoted
)
def visit_Cast(self, op, *, arg, to):
from_ = op.arg.dtype
if from_.is_integer() and to.is_interval():
return self._make_interval(arg, to.unit)
return self.cast(arg, to)
def visit_ScalarSubquery(self, op, *, rel):
return rel.this.subquery(copy=False)
def visit_Alias(self, op, *, arg, name):
return arg
def visit_Literal(self, op, *, value, dtype):
"""Compile a literal value.
This is the default implementation for compiling literal values.
Most backends should not need to override this method unless they want
to handle NULL literals as well as every other type of non-null literal
including integers, floating point numbers, decimals, strings, etc.
The logic here is:
1. If the value is None and the type is nullable, return NULL
1. If the value is None and the type is not nullable, raise an error
1. Call `visit_NonNullLiteral` method.
1. If the previous returns `None`, call `visit_DefaultLiteral` method
else return the result of the previous step.
"""
if value is None:
if dtype.is_array():
# hack: bq arrays are like semi-nullable, but want to treat as non-nullable for simplicity
# instead, use empty array as missing value sentinel
return self.cast(self.f.array(), dtype)
if dtype.nullable:
return NULL if dtype.is_null() else self.cast(NULL, dtype)
raise ibis_exceptions.UnsupportedOperationError(
f"Unsupported NULL for non-nullable type: {dtype!r}"
)
else:
result = self.visit_NonNullLiteral(op, value=value, dtype=dtype)
if result is None:
return self.visit_DefaultLiteral(op, value=value, dtype=dtype)
return result
def visit_NonNullLiteral(self, op, *, value, dtype):
"""Compile a non-null literal differently than the default implementation.
Most backends should implement this, but only when they need to handle
some non-null literal differently than the default implementation
(`visit_DefaultLiteral`).
Return `None` from an override of this method to fall back to
`visit_DefaultLiteral`.
"""
return self.visit_DefaultLiteral(op, value=value, dtype=dtype)
def visit_DefaultLiteral(self, op, *, value, dtype):
"""Compile a literal with a non-null value.
This is the default implementation for compiling non-null literals.
Most backends should not need to override this method unless they want
to handle compiling every kind of non-null literal value.
"""
if dtype.is_integer():
return sge.convert(value)
elif dtype.is_floating():
if math.isnan(value):
return self.NAN
elif math.isinf(value):
return self.POS_INF if value > 0 else self.NEG_INF
return sge.convert(value)
elif dtype.is_decimal():
return self.cast(str(value), dtype)
elif dtype.is_interval():
return sge.Interval(
this=sge.convert(str(value)),
unit=sge.Var(this=dtype.resolution.upper()),
)
elif dtype.is_boolean():
return sge.Boolean(this=bool(value))
elif dtype.is_string():
return sge.convert(value)
elif dtype.is_inet() or dtype.is_macaddr():
return sge.convert(str(value))
elif dtype.is_timestamp() or dtype.is_time():
return self.cast(value.isoformat(), dtype)
elif dtype.is_date():
return self.f.datefromparts(value.year, value.month, value.day)
elif dtype.is_array():
# array type is ambiguous if no elements
value_type = dtype.value_type
values = self.f.array(
*(
self.visit_Literal(
ops.Literal(v, value_type), value=v, dtype=value_type
)
for v in value
)
)
return values if len(value) > 0 else self.cast(values, dtype)
elif dtype.is_map():
key_type = dtype.key_type
keys = self.f.array(
*(
self.visit_Literal(
ops.Literal(k, key_type), value=k, dtype=key_type
)
for k in value.keys()
)
)
value_type = dtype.value_type
values = self.f.array(
*(
self.visit_Literal(
ops.Literal(v, value_type), value=v, dtype=value_type
)
for v in value.values()
)
)
return self.f.map(keys, values)
elif dtype.is_struct():
items = [
self.visit_Literal(
ops.Literal(v, field_dtype), value=v, dtype=field_dtype
).as_(k, quoted=self.quoted)
for field_dtype, (k, v) in zip(dtype.types, value.items())
]
return sge.Struct.from_arg_list(items)
elif dtype.is_uuid():
return self.cast(str(value), dtype)
elif dtype.is_json():
return sge.JSON(this=sge.convert(str(value)))
elif dtype.is_geospatial():
wkt = value if isinstance(value, str) else value.wkt
return self.f.st_geogfromtext(wkt)
raise NotImplementedError(f"Unsupported type: {dtype!r}")
def visit_BitwiseNot(self, op, *, arg):
return sge.BitwiseNot(this=arg)
### Mathematical Calisthenics
def visit_E(self, op):
return self.f.exp(1)
def visit_Log(self, op, *, arg, base):
if base is None:
return self.f.ln(arg)
elif str(base) in ("2", "10"):
return self.f[f"log{base}"](arg)
else:
return self.f.ln(arg) / self.f.ln(base)
def visit_Clip(self, op, *, arg, lower, upper):
if upper is not None:
arg = self.if_(arg.is_(NULL), arg, self.f.least(upper, arg))
if lower is not None:
arg = self.if_(arg.is_(NULL), arg, self.f.greatest(lower, arg))
return arg
def visit_FloorDivide(self, op, *, left, right):
return self.cast(self.f.floor(left / right), op.dtype)
def visit_Ceil(self, op, *, arg):
return self.cast(self.f.ceil(arg), op.dtype)
def visit_Floor(self, op, *, arg):
return self.cast(self.f.floor(arg), op.dtype)
def visit_Round(self, op, *, arg, digits):
if digits is not None:
return sge.Round(this=arg, decimals=digits)
return sge.Round(this=arg)
### Random Noise
def visit_RandomScalar(self, op, **kwargs):
return self.f.rand()
def visit_RandomUUID(self, op, **kwargs):
return self.f.uuid()
### Dtype Dysmorphia
def visit_TryCast(self, op, *, arg, to):
return sge.TryCast(this=arg, to=self.type_mapper.from_ibis(to))
### Comparator Conundrums
def visit_Between(self, op, *, arg, lower_bound, upper_bound):
return sge.Between(this=arg, low=lower_bound, high=upper_bound)
def visit_Negate(self, op, *, arg):
return -sge.paren(arg, copy=False)
def visit_Not(self, op, *, arg):
if isinstance(arg, sge.Filter):
return sge.Filter(
this=sg.not_(arg.this, copy=False), expression=arg.expression
)
return sg.not_(sge.paren(arg, copy=False))
### Timey McTimeFace
def visit_Time(self, op, *, arg):
return self.cast(arg, to=dt.time)
def visit_TimestampNow(self, op):
return sge.CurrentTimestamp()
def visit_DateNow(self, op):
return sge.CurrentDate()
def visit_Strftime(self, op, *, arg, format_str):
return sge.TimeToStr(this=arg, format=format_str)
def visit_ExtractEpochSeconds(self, op, *, arg):
return self.f.epoch(self.cast(arg, dt.timestamp))
def visit_ExtractYear(self, op, *, arg):
return self.f.extract(self.v.year, arg)
def visit_ExtractMonth(self, op, *, arg):
return self.f.extract(self.v.month, arg)
def visit_ExtractDay(self, op, *, arg):
return self.f.extract(self.v.day, arg)
def visit_ExtractDayOfYear(self, op, *, arg):
return self.f.extract(self.v.dayofyear, arg)
def visit_ExtractQuarter(self, op, *, arg):
return self.f.extract(self.v.quarter, arg)
def visit_ExtractWeekOfYear(self, op, *, arg):
return self.f.extract(self.v.week, arg)
def visit_ExtractHour(self, op, *, arg):
return self.f.extract(self.v.hour, arg)
def visit_ExtractMinute(self, op, *, arg):
return self.f.extract(self.v.minute, arg)
def visit_ExtractSecond(self, op, *, arg):
return self.f.extract(self.v.second, arg)
def visit_TimestampTruncate(self, op, *, arg, unit):
unit_mapping = {
"Y": "year",
"Q": "quarter",
"M": "month",
"W": "week",
"D": "day",
"h": "hour",
"m": "minute",
"s": "second",
"ms": "ms",
"us": "us",
}
if (raw_unit := unit_mapping.get(unit.short)) is None:
raise ibis_exceptions.UnsupportedOperationError(
f"Unsupported truncate unit {unit.short!r}"
)
return self.f.date_trunc(raw_unit, arg)
def visit_DateTruncate(self, op, *, arg, unit):
return self.visit_TimestampTruncate(op, arg=arg, unit=unit)
def visit_TimeTruncate(self, op, *, arg, unit):
return self.visit_TimestampTruncate(op, arg=arg, unit=unit)
def visit_DayOfWeekIndex(self, op, *, arg):
return (self.f.dayofweek(arg) + 6) % 7
def visit_DayOfWeekName(self, op, *, arg):
# day of week number is 0-indexed
# Sunday == 0
# Saturday == 6
return sge.Case(
this=(self.f.dayofweek(arg) + 6) % 7,
ifs=list(itertools.starmap(self.if_, enumerate(calendar.day_name))),
)
def _make_interval(self, arg, unit):
return sge.Interval(this=arg, unit=self.v[unit.singular])
def visit_IntervalFromInteger(self, op, *, arg, unit):
return self._make_interval(arg, unit)
### String Instruments
def visit_Strip(self, op, *, arg):
return self.f.trim(arg, string.whitespace)
def visit_RStrip(self, op, *, arg):
return self.f.rtrim(arg, string.whitespace)
def visit_LStrip(self, op, *, arg):
return self.f.ltrim(arg, string.whitespace)
def visit_Substring(self, op, *, arg, start, length):
if isinstance(op.length, ops.Literal) and (value := op.length.value) < 0:
raise ibis_exceptions.IbisInputError(
f"Length parameter must be a non-negative value; got {value}"
)
start += 1
start = self.if_(start >= 1, start, start + self.f.length(arg))
if length is None:
return self.f.substring(arg, start)
return self.f.substring(arg, start, length)
def visit_StringFind(self, op, *, arg, substr, start, end):
if end is not None:
raise ibis_exceptions.UnsupportedOperationError(