-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathfunctions.py
More file actions
11385 lines (9575 loc) · 416 KB
/
functions.py
File metadata and controls
11385 lines (9575 loc) · 416 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.
#
"""
Provides utility and SQL functions that generate :class:`~snowflake.snowpark.Column` expressions that you can pass to :class:`~snowflake.snowpark.DataFrame` transformation methods.
These utility functions generate references to columns, literals, and SQL expressions (e.g. "c + 1").
- Use :func:`col()` to convert a column name to a :class:`Column` object. Refer to the API docs of :class:`Column` to know more ways of referencing a column.
- Use :func:`lit()` to convert a Python value to a :class:`Column` object that represents a constant value in Snowflake SQL.
- Use :func:`sql_expr()` to convert a Snowflake SQL expression to a :class:`Column`.
>>> df = session.create_dataframe([[1, 'a', True, '2022-03-16'], [3, 'b', False, '2023-04-17']], schema=["a", "b", "c", "d"])
>>> res1 = df.filter(col("a") == 1).collect()
>>> res2 = df.filter(lit(1) == col("a")).collect()
>>> res3 = df.filter(sql_expr("a = 1")).collect()
>>> assert res1 == res2 == res3
>>> res1
[Row(A=1, B='a', C=True, D='2022-03-16')]
Some :class:`DataFrame` methods accept column names or SQL expressions text aside from a Column object for convenience.
For instance:
>>> df.filter("a = 1").collect() # use the SQL expression directly in filter
[Row(A=1, B='a', C=True, D='2022-03-16')]
>>> df.select("a").collect()
[Row(A=1), Row(A=3)]
whereas :class:`Column` objects enable you to use chained column operators and transformations with
Python code fluently:
>>> # Use columns and literals in expressions.
>>> df.select(((col("a") + 1).cast("string")).alias("add_one")).show()
-------------
|"ADD_ONE" |
-------------
|2 |
|4 |
-------------
<BLANKLINE>
The Snowflake database has hundreds of `SQL functions <https://docs.snowflake.com/en/sql-reference-functions.html>`_
This module provides Python functions that correspond to the Snowflake SQL functions. They typically accept :class:`Column`
objects or column names as input parameters and return a new :class:`Column` objects.
The following examples demonstrate the use of some of these functions:
>>> # This example calls the function that corresponds to the TO_DATE() SQL function.
>>> df.select(dateadd('day', lit(1), to_date(col("d")))).show()
---------------------------------------
|"DATEADD('DAY', 1, TO_DATE(""D""))" |
---------------------------------------
|2022-03-17 |
|2023-04-18 |
---------------------------------------
<BLANKLINE>
If you want to use a SQL function in Snowflake but can't find the corresponding Python function here,
you can create your own Python function with :func:`function`:
>>> my_radians = function("radians") # "radians" is the SQL function name.
>>> df.select(my_radians(col("a")).alias("my_radians")).show()
------------------------
|"MY_RADIANS" |
------------------------
|0.017453292519943295 |
|0.05235987755982988 |
------------------------
<BLANKLINE>
or call the SQL function directly:
>>> df.select(call_function("radians", col("a")).as_("call_function_radians")).show()
---------------------------
|"CALL_FUNCTION_RADIANS" |
---------------------------
|0.017453292519943295 |
|0.05235987755982988 |
---------------------------
<BLANKLINE>
Similarly, to call a table function, you can use :func:`~snowflake.snowpark.functions.table_function`, or :func:`~snowflake.snowpark.functions.call_table_function`.
**How to find help on input parameters of the Python functions for SQL functions**
The Python functions have the same name as the corresponding `SQL functions <https://docs.snowflake.com/en/sql-reference-functions.html>`_.
By reading the API docs or the source code of a Python function defined in this module, you'll see the type hints of the input parameters and return type.
The return type is always ``Column``. The input types tell you the acceptable values:
- ``ColumnOrName`` accepts a :class:`Column` object, or a column name in str. Most functions accept this type.
If you still want to pass a literal to it, use `lit(value)`, which returns a ``Column`` object that represents a literal value.
>>> df.select(avg("a")).show()
----------------
|"AVG(""A"")" |
----------------
|2.000000 |
----------------
<BLANKLINE>
>>> df.select(avg(col("a"))).show()
----------------
|"AVG(""A"")" |
----------------
|2.000000 |
----------------
<BLANKLINE>
- ``LiteralType`` accepts a value of type ``bool``, ``int``, ``float``, ``str``, ``bytearray``, ``decimal.Decimal``,
``datetime.date``, ``datetime.datetime``, ``datetime.time``, or ``bytes``. An example is the third parameter of :func:`lead`.
>>> import datetime
>>> from snowflake.snowpark.window import Window
>>> df.select(col("d"), lead("d", 1, datetime.date(2024, 5, 18), False).over(Window.order_by("d")).alias("lead_day")).show()
---------------------------
|"D" |"LEAD_DAY" |
---------------------------
|2022-03-16 |2023-04-17 |
|2023-04-17 |2024-05-18 |
---------------------------
<BLANKLINE>
- ``ColumnOrLiteral`` accepts a ``Column`` object, or a value of ``LiteralType`` mentioned above.
The difference from ``ColumnOrLiteral`` is ``ColumnOrLiteral`` regards a str value as a SQL string value instead of
a column name. When a function is much more likely to accept a SQL constant value than a column expression, ``ColumnOrLiteral``
is used. Yet you can still pass in a ``Column`` object if you need to. An example is the second parameter of
:func:``when``.
>>> df.select(when(df["a"] > 2, "Greater than 2").else_("Less than 2").alias("compare_with_2")).show()
--------------------
|"COMPARE_WITH_2" |
--------------------
|Less than 2 |
|Greater than 2 |
--------------------
<BLANKLINE>
- ``int``, ``bool``, ``str``, or another specific type accepts a value of that type. An example is :func:`to_decimal`.
>>> df.with_column("e", lit("1.2")).select(to_decimal("e", 5, 2)).show()
-----------------------------
|"TO_DECIMAL(""E"", 5, 2)" |
-----------------------------
|1.20 |
|1.20 |
-----------------------------
<BLANKLINE>
- ``ColumnOrSqlExpr`` accepts a ``Column`` object, or a SQL expression. For instance, the first parameter in :func:``when``.
>>> df.select(when("a > 2", "Greater than 2").else_("Less than 2").alias("compare_with_2")).show()
--------------------
|"COMPARE_WITH_2" |
--------------------
|Less than 2 |
|Greater than 2 |
--------------------
<BLANKLINE>
"""
import functools
import sys
import typing
from functools import reduce
from random import randint
from types import ModuleType
from typing import Callable, Dict, List, Optional, Tuple, Union, overload
import snowflake.snowpark
import snowflake.snowpark._internal.proto.generated.ast_pb2 as proto
import snowflake.snowpark.table_function
from snowflake.snowpark._internal.analyzer.expression import (
CaseWhen,
Expression,
FunctionExpression,
Interval,
ListAgg,
Literal,
MultipleExpression,
Star,
)
from snowflake.snowpark._internal.analyzer.unary_expression import Alias
from snowflake.snowpark._internal.analyzer.window_expression import (
FirstValue,
Lag,
LastValue,
Lead,
NthValue,
)
from snowflake.snowpark._internal.ast.utils import (
build_builtin_fn_apply,
build_call_table_function_apply,
build_expr_from_snowpark_column_or_python_val,
build_expr_from_snowpark_column_or_sql_str,
create_ast_for_column,
set_builtin_fn_alias,
snowpark_expression_to_ast,
with_src_position,
build_function_expr,
)
from snowflake.snowpark._internal.type_utils import (
ColumnOrLiteral,
ColumnOrLiteralStr,
ColumnOrName,
ColumnOrSqlExpr,
LiteralType,
type_string_to_type_object,
)
from snowflake.snowpark._internal.udf_utils import check_decorator_args
from snowflake.snowpark._internal.utils import (
parse_duration_string,
parse_positional_args_to_list,
publicapi,
validate_object_name,
check_create_map_parameter,
warning,
)
from snowflake.snowpark.column import (
CaseExpr,
Column,
_to_col_if_lit,
_to_col_if_sql_expr,
_to_col_if_str,
_to_col_if_str_or_int,
)
from snowflake.snowpark.stored_procedure import (
StoredProcedure,
StoredProcedureRegistration,
)
from snowflake.snowpark.types import (
ArrayType,
DataType,
FloatType,
PandasDataFrameType,
StringType,
StructType,
TimestampTimeZone,
TimestampType,
)
from snowflake.snowpark.udaf import UDAFRegistration, UserDefinedAggregateFunction
from snowflake.snowpark.udf import UDFRegistration, UserDefinedFunction
from snowflake.snowpark.udtf import UDTFRegistration, UserDefinedTableFunction
# 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
# check function to allow test_dataframe_alias_negative to pass in AST mode.
def _check_column_parameters(name1: str, name2: Optional[str]) -> None:
if not isinstance(name1, str):
raise ValueError(
f"Expects first argument to be of type str, got {type(name1)}."
)
if name2 is not None and not isinstance(name2, str):
raise ValueError(
f"Expects second argument to be of type str or None, got {type(name1)}."
)
@overload
@publicapi
def col(
col_name: str, _emit_ast: bool = True, *, _is_qualified_name: bool = False
) -> Column:
"""Returns the :class:`~snowflake.snowpark.Column` with the specified name.
Args:
col_name: The name of the column.
Example::
>>> df = session.sql("select 1 as a")
>>> df.select(col("a")).collect()
[Row(A=1)]
"""
... # pragma: no cover
@overload
@publicapi
def col(
df_alias: str,
col_name: str,
_emit_ast: bool = True,
*,
_is_qualified_name: bool = False,
) -> Column:
"""Returns the :class:`~snowflake.snowpark.Column` with the specified dataframe alias and column name.
Example::
>>> df = session.sql("select 1 as a")
>>> df.alias("df").select(col("df", "a")).collect()
[Row(A=1)]
"""
... # pragma: no cover
@publicapi
def col(
name1: str,
name2: Optional[str] = None,
_emit_ast: bool = True,
*,
_is_qualified_name: bool = False,
) -> Column:
_check_column_parameters(name1, name2)
ast = None
if _emit_ast:
ast = create_ast_for_column(name1, name2, "col")
if name2 is None:
return Column(name1, _is_qualified_name=_is_qualified_name, _ast=ast)
else:
return Column(name1, name2, _is_qualified_name=_is_qualified_name, _ast=ast)
@overload
@publicapi
def column(
col_name: str, _emit_ast: bool = True, *, _is_qualified_name: bool = False
) -> Column:
"""Returns a :class:`~snowflake.snowpark.Column` with the specified name. Alias for col.
Args:
col_name: The name of the column.
Example::
>>> df = session.sql("select 1 as a")
>>> df.select(column("a")).collect()
[Row(A=1)]
"""
... # pragma: no cover
@overload
@publicapi
def column(
df_alias: str,
col_name: str,
_emit_ast: bool = True,
*,
_is_qualified_name: bool = False,
) -> Column:
"""Returns a :class:`~snowflake.snowpark.Column` with the specified name and dataframe alias name. Alias for col.
Example::
>>> df = session.sql("select 1 as a")
>>> df.alias("df").select(column("df", "a")).collect()
[Row(A=1)]
"""
... # pragma: no cover
@publicapi
def column(
name1: str,
name2: Optional[str] = None,
_emit_ast: bool = True,
*,
_is_qualified_name: bool = False,
) -> Column:
_check_column_parameters(name1, name2)
ast = create_ast_for_column(name1, name2, "column") if _emit_ast else None
if name2 is None:
return Column(name1, _is_qualified_name=_is_qualified_name, _ast=ast)
else:
return Column(name1, name2, _is_qualified_name=_is_qualified_name, _ast=ast)
@publicapi
def lit(
literal: ColumnOrLiteral,
datatype: Optional[DataType] = None,
_emit_ast: bool = True,
) -> Column:
"""
Creates a :class:`~snowflake.snowpark.Column` expression for a literal value.
It supports basic Python data types, including ``int``, ``float``, ``str``,
``bool``, ``bytes``, ``bytearray``, ``datetime.time``, ``datetime.date``,
``datetime.datetime`` and ``decimal.Decimal``. Also, it supports Python structured data types,
including ``list``, ``tuple`` and ``dict``, but this container must
be JSON serializable. If a ``Column`` object is passed, it is returned as is.
Example::
>>> import datetime
>>> columns = [lit(1), lit("1"), lit(1.0), lit(True), lit(b'snow'), lit(datetime.date(2023, 2, 2)), lit([1, 2]), lit({"snow": "flake"}), lit(lit(1))]
>>> session.create_dataframe([[]]).select([c.as_(str(i)) for i, c in enumerate(columns)]).show()
---------------------------------------------------------------------------------------------
|"0" |"1" |"2" |"3" |"4" |"5" |"6" |"7" |"8" |
---------------------------------------------------------------------------------------------
|1 |1 |1.0 |True |bytearray(b'snow') |2023-02-02 |[ |{ |1 |
| | | | | | | 1, | "snow": "flake" | |
| | | | | | | 2 |} | |
| | | | | | |] | | |
---------------------------------------------------------------------------------------------
<BLANKLINE>
"""
if _emit_ast:
ast = proto.Expr()
if datatype is None:
build_builtin_fn_apply(ast, "lit", literal)
else:
build_builtin_fn_apply(ast, "lit", literal, datatype)
if isinstance(literal, Column):
# Create new Column, and assign expression of current Column object.
# This will encode AST correctly.
c = Column("", _emit_ast=False)
c._expression = literal._expression
c._ast = ast
return c
return Column(Literal(literal, datatype=datatype), _ast=ast, _emit_ast=True)
if isinstance(literal, Column):
return literal
return Column(Literal(literal, datatype=datatype), _ast=None, _emit_ast=False)
@publicapi
def sql_expr(sql: str, _emit_ast: bool = True) -> Column:
"""Creates a :class:`~snowflake.snowpark.Column` expression from raw SQL text.
Note that the function does not interpret or check the SQL text.
Example::
>>> df = session.create_dataframe([[1, 2], [3, 4]], schema=["A", "B"])
>>> df.filter("a > 1").collect() # use SQL expression
[Row(A=3, B=4)]
"""
ast = None
if _emit_ast:
sql_expr_ast = proto.Expr()
ast = with_src_position(sql_expr_ast.sp_column_sql_expr)
ast.sql = sql
# Capture with ApplyFn in order to restore sql_expr(...) function.
ast = proto.Expr()
build_builtin_fn_apply(ast, "sql_expr", sql_expr_ast)
return Column._expr(sql, ast=ast)
@publicapi
def system_reference(
object_type: str,
object_identifier: str,
scope: str = "CALL",
privileges: Optional[List[str]] = None,
_emit_ast: bool = True,
):
"""
Returns a reference to an object (a table, view, or function). When you execute SQL actions on a
reference to an object, the actions are performed using the role of the user who created the
reference.
Example::
>>> df = session.create_dataframe([(1,)], schema=["A"])
>>> df.write.save_as_table("my_table", mode="overwrite", table_type="temporary")
>>> df.select(substr(system_reference("table", "my_table"), 1, 14).alias("identifier")).collect()
[Row(IDENTIFIER='ENT_REF_TABLE_')]
"""
privileges = privileges or []
return builtin("system$reference", _emit_ast=_emit_ast)(
object_type, object_identifier, scope, *privileges
)
@publicapi
def current_session(_emit_ast: bool = True) -> Column:
"""
Returns a unique system identifier for the Snowflake session corresponding to the present connection.
This will generally be a system-generated alphanumeric string. It is NOT derived from the user name or user account.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_session()).collect()
>>> assert result[0]['CURRENT_SESSION()'] is not None
"""
return builtin("current_session", _emit_ast=_emit_ast)()
@publicapi
def current_statement(_emit_ast: bool = True) -> Column:
"""
Returns the SQL text of the statement that is currently executing.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> session.create_dataframe([1]).select(current_statement()).collect()
[Row(CURRENT_STATEMENT()='SELECT current_statement() FROM ( SELECT "_1" FROM ( SELECT $1 AS "_1" FROM VALUES (1 :: INT)))')]
"""
return builtin("current_statement", _emit_ast=_emit_ast)()
@publicapi
def current_user(_emit_ast: bool = True) -> Column:
"""
Returns the name of the user currently logged into the system.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_user()).collect()
>>> assert result[0]['CURRENT_USER()'] is not None
"""
return builtin("current_user", _emit_ast=_emit_ast)()
@publicapi
def current_version(_emit_ast: bool = True) -> Column:
"""
Returns the current Snowflake version.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_version()).collect()
>>> assert result[0]['CURRENT_VERSION()'] is not None
"""
return builtin("current_version", _emit_ast=_emit_ast)()
@publicapi
def current_warehouse(_emit_ast: bool = True) -> Column:
"""
Returns the name of the warehouse in use for the current session.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_warehouse()).collect()
>>> assert result[0]['CURRENT_WAREHOUSE()'] is not None
"""
return builtin("current_warehouse", _emit_ast=_emit_ast)()
@publicapi
def current_database(_emit_ast: bool = True) -> Column:
"""Returns the name of the database in use for the current session.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_database()).collect()
>>> assert result[0]['CURRENT_DATABASE()'] is not None
"""
return builtin("current_database", _emit_ast=_emit_ast)()
@publicapi
def current_role(_emit_ast: bool = True) -> Column:
"""Returns the name of the role in use for the current session.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_role()).collect()
>>> assert result[0]['CURRENT_ROLE()'] is not None
"""
return builtin("current_role", _emit_ast=_emit_ast)()
@publicapi
def current_schema(_emit_ast: bool = True) -> Column:
"""Returns the name of the schema in use for the current session.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_schema()).collect()
>>> assert result[0]['CURRENT_SCHEMA()'] is not None
"""
return builtin("current_schema", _emit_ast=_emit_ast)()
@publicapi
def current_schemas(_emit_ast: bool = True) -> Column:
"""Returns active search path schemas.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_schemas()).collect()
>>> assert result[0]['CURRENT_SCHEMAS()'] is not None
"""
return builtin("current_schemas", _emit_ast=_emit_ast)()
@publicapi
def current_region(_emit_ast: bool = True) -> Column:
"""Returns the name of the region for the account where the current user is logged in.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_region()).collect()
>>> assert result[0]['CURRENT_REGION()'] is not None
"""
return builtin("current_region", _emit_ast=_emit_ast)()
@publicapi
def current_account(_emit_ast: bool = True) -> Column:
"""Returns the name of the account used in the current session.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_account()).collect()
>>> assert result[0]['CURRENT_ACCOUNT()'] is not None
"""
return builtin("current_account", _emit_ast=_emit_ast)()
@publicapi
def current_available_roles(_emit_ast: bool = True) -> Column:
"""Returns a JSON string that lists all roles granted to the current user.
Example:
>>> # Return result is tied to session, so we only test if the result exists
>>> result = session.create_dataframe([1]).select(current_available_roles()).collect()
>>> assert result[0]['CURRENT_AVAILABLE_ROLES()'] is not None
"""
return builtin("current_available_roles", _emit_ast=_emit_ast)()
@publicapi
def add_months(
date_or_timestamp: ColumnOrName,
number_of_months: Union[Column, int],
_emit_ast: bool = True,
) -> Column:
"""Adds or subtracts a specified number of months to a date or timestamp, preserving the end-of-month information.
Example:
>>> import datetime
>>> df = session.create_dataframe([datetime.date(2022, 4, 6)], schema=["d"])
>>> df.select(add_months("d", 4)).collect()[0][0]
datetime.date(2022, 8, 6)
"""
c = _to_col_if_str(date_or_timestamp, "add_months")
return builtin("add_months", _emit_ast=_emit_ast)(c, number_of_months)
@publicapi
def any_value(e: ColumnOrName, _emit_ast: bool = True) -> Column:
"""Returns a non-deterministic any value for the specified column.
This is an aggregate and window function.
Example:
>>> df = session.create_dataframe([[1, 2], [3, 4]], schema=["a", "b"])
>>> result = df.select(any_value("a")).collect()
>>> assert len(result) == 1 # non-deterministic value in result.
"""
c = _to_col_if_str(e, "any_value")
return call_builtin("any_value", c, _emit_ast=_emit_ast)
@publicapi
def bitnot(e: ColumnOrName, _emit_ast: bool = True) -> Column:
"""Returns the bitwise negation of a numeric expression.
Example:
>>> df = session.create_dataframe([1], schema=["a"])
>>> df.select(bitnot("a")).collect()[0][0]
-2
"""
c = _to_col_if_str(e, "bitnot")
return call_builtin("bitnot", c, _emit_ast=_emit_ast)
@publicapi
def bitshiftleft(
to_shift_column: ColumnOrName, n: Union[Column, int], _emit_ast: bool = True
) -> Column:
"""Returns the bitwise negation of a numeric expression.
Example:
>>> df = session.create_dataframe([2], schema=["a"])
>>> df.select(bitshiftleft("a", 1)).collect()[0][0]
4
"""
c = _to_col_if_str(to_shift_column, "bitshiftleft")
return call_builtin("bitshiftleft", c, n, _emit_ast=_emit_ast)
@publicapi
def bitshiftright(
to_shift_column: ColumnOrName, n: Union[Column, int], _emit_ast: bool = True
) -> Column:
"""Returns the bitwise negation of a numeric expression.
Example:
>>> df = session.create_dataframe([2], schema=["a"])
>>> df.select(bitshiftright("a", 1)).collect()[0][0]
1
"""
c = _to_col_if_str(to_shift_column, "bitshiftright")
return call_builtin("bitshiftright", c, n, _emit_ast=_emit_ast)
@publicapi
def bround(
col: ColumnOrName, scale: Union[Column, int], _emit_ast: bool = True
) -> Column:
"""
Rounds the number using `HALF_TO_EVEN` option. The `HALF_TO_EVEN` rounding mode rounds the given decimal value to the specified scale (number of decimal places) as follows:
* If scale is greater than or equal to 0, round to the specified number of decimal places using half-even rounding. This rounds towards the nearest value with ties (equally close values) rounding to the nearest even digit.
* If scale is less than 0, round to the integral part of the decimal. This rounds towards 0 and truncates the decimal places.
Note:
1. The data type of the expression must be one of the `data types for a fixed-point number
<https://docs.snowflake.com/en/sql-reference/data-types-numeric.html#label-data-types-for-fixed-point-numbers>`_.
2. Data types for floating point numbers (e.g. FLOAT) are not supported with this argument.
3. If the expression data type is not supported, the expression must be explicitly cast to decimal before calling.
Example:
>>> import decimal
>>> data = [(decimal.Decimal(1.235)),(decimal.Decimal(3.5))]
>>> df = session.createDataFrame(data, ["value"])
>>> df.select(bround('VALUE',1).alias("VALUE")).show() # Rounds to 1 decimal place
-----------
|"VALUE" |
-----------
|1.2 |
|3.5 |
-----------
<BLANKLINE>
>>> df.select(bround('VALUE',0).alias("VALUE")).show() # Rounds to 1 decimal place
-----------
|"VALUE" |
-----------
|1 |
|4 |
-----------
<BLANKLINE>
"""
# AST.
ast = None
if _emit_ast:
ast = proto.Expr()
build_builtin_fn_apply(ast, "bround", col, scale)
col = _to_col_if_str(col, "bround")
scale = _to_col_if_lit(scale, "bround")
# Note: Original Snowpark python code capitalized here.
col = call_builtin(
"ROUND", col, scale, lit("HALF_TO_EVEN", _emit_ast=False), _emit_ast=False
)
col._ast = ast
return col
@publicapi
def convert_timezone(
target_timezone: ColumnOrName,
source_time: ColumnOrName,
source_timezone: Optional[ColumnOrName] = None,
_emit_ast: bool = True,
) -> Column:
"""Converts the given source_time to the target timezone.
For timezone information, refer to the `Snowflake SQL convert_timezone notes <https://docs.snowflake.com/en/sql-reference/functions/convert_timezone.html#usage-notes>`_
Args:
target_timezone: The time zone to which the input timestamp should be converted.=
source_time: The timestamp to convert. When it's a TIMESTAMP_LTZ, use ``None`` for ``source_timezone``.
source_timezone: The time zone for the ``source_time``. Required for timestamps with no time zone (i.e. TIMESTAMP_NTZ). Use ``None`` if the timestamps have a time zone (i.e. TIMESTAMP_LTZ). Default is ``None``.
Note:
The sequence of the 3 params is different from the SQL function, which two overloads:
- ``CONVERT_TIMEZONE( <source_tz> , <target_tz> , <source_timestamp_ntz> )``
- ``CONVERT_TIMEZONE( <target_tz> , <source_timestamp> )``
The first parameter ``source_tz`` is optional. But in Python an optional argument shouldn't be placed at the first.
So ``source_timezone`` is after ``source_time``.
Example:
>>> import datetime
>>> from dateutil import tz
>>> datetime_with_tz = datetime.datetime(2022, 4, 6, 9, 0, 0, tzinfo=tz.tzoffset("myzone", -3600*7))
>>> datetime_with_no_tz = datetime.datetime(2022, 4, 6, 9, 0, 0)
>>> df = session.create_dataframe([[datetime_with_tz, datetime_with_no_tz]], schema=["a", "b"])
>>> result = df.select(convert_timezone(lit("UTC"), col("a")), convert_timezone(lit("UTC"), col("b"), lit("Asia/Shanghai"))).collect()
>>> result[0][0]
datetime.datetime(2022, 4, 6, 16, 0, tzinfo=<UTC>)
>>> result[0][1]
datetime.datetime(2022, 4, 6, 1, 0)
"""
source_tz = (
_to_col_if_str(source_timezone, "convert_timezone")
if source_timezone is not None
else None
)
target_tz = _to_col_if_str(target_timezone, "convert_timezone")
source_time_to_convert = _to_col_if_str(source_time, "convert_timezone")
# Build AST here to prevent rearrangement of args in the encoded AST.
ast = (
build_function_expr(
"convert_timezone",
[target_timezone, source_time, source_timezone],
ignore_null_args=True,
)
if _emit_ast
else None
)
if source_timezone is None:
return call_builtin(
"convert_timezone",
target_tz,
source_time_to_convert,
_ast=ast,
_emit_ast=False,
)
return call_builtin(
"convert_timezone",
source_tz,
target_tz,
source_time_to_convert,
_ast=ast,
_emit_ast=False,
)
@publicapi
def approx_count_distinct(e: ColumnOrName, _emit_ast: bool = True) -> Column:
"""Uses HyperLogLog to return an approximation of the distinct cardinality of the input (i.e. HLL(col1, col2, ... )
returns an approximation of COUNT(DISTINCT col1, col2, ... )).
Example::
>>> df = session.create_dataframe([[1, 2], [3, 4], [5, 6]], schema=["a", "b"])
>>> df.select(approx_count_distinct("a").alias("result")).show()
------------
|"RESULT" |
------------
|3 |
------------
<BLANKLINE>
"""
c = _to_col_if_str(e, "approx_count_distinct")
return builtin("approx_count_distinct", _emit_ast=_emit_ast)(c)
@publicapi
def avg(e: ColumnOrName, _emit_ast: bool = True) -> Column:
"""Returns the average of non-NULL records. If all records inside a group are NULL,
the function returns NULL.
Example::
>>> df = session.create_dataframe([[1], [2], [2]], schema=["d"])
>>> df.select(avg(df.d).alias("result")).show()
------------
|"RESULT" |
------------
|1.666667 |
------------
<BLANKLINE>
"""
c = _to_col_if_str(e, "avg")
return builtin("avg", _emit_ast=_emit_ast)(c)
@publicapi
def corr(
column1: ColumnOrName, column2: ColumnOrName, _emit_ast: bool = True
) -> Column:
"""Returns the correlation coefficient for non-null pairs in a group.
Example:
>>> df = session.create_dataframe([[1, 2], [1, 2], [4, 5], [2, 3], [3, None], [4, None], [6,4]], schema=["a", "b"])
>>> df.select(corr(col("a"), col("b")).alias("result")).show()
---------------------
|"RESULT" |
---------------------
|0.813681508328809 |
---------------------
<BLANKLINE>
"""
c1 = _to_col_if_str(column1, "corr")
c2 = _to_col_if_str(column2, "corr")
return builtin("corr", _emit_ast=_emit_ast)(c1, c2)
@publicapi
def count(e: ColumnOrName, _emit_ast: bool = True) -> Column:
"""Returns either the number of non-NULL records for the specified columns, or the
total number of records.
Example:
>>> df = session.create_dataframe([[1], [None], [3], [4], [None]], schema=["a"])
>>> df.select(count(col("a")).alias("result")).show()
------------
|"RESULT" |
------------
|3 |
------------
<BLANKLINE>
>>> df.select(count("*").alias("result")).show()
------------
|"RESULT" |
------------
|5 |
------------
<BLANKLINE>
"""
ast = None
if _emit_ast:
ast = proto.Expr()
build_builtin_fn_apply(ast, "count", e)
c = _to_col_if_str(e, "count")
expr = Literal(1) if isinstance(c._expression, Star) else c._expression
ans = builtin("count", _emit_ast=False)(expr)
ans._ast = ast
return ans
@publicapi
def count_distinct(*cols: ColumnOrName, _emit_ast: bool = True) -> Column:
"""Returns either the number of non-NULL distinct records for the specified columns,
or the total number of the distinct records.
Example:
>>> df = session.create_dataframe([[1, 2], [1, 2], [3, None], [2, 3], [3, None], [4, None]], schema=["a", "b"])
>>> df.select(count_distinct(col("a"), col("b")).alias("result")).show()
------------
|"RESULT" |
------------
|2 |
------------
<BLANKLINE>
>>> # The result should be 2 for {[1,2],[2,3]} since the rest are either duplicate or NULL records
"""
ast = None
if _emit_ast:
ast = proto.Expr()
build_builtin_fn_apply(ast, "count_distinct", *cols)
cs = [_to_col_if_str(c, "count_distinct") for c in cols]
return Column(
FunctionExpression("count", [c._expression for c in cs], is_distinct=True),
_ast=ast,
_emit_ast=False,
)
@publicapi
def covar_pop(
column1: ColumnOrName, column2: ColumnOrName, _emit_ast: bool = True
) -> Column:
"""Returns the population covariance for non-null pairs in a group.
Example:
>>> from snowflake.snowpark.types import DecimalType
>>> df = session.create_dataframe([[1, 2], [1, 2], [4, 5], [2, 3], [3, None], [4, None], [6,4]], schema=["a", "b"])
>>> df.select(covar_pop(col("a"), col("b")).cast(DecimalType(scale=3)).alias("result")).show()
------------
|"RESULT" |
------------
|1.840 |
------------
<BLANKLINE>
"""
col1 = _to_col_if_str(column1, "covar_pop")
col2 = _to_col_if_str(column2, "covar_pop")
return builtin("covar_pop", _emit_ast=_emit_ast)(col1, col2)
@publicapi
def covar_samp(
column1: ColumnOrName, column2: ColumnOrName, _emit_ast: bool = True
) -> Column:
"""Returns the sample covariance for non-null pairs in a group.
Example:
>>> from snowflake.snowpark.types import DecimalType
>>> df = session.create_dataframe([[1, 2], [1, 2], [4, 5], [2, 3], [3, None], [4, None], [6,4]], schema=["a", "b"])
>>> df.select(covar_samp(col("a"), col("b")).cast(DecimalType(scale=3)).alias("result")).show()
------------
|"RESULT" |
------------
|2.300 |
------------
<BLANKLINE>
"""
col1 = _to_col_if_str(column1, "covar_samp")
col2 = _to_col_if_str(column2, "covar_samp")
return builtin("covar_samp", _emit_ast=_emit_ast)(col1, col2)