-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathdecoder.py
More file actions
2464 lines (2236 loc) · 104 KB
/
decoder.py
File metadata and controls
2464 lines (2236 loc) · 104 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
#
# Copyright (c) 2012-2025 Snowflake Computing Inc. All rights reserved.
#
import logging
import re
from typing import Any, Optional, Iterable, List, Union, Dict, Tuple, Callable, Literal
from datetime import date, datetime, time, timedelta, timezone
from decimal import Decimal
from pandas import DataFrame as PandasDataFrame
from snowflake.snowpark.window import WindowSpec, Window, WindowRelativePosition
import snowflake.snowpark._internal.proto.generated.ast_pb2 as proto
from google.protobuf.json_format import MessageToDict
from snowflake.snowpark.relational_grouped_dataframe import GroupingSets
from snowflake.snowpark import Session, Column, DataFrameAnalyticsFunctions, Row
import snowflake.snowpark.functions
from snowflake.snowpark.functions import (
udaf,
udf,
udtf,
when,
sproc,
call_table_function,
)
from snowflake.snowpark.types import (
DataType,
ArrayType,
BinaryType,
BooleanType,
ByteType,
ColumnIdentifier,
DateType,
DoubleType,
FloatType,
GeographyType,
GeometryType,
IntegerType,
LongType,
NullType,
ShortType,
StringType,
StructField,
StructType,
TimeType,
VariantType,
VectorType,
DecimalType,
MapType,
PandasDataFrameType,
PandasSeriesType,
TimestampTimeZone,
TimestampType,
)
logger = logging.getLogger(__name__)
class Decoder:
def __init__(self, session: Optional[Session]):
# Map from var_id to (symbol_name, value). symbol_name is the identifier used in the program to store value.
self.symbol_table: Dict[int, Tuple[str, object]] = dict()
try:
self.session = session if session is not None else Session.builder.create()
except Exception as e:
self.session = None
logger.warning("Error creating a Snowpark session for the decoder: %s", e)
def capture_local_variable_name(self, assign_expr: proto.Assign) -> str:
"""
Capture the local variable name from an assign expression.
Parameters
----------
assign_expr : proto.Assign
The assign expression to capture the local variable name from.
Returns
-------
str
The local variable name.
"""
return assign_expr.symbol.value
def get_dataframe_analytics_function_column_formatter(
self, sp_dataframe_analytics_expr: proto.Expr
) -> Callable:
"""
Create a dataframe analytics function column formatter.
This is mainly to pass the df_analytics_functions.test.
Parameters
----------
sp_dataframe_analytics_expr : proto.Expr
The dataframe analytics expression.
Returns
-------
Callable
The dataframe analytics function column formatter.
"""
if "formattedColNames" in MessageToDict(sp_dataframe_analytics_expr):
formatted_col_names = list(sp_dataframe_analytics_expr.formatted_col_names)
w_lambda_pattern = re.compile(r"^(\w+)_W_(\w+)$")
xy_lambda_pattern = re.compile(r"^(\w+)_X_(\w+)_Y_(\w+)$")
if all(re.match(xy_lambda_pattern, col) for col in formatted_col_names):
return (
lambda input, agg, window_size: f"{input}_X_{agg}_Y_{window_size}"
)
elif all(re.match(w_lambda_pattern, col) for col in formatted_col_names):
return lambda input, agg: f"{input}_W_{agg}"
else:
return lambda input_col, agg, window: f"{agg}_{input_col}_{window}"
else:
return DataFrameAnalyticsFunctions._default_col_formatter
def decode_callable_expr(
self,
callable_expr: proto.SpCallable,
callable_type: Optional[Literal["udaf", "udtf"]] = None,
) -> Tuple[Callable, str]:
"""
Decode a callable expression to get the callable.
Parameters
----------
callable_expr : proto.SpCallable
The callable expression to decode.
callable_type : Optional[Literal["udaf", "udtf"]]
The type of callable.
If None, it will be treated as a regular function; an empty function will be created and renamed based on
the recorded function's name.
Returns
-------
Tuple[Callable, str]
The decoded callable and its associated name.
"""
id = callable_expr.id
name = callable_expr.name
object_name = (
self.decode_name_expr(callable_expr.object_name)
if callable_expr.HasField("object_name")
else None
)
if callable_type == "udtf":
handler = self.session._udtf_registration.get_udtf(object_name).handler
elif callable_type == "udaf":
handler = self.session._udaf_registration.get_udaf(object_name).handler
else:
def __temp_handler_func():
pass
# Set the name of the function to whatever it was originally.
__temp_handler_func.__name__ = name
handler, object_name = __temp_handler_func, name
return handler, object_name
def decode_col_exprs(self, expr: proto.Expr) -> List[Column]:
"""
Decode a protobuf object to a list of column expressions.
Parameters
----------
expr : proto.Expr
The protobuf object to decode.
Returns
-------
List[Column]
The decoded columns.
"""
if len(expr) == 1:
# Prevent nesting the list in a list if there is only one expression.
# This usually happens when the expression is a list_val.
col_list = self.decode_expr(expr[0])
if not isinstance(col_list, list):
col_list = [col_list]
else:
col_list = [self.decode_expr(arg) for arg in expr]
return col_list
def decode_dsl_map_expr(self, map_expr: Iterable) -> dict:
"""
Given a map expression, return the result as a Python dictionary.
Under the hood, protoc converts the key-value pairs into a list of Tuple_X_Y.
Parameters
----------
map_expr : Iterable[proto.Tuple_X_Y]
The map expression to decode.
Returns
-------
dict
The decoded Python dictionary.
"""
python_map = dict()
for pair in map_expr:
key = (
self.decode_expr(pair._1)
if isinstance(pair._1, proto.Expr)
else pair._1
)
value = (
self.decode_expr(pair._2)
if isinstance(pair._2, proto.Expr)
else pair._2
)
python_map[key] = value
return python_map
def convert_name_to_list(self, name: any) -> List:
if isinstance(name, str):
return [name]
return [qualified_name for qualified_name in name]
def decode_name_expr(self, table_name: proto.SpName) -> Union[str, List]:
"""
Decode a table name expression to get the table name.
Parameters
----------
table_name : proto.SpTableName
The table name to decode.
Returns
-------
str
The decoded table name.
"""
if table_name.name.HasField("sp_name_flat"):
return table_name.name.sp_name_flat.name
elif table_name.name.HasField("sp_name_structured"):
return [name for name in table_name.name.sp_name_structured.name]
else:
raise ValueError("Table name not found in proto.SpName")
def decode_fn_ref_expr(self, fn_ref_expr: proto.FnRefExpr) -> str:
"""
Decode a function reference expression to get the function name.
Parameters
----------
expr : proto.FnRefExpr
The expression to decode.
Returns
-------
str
The decoded function name.
"""
match fn_ref_expr.WhichOneof("variant"):
# case "trait_fn_id_ref_expr":
# pass
# case "trait_fn_name_ref_expr":
# pass
case "builtin_fn":
return self.decode_name_expr(fn_ref_expr.builtin_fn.name)
case "call_table_function_expr":
return self.decode_name_expr(fn_ref_expr.call_table_function_expr.name)
case "indirect_table_fn_id_ref":
return self.symbol_table[
fn_ref_expr.indirect_table_fn_id_ref.id.bitfield1
][0]
case "indirect_table_fn_name_ref":
return self.decode_name_expr(
fn_ref_expr.indirect_table_fn_name_ref.name
)
case "sp_fn_ref":
return self.symbol_table[fn_ref_expr.sp_fn_ref.id.bitfield1][0]
case "stored_procedure":
return self.decode_name_expr(fn_ref_expr.stored_procedure.name)
# case "udaf":
# pass
# case "udf":
# pass
# case "udtf":
# pass
case _:
raise ValueError(
"Unknown function reference type: %s"
% fn_ref_expr.WhichOneof("variant")
)
def decode_dataframe_data_expr(
self, df_data_expr: proto.SpDataframeData
) -> Union[List, PandasDataFrame]:
"""
Decode a dataframe data expression to get the underlying data.
Parameters
----------
df_data_expr : proto.SpDataframeData
The expr to decode.
Returns
-------
List or pandas.DataFrame
The decoded data.
"""
match df_data_expr.WhichOneof("sealed_value"):
case "sp_dataframe_data__list":
# vs can be a list of Expr, a single Expr, or [].
if hasattr(df_data_expr.sp_dataframe_data__list, "vs"):
if isinstance(df_data_expr.sp_dataframe_data__list.vs, Iterable):
return [
self.decode_expr(v)
for v in df_data_expr.sp_dataframe_data__list.vs
]
else:
return [
self.decode_expr(df_data_expr.sp_dataframe_data__list.vs)
]
else:
return []
case "sp_dataframe_data__pandas":
# We don't know what pandas DataFrame was passed in, return an empty one.
return PandasDataFrame()
# case "sp_dataframe_data__tuple":
# pass
case _:
raise ValueError(
"Unknown dataframe data type: %s"
% df_data_expr.WhichOneof("sealed_value")
)
def decode_dataframe_schema_expr(
self, df_schema_expr: proto.SpDataframeSchema
) -> Union[List, None, StructType]:
"""
Decode a dataframe schema expression to get the schema.
Parameters
----------
df_schema_expr : proto.SpDataframeSchema
The expr to decode.
Returns
-------
List
The decoded schema.
"""
match df_schema_expr.WhichOneof("sealed_value"):
case "sp_dataframe_schema__list":
# vs can be a list of Expr, a single Expr, or None.
if hasattr(df_schema_expr.sp_dataframe_schema__list, "vs"):
if isinstance(
df_schema_expr.sp_dataframe_schema__list.vs, Iterable
):
return [v for v in df_schema_expr.sp_dataframe_schema__list.vs]
else:
return [df_schema_expr.sp_dataframe_schema__list.vs]
else:
return None
case "sp_dataframe_schema__struct":
return self.decode_struct_type_expr(
df_schema_expr.sp_dataframe_schema__struct.v
)
case _:
raise ValueError(
"Unknown dataframe schema type: %s"
% df_schema_expr.WhichOneof("sealed_value")
)
def decode_data_type_expr(
self, data_type_expr: proto.SpDataType
) -> Union[DataType, StructField, ColumnIdentifier]:
"""
Decode a data type expression to get the data type.
Parameters
----------
data_type_expr : proto.SpDataType
The expression to decode.
Returns
-------
DataType, StructField, or ColumnIdentifier
The decoded data type.
"""
match data_type_expr.WhichOneof("variant"):
case "sp_array_type":
structured = data_type_expr.sp_array_type.structured
element_type = self.decode_data_type_expr(
data_type_expr.sp_array_type.ty
)
return ArrayType(element_type, structured)
case "sp_binary_type":
return BinaryType()
case "sp_boolean_type":
return BooleanType()
case "sp_byte_type":
return ByteType()
case "sp_column_identifier":
name = data_type_expr.sp_column_identifier.name
return ColumnIdentifier(name)
case "sp_date_type":
return DateType()
case "sp_decimal_type":
precision = data_type_expr.sp_decimal_type.precision
scale = data_type_expr.sp_decimal_type.scale
return DecimalType(precision, scale)
case "sp_double_type":
return DoubleType()
case "sp_float_type":
return FloatType()
case "sp_geography_type":
return GeographyType()
case "sp_geometry_type":
return GeometryType()
case "sp_integer_type":
return IntegerType()
case "sp_long_type":
return LongType()
case "sp_map_type":
key_type = self.decode_data_type_expr(data_type_expr.sp_map_type.key_ty)
value_type = self.decode_data_type_expr(
data_type_expr.sp_map_type.value_ty
)
structured = data_type_expr.sp_map_type.structured
return MapType(key_type, value_type, structured)
case "sp_null_type":
return NullType()
case "sp_pandas_data_frame_type":
# Both col_types and col_names can be a list of Expr or a single Expr.
if isinstance(
data_type_expr.sp_pandas_data_frame_type.col_types, Iterable
):
col_types = []
for col_type in data_type_expr.sp_pandas_data_frame_type.col_types:
col_types.append(self.decode_data_type_expr(col_type))
else:
col_types = [data_type_expr.sp_pandas_data_frame_type.col_types]
if isinstance(
data_type_expr.sp_pandas_data_frame_type.col_names, Iterable
):
col_names = [
col_name
for col_name in data_type_expr.sp_pandas_data_frame_type.col_names
]
else:
col_names = [data_type_expr.sp_pandas_data_frame_type.col_names]
return PandasDataFrameType(col_types, col_names)
case "sp_pandas_series_type":
# element_type is an optional field.
element_type = (
self.decode_data_type_expr(
data_type_expr.sp_pandas_series_type.el_ty
)
if data_type_expr.sp_pandas_series_type.HasField("el_ty")
else None
)
return PandasSeriesType(element_type)
case "sp_short_type":
return ShortType()
case "sp_string_type":
length = (
data_type_expr.sp_string_type.length
if data_type_expr.sp_string_type.HasField("length")
and isinstance(data_type_expr.sp_string_type.length, int)
else None
)
return StringType(length)
case "sp_struct_field":
column_identifier = self.decode_data_type_expr(
data_type_expr.sp_struct_field.column_identifier
)
data_type = self.decode_data_type_expr(
data_type_expr.sp_struct_field.data_type
)
nullable = data_type_expr.sp_struct_field.nullable
return StructField(column_identifier, data_type, nullable)
case "sp_struct_type":
# The fields can be a list of Expr, a single Expr, or None.
fields = []
if hasattr(data_type_expr.sp_struct_type, "fields"):
for field in data_type_expr.sp_struct_type.fields.list:
column_identifier = field.column_identifier.name
data_type = self.decode_data_type_expr(field.data_type)
fields.append(StructField(column_identifier, data_type))
else:
fields = None
structured = data_type_expr.sp_struct_type.structured
return StructType(fields, structured)
case "sp_time_type":
return TimeType()
case "sp_timestamp_type":
match data_type_expr.sp_timestamp_type.time_zone.WhichOneof("variant"):
case "sp_timestamp_time_zone_default":
tz = TimestampTimeZone.DEFAULT
case "sp_timestamp_time_zone_ltz":
tz = TimestampTimeZone.LTZ
case "sp_timestamp_time_zone_ntz":
tz = TimestampTimeZone.NTZ
case "sp_timestamp_time_zone_tz":
tz = TimestampTimeZone.TZ
case _:
raise ValueError(
"Unknown timezone: %s"
% data_type_expr.sp_timestamp_type.time_zone.WhichOneof(
"variant"
)
)
return TimestampType(tz)
case "sp_variant_type":
return VariantType()
case "sp_vector_type":
dimension = data_type_expr.sp_vector_type.dimension
# element_type is encoded as a SpDataType but the input to VectorType is supposed to be a Python type.
element_type = self.decode_data_type_expr(
data_type_expr.sp_vector_type.ty
)
if isinstance(element_type, IntegerType):
element_type = int
elif isinstance(element_type, FloatType):
element_type = float
else:
raise ValueError(
"VectorType does not support element type: %s" % element_type
)
return VectorType(element_type, dimension)
case _:
raise ValueError(
"Unknown data type: %s" % data_type_expr.WhichOneof("variant")
)
def decode_join_type(self, join_type: proto.SpJoinType) -> str:
"""
Decode a join type expression to get the join type.
Parameters
----------
join_type : proto.SpJoinType
The expression to decode.
Returns
-------
str
The decoded join type.
"""
match join_type.WhichOneof("variant"):
case "sp_join_type__asof":
return "asof"
case "sp_join_type__cross":
return "cross"
case "sp_join_type__full_outer":
return "full"
case "sp_join_type__inner":
return "inner"
case "sp_join_type__left_anti":
return "anti"
case "sp_join_type__left_outer":
return "left"
case "sp_join_type__left_semi":
return "semi"
case "sp_join_type__right_outer":
return "right"
case _:
raise ValueError(
"Unknown join type: %s" % join_type.WhichOneof("variant")
)
def decode_pivot_value_expr(self, pivot_value_expr: proto.SpPivotValue) -> Any:
"""
Decode expr to get the pivot value.
Parameters
----------
pivot_value_expr : proto.SpPivotValues
The expression to decode.
Returns
-------
Any
The decoded pivot value.
"""
match pivot_value_expr.WhichOneof("sealed_value"):
case "sp_pivot_value__dataframe":
return self.decode_expr(pivot_value_expr.sp_pivot_value__dataframe.v)
case "sp_pivot_value__expr":
return self.decode_expr(pivot_value_expr.sp_pivot_value__expr.v)
case _:
raise ValueError(
"Unknown pivot value: %s"
% pivot_value_expr.WhichOneof("sealed_value")
)
def decode_struct_type_expr(
self, sp_struct_type_expr: proto.SpStructType
) -> StructType:
"""
Decode a struct type expression to get the struct type.
Parameters
----------
struct_type_expr : proto.SpStructType
The expression to decode.
Returns
-------
StructType
The decoded object.
"""
struct_field_list = []
for field in sp_struct_type_expr.fields.list:
column_identifier = field.column_identifier.name
datatype = self.decode_data_type_expr(field.data_type)
nullable = field.nullable
struct_field_list.append(StructField(column_identifier, datatype, nullable))
structured = sp_struct_type_expr.structured
return StructType(struct_field_list, structured)
def decode_timezone_expr(self, tz_expr: proto.PythonTimeZone) -> Any:
"""
Decode a Python timezone expression to get the timezone.
Parameters
----------
tz_expr : proto.PythonTimeZone
The expression to decode.
"""
tz_name = tz_expr.name.value
offset_seconds = tz_expr.offset_seconds
return timezone(offset=timedelta(seconds=offset_seconds), name=tz_name)
def decode_udtf_schema(
self, udtf_schema: proto.UdtfSchema
) -> Union[List, DataType]:
"""
Decode a UDTF schema expression to get the schema.
Parameters
----------
udtf_schema : proto.UdtfSchema
The expression to decode.
Returns
-------
List or DataType
The decoded schema.
"""
match udtf_schema.WhichOneof("sealed_value"):
case "udtf_schema__names":
return [s for s in udtf_schema.udtf_schema__names.schema]
case "udtf_schema__type":
return self.decode_data_type_expr(
udtf_schema.udtf_schema__type.return_type
)
case _:
raise ValueError(
"Unknown UDTF schema type: %s"
% udtf_schema.WhichOneof("sealed_value")
)
def decode_window_spec_expr(self, window_spec_expr: proto.SpWindowSpecExpr) -> Any:
"""
Decode a window specification expression.
Parameters
----------
window_spec_expr : proto.SpWindowSpecExpr
The expression to decode.
Returns
-------
Any
The decoded window specification.
"""
match window_spec_expr.WhichOneof("variant"):
case "sp_window_spec_empty":
return Window._spec()
case "sp_window_spec_order_by":
window_spec = self.decode_window_spec_expr(
window_spec_expr.sp_window_spec_order_by.wnd
)
cols = self.decode_col_exprs(
window_spec_expr.sp_window_spec_order_by.cols
)
return window_spec.order_by(*cols)
case "sp_window_spec_partition_by":
window_spec = self.decode_window_spec_expr(
window_spec_expr.sp_window_spec_partition_by.wnd
)
cols = self.decode_col_exprs(
window_spec_expr.sp_window_spec_partition_by.cols
)
return window_spec.partition_by(*cols)
case "sp_window_spec_range_between":
start = self.decode_window_relative_position(
window_spec_expr.sp_window_spec_range_between.start
)
end = self.decode_window_relative_position(
window_spec_expr.sp_window_spec_range_between.end
)
window_spec = self.decode_window_spec_expr(
window_spec_expr.sp_window_spec_range_between.wnd
)
return window_spec.range_between(start, end)
case "sp_window_spec_rows_between":
start = self.decode_window_relative_position(
window_spec_expr.sp_window_spec_rows_between.start
)
end = self.decode_window_relative_position(
window_spec_expr.sp_window_spec_rows_between.end
)
window_spec = self.decode_window_spec_expr(
window_spec_expr.sp_window_spec_rows_between.wnd
)
return window_spec.rows_between(start, end)
case None:
# This is for the case col.over() where the window spec is None.
return None
case _:
raise ValueError(
"Unknown window specification type: %s"
% window_spec_expr.WhichOneof("variant")
)
def decode_window_relative_position(
self, wnd_relative_position: proto.SpWindowRelativePosition
):
"""
Helper function for AST decoding to fill relative positions for window spec range-between, and rows-between.
If the value passed in for start/end is of type WindowRelativePosition encoding will preserve the syntax.
(For example, Window.CURRENT_ROW)
Parameters
----------
wnd_relative_position : proto.SpWindowRelativePosition
The expression to decode.
"""
match wnd_relative_position.WhichOneof("variant"):
case "sp_window_relative_position__current_row":
return WindowRelativePosition.CURRENT_ROW
case "sp_window_relative_position__position":
return self.decode_expr(
wnd_relative_position.sp_window_relative_position__position.n
)
case "sp_window_relative_position__unbounded_following":
return WindowRelativePosition.UNBOUNDED_FOLLOWING
case "sp_window_relative_position__unbounded_preceding":
return WindowRelativePosition.UNBOUNDED_PRECEDING
case _:
raise ValueError(
"Unknown window relative position type: %s"
% wnd_relative_position.WhichOneof("variant")
)
def binop(self, ast, fn):
return fn(self.decode_expr(ast.lhs), self.decode_expr(ast.rhs))
def bitop(self, ast, fn):
lhs = self.decode_expr(ast.lhs)
rhs = self.decode_expr(ast.rhs)
return getattr(lhs, fn)(rhs)
def get_statement_params(self, d: Dict):
statement_params = {}
statement_params_list = d.get("statementParams", [])
for statement_params_list_map in statement_params_list:
statement_params[
statement_params_list_map["1"]
] = statement_params_list_map["2"]
return statement_params
def decode_expr(self, expr: proto.Expr, **kwargs) -> Any:
match expr.WhichOneof("variant"):
# COLUMN BINARY OPERATIONS
case "add":
lhs = self.decode_expr(expr.add.lhs)
rhs = self.decode_expr(expr.add.rhs)
return lhs + rhs
case "apply_expr":
fn_name = self.decode_fn_ref_expr(expr.apply_expr.fn)
if isinstance(fn_name, str):
if hasattr(snowflake.snowpark.functions, fn_name):
fn = getattr(snowflake.snowpark.functions, fn_name)
elif expr.apply_expr.fn.sp_fn_ref.id.bitfield1 in self.symbol_table:
fn = self.symbol_table[
expr.apply_expr.fn.sp_fn_ref.id.bitfield1
][1]
else:
fn = None
else:
# If fn_name is not a string, it is a collection of table functions. Convert it to a list.
fn_name = [name for name in fn_name]
fn = None
# The named arguments are stored as a list of Tuple_String_Expr.
named_args = self.decode_dsl_map_expr(expr.apply_expr.named_args)
# The positional args can be a list of Expr, a single Expr, or [].
if hasattr(expr.apply_expr, "pos_args"):
if isinstance(expr.apply_expr.pos_args, Iterable):
pos_args = [
self.decode_expr(pos_arg)
for pos_arg in expr.apply_expr.pos_args
]
else:
pos_args = [self.decode_expr(expr.apply_expr.pos_args)]
else:
pos_args = []
if fn is None:
# Stored procedures, table functions, (and in the future I expect UDTFs maybe) will pass through
# here directly (not through their respective entities) when invoked. Call the right method.
# If a source is provided via kwargs, short-circuit with that.
source = kwargs.get("source", None)
match expr.apply_expr.fn.WhichOneof("variant"):
case "sp_fn_ref":
return self.session.call(fn_name, *pos_args, **named_args)
case "indirect_table_fn_id_ref":
return self.session.table_function(
self.symbol_table[
expr.apply_expr.fn.indirect_table_fn_id_ref.id.bitfield1
][1]
)
case "call_table_function_expr" | "indirect_table_fn_name_ref":
if source == "sp_session_table_function":
return self.session.table_function(
fn_name, *pos_args, **named_args
)
else:
return call_table_function(
fn_name, *pos_args, **named_args
)
case _:
raise ValueError(
"Unknown function reference type: %s"
% expr.apply_expr.fn.WhichOneof("variant")
)
result = fn(*pos_args, **named_args)
if hasattr(expr, "var_id"):
self.symbol_table[expr.var_id.bitfield1] = (
self.capture_local_variable_name(expr),
result,
)
return result
# PYTHON VALUE LITERALS
case "big_decimal_val":
# For values like nan, snan, inf, etc. "special" is a combination of a sign and a character representing
# the special value.
if hasattr(expr.big_decimal_val, "special"):
match expr.big_decimal_val.special.value:
case "+F":
return Decimal("Infinity")
case "-F":
return Decimal("-Infinity")
case "+n":
return Decimal("nan")
case "-n":
return Decimal("-nan")
case "+N":
return Decimal("snan")
case "-N":
return Decimal("-snan")
case "":
# If special is empty, it means that the value is a normal big decimal.
pass
case _:
raise ValueError(
"Big decimal special value not recognized: %s"
% expr.big_decimal_val.special.value
)
unscaled_value = int.from_bytes(
expr.big_decimal_val.unscaled_value, byteorder="big", signed=True
)
scale = expr.big_decimal_val.scale
return Decimal(unscaled_value) / Decimal(10**-scale)
case "binary_val":
return expr.binary_val.v
case "bool_val":
return expr.bool_val.v
case "float64_val":
return expr.float64_val.v
case "int64_val":
return expr.int64_val.v
case "list_val":
# vs can be a list of Expr, a single Expr, or [].
if hasattr(expr.list_val, "vs"):
if isinstance(expr.list_val.vs, Iterable):
return [self.decode_expr(v) for v in expr.list_val.vs]
else:
return [self.decode_expr(expr.list_val.vs)]
else:
return []
case "none_val":
return None
case "null_val":
return None
case "python_date_val":
return date(
year=expr.python_date_val.year,
month=expr.python_date_val.month,
day=expr.python_date_val.day,
)
case "python_time_val":
return time(
hour=expr.python_time_val.hour,
minute=expr.python_time_val.minute,
second=expr.python_time_val.second,
microsecond=expr.python_time_val.microsecond,
tzinfo=self.decode_timezone_expr(expr.python_time_val.tz),
)
case "python_timestamp_val":
return datetime(
year=expr.python_timestamp_val.year,
month=expr.python_timestamp_val.month,
day=expr.python_timestamp_val.day,
hour=expr.python_timestamp_val.hour,
minute=expr.python_timestamp_val.minute,
second=expr.python_timestamp_val.second,
microsecond=expr.python_timestamp_val.microsecond,
tzinfo=self.decode_timezone_expr(expr.python_timestamp_val.tz),
)
case "seq_map_val":
return {
self.decode_expr(kv.vs[0]): self.decode_expr(kv.vs[1])
for kv in expr.seq_map_val.kvs
}
case "sp_datatype_val":
return self.decode_data_type_expr(expr.sp_datatype_val.datatype)
case "tuple_val":
# vs can be a list of Expr, a single Expr, or ().
if hasattr(expr.tuple_val, "vs"):
if isinstance(expr.tuple_val.vs, Iterable):
return tuple(self.decode_expr(v) for v in expr.tuple_val.vs)
else:
return tuple(self.decode_expr(expr.tuple_val.vs))
else:
return tuple()
case "string_val":
return expr.string_val.v
# COLUMN FUNCTIONS
case "sp_column_alias":
col = self.decode_expr(expr.sp_column_alias.col)
alias = expr.sp_column_alias.name
# Column.as if True; Column.alias if False, Column.name if None.
match expr.sp_column_alias.fn.WhichOneof("variant"):
case "sp_column_alias_fn_alias":
return col.alias(alias)
case "sp_column_alias_fn_as":
return col.as_(alias)
case _:
return col.name(alias)
case "sp_column_apply__int":
col = self.decode_expr(expr.sp_column_apply__int.col)
field = expr.sp_column_apply__int.idx
return col[field]
case "sp_column_apply__string":
col = self.decode_expr(expr.sp_column_apply__string.col)
field = expr.sp_column_apply__string.field
return col[field]
case "sp_column_asc":
col = self.decode_expr(expr.sp_column_asc.col)
match expr.sp_column_asc.null_order.WhichOneof("variant"):
case "sp_null_order_default":
return col.asc()
case "sp_null_order_nulls_first":
return col.asc_nulls_first()
case "sp_null_order_nulls_last":
return col.asc_nulls_last()
case _:
raise ValueError(
"Unknown null order for sp_column_asc: %s"
% expr.sp_column_asc.null_order.WhichOneof("variant")
)
case "sp_column_between":
col = self.decode_expr(expr.sp_column_between.col)
lower = self.decode_expr(expr.sp_column_between.lower_bound)
upper = self.decode_expr(expr.sp_column_between.upper_bound)