-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathordered_dataframe.py
More file actions
2061 lines (1866 loc) · 94.9 KB
/
ordered_dataframe.py
File metadata and controls
2061 lines (1866 loc) · 94.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright (c) 2012-2025 Snowflake Computing Inc. All rights reserved.
#
import logging
import sys
import uuid
from collections.abc import Hashable
from dataclasses import dataclass
from typing import Any, Optional, Union
import pandas
from snowflake.snowpark._internal.type_utils import (
ColumnOrName,
ColumnOrSqlExpr,
LiteralType,
)
from snowflake.snowpark._internal.utils import parse_positional_args_to_list
from snowflake.snowpark.column import Column
from snowflake.snowpark.dataframe import DataFrame as SnowparkDataFrame
from snowflake.snowpark.dataframe_writer import DataFrameWriter
from snowflake.snowpark.functions import (
coalesce,
count,
iff,
lit,
max as max_,
not_,
row_number,
sum as sum_,
)
from snowflake.snowpark.modin.plugin._typing import AlignTypeLit, JoinTypeLit
from snowflake.snowpark.row import Row
from snowflake.snowpark.session import Session
from snowflake.snowpark.table_function import TableFunctionCall
from snowflake.snowpark.types import StructType
from snowflake.snowpark.window import Window
# 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 collections.abc import Iterable
else:
from collections.abc import Iterable
_logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class OrderingColumn:
"""
Representation of an ordering column for the dataframe. The ordering column is
used for recovering the data order for the dataframe.
"""
# The snowflake quoted identifier for the column that is used for ordering.
snowflake_quoted_identifier: str
# Whether sort the column in ascending or descending order, by default it is sort in ascending order.
ascending: bool = True
# Whether the null value comes before or after the none null values during sort, by default,
# null values comes after non-null values.
na_last: bool = True
@property
def snowpark_column(self) -> Column:
"""
The corresponding SnowparkColumn that can be used for snowpark
dataframe for sorting.
"""
col = Column(self.snowflake_quoted_identifier)
if self.ascending and self.na_last:
return col.asc_nulls_last()
elif self.ascending and not self.na_last:
return col.asc_nulls_first()
elif not self.ascending and self.na_last:
return col.desc_nulls_last()
else: # i.e., not self.ascending and not self.na_last:
return col.desc_nulls_first()
def reverse(self) -> "OrderingColumn":
"""
Generate a reversed OrderingColumn. To reverse the order of an `OrderingColumn`, we need to reverse both
`ascending` and `na_last`. For example, an `OrderingColumn`( "column1" with ascending=True and na_last=False):
SELECT column1
FROM VALUES (1), (null), (2), (null), (3)
ORDER BY column1
ASC NULLS FIRST;
The results will be (null), (null), 1, 2, 3.
To reverse the order, the new `OrderingColumn` will be "column1" with ascending=False and na_last=True:
SELECT column1
FROM VALUES (1), (null), (2), (null), (3)
ORDER BY column1
DESC NULLS LAST;
The results become 3, 2, 1, (null), (null).
Returns:
The reversed column.
"""
return OrderingColumn(
snowflake_quoted_identifier=self.snowflake_quoted_identifier,
ascending=not self.ascending,
na_last=not self.na_last,
)
class DataFrameReference:
"""
A class for referencing a SnowparkDataFrame object and providing access to its schema,
which is designed to enable the mutability of Snowpark DataFrame and sharing across different OrderedDataFrame.
"""
# Snowflake quoted identifiers of ALL Snowpark dataframe columns that is cached in the class.
# This must be in the same length and order as the Snowpark dataframe.
# Note that this field is Optional, when it is None, it doesn't mean the Snowpark dataframe
# doesn't have any column, it only means the quoted identifiers of the Snowpark dataframe isn't
# cached by the class.
cached_snowflake_quoted_identifiers_tuple: Optional[tuple[str, ...]]
def __init__(
self,
snowpark_dataframe: SnowparkDataFrame,
snowflake_quoted_identifiers: Optional[list[str]] = None,
) -> None:
"""
Constructor for DataFrameReference.
Args:
snowpark_dataframe: SnowparkDataFrame. The Snowark dataframe that it refers to
snowflake_quoted_identifiers: the snowflake quoted identifiers for the Snowpark dataframe that it
refers to. Must include identifiers for all columns, not a subset.
"""
self.snowpark_dataframe = snowpark_dataframe
self._id = uuid.uuid4() # for debug purpose only
if snowflake_quoted_identifiers is not None:
self.cached_snowflake_quoted_identifiers_tuple = tuple(
snowflake_quoted_identifiers
)
else:
self.cached_snowflake_quoted_identifiers_tuple = None
@property
def schema(self) -> StructType:
"""
Get the schema of the referenced SnowparkDataFrame.
Returns:
StructType: The schema of the referenced SnowparkDataFrame.
"""
return self.snowpark_dataframe.schema
@property
def snowflake_quoted_identifiers(self) -> list[str]:
"""
The snowflake quoted identifiers for all snowpark dataframe columns.
"""
if self.cached_snowflake_quoted_identifiers_tuple is None:
# if there is no cached snowflake quoted identifiers, reach to the
# Snowpark schema to fetch the identifiers. Note this will trigger one query
# describe call to server.
self.cached_snowflake_quoted_identifiers_tuple = tuple(
f.column_identifier.quoted_name for f in self.schema.fields
)
return list(self.cached_snowflake_quoted_identifiers_tuple)
def _raise_if_identifier_not_exists(
identifiers: list[str], existing_identifiers: list[str], category: str = ""
) -> None:
"""Checks whether all elements in `identifiers` existing in `existing_identifiers`"""
existing_identifiers_set = set(existing_identifiers)
for identifier in identifiers:
if not isinstance(identifier, str):
raise AssertionError(
f"Only column identifier with string type is allowed for {category}"
)
if identifier not in existing_identifiers_set:
raise AssertionError(
f"{category} {identifier} not found in {existing_identifiers}"
)
class OrderedDataFrame:
"""
A mutable class representing an ordered DataFrame with projection columns and ordering columns.
It allows you to specify a DataFrameReference to reference the source Snowpark DataFrame,
select projected columns, define ordering columns and the row position identifier. We only
provide a minimal set of dataframe operation methods in this class, which are enough to implement
pandas dataframe operations.
Note:
- This class maintains project columns and ordering columns, where some ordering columns may
not be in project columns.
- All identifiers used here are Snowflake quoted identifiers.
- Currently, only select and ensure_row_position_column operation will not update
the DataFrameReference inside the class.
- "Order" or "Ordering" is defined as the order of the source Snowpark DataFrame, which may
or may not exist. If not exist, we assign a default order that all projected columns will
be used as ordering columns
- Ordering semantics,
- `select`, `filter`, `limit` and `dropna` don't change ordering columns.
- `sort` will update ordering columns by the specified columns.
- `group_by` will use the grouped columns as ordering columns.
- `rename` will keep the original ordering columns with updated names.
- `join` with `right` join method preserves the right frame order, followed by self/left
frame order. For all other join methods, the result preserves the self/left frame order
first, followed by the right frame order.
- `align` sorts lexicographically on the align keys for `outer` method. For `left`, it
preserves the left order first, and then followed by right order, same as join.
- `union_all`, `pivot`, `unpivot` and `agg` uses the default order.
"""
# A DataFrameReference object referencing the source Snowpark DataFrame.
_dataframe_ref: DataFrameReference
# The snowflake quoted identifiers for projected columns, which is represented as tuple of
# string to ensure immutability. Note that the projected columns is a subset of snowflake quoted
# identifiers of the underlying Snowpark DataFrame in _dataframe_ref.
_projected_column_snowflake_quoted_identifiers_tuple: tuple[str, ...]
# a tuple of OrderingColumn objects that defines the order of the current OrderedDataFrame
# It must be part of projected columns
_ordering_columns_tuple: tuple[OrderingColumn, ...]
# row position snowflake quoted identifier
row_position_snowflake_quoted_identifier: Optional[str]
# row count snowflake quoted identifier
row_count_snowflake_quoted_identifier: Optional[str]
def __init__(
self,
dataframe_ref: DataFrameReference,
*,
projected_column_snowflake_quoted_identifiers: Optional[list[str]] = None,
ordering_columns: Optional[list[OrderingColumn]] = None,
row_position_snowflake_quoted_identifier: Optional[str] = None,
row_count_snowflake_quoted_identifier: Optional[str] = None,
) -> None:
self._dataframe_ref = dataframe_ref
all_existing_snowflake_quoted_identifiers = (
self._dataframe_ref.snowflake_quoted_identifiers
)
# If projected_columns is not specified, it will be all columns in the source Snowpark DataFrame
if projected_column_snowflake_quoted_identifiers:
_raise_if_identifier_not_exists(
projected_column_snowflake_quoted_identifiers,
all_existing_snowflake_quoted_identifiers,
"projected column",
)
self._projected_column_snowflake_quoted_identifiers_tuple = tuple(
projected_column_snowflake_quoted_identifiers
)
else:
self._projected_column_snowflake_quoted_identifiers_tuple = tuple(
all_existing_snowflake_quoted_identifiers
)
# If ordering_columns is not specified, all projected columns will be used as
# ordering columns by default.
# Note that an ordering column may not be in projected columns,
# and only need to be in the source Snowpark dataframe
if ordering_columns is not None:
_raise_if_identifier_not_exists(
[column.snowflake_quoted_identifier for column in ordering_columns],
all_existing_snowflake_quoted_identifiers,
"ordering column",
)
self._ordering_columns_tuple = tuple(ordering_columns)
else:
self._ordering_columns_tuple = tuple(
OrderingColumn(column)
for column in self._projected_column_snowflake_quoted_identifiers_tuple
)
assert self.ordering_columns, "ordering_columns cannot be empty"
if row_position_snowflake_quoted_identifier:
_raise_if_identifier_not_exists(
[row_position_snowflake_quoted_identifier],
all_existing_snowflake_quoted_identifiers,
"row position column",
)
if row_count_snowflake_quoted_identifier:
_raise_if_identifier_not_exists(
[row_count_snowflake_quoted_identifier],
all_existing_snowflake_quoted_identifiers,
"row count column",
)
self.row_position_snowflake_quoted_identifier = (
row_position_snowflake_quoted_identifier
)
self.row_count_snowflake_quoted_identifier = (
row_count_snowflake_quoted_identifier
)
@property
def ordering_columns(self) -> list[OrderingColumn]:
return list(self._ordering_columns_tuple)
def _ordering_snowpark_columns(self) -> list[Column]:
"""
Returns a list of SnowparkColumns that can be applied to the snowpark
dataframe to derive the ordered result.
Returns:
List of SnowparkColumn
"""
return [col.snowpark_column for col in self.ordering_columns]
@property
def ordering_column_snowflake_quoted_identifiers(self) -> list[str]:
"""
Get all snowflake quoted identifiers for the ordering columns.
Return:
List of snowflake quoted identifier for the ordering columns
"""
return [col.snowflake_quoted_identifier for col in self.ordering_columns]
def _row_position_snowpark_column(self) -> Column:
"""
Returns a row position Snowpark column for the dataframe.
If row position column already exist in the current dataframe, it will be directly returned.
Otherwise, the row position column will be generated based on the ordering columns.
Return:
SnowparkColumn to get the row position column.
"""
if self.row_position_snowflake_quoted_identifier is not None:
return Column(self.row_position_snowflake_quoted_identifier)
return row_number().over(Window.order_by(self._ordering_snowpark_columns())) - 1
@property
def projected_column_snowflake_quoted_identifiers(self) -> list[str]:
"""
Returns:
List of snowflake quoted identifiers for the projected columns of the current ordered dataframe.
"""
return list(self._projected_column_snowflake_quoted_identifiers_tuple)
def ensure_row_position_column(self) -> "OrderedDataFrame":
"""
Returns an OrderedDataFrame with a row position column, and the row position column is guaranteed to
be part of the projected column.
If self.row_position_snowflake_quoted_identifier is not None, there is already a row position column,
no new row position column will be generated.
Note that the returned OrderedDataframe retains the original ordering columns.
"""
if self.row_position_snowflake_quoted_identifier is not None:
# if the row position column is not part of the projected columns, do a select to make sure
# the row position column becomes part of the projected columns.
if (
self.row_position_snowflake_quoted_identifier
not in self.projected_column_snowflake_quoted_identifiers
):
return self.select(
self.projected_column_snowflake_quoted_identifiers
+ [self.row_position_snowflake_quoted_identifier]
)
else:
return self
from snowflake.snowpark.modin.plugin._internal.utils import (
ROW_POSITION_COLUMN_LABEL,
)
row_position_snowflake_quoted_identifier = (
self.generate_snowflake_quoted_identifiers(
pandas_labels=[ROW_POSITION_COLUMN_LABEL],
wrap_double_underscore=True,
)[0]
)
ordered_dataframe = self.select(
*self.projected_column_snowflake_quoted_identifiers,
self._row_position_snowpark_column().as_(
row_position_snowflake_quoted_identifier
),
)
# inplace update so dataframe_ref can be shared. Note that we keep
# the original ordering columns.
ordered_dataframe.row_position_snowflake_quoted_identifier = (
row_position_snowflake_quoted_identifier
)
return ordered_dataframe
def ensure_row_count_column(self) -> "OrderedDataFrame":
"""
Returns an OrderedDataFrame with a row count column, and the row count column is guaranteed to
be part of the projected column.
If self.row_count_snowflake_quoted_identifier is not None, there is already a row count column,
no new row count column will be generated.
Note that the returned OrderedDataframe retains the original ordering columns.
"""
if self.row_count_snowflake_quoted_identifier is not None:
# if the row count column is not part of the projected columns, do a select to make sure
# the row count column becomes part of the projected columns.
if (
self.row_count_snowflake_quoted_identifier
not in self.projected_column_snowflake_quoted_identifiers
):
return self.select(
self.projected_column_snowflake_quoted_identifiers
+ [self.row_count_snowflake_quoted_identifier]
)
else:
return self
from snowflake.snowpark.modin.plugin._internal.utils import (
ROW_COUNT_COLUMN_LABEL,
)
row_count_snowflake_quoted_identifier = (
self.generate_snowflake_quoted_identifiers(
pandas_labels=[ROW_COUNT_COLUMN_LABEL],
wrap_double_underscore=True,
)[0]
)
ordered_dataframe = self.select(
*self.projected_column_snowflake_quoted_identifiers,
count("*").over().as_(row_count_snowflake_quoted_identifier),
)
# inplace update so dataframe_ref can be shared. Note that we keep
# the original ordering columns.
ordered_dataframe.row_count_snowflake_quoted_identifier = (
row_count_snowflake_quoted_identifier
)
return ordered_dataframe
def materialize_row_count(self) -> int:
"""
Perform a query to retrieve the row count of this OrderedDataFrame.
Use this function in place of ensure_row_count_column() in scenarios where the extra
query is acceptable, and the embedded `COUNT(*) OVER()` window operation would be too expensive.
Performing a naked `COUNT(*)` and avoiding a potential window function or cross join is
more performance in these scenarios.
"""
return self._dataframe_ref.snowpark_dataframe.count()
def generate_snowflake_quoted_identifiers(
self,
*,
pandas_labels: list[Hashable],
excluded: Optional[list[str]] = None,
wrap_double_underscore: Optional[bool] = False,
) -> list[str]:
"""
See detailed docstring of generate_snowflake_quoted_identifiers_helper in
snowflake/snowpark/modin/plugin/_internal/utils.
The only difference between this method and generate_snowflake_quoted_identifiers_helper is
that all snowflake quoted identifier of the underlying snowpark dataframe in the dataframe_ref
will be added to `excluded`.
"""
from snowflake.snowpark.modin.plugin._internal.utils import (
generate_snowflake_quoted_identifiers_helper,
)
if not excluded:
excluded = []
existing_identifiers = self._dataframe_ref.snowflake_quoted_identifiers
return generate_snowflake_quoted_identifiers_helper(
pandas_labels=pandas_labels,
excluded=excluded + existing_identifiers,
wrap_double_underscore=wrap_double_underscore,
)
@property
def schema(self) -> StructType:
"""Get the schema of OrderedDataFrame. It only includes the schema of projected columns."""
quoted_identifier_to_field_mapping = {
field.column_identifier.quoted_name: field
for field in self._dataframe_ref.schema.fields
}
return StructType(
[
quoted_identifier_to_field_mapping[identifier]
for identifier in self.projected_column_snowflake_quoted_identifiers
if identifier in quoted_identifier_to_field_mapping
]
)
@property
def queries(self) -> dict[str, list[str]]:
"""Get underlying SQL queries of an OrderedDataFrame."""
return self._dataframe_ref.snowpark_dataframe.queries
@property
def session(self) -> Session:
"""Returns a Snowpark session object associated with this ordered dataframe."""
return self._dataframe_ref.snowpark_dataframe.session
def _get_active_column_snowflake_quoted_identifiers(
self,
include_ordering_columns: bool = True,
include_row_position_column: bool = True,
include_row_count_column: bool = True,
) -> list[str]:
"""
Get the snowflake quoted identifiers for columns that are active for the ordering dataframe.
The columns that are active for an ordering dataframe includes the projected columns, ordering columns
and row position column if exists, ordering columns and row position column can be excluded based on
configuration.
Args:
include_ordering_columns: whether include the snowflake quoted identifiers for the ordering columns in the result
include_row_position_column: whether include the snowflake quoted identifier for the row position column in the result
include_row_count_column: whether or not to include the snowflake quoted identifier for the row count column in the result
Returns:
List of the snowflake quoted identifiers for the in use columns.
"""
column_quoted_identifiers = self.projected_column_snowflake_quoted_identifiers
if include_ordering_columns:
extra_ordering_column_quoted_identifiers = [
quoted_identifier
for quoted_identifier in self.ordering_column_snowflake_quoted_identifiers
if quoted_identifier not in column_quoted_identifiers
]
column_quoted_identifiers.extend(extra_ordering_column_quoted_identifiers)
if (
include_row_position_column
and self.row_position_snowflake_quoted_identifier is not None
):
if (
self.row_position_snowflake_quoted_identifier
not in column_quoted_identifiers
):
column_quoted_identifiers.append(
self.row_position_snowflake_quoted_identifier
)
if (
include_row_count_column
and self.row_count_snowflake_quoted_identifier is not None
):
if (
self.row_count_snowflake_quoted_identifier
not in column_quoted_identifiers
):
column_quoted_identifiers.append(
self.row_count_snowflake_quoted_identifier
)
return column_quoted_identifiers
def _extract_quoted_identifiers_from_column_or_name(
self, col: ColumnOrName, active_columns: list[str]
) -> list[str]:
"""
Extract the snowflake quoted identifiers out of a Column or column name with following rule:
1) when it is a Snowpark column, only column with alias name can be handled, the alias name is
extracted as the quoted identifier.
2) when it is a str
a) if it is a start (*), then all projected columns snowflake quoted identifiers are added
b) otherwise, it is treated as a name of existing column, and a validation check is applied
to ensure that only active columns of the current ordered dataframe can be used
e) AssertionError is raised for all cases can not be handled.
Args:
col: ColumnOrName, Snowpark Column expression or column name
active_columns: the active columns of the current ordered dataframe to perform the check against,
includes all projected columns, row position columns and ordering columns.
"""
from snowflake.snowpark.modin.plugin._internal.utils import (
is_valid_snowflake_quoted_identifier,
)
if isinstance(col, Column):
if col._expression.pretty_name == "ALIAS":
column_name = col._named().name
assert is_valid_snowflake_quoted_identifier(
column_name
), f"Invalid snowflake quoted identifier {column_name} used"
return [column_name]
else:
raise AssertionError(
f"Column {col} is invalid, only column with alias name is allowed!"
)
elif isinstance(col, str):
if col == "*":
# star adds all projected columns to the result
return self.projected_column_snowflake_quoted_identifiers
else:
if col in active_columns:
return [col]
else:
raise AssertionError(
f"Column {col} is not in active columns {active_columns}"
)
else:
raise AssertionError(
f"Can not extract name for {col}, only Column with alias name or str can be handled!"
)
def select(
self,
*cols: Union[
Union[ColumnOrName, TableFunctionCall],
Iterable[Union[ColumnOrName, TableFunctionCall]],
],
) -> "OrderedDataFrame":
"""
Returns a DataFrame by selecting the specified columns.
Any existing columns that are not in `cols` will be still retained in the
source dataframe reference/snowpark DataFrame (unless `cols` contains TableFunctionCall object),
which will be shared across multiple ordered DataFrames.
Note that ordering columns will not be changed.
See detailed docstring in Snowpark DataFrame's select. Compared with Snowpark DataFrame's select,
this select has the following restrictions:
1. To select an existing column, must use column name instead of column expression. For example:
select(col("a")) is not allowed, but select("a") is allowed. Note: only existing active columns
can be selected, which includes projected columns, ordering columns, row position column and
row_count column.
2. if you want to select a Column object, it must have an alias.
3. You can't select an aggregated column anymore (e.g., `max("a").as_("a")`).
To select an aggregated column, use `agg()`.
"""
exprs = parse_positional_args_to_list(*cols)
assert exprs, "The input of select() cannot be empty"
# a list of new Column objects to be selected for new OrderedDataFrame
new_snowpark_column_objects: list[Column] = []
# a list of snowflake quoted identifiers as projected columns for new OrderedDataFrame
new_projected_columns: list[str] = []
active_columns = self._get_active_column_snowflake_quoted_identifiers()
for e in exprs:
if isinstance(e, TableFunctionCall):
# we couldn't handle TableFunctionCall, so just use the original select
snowpark_dataframe = self._dataframe_ref.snowpark_dataframe.select(
*cols
)
return OrderedDataFrame(DataFrameReference(snowpark_dataframe))
elif isinstance(e, (Column, str)):
column_names = self._extract_quoted_identifiers_from_column_or_name(
e, active_columns
)
new_projected_columns.extend(column_names)
if isinstance(e, Column):
new_snowpark_column_objects.append(e)
else:
raise AssertionError(
"Only columns with alias name, column names and table functions are accepted"
)
dataframe_ref = self._dataframe_ref
if len(new_snowpark_column_objects) > 0:
existing_columns = self._dataframe_ref.snowflake_quoted_identifiers
# this is an inplace update of the snowpark dataframe so it can be shared
dataframe_ref.snowpark_dataframe = dataframe_ref.snowpark_dataframe.select(
existing_columns + new_snowpark_column_objects
)
# update the managed quoted identifiers for the dataframe reference to the new set
# of identifiers.
new_column_identifiers = existing_columns + [
quoted_identifier
for quoted_identifier in new_projected_columns
if quoted_identifier not in existing_columns
]
dataframe_ref.cached_snowflake_quoted_identifiers_tuple = tuple(
new_column_identifiers
)
_logger.debug(
f"The Snowpark DataFrame in DataFrameReference with id={dataframe_ref._id} is updated"
)
return OrderedDataFrame(
dataframe_ref,
projected_column_snowflake_quoted_identifiers=new_projected_columns,
# keep the original ordering columns and row position column
ordering_columns=self.ordering_columns,
row_position_snowflake_quoted_identifier=self.row_position_snowflake_quoted_identifier,
row_count_snowflake_quoted_identifier=self.row_count_snowflake_quoted_identifier,
)
def dropna(
self,
how: str = "any",
thresh: Optional[int] = None,
subset: Optional[Union[str, Iterable[str]]] = None,
) -> "OrderedDataFrame":
"""
Returns a new DataFrame that excludes all rows containing fewer than
a specified number of non-null and non-NaN values in the specified
columns. Note that ordering columns will not be changed.
See detailed docstring in Snowpark DataFrame's dropna.
"""
projected_dataframe_ref = self._to_projected_snowpark_dataframe_reference(
include_ordering_columns=True
)
snowpark_dataframe = projected_dataframe_ref.snowpark_dataframe.dropna(
how=how, thresh=thresh, subset=subset
)
# dropna doesn't change the column quoted identifiers
result_column_quoted_identifiers = (
projected_dataframe_ref.snowflake_quoted_identifiers
)
return OrderedDataFrame(
DataFrameReference(snowpark_dataframe, result_column_quoted_identifiers),
projected_column_snowflake_quoted_identifiers=result_column_quoted_identifiers,
ordering_columns=self.ordering_columns,
)
def union_all(self, other: "OrderedDataFrame") -> "OrderedDataFrame":
"""
Returns a new DataFrame that contains all the rows in the current DataFrame
and another DataFrame (``other``), including any duplicate rows. Both input
DataFrames must contain the same number of columns.
Note that the ordering columns will become all columns in the DataFrame.
TODO SNOW-966319: set ordering columns for union_all
See detailed docstring in Snowpark DataFrame's union_all.
"""
self_snowpark_dataframe_ref = self._to_projected_snowpark_dataframe_reference()
other_snowpark_dataframe_ref = (
other._to_projected_snowpark_dataframe_reference()
)
# union all result uses the snowflake quoted identifiers of self snowpark dataframe
result_column_quoted_identifiers = (
self_snowpark_dataframe_ref.snowflake_quoted_identifiers
)
snowpark_dataframe = self_snowpark_dataframe_ref.snowpark_dataframe.union_all(
other_snowpark_dataframe_ref.snowpark_dataframe
)
return OrderedDataFrame(
DataFrameReference(snowpark_dataframe, result_column_quoted_identifiers),
projected_column_snowflake_quoted_identifiers=result_column_quoted_identifiers,
)
def _extract_aggregation_result_column_quoted_identifiers(
self,
*agg_exprs: ColumnOrName,
) -> list[str]:
"""
Extract the quoted identifiers for the aggregation columns.
"""
exprs = parse_positional_args_to_list(*agg_exprs)
# extract the aggregation function name
result_column_quoted_identifiers: list[str] = []
active_columns = self._get_active_column_snowflake_quoted_identifiers()
for e in exprs:
if isinstance(e, (Column, str)):
column_names = self._extract_quoted_identifiers_from_column_or_name(
e, active_columns
)
result_column_quoted_identifiers.extend(column_names)
else:
raise AssertionError(
"Only column name or column expression with alias name can be used as aggregation expression"
)
return result_column_quoted_identifiers
def group_by(
self,
cols: Iterable[str],
*agg_exprs: ColumnOrName,
) -> "OrderedDataFrame":
"""
Groups rows by the columns specified by expressions (similar to GROUP BY in
SQL), which are followed by aggregations.
Note that the ordering columns will become `cols`.
Args:
cols: A list of Snowflake quoted identifiers for group by. We don't allow Column objects
here, which is different from Snowpark DataFrame's group_by
agg_exprs: aggregation expressions
See detailed docstring in Snowpark DataFrame's group_by.
"""
# the result columns for groupby aggregate are the groupby columns + the aggregation columns
result_column_quoted_identifiers: list[str] = [
identifier for identifier in cols
] # add the groupby columns
# add the aggregation columns
result_column_quoted_identifiers += (
self._extract_aggregation_result_column_quoted_identifiers(*agg_exprs)
)
return OrderedDataFrame(
DataFrameReference(
self._dataframe_ref.snowpark_dataframe.group_by(cols).agg(*agg_exprs),
snowflake_quoted_identifiers=result_column_quoted_identifiers,
),
projected_column_snowflake_quoted_identifiers=result_column_quoted_identifiers,
ordering_columns=[OrderingColumn(identifier) for identifier in cols],
)
def sort(
self,
*cols: Union[OrderingColumn, Iterable[OrderingColumn]],
) -> "OrderedDataFrame":
"""
Sorts a DataFrame by the specified expressions (similar to ORDER BY in SQL).
Note that this is not a real "sort", but just set the ordering columns.
"""
# parse cols to get the new Ordering columns
ordering_columns = parse_positional_args_to_list(*cols)
# check all ordering_columns are in the current active columns
_raise_if_identifier_not_exists(
[column.snowflake_quoted_identifier for column in ordering_columns],
self._get_active_column_snowflake_quoted_identifiers(),
"ordering column",
)
# check if the column is the same as the ordering column now
if ordering_columns == self.ordering_columns:
return self
return OrderedDataFrame(
self._to_projected_snowpark_dataframe_reference(
include_row_count_column=True, include_ordering_columns=True
),
projected_column_snowflake_quoted_identifiers=self.projected_column_snowflake_quoted_identifiers,
ordering_columns=ordering_columns,
# should reset the row position column since ordering is updated
row_position_snowflake_quoted_identifier=None,
# No need to reset row count, since sorting should not add/drop rows.
row_count_snowflake_quoted_identifier=self.row_count_snowflake_quoted_identifier,
)
def pivot(
self,
pivot_col: ColumnOrName,
values: Optional[Union[Iterable[LiteralType]]] = None,
default_on_null: Optional[LiteralType] = None,
*agg_exprs: Union[Column, tuple[ColumnOrName, str], dict[str, str]],
) -> "OrderedDataFrame":
"""
Rotates this DataFrame by turning the unique values from one column in the input
expression into multiple columns and aggregating results (followed by `agg_exprs`)
where required on any remaining column values.
Note that the ordering columns will become all columns in the DataFrame.
See detailed docstring in Snowpark DataFrame's pivot.
"""
snowpark_dataframe = self.to_projected_snowpark_dataframe()
return OrderedDataFrame(
# the pivot result columns for dynamic pivot are data dependent, a schema call is required
# to know all the quoted identifiers for the pivot result.
DataFrameReference(
snowpark_dataframe.pivot(
pivot_col=pivot_col,
values=values,
default_on_null=default_on_null,
).agg(*agg_exprs)
)
)
def unpivot(
self,
value_column: str,
name_column: str,
column_list: list[str],
col_mapper: Optional[dict[str, str]] = None,
) -> "OrderedDataFrame":
"""
Rotates a table by transforming columns into rows.
UNPIVOT is a relational operator that accepts two columns (from a table or subquery),
along with a list of columns, and generates a row for each column specified in the list.
Note that the ordering columns will become all columns in the DataFrame.
Prior to the unpivot the dataframe reference will be updated to avoid ambigious column
issues. An optional map, column_list_name_map can be used to map temporary column names
back to the expected column names used for the variable column in unpivot.
Args:
value_column: name of the value column, typically "values"
name_column: name of the variable column, containing the column names from the unpivot
column_list: list of columns to unpivot
col_mapper: a mapping between the current column_list names and the desired
column names which would be used in the new name_column
"""
# check columns in column_list are in projected columns
_raise_if_identifier_not_exists(
[quoted_identifier for quoted_identifier in column_list],
self.projected_column_snowflake_quoted_identifiers,
"unpivot column list",
)
# Apply a select to project only the desired columns, and return a non-sharable
# dataframe reference because unpivot is destructive to the types of alignment/join
# optimizations intended.
projected_dataframe_ref = self._to_projected_snowpark_dataframe_reference(
col_mapper=col_mapper
)
unpivot_column_list = column_list
# Remap the columns from the projection back to the desired names. This is
# particularly important if the projection has applied transformations to the
# columns to normalize the data.
if col_mapper is not None:
unpivot_column_list = []
for col in column_list:
if col in col_mapper:
unpivot_column_list.append(col_mapper[col])
else:
unpivot_column_list.append(col)
# all columns other than the unpivot columns are retained in the result
result_column_quoted_identifiers = [
quoted_identifier
for quoted_identifier in projected_dataframe_ref.snowflake_quoted_identifiers
if quoted_identifier not in unpivot_column_list
]
# add the name column and value colum to the result
result_column_quoted_identifiers += [name_column, value_column]
return OrderedDataFrame(
DataFrameReference(
projected_dataframe_ref.snowpark_dataframe.unpivot(
value_column=value_column,
name_column=name_column,
column_list=unpivot_column_list,
include_nulls=True,
),
snowflake_quoted_identifiers=result_column_quoted_identifiers,
),
projected_column_snowflake_quoted_identifiers=result_column_quoted_identifiers,
)
def agg(
self,
*exprs: ColumnOrName,
) -> "OrderedDataFrame":
"""
Aggregates the data in the DataFrame. Use this method if you don't need to
group the data. Note that the ordering columns will become all columns in the DataFrame.
See detailed docstring in Snowpark DataFrame's agg.
"""
snowpark_dataframe = self._dataframe_ref.snowpark_dataframe.agg(*exprs)
result_column_quoted_identifiers = (
self._extract_aggregation_result_column_quoted_identifiers(*exprs)
)
return OrderedDataFrame(
DataFrameReference(snowpark_dataframe, result_column_quoted_identifiers),
projected_column_snowflake_quoted_identifiers=result_column_quoted_identifiers,
)
def _deduplicate_active_column_snowflake_quoted_identifiers(
self,
against: "OrderedDataFrame",
include_ordering_columns: bool = True,
include_row_position_column: bool = True,
include_row_count_column: bool = True,
) -> "OrderedDataFrame":
"""
Deduplicate all active column snowflake quoted identifiers of the current OrderedDataFrame against the
given OrderedDataFrame. The active columns involve projected columns, ordering columns and row position column.
For example:
current dataframe has projected columns = ['"A"', '"B"', '"C"'], ordering columns = ['"D"', '"A"'], and
row position column = ['"row_pos"']
and given ordered dataframe to de-duplicate against has
projected columns = ['"A"', '"B"', '"E"'], ordering columns = ['"A"', '"E"'], and
row position column = ['"row_pos"']
After deduplication, the result ordered dataframe will have
projected_columns = ['"A_<suffix>"', '"B_<suffix>"', '"C"'], ordering columns = ['"D"', '"A_<suffix>"'],
and row position column = ['"row_pos_<suffix>"']
Where column '"A"', '"B"' and '"row_pos"' is deduplicated since they conflict with the columns in self.
Args:
against: The OrderedDataFrame to deduplicate
include_ordering_columns: Whether to include the ordering columns during deduplication.
include_row_position_column: Whether to include the row position column during deduplication.
include_row_count_column: Whether to include the row count column during deduplication.
Returns:
An OrderedDataFrame with ordering and projected columns properly deduplicated
"""
from snowflake.snowpark.modin.plugin._internal.utils import (
unquote_name_if_quoted,
)
quoted_identifiers_to_deduplicate = (
self._get_active_column_snowflake_quoted_identifiers(
include_ordering_columns=include_ordering_columns,
include_row_position_column=include_row_position_column,
include_row_count_column=include_row_count_column,
)
)
quoted_identifiers_to_deduplicate_against = (
against._get_active_column_snowflake_quoted_identifiers(
include_ordering_columns=include_ordering_columns,
include_row_position_column=include_row_position_column,
include_row_count_column=include_row_count_column,
)
)
original_projected_columns_quoted_identifiers = (
self.projected_column_snowflake_quoted_identifiers
)