-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathsnowflake_plan.py
More file actions
1695 lines (1573 loc) · 63.3 KB
/
snowflake_plan.py
File metadata and controls
1695 lines (1573 loc) · 63.3 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
#!/usr/bin/env python3
#
# Copyright (c) 2012-2025 Snowflake Computing Inc. All rights reserved.
#
import copy
import re
import sys
import uuid
from collections import defaultdict
from enum import Enum
from functools import cached_property
from typing import (
TYPE_CHECKING,
Any,
Callable,
DefaultDict,
Dict,
List,
Optional,
Sequence,
Tuple,
Union,
)
from snowflake.snowpark._internal.analyzer.query_plan_analysis_utils import (
PlanNodeCategory,
PlanState,
)
from snowflake.snowpark._internal.analyzer.table_function import (
GeneratorTableFunction,
TableFunctionRelation,
)
if TYPE_CHECKING:
from snowflake.snowpark._internal.analyzer.select_statement import (
Selectable,
) # pragma: no cover
import snowflake.snowpark.session
import snowflake.snowpark.dataframe
import snowflake.connector
import snowflake.snowpark
from snowflake.snowpark._internal.analyzer.analyzer_utils import (
TEMPORARY_STRING_SET,
aggregate_statement,
attribute_to_schema_string,
batch_insert_into_statement,
copy_into_location,
copy_into_table,
create_file_format_statement,
create_or_replace_dynamic_table_statement,
create_or_replace_view_statement,
create_table_as_select_statement,
create_table_statement,
delete_statement,
drop_file_format_if_exists_statement,
drop_table_if_exists_statement,
file_operation_statement,
filter_statement,
insert_into_statement,
join_statement,
join_table_function_statement,
lateral_statement,
limit_statement,
merge_statement,
pivot_statement,
project_statement,
rename_statement,
result_scan_statement,
sample_statement,
schema_cast_named,
schema_cast_seq,
schema_value_statement,
select_from_path_with_format_statement,
set_operator_statement,
sort_statement,
table_function_statement,
unpivot_statement,
update_statement,
)
from snowflake.snowpark._internal.analyzer.binary_plan_node import (
JoinType,
SetOperation,
)
from snowflake.snowpark._internal.analyzer.expression import Attribute
from snowflake.snowpark._internal.analyzer.metadata_utils import (
PlanMetadata,
cache_metadata_if_select_statement,
infer_metadata,
)
from snowflake.snowpark._internal.analyzer.schema_utils import analyze_attributes
from snowflake.snowpark._internal.analyzer.snowflake_plan_node import (
DynamicTableCreateMode,
LogicalPlan,
SaveMode,
TableCreationSource,
WithQueryBlock,
)
from snowflake.snowpark._internal.compiler.cte_utils import (
encode_node_id_with_query,
find_duplicate_subtrees,
merge_referenced_ctes,
)
from snowflake.snowpark._internal.error_message import SnowparkClientExceptionMessages
from snowflake.snowpark._internal.utils import (
INFER_SCHEMA_FORMAT_TYPES,
TempObjectType,
generate_random_alphanumeric,
get_copy_into_table_options,
is_sql_select_statement,
)
from snowflake.snowpark.row import Row
from snowflake.snowpark.types import StructType
# Python 3.8 needs to use typing.Iterable because collections.abc.Iterable is not subscriptable
# Python 3.9 can use both
# Python 3.10 needs to use collections.abc.Iterable because typing.Iterable is removed
if sys.version_info <= (3, 9):
from typing import Iterable
else:
from collections.abc import Iterable
class SnowflakePlan(LogicalPlan):
class Decorator:
__wrap_exception_regex_match = re.compile(
r"""(?s).*invalid identifier '"?([^'"]*)"?'.*"""
)
__wrap_exception_regex_sub = re.compile(r"""^"|"$""")
@staticmethod
def wrap_exception(func):
def wrap(*args, **kwargs):
try:
return func(*args, **kwargs)
except snowflake.connector.errors.ProgrammingError as e:
query = getattr(e, "query", None)
tb = sys.exc_info()[2]
assert e.msg is not None
if "unexpected 'as'" in e.msg.lower():
ne = SnowparkClientExceptionMessages.SQL_PYTHON_REPORT_UNEXPECTED_ALIAS(
query
)
raise ne.with_traceback(tb) from None
elif e.sqlstate == "42000" and "invalid identifier" in e.msg:
match = (
SnowflakePlan.Decorator.__wrap_exception_regex_match.match(
e.msg
)
)
if not match: # pragma: no cover
ne = SnowparkClientExceptionMessages.SQL_EXCEPTION_FROM_PROGRAMMING_ERROR(
e
)
raise ne.with_traceback(tb) from None
col = match.group(1)
children = [
arg for arg in args if isinstance(arg, SnowflakePlan)
]
remapped = [
SnowflakePlan.Decorator.__wrap_exception_regex_sub.sub(
"", val
)
for child in children
for val in child.expr_to_alias.values()
]
if col in remapped:
unaliased_cols = (
snowflake.snowpark.dataframe._get_unaliased(col)
)
orig_col_name = (
unaliased_cols[0] if unaliased_cols else "<colname>"
)
ne = SnowparkClientExceptionMessages.SQL_PYTHON_REPORT_INVALID_ID(
orig_col_name, query
)
raise ne.with_traceback(tb) from None
elif (
len(
[
unaliased
for item in remapped
for unaliased in snowflake.snowpark.dataframe._get_unaliased(
item
)
if unaliased == col
]
)
> 1
):
ne = SnowparkClientExceptionMessages.SQL_PYTHON_REPORT_JOIN_AMBIGUOUS(
col, col, query
)
raise ne.with_traceback(tb) from None
else:
ne = SnowparkClientExceptionMessages.SQL_EXCEPTION_FROM_PROGRAMMING_ERROR(
e
)
raise ne.with_traceback(tb) from None
else:
ne = SnowparkClientExceptionMessages.SQL_EXCEPTION_FROM_PROGRAMMING_ERROR(
e
)
raise ne.with_traceback(tb) from None
return wrap
def __init__(
self,
queries: List["Query"],
# schema_query will be None for the SnowflakePlan node build
# during the compilation stage.
schema_query: Optional[str],
post_actions: Optional[List["Query"]] = None,
expr_to_alias: Optional[Dict[uuid.UUID, str]] = None,
source_plan: Optional[LogicalPlan] = None,
is_ddl_on_temp_object: bool = False,
api_calls: Optional[List[Dict]] = None,
df_aliased_col_name_to_real_col_name: Optional[
DefaultDict[str, Dict[str, str]]
] = None,
# This field records all the WithQueryBlocks and their reference count that are
# referred by the current SnowflakePlan tree. This is needed for the final query
# generation to generate the correct sql query with CTE definition.
referenced_ctes: Optional[Dict[WithQueryBlock, int]] = None,
*,
session: "snowflake.snowpark.session.Session",
) -> None:
super().__init__()
self.queries = queries
self.schema_query = schema_query
self.post_actions = post_actions if post_actions else []
self.expr_to_alias = expr_to_alias if expr_to_alias else {}
self.session = session
self.source_plan = source_plan
self.is_ddl_on_temp_object = is_ddl_on_temp_object
# We need to copy this list since we don't want to change it for the
# previous SnowflakePlan objects
self.api_calls = api_calls.copy() if api_calls else []
self._output_dict = None
# Used for dataframe alias
if df_aliased_col_name_to_real_col_name:
self.df_aliased_col_name_to_real_col_name = (
df_aliased_col_name_to_real_col_name
)
else:
self.df_aliased_col_name_to_real_col_name = defaultdict(dict)
# In the placeholder query, subquery (child) is held by the ID of query plan
# It is used for optimization, by replacing a subquery with a CTE
# encode an id for CTE optimization. This is generated based on the main
# query, query parameters and the node type. We use this id for equality
# comparison to determine if two plans are the same.
self.encoded_node_id_with_query = encode_node_id_with_query(self)
self.referenced_ctes: Dict[WithQueryBlock, int] = (
referenced_ctes.copy() if referenced_ctes else dict()
)
self._cumulative_node_complexity: Optional[Dict[PlanNodeCategory, int]] = None
# UUID for the plan to uniquely identify the SnowflakePlan object. We also use this
# to UUID track queries that are generated from the same plan.
self._uuid = str(uuid.uuid4())
# Metadata for the plan
self._metadata: PlanMetadata = infer_metadata(
self.source_plan,
self.session._analyzer,
self.df_aliased_col_name_to_real_col_name,
)
self._plan_state: Optional[Dict[PlanState, Any]] = None
@property
def uuid(self) -> str:
return self._uuid
@property
def execution_queries(self) -> Dict["PlanQueryType", List["Query"]]:
"""
Get the list of queries that will be sent over to server evaluation. The queries
have optimizations applied of optimizations are enabled.
Returns
-------
A mapping between the PlanQueryType and the list of Queries corresponds to the type.
"""
from snowflake.snowpark._internal.compiler.plan_compiler import PlanCompiler
compiler = PlanCompiler(self)
return compiler.compile()
@property
def children_plan_nodes(self) -> List[Union["Selectable", "SnowflakePlan"]]:
"""
This property is currently only used for traversing the query plan tree
when performing CTE optimization.
"""
from snowflake.snowpark._internal.analyzer.select_statement import Selectable
if self.source_plan:
if isinstance(self.source_plan, Selectable):
return self.source_plan.children_plan_nodes
else:
return self.source_plan.children
else:
return []
def with_subqueries(self, subquery_plans: List["SnowflakePlan"]) -> "SnowflakePlan":
pre_queries = self.queries[:-1]
new_schema_query = self.schema_query
new_post_actions = [*self.post_actions]
api_calls = [*self.api_calls]
for plan in subquery_plans:
for query in plan.queries[:-1]:
if query not in pre_queries:
pre_queries.append(query)
# when self.schema_query is None, that means no schema query is propagated during
# the process, there is no need to update the schema query.
if (new_schema_query is not None) and (plan.schema_query is not None):
new_schema_query = new_schema_query.replace(
plan.queries[-1].sql, plan.schema_query
)
for action in plan.post_actions:
if action not in new_post_actions:
new_post_actions.append(action)
api_calls.extend(plan.api_calls)
return SnowflakePlan(
pre_queries + [self.queries[-1]],
new_schema_query,
post_actions=new_post_actions,
expr_to_alias=self.expr_to_alias,
session=self.session,
source_plan=self.source_plan,
api_calls=api_calls,
df_aliased_col_name_to_real_col_name=self.df_aliased_col_name_to_real_col_name,
referenced_ctes=self.referenced_ctes,
)
@property
def quoted_identifiers(self) -> List[str]:
# If self._metadata.quoted_identifiers is not None (self._metadata.attributes must be None),
# retrieve quoted identifiers from self._metadata.quoted_identifiers.
# otherwise, retrieve quoted identifiers from self.attributes
# (which may trigger a describe query).
if self._metadata.quoted_identifiers is not None:
return self._metadata.quoted_identifiers
else:
return [attr.name for attr in self.attributes]
@property
def attributes(self) -> List[Attribute]:
if self._metadata.attributes is not None:
return self._metadata.attributes
assert (
self.schema_query is not None
), "No schema query is available for the SnowflakePlan"
attributes = analyze_attributes(self.schema_query, self.session)
self._metadata = PlanMetadata(attributes=attributes, quoted_identifiers=None)
# We need to cache attributes on SelectStatement too because df._plan is not
# carried over to next SelectStatement (e.g., check the implementation of df.filter()).
cache_metadata_if_select_statement(self.source_plan, self._metadata)
# No simplifier case relies on this schema_query change to update SHOW TABLES to a nested sql friendly query.
if not self.schema_query or not self.session.sql_simplifier_enabled:
self.schema_query = schema_value_statement(attributes)
return attributes
@cached_property
def output(self) -> List[Attribute]:
return [Attribute(a.name, a.datatype, a.nullable) for a in self.attributes]
@property
def output_dict(self) -> Dict[str, Any]:
if self._output_dict is None:
self._output_dict = {
attr.name: (attr.datatype, attr.nullable) for attr in self.output
}
return self._output_dict
@property
def plan_state(self) -> Dict[PlanState, Any]:
with self.session._plan_lock:
if self._plan_state is not None:
# return the cached plan state
return self._plan_state
from snowflake.snowpark._internal.analyzer.select_statement import (
SelectStatement,
)
# calculate plan height and num_selects_with_complexity_merged
height = 0
num_selects_with_complexity_merged = 0
current_level = [self]
while len(current_level) > 0:
next_level = []
for node in current_level:
next_level.extend(node.children_plan_nodes)
if (
isinstance(node, SelectStatement)
and node._merge_projection_complexity_with_subquery
):
num_selects_with_complexity_merged += 1
height += 1
current_level = next_level
# calculate the repeated node status
(
cte_nodes,
duplicated_node_complexity_distribution,
) = find_duplicate_subtrees(self, propagate_complexity_hist=True)
self._plan_state = {
PlanState.PLAN_HEIGHT: height,
PlanState.NUM_SELECTS_WITH_COMPLEXITY_MERGED: num_selects_with_complexity_merged,
PlanState.NUM_CTE_NODES: len(cte_nodes),
PlanState.DUPLICATED_NODE_COMPLEXITY_DISTRIBUTION: duplicated_node_complexity_distribution,
}
return self._plan_state
@property
def individual_node_complexity(self) -> Dict[PlanNodeCategory, int]:
if self.source_plan:
return self.source_plan.individual_node_complexity
return {}
@property
def cumulative_node_complexity(self) -> Dict[PlanNodeCategory, int]:
with self.session._plan_lock:
if self._cumulative_node_complexity is None:
# if source plan is available, the source plan complexity
# is the snowflake plan complexity.
if self.source_plan:
self._cumulative_node_complexity = (
self.source_plan.cumulative_node_complexity
)
else:
self._cumulative_node_complexity = {}
return self._cumulative_node_complexity
@cumulative_node_complexity.setter
def cumulative_node_complexity(self, value: Dict[PlanNodeCategory, int]):
self._cumulative_node_complexity = value
def reset_cumulative_node_complexity(self) -> None:
super().reset_cumulative_node_complexity()
if self.source_plan:
self.source_plan.reset_cumulative_node_complexity()
def __copy__(self) -> "SnowflakePlan":
if self.session._cte_optimization_enabled:
return SnowflakePlan(
copy.deepcopy(self.queries) if self.queries else [],
self.schema_query,
copy.deepcopy(self.post_actions) if self.post_actions else None,
dict(self.expr_to_alias) if self.expr_to_alias else None,
self.source_plan,
self.is_ddl_on_temp_object,
copy.deepcopy(self.api_calls) if self.api_calls else None,
self.df_aliased_col_name_to_real_col_name,
session=self.session,
referenced_ctes=self.referenced_ctes,
)
else:
return SnowflakePlan(
self.queries.copy() if self.queries else [],
self.schema_query,
self.post_actions.copy() if self.post_actions else None,
dict(self.expr_to_alias) if self.expr_to_alias else None,
self.source_plan,
self.is_ddl_on_temp_object,
self.api_calls.copy() if self.api_calls else None,
self.df_aliased_col_name_to_real_col_name,
session=self.session,
referenced_ctes=self.referenced_ctes,
)
def __deepcopy__(self, memodict={}) -> "SnowflakePlan": # noqa: B006
if self.source_plan:
copied_source_plan = copy.deepcopy(self.source_plan, memodict)
else:
copied_source_plan = None
copied_plan = SnowflakePlan(
queries=copy.deepcopy(self.queries) if self.queries else [],
schema_query=self.schema_query,
post_actions=copy.deepcopy(self.post_actions)
if self.post_actions
else None,
expr_to_alias=copy.deepcopy(self.expr_to_alias)
if self.expr_to_alias
else None,
source_plan=copied_source_plan,
is_ddl_on_temp_object=self.is_ddl_on_temp_object,
api_calls=copy.deepcopy(self.api_calls) if self.api_calls else None,
df_aliased_col_name_to_real_col_name=copy.deepcopy(
self.df_aliased_col_name_to_real_col_name
)
if self.df_aliased_col_name_to_real_col_name
else None,
# note that there is no copy of the session object, be careful when using the
# session object after deepcopy
session=self.session,
referenced_ctes=self.referenced_ctes,
)
copied_plan._is_valid_for_replacement = True
if copied_source_plan:
copied_source_plan._is_valid_for_replacement = True
return copied_plan
def add_aliases(self, to_add: Dict) -> None:
self.expr_to_alias = {**self.expr_to_alias, **to_add}
class SnowflakePlanBuilder:
def __init__(
self,
session: "snowflake.snowpark.session.Session",
skip_schema_query: bool = False,
) -> None:
self.session = session
# Whether skip the schema query build. If true, the schema_query associated
# with the resolved plan will be None.
# This option is currently only expected to be used for the query generator applied
# on the optimized plan. During the final query generation, no schema query is needed,
# this helps reduces un-necessary overhead for the describing call.
self._skip_schema_query = skip_schema_query
@SnowflakePlan.Decorator.wrap_exception
def build(
self,
sql_generator: Callable[[str], str],
child: SnowflakePlan,
source_plan: Optional[LogicalPlan],
schema_query: Optional[str] = None,
is_ddl_on_temp_object: bool = False,
) -> SnowflakePlan:
select_child = self.add_result_scan_if_not_select(child)
queries = select_child.queries[:-1] + [
Query(
sql_generator(select_child.queries[-1].sql),
query_id_place_holder="",
is_ddl_on_temp_object=is_ddl_on_temp_object,
params=select_child.queries[-1].params,
)
]
if self._skip_schema_query:
new_schema_query = None
else:
assert (
child.schema_query is not None
), "No schema query is available in child SnowflakePlan"
new_schema_query = schema_query or sql_generator(child.schema_query)
return SnowflakePlan(
queries,
new_schema_query,
select_child.post_actions,
select_child.expr_to_alias,
source_plan,
is_ddl_on_temp_object,
api_calls=select_child.api_calls,
df_aliased_col_name_to_real_col_name=child.df_aliased_col_name_to_real_col_name,
session=self.session,
referenced_ctes=child.referenced_ctes,
)
@SnowflakePlan.Decorator.wrap_exception
def build_binary(
self,
sql_generator: Callable[[str, str], str],
left: SnowflakePlan,
right: SnowflakePlan,
source_plan: Optional[LogicalPlan],
) -> SnowflakePlan:
select_left = self.add_result_scan_if_not_select(left)
select_right = self.add_result_scan_if_not_select(right)
if self._skip_schema_query:
schema_query = None
else:
left_schema_query = schema_value_statement(select_left.attributes)
right_schema_query = schema_value_statement(select_right.attributes)
schema_query = sql_generator(left_schema_query, right_schema_query)
common_columns = set(select_left.expr_to_alias.keys()).intersection(
select_right.expr_to_alias.keys()
)
new_expr_to_alias = {
k: v
for k, v in {
**select_left.expr_to_alias,
**select_right.expr_to_alias,
}.items()
if k not in common_columns
}
api_calls = [*select_left.api_calls, *select_right.api_calls]
# Need to do a deduplication to avoid repeated query.
merged_queries = select_left.queries[:-1].copy()
for query in select_right.queries[:-1]:
if query not in merged_queries:
merged_queries.append(copy.copy(query))
post_actions = select_left.post_actions.copy()
for post_action in select_right.post_actions:
if post_action not in post_actions:
post_actions.append(copy.copy(post_action))
referenced_ctes: Dict[WithQueryBlock, int] = dict()
if (
self.session.cte_optimization_enabled
and self.session._query_compilation_stage_enabled
):
# When the cte optimization and the new compilation stage is enabled,
# the referred cte tables are propagated from left and right can have
# duplicated queries if there is a common CTE block referenced by
# both left and right.
referenced_ctes = merge_referenced_ctes(
select_left.referenced_ctes, select_right.referenced_ctes
)
queries = merged_queries + [
Query(
sql_generator(
select_left.queries[-1].sql, select_right.queries[-1].sql
),
params=[
*select_left.queries[-1].params,
*select_right.queries[-1].params,
],
)
]
return SnowflakePlan(
queries,
schema_query,
post_actions,
new_expr_to_alias,
source_plan,
api_calls=api_calls,
session=self.session,
referenced_ctes=referenced_ctes,
)
def query(
self,
sql: str,
source_plan: Optional[LogicalPlan],
api_calls: Optional[List[Dict]] = None,
params: Optional[Sequence[Any]] = None,
schema_query: Optional[str] = None,
) -> SnowflakePlan:
return SnowflakePlan(
queries=[Query(sql, params=params)],
schema_query=schema_query or sql,
session=self.session,
source_plan=source_plan,
api_calls=api_calls,
)
def large_local_relation_plan(
self,
output: List[Attribute],
data: List[Row],
source_plan: Optional[LogicalPlan],
schema_query: Optional[str],
) -> SnowflakePlan:
temp_table_name = f"temp_name_placeholder_{generate_random_alphanumeric()}"
attributes = [
Attribute(attr.name, attr.datatype, attr.nullable) for attr in output
]
create_table_stmt = create_table_statement(
temp_table_name,
attribute_to_schema_string(attributes),
replace=True,
table_type="temporary",
use_scoped_temp_objects=self.session._use_scoped_temp_objects,
is_generated=True,
)
insert_stmt = batch_insert_into_statement(
temp_table_name,
[attr.name for attr in attributes],
self.session._conn._conn._paramstyle,
)
select_stmt = project_statement([], temp_table_name)
drop_table_stmt = drop_table_if_exists_statement(temp_table_name)
if self._skip_schema_query:
schema_query = None
else:
schema_query = schema_query or schema_value_statement(attributes)
queries = [
Query(
create_table_stmt,
is_ddl_on_temp_object=True,
temp_obj_name_placeholder=(temp_table_name, TempObjectType.TABLE),
),
BatchInsertQuery(insert_stmt, data),
Query(select_stmt),
]
return SnowflakePlan(
queries=queries,
schema_query=schema_query,
post_actions=[Query(drop_table_stmt, is_ddl_on_temp_object=True)],
session=self.session,
source_plan=source_plan,
)
def table(self, table_name: str, source_plan: LogicalPlan) -> SnowflakePlan:
return self.query(project_statement([], table_name), source_plan)
def file_operation_plan(
self, command: str, file_name: str, stage_location: str, options: Dict[str, str]
) -> SnowflakePlan:
return self.query(
file_operation_statement(command, file_name, stage_location, options),
None,
)
def project(
self,
project_list: List[str],
child: SnowflakePlan,
source_plan: Optional[LogicalPlan],
is_distinct: bool = False,
) -> SnowflakePlan:
return self.build(
lambda x: project_statement(project_list, x, is_distinct=is_distinct),
child,
source_plan,
)
def aggregate(
self,
grouping_exprs: List[str],
aggregate_exprs: List[str],
child: SnowflakePlan,
source_plan: Optional[LogicalPlan],
) -> SnowflakePlan:
return self.build(
lambda x: aggregate_statement(grouping_exprs, aggregate_exprs, x),
child,
source_plan,
)
def filter(
self,
condition: str,
child: SnowflakePlan,
source_plan: Optional[LogicalPlan],
) -> SnowflakePlan:
return self.build(lambda x: filter_statement(condition, x), child, source_plan)
def sample(
self,
child: SnowflakePlan,
source_plan: Optional[LogicalPlan],
probability_fraction: Optional[float] = None,
row_count: Optional[int] = None,
) -> SnowflakePlan:
"""Builds the sample part of the resultant sql statement"""
return self.build(
lambda x: sample_statement(
x, probability_fraction=probability_fraction, row_count=row_count
),
child,
source_plan,
)
def sort(
self,
order: List[str],
child: SnowflakePlan,
source_plan: Optional[LogicalPlan],
) -> SnowflakePlan:
return self.build(lambda x: sort_statement(order, x), child, source_plan)
def set_operator(
self,
left: SnowflakePlan,
right: SnowflakePlan,
op: str,
source_plan: Optional[LogicalPlan],
) -> SnowflakePlan:
return self.build_binary(
lambda x, y: set_operator_statement(x, y, op),
left,
right,
source_plan,
)
def join(
self,
left: SnowflakePlan,
right: SnowflakePlan,
join_type: JoinType,
join_condition: str,
match_condition: str,
source_plan: Optional[LogicalPlan],
use_constant_subquery_alias: bool,
):
return self.build_binary(
lambda x, y: join_statement(
x,
y,
join_type,
join_condition,
match_condition,
use_constant_subquery_alias,
),
left,
right,
source_plan,
)
def save_as_table(
self,
table_name: Iterable[str],
column_names: Optional[Iterable[str]],
mode: SaveMode,
table_type: str,
clustering_keys: Iterable[str],
comment: Optional[str],
enable_schema_evolution: Optional[bool],
data_retention_time: Optional[int],
max_data_extension_time: Optional[int],
change_tracking: Optional[bool],
copy_grants: bool,
child: SnowflakePlan,
source_plan: Optional[LogicalPlan],
use_scoped_temp_objects: bool,
creation_source: TableCreationSource,
child_attributes: Optional[List[Attribute]],
iceberg_config: Optional[dict] = None,
table_exists: Optional[bool] = None,
) -> SnowflakePlan:
"""Returns a SnowflakePlan to materialize the child plan into a table.
Args:
table_name: fully qualified table name
column_names: names of columns for the table
mode: APPEND, TRUNCATE, OVERWRITE, IGNORE, ERROR_IF_EXISTS
table_type: temporary, transient, or permanent
clustering_keys: list of clustering columns
comment: comment associated with the table
enable_schema_evolution: whether to enable schema evolution
data_retention_time: data retention time in days
max_data_extension_time: max data extension time in days
change_tracking: whether to enable change tracking
copy_grants: whether to copy grants
child: the SnowflakePlan that is being materialized into a table
source_plan: the source plan of the child
use_scoped_temp_objects: should we use scoped temp objects
creation_source: the creator for the SnowflakeCreateTable node, today it can come from the
cache result api, compilation transformations like large query breakdown, or other like
save_as_table call. This parameter is used to identify whether a table is internally
generated with cache_result or by the compilation transformation, and some special
check and handling needs to be applied to guarantee the correctness of generated query.
child_attributes: child attributes will be none in the case of large query breakdown
where we use ctas query to create the table which does not need to know the column
metadata.
iceberg_config: A dictionary that can contain the following iceberg configuration values:
external_volume: specifies the identifier for the external volume where
the Iceberg table stores its metadata files and data in Parquet format
catalog: specifies either Snowflake or a catalog integration to use for this table
base_location: the base directory that snowflake can write iceberg metadata and files to
catalog_sync: optionally sets the catalog integration configured for Polaris Catalog
storage_serialization_policy: specifies the storage serialization policy for the table
table_exists: whether the table already exists in the database.
Only used for APPEND and TRUNCATE mode.
"""
is_generated = creation_source in (
TableCreationSource.CACHE_RESULT,
TableCreationSource.LARGE_QUERY_BREAKDOWN,
)
if is_generated and mode != SaveMode.ERROR_IF_EXISTS:
# an internally generated save_as_table comes from two sources:
# 1. df.cache_result: plan is created with create table + insert statement
# 2. large query breakdown: plan is created using a CTAS statement
# For these cases, we must use mode ERROR_IF_EXISTS
raise ValueError(
"Internally generated tables must be called with mode ERROR_IF_EXISTS"
)
if (
child_attributes is None
and creation_source != TableCreationSource.LARGE_QUERY_BREAKDOWN
):
raise ValueError(
"child attribute must be provided when table creation source is not large query breakdown"
)
full_table_name = ".".join(table_name)
is_temp_table_type = table_type in TEMPORARY_STRING_SET
# here get the column definition from the child attributes. In certain cases we have
# the attributes set to ($1, VariantType()) which cannot be used as valid column name
# in save as table. So we rename ${number} with COL{number}.
hidden_column_pattern = r"\"\$(\d+)\""
column_definition = None
if child_attributes is not None:
column_definition_with_hidden_columns = attribute_to_schema_string(
child_attributes or []
)
column_definition = re.sub(
hidden_column_pattern,
lambda match: f'"COL{match.group(1)}"',
column_definition_with_hidden_columns,
)
def get_create_table_as_select_plan(child: SnowflakePlan, replace, error):
return self.build(
lambda x: create_table_as_select_statement(
full_table_name,
x,
column_definition,
replace=replace,
error=error,
table_type=table_type,
clustering_key=clustering_keys,
comment=comment,
enable_schema_evolution=enable_schema_evolution,
data_retention_time=data_retention_time,
max_data_extension_time=max_data_extension_time,
change_tracking=change_tracking,
copy_grants=copy_grants,
iceberg_config=iceberg_config,
use_scoped_temp_objects=use_scoped_temp_objects,
is_generated=is_generated,
),
child,
source_plan,
is_ddl_on_temp_object=is_temp_table_type,
)
def get_create_and_insert_plan(child: SnowflakePlan, replace, error):
assert (
column_definition is not None
), "column definition is required for create table statement"
create_table = create_table_statement(
full_table_name,
column_definition,
replace=replace,
error=error,
table_type=table_type,
clustering_key=clustering_keys,
comment=comment,
enable_schema_evolution=enable_schema_evolution,
data_retention_time=data_retention_time,
max_data_extension_time=max_data_extension_time,
change_tracking=change_tracking,
copy_grants=copy_grants,
use_scoped_temp_objects=use_scoped_temp_objects,
is_generated=is_generated,
iceberg_config=iceberg_config,
)
# so that dataframes created from non-select statements,
# such as table sprocs, work
child = self.add_result_scan_if_not_select(child)
return SnowflakePlan(
[
*child.queries[0:-1],
Query(create_table, is_ddl_on_temp_object=is_temp_table_type),
Query(
insert_into_statement(
table_name=full_table_name,
child=child.queries[-1].sql,
column_names=column_names,
),
params=child.queries[-1].params,
is_ddl_on_temp_object=is_temp_table_type,
),
],
create_table,
child.post_actions,
{},
source_plan,
api_calls=child.api_calls,
session=self.session,
referenced_ctes=child.referenced_ctes,
)
if mode == SaveMode.APPEND:
assert table_exists is not None
if table_exists:
return self.build(
lambda x: insert_into_statement(
table_name=full_table_name,
child=x,
column_names=column_names,
),
child,
source_plan,
)
else:
return get_create_and_insert_plan(child, replace=False, error=False)
elif mode == SaveMode.TRUNCATE:
assert table_exists is not None
if table_exists:
return self.build(
lambda x: insert_into_statement(