-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathsnowflake_query_compiler.py
More file actions
19895 lines (18033 loc) · 860 KB
/
snowflake_query_compiler.py
File metadata and controls
19895 lines (18033 loc) · 860 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
import typing
import uuid
from collections.abc import Hashable, Iterable, Mapping, Sequence
from datetime import timedelta, tzinfo
from functools import reduce
from typing import Any, Callable, List, Literal, Optional, TypeVar, Union, get_args
import modin.pandas as pd
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 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_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,
parse_table_name,
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,
bround,
builtin,
cast,
coalesce,
col,
concat,
corr,
count,
count_distinct,
date_from_parts,
date_part,
date_trunc,
dateadd,
dayofmonth,
dayofyear,
dense_rank,
first_value,
floor,
get,
greatest,
hour,
iff,
initcap,
is_char,
is_null,
lag,
last_day,
last_value,
lead,
least,
length,
lower,
lpad,
ltrim,
max as max_,
min as min_,
minute,
month,
negate,
not_,
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.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 (
APPLY_LABEL_COLUMN_QUOTED_IDENTIFIER,
APPLY_VALUE_COLUMN_QUOTED_IDENTIFIER,
DEFAULT_UDTF_PARTITION_SIZE,
GroupbyApplySortMethod,
check_return_variant_and_get_return_type,
create_udf_for_series_apply,
create_udtf_for_apply_axis_1,
create_udtf_for_groupby_apply,
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,
sort_apply_udtf_result_columns_by_pandas_positions,
make_series_map_snowpark_function,
SUPPORTED_SNOWFLAKE_CORTEX_FUNCTIONS_IN_APPLY,
)
from collections import defaultdict
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,
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,
)
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,
RULE_WEEK_TO_YEAR,
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,
)
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 (
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_ordered_dataframe_with_readonly_temp_table,
extract_all_duplicates,
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,
)
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.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 pd.Grouper, 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
]
T = TypeVar("T", bound=Callable[..., Any])
_CORTEX_FUNC_NAMES = [
"ClassifyText",
"Complete",
"CompleteOptions",
"EmbedText1024",
"EmbedText768",
"ExtractAnswer",
"Finetune",
"FinetuneJob",
"FinetuneStatus",
"Sentiment",
"Summarize",
"Translate",
"_classify_text",
"_complete",
"_embed_text_1024",
"_embed_text_768",
"_extract_answer",
"_finetune",
"_sentiment",
"_sse_client",
"_summarize",
"_translate",
"_util",
]
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
@_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 lazy_execution=True, upstream Modin elides some length checks that would incur queries.
lazy_execution = True
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.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]()
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]
)
@classmethod
def from_pandas(
cls, df: native_pd.DataFrame, *args: Any, **kwargs: Any
) -> "SnowflakeQueryCompiler":
# create copy of original dataframe
df = df.copy()
# encode column labels to snowflake compliant strings.
# If df.columns is a MultiIndex, it will become a list of tuples
original_column_labels = df.columns.tolist()
# if name is not set, df.columns.names will return FrozenList[None].
original_column_index_names = df.columns.names
# session.create_dataframe creates a temporary snowflake table from given pandas dataframe. Snowflake
# tables do not support duplicate column names hence column names of pandas dataframe here must be de-duplicated
# before passing this dataframe to create_dataframe() method. We de-duplicate pandas dataframe column names in
# following two steps:
# 1. Generate snowflake quoted identifiers which are duplicate free.
# 2. Extract pandas labels from generated snowflake quoted identifiers and update columns of original dataframe.
# Note: In our internal frame mapping we will continue to use original pandas labels (which may have duplicates)
data_column_snowflake_quoted_identifiers = (
generate_snowflake_quoted_identifiers_helper(
pandas_labels=original_column_labels, excluded=[]
)
)
# Extract pandas labels from snowflake quoted identifiers and reassign these new labels to pandas dataframe
# before writing to temporary table.
df.columns = [
extract_pandas_label_from_snowflake_quoted_identifier(identifier)
for identifier in data_column_snowflake_quoted_identifiers
]
# Generate snowflake quoted identifier for index columns
original_index_pandas_labels = df.index.names
index_snowflake_quoted_identifiers = (
generate_snowflake_quoted_identifiers_helper(
pandas_labels=fill_none_in_index_labels(original_index_pandas_labels),
excluded=data_column_snowflake_quoted_identifiers,
wrap_double_underscore=True,
)
)
current_df_data_column_snowflake_quoted_identifiers = (
index_snowflake_quoted_identifiers
+ data_column_snowflake_quoted_identifiers
)
# reset index so the index can be a data column in the native pandas df
# this is because write_pandas in python connector will not write the
# index column into Snowflake
# See https://github.com/snowflakedb/snowflake-connector-python/blob/main/src/snowflake/connector/pandas_tools.py
df.reset_index(
inplace=True,
names=[
extract_pandas_label_from_snowflake_quoted_identifier(identifier)
for identifier in index_snowflake_quoted_identifiers
],
)
# need to keep row_position column (or expression in the future)
# i.e., when https://snowflakecomputing.atlassian.net/browse/SNOW-767687 is done,
# replace column with expression
row_position_snowflake_quoted_identifier = (
generate_snowflake_quoted_identifiers_helper(
pandas_labels=[ROW_POSITION_COLUMN_LABEL],
excluded=current_df_data_column_snowflake_quoted_identifiers,
wrap_double_underscore=True,
)[0]
)
df[
extract_pandas_label_from_snowflake_quoted_identifier(
row_position_snowflake_quoted_identifier
)
] = np.arange(len(df))
current_df_data_column_snowflake_quoted_identifiers.append(
row_position_snowflake_quoted_identifier
)
# create snowpark df
snowpark_pandas_types, snowpark_types = infer_snowpark_types_from_pandas(df)
ordered_dataframe = create_ordered_dataframe_from_pandas(
df,
snowflake_quoted_identifiers=current_df_data_column_snowflake_quoted_identifiers,
snowpark_types=snowpark_types,
ordering_columns=[
OrderingColumn(row_position_snowflake_quoted_identifier),
],
row_position_snowflake_quoted_identifier=row_position_snowflake_quoted_identifier,
)
# construct the internal frame for the dataframe
return cls(
InternalFrame.create(
ordered_dataframe=ordered_dataframe,
data_column_pandas_labels=original_column_labels,
data_column_pandas_index_names=original_column_index_names,
# data columns appear after the index columns, but before the
# row position column.
data_column_types=snowpark_pandas_types[
len(index_snowflake_quoted_identifiers) : (
len(index_snowflake_quoted_identifiers)
+ len(data_column_snowflake_quoted_identifiers)
)
],
data_column_snowflake_quoted_identifiers=data_column_snowflake_quoted_identifiers,
index_column_pandas_labels=original_index_pandas_labels,
index_column_snowflake_quoted_identifiers=index_snowflake_quoted_identifiers,
# The columns up to position `len(index_snowflake_quoted_identifiers)`
# are the index columns.
index_column_types=snowpark_pandas_types[
: len(index_snowflake_quoted_identifiers)
],
)
)
@classmethod
def from_arrow(cls, at: Any, *args: Any, **kwargs: Any) -> "SnowflakeQueryCompiler":
return cls(at.to_pandas())
def to_dataframe(
self, nan_as_null: bool = False, allow_copy: bool = True
) -> InterchangeDataframe:
return self.to_pandas().__dataframe__(
nan_as_null=nan_as_null, allow_copy=allow_copy
)
@classmethod
def from_dataframe(cls, df: native_pd.DataFrame, data_cls: Any) -> None:
pass
@classmethod
def from_date_range(
cls,
start: Optional[pd.Timestamp],
end: Optional[pd.Timestamp],
periods: Optional[int],
freq: Optional[pd.DateOffset],
tz: Union[str, tzinfo],
left_inclusive: bool,
right_inclusive: bool,
) -> "SnowflakeQueryCompiler":
"""
Snowpark pandas implementation for generating date ranges.
Args:
start : Timestamp, optional
Left bound for generating dates.
end : Timestamp, optional
Right bound for generating dates.
periods : int
Number of periods to generate.
freq : str or DateOffset
Frequency strings can have multiples, e.g. '5H'. See
:ref:`here <timeseries.offset_aliases>` for a list of
frequency aliases.
tz : str or tzinfo
Time zone name for returning localized DatetimeIndex, for example
'Asia/Hong_Kong'. By default, the resulting DatetimeIndex is
timezone-naive.
left_inclusive : bool
Whether to include left boundary.
right_inclusive : bool
Whether to include right boundary.
Returns:
A series with generated datetime values in the target range
"""
assert freq is not None or not any(
x is None for x in [periods, start, end]
), "Must provide freq argument if no data is supplied"
remove_non_business_days = False
if freq is not None:
if isinstance(freq, CustomBusinessDay):
ErrorMessage.not_implemented("CustomBusinessDay is not supported.")
if isinstance(freq, BusinessDay):
freq = Day()
remove_non_business_days = True
# We break Day arithmetic (fixed 24 hour) here and opt for
# Day to mean calendar day (23/24/25 hour). Therefore, strip
# tz info from start and day to avoid DST arithmetic
if isinstance(freq, Day):
if start is not None:
start = start.tz_localize(None)
if end is not None:
end = end.tz_localize(None)
if isinstance(freq, Tick):
# generate nanosecond values
ns_values = generator_utils.generate_regular_range(
start, end, periods, freq
)
dt_values = ns_values.series_to_datetime()
else:
dt_values = generator_utils.generate_irregular_range(
start, end, periods, freq
)
else:
# Create a linearly spaced date_range in local time
# This is the original pandas source code:
# i8values = (
# np.linspace(0, end.value - start.value, periods, dtype="int64")
# + start.value
# )
# Here we implement it similarly as np.linspace
div = periods - 1 # type: ignore[operator]
delta = end.value * 1.0 - start.value # type: ignore[union-attr]
if div == 0:
# Only 1 period, just return the start value
ns_values = pd.Series([start.value])._query_compiler # type: ignore[union-attr]
else:
stride = delta / div
# Make sure end is included in this case
e = start.value + delta // stride * stride + stride // 2 + 1 # type: ignore[union-attr]
ns_values = generator_utils.generate_range(start.value, e, stride) # type: ignore[union-attr]
dt_values = ns_values.series_to_datetime()
dt_series = pd.Series(query_compiler=dt_values)
if remove_non_business_days:
dt_series = dt_series[dt_series.dt.dayofweek < 5]
if not left_inclusive or not right_inclusive:
if not left_inclusive and start is not None:
dt_series = dt_series[dt_series != start].reset_index(drop=True)
if not right_inclusive and end is not None:
# No need to reset_index since we only removed the tail
dt_series = dt_series[dt_series != end]
return dt_series._query_compiler
@snowpark_pandas_type_immutable_check
def copy(self) -> "SnowflakeQueryCompiler":
"""
Make a copy of this object.
Returns:
An instance of Snowflake query compiler.
"""
# InternalFrame is immutable, it's safe to use same underlying instance for
# multiple query compilers.
qc = SnowflakeQueryCompiler(self._modin_frame)
qc.snowpark_pandas_api_calls = self.snowpark_pandas_api_calls.copy()
return qc
def to_pandas(
self,
*,
statement_params: Optional[dict[str, str]] = None,
**kwargs: Any,
) -> native_pd.DataFrame:
"""
Convert underlying query compilers data to ``pandas.DataFrame``.
Args:
statement_params: Dictionary of statement level parameters to be set while executing this action.
Returns:
pandas.DataFrame
The QueryCompiler converted to pandas.
"""
result = self._modin_frame.to_pandas(statement_params, **kwargs)
if self._attrs:
result.attrs = self._attrs