-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy path_plan.py
More file actions
2772 lines (2536 loc) · 113 KB
/
_plan.py
File metadata and controls
2772 lines (2536 loc) · 113 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 importlib
import inspect
import json
import math
import re
import statistics
import typing
import uuid
from collections import defaultdict
from collections.abc import Iterable
from enum import Enum
from functools import cached_property, partial, reduce
from typing import TYPE_CHECKING, Any, Dict, List, NoReturn, Optional, Union
from unittest.mock import MagicMock
from snowflake.snowpark._internal.analyzer.select_statement import SelectTableFunction
from snowflake.snowpark._internal.analyzer.table_function import TableFunctionJoin
from snowflake.snowpark._internal.analyzer.table_merge_expression import (
DeleteMergeExpression,
InsertMergeExpression,
TableDelete,
TableMerge,
TableUpdate,
UpdateMergeExpression,
)
from snowflake.snowpark._internal.analyzer.window_expression import (
FirstValue,
Lag,
LastValue,
Lead,
RangeFrame,
RowFrame,
SpecifiedWindowFrame,
UnboundedFollowing,
UnboundedPreceding,
WindowExpression,
)
from snowflake.snowpark.mock._udf_utils import coerce_variant_input, remove_null_wrapper
from snowflake.snowpark.mock._util import ImportContext, get_fully_qualified_name
from snowflake.snowpark.mock._window_utils import (
EntireWindowIndexer,
RowFrameIndexer,
is_rank_related_window_function,
)
from snowflake.snowpark.mock.exceptions import SnowparkLocalTestingException
if TYPE_CHECKING:
from snowflake.snowpark.mock._analyzer import MockAnalyzer
from snowflake.snowpark._internal.analyzer.analyzer_utils import (
EXCEPT,
INTERSECT,
UNION,
UNION_ALL,
quote_name,
)
from snowflake.snowpark._internal.analyzer.binary_expression import (
Add,
And,
BinaryExpression,
BitwiseAnd,
BitwiseOr,
BitwiseXor,
Divide,
EqualNullSafe,
EqualTo,
GreaterThan,
GreaterThanOrEqual,
LessThan,
LessThanOrEqual,
Multiply,
NotEqualTo,
Or,
Pow,
Remainder,
Subtract,
)
from snowflake.snowpark._internal.analyzer.binary_plan_node import Join
from snowflake.snowpark._internal.analyzer.expression import (
Attribute,
CaseWhen,
ColumnSum,
Expression,
FunctionExpression,
InExpression,
Interval,
Like,
ListAgg,
Literal,
MultipleExpression,
RegExp,
ScalarSubquery,
SnowflakeUDF,
Star,
SubfieldInt,
SubfieldString,
UnresolvedAttribute,
WithinGroup,
)
from snowflake.snowpark._internal.analyzer.query_plan_analysis_utils import PlanState
from snowflake.snowpark._internal.analyzer.snowflake_plan import (
PlanQueryType,
Query,
SnowflakePlan,
)
from snowflake.snowpark._internal.analyzer.snowflake_plan_node import (
LogicalPlan,
Range,
SaveMode,
SnowflakeCreateTable,
SnowflakeTable,
SnowflakeValues,
)
from snowflake.snowpark._internal.analyzer.sort_expression import (
Ascending,
NullsFirst,
SortOrder,
)
from snowflake.snowpark._internal.analyzer.unary_expression import (
Alias,
Cast,
IsNaN,
IsNotNull,
IsNull,
Not,
UnaryMinus,
UnresolvedAlias,
)
from snowflake.snowpark._internal.analyzer.unary_plan_node import (
Aggregate,
CreateViewCommand,
Pivot,
Sample,
Project,
)
from snowflake.snowpark._internal.type_utils import infer_type
from snowflake.snowpark._internal.utils import (
generate_random_alphanumeric,
parse_table_name,
)
from snowflake.snowpark.column import Column
from snowflake.snowpark.mock._functions import MockedFunctionRegistry, cast_column_to
from snowflake.snowpark.mock._options import pandas as pd
from snowflake.snowpark.mock._select_statement import (
MockSelectable,
MockSelectableEntity,
MockSelectExecutionPlan,
MockSelectStatement,
MockSetStatement,
)
from snowflake.snowpark.mock._snowflake_data_type import (
ColumnEmulator,
ColumnType,
TableEmulator,
get_coerce_result_type,
)
from snowflake.snowpark.mock._util import (
convert_wildcard_to_regex,
custom_comparator,
fix_drift_between_column_sf_type_and_dtype,
)
from snowflake.snowpark.row import Row
from snowflake.snowpark.types import (
BooleanType,
ByteType,
DecimalType,
DoubleType,
FloatType,
IntegerType,
LongType,
NullType,
ShortType,
StringType,
VariantType,
_NumericType,
)
class MockExecutionPlan(LogicalPlan):
def __init__(
self,
source_plan: LogicalPlan,
session,
*,
child: Optional["MockExecutionPlan"] = None,
expr_to_alias: Optional[Dict[uuid.UUID, str]] = None,
df_aliased_col_name_to_real_col_name: Optional[Dict[str, str]] = None,
) -> NoReturn:
super().__init__()
self.source_plan = source_plan
self.session = session
self.schema_query = None
mock_query = MagicMock()
mock_query.sql = "SELECT MOCK_TEST_FAKE_QUERY()"
self.queries = [mock_query]
self.child = child
self.expr_to_alias = expr_to_alias if expr_to_alias is not None else {}
self.df_aliased_col_name_to_real_col_name = (
df_aliased_col_name_to_real_col_name or defaultdict(dict)
)
self.api_calls = []
self._attributes = None
@property
def attributes(self) -> List[Attribute]:
return describe(self)
@cached_property
def output(self) -> List[Attribute]:
return [Attribute(a.name, a.datatype, a.nullable) for a in self.attributes]
@cached_property
def plan_state(self) -> Dict[PlanState, Any]:
# dummy return
return {
PlanState.PLAN_HEIGHT: -1,
PlanState.NUM_SELECTS_WITH_COMPLEXITY_MERGED: -1,
PlanState.NUM_CTE_NODES: -1,
PlanState.DUPLICATED_NODE_COMPLEXITY_DISTRIBUTION: [],
}
@property
def post_actions(self):
return []
@property
def execution_queries(self) -> Dict[PlanQueryType, List[Query]]:
return {
PlanQueryType.QUERIES: self.queries,
PlanQueryType.POST_ACTIONS: self.post_actions,
}
def add_aliases(self, to_add: Dict) -> None:
self.expr_to_alias.update(to_add)
class MockFileOperation(MockExecutionPlan):
class Operator(str, Enum):
PUT = "put"
GET = "get"
READ_FILE = "read_file"
# others are not supported yet
def __init__(
self,
session,
operator: Union[str, Operator],
*,
options: Dict[str, str],
local_file_name: Optional[str] = None,
stage_location: Optional[str] = None,
child: Optional["MockExecutionPlan"] = None,
source_plan: Optional[LogicalPlan] = None,
format: Optional[str] = None,
schema: Optional[List[Attribute]] = None,
) -> None:
super().__init__(session=session, child=child, source_plan=source_plan)
self.operator = operator
self.local_file_name = local_file_name
self.stage_location = stage_location
self.api_calls = self.api_calls or []
self.format = format
self.schema = schema
self.options = options
def coerce_order_by_arguments(order_by: List[Expression]):
return [
order if isinstance(order, SortOrder) else SortOrder(order, Ascending())
for order in order_by
]
def handle_order_by_clause(
order_by: List[SortOrder],
result_df: TableEmulator,
analyzer: "MockAnalyzer",
expr_to_alias: Optional[Dict[str, str]],
keep_added_columns: bool = False,
) -> TableEmulator:
"""Given an input dataframe `result_df` and a list of SortOrder expressions `order_by`, return the sorted dataframe."""
sort_columns_array = []
sort_orders_array = []
null_first_last_array = []
added_columns = []
for exp in order_by:
exp_name = analyzer.analyze(exp.child, expr_to_alias)
if exp_name not in result_df.columns:
result_df[exp_name] = calculate_expression(
exp.child, result_df, analyzer, expr_to_alias
)
added_columns.append(exp_name)
sort_columns_array.append(exp_name)
sort_orders_array.append(isinstance(exp.direction, Ascending))
null_first_last_array.append(
isinstance(exp.null_ordering, NullsFirst) or exp.null_ordering == NullsFirst
)
for column, ascending, null_first in reversed(
list(zip(sort_columns_array, sort_orders_array, null_first_last_array))
):
comparator = partial(custom_comparator, ascending, null_first)
result_df = result_df.sort_values(by=column, key=comparator)
result_df.sorted_by = sort_columns_array
if not keep_added_columns:
result_df = result_df.drop(columns=added_columns)
return result_df
def handle_range_frame_indexing(
order_spec: List[SortOrder],
res_index: "pd.Index",
res: "pd.api.typing.DataFrameGroupBy",
analyzer: "MockAnalyzer",
expr_to_alias: Dict[str, str],
unbounded_preceding: bool,
unbounded_following: bool,
) -> "pd.api.typing.RollingGroupby":
"""Return a list of range between window frames based on the dataframe paritions `res` and the ORDER BY clause `order_spec`."""
if order_spec:
windows = []
for current_row, win in zip(res_index, res.rolling(EntireWindowIndexer())):
_win = handle_order_by_clause(order_spec, win, analyzer, expr_to_alias)
row_idx = list(_win.index).index(current_row)
start_idx = 0 if unbounded_preceding else row_idx
end_idx = len(_win) - 1 if unbounded_following else row_idx
def search_boundary_idx(idx, delta, _win):
while 0 <= idx + delta < len(_win):
cur_expr = list(
calculate_expression(
exp.child, _win.iloc[idx], analyzer, expr_to_alias
)
for exp in order_spec
)
next_expr = list(
calculate_expression(
exp.child, _win.iloc[idx + delta], analyzer, expr_to_alias
)
for exp in order_spec
)
if not cur_expr == next_expr:
break
idx += delta
return idx
start_idx = search_boundary_idx(start_idx, -1, _win)
end_idx = search_boundary_idx(end_idx, 1, _win)
windows.append(_win[start_idx : end_idx + 1])
else: # If order by is not specified, just use the entire window
windows = res.rolling(EntireWindowIndexer())
return windows
def handle_function_expression(
exp: FunctionExpression,
input_data: Union[TableEmulator, ColumnEmulator],
analyzer: "MockAnalyzer",
expr_to_alias: Dict[str, str],
current_row=None,
):
func = MockedFunctionRegistry.get_or_create().get_function(exp)
connection_lock = analyzer.session._conn.get_lock()
if func is None:
with connection_lock:
current_schema = analyzer.session.get_current_schema()
current_database = analyzer.session.get_current_database()
udf_name = get_fully_qualified_name(exp.name, current_schema, current_database)
# If udf name in the registry then this is a udf, not an actual function
with connection_lock:
if udf_name in analyzer.session.udf._registry:
exp.udf_name = udf_name
return handle_udf_expression(
exp, input_data, analyzer, expr_to_alias, current_row
)
if exp.api_call_source == "functions.call_udf":
raise SnowparkLocalTestingException(
f"Unknown function {exp.name}. UDF by that name does not exist."
)
analyzer.session._conn.log_not_supported_error(
external_feature_name=exp.name,
error_message=f"Function {exp.name} is not implemented. You can implement and make a patch by "
f"using the `snowflake.snowpark.mock.patch` decorator.",
raise_error=NotImplementedError,
)
try:
original_func = getattr(
importlib.import_module("snowflake.snowpark.functions"), func.name
)
except AttributeError:
original_func = None
# raise error depending on whether users has a provided a patch for function not available in snowpark-python
analyzer.session._conn.log_not_supported_error(
external_feature_name=func.name,
error_message=f"Function {func.name} is not supported in snowpark-python.",
raise_error=NotImplementedError if func is None else None,
)
to_mock_func = original_func or func.impl
# Use the non-decorated function.
if "__wrapped__" in to_mock_func.__dict__:
to_mock_func = to_mock_func.__wrapped__
signatures = inspect.signature(to_mock_func)
spec = inspect.getfullargspec(to_mock_func)
to_pass_args = []
type_hints = typing.get_type_hints(to_mock_func)
parameters_except_ast = list(signatures.parameters)
if "_emit_ast" in parameters_except_ast:
parameters_except_ast.remove("_emit_ast")
del type_hints["_emit_ast"]
for idx, key in enumerate(parameters_except_ast):
type_hint = str(type_hints[key])
keep_literal = "Column" not in type_hint
if key == spec.varargs:
# SNOW-1441602: Move Star logic to calculate_expression once it can handle table returns
args = []
for c in exp.children[idx:]:
if isinstance(c, Star):
args.extend(
[
calculate_expression(
cc,
input_data,
analyzer,
expr_to_alias,
keep_literal=keep_literal,
)
for cc in c.expressions
]
)
else:
args.append(
calculate_expression(
c,
input_data,
analyzer,
expr_to_alias,
keep_literal=keep_literal,
)
)
to_pass_args.extend(args)
else:
try:
to_pass_args.append(
calculate_expression(
exp.children[idx],
input_data,
analyzer,
expr_to_alias,
keep_literal=keep_literal,
)
)
except IndexError:
to_pass_args.append(None)
try:
result = func(*to_pass_args, row_number=current_row, input_data=input_data)
except Exception as err:
extra_err_info = (
(
f"\nA patch is provided for '{func.name}' which is not supported in Snowpark Python."
f" Please ensure the implementation follows specifications outlined at:"
f" https://docs.snowflake.com/en/sql-reference/functions-all and refer to"
f" https://github.com/snowflakedb/snowpark-python/blob/main/src/snowflake/snowpark/mock/_functions.py"
f" for patterns on creating a compatible patch function for input and output types."
)
if not original_func and func
else ""
)
SnowparkLocalTestingException.raise_from_error(
err,
error_message=f"Error executing mocked function '{func.name}'."
f" See error traceback for detailed information.{extra_err_info}",
)
return result
def handle_udf_expression(
exp: FunctionExpression,
input_data: Union[TableEmulator, ColumnEmulator],
analyzer: "MockAnalyzer",
expr_to_alias: Dict[str, str],
current_row=None,
):
udf_registry = analyzer.session.udf
udf_name = exp.udf_name
connection_lock = analyzer.session._conn.get_lock()
with connection_lock:
udf = udf_registry.get_udf(udf_name)
udf_imports = udf_registry.get_udf_imports(udf_name)
with ImportContext(udf_imports):
# Resolve handler callable
if type(udf.func) is tuple:
module_name, handler_name = udf.func
exec(f"from {module_name} import {handler_name}")
udf_handler = eval(handler_name)
else:
udf_handler = udf.func
# Compute input data and validate typing
if len(exp.children) != len(udf._input_types):
raise SnowparkLocalTestingException(
f"Expected {len(udf._input_types)} arguments, but received {len(exp.children)}"
)
function_input = TableEmulator(index=input_data.index)
for child, expected_type in zip(exp.children, udf._input_types):
col_name = analyzer.analyze(child, expr_to_alias)
column_data = calculate_expression(
child, input_data, analyzer, expr_to_alias
)
# Variant Data is often cast to specific python types when passed to a udf.
if isinstance(expected_type, VariantType):
column_data = column_data.apply(coerce_variant_input)
coerce_result = get_coerce_result_type(
column_data.sf_type, ColumnType(expected_type, False)
)
if coerce_result is None:
raise SnowparkLocalTestingException(
f"UDF received input type {column_data.sf_type.datatype} for column {child.name}, but expected input type of {expected_type}"
)
function_input[col_name] = cast_column_to(
column_data, ColumnType(expected_type, False)
)
try:
# we do not use pd.apply here because pd.apply will auto infer dtype for the output column
# this will lead to NaN or None information loss, think about the following case of a udf definition:
# def udf(x): return numpy.sqrt(x) if x is not None else None
# calling udf(-1) and udf(None), pd.apply will infer the column dtype to be int which returns NaT for both
# however, we want NaT for the former case and None for the latter case.
# using dtype object + function execution does not have the limitation
# In the future maybe we could call fix_drift_between_column_sf_type_and_dtype in methods like set_sf_type.
# The code would look like:
# res=input.apply(...)
# res.set_sf_type(ColumnType(exp.datatype, exp.nullable)) # fixes the drift and removes NaT
data = []
for _, row in function_input.iterrows():
if udf.strict and any([v is None for v in row]):
result = None
else:
result = remove_null_wrapper(udf_handler(*row))
data.append(result)
res = ColumnEmulator(
data=data,
sf_type=ColumnType(exp.datatype, exp.nullable),
name=quote_name(
f"{exp.udf_name}({', '.join(input_data.columns)})".upper()
),
dtype=object,
)
except Exception as err:
SnowparkLocalTestingException.raise_from_error(
err, error_message=f"Python Interpreter Error: {err}"
)
return res
def handle_udaf_expression(
exp: FunctionExpression,
input_data: Union[TableEmulator, ColumnEmulator],
analyzer: "MockAnalyzer",
expr_to_alias: Dict[str, str],
current_row=None,
):
udaf_registry = analyzer.session.udaf
udaf_name = exp.udf_name
udaf = udaf_registry.get_udaf(udaf_name)
with ImportContext(udaf_registry.get_udaf_imports(udaf_name)):
# Resolve handler callable
if type(udaf.handler) is tuple:
module_name, handler_name = udaf.func
exec(f"from {module_name} import {handler_name}")
udaf_class = eval(handler_name)
else:
udaf_class = udaf.handler
# Compute input data and validate typing
if len(exp.children) != len(udaf._input_types):
raise SnowparkLocalTestingException(
f"Expected {len(udaf._input_types)} arguments, but received {len(exp.children)}"
)
function_input = TableEmulator(index=input_data.index)
for child, expected_type in zip(exp.children, udaf._input_types):
col_name = analyzer.analyze(child, expr_to_alias)
column_data = calculate_expression(
child, input_data, analyzer, expr_to_alias
)
# Variant Data is often cast to specific python types when passed to a udf.
if isinstance(expected_type, VariantType):
column_data = column_data.apply(coerce_variant_input)
coerce_result = get_coerce_result_type(
column_data.sf_type, ColumnType(expected_type, False)
)
if coerce_result is None:
raise SnowparkLocalTestingException(
f"UDAF received input type {column_data.sf_type.datatype} for column {child.name}, but expected input type of {expected_type}"
)
function_input[col_name] = cast_column_to(
column_data, ColumnType(expected_type, False)
)
try:
# Initialize Aggregation handler class, i.e. the aggregation accumulator.
AggregationAccumulator = udaf_class()
# Init its state.
some_agg_state = AggregationAccumulator.aggregate_state
for _, row in function_input.iterrows():
# Call Agg.accumulate
if udaf.strict and any([v is None for v in row]):
AggregationAccumulator.accumulate(None)
else:
AggregationAccumulator.accumulate(*row)
# Call merge with empty state
AggregationAccumulator.merge(some_agg_state)
result = AggregationAccumulator.finish()
# Single row result for aggregation.
res = ColumnEmulator(
data=[result],
sf_type=ColumnType(exp.datatype, exp.nullable),
name=quote_name(
f"{exp.udf_name}({', '.join(input_data.columns)})".upper()
),
dtype=object,
)
except Exception as err:
SnowparkLocalTestingException.raise_from_error(
err, error_message=f"Python Interpreter Error: {err}"
)
return res
def handle_udtf_expression(
exp: FunctionExpression,
input_data: Union[TableEmulator, ColumnEmulator],
analyzer: "MockAnalyzer",
expr_to_alias: Dict[str, str],
current_row=None,
join_with_input_columns=True,
):
# TODO: handle and support imports + other udtf attributes.
udtf_registry = analyzer.session.udtf
udtf_name = exp.func_name
udtf = udtf_registry.get_udtf(udtf_name)
# calls __init__ in UDTF handler.
handler = udtf.handler()
# Vectorized or non-vectorized UDTF?
if hasattr(handler, "end_partition") and hasattr(
handler.end_partition, "_sf_vectorized_input"
):
# vectorized
df = input_data.copy()
df.columns = [c.strip('"') for c in df.columns]
data = handler.end_partition(df)
if join_with_input_columns:
# Join input data with output data together.
# For now carried out as horizontal concat. Need to address join case separately.
# suffix df accordingly, todo proper check.
data = pd.concat(
(df.rename(columns={c: c + "_R" for c in df.columns}), data), axis=1
)
return data
else:
res = TableEmulator(
data=[],
)
output_columns = udtf._output_schema.names
sf_types = {
f.name: ColumnType(datatype=f.datatype, nullable=f.nullable)
for f in udtf._output_schema.fields
}
sf_types_by_col_index = {
idx: ColumnType(datatype=f.datatype, nullable=f.nullable)
for idx, f in enumerate(udtf._output_schema.fields)
}
# Aliases? Use them then instead of output columns.
# TODO SNOW-1826001: Clarify whether there will be ever a case when only some columns are aliased.
if exp.aliases:
output_columns = exp.aliases
if join_with_input_columns:
output_columns = list(input_data.columns) + output_columns
assert len(output_columns) == len(input_data.columns) + len(
udtf._output_schema.names
), "non-unique identifiers found, can't carry out table function join."
sf_types.update(input_data.sf_types)
sf_types_by_col_index.update(input_data.sf_types_by_col_index)
# Process each row
if hasattr(handler, "process"):
data = []
# Special case: No data, but args provided. This implies that `process` of the UDTF handler may
# be a generator called with literals.
if len(input_data) == 0 and exp.args:
assert all(
isinstance(arg, Literal) for arg in exp.args
), "Arguments must be literals when no data is provided."
args = tuple(arg.value for arg in exp.args)
if udtf.strict:
data = [None]
else:
result = remove_null_wrapper(handler.process(*args))
for result_row in result:
data.append(tuple(result_row))
else:
# input_data provided, TODO: args/kwargs.
for _, row in input_data.iterrows():
if udtf.strict and any([v is None for v in row]):
result = None
else:
result = remove_null_wrapper(handler.process(*row))
for result_row in result:
if join_with_input_columns:
data.append(tuple(row.values) + tuple(result_row))
else:
data.append(tuple(result_row))
res = TableEmulator(
data=data,
columns=output_columns,
sf_types=sf_types,
sf_types_by_col_index=sf_types_by_col_index,
)
res.columns = [c.strip('"') for c in res.columns]
# Finish partition
if hasattr(handler, "end_partition"):
handler.end_partition()
return res
def handle_sproc_expression(
exp: FunctionExpression,
input_data: Union[TableEmulator, ColumnEmulator],
analyzer: "MockAnalyzer",
expr_to_alias: Dict[str, str],
current_row=None,
):
sproc_registry = analyzer.session.sproc
sproc_name = exp.sproc_name
sproc = sproc_registry.get_sproc(sproc_name)
with ImportContext(sproc_registry.get_sproc_imports(sproc_name)):
# Resolve handler callable
if type(sproc.func) is tuple:
module_name, handler_name = sproc.func
exec(f"from {module_name} import {handler_name}")
sproc_handler = eval(handler_name)
else:
sproc_handler = sproc.func
# Compute input data and validate typing
if len(exp.children) != len(sproc._input_types):
raise SnowparkLocalTestingException(
f"Expected {len(sproc._input_types)} arguments, but received {len(exp.children)}"
)
function_input = TableEmulator(index=input_data.index)
for child, expected_type in zip(exp.children, sproc._input_types):
col_name = analyzer.analyze(child, expr_to_alias)
column_data = calculate_expression(
child, input_data, analyzer, expr_to_alias
)
# Variant Data is often cast to specific python types when passed to a sproc.
if isinstance(expected_type, VariantType):
column_data = column_data.apply(coerce_variant_input)
coerce_result = get_coerce_result_type(
column_data.sf_type, ColumnType(expected_type, False)
)
if coerce_result is None:
raise SnowparkLocalTestingException(
f"Stored procedure received input type {column_data.sf_type.datatype} for column {child.name}, but expected input type of {expected_type}"
)
function_input[col_name] = cast_column_to(
column_data, ColumnType(expected_type, False)
)
try:
res = sproc_handler(*function_input.values)
if sproc._is_return_table:
# Emulate a tabular result only if a table is returned. Else, return value is a scalar.
output_columns = sproc._output_schema.names
sf_types = {
f.name: ColumnType(datatype=f.datatype, nullable=f.nullable)
for f in sproc._output_schema.fields
}
sf_types_by_col_index = {
idx: ColumnType(datatype=f.datatype, nullable=f.nullable)
for idx, f in enumerate(sproc._output_schema.fields)
}
# Aliases? Use them then instead of output columns.
# TODO SNOW-1826001: Clarify whether there will be ever a case when only some columns are aliased.
if exp.aliases:
output_columns = exp.aliases
res = TableEmulator(
data=res,
columns=output_columns,
sf_types=sf_types,
sf_types_by_col_index=sf_types_by_col_index,
)
except Exception as err:
SnowparkLocalTestingException.raise_from_error(
err, error_message=f"Python Interpreter Error: {err}"
)
return res
def execute_mock_plan(
plan: MockExecutionPlan,
expr_to_alias: Optional[Dict[str, str]] = None,
) -> Union[TableEmulator, List[Row]]:
import numpy as np
if expr_to_alias is None:
expr_to_alias = plan.expr_to_alias
if isinstance(plan, (MockExecutionPlan, SnowflakePlan)):
source_plan = plan.source_plan
analyzer = plan.session._analyzer
else:
source_plan = plan
analyzer = plan.analyzer
entity_registry = analyzer.session._conn.entity_registry
connection_lock = analyzer.session._conn.get_lock()
if isinstance(source_plan, SnowflakeValues):
table = TableEmulator(
source_plan.data,
columns=[x.name for x in source_plan.output],
sf_types={
x.name: ColumnType(x.datatype, x.nullable) for x in source_plan.output
},
dtype=object,
)
for column_name in table.columns:
sf_type = table.sf_types[column_name]
table[column_name].sf_type = table.sf_types[column_name]
if not isinstance(sf_type.datatype, _NumericType):
table[column_name] = table[column_name].replace(np.nan, None)
return table
if isinstance(source_plan, MockSelectExecutionPlan):
return execute_mock_plan(source_plan.execution_plan, expr_to_alias)
if isinstance(source_plan, MockSelectStatement):
projection: Optional[List[Expression]] = source_plan.projection or []
from_: Optional[MockSelectable] = source_plan.from_
where: Optional[Expression] = source_plan.where
order_by: Optional[List[Expression]] = source_plan.order_by
limit_: Optional[int] = source_plan.limit_
offset: Optional[int] = source_plan.offset
from_df = execute_mock_plan(from_, expr_to_alias)
if from_df is None:
return TableEmulator()
columns = []
data = []
sf_types = []
null_rows_idxs_map = {}
for exp in projection:
if isinstance(exp, Star):
data += [d for _, d in from_df.items()]
columns += list(from_df.columns)
sf_types += list(
from_df.sf_types_by_col_index.values()
if from_df.sf_types_by_col_index
else from_df.sf_types.values()
)
null_rows_idxs_map.update(from_df._null_rows_idxs_map)
elif (
isinstance(exp, UnresolvedAlias)
and exp.child
and isinstance(exp.child, Star)
):
for e in exp.child.expressions:
column_name = analyzer.analyze(e, expr_to_alias)
columns.append(column_name)
column_series = calculate_expression(
e, from_df, analyzer, expr_to_alias
)
data.append(column_series)
sf_types.append(column_series.sf_type)
null_rows_idxs_map[column_name] = column_series._null_rows_idxs
else:
if isinstance(exp, Alias):
column_name = expr_to_alias.get(exp.expr_id, exp.name)
else:
column_name = analyzer.analyze(
exp, expr_to_alias, parse_local_name=True
)
column_series = calculate_expression(
exp, from_df, analyzer, expr_to_alias
)
columns.append(column_name)
data.append(column_series)
sf_types.append(column_series.sf_type)
null_rows_idxs_map[column_name] = column_series._null_rows_idxs
if isinstance(exp, (Alias)):
if isinstance(exp.child, Attribute):
quoted_name = quote_name(exp.name)
expr_to_alias[exp.child.expr_id] = quoted_name
for k, v in expr_to_alias.items():
if v == exp.child.name:
expr_to_alias[k] = quoted_name
df = pd.concat(data, axis=1)
result_df = TableEmulator(
data=df,
sf_types={k: v for k, v in zip(columns, sf_types)},
sf_types_by_col_index={i: v for i, v in enumerate(sf_types)},
)
result_df.columns = columns
result_df._null_rows_idxs_map = null_rows_idxs_map
if where:
condition = calculate_expression(where, result_df, analyzer, expr_to_alias)
result_df = result_df[condition.fillna(value=False)]
if order_by:
result_df = handle_order_by_clause(
order_by, result_df, analyzer, expr_to_alias
)
if limit_ is not None:
if offset is not None:
result_df = result_df.iloc[offset:]
result_df = result_df.head(n=limit_)
return result_df
if isinstance(source_plan, MockSetStatement):
first_operand = source_plan.set_operands[0]
res_df = execute_mock_plan(
MockExecutionPlan(
first_operand.selectable,
source_plan._session,
),
expr_to_alias,
)
for i in range(1, len(source_plan.set_operands)):
operand = source_plan.set_operands[i]
operator = operand.operator
cur_df = execute_mock_plan(
MockExecutionPlan(operand.selectable, source_plan._session),
expr_to_alias,
)
if len(res_df.columns) != len(cur_df.columns):