-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathtest_stored_procedure.py
More file actions
2586 lines (2191 loc) · 89.2 KB
/
test_stored_procedure.py
File metadata and controls
2586 lines (2191 loc) · 89.2 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 datetime
import importlib.metadata
import logging
import os
import re
import sys
import time
from typing import Dict, List, Optional, Union
from unittest.mock import patch
from textwrap import dedent
import pytest
try:
import pandas as pd # noqa: F401
from snowflake.snowpark.types import PandasSeries
is_pandas_available = True
except ImportError:
is_pandas_available = False
from snowflake.snowpark import Session, AsyncJob
from snowflake.snowpark._internal.analyzer.analyzer_utils import unquote_if_quoted
from snowflake.snowpark._internal.udf_utils import resolve_imports_and_packages
from snowflake.snowpark._internal.utils import (
unwrap_stage_location_single_quote,
)
from snowflake.snowpark.dataframe import DataFrame
from snowflake.snowpark.exceptions import (
SnowparkInvalidObjectNameException,
SnowparkSQLException,
)
from snowflake.snowpark.functions import (
cast,
col,
current_date,
date_from_parts,
iff,
lit,
max as max_,
pow,
sproc,
sqrt,
system_reference,
)
from snowflake.snowpark.row import Row
from snowflake.snowpark.types import (
DateType,
DoubleType,
IntegerType,
StringType,
StructField,
StructType,
)
from tests.utils import (
IS_IN_STORED_PROC,
IS_NOT_ON_GITHUB,
TempObjectType,
TestFiles,
Utils,
)
pytestmark = [
pytest.mark.udf,
]
tmp_stage_name = Utils.random_stage_name()
@pytest.fixture(scope="module", autouse=True)
def setup(session, resources_path, local_testing_mode):
test_files = TestFiles(resources_path)
if not local_testing_mode:
Utils.create_stage(session, tmp_stage_name, is_temporary=True)
session.add_packages("snowflake-snowpark-python")
Utils.upload_to_stage(
session, tmp_stage_name, test_files.test_sp_py_file, compress=False
)
@pytest.mark.xfail(
"config.getoption('local_testing_mode', default=False)",
reason="Packaging processing is a NOOP in Local Testing",
run=False,
)
@pytest.mark.skipif(
IS_IN_STORED_PROC,
reason="Cannot create session in SP",
)
@patch("snowflake.snowpark._internal.udf_utils.VERSION", (999, 9, 9))
@pytest.mark.parametrize(
"packages,should_fail",
[
# Adding package without version pin should always work
(["snowflake-snowpark-python"], False),
# Including a future version fails because it doesn't exist on the server
(["snowflake-snowpark-python==9999.9.9"], True),
# Auto including the testing version should fail since it's ahead of what the server can support
([], True),
# Auto including the current version via session also fails.
(None, True),
],
)
def test_add_packages_failures(packages, should_fail, db_parameters):
def return1(session_):
return session_.sql("select '1'").collect()[0][0]
with Session.builder.configs(db_parameters).create() as new_session:
if should_fail:
with pytest.raises(
RuntimeError, match="Cannot add package snowflake-snowpark-python"
):
sproc(
return1,
session=new_session,
return_type=StringType(),
packages=packages,
)
else:
return1_sproc = sproc(
return1,
session=new_session,
return_type=StringType(),
packages=packages,
)
assert return1_sproc(session=new_session) == "1"
@pytest.mark.xfail(
"config.getoption('local_testing_mode', default=False)",
reason="Packaging processing is a NOOP in Local Testing",
run=False,
)
@pytest.mark.skipif(
IS_IN_STORED_PROC,
reason="Cannot create session in SP",
)
@patch(
"snowflake.snowpark.stored_procedure.resolve_imports_and_packages",
wraps=resolve_imports_and_packages,
)
@pytest.mark.parametrize(
"session_packages,local_packages",
[
# Test that sproc package list is updated correctly
(["pyyaml"], []),
# Test that session packages are updated correctly
([], ["pyyaml"]),
],
)
@patch("snowflake.snowpark._internal.udf_utils.VERSION", (999, 9, 9))
def test__do_register_sp_submits_correct_packages(
patched_resolve, session_packages, local_packages, db_parameters
):
major, minor, patch = (999, 9, 9)
this_package = f"snowflake-snowpark-python=={major}.{minor}.{patch}"
def return1(session_):
return session_.sql("select '1'").collect()[0][0]
with Session.builder.configs(db_parameters).create() as new_session:
# Adding the testing version of the package fails, but the package list should still be correct
with pytest.raises(
RuntimeError, match="Cannot add package snowflake-snowpark-python"
):
sproc(
return1,
session=new_session,
return_type=StringType(),
packages=["pyyaml"],
)
assert patched_resolve.called
assert (
session_packages + local_packages + [this_package]
in patched_resolve.call_args[0]
)
def test_basic_stored_procedure(session, local_testing_mode):
def return1(session_):
return session_.create_dataframe([["1"]]).collect()[0][0]
def plus1(session_, x):
return (
session_.create_dataframe([[x]])
.to_df(["a"])
.select(col("a") + lit(1))
.collect()[0][0]
)
def add(session_, x, y):
return (
session_.create_dataframe([[x, y]])
.to_df(["a", "b"])
.select(col("a") + col("b"))
.collect()[0][0]
)
def int2str(session_, x):
return (
session_.create_dataframe([[x]])
.to_df(["a"])
.select(cast(col("a"), "string"))
.collect()[0][0]
)
return1_sp = sproc(return1, return_type=StringType())
plus1_sp = sproc(plus1, return_type=IntegerType(), input_types=[IntegerType()])
add_sp = sproc(
add, return_type=IntegerType(), input_types=[IntegerType(), IntegerType()]
)
int2str_sp = sproc(int2str, return_type=StringType(), input_types=[IntegerType()])
assert return1_sp() == "1"
assert plus1_sp(1) == 2
assert add_sp(4, 6) == 10
assert int2str_sp(123) == "123"
assert return1_sp(session=session) == "1"
assert plus1_sp(1, session=session) == 2
assert add_sp(4, 6, session=session) == 10
assert int2str_sp(123, session=session) == "123"
def sp_pow(session_, x, y):
return (
session_.create_dataframe([[x, y]])
.to_df(["a", "b"])
.select(pow(col("a"), col("b")))
.collect()[0][0]
)
pow_sp = sproc(
sp_pow,
return_type=DoubleType(),
input_types=[IntegerType(), IntegerType()],
)
assert pow_sp(2, 10) == 1024
assert pow_sp(2, 10, session=session) == 1024
def test_stored_procedure_with_basic_column_datatype(session, local_testing_mode):
expected_err = Exception if local_testing_mode else SnowparkSQLException
def plus1(session_, x):
return x + 1
plus1_sp = sproc(plus1, return_type=IntegerType(), input_types=[IntegerType()])
assert plus1_sp(lit(6)) == 7
with pytest.raises(expected_err) as ex_info:
plus1_sp(col("a"))
assert "invalid identifier" in str(ex_info.value)
with pytest.raises(expected_err) as ex_info:
plus1_sp(current_date())
assert "Invalid argument types for function" in str(
ex_info.value
) or "Unexpected type" in str(ex_info.value)
with pytest.raises(expected_err) as ex_info:
plus1_sp(lit(""))
assert "not recognized" in str(ex_info.value) or "Unexpected type" in str(
ex_info.value
)
def test_stored_procedure_with_column_datatype(session, local_testing_mode):
def add(session_, x, y):
return x + y
add_sp = sproc(
add, return_type=IntegerType(), input_types=[IntegerType(), IntegerType()]
)
assert add_sp(4, sqrt(lit(36))) == 10
if not local_testing_mode:
dt = datetime.date(1992, 12, 14) + datetime.timedelta(days=3)
def add_date(session_, date, add_days):
return date + datetime.timedelta(days=add_days)
add_date_sp = sproc(
add_date, return_type=DateType(), input_types=[DateType(), IntegerType()]
)
# the date can be different between server and client due to timezone difference
assert -1 <= (add_date_sp(date_from_parts(1992, 12, 14), 3) - dt).days <= 1
@pytest.mark.skipif(
IS_IN_STORED_PROC,
reason="Named temporary procedure is not supported in stored proc",
)
def test_call_named_stored_procedure(
session, temp_schema, db_parameters, local_testing_mode
):
sproc_name = f"test_mul_{Utils.random_alphanumeric_str(3)}"
if not local_testing_mode:
session._run_query(f"drop procedure if exists {sproc_name}(int, int)")
sproc(
lambda session_, x, y: session_.create_dataframe([[x * y]]).collect()[0][0],
return_type=IntegerType(),
input_types=[IntegerType(), IntegerType()],
name=sproc_name,
)
assert session.call(sproc_name, 13, 19) == 13 * 19
assert (
session.call(session.get_fully_qualified_name_if_possible(sproc_name), 13, 19)
== 13 * 19
)
if not local_testing_mode:
# create a stored procedure when the session doesn't have a schema
new_session = (
Session.builder.configs(db_parameters)._remove_config("schema").create()
)
new_session.sql_simplifier_enabled = session.sql_simplifier_enabled
new_session.add_packages("snowflake-snowpark-python")
try:
assert not new_session.get_current_schema()
tmp_stage_name_in_temp_schema = f"{temp_schema}.{Utils.random_name_for_temp_object(TempObjectType.STAGE)}"
new_session._run_query(f"create temp stage {tmp_stage_name_in_temp_schema}")
full_sp_name = f"{temp_schema}.test_add"
new_session._run_query(f"drop procedure if exists {full_sp_name}(int, int)")
new_session.sproc.register(
lambda session_, x, y: session_.sql(f"select {x} + {y}").collect()[0][
0
],
return_type=IntegerType(),
input_types=[IntegerType(), IntegerType()],
name=[*temp_schema.split("."), "test_add"],
stage_location=unwrap_stage_location_single_quote(
tmp_stage_name_in_temp_schema
),
is_permanent=True,
)
assert new_session.call(full_sp_name, 13, 19) == 13 + 19
# oen result in the temp schema
assert (
len(
new_session.sql(
f"show procedures like '%test_add%' in schema {temp_schema}"
).collect()
)
== 1
)
finally:
new_session.close()
# restore active session
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="system functions not supported by local testing",
)
def test_infer_table_type_is_skipped_for_system_procedures(session):
with session.query_history() as history:
session.call("system$wait", 1)
assert len(history.queries) == 1
@pytest.mark.skipif(
"config.getoption('local_testing_mode', default=False)",
reason="system functions not supported by local testing",
)
def test_sproc_pass_system_reference(session, validate_ast):
table_name = Utils.random_name_for_temp_object(TempObjectType.TABLE)
df = session.create_dataframe([(1,)]).to_df(["a"])
df.write.save_as_table(
table_name,
mode="ignore" if validate_ast else "errorifexists",
)
def insert_and_return_count(session_: Session, table_name_: str) -> int:
session_.sql(f"INSERT INTO {table_name_} VALUES (2)").collect()
return session_.table(table_name_).count()
insert_sproc = sproc(insert_and_return_count, return_type=IntegerType())
try:
assert (
insert_sproc(
system_reference(
"TABLE",
table_name,
"SESSION",
["SELECT", "INSERT", "UPDATE", "TRUNCATE"],
)
)
== 2
)
Utils.check_answer(session.table(table_name), [Row(1), Row(2)])
finally:
Utils.drop_table(session, table_name)
@pytest.mark.parametrize("anonymous", [True, False])
def test_call_table_sproc_triggers_action(session, anonymous):
"""Here we create a table sproc which creates a table. we call the table sproc using
session.call trigger this action and test using session.table that the table was
indeed created
"""
sproc_name = Utils.random_name_for_temp_object(TempObjectType.PROCEDURE)
table_name = Utils.random_name_for_temp_object(TempObjectType.TABLE)
def create_temp_table_sp(session_: Session, name: str):
df = session_.create_dataframe([1]).to_df("A")
df.write.save_as_table(name, mode="overwrite")
return df
session.sproc.register(
create_temp_table_sp,
name=sproc_name,
return_type=StructType(),
input_types=[StringType()],
replace=True,
anomymous=anonymous,
)
try:
session.call(sproc_name, table_name)
Utils.check_answer(session.table(table_name), [Row(A=1)])
finally:
Utils.drop_table(session, table_name)
def test_recursive_function(session):
# Test recursive function
def factorial(session_, n):
return 1 if n == 1 or n == 0 else n * factorial(session_, n - 1)
factorial_sp = sproc(
factorial, return_type=IntegerType(), input_types=[IntegerType()]
)
assert factorial_sp(3) == factorial(session, 3)
def test_nested_function(session):
def outer_func(session_):
def inner_func():
return "snow"
return session_.create_dataframe([f"{inner_func()}-{inner_func()}"]).collect()[
0
][0]
def square(session_, x):
df = session_.create_dataframe([x]).to_df("a")
return df.select(pow("a", lit(2))).collect()[0][0]
def cube(session_, x):
return square(session_, x) * x
outer_func_sp = sproc(outer_func, return_type=StringType())
assert outer_func_sp() == "snow-snow"
# we don't need to register function square()
cube_sp = sproc(cube, return_type=IntegerType(), input_types=[IntegerType()])
assert cube_sp(2) == 8
# but we can still register function square()
square_sp = sproc(square, return_type=IntegerType(), input_types=[IntegerType()])
assert cube_sp(2) == 8
assert square_sp(2) == 4
def test_decorator_function(session):
def decorator_do_twice(func):
def wrapper(*args, **kwargs):
l1 = func(*args, **kwargs)
l2 = func(*args, **kwargs)
return l1 * l2
return wrapper
@decorator_do_twice
def square(session_, x):
df = session_.create_dataframe([x]).to_df("a")
return df.select(pow("a", lit(2))).collect()[0][0]
square_twice_sp = sproc(
square,
return_type=IntegerType(),
input_types=[IntegerType()],
)
assert square_twice_sp(2) == 16
def test_annotation_syntax(session):
@sproc(return_type=IntegerType(), input_types=[IntegerType(), IntegerType()])
def add_sp(session_, x, y):
df = session_.create_dataframe([(x, y)]).to_df("a", "b")
return df.select(col("a") + col("b")).collect()[0][0]
@sproc(return_type=StringType())
def snow(session_):
return session_.create_dataframe(["snow"]).collect()[0][0]
assert add_sp(1, 2) == 3
assert snow() == "snow"
def test_register_sp_from_file(session, resources_path, tmpdir):
test_files = TestFiles(resources_path)
mod5_sp = session.sproc.register_from_file(
test_files.test_sp_py_file,
"mod5",
return_type=IntegerType(),
input_types=[IntegerType()],
)
assert isinstance(mod5_sp.func, tuple)
assert mod5_sp(3) == 3
# test zip file
from zipfile import ZipFile
zip_path = f"{tmpdir.join(os.path.basename(test_files.test_sp_py_file))}.zip"
with ZipFile(zip_path, "w") as zf:
zf.write(
test_files.test_sp_py_file, os.path.basename(test_files.test_sp_py_file)
)
mod5_sp_zip = session.sproc.register_from_file(
zip_path, "mod5", return_type=IntegerType(), input_types=[IntegerType()]
)
assert mod5_sp_zip(3) == 3
# test a remote python file
stage_file = f"@{tmp_stage_name}/{os.path.basename(test_files.test_sp_py_file)}"
mod5_sp_stage = session.sproc.register_from_file(
stage_file, "mod5", return_type=IntegerType(), input_types=[IntegerType()]
)
assert mod5_sp_stage(3) == 3
# test a table sproc file with type hints
range5_sproc = session.sproc.register_from_file(
test_files.test_table_sp_py_file,
"range5_sproc",
)
Utils.check_answer(
range5_sproc(), [Row(ID=0), Row(ID=1), Row(ID=2), Row(ID=3), Row(ID=4)]
)
def test_session_register_sp(session, local_testing_mode):
add_sp = session.sproc.register(
lambda session_, x, y: session_.create_dataframe([(x, y)])
.to_df("a", "b")
.select(col("a") + col("b"))
.collect()[0][0],
return_type=IntegerType(),
input_types=[IntegerType(), IntegerType()],
)
assert add_sp(1, 2) == 3
query_tag = f"QUERY_TAG_{Utils.random_alphanumeric_str(10)}"
add_sp = session.sproc.register(
lambda session_, x, y: session_.create_dataframe([(x, y)])
.to_df("a", "b")
.select(col("a") + col("b"))
.collect()[0][0],
return_type=IntegerType(),
input_types=[IntegerType(), IntegerType()],
statement_params={"QUERY_TAG": query_tag},
)
assert add_sp(1, 2) == 3
Utils.assert_executed_with_query_tag(session, query_tag, local_testing_mode)
def test_add_import_local_file(session, resources_path):
test_files = TestFiles(resources_path)
def plus4_then_mod5(session_, x):
from test_sp_dir.test_sp_file import mod5
return mod5(
session_,
session_.create_dataframe([[x]], schema=["a"])
.select(col("a") + 4)
.collect()[0][0],
)
def plus4_then_mod5_direct_import(session_, x):
from test_sp_file import mod5
return mod5(
session_,
session_.create_dataframe([[x]], schema=["a"])
.select(col("a") + 4)
.collect()[0][0],
)
session.add_import(
test_files.test_sp_py_file, import_path="test_sp_dir.test_sp_file"
)
plus4_then_mod5_sp = sproc(
plus4_then_mod5, return_type=IntegerType(), input_types=[IntegerType()]
)
assert plus4_then_mod5_sp(3) == 2
# if import_as argument changes, the checksum of the file will also change
# and we will overwrite the file in the stage
session.add_import(test_files.test_sp_py_file)
plus4_then_mod5_direct_import_sp = sproc(
plus4_then_mod5_direct_import,
return_type=IntegerType(),
input_types=[IntegerType()],
)
assert plus4_then_mod5_direct_import_sp(3) == 2
# clean
session.clear_imports()
def test_add_import_local_directory(session, resources_path):
test_files = TestFiles(resources_path)
def plus4_then_mod5(session_, x):
from resources.test_sp_dir.test_sp_file import mod5
return mod5(
session_,
session_.create_dataframe([[x]], schema=["a"])
.select(col("a") + 4)
.collect()[0][0],
)
def plus4_then_mod5_direct_import(session_, x):
from test_sp_dir.test_sp_file import mod5
return mod5(
session_,
session_.create_dataframe([[x]], schema=["a"])
.select(col("a") + 4)
.collect()[0][0],
)
session.add_import(
test_files.test_sp_directory, import_path="resources.test_sp_dir"
)
plus4_then_mod5_sp = sproc(
plus4_then_mod5, return_type=IntegerType(), input_types=[IntegerType()]
)
assert plus4_then_mod5_sp(3) == 2
session.add_import(test_files.test_sp_directory)
plus4_then_mod5_direct_import_sp = sproc(
plus4_then_mod5_direct_import,
return_type=IntegerType(),
input_types=[IntegerType()],
)
assert plus4_then_mod5_direct_import_sp(3) == 2
# clean
session.clear_imports()
def test_add_import_stage_file(session, resources_path):
test_files = TestFiles(resources_path)
def plus4_then_mod5(session_, x):
from test_sp_file import mod5
return mod5(
session_,
session_.create_dataframe([[x]], schema=["a"])
.select(col("a") + 4)
.collect()[0][0],
)
stage_file = f"@{tmp_stage_name}/{os.path.basename(test_files.test_sp_py_file)}"
session.add_import(stage_file)
plus4_then_mod5_sp = sproc(
plus4_then_mod5, return_type=IntegerType(), input_types=[IntegerType()]
)
assert plus4_then_mod5_sp(3) == 2
# clean
session.clear_imports()
def test_sp_level_import(session, resources_path, local_testing_mode):
test_files = TestFiles(resources_path)
def plus4_then_mod5(session_, x):
from test_sp_dir.test_sp_file import mod5
return mod5(
session_,
session_.create_dataframe([[x]], schema=["a"])
.select(col("a") + 4)
.collect()[0][0],
)
# with sp-level imports
plus4_then_mod5_sp = sproc(
plus4_then_mod5,
return_type=IntegerType(),
input_types=[IntegerType()],
imports=[(test_files.test_sp_py_file, "test_sp_dir.test_sp_file")],
)
assert plus4_then_mod5_sp(3) == 2
# without sp-level imports
plus4_then_mod5_sp = sproc(
plus4_then_mod5,
return_type=IntegerType(),
input_types=[IntegerType()],
)
with pytest.raises(SnowparkSQLException) as ex_info:
plus4_then_mod5_sp(3)
if local_testing_mode:
# Local testing nests the error, but pytest only provides the top level error message
assert "Python Interpreter Error" in ex_info.value.message
else:
assert "No module named" in ex_info.value.message
def test_type_hints(session):
@sproc()
def add_sp(session_: Session, x: int, y: int) -> int:
df = session_.create_dataframe(
[
(x, y),
]
).to_df(["a", "b"])
return df.select(col("a") + col("b")).collect()[0][0]
@sproc
def snow_sp(session_: Session, x: int) -> Optional[str]:
df = session_.create_dataframe(
[
(x),
]
).to_df(["a"])
return df.select(iff(col("a") % 2 == 0, "snow", None)).collect()[0][0]
@sproc
def double_str_list_sp(session_: Session, x: str) -> List[str]:
df = session_.create_dataframe(
[
(x),
]
).to_df(["a"])
val = df.collect()[0][0]
return [val, val]
dt = datetime.datetime.strptime("2017-02-24 12:00:05.456", "%Y-%m-%d %H:%M:%S.%f")
@sproc
def return_datetime_sp(_: Session) -> datetime.datetime:
return dt
@sproc
def first_element_sp(_: Session, x: List[str]) -> str:
return x[0]
@sproc
def get_sp(_: Session, d: Dict[str, str], i: str) -> str:
return d[i]
assert add_sp(1, 2) == 3
assert snow_sp(1) is None
assert snow_sp(2) == "snow"
assert double_str_list_sp("abc") == '[\n "abc",\n "abc"\n]'
assert return_datetime_sp() == dt
assert first_element_sp(["0", "'"]) == "0"
assert get_sp({"0": "snow", "1": "flake"}, "0") == "snow"
def test_type_hint_no_change_after_registration(session):
def add(session_: Session, x: int, y: int) -> int:
return (
session_.create_dataframe([(x, y)])
.to_df("a", "b")
.select(col("a") + col("b"))
.collect()[0][0],
)
annotations = add.__annotations__
session.sproc.register(add)
assert annotations == add.__annotations__
def test_register_sp_from_file_type_hints(session, tmpdir):
source = """
import datetime
import snowflake
from snowflake.snowpark import Session
from typing import Dict, List, Optional
from snowflake.snowpark.functions import (
col,
iff,
lit
)
def add(session: snowflake.snowpark.Session, x: int, y: int) -> int:
return session.create_dataframe([[x, y]], schema=["x", "y"]).select(col("x")+col("y")).collect()[0][0]
def snow(session_: Session, x: int) -> Optional[str]:
return session_.create_dataframe([[x]],schema=["x"]).select(iff(col("x")%2==0, lit('snow'), lit(None))).collect()[0][0]
def double_str_list(session_: snowflake.snowpark.Session, x: str) -> List[str]:
val = session_.create_dataframe([[str(x)]]).collect()[0][0]
return [val, val]
dt = datetime.datetime.strptime("2017-02-24 12:00:05.456", "%Y-%m-%d %H:%M:%S.%f")
def return_datetime(_: Session) -> datetime.datetime:
return dt
"""
file_path = os.path.join(tmpdir, "register_from_file_type_hints.py")
with open(file_path, "w") as f:
f.write(source)
add_sp = session.sproc.register_from_file(file_path, "add")
add_sp_with_statement_params = session.sproc.register_from_file(
file_path, "add", statement_params={"SF_PARTNER": "FAKE_PARTNER"}
)
snow_sp = session.sproc.register_from_file(file_path, "snow")
double_str_list_sp = session.sproc.register_from_file(file_path, "double_str_list")
return_datetime_sp = session.sproc.register_from_file(file_path, "return_datetime")
assert add_sp(1, 2) == 3
assert add_sp_with_statement_params(1, 2) == 3
assert snow_sp(0) == "snow"
assert snow_sp(1) is None
assert double_str_list_sp("abc") == '[\n "abc",\n "abc"\n]'
dt = datetime.datetime.strptime("2017-02-24 12:00:05.456", "%Y-%m-%d %H:%M:%S.%f")
assert return_datetime_sp() == dt
@pytest.mark.xfail(
"config.getoption('local_testing_mode', default=False)",
reason="SNOW-1412530 to fix bug",
run=False,
)
@pytest.mark.parametrize("register_from_file", [True, False])
def test_register_sp_with_optional_args(session: Session, tmpdir, register_from_file):
import decimal # noqa: F401
from snowflake.snowpark.types import Variant, Geometry, Geography # noqa: F401
import_body = """
import datetime
import decimal
from snowflake.snowpark import Session
from snowflake.snowpark.types import Variant, Geometry, Geography
from snowflake.snowpark.functions import (
col,
iff,
lit
)
from typing import Dict, List, Optional
"""
func_body = """
def add(session_: Session, x: int = 0, y: int = 0) -> int:
return (
session_.create_dataframe([[x, y]], schema=["x", "y"])
.select(col("x") + col("y"))
.collect()[0][0]
)
def snow(session_: Session, x: int = 1) -> Optional[str]:
return (
session_.create_dataframe([[x]], schema=["x"])
.select(iff(col("x") % 2 == 0, lit("snow"), lit(None)))
.collect()[0][0]
)
def double_str_list(session_: Session, x: str = "a") -> List[str]:
val = session_.create_dataframe([[str(x)]]).collect()[0][0]
return [val, val]
def return_date(
_: Session, dt: datetime.date = datetime.date(2017, 1, 1)
) -> datetime.date:
return dt
def return_arr(
_: Session, base_arr: List[int], extra_arr: List[int] = [4]
) -> List[int]:
base_arr.extend(extra_arr)
return base_arr
def return_all_datatypes(
_: Session,
a: int = 1,
b: float = 1.0,
c: str = "one",
d: List[int] = [],
e: Dict[str, int] = {"s": 1},
f: Variant = {"key": "val"},
g: Geometry = "POINT(-122.35 37.55)",
h: Geography = "POINT(-122.35 37.55)",
i: datetime.datetime = datetime.datetime(2021, 1, 1, 0, 0, 0),
j: datetime.date = datetime.date(2021, 1, 1),
k: datetime.time = datetime.time(0, 0, 0),
l: bytes = b"123",
m: bool = True,
n: decimal.Decimal = decimal.Decimal(1.0),
) -> str:
final_str = f"{a}, {b}, {c}, {d}, {e}, {f}, {g}, {h}, {i}, {j}, {k}, {l}, {m}, {n}"
return final_str
"""
if register_from_file:
file_path = os.path.join(tmpdir, "register_from_file_optional_args.py")
with open(file_path, "w") as f:
source = f"{import_body}\n{func_body}"
f.write(source)
add_sp = session.sproc.register_from_file(file_path, "add")
snow_sp = session.sproc.register_from_file(file_path, "snow")
double_str_list_sp = session.sproc.register_from_file(
file_path, "double_str_list"
)
return_date_sp = session.sproc.register_from_file(file_path, "return_date")
return_arr_sp = session.sproc.register_from_file(file_path, "return_arr")
return_all_types_sp = session.sproc.register_from_file(
file_path, "return_all_datatypes"
)
else:
d = {}
exec(func_body, {**globals(), **locals()}, d)
add_sp = session.sproc.register(d["add"])
snow_sp = session.sproc.register(d["snow"])
double_str_list_sp = session.sproc.register(d["double_str_list"])
return_date_sp = session.sproc.register(d["return_date"])
return_arr_sp = session.sproc.register(d["return_arr"])
return_all_types_sp = session.sproc.register(d["return_all_datatypes"])
assert add_sp(1, 2) == 3
assert add_sp(1) == 1
assert add_sp() == 0
assert snow_sp(0) == "snow"
assert snow_sp(1) is None
assert snow_sp() is None
assert double_str_list_sp("abc") == '[\n "abc",\n "abc"\n]'
assert double_str_list_sp() == '[\n "a",\n "a"\n]'
assert return_date_sp(datetime.date(2024, 1, 2)) == datetime.date(2024, 1, 2)
assert return_date_sp() == datetime.date(2017, 1, 1)
assert return_arr_sp([1, 2, 3], [4, 5]) == "[\n 1,\n 2,\n 3,\n 4,\n 5\n]"
assert return_arr_sp([1, 2, 3]) == "[\n 1,\n 2,\n 3,\n 4\n]"
assert return_all_types_sp() == (
"1, 1.0, one, [], {'s': 1}, {'key': 'val'}, {'coordinates': [-122.35, 37.55], 'type': 'Point'}, "
"{'coordinates': [-122.35, 37.55], 'type': 'Point'}, 2021-01-01 00:00:00, 2021-01-01, 00:00:00, "
"b'123', True, 1.000000000000000000"
)
assert return_all_types_sp(2, 2.0, "two", [1, 2, 3]) == (
"2, 2.0, two, [1, 2, 3], {'s': 1}, {'key': 'val'}, {'coordinates': [-122.35, 37.55], 'type': 'Point'}, "
"{'coordinates': [-122.35, 37.55], 'type': 'Point'}, 2021-01-01 00:00:00, 2021-01-01, 00:00:00, "
"b'123', True, 1.000000000000000000"
)
@pytest.mark.xfail(
"config.getoption('local_testing_mode', default=False)",
reason="Database objects do not persist across sessions in Local Testing",
run=False,
)
@pytest.mark.skipif(IS_IN_STORED_PROC, reason="Cannot create session in SP")
def test_permanent_sp(session, db_parameters):
stage_name = Utils.random_stage_name()
sp_name = Utils.random_name_for_temp_object(TempObjectType.PROCEDURE)
with Session.builder.configs(db_parameters).create() as new_session:
new_session.sql_simplifier_enabled = session.sql_simplifier_enabled
new_session.add_packages("snowflake-snowpark-python")
try:
Utils.create_stage(session, stage_name, is_temporary=False)
sproc(
lambda session_, x, y: session_.sql(f"SELECT {x} + {y}").collect()[0][
0
],
return_type=IntegerType(),
input_types=[IntegerType(), IntegerType()],
name=sp_name,
is_permanent=True,
stage_location=stage_name,
session=new_session,
)
assert session.call(sp_name, 1, 2) == 3
assert new_session.call(sp_name, 8, 9) == 17
finally:
session._run_query(f"drop function if exists {sp_name}(int, int)")
Utils.drop_stage(session, stage_name)