-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathcolumn.py
More file actions
1580 lines (1400 loc) · 59.5 KB
/
column.py
File metadata and controls
1580 lines (1400 loc) · 59.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# Copyright (c) 2012-2025 Snowflake Computing Inc. All rights reserved.
#
import sys
import typing
from typing import Any, Optional, Union
import snowflake.snowpark
import snowflake.snowpark._internal.proto.generated.ast_pb2 as proto
from snowflake.snowpark._internal.analyzer.binary_expression import (
Add,
And,
BitwiseAnd,
BitwiseOr,
BitwiseXor,
Divide,
EqualNullSafe,
EqualTo,
GreaterThan,
GreaterThanOrEqual,
LessThan,
LessThanOrEqual,
Multiply,
NotEqualTo,
Or,
Pow,
Remainder,
Subtract,
)
from snowflake.snowpark._internal.analyzer.expression import (
CaseWhen,
Collate,
Expression,
InExpression,
Like,
Literal,
MultipleExpression,
NamedExpression,
RegExp,
ScalarSubquery,
Star,
SubfieldInt,
SubfieldString,
UnresolvedAttribute,
WithinGroup,
)
from snowflake.snowpark._internal.analyzer.sort_expression import (
Ascending,
Descending,
NullsFirst,
NullsLast,
SortOrder,
)
from snowflake.snowpark._internal.analyzer.unary_expression import (
Alias,
Cast,
IsNaN,
IsNotNull,
IsNull,
Not,
UnaryMinus,
UnresolvedAlias,
)
from snowflake.snowpark._internal.ast.utils import (
build_expr_from_python_val,
build_expr_from_snowpark_column_or_python_val,
build_expr_from_snowpark_column_or_sql_str,
create_ast_for_column,
snowpark_expression_to_ast,
with_src_position,
)
from snowflake.snowpark._internal.type_utils import (
VALID_PYTHON_TYPES_FOR_LITERAL_VALUE,
ColumnOrLiteral,
ColumnOrLiteralStr,
ColumnOrName,
ColumnOrSqlExpr,
LiteralType,
type_string_to_type_object,
)
from snowflake.snowpark._internal.utils import (
parse_positional_args_to_list,
publicapi,
quote_name,
)
from snowflake.snowpark.types import (
DataType,
IntegerType,
StringType,
TimestampTimeZone,
TimestampType,
ArrayType,
MapType,
StructType,
)
from snowflake.snowpark.window import Window, WindowSpec
# Python 3.8 needs to use typing.Iterable because collections.abc.Iterable is not subscriptable
# Python 3.9 can use both
# Python 3.10 needs to use collections.abc.Iterable because typing.Iterable is removed
if sys.version_info <= (3, 9):
from typing import Iterable
else:
from collections.abc import Iterable
def _to_col_if_lit(
col: Union[ColumnOrLiteral, "snowflake.snowpark.DataFrame"], func_name: str
) -> "Column":
if isinstance(col, (Column, snowflake.snowpark.DataFrame, list, tuple, set)):
return col
elif isinstance(col, VALID_PYTHON_TYPES_FOR_LITERAL_VALUE):
return Column(Literal(col), _emit_ast=False)
else: # pragma: no cover
raise TypeError(
f"'{func_name}' expected Column, DataFrame, Iterable or LiteralType, got: {type(col)}"
)
def _to_col_if_sql_expr(col: ColumnOrSqlExpr, func_name: str) -> "Column":
if isinstance(col, Column):
return col
elif isinstance(col, str):
return Column._expr(col)
else:
raise TypeError(
f"'{func_name}' expected Column or str as SQL expression, got: {type(col)}"
)
def _to_col_if_str(col: ColumnOrName, func_name: str) -> "Column":
if isinstance(col, Column):
return col
elif isinstance(col, str):
return Column(col)
else:
raise TypeError(
f"'{func_name.upper()}' expected Column or str, got: {type(col)}"
)
def _to_col_if_str_or_int(col: Union[ColumnOrName, int], func_name: str) -> "Column":
if isinstance(col, Column):
return col
elif isinstance(col, str):
return Column(col)
elif isinstance(col, int):
return Column(Literal(col))
else: # pragma: no cover
raise TypeError(
f"'{func_name.upper()}' expected Column, int or str, got: {type(col)}"
)
class Column:
"""Represents a column or an expression in a :class:`DataFrame`.
To access a Column object that refers a column in a :class:`DataFrame`, you can:
- Use the column name.
- Use the :func:`functions.col` function.
- Use the :func:`DataFrame.col` method.
- Use the index operator ``[]`` on a dataframe object with a column name.
- Use the dot operator ``.`` on a dataframe object with a column name.
>>> from snowflake.snowpark.functions import col
>>> df = session.create_dataframe([["John", 1], ["Mike", 11]], schema=["name", "age"])
>>> df.select("name").collect()
[Row(NAME='John'), Row(NAME='Mike')]
>>> df.select(col("name")).collect()
[Row(NAME='John'), Row(NAME='Mike')]
>>> df.select(df.col("name")).collect()
[Row(NAME='John'), Row(NAME='Mike')]
>>> df.select(df["name"]).collect()
[Row(NAME='John'), Row(NAME='Mike')]
>>> df.select(df.name).collect()
[Row(NAME='John'), Row(NAME='Mike')]
Snowflake object identifiers, including column names, may or may not be case sensitive depending on a set of rules.
Refer to `Snowflake Object Identifier Requirements <https://docs.snowflake.com/en/sql-reference/identifiers-syntax.html>`_ for details.
When you use column names with a DataFrame, you should follow these rules.
The returned column names after a DataFrame is evaluated follow the case-sensitivity rules too.
The above ``df`` was created with column name "name" while the returned column name after ``collect()`` was called became "NAME".
It's because the column is regarded as ignore-case so the Snowflake database returns the upper case.
To create a Column object that represents a constant value, use :func:`snowflake.snowpark.functions.lit`:
>>> from snowflake.snowpark.functions import lit
>>> df.select(col("name"), lit("const value").alias("literal_column")).collect()
[Row(NAME='John', LITERAL_COLUMN='const value'), Row(NAME='Mike', LITERAL_COLUMN='const value')]
This class also defines utility functions for constructing expressions with Columns.
Column objects can be built with the operators, summarized by operator precedence,
in the following table:
============================================== ==============================================
Operator Description
============================================== ==============================================
``x[index]`` Index operator to get an item out of a Snowflake ARRAY or OBJECT
``**`` Power
``-x``, ``~x`` Unary minus, unary not
``*``, ``/``, ``%`` Multiply, divide, remainder
``+``, ``-`` Plus, minus
``&`` And
``|`` Or
``==``, ``!=``, ``<``, ``<=``, ``>``, ``>=`` Equal to, not equal to, less than, less than or equal to, greater than, greater than or equal to
============================================== ==============================================
The following examples demonstrate how to use Column objects in expressions:
>>> df = session.create_dataframe([[20, 5], [1, 2]], schema=["a", "b"])
>>> df.filter((col("a") == 20) | (col("b") <= 10)).collect() # use parentheses before and after the | operator.
[Row(A=20, B=5), Row(A=1, B=2)]
>>> df.filter((df["a"] + df.b) < 10).collect()
[Row(A=1, B=2)]
>>> df.select((col("b") * 10).alias("c")).collect()
[Row(C=50), Row(C=20)]
When you use ``|``, ``&``, and ``~`` as logical operators on columns, you must always enclose column expressions
with parentheses as illustrated in the above example, because their order precedence is higher than ``==``, ``<``, etc.
Do not use ``and``, ``or``, and ``not`` logical operators on column objects, for instance, ``(df.col1 > 1) and (df.col2 > 2)`` is wrong.
The reason is Python doesn't have a magic method, or dunder method for them.
It will raise an error and tell you to use ``|``, ``&`` or ``~``, for which Python has magic methods.
A side effect is ``if column:`` will raise an error because it has a hidden call to ``bool(a_column)``, like using the ``and`` operator.
Use ``if a_column is None:`` instead.
To access elements of a semi-structured Object and Array, use ``[]`` on a Column object:
>>> from snowflake.snowpark.types import StringType, IntegerType
>>> df_with_semi_data = session.create_dataframe([[{"k1": "v1", "k2": "v2"}, ["a0", 1, "a2"]]], schema=["object_column", "array_column"])
>>> df_with_semi_data.select(df_with_semi_data["object_column"]["k1"].alias("k1_value"), df_with_semi_data["array_column"][0].alias("a0_value"), df_with_semi_data["array_column"][1].alias("a1_value")).collect()
[Row(K1_VALUE='"v1"', A0_VALUE='"a0"', A1_VALUE='1')]
>>> # The above two returned string columns have JSON literal values because children of semi-structured data are semi-structured.
>>> # The next line converts JSON literal to a string
>>> df_with_semi_data.select(df_with_semi_data["object_column"]["k1"].cast(StringType()).alias("k1_value"), df_with_semi_data["array_column"][0].cast(StringType()).alias("a0_value"), df_with_semi_data["array_column"][1].cast(IntegerType()).alias("a1_value")).collect()
[Row(K1_VALUE='v1', A0_VALUE='a0', A1_VALUE=1)]
This class has methods for the most frequently used column transformations and operators. Module :mod:`snowflake.snowpark.functions` defines many functions to transform columns.
"""
# NOTE: For now assume Expression instances can be safely ignored when building AST
# Expression logic can be eliminated entirely once phase 0 is integrated
# Currently a breaking example can be created using the Column.isin method as it does not build the AST.
# For example, running: df.filter(col("A").isin(1, 2, 3) & col("B")) would fail since the boolean operator
# '&' would try to construct an AST using that of the new col("A").isin(1, 2, 3) column (which we currently
# don't fill if the only argument provided in the Column constructor is 'expr1' of type Expression)
def __init__(
self,
expr1: Union[str, Expression],
expr2: Optional[str] = None,
json_element: bool = False,
_ast: Optional[proto.Expr] = None,
_emit_ast: bool = True,
) -> None:
self._ast = _ast
def derive_json_element_expr(
expr: str, df_alias: Optional[str] = None
) -> UnresolvedAttribute:
parts = expr.split(".")
if len(parts) == 1:
return UnresolvedAttribute(quote_name(parts[0]), df_alias=df_alias)
else:
# According to https://docs.snowflake.com/en/user-guide/querying-semistructured#dot-notation,
# the json value on the path should be case-sensitive
return UnresolvedAttribute(
f"{quote_name(parts[0])}:{'.'.join(quote_name(part, keep_case=True) for part in parts[1:])}",
is_sql_text=True,
df_alias=df_alias,
)
if expr2 is not None:
if not (isinstance(expr1, str) and isinstance(expr2, str)):
raise ValueError(
"When Column constructor gets two arguments, both need to be <str>"
)
if expr2 == "*":
self._expression = Star([], df_alias=expr1)
elif json_element:
self._expression = derive_json_element_expr(expr2, expr1)
else:
self._expression = UnresolvedAttribute(
quote_name(expr2), df_alias=expr1
)
# Alias field should be from the parameter provided to DataFrame.alias(self, name: str)
# A column from the aliased DataFrame instance can be created using this alias like col(<df_alias>, <col_name>)
# In the IR we will need to store this alias to resolve which DataFrame instance the user is referring to
if self._ast is None and _emit_ast:
self._ast = create_ast_for_column(expr1, expr2)
elif isinstance(expr1, str):
if expr1 == "*":
self._expression = Star([])
elif json_element:
self._expression = derive_json_element_expr(expr1)
else:
self._expression = UnresolvedAttribute(quote_name(expr1))
if self._ast is None and _emit_ast:
self._ast = create_ast_for_column(expr1, None)
elif isinstance(expr1, Expression):
self._expression = expr1
if self._ast is None and _emit_ast:
if hasattr(expr1, "_ast"):
self._ast = expr1._ast
else:
self._ast = snowpark_expression_to_ast(expr1)
else: # pragma: no cover
raise TypeError("Column constructor only accepts str or expression.")
assert self._expression is not None
def __should_emit_ast_for_binary(self, other: Any) -> bool:
"""Helper function to determine without a session whether AST should be generated or not based on
checking whether self and other have an AST."""
if isinstance(other, (Column, Expression)) and other._ast is None:
return False
return self._ast is not None
def __getitem__(self, field: Union[str, int]) -> "Column":
"""Accesses an element of ARRAY column by ordinal position, or an element of OBJECT column by key."""
_emit_ast = self._ast is not None
expr = None
if isinstance(field, str):
if _emit_ast:
expr = proto.Expr()
ast = with_src_position(expr.sp_column_apply__string)
ast.col.CopyFrom(self._ast)
ast.field = field
return Column(
SubfieldString(self._expression, field), _ast=expr, _emit_ast=_emit_ast
)
elif isinstance(field, int):
if _emit_ast:
expr = proto.Expr()
ast = with_src_position(expr.sp_column_apply__int)
ast.col.CopyFrom(self._ast)
ast.idx = field
return Column(
SubfieldInt(self._expression, field), _ast=expr, _emit_ast=_emit_ast
)
else:
raise TypeError(f"Unexpected item type: {type(field)}")
def __eq__(self, other: Union[ColumnOrLiteral, Expression]) -> "Column":
"""Equal to."""
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.eq)
ast.lhs.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.rhs, other)
right = Column._to_expr(other)
return Column(EqualTo(self._expression, right), _ast=expr, _emit_ast=_emit_ast)
def __ne__(self, other: Union[ColumnOrLiteral, Expression]) -> "Column":
"""Not equal to."""
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.neq)
ast.lhs.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.rhs, other)
right = Column._to_expr(other)
return Column(
NotEqualTo(self._expression, right), _ast=expr, _emit_ast=_emit_ast
)
def __gt__(self, other: Union[ColumnOrLiteral, Expression]) -> "Column":
"""Greater than."""
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.gt)
ast.lhs.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.rhs, other)
return Column(
GreaterThan(self._expression, Column._to_expr(other)),
_ast=expr,
_emit_ast=_emit_ast,
)
def __lt__(self, other: Union[ColumnOrLiteral, Expression]) -> "Column":
"""Less than."""
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.lt)
ast.lhs.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.rhs, other)
return Column(
LessThan(self._expression, Column._to_expr(other)),
_ast=expr,
_emit_ast=_emit_ast,
)
def __ge__(self, other: Union[ColumnOrLiteral, Expression]) -> "Column":
"""Greater than or equal to."""
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.geq)
ast.lhs.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.rhs, other)
return Column(
GreaterThanOrEqual(self._expression, Column._to_expr(other)),
_ast=expr,
_emit_ast=_emit_ast,
)
def __le__(self, other: Union[ColumnOrLiteral, Expression]) -> "Column":
"""Less than or equal to."""
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.leq)
ast.lhs.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.rhs, other)
return Column(
LessThanOrEqual(self._expression, Column._to_expr(other)),
_ast=expr,
_emit_ast=_emit_ast,
)
def __add__(self, other: Union[ColumnOrLiteral, Expression]) -> "Column":
"""Plus."""
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.add)
ast.lhs.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.rhs, other)
return Column(
Add(self._expression, Column._to_expr(other)),
_ast=expr,
_emit_ast=_emit_ast,
)
def __radd__(self, other: Union[ColumnOrLiteral, Expression]) -> "Column":
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.add)
build_expr_from_snowpark_column_or_python_val(ast.lhs, other)
ast.rhs.CopyFrom(self._ast)
return Column(
Add(Column._to_expr(other), self._expression),
_ast=expr,
_emit_ast=_emit_ast,
)
def __sub__(self, other: Union[ColumnOrLiteral, Expression]) -> "Column":
"""Minus."""
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.sub)
ast.lhs.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.rhs, other)
return Column(
Subtract(self._expression, Column._to_expr(other)),
_ast=expr,
_emit_ast=_emit_ast,
)
def __rsub__(self, other: Union[ColumnOrLiteral, Expression]) -> "Column":
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.sub)
build_expr_from_snowpark_column_or_python_val(ast.lhs, other)
ast.rhs.CopyFrom(self._ast)
return Column(
Subtract(Column._to_expr(other), self._expression),
_ast=expr,
_emit_ast=_emit_ast,
)
def __mul__(self, other: Union[ColumnOrLiteral, Expression]) -> "Column":
"""Multiply."""
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.mul)
ast.lhs.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.rhs, other)
return Column(
Multiply(self._expression, Column._to_expr(other)),
_ast=expr,
_emit_ast=_emit_ast,
)
def __rmul__(self, other: Union[ColumnOrLiteral, Expression]) -> "Column":
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.mul)
build_expr_from_snowpark_column_or_python_val(ast.lhs, other)
ast.rhs.CopyFrom(self._ast)
return Column(
Multiply(Column._to_expr(other), self._expression),
_ast=expr,
_emit_ast=_emit_ast,
)
def __truediv__(self, other: Union[ColumnOrLiteral, Expression]) -> "Column":
"""Divide."""
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.div)
ast.lhs.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.rhs, other)
return Column(
Divide(self._expression, Column._to_expr(other)),
_ast=expr,
_emit_ast=_emit_ast,
)
def __rtruediv__(self, other: Union[ColumnOrLiteral, Expression]) -> "Column":
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.div)
build_expr_from_snowpark_column_or_python_val(ast.lhs, other)
ast.rhs.CopyFrom(self._ast)
return Column(
Divide(Column._to_expr(other), self._expression),
_ast=expr,
_emit_ast=_emit_ast,
)
def __mod__(self, other: Union[ColumnOrLiteral, Expression]) -> "Column":
"""Remainder."""
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.mod)
ast.lhs.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.rhs, other)
return Column(
Remainder(self._expression, Column._to_expr(other)),
_ast=expr,
_emit_ast=_emit_ast,
)
def __rmod__(self, other: Union[ColumnOrLiteral, Expression]) -> "Column":
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.mod)
build_expr_from_snowpark_column_or_python_val(ast.lhs, other)
ast.rhs.CopyFrom(self._ast)
return Column(
Remainder(Column._to_expr(other), self._expression),
_ast=expr,
_emit_ast=_emit_ast,
)
def __pow__(self, other: Union[ColumnOrLiteral, Expression]) -> "Column":
"""Power."""
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.pow)
ast.lhs.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.rhs, other)
return Column(
Pow(self._expression, Column._to_expr(other)),
_ast=expr,
_emit_ast=_emit_ast,
)
def __rpow__(self, other: Union[ColumnOrLiteral, Expression]) -> "Column":
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.pow)
build_expr_from_snowpark_column_or_python_val(ast.lhs, other)
ast.rhs.CopyFrom(self._ast)
return Column(
Pow(Column._to_expr(other), self._expression),
_ast=expr,
_emit_ast=_emit_ast,
)
def __bool__(self) -> bool:
raise TypeError(
"Cannot convert a Column object into bool: please use '&' for 'and', '|' for 'or', "
"'~' for 'not' if you're building DataFrame filter expressions. For example, use df.filter((col1 > 1) & (col2 > 2)) instead of df.filter(col1 > 1 and col2 > 2)."
)
def __iter__(self) -> None:
raise TypeError(
"Column is not iterable. This error can occur when you use the Python built-ins for sum, min and max. Please make sure you use the corresponding function from snowflake.snowpark.functions."
)
def __round__(self, n=None):
raise TypeError(
"Column cannot be rounded. This error can occur when you use the Python built-in round. Please make sure you use the snowflake.snowpark.functions.round function instead."
)
def __hash__(self):
return hash(self._expression)
@publicapi
def in_(
self,
*vals: Union[
LiteralType,
Iterable[LiteralType],
"snowflake.snowpark.DataFrame",
],
_emit_ast: bool = True,
) -> "Column":
"""Returns a conditional expression that you can pass to the :meth:`DataFrame.filter`
or where :meth:`DataFrame.where` to perform the equivalent of a WHERE ... IN query
with a specified list of values. You can also pass this to a
:meth:`DataFrame.select` call.
The expression evaluates to true if the value in the column is one of the values in
a specified sequence.
For example, the following code returns a DataFrame that contains the rows where
the column "a" contains the value 1, 2, or 3. This is equivalent to
``SELECT * FROM table WHERE a IN (1, 2, 3)``.
:meth:`isin` is an alias for :meth:`in_`.
Examples::
>>> from snowflake.snowpark.functions import lit
>>> df = session.create_dataframe([[1, "x"], [2, "y"] ,[4, "z"]], schema=["a", "b"])
>>> # Basic example
>>> df.filter(df["a"].in_(lit(1), lit(2), lit(3))).collect()
[Row(A=1, B='x'), Row(A=2, B='y')]
>>> # Check in membership for a DataFrame that has a single column
>>> df_for_in = session.create_dataframe([[1], [2] ,[3]], schema=["col1"])
>>> df.filter(df["a"].in_(df_for_in)).sort(df["a"].asc()).collect()
[Row(A=1, B='x'), Row(A=2, B='y')]
>>> # Use in with a select method call
>>> df.select(df["a"].in_(lit(1), lit(2), lit(3)).alias("is_in_list")).collect()
[Row(IS_IN_LIST=True), Row(IS_IN_LIST=True), Row(IS_IN_LIST=False)]
Args:
vals: The values, or a :class:`DataFrame` instance to use to check for membership against this column.
"""
cols = parse_positional_args_to_list(*vals)
# If cols is an empty list then in_ will always be False
if not cols:
ast = None
if _emit_ast:
ast = proto.Expr()
proto_ast = ast.sp_column_in
proto_ast.col.CopyFrom(self._ast)
return Column(Literal(False), _ast=ast, _emit_ast=_emit_ast)
cols = [_to_col_if_lit(col, "in_") for col in cols]
column_count = (
len(self._expression.expressions)
if isinstance(self._expression, MultipleExpression)
else 1
)
def value_mapper(value):
if isinstance(value, (tuple, set, list)):
if len(value) == column_count:
return MultipleExpression([Column._to_expr(v) for v in value])
else:
raise ValueError(
f"The number of values {len(value)} does not match the number of columns {column_count}."
)
elif isinstance(value, snowflake.snowpark.DataFrame):
if len(value.schema.fields) == column_count:
return ScalarSubquery(value._plan)
else:
raise ValueError(
f"The number of values {len(value.schema.fields)} does not match the number of columns {column_count}."
)
else:
return Column._to_expr(value)
value_expressions = [value_mapper(col) for col in cols]
if len(cols) != 1 or not isinstance(value_expressions[0], ScalarSubquery):
def validate_value(value_expr: Expression):
if isinstance(value_expr, Literal):
return
elif isinstance(value_expr, MultipleExpression):
for expr in value_expr.expressions:
validate_value(expr)
return
else:
raise TypeError(
f"'{type(value_expr)}' is not supported for the values parameter of the function "
f"in(). You must either specify a sequence of literals or a DataFrame that "
f"represents a subquery."
)
for ve in value_expressions:
validate_value(ve)
ast = None
if _emit_ast:
ast = proto.Expr()
proto_ast = ast.sp_column_in
proto_ast.col.CopyFrom(self._ast)
for val in vals:
val_ast = proto_ast.values.add()
if isinstance(val, snowflake.snowpark.dataframe.DataFrame):
val._set_ast_ref(val_ast)
else:
build_expr_from_python_val(val_ast, val)
return Column(
InExpression(self._expression, value_expressions),
_ast=ast,
_emit_ast=_emit_ast,
)
@publicapi
def between(
self,
lower_bound: Union[ColumnOrLiteral, Expression],
upper_bound: Union[ColumnOrLiteral, Expression],
_emit_ast: bool = True,
) -> "Column":
"""Between lower bound and upper bound."""
expr = None
if _emit_ast and self._ast is not None:
expr = proto.Expr()
ast = with_src_position(expr.sp_column_between)
ast.col.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.lower_bound, lower_bound)
build_expr_from_snowpark_column_or_python_val(ast.upper_bound, upper_bound)
ret = (Column._to_expr(lower_bound) <= self) & (
self <= Column._to_expr(upper_bound)
)
ret._ast = expr
return ret
@publicapi
def bitand(
self, other: Union[ColumnOrLiteral, Expression], _emit_ast: bool = True
) -> "Column":
"""Bitwise and."""
expr = None
if _emit_ast and self._ast is not None:
expr = proto.Expr()
ast = with_src_position(expr.bit_and)
ast.lhs.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.rhs, other)
return Column(
BitwiseAnd(Column._to_expr(other), self._expression),
_ast=expr,
_emit_ast=_emit_ast,
)
@publicapi
def bitor(
self, other: Union[ColumnOrLiteral, Expression], _emit_ast: bool = True
) -> "Column":
"""Bitwise or."""
expr = None
if _emit_ast and self._ast is not None:
expr = proto.Expr()
ast = with_src_position(expr.bit_or)
ast.lhs.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.rhs, other)
return Column(
BitwiseOr(Column._to_expr(other), self._expression),
_ast=expr,
_emit_ast=_emit_ast,
)
@publicapi
def bitxor(
self, other: Union[ColumnOrLiteral, Expression], _emit_ast: bool = True
) -> "Column":
"""Bitwise xor."""
expr = None
if _emit_ast and self._ast is not None:
expr = proto.Expr()
ast = with_src_position(expr.bit_xor)
ast.lhs.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.rhs, other)
return Column(
BitwiseXor(Column._to_expr(other), self._expression),
_ast=expr,
_emit_ast=_emit_ast,
)
# Note: For the operator overrides we always emit ast, it simply gets ignored in a call chain.
def __neg__(self) -> "Column":
"""Unary minus."""
expr = None
_emit_ast = self._ast is not None
if _emit_ast:
expr = proto.Expr()
ast = with_src_position(expr.neg)
ast.operand.CopyFrom(self._ast)
return Column(UnaryMinus(self._expression), _ast=expr, _emit_ast=_emit_ast)
@publicapi
def equal_null(self, other: "Column", _emit_ast: bool = True) -> "Column":
"""Equal to. You can use this for comparisons against a null value."""
expr = None
if _emit_ast := _emit_ast and self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(expr.sp_column_equal_null)
ast.lhs.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.rhs, other)
return Column(
EqualNullSafe(self._expression, Column._to_expr(other)),
_ast=expr,
_emit_ast=_emit_ast,
)
@publicapi
def equal_nan(self, _emit_ast: bool = True) -> "Column":
"""Is NaN."""
expr = None
if _emit_ast and self._ast is not None:
expr = proto.Expr()
ast = with_src_position(expr.sp_column_equal_nan)
ast.col.CopyFrom(self._ast)
return Column(IsNaN(self._expression), _ast=expr, _emit_ast=_emit_ast)
@publicapi
def is_null(self, _emit_ast: bool = True) -> "Column":
"""Is null."""
expr = None
if _emit_ast and self._ast is not None:
expr = proto.Expr()
ast = with_src_position(expr.sp_column_is_null)
ast.col.CopyFrom(self._ast)
return Column(IsNull(self._expression), _ast=expr, _emit_ast=_emit_ast)
@publicapi
def is_not_null(self, _emit_ast: bool = True) -> "Column":
"""Is not null."""
expr = None
if _emit_ast and self._ast is not None:
expr = proto.Expr()
ast = with_src_position(expr.sp_column_is_not_null)
ast.col.CopyFrom(self._ast)
return Column(IsNotNull(self._expression), _ast=expr, _emit_ast=_emit_ast)
# `and, or, not` cannot be overloaded in Python, so use bitwise operators as boolean operators
def __and__(self, other: Union["Column", Any]) -> "Column":
"""And."""
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(getattr(expr, "and"))
ast.lhs.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.rhs, other)
return Column(
And(self._expression, Column._to_expr(other)),
_ast=expr,
_emit_ast=_emit_ast,
)
def __rand__(self, other: Union["Column", Any]) -> "Column":
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(getattr(expr, "and"))
build_expr_from_snowpark_column_or_python_val(ast.lhs, other)
ast.rhs.CopyFrom(self._ast)
return Column(
And(Column._to_expr(other), self._expression),
_ast=expr,
_emit_ast=_emit_ast,
) # pragma: no cover
def __or__(self, other: Union["Column", Any]) -> "Column":
"""Or."""
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(getattr(expr, "or"))
ast.lhs.CopyFrom(self._ast)
build_expr_from_snowpark_column_or_python_val(ast.rhs, other)
return Column(
Or(self._expression, Column._to_expr(other)), _ast=expr, _emit_ast=_emit_ast
)
def __ror__(self, other: Union["Column", Any]) -> "Column":
expr = None
if _emit_ast := self.__should_emit_ast_for_binary(other):
expr = proto.Expr()
ast = with_src_position(getattr(expr, "or"))
build_expr_from_snowpark_column_or_python_val(ast.lhs, other)
ast.rhs.CopyFrom(self._ast)
return Column(
And(Column._to_expr(other), self._expression),
_ast=expr,
_emit_ast=_emit_ast,
) # pragma: no cover
def __invert__(self) -> "Column":
"""Unary not."""
expr = None
_emit_ast = self._ast is not None
if _emit_ast:
expr = proto.Expr()
ast = with_src_position(getattr(expr, "not"))
ast.operand.CopyFrom(self._ast)
return Column(Not(self._expression), _ast=expr, _emit_ast=_emit_ast)
def _cast(
self,
to: Union[str, DataType],
try_: bool = False,
rename_fields: bool = False,
add_fields: bool = False,
_emit_ast: bool = True,
) -> "Column":
if add_fields and rename_fields:
raise ValueError(
"is_add and is_rename cannot be set to True at the same time"
)
if isinstance(to, str):
to = type_string_to_type_object(to)
if isinstance(to, (ArrayType, MapType, StructType)):
to = to._as_nested()
if self._ast is None:
_emit_ast = False
expr = None
if _emit_ast:
expr = proto.Expr()
ast = with_src_position(
expr.sp_column_try_cast if try_ else expr.sp_column_cast
)
ast.col.CopyFrom(self._ast)
to._fill_ast(ast.to)
return Column(
Cast(self._expression, to, try_, rename_fields, add_fields),
_ast=expr,
_emit_ast=_emit_ast,
)
@publicapi
def cast(
self,
to: Union[str, DataType],
rename_fields: bool = False,
add_fields: bool = False,
_emit_ast: bool = True,
) -> "Column":
"""Casts the value of the Column to the specified data type.
It raises an error when the conversion can not be performed.
"""
return self._cast(
to,
False,
rename_fields=rename_fields,
add_fields=add_fields,
_emit_ast=_emit_ast,
)
@publicapi
def try_cast(
self,
to: Union[str, DataType],
rename_fields: bool = False,
add_fields: bool = False,
_emit_ast: bool = True,
) -> "Column":
"""Tries to cast the value of the Column to the specified data type.
It returns a NULL value instead of raising an error when the conversion can not be performed.