-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathsnowflake_query_compiler.py
More file actions
22401 lines (20346 loc) · 956 KB
/
snowflake_query_compiler.py
File metadata and controls
22401 lines (20346 loc) · 956 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 calendar
import collections
import copy
import functools
import inspect
import itertools
import json
import logging
import re
from collections import Counter, defaultdict
from dataclasses import dataclass, field
import typing
import uuid
from collections.abc import Hashable, Iterable, Mapping, Sequence
from datetime import timedelta, tzinfo
from functools import reduce
from types import MappingProxyType
from typing import (
Any,
Callable,
List,
Literal,
NamedTuple,
Optional,
TypeVar,
Union,
get_args,
Set,
Tuple,
)
import modin.pandas as pd
from modin.pandas import Series, DataFrame
from modin.pandas.base import BasePandasDataset
import numpy as np
import numpy.typing as npt
import pandas as native_pd
import pandas.core.resample
import pandas.io.parsers
from pandas.core.interchange.dataframe_protocol import DataFrame as InterchangeDataframe
import pandas.io.parsers.readers
import pytz # type: ignore
from modin.core.storage_formats import BaseQueryCompiler # type: ignore
from modin.core.storage_formats.base.query_compiler import QCCoercionCost
from modin.core.storage_formats.pandas.query_compiler_caster import (
register_function_for_pre_op_switch,
)
from pandas import Timedelta
from pandas._libs import lib
from pandas._libs.lib import no_default
from pandas._libs.tslibs import Tick
from pandas._libs.tslibs.offsets import BusinessDay, CustomBusinessDay, Day
from pandas._typing import (
AggFuncType,
AnyArrayLike,
Axes,
Axis,
DateTimeErrorChoices,
DtypeBackend,
FillnaOptions,
Frequency,
IgnoreRaise,
IndexKeyFunc,
IndexLabel,
Level,
NaPosition,
RandomState,
Renamer,
Scalar,
SortKind,
Suffixes,
)
from pandas.api.types import (
is_bool,
is_bool_dtype,
is_datetime64_any_dtype,
is_integer_dtype,
is_named_tuple,
is_numeric_dtype,
is_object_dtype,
is_re_compilable,
is_scalar,
is_string_dtype,
is_timedelta64_dtype,
)
from pandas.core.dtypes.base import ExtensionDtype
from pandas.core.dtypes.common import is_dict_like, is_list_like, pandas_dtype
from pandas.core.indexes.base import ensure_index
from pandas.errors import DataError
from pandas.io.formats.format import format_percentiles
from pandas.io.formats.printing import PrettyDict
from snowflake.snowpark._internal.analyzer.analyzer_utils import (
quote_name_without_upper_casing,
)
from snowflake.snowpark._internal.type_utils import ColumnOrName
from snowflake.snowpark._internal.utils import (
generate_random_alphanumeric,
random_name_for_temp_object,
)
from snowflake.snowpark.column import CaseExpr, Column as SnowparkColumn
from snowflake.snowpark.dataframe import DataFrame as SnowparkDataFrame
from snowflake.snowpark.exceptions import SnowparkSQLException
from snowflake.snowpark.functions import (
abs as abs_,
array_construct,
array_size,
array_slice,
bround,
builtin,
cast,
coalesce,
col,
concat,
corr,
count,
count_distinct,
date_from_parts,
date_part,
dateadd,
dayofmonth,
dayofyear,
dense_rank,
first_value,
floor,
get,
greatest,
hour,
iff,
initcap,
is_char,
is_null,
lag,
last_value,
lead,
least,
length,
lower,
lpad,
ltrim,
max as max_,
min as min_,
minute,
month,
negate,
not_,
object_keys,
pandas_udf,
quarter,
random,
rank,
regexp_replace,
reverse,
round as snowpark_round,
row_number,
rpad,
rtrim,
second,
substring,
sum as sum_,
sum_distinct,
timestamp_ntz_from_parts,
to_date,
to_time,
to_variant,
translate,
trim,
trunc,
uniform,
upper,
when,
year,
)
from snowflake.snowpark.modin.config.envvars import SnowflakePandasTransferThreshold
from snowflake.snowpark.modin.plugin._internal import (
concat_utils,
generator_utils,
join_utils,
get_dummies_utils,
)
from snowflake.snowpark.modin.plugin._internal.aggregation_utils import (
AGG_NAME_COL_LABEL,
AggFuncInfo,
AggFuncWithLabel,
AggregateColumnOpParameters,
_columns_coalescing_idxmax_idxmin_helper,
aggregate_with_ordered_dataframe,
check_is_aggregation_supported_in_snowflake,
column_quantile,
convert_agg_func_arg_to_col_agg_func_map,
drop_non_numeric_data_columns,
generate_column_agg_info,
get_agg_func_to_col_map,
get_pandas_aggr_func_name,
get_snowflake_agg_func,
is_first_last_in_agg_funcs,
repr_aggregate_function,
using_named_aggregations_for_func,
)
from snowflake.snowpark.modin.plugin._internal.align_utils import (
align_axis_0_left,
align_axis_0_right,
align_axis_1,
)
from snowflake.snowpark.modin.plugin._internal.apply_utils import (
ALL_SNOWFLAKE_CORTEX_FUNCTIONS,
APPLY_LABEL_COLUMN_QUOTED_IDENTIFIER,
APPLY_VALUE_COLUMN_QUOTED_IDENTIFIER,
DEFAULT_UDTF_PARTITION_SIZE,
GroupbyApplySortMethod,
SUPPORTED_SNOWFLAKE_CORTEX_FUNCTIONS_IN_APPLY,
SUPPORTED_SNOWPARK_PYTHON_FUNCTIONS_IN_APPLY,
check_return_variant_and_get_return_type,
create_udf_for_series_apply,
create_udtf_for_apply_axis_1,
create_udtf_for_groupby_apply,
create_internal_frame_for_groupby_apply_no_pivot_result,
deduce_return_type_from_function,
get_metadata_from_groupby_apply_pivot_result_column_names,
groupby_apply_create_internal_frame_from_final_ordered_dataframe,
groupby_apply_pivot_result_to_final_ordered_dataframe,
groupby_apply_sort_method,
is_supported_snowpark_python_function,
make_series_map_snowpark_function,
sort_apply_udtf_result_columns_by_pandas_positions,
)
from snowflake.snowpark.modin.plugin._internal.binary_op_utils import (
BinaryOp,
merge_label_and_identifier_pairs,
prepare_binop_pairs_between_dataframe_and_dataframe,
)
from snowflake.snowpark.modin.plugin._internal.cumulative_utils import (
get_cumagg_col_to_expr_map_axis0,
get_groupby_cumagg_frame_axis0,
)
from snowflake.snowpark.modin.plugin._internal.cut_utils import (
compute_bin_indices,
preprocess_bins_for_cut,
)
from snowflake.snowpark.modin.plugin._internal.frame import (
InternalFrame,
LabelIdentifierPair,
)
from snowflake.snowpark.modin.plugin._internal.groupby_utils import (
check_is_groupby_supported_by_snowflake,
resample_and_extract_groupby_column_pandas_labels,
get_frame_with_groupby_columns_as_index,
get_groups_for_ordered_dataframe,
make_groupby_rank_col_for_method,
validate_groupby_columns,
extract_groupby_column_pandas_labels,
fill_missing_groupby_resample_bins_for_frame,
validate_groupby_resample_supported_by_snowflake,
)
from snowflake.snowpark.modin.plugin._internal.indexing_utils import (
ValidIndex,
convert_snowpark_row_to_pandas_index,
get_frame_by_col_label,
get_frame_by_col_pos,
get_frame_by_row_label,
get_frame_by_row_pos_frame,
get_frame_by_row_pos_slice_frame,
get_index_frame_by_row_label_slice,
get_row_pos_frame_from_row_key,
get_snowflake_filter_for_row_label,
get_valid_col_pos_list_from_columns,
get_valid_index_values,
set_frame_2d_labels,
set_frame_2d_positional,
)
from snowflake.snowpark.modin.plugin._internal.io_utils import (
TO_CSV_DEFAULTS,
get_columns_to_keep_for_usecols,
get_compression_algorithm_for_csv,
get_non_pandas_kwargs,
is_local_filepath,
upload_local_path_to_snowflake_stage,
)
from snowflake.snowpark.modin.plugin._internal.isin_utils import (
compute_isin_with_dataframe,
compute_isin_with_series,
convert_values_to_list_of_literals_and_return_type,
scalar_isin_expression,
)
from snowflake.snowpark.modin.plugin._internal.join_utils import (
InheritJoinIndex,
JoinKeyCoalesceConfig,
MatchComparator,
convert_index_type_to_variant,
)
from snowflake.snowpark.modin.plugin._internal.ordered_dataframe import (
DataFrameReference,
OrderedDataFrame,
OrderingColumn,
)
from snowflake.snowpark.modin.plugin._internal.pivot_utils import (
expand_pivot_result_with_pivot_table_margins,
expand_pivot_result_with_pivot_table_margins_no_groupby_columns,
generate_pivot_aggregation_value_label_snowflake_quoted_identifier_mappings,
generate_single_pivot_labels,
pivot_helper,
)
from snowflake.snowpark.modin.plugin._internal.resample_utils import (
IMPLEMENTED_AGG_METHODS,
RULE_SECOND_TO_DAY,
fill_missing_resample_bins_for_frame,
get_expected_resample_bins_frame,
get_snowflake_quoted_identifier_for_resample_index_col,
perform_asof_join_on_frame,
perform_resample_binning_on_frame,
rule_to_snowflake_width_and_slice_unit,
validate_resample_supported_by_snowflake,
compute_resample_start_and_end_date,
)
from snowflake.snowpark.modin.plugin._internal.row_count_estimation import (
MAX_ROW_COUNT_FOR_ESTIMATION,
)
from snowflake.snowpark.modin.plugin._internal.snowpark_pandas_types import (
SnowparkPandasColumn,
SnowparkPandasType,
TimedeltaType,
)
from snowflake.snowpark.modin.plugin._internal.timestamp_utils import (
VALID_TO_DATETIME_DF_KEYS,
DateTimeOrigin,
col_to_timedelta,
generate_timestamp_col,
raise_if_to_datetime_not_supported,
timedelta_freq_to_nanos,
to_snowflake_timestamp_format,
tz_convert_column,
tz_localize_column,
)
from snowflake.snowpark.modin.plugin._internal.transpose_utils import (
clean_up_transpose_result_index_and_labels,
prepare_and_unpivot_for_transpose,
transpose_empty_df,
)
from snowflake.snowpark.modin.plugin._internal.type_utils import (
DataTypeGetter,
TypeMapper,
column_astype,
infer_object_type,
is_astype_type_error,
is_compatible_snowpark_types,
)
from snowflake.snowpark.modin.plugin._internal.unpivot_utils import (
StackOperation,
unpivot,
unpivot_empty_df,
)
from snowflake.snowpark.modin.plugin._internal.utils import (
extract_and_validate_index_labels_for_to_snowflake,
handle_if_exists_for_to_snowflake,
new_snow_series,
INDEX_LABEL,
ROW_COUNT_COLUMN_LABEL,
ROW_POSITION_COLUMN_LABEL,
SAMPLED_ROW_POSITION_COLUMN_LABEL,
FillNAMethod,
TempObjectType,
append_columns,
cache_result,
check_snowpark_pandas_object_in_arg,
check_valid_pandas_labels,
count_rows,
create_frame_with_data_columns,
create_ordered_dataframe_from_pandas,
create_initial_ordered_dataframe,
extract_pandas_label_from_snowflake_quoted_identifier,
fill_missing_levels_for_pandas_label,
fill_none_in_index_labels,
fillna_label_to_value_map,
generate_snowflake_quoted_identifiers_helper,
get_default_snowpark_pandas_statement_params,
get_distinct_rows,
get_mapping_from_left_to_right_columns_by_label,
infer_snowpark_types_from_pandas,
is_all_label_components_none,
is_duplicate_free,
label_prefix_match,
pandas_lit,
parse_object_construct_snowflake_quoted_identifier_and_extract_pandas_label,
parse_snowflake_object_construct_identifier_to_map,
unquote_name_if_quoted,
validate_column_labels_for_to_snowflake,
MODIN_IS_AT_LEAST_0_37_0,
)
from snowflake.snowpark.modin.plugin._internal.where_utils import (
validate_expected_boolean_data_columns,
)
from snowflake.snowpark.modin.plugin._internal.window_utils import (
WindowFunction,
check_and_raise_error_expanding_window_supported_by_snowflake,
check_and_raise_error_rolling_window_supported_by_snowflake,
create_snowpark_interval_from_window,
get_rolling_corr_column,
)
from snowflake.snowpark.modin.plugin._typing import (
DropKeep,
JoinTypeLit,
ListLike,
PandasLabelToSnowflakeIdentifierPair,
SnowflakeSupportedFileTypeLit,
)
from snowflake.snowpark.modin.plugin.utils.error_message import ErrorMessage
from snowflake.snowpark.modin.plugin.utils.warning_message import WarningMessage
from snowflake.snowpark.modin.utils import MODIN_UNNAMED_SERIES_LABEL
from snowflake.snowpark.modin.plugin.utils.numpy_to_pandas import (
NUMPY_UNIVERSAL_FUNCTION_TO_SNOWFLAKE_FUNCTION,
)
from snowflake.snowpark.modin.plugin.compiler.ray_utils import (
move_from_ray_helper,
move_to_ray_helper,
)
from snowflake.snowpark.row import Row
from snowflake.snowpark.session import Session
from snowflake.snowpark.types import (
ArrayType,
BinaryType,
BooleanType,
DataType,
DateType,
DecimalType,
DoubleType,
FloatType,
IntegerType,
MapType,
PandasDataFrameType,
PandasSeriesType,
StringType,
TimestampTimeZone,
TimestampType,
TimeType,
VariantType,
_IntegralType,
_NumericType,
)
from snowflake.snowpark.udf import UserDefinedFunction
from snowflake.snowpark.window import Window
_logger = logging.getLogger(__name__)
# TODO: SNOW-1229442 remove this restriction once bug in quantile is fixed.
# For now, limit number of quantiles supported df.quantiles to avoid producing recursion limit failure in Snowpark.
MAX_QUANTILES_SUPPORTED: int = 16
_GROUPBY_UNSUPPORTED_GROUPING_MESSAGE = "does not yet support axis == 1, by != None and level != None, or by containing any non-pandas hashable labels."
QUARTER_START_MONTHS = [1, 4, 7, 10]
SUPPORTED_DT_FLOOR_CEIL_FREQS = ["day", "hour", "minute", "second"]
SECONDS_PER_DAY = 86400
NANOSECONDS_PER_SECOND = 10**9
NANOSECONDS_PER_MICROSECOND = 10**3
MICROSECONDS_PER_SECOND = 10**6
NANOSECONDS_PER_DAY = SECONDS_PER_DAY * NANOSECONDS_PER_SECOND
# Matches pandas
_TIMEDELTA_ROLLING_AGGREGATION_NOT_SUPPORTED = "No numeric types to aggregate"
# Matches pandas
_TIMEDELTA_ROLLING_CORR_NOT_SUPPORTED = (
"ops for Rolling for this dtype timedelta64[ns] are not implemented"
)
# List of query compiler methods where attrs on the result should always be empty.
_RESET_ATTRS_METHODS = [
"compare",
"merge",
"value_counts",
"dataframe_to_datetime",
"series_to_datetime",
"to_numeric",
"dt_isocalendar",
"groupby_all",
"groupby_any",
"groupby_cumcount",
"groupby_cummax",
"groupby_cummin",
"groupby_cumsum",
"groupby_nunique",
"groupby_rank",
"groupby_size",
"groupby_pct_change",
# expanding and rolling methods also do not propagate; we check them by prefix matching
# agg, crosstab, and concat depend on their inputs, and are handled separately
]
# Functions which should be considered for execution outside of snowflake
HYBRID_HIGH_OVERHEAD_METHODS = [
"apply",
"describe",
"quantile",
"read_csv",
"read_json",
"T",
"concat",
"merge",
]
HYBRID_ITERATIVE_STYLE_METHODS = ["iterrows", "itertuples", "items", "plot"]
HYBRID_ALL_EXPENSIVE_METHODS = (
HYBRID_HIGH_OVERHEAD_METHODS + HYBRID_ITERATIVE_STYLE_METHODS
)
# Named tuple for method registry keys.
class MethodKey(NamedTuple):
api_cls_name: Optional[str]
method_name: str
# Rule defining which args should trigger auto-switching.
@dataclass(frozen=True)
class UnsupportedArgsRule:
"""
Rule for defining argument combinations that trigger auto-switching to native pandas.
Attributes:
unsupported_conditions: List of conditions that can be:
- tuple[str, Any]: (argument_name, unsupported_value) for simple value checks
- tuple[Callable, str]: (condition_function, reason) for complex checks and simple string reason
- tuple[Callable, Callable]: (condition_function, reason_function) for complex checks and reason generation
"""
unsupported_conditions: List[
Union[
Tuple[str, Any],
Tuple[
Callable[[MappingProxyType], bool],
Union[str, Callable[[MappingProxyType], str]],
],
]
] = field(default_factory=list)
def __post_init__(self) -> None:
# Validate all conditions are properly formatted at initialization time.
for i, condition in enumerate(self.unsupported_conditions):
if not isinstance(condition, tuple) or len(condition) != 2:
raise ValueError(
f"Invalid condition at index {i}: expected tuple of length 2, "
f"got {type(condition).__name__} of length "
f"{len(condition) if hasattr(condition, '__len__') else 'unknown'}. "
f"Condition: {condition}"
)
if not (callable(condition[0]) or isinstance(condition[0], str)):
raise ValueError(
f"Invalid condition at index {i}: first element must be callable or string, "
f"got {type(condition[0]).__name__}. Condition: {condition}"
)
if callable(condition[0]) and not (
isinstance(condition[1], str) or callable(condition[1])
):
raise ValueError(
f"Invalid condition at index {i}: when first element is callable, "
f"second element must be a string representing the reason, or a callable that returns the reason, got {type(condition[1]).__name__}. "
f"Condition: {condition}"
)
def get_reason_if_unsupported(
self, args: MappingProxyType[Any, Any]
) -> Optional[str]:
"""
Validate arguments and return the reason if unsupported.
Args:
args: Method arguments to check
Returns:
The specific reason string if unsupported args detected, None if all args are supported
"""
for condition in self.unsupported_conditions:
if callable(condition[0]):
# tuple[Callable, str or Callable]: (condition_function, reason)
condition_func, reason = condition
if condition_func(args):
return reason(args) if callable(reason) else reason
else:
# tuple[str, Any]: (argument_name, unsupported_value)
arg_name, unsupported_value = condition
if args.get(arg_name) == unsupported_value:
return f"{arg_name} = {unsupported_value} is not supported"
return None
def is_unsupported(self, args: MappingProxyType[Any, Any]) -> bool:
"""
Returns True if args are unsupported.
"""
return self.get_reason_if_unsupported(args) is not None
@staticmethod
def get_unsupported_args_reason(
api_cls_name: Optional[str],
operation: str,
args: MappingProxyType[Any, Any],
) -> Optional[str]:
"""
Get the specific reason why args are unsupported.
Args:
api_cls_name: Class name (DataFrame, Series, BasePandasDataset, None for top-level functions)
operation: Method name
args: Method arguments
Returns:
The specific reason string if unsupported args detected, None otherwise
"""
rule = HYBRID_SWITCH_FOR_UNSUPPORTED_ARGS.get(
MethodKey(api_cls_name, operation)
)
return rule.get_reason_if_unsupported(args) if rule else None
# Set of MethodKey objects for methods that are wholly unimplemented by
# Snowpark pandas. This list is populated by the register_*_not_implemented decorators.
HYBRID_SWITCH_FOR_UNIMPLEMENTED_METHODS: Set[MethodKey] = set()
# Global registry for args-based switching rules
HYBRID_SWITCH_FOR_UNSUPPORTED_ARGS: dict[MethodKey, UnsupportedArgsRule] = {}
def register_query_compiler_method_not_implemented(
api_cls_names: List[Optional[str]],
method_name: str,
unsupported_args: Optional["UnsupportedArgsRule"] = None,
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
"""
Decorator for SnowflakeQueryCompiler methods with args-based auto-switching.
Registers pre-op switching for the specified API-layer method, replacing the decorated query
compiler method with a version that raises a NotImplementedError if any unsupported parameter predicate evaluates True.
This decorator is applied at the query compiler level rather than the frontend to avoid
creating unnecessary frontend overrides. Frontend decorators in Modin must attach to an
existing method for dispatch, but many functions already rely on Modin's default frontend
implementations and delegate directly to the query compiler. Adding frontend decorators
would require redundant overrides solely as attachment points, increasing code complexity
without meaningful benefit.
Args:
api_cls_names: Frontend class names (e.g., ["BasePandasDataset", "Series", "DataFrame", None]). This is a list because some methods are implemented for both DataFrames and Series.
method_name: Method name to register.
unsupported_args: UnsupportedArgsRule for args-based auto-switching.
If None, method is treated as completely unimplemented.
"""
for api_cls_name in api_cls_names:
reg_key = MethodKey(api_cls_name, method_name)
# register the method in the hybrid switch for unsupported args
if unsupported_args is None:
HYBRID_SWITCH_FOR_UNIMPLEMENTED_METHODS.add(reg_key)
else:
HYBRID_SWITCH_FOR_UNSUPPORTED_ARGS[reg_key] = unsupported_args
register_function_for_pre_op_switch(
class_name=api_cls_name, backend="Snowflake", method=method_name
)
def decorator(query_compiler_method: Callable[..., Any]) -> Callable[..., Any]:
@functools.wraps(query_compiler_method)
def wrapper(self: "SnowflakeQueryCompiler", *args: Any, **kwargs: Any) -> Any:
bound_arguments = inspect.signature(query_compiler_method).bind(
self, *args, **kwargs
)
bound_arguments.apply_defaults()
# Extract parameters excluding 'self'
arguments = MappingProxyType(
{k: v for k, v in bound_arguments.arguments.items() if k != "self"}
)
# Check if any condition triggers unsupported behavior
if SnowflakeQueryCompiler._has_unsupported_args(
api_cls_name, method_name, arguments
):
ErrorMessage.not_implemented_with_reason(
method_name,
UnsupportedArgsRule.get_unsupported_args_reason(
api_cls_name, method_name, arguments
),
)
return query_compiler_method(self, *args, **kwargs)
return wrapper
return decorator
T = TypeVar("T", bound=Callable[..., Any])
def _propagate_attrs_on_methods(cls): # type: ignore
"""
Decorator that modifies all methods on the class to copy `_attrs` from `self`
to the output of the method, if the output is another query compiler.
"""
def propagate_attrs_decorator(method: T) -> T:
@functools.wraps(method)
def wrap(self, *args, **kwargs): # type: ignore
result = method(self, *args, **kwargs)
if isinstance(result, SnowflakeQueryCompiler) and len(self._attrs):
result._attrs = copy.deepcopy(self._attrs)
return result
return typing.cast(T, wrap)
def reset_attrs_decorator(method: T) -> T:
@functools.wraps(method)
def wrap(self, *args, **kwargs): # type: ignore
result = method(self, *args, **kwargs)
if isinstance(result, SnowflakeQueryCompiler) and len(self._attrs):
result._attrs = {}
return result
return typing.cast(T, wrap)
for attr_name, attr_value in cls.__dict__.items():
# concat is handled explicitly because it checks all of its arguments
# agg is handled explicitly because it sometimes resets and sometimes propagates
if attr_name.startswith("_") or attr_name in ["concat", "agg"]:
continue
if attr_name in _RESET_ATTRS_METHODS or any(
attr_name.startswith(prefix) for prefix in ["expanding", "rolling"]
):
setattr(cls, attr_name, reset_attrs_decorator(attr_value))
elif isinstance(attr_value, property):
setattr(
cls,
attr_name,
property(
propagate_attrs_decorator(
attr_value.fget
if attr_value.fget is not None
else attr_value.__get__
),
propagate_attrs_decorator(
attr_value.fset
if attr_value.fset is not None
else attr_value.__set__
),
propagate_attrs_decorator(
attr_value.fdel
if attr_value.fdel is not None
else attr_value.__delete__
),
),
)
elif inspect.isfunction(attr_value):
setattr(cls, attr_name, propagate_attrs_decorator(attr_value))
return cls
def _apply_func_has_snowpark_function(func: Any) -> bool:
"""
Check if the function passed to an apply-like method is a Snowpark or Cortex function.
Args:
func: The function to check. Could be a single function, a list-like
of functions, or a dict-like of functions.
Returns:
True if the function is a Snowpark or Cortex function, False otherwise.
"""
if is_dict_like(func):
return any(_apply_func_has_snowpark_function(func[key]) for key in func.keys())
if is_list_like(func):
return any(_apply_func_has_snowpark_function(each_item) for each_item in func)
return (
func in SUPPORTED_SNOWFLAKE_CORTEX_FUNCTIONS_IN_APPLY
or func in SUPPORTED_SNOWPARK_PYTHON_FUNCTIONS_IN_APPLY
)
@_propagate_attrs_on_methods
class SnowflakeQueryCompiler(BaseQueryCompiler):
"""based on: https://modin.readthedocs.io/en/0.11.0/flow/modin/backends/base/query_compiler.html
this class is best explained by looking at https://github.com/modin-project/modin/blob/a8be482e644519f2823668210cec5cf1564deb7e/modin/experimental/core/storage_formats/hdk/query_compiler.py
"""
# When these laziness flags are set, upstream Modin elides some length checks that would incur queries.
lazy_row_labels = True
lazy_row_count = True
lazy_column_types = False
lazy_column_labels = False
lazy_column_count = False
_MAX_SIZE_THIS_ENGINE_CAN_HANDLE = 10_000_000_000_000
_OPERATION_INITIALIZATION_OVERHEAD = 100
_OPERATION_PER_ROW_OVERHEAD = 10
def __init__(self, frame: InternalFrame) -> None:
"""this stores internally a local pandas object (refactor this)"""
assert frame is not None and isinstance(
frame, InternalFrame
), "frame is None or not a InternalFrame"
self._modin_frame = frame
self._dummy_row_pos_mode = False
self._relaxed_query_compiler: Optional[SnowflakeQueryCompiler] = None
# self.snowpark_pandas_api_calls a list of lazy Snowpark pandas telemetry api calls
# Copying and modifying self.snowpark_pandas_api_calls and self._method_call_counts
# is taken care of in telemetry decorators
self.snowpark_pandas_api_calls: list = []
self._attrs: dict[Any, Any] = {}
self._method_call_counts: Counter[str] = Counter[str]()
engine = property(lambda self: "Snowflake")
storage_format = property(lambda self: "Snowflake")
def _raise_not_implemented_error_for_timedelta(
self, frame: InternalFrame = None
) -> None:
"""Raise NotImplementedError for SnowflakeQueryCompiler methods which does not support timedelta yet."""
if frame is None:
frame = self._modin_frame
for val in frame.snowflake_quoted_identifier_to_snowpark_pandas_type.values():
if isinstance(val, TimedeltaType):
method = inspect.currentframe().f_back.f_back.f_code.co_name # type: ignore[union-attr]
ErrorMessage.not_implemented_for_timedelta(method)
def _warn_lost_snowpark_pandas_type(self) -> None:
"""Warn Snowpark pandas type can be lost in current operation."""
method = inspect.currentframe().f_back.f_back.f_code.co_name # type: ignore[union-attr]
snowpark_pandas_types = [
type(t).__name__
for t in set(
self._modin_frame.cached_data_column_snowpark_pandas_types
+ self._modin_frame.cached_index_column_snowpark_pandas_types
)
if t is not None
]
if snowpark_pandas_types:
WarningMessage.lost_type_warning(
method,
", ".join(snowpark_pandas_types),
)
def snowpark_pandas_type_immutable_check(func: Callable) -> Any:
"""The decorator to check on SnowflakeQueryCompiler methods which return a new SnowflakeQueryCompiler.
It verifies the cached Snowpark pandas types should not be changed.
"""
def check_type(input: List, output: List) -> None:
assert len(input) == len(
output
), "self frame and output frame have different number of columns"
for lt, rt in zip(input, output):
assert (
lt == rt
), f"one column's Snowpark pandas type has been changed from {lt} to {rt}"
@functools.wraps(func)
def wrap(*args, **kwargs): # type: ignore
self_qc = args[0]
output_qc = func(*args, **kwargs)
assert isinstance(self_qc, SnowflakeQueryCompiler) and isinstance(
output_qc, SnowflakeQueryCompiler
), (
"immutable_snowpark_pandas_type_check only works with SnowflakeQueryCompiler member methods with "
"SnowflakeQueryCompiler as the return result"
)
check_type(
self_qc._modin_frame.cached_index_column_snowpark_pandas_types,
output_qc._modin_frame.cached_index_column_snowpark_pandas_types,
)
check_type(
self_qc._modin_frame.cached_data_column_snowpark_pandas_types,
output_qc._modin_frame.cached_data_column_snowpark_pandas_types,
)
return output_qc
return wrap
def _get_dtypes(
self, snowflake_quoted_identifiers: List[str]
) -> List[Union[np.dtype, ExtensionDtype]]:
"""
Get dtypes for the input columns.
Args:
snowflake_quoted_identifiers: input column identifiers
Returns:
a list of the dtypes.
"""
type_map = self._modin_frame.quoted_identifier_to_snowflake_type(
snowflake_quoted_identifiers
)
return [
self._modin_frame.get_datetime64tz_from_timestamp_tz(i)
if t == TimestampType(TimestampTimeZone.TZ)
else self._modin_frame.get_datetime64tz_from_timestamp_ltz()
if t == TimestampType(TimestampTimeZone.LTZ)
else TypeMapper.to_pandas(t)
for i, t in type_map.items()
]
@property
def dtypes(self) -> native_pd.Series:
"""
Get columns dtypes.
Returns
-------
pandas.Series
Series with dtypes of each column.
"""
return native_pd.Series(
data=self._get_dtypes(
self._modin_frame.data_column_snowflake_quoted_identifiers
),
index=self._modin_frame.data_columns_index,
dtype=object,
)
@property
def index_dtypes(self) -> list[Union[np.dtype, ExtensionDtype]]:
"""
Get index dtypes.
Returns
-------
pandas.Series
Series with dtypes of each column.
"""
return self._get_dtypes(
self._modin_frame.index_column_snowflake_quoted_identifiers
)
def is_timestamp_type(self, idx: int, is_index: bool = True) -> bool:
"""Return True if column at the index is TIMESTAMP TYPE.
Args:
idx: the index of the column
is_index: whether it is an index or data column
"""
return isinstance(
self._modin_frame.get_snowflake_type(
self._modin_frame.index_column_snowflake_quoted_identifiers
if is_index
else self._modin_frame.data_column_snowflake_quoted_identifiers
)[idx],
TimestampType,
)
def is_datetime64_any_dtype(self, idx: int, is_index: bool = True) -> bool:
"""Helper method similar to is_datetime64_any_dtype, but it avoids extra query for DatetimeTZDtype.
Args:
idx: the index of the column
is_index: whether it is an index or data column
"""
return self.is_timestamp_type(idx, is_index)
def is_timedelta64_dtype(self, idx: int, is_index: bool = True) -> bool:
"""Helper method similar to is_timedelta_dtype, but it avoids extra query for DatetimeTZDtype.
Args:
idx: the index of the column
is_index: whether it is an index or data column
"""
id = (
self._modin_frame.index_column_snowflake_quoted_identifiers[idx]
if is_index
else self._modin_frame.data_column_snowflake_quoted_identifiers[idx]
)
return self._modin_frame.get_snowflake_type(id) == TimedeltaType()
def is_string_dtype(self, idx: int, is_index: bool = True) -> bool:
"""Helper method similar to is_timedelta_dtype, but it avoids extra query for DatetimeTZDtype.
Args:
idx: the index of the column
is_index: whether it is an index or data column
"""
return not self.is_timestamp_type(idx, is_index) and is_string_dtype(
self.index_dtypes[idx] if is_index else self.dtypes[idx]
)
def _maybe_set_relaxed_qc(
self,
qc: "SnowflakeQueryCompiler",
relaxed_query_compiler: Optional["SnowflakeQueryCompiler"],
) -> "SnowflakeQueryCompiler":
if relaxed_query_compiler is not None:
qc._relaxed_query_compiler = relaxed_query_compiler
qc._relaxed_query_compiler._dummy_row_pos_mode = True
return qc
# BEGIN: hybrid auto-switching helpers