/
session.py
2025 lines (1797 loc) · 86.1 KB
/
session.py
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-2023 Snowflake Computing Inc. All rights reserved.
#
import datetime
import decimal
import json
import logging
import os
from array import array
from functools import reduce
from logging import getLogger
from threading import RLock
from types import ModuleType
from typing import Any, Dict, List, Literal, Optional, Set, Tuple, Union
import cloudpickle
import pkg_resources
from snowflake.connector import ProgrammingError, SnowflakeConnection
from snowflake.connector.options import installed_pandas, pandas
from snowflake.connector.pandas_tools import write_pandas
from snowflake.snowpark._internal.analyzer.analyzer import Analyzer
from snowflake.snowpark._internal.analyzer.analyzer_utils import (
escape_quotes,
quote_name,
)
from snowflake.snowpark._internal.analyzer.datatype_mapper import str_to_sql
from snowflake.snowpark._internal.analyzer.expression import Attribute
from snowflake.snowpark._internal.analyzer.select_statement import (
SelectSnowflakePlan,
SelectSQL,
SelectStatement,
SelectTableFunction,
)
from snowflake.snowpark._internal.analyzer.snowflake_plan import SnowflakePlanBuilder
from snowflake.snowpark._internal.analyzer.snowflake_plan_node import (
Range,
SnowflakeValues,
)
from snowflake.snowpark._internal.analyzer.table_function import (
FlattenFunction,
GeneratorTableFunction,
TableFunctionRelation,
)
from snowflake.snowpark._internal.error_message import SnowparkClientExceptionMessages
from snowflake.snowpark._internal.server_connection import ServerConnection
from snowflake.snowpark._internal.telemetry import set_api_call_source
from snowflake.snowpark._internal.type_utils import (
ColumnOrName,
infer_schema,
merge_type,
)
from snowflake.snowpark._internal.udf_utils import generate_call_python_sp_sql
from snowflake.snowpark._internal.utils import (
MODULE_NAME_TO_PACKAGE_NAME_MAP,
STAGE_PREFIX,
SUPPORTED_TABLE_TYPES,
PythonObjJSONEncoder,
TempObjectType,
calculate_checksum,
deprecated,
experimental,
get_connector_version,
get_os_name,
get_python_version,
get_stage_file_prefix_length,
get_temp_type_for_object,
get_version,
is_in_stored_procedure,
normalize_remote_file_or_dir,
parse_positional_args_to_list,
random_name_for_temp_object,
unwrap_single_quote,
unwrap_stage_location_single_quote,
validate_object_name,
warning,
zip_file_or_directory_to_stream,
)
from snowflake.snowpark.async_job import AsyncJob
from snowflake.snowpark.column import Column
from snowflake.snowpark.context import _use_scoped_temp_objects
from snowflake.snowpark.dataframe import DataFrame
from snowflake.snowpark.dataframe_reader import DataFrameReader
from snowflake.snowpark.file_operation import FileOperation
from snowflake.snowpark.functions import (
array_agg,
col,
column,
lit,
parse_json,
to_array,
to_date,
to_decimal,
to_geography,
to_object,
to_time,
to_timestamp,
to_variant,
)
from snowflake.snowpark.query_history import QueryHistory
from snowflake.snowpark.row import Row
from snowflake.snowpark.stored_procedure import StoredProcedureRegistration
from snowflake.snowpark.table import Table
from snowflake.snowpark.table_function import (
TableFunctionCall,
_create_table_function_expression,
)
from snowflake.snowpark.types import (
ArrayType,
DateType,
DecimalType,
GeographyType,
MapType,
StringType,
StructType,
TimestampType,
TimeType,
VariantType,
_AtomicType,
)
from snowflake.snowpark.udf import UDFRegistration
from snowflake.snowpark.udtf import UDTFRegistration
# 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
try:
from typing import Iterable
except ImportError:
from collections.abc import Iterable
_logger = getLogger(__name__)
_session_management_lock = RLock()
_active_sessions: Set["Session"] = set()
_PYTHON_SNOWPARK_USE_SCOPED_TEMP_OBJECTS_STRING = (
"PYTHON_SNOWPARK_USE_SCOPED_TEMP_OBJECTS"
)
_PYTHON_SNOWPARK_USE_SQL_SIMPLIFIER_STRING = "PYTHON_SNOWPARK_USE_SQL_SIMPLIFIER"
WRITE_PANDAS_CHUNK_SIZE: int = 100000 if is_in_stored_procedure() else None
def _get_active_session() -> Optional["Session"]:
with _session_management_lock:
if len(_active_sessions) == 1:
return next(iter(_active_sessions))
elif len(_active_sessions) > 1:
raise SnowparkClientExceptionMessages.MORE_THAN_ONE_ACTIVE_SESSIONS()
else:
raise SnowparkClientExceptionMessages.SERVER_NO_DEFAULT_SESSION()
def _add_session(session: "Session") -> None:
with _session_management_lock:
_active_sessions.add(session)
def _remove_session(session: "Session") -> None:
with _session_management_lock:
try:
_active_sessions.remove(session)
except KeyError:
pass
class Session:
"""
Establishes a connection with a Snowflake database and provides methods for creating DataFrames
and accessing objects for working with files in stages.
When you create a :class:`Session` object, you provide connection parameters to establish a
connection with a Snowflake database (e.g. an account, a user name, etc.). You can
specify these settings in a dict that associates connection parameters names with values.
The Snowpark library uses `the Snowflake Connector for Python <https://docs.snowflake.com/en/user-guide/python-connector.html>`_
to connect to Snowflake. Refer to
`Connecting to Snowflake using the Python Connector <https://docs.snowflake.com/en/user-guide/python-connector-example.html#connecting-to-snowflake>`_
for the details of `Connection Parameters <https://docs.snowflake.com/en/user-guide/python-connector-api.html#connect>`_.
To create a :class:`Session` object from a ``dict`` of connection parameters::
>>> connection_parameters = {
... "user": "<user_name>",
... "password": "<password>",
... "account": "<account_name>",
... "role": "<role_name>",
... "warehouse": "<warehouse_name>",
... "database": "<database_name>",
... "schema": "<schema_name>",
... }
>>> session = Session.builder.configs(connection_parameters).create() # doctest: +SKIP
To create a :class:`Session` object from an existing Python Connector connection::
>>> session = Session.builder.configs({"connection": <your python connector connection>}).create() # doctest: +SKIP
:class:`Session` contains functions to construct a :class:`DataFrame` like :meth:`table`,
:meth:`sql` and :attr:`read`, etc.
A :class:`Session` object is not thread-safe.
"""
class RuntimeConfig:
def __init__(self, session: "Session", conf: Dict[str, Any]) -> None:
self._session = session
self._conf = {
"use_constant_subquery_alias": True
} # For config that's temporary/to be removed soon
for key, val in conf.items():
if self.is_mutable(key):
self.set(key, val)
def get(self, key: str, default=None) -> Any:
if hasattr(Session, key):
return getattr(self._session, key)
if hasattr(self._session._conn._conn, key):
return getattr(self._session._conn._conn, key)
return self._conf.get(key, default)
def is_mutable(self, key: str) -> bool:
if hasattr(Session, key) and isinstance(getattr(Session, key), property):
return getattr(Session, key).fset is not None
if hasattr(SnowflakeConnection, key) and isinstance(
getattr(SnowflakeConnection, key), property
):
return getattr(SnowflakeConnection, key).fset is not None
return key in self._conf
def set(self, key: str, value: Any) -> None:
if self.is_mutable(key):
if hasattr(Session, key):
setattr(self._session, key, value)
if hasattr(SnowflakeConnection, key):
setattr(self._session._conn._conn, key, value)
if key in self._conf:
self._conf[key] = value
else:
raise AttributeError(
f'Configuration "{key}" does not exist or is not mutable in runtime'
)
class SessionBuilder:
"""
Provides methods to set connection parameters and create a :class:`Session`.
"""
def __init__(self) -> None:
self._options = {}
def _remove_config(self, key: str) -> "Session.SessionBuilder":
"""Only used in test."""
self._options.pop(key, None)
return self
def config(self, key: str, value: Union[int, str]) -> "Session.SessionBuilder":
"""
Adds the specified connection parameter to the :class:`SessionBuilder` configuration.
"""
self._options[key] = value
return self
def configs(
self, options: Dict[str, Union[int, str]]
) -> "Session.SessionBuilder":
"""
Adds the specified :class:`dict` of connection parameters to
the :class:`SessionBuilder` configuration.
Note:
Calling this method overwrites any existing connection parameters
that you have already set in the SessionBuilder.
"""
self._options = {**self._options, **options}
return self
def create(self) -> "Session":
"""Creates a new Session."""
session = self._create_internal(self._options.get("connection"))
return session
def _create_internal(
self, conn: Optional[SnowflakeConnection] = None
) -> "Session":
# Set paramstyle to qmark by default to be consistent with previous behavior
if "paramstyle" not in self._options:
self._options["paramstyle"] = "qmark"
new_session = Session(
ServerConnection({}, conn) if conn else ServerConnection(self._options),
self._options,
)
if "password" in self._options:
self._options["password"] = None
_add_session(new_session)
return new_session
def __get__(self, obj, objtype=None):
return Session.SessionBuilder()
#: Returns a builder you can use to set configuration properties
#: and create a :class:`Session` object.
builder: SessionBuilder = SessionBuilder()
def __init__(
self, conn: ServerConnection, options: Optional[Dict[str, Any]] = None
) -> None:
if len(_active_sessions) >= 1 and is_in_stored_procedure():
raise SnowparkClientExceptionMessages.DONT_CREATE_SESSION_IN_SP()
self._conn = conn
self._query_tag = None
self._import_paths: Dict[str, Tuple[Optional[str], Optional[str]]] = {}
self._packages: Dict[str, str] = {}
self._session_id = self._conn.get_session_id()
self._session_info = f"""
"version" : {get_version()},
"python.version" : {get_python_version()},
"python.connector.version" : {get_connector_version()},
"python.connector.session.id" : {self._session_id},
"os.name" : {get_os_name()}
"""
self._session_stage = random_name_for_temp_object(TempObjectType.STAGE)
self._stage_created = False
self._udf_registration = UDFRegistration(self)
self._udtf_registration = UDTFRegistration(self)
self._sp_registration = StoredProcedureRegistration(self)
self._plan_builder = SnowflakePlanBuilder(self)
self._last_action_id = 0
self._last_canceled_id = 0
self._use_scoped_temp_objects: bool = (
_use_scoped_temp_objects
and self._get_client_side_session_parameter(
_PYTHON_SNOWPARK_USE_SCOPED_TEMP_OBJECTS_STRING, True
)
)
self._file = FileOperation(self)
self._analyzer = Analyzer(self)
self._sql_simplifier_enabled: bool = self._get_client_side_session_parameter(
_PYTHON_SNOWPARK_USE_SQL_SIMPLIFIER_STRING, True
)
self._conf = self.RuntimeConfig(self, options or {})
_logger.info("Snowpark Session information: %s", self._session_info)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def __str__(self):
return (
f"<{self.__class__.__module__}.{self.__class__.__name__}: account={self.get_current_account()}, "
f"role={self.get_current_role()}, database={self.get_current_database()}, "
f"schema={self.get_current_schema()}, warehouse={self.get_current_warehouse()}>"
)
def _generate_new_action_id(self) -> int:
self._last_action_id += 1
return self._last_action_id
def close(self) -> None:
"""Close this session."""
if is_in_stored_procedure():
raise SnowparkClientExceptionMessages.DONT_CLOSE_SESSION_IN_SP()
try:
if self._conn.is_closed():
_logger.debug(
"No-op because session %s had been previously closed.",
self._session_id,
)
else:
_logger.info("Closing session: %s", self._session_id)
self.cancel_all()
except Exception as ex:
raise SnowparkClientExceptionMessages.SERVER_FAILED_CLOSE_SESSION(str(ex))
finally:
try:
self._conn.close()
_logger.info("Closed session: %s", self._session_id)
finally:
_remove_session(self)
@property
def conf(self) -> RuntimeConfig:
return self._conf
@property
def sql_simplifier_enabled(self) -> bool:
return self._sql_simplifier_enabled
@sql_simplifier_enabled.setter
def sql_simplifier_enabled(self, value: bool) -> None:
"""Set to ``True`` to use the SQL simplifier.
The generated SQLs from ``DataFrame`` transformations would have fewer layers of nested queries if the SQL simplifier is enabled."""
self._conn._telemetry_client.send_sql_simplifier_telemetry(
self._session_id, value
)
try:
self._conn._cursor.execute(
f"alter session set {_PYTHON_SNOWPARK_USE_SQL_SIMPLIFIER_STRING} = {value}"
)
except Exception:
pass
self._sql_simplifier_enabled = value
def cancel_all(self) -> None:
"""
Cancel all action methods that are running currently.
This does not affect any action methods called in the future.
"""
_logger.info("Canceling all running queries")
self._last_canceled_id = self._last_action_id
self._conn.run_query(f"select system$cancel_all_queries({self._session_id})")
def get_imports(self) -> List[str]:
"""
Returns a list of imports added for user defined functions (UDFs).
This list includes any Python or zip files that were added automatically by the library.
"""
return list(self._import_paths.keys())
def add_import(self, path: str, import_path: Optional[str] = None) -> None:
"""
Registers a remote file in stage or a local file as an import of a user-defined function
(UDF). The local file can be a compressed file (e.g., zip), a Python file (.py),
a directory, or any other file resource. You can also find examples in
:class:`~snowflake.snowpark.udf.UDFRegistration`.
Args:
path: The path of a local file or a remote file in the stage. In each case:
* if the path points to a local file, this file will be uploaded to the
stage where the UDF is registered and Snowflake will import the file when
executing that UDF.
* if the path points to a local directory, the directory will be compressed
as a zip file and will be uploaded to the stage where the UDF is registered
and Snowflake will import the file when executing that UDF.
* if the path points to a file in a stage, the file will be included in the
imports when executing a UDF.
import_path: The relative Python import path for a UDF.
If it is not provided or it is None, the UDF will import the package
directly without any leading package/module. This argument will become
a no-op if the path points to a stage file or a non-Python local file.
Example::
>>> from snowflake.snowpark.types import IntegerType
>>> from resources.test_udf_dir.test_udf_file import mod5
>>> session.add_import("tests/resources/test_udf_dir/test_udf_file.py", import_path="resources.test_udf_dir.test_udf_file")
>>> mod5_and_plus1_udf = session.udf.register(
... lambda x: mod5(x) + 1,
... return_type=IntegerType(),
... input_types=[IntegerType()]
... )
>>> session.range(1, 8, 2).select(mod5_and_plus1_udf("id")).to_df("col1").collect()
[Row(COL1=2), Row(COL1=4), Row(COL1=1), Row(COL1=3)]
>>> session.clear_imports()
Note:
1. In favor of the lazy execution, the file will not be uploaded to the stage
immediately, and it will be uploaded when a UDF is created.
2. The Snowpark library calculates a sha256 checksum for every file/directory.
Each file is uploaded to a subdirectory named after the checksum for the
file in the stage. If there is an existing file or directory, the Snowpark
library will compare their checksums to determine whether it should be re-uploaded.
Therefore, after uploading a local file to the stage, if the user makes
some changes to this file and intends to upload it again, just call this
function with the file path again, the existing file in the stage will be
overwritten by the re-uploaded file.
3. Adding two files with the same file name is not allowed, because UDFs
can't be created with two imports with the same name.
4. This method will register the file for all UDFs created later in the current
session. If you only want to import a file for a specific UDF, you can use
``imports`` argument in :func:`functions.udf` or
:meth:`session.udf.register() <snowflake.snowpark.udf.UDFRegistration.register>`.
"""
path, checksum, leading_path = self._resolve_import_path(path, import_path)
self._import_paths[path] = (checksum, leading_path)
def remove_import(self, path: str) -> None:
"""
Removes a file in stage or local file from the imports of a user-defined function (UDF).
Args:
path: a path pointing to a local file or a remote file in the stage
Examples::
>>> session.clear_imports()
>>> len(session.get_imports())
0
>>> session.add_import("tests/resources/test_udf_dir/test_udf_file.py")
>>> len(session.get_imports())
1
>>> session.remove_import("tests/resources/test_udf_dir/test_udf_file.py")
>>> len(session.get_imports())
0
"""
trimmed_path = path.strip()
abs_path = (
os.path.abspath(trimmed_path)
if not trimmed_path.startswith(STAGE_PREFIX)
else trimmed_path
)
if abs_path not in self._import_paths:
raise KeyError(f"{abs_path} is not found in the existing imports")
else:
self._import_paths.pop(abs_path)
def clear_imports(self) -> None:
"""
Clears all files in a stage or local files from the imports of a user-defined function (UDF).
"""
self._import_paths.clear()
def _resolve_import_path(
self, path: str, import_path: Optional[str] = None
) -> Tuple[str, Optional[str], Optional[str]]:
trimmed_path = path.strip()
trimmed_import_path = import_path.strip() if import_path else None
if not trimmed_path.startswith(STAGE_PREFIX):
if not os.path.exists(trimmed_path):
raise FileNotFoundError(f"{trimmed_path} is not found")
if not os.path.isfile(trimmed_path) and not os.path.isdir(
trimmed_path
): # pragma: no cover
# os.path.isfile() returns True when the passed in file is a symlink.
# So this code might not be reachable. To avoid mistakes, keep it here for now.
raise ValueError(
f"add_import() only accepts a local file or directory, "
f"or a file in a stage, but got {trimmed_path}"
)
abs_path = os.path.abspath(trimmed_path)
# convert the Python import path to the file path
# and extract the leading path, where
# absolute path = [leading path]/[parsed file path of Python import path]
if trimmed_import_path is not None:
# the import path only works for the directory and the Python file
if os.path.isdir(abs_path):
import_file_path = trimmed_import_path.replace(".", os.path.sep)
elif os.path.isfile(abs_path) and abs_path.endswith(".py"):
import_file_path = (
f"{trimmed_import_path.replace('.', os.path.sep)}.py"
)
else:
import_file_path = None
if import_file_path:
if abs_path.endswith(import_file_path):
leading_path = abs_path[: -len(import_file_path)]
else:
raise ValueError(
f"import_path {trimmed_import_path} is invalid "
f"because it's not a part of path {abs_path}"
)
else:
leading_path = None
else:
leading_path = None
# Include the information about import path to the checksum
# calculation, so if the import path changes, the checksum
# will change and the file in the stage will be overwritten.
return (
abs_path,
calculate_checksum(abs_path, additional_info=leading_path),
leading_path,
)
else:
return trimmed_path, None, None
def _resolve_imports(
self,
stage_location: str,
udf_level_import_paths: Optional[
Dict[str, Tuple[Optional[str], Optional[str]]]
] = None,
*,
statement_params: Optional[Dict[str, str]] = None,
) -> List[str]:
"""Resolve the imports and upload local files (if any) to the stage."""
resolved_stage_files = []
stage_file_list = self._list_files_in_stage(
stage_location, statement_params=statement_params
)
normalized_stage_location = unwrap_stage_location_single_quote(stage_location)
import_paths = udf_level_import_paths or self._import_paths
for path, (prefix, leading_path) in import_paths.items():
# stage file
if path.startswith(STAGE_PREFIX):
resolved_stage_files.append(path)
else:
filename = (
f"{os.path.basename(path)}.zip"
if os.path.isdir(path) or path.endswith(".py")
else os.path.basename(path)
)
filename_with_prefix = f"{prefix}/{filename}"
if filename_with_prefix in stage_file_list:
_logger.debug(
f"{filename} exists on {normalized_stage_location}, skipped"
)
else:
# local directory or .py file
if os.path.isdir(path) or path.endswith(".py"):
with zip_file_or_directory_to_stream(
path, leading_path, add_init_py=True
) as input_stream:
self._conn.upload_stream(
input_stream=input_stream,
stage_location=normalized_stage_location,
dest_filename=filename,
dest_prefix=prefix,
source_compression="DEFLATE",
compress_data=False,
overwrite=True,
is_in_udf=True,
)
# local file
else:
self._conn.upload_file(
path=path,
stage_location=normalized_stage_location,
dest_prefix=prefix,
compress_data=False,
overwrite=True,
)
resolved_stage_files.append(
normalize_remote_file_or_dir(
f"{normalized_stage_location}/{filename_with_prefix}"
)
)
return resolved_stage_files
def _list_files_in_stage(
self,
stage_location: Optional[str] = None,
*,
statement_params: Optional[Dict[str, str]] = None,
) -> Set[str]:
normalized = normalize_remote_file_or_dir(
unwrap_single_quote(stage_location)
if stage_location
else self._session_stage
)
file_list = (
self.sql(f"ls {normalized}")
.select('"name"')
._internal_collect_with_tag(statement_params=statement_params)
)
prefix_length = get_stage_file_prefix_length(stage_location)
return {str(row[0])[prefix_length:] for row in file_list}
def get_packages(self) -> Dict[str, str]:
"""
Returns a ``dict`` of packages added for user-defined functions (UDFs).
The key of this ``dict`` is the package name and the value of this ``dict``
is the corresponding requirement specifier.
"""
return self._packages.copy()
def add_packages(
self, *packages: Union[str, ModuleType, Iterable[Union[str, ModuleType]]]
) -> None:
"""
Adds third-party packages as dependencies of a user-defined function (UDF).
Use this method to add packages for UDFs as installing packages using
`conda <https://docs.conda.io/en/latest/>`_. You can also find examples in
:class:`~snowflake.snowpark.udf.UDFRegistration`. See details of
`third-party Python packages in Snowflake <https://docs.snowflake.com/en/developer-guide/udf/python/udf-python-packages.html>`_.
Args:
packages: A `requirement specifier <https://packaging.python.org/en/latest/glossary/#term-Requirement-Specifier>`_,
a ``module`` object or a list of them for installing the packages. An exception
will be raised if two conflicting requirement specifiers are provided.
The syntax of a requirement specifier is defined in full in
`PEP 508 <https://www.python.org/dev/peps/pep-0508/>`_, but currently only the
`version matching clause <https://www.python.org/dev/peps/pep-0440/#version-matching>`_ (``==``)
is supported as a `version specifier <https://packaging.python.org/en/latest/glossary/#term-Version-Specifier>`_
for this argument. If a ``module`` object is provided, the package will be
installed with the version in the local environment.
Example::
>>> import numpy as np
>>> from snowflake.snowpark.functions import udf
>>> import numpy
>>> import pandas
>>> import dateutil
>>> # add numpy with the latest version on Snowflake Anaconda
>>> # and pandas with the version "1.3.*"
>>> # and dateutil with the local version in your environment
>>> session.add_packages("numpy", "pandas==1.3.*", dateutil)
>>> @udf
... def get_package_name_udf() -> list:
... return [numpy.__name__, pandas.__name__, dateutil.__name__]
>>> session.sql(f"select {get_package_name_udf.name}()").to_df("col1").show()
----------------
|"COL1" |
----------------
|[ |
| "numpy", |
| "pandas", |
| "dateutil" |
|] |
----------------
<BLANKLINE>
>>> session.clear_packages()
Note:
1. This method will add packages for all UDFs created later in the current
session. If you only want to add packages for a specific UDF, you can use
``packages`` argument in :func:`functions.udf` or
:meth:`session.udf.register() <snowflake.snowpark.udf.UDFRegistration.register>`.
2. We recommend you to `setup the local environment with Anaconda <https://docs.snowflake.com/en/developer-guide/udf/python/udf-python-packages.html#local-development-and-testing>`_,
to ensure the consistent experience of a UDF between your local environment
and the Snowflake server.
"""
self._resolve_packages(parse_positional_args_to_list(*packages), self._packages)
def remove_package(self, package: str) -> None:
"""
Removes a third-party package from the dependency list of a user-defined function (UDF).
Args:
package: The package name.
Examples::
>>> session.clear_packages()
>>> len(session.get_packages())
0
>>> session.add_packages("numpy", "pandas==1.3.5")
>>> len(session.get_packages())
2
>>> session.remove_package("numpy")
>>> len(session.get_packages())
1
>>> session.remove_package("pandas")
>>> len(session.get_packages())
0
"""
package_name = pkg_resources.Requirement.parse(package).key
if package_name in self._packages:
self._packages.pop(package_name)
else:
raise ValueError(f"{package_name} is not in the package list")
def clear_packages(self) -> None:
"""
Clears all third-party packages of a user-defined function (UDF).
"""
self._packages.clear()
def add_requirements(self, file_path: str) -> None:
"""
Adds a `requirement file <https://pip.pypa.io/en/stable/user_guide/#requirements-files>`_
that contains a list of packages as dependencies of a user-defined function (UDF).
Args:
file_path: The path of a local requirement file.
Example::
>>> from snowflake.snowpark.functions import udf
>>> import numpy
>>> import pandas
>>> # test_requirements.txt contains "numpy" and "pandas"
>>> session.add_requirements("tests/resources/test_requirements.txt")
>>> @udf
... def get_package_name_udf() -> list:
... return [numpy.__name__, pandas.__name__]
>>> session.sql(f"select {get_package_name_udf.name}()").to_df("col1").show()
--------------
|"COL1" |
--------------
|[ |
| "numpy", |
| "pandas" |
|] |
--------------
<BLANKLINE>
>>> session.clear_packages()
Note:
1. This method will add packages for all UDFs created later in the current
session. If you only want to add packages for a specific UDF, you can use
``packages`` argument in :func:`functions.udf` or
:meth:`session.udf.register() <snowflake.snowpark.udf.UDFRegistration.register>`.
2. We recommend you to `setup the local environment with Anaconda <https://docs.snowflake.com/en/developer-guide/udf/python/udf-python-packages.html#local-development-and-testing>`_,
to ensure the consistent experience of a UDF between your local environment
and the Snowflake server.
"""
packages = []
with open(file_path) as f:
for line in f:
package = line.rstrip()
if package:
packages.append(package)
self.add_packages(packages)
def _resolve_packages(
self,
packages: List[Union[str, ModuleType]],
existing_packages_dict: Optional[Dict[str, str]] = None,
validate_package: bool = True,
include_pandas: bool = False,
) -> List[str]:
package_dict = dict()
for package in packages:
if isinstance(package, ModuleType):
package_name = MODULE_NAME_TO_PACKAGE_NAME_MAP.get(
package.__name__, package.__name__
)
package = f"{package_name}=={pkg_resources.get_distribution(package_name).version}"
use_local_version = True
else:
package = package.strip().lower()
use_local_version = False
package_req = pkg_resources.Requirement.parse(package)
# get the standard package name if there is no underscore
# underscores are discouraged in package names, but are still used in Anaconda channel
# pkg_resources.Requirement.parse will convert all underscores to dashes
package_name = (
package if not use_local_version and "_" in package else package_req.key
)
package_dict[package] = (package_name, use_local_version, package_req)
valid_packages = (
{
p[0]: json.loads(p[1])
for p in self.table("information_schema.packages")
.filter(
(col("language") == "python")
& (col("package_name").in_([v[0] for v in package_dict.values()]))
)
.group_by("package_name")
.agg(array_agg("version"))
._internal_collect_with_tag()
}
if validate_package and package_dict
else None
)
result_dict = (
existing_packages_dict if existing_packages_dict is not None else {}
)
for package, package_info in package_dict.items():
package_name, use_local_version, package_req = package_info
package_version_req = package_req.specs[0][1] if package_req.specs else None
if validate_package:
unavailable_pkg_err_msg = (
"it is not available in Snowflake. Check information_schema.packages "
"to see available packages for UDFs. If this package is a "
'"pure-Python" package, you can find the directory of this package '
"and add it via session.add_import(). See details at "
"https://docs.snowflake.com/en/developer-guide/snowpark/python/creating-udfs.html#using-third-party-packages-from-anaconda-in-a-udf."
)
if package_name not in valid_packages:
is_anaconda_terms_acknowledged = self._run_query(
"select system$are_anaconda_terms_acknowledged()"
)[0][0]
if is_anaconda_terms_acknowledged:
detailed_err_msg = unavailable_pkg_err_msg
else:
detailed_err_msg = (
"Anaconda terms must be accepted by ORGADMIN to use "
"Anaconda 3rd party packages. Please follow the instructions at "
"https://docs.snowflake.com/en/developer-guide/udf/python/udf-python-packages.html#using-third-party-packages-from-anaconda."
)
raise ValueError(
f"Cannot add package {package_name} because {detailed_err_msg}"
)
elif package_version_req and not any(
v in package_req for v in valid_packages[package_name]
):
raise ValueError(
f"Cannot add package {package_name}=={package_version_req} because {unavailable_pkg_err_msg}"
)
elif not use_local_version:
try:
package_client_version = pkg_resources.get_distribution(
package_name
).version
if package_client_version not in valid_packages[package_name]:
_logger.warning(
"The version of package %s in the local environment is %s, "
"which does not fit the criteria for the requirement %s. "
"Your UDF might not work when the package version is different "
"between the server and your local environment",
package_name,
package_client_version,
package,
)
except pkg_resources.DistributionNotFound:
_logger.warning(
"package %s is not installed in the local environment"
"Your UDF might not work when the package is installed "
"on the server but not on your local environment.",
package_name,
)
except Exception as ex: # pragma: no cover
logging.warning(
"Failed to get the local distribution of package %s: %s",
package_name,
ex,
)
if package_name in result_dict:
if result_dict[package_name] != package:
raise ValueError(
f"Cannot add {package} because {result_dict[package_name]} "
"is already added"
)
else:
result_dict[package_name] = package
def get_req_identifiers_list(
modules: List[Union[str, ModuleType]]
) -> List[str]:
res = []
for m in modules:
if isinstance(m, str) and m not in result_dict:
res.append(m)
elif isinstance(m, ModuleType) and m.__name__ not in result_dict:
res.append(f"{m.__name__}=={m.__version__}")
return res
# always include cloudpickle
extra_modules = [cloudpickle]
if include_pandas:
extra_modules.append("pandas")
return list(result_dict.values()) + get_req_identifiers_list(extra_modules)
@property
def query_tag(self) -> Optional[str]:
"""
The query tag for this session.
:getter: Returns the query tag. You can use the query tag to find all queries
run for this session in the History page of the Snowflake web interface.
:setter: Sets the query tag. If the input is ``None`` or an empty :class:`str`,
the session's query_tag will be unset. If the query tag is not set, the default
will be the call stack when a :class:`DataFrame` method that pushes down the SQL
query to the Snowflake Database is called. For example, :meth:`DataFrame.collect`,
:meth:`DataFrame.show`, :meth:`DataFrame.create_or_replace_view` and
:meth:`DataFrame.create_or_replace_temp_view` will push down the SQL query.
"""
return self._query_tag
@query_tag.setter
def query_tag(self, tag: str) -> None:
if tag:
self._conn.run_query(f"alter session set query_tag = {str_to_sql(tag)}")
else:
self._conn.run_query("alter session unset query_tag")
self._query_tag = tag
def table(self, name: Union[str, Iterable[str]]) -> Table:
"""
Returns a Table that points the specified table.
Args:
name: A string or list of strings that specify the table name or
fully-qualified object identifier (database name, schema name, and table name).
Note:
If your table name contains special characters, use double quotes to mark it like this, ``session.table('"my table"')``.
For fully qualified names, you need to use double quotes separately like this, ``session.table('"my db"."my schema"."my.table"')``.
Refer to `Identifier Requirements <https://docs.snowflake.com/en/sql-reference/identifiers-syntax.html>`_.
Examples::
>>> df1 = session.create_dataframe([[1, 2], [3, 4]], schema=["a", "b"])
>>> df1.write.save_as_table("my_table", mode="overwrite", table_type="temporary")
>>> session.table("my_table").collect()
[Row(A=1, B=2), Row(A=3, B=4)]
>>> current_db = session.get_current_database()
>>> current_schema = session.get_current_schema()
>>> session.table([current_db, current_schema, "my_table"]).collect()
[Row(A=1, B=2), Row(A=3, B=4)]
"""