-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathsession.py
More file actions
4107 lines (3661 loc) · 177 KB
/
session.py
File metadata and controls
4107 lines (3661 loc) · 177 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-2024 Snowflake Computing Inc. All rights reserved.
#
import atexit
import datetime
import decimal
import inspect
import json
import os
import re
import sys
import tempfile
import warnings
from array import array
from functools import reduce
from logging import getLogger
from threading import RLock
from types import ModuleType
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Union,
)
import cloudpickle
import pkg_resources
import snowflake.snowpark._internal.proto.generated.ast_pb2 as proto
import snowflake.snowpark.context as context
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 import analyzer_utils
from snowflake.snowpark._internal.analyzer.analyzer import Analyzer
from snowflake.snowpark._internal.analyzer.analyzer_utils import result_scan_statement
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 (
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.analyzer.unary_expression import Cast
from snowflake.snowpark._internal.ast.batch import AstBatch
from snowflake.snowpark._internal.ast.utils import (
add_intermediate_stmt,
build_expr_from_python_val,
build_indirect_table_fn_apply,
build_proto_from_struct_type,
build_sp_table_name,
with_src_position,
)
from snowflake.snowpark._internal.error_message import SnowparkClientExceptionMessages
from snowflake.snowpark._internal.packaging_utils import (
DEFAULT_PACKAGES,
ENVIRONMENT_METADATA_FILE_NAME,
IMPLICIT_ZIP_FILE_NAME,
delete_files_belonging_to_packages,
detect_native_dependencies,
get_signature,
identify_supported_packages,
map_python_packages_to_files_and_folders,
parse_conda_environment_yaml_file,
parse_requirements_text_file,
pip_install_packages_to_target_folder,
zip_directory_contents,
)
from snowflake.snowpark._internal.server_connection import ServerConnection
from snowflake.snowpark._internal.telemetry import set_api_call_source
from snowflake.snowpark._internal.temp_table_auto_cleaner import TempTableAutoCleaner
from snowflake.snowpark._internal.type_utils import (
ColumnOrName,
convert_sp_to_sf_type,
infer_schema,
infer_type,
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,
check_flatten_mode,
create_rlock,
create_thread_local,
deprecated,
escape_quotes,
experimental,
experimental_parameter,
get_connector_version,
get_os_name,
get_python_version,
get_stage_file_prefix_length,
get_temp_type_for_object,
get_version,
import_or_missing_modin_pandas,
is_in_stored_procedure,
normalize_local_file,
normalize_remote_file_or_dir,
parse_positional_args_to_list,
parse_positional_args_to_list_variadic,
private_preview,
publicapi,
quote_name,
random_name_for_temp_object,
strip_double_quotes_in_like_statement_in_table_name,
unwrap_single_quote,
unwrap_stage_location_single_quote,
validate_object_name,
warn_session_config_update_in_multithreaded_mode,
warning,
zip_file_or_directory_to_stream,
)
from snowflake.snowpark.async_job import AsyncJob
from snowflake.snowpark.catalog import Catalog
from snowflake.snowpark.column import Column
from snowflake.snowpark.context import (
_is_execution_environment_sandboxed_for_client,
_use_scoped_temp_objects,
)
from snowflake.snowpark.dataframe import DataFrame
from snowflake.snowpark.dataframe_reader import DataFrameReader
from snowflake.snowpark.exceptions import (
SnowparkClientException,
SnowparkSessionException,
)
from snowflake.snowpark.file_operation import FileOperation
from snowflake.snowpark.functions import (
array_agg,
col,
column,
lit,
parse_json,
to_date,
to_decimal,
to_geography,
to_geometry,
to_time,
to_timestamp,
to_timestamp_ltz,
to_timestamp_ntz,
to_timestamp_tz,
to_variant,
)
from snowflake.snowpark.lineage import Lineage
from snowflake.snowpark.mock._analyzer import MockAnalyzer
from snowflake.snowpark.mock._connection import MockServerConnection
from snowflake.snowpark.mock._nop_analyzer import NopAnalyzer
from snowflake.snowpark.mock._nop_connection import NopConnection
from snowflake.snowpark.mock._pandas_util import (
_convert_dataframe_to_table,
_extract_schema_and_data_from_pandas_df,
)
from snowflake.snowpark.mock._plan_builder import MockSnowflakePlanBuilder
from snowflake.snowpark.mock._stored_procedure import MockStoredProcedureRegistration
from snowflake.snowpark.mock._udaf import MockUDAFRegistration
from snowflake.snowpark.mock._udf import MockUDFRegistration
from snowflake.snowpark.mock._udtf import MockUDTFRegistration
from snowflake.snowpark.query_history import AstListener, QueryHistory
from snowflake.snowpark.row import Row
from snowflake.snowpark.stored_procedure import StoredProcedureRegistration
from snowflake.snowpark.stored_procedure_profiler import StoredProcedureProfiler
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,
GeometryType,
IntegerType,
MapType,
StringType,
StructField,
StructType,
TimestampTimeZone,
TimestampType,
TimeType,
VariantType,
VectorType,
_AtomicType,
)
from snowflake.snowpark.udaf import UDAFRegistration
from snowflake.snowpark.udf import UDFRegistration
from snowflake.snowpark.udtf import UDTFRegistration
if TYPE_CHECKING:
import modin.pandas # pragma: no cover
# 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
_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"
_PYTHON_SNOWPARK_USE_LOGICAL_TYPE_FOR_CREATE_DATAFRAME_STRING = (
"PYTHON_SNOWPARK_USE_LOGICAL_TYPE_FOR_CREATE_DATAFRAME"
)
# parameter used to turn off the whole new query compilation stage in one shot. If turned
# off, the plan won't go through the extra optimization and query generation steps.
_PYTHON_SNOWPARK_ENABLE_QUERY_COMPILATION_STAGE = (
"PYTHON_SNOWPARK_COMPILATION_STAGE_ENABLED"
)
_PYTHON_SNOWPARK_USE_CTE_OPTIMIZATION_VERSION = (
"PYTHON_SNOWPARK_USE_CTE_OPTIMIZATION_VERSION"
)
_PYTHON_SNOWPARK_ELIMINATE_NUMERIC_SQL_VALUE_CAST_ENABLED = (
"PYTHON_SNOWPARK_ELIMINATE_NUMERIC_SQL_VALUE_CAST_ENABLED"
)
_PYTHON_SNOWPARK_AUTO_CLEAN_UP_TEMP_TABLE_ENABLED_VERSION = (
"PYTHON_SNOWPARK_AUTO_CLEAN_UP_TEMP_TABLE_ENABLED_VERSION"
)
_PYTHON_SNOWPARK_REDUCE_DESCRIBE_QUERY_ENABLED = (
"PYTHON_SNOWPARK_REDUCE_DESCRIBE_QUERY_ENABLED"
)
_PYTHON_SNOWPARK_USE_LARGE_QUERY_BREAKDOWN_OPTIMIZATION_VERSION = (
"PYTHON_SNOWPARK_USE_LARGE_QUERY_BREAKDOWN_OPTIMIZATION_VERSION"
)
_PYTHON_SNOWPARK_LARGE_QUERY_BREAKDOWN_COMPLEXITY_UPPER_BOUND = (
"PYTHON_SNOWPARK_LARGE_QUERY_BREAKDOWN_COMPLEXITY_UPPER_BOUND"
)
_PYTHON_SNOWPARK_LARGE_QUERY_BREAKDOWN_COMPLEXITY_LOWER_BOUND = (
"PYTHON_SNOWPARK_LARGE_QUERY_BREAKDOWN_COMPLEXITY_LOWER_BOUND"
)
_PYTHON_SNOWPARK_ENABLE_THREAD_SAFE_SESSION = (
"PYTHON_SNOWPARK_ENABLE_THREAD_SAFE_SESSION"
)
# Flag for controlling the usage of scoped temp read only table.
_PYTHON_SNOWPARK_ENABLE_SCOPED_TEMP_READ_ONLY_TABLE = (
"PYTHON_SNOWPARK_ENABLE_SCOPED_TEMP_READ_ONLY_TABLE"
)
# AST encoding.
_PYTHON_SNOWPARK_USE_AST = "PYTHON_SNOWPARK_USE_AST"
# TODO SNOW-1677514: Add server-side flag and initialize value with it. Add telemetry support for flag.
_PYTHON_SNOWPARK_USE_AST_DEFAULT_VALUE = False
# The complexity score lower bound is set to match COMPILATION_MEMORY_LIMIT
# in Snowflake. This is the limit where we start seeing compilation errors.
DEFAULT_COMPLEXITY_SCORE_LOWER_BOUND = 10_000_000
DEFAULT_COMPLEXITY_SCORE_UPPER_BOUND = 12_000_000
WRITE_PANDAS_CHUNK_SIZE: int = 100000 if is_in_stored_procedure() else None
def _get_active_session() -> "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 _get_active_sessions() -> Set["Session"]:
with _session_management_lock:
if len(_active_sessions) >= 1:
# TODO: This function is allowing unsafe access to a mutex protected data
# structure, we should ONLY use it in tests
return _active_sessions
else:
raise SnowparkClientExceptionMessages.SERVER_NO_DEFAULT_SESSION()
def _add_session(session: "Session") -> None:
with _session_management_lock:
_active_sessions.add(session)
def _get_sandbox_conditional_active_session(session: "Session") -> "Session":
# Precedence to checking sandbox to avoid any side effects
if _is_execution_environment_sandboxed_for_client:
session = None
else:
session = session or _get_active_session()
return 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,
"flatten_select_after_filter_and_orderby": True,
} # For config that's temporary/to be removed soon
self._lock = self._session._lock
for key, val in conf.items():
if self.is_mutable(key):
self.set(key, val)
def get(self, key: str, default=None) -> Any:
with self._lock:
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:
with self._lock:
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:
with self._lock:
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 = {}
self._app_name = None
self._format_json = None
def _remove_config(self, key: str) -> "Session.SessionBuilder":
"""Only used in test."""
self._options.pop(key, None)
return self
def app_name(
self, app_name: str, format_json: bool = False
) -> "Session.SessionBuilder":
"""
Adds the app name to the :class:`SessionBuilder` to set in the query_tag after session creation
Args:
app_name: The name of the application.
format_json: If set to `True`, it will add the app name to the session query tag in JSON format,
otherwise, it will add it using a key=value format.
Returns:
A :class:`SessionBuilder` instance.
Example::
>>> session = Session.builder.app_name("my_app").configs(db_parameters).create() # doctest: +SKIP
>>> print(session.query_tag) # doctest: +SKIP
APPNAME=my_app
>>> session = Session.builder.app_name("my_app", format_json=True).configs(db_parameters).create() # doctest: +SKIP
>>> print(session.query_tag) # doctest: +SKIP
{"APPNAME": "my_app"}
"""
self._app_name = app_name
self._format_json = format_json
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."""
if self._options.get("local_testing", False):
session = Session(MockServerConnection(self._options), self._options)
if "password" in self._options:
self._options["password"] = None
_add_session(session)
elif self._options.get("nop_testing", False):
session = Session(NopConnection(self._options), self._options)
if "password" in self._options:
self._options["password"] = None
_add_session(session)
else:
session = self._create_internal(self._options.get("connection"))
if self._app_name:
if self._format_json:
app_name_tag = {"APPNAME": self._app_name}
session.update_query_tag(app_name_tag)
else:
app_name_tag = f"APPNAME={self._app_name}"
session.append_query_tag(app_name_tag)
return session
def getOrCreate(self) -> "Session":
"""Gets the last created session or creates a new one if needed."""
try:
session = _get_active_session()
if session._conn._conn.expired:
_remove_session(session)
return self.create()
return session
except SnowparkClientException as ex:
if ex.error_code == "1403": # No session, ok lets create one
return self.create()
raise
def _create_internal(
self,
conn: Optional[SnowflakeConnection] = None,
) -> "Session":
# If no connection object and no connection parameter is provided,
# we read from the default config file
if not is_in_stored_procedure() and not conn and not self._options:
from snowflake.connector.config_manager import (
_get_default_connection_params,
)
self._options = _get_default_connection_params()
# 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
appName = app_name
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: Union[ServerConnection, MockServerConnection, NopConnection],
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.version = get_version()
self._session_stage = None
if isinstance(conn, MockServerConnection):
self._udf_registration = MockUDFRegistration(self)
self._udtf_registration = MockUDTFRegistration(self)
self._udaf_registration = MockUDAFRegistration(self)
self._sp_registration = MockStoredProcedureRegistration(self)
else:
self._udf_registration = UDFRegistration(self)
self._sp_registration = StoredProcedureRegistration(self)
self._udtf_registration = UDTFRegistration(self)
self._udaf_registration = UDAFRegistration(self)
self._plan_builder = (
SnowflakePlanBuilder(self)
if isinstance(self._conn, ServerConnection)
else MockSnowflakePlanBuilder(self)
)
self._last_action_id = 0
self._last_canceled_id = 0
self._use_scoped_temp_objects: bool = (
_use_scoped_temp_objects
and self._conn._get_client_side_session_parameter(
_PYTHON_SNOWPARK_USE_SCOPED_TEMP_OBJECTS_STRING, True
)
)
self._use_scoped_temp_read_only_table: bool = (
self._conn._get_client_side_session_parameter(
_PYTHON_SNOWPARK_ENABLE_SCOPED_TEMP_READ_ONLY_TABLE, False
)
)
self._file = FileOperation(self)
self._lineage = Lineage(self)
self._sql_simplifier_enabled: bool = (
self._conn._get_client_side_session_parameter(
_PYTHON_SNOWPARK_USE_SQL_SIMPLIFIER_STRING, True
)
)
self._cte_optimization_enabled: bool = self.is_feature_enabled_for_version(
_PYTHON_SNOWPARK_USE_CTE_OPTIMIZATION_VERSION
)
self._use_logical_type_for_create_df: bool = (
self._conn._get_client_side_session_parameter(
_PYTHON_SNOWPARK_USE_LOGICAL_TYPE_FOR_CREATE_DATAFRAME_STRING, True
)
)
self._eliminate_numeric_sql_value_cast_enabled: bool = (
self._conn._get_client_side_session_parameter(
_PYTHON_SNOWPARK_ELIMINATE_NUMERIC_SQL_VALUE_CAST_ENABLED, False
)
)
self._auto_clean_up_temp_table_enabled: bool = (
self.is_feature_enabled_for_version(
_PYTHON_SNOWPARK_AUTO_CLEAN_UP_TEMP_TABLE_ENABLED_VERSION
)
)
self._reduce_describe_query_enabled: bool = (
self._conn._get_client_side_session_parameter(
_PYTHON_SNOWPARK_REDUCE_DESCRIBE_QUERY_ENABLED, False
)
)
self._query_compilation_stage_enabled: bool = (
self._conn._get_client_side_session_parameter(
_PYTHON_SNOWPARK_ENABLE_QUERY_COMPILATION_STAGE, False
)
)
self._large_query_breakdown_enabled: bool = self.is_feature_enabled_for_version(
_PYTHON_SNOWPARK_USE_LARGE_QUERY_BREAKDOWN_OPTIMIZATION_VERSION
)
self._ast_enabled: bool = self._conn._get_client_side_session_parameter(
_PYTHON_SNOWPARK_USE_AST, _PYTHON_SNOWPARK_USE_AST_DEFAULT_VALUE
)
# The complexity score lower bound is set to match COMPILATION_MEMORY_LIMIT
# in Snowflake. This is the limit where we start seeing compilation errors.
self._large_query_breakdown_complexity_bounds: Tuple[int, int] = (
self._conn._get_client_side_session_parameter(
_PYTHON_SNOWPARK_LARGE_QUERY_BREAKDOWN_COMPLEXITY_LOWER_BOUND,
DEFAULT_COMPLEXITY_SCORE_LOWER_BOUND,
),
self._conn._get_client_side_session_parameter(
_PYTHON_SNOWPARK_LARGE_QUERY_BREAKDOWN_COMPLEXITY_UPPER_BOUND,
DEFAULT_COMPLEXITY_SCORE_UPPER_BOUND,
),
)
self._thread_store = create_thread_local(
self._conn._thread_safe_session_enabled
)
self._lock = create_rlock(self._conn._thread_safe_session_enabled)
# this lock is used to protect _packages. We use introduce a new lock because add_packages
# launches a query to snowflake to get all version of packages available in snowflake. This
# query can be slow and prevent other threads from moving on waiting for _lock.
self._package_lock = create_rlock(self._conn._thread_safe_session_enabled)
# this lock is used to protect race-conditions when evaluating critical lazy properties
# of SnowflakePlan or Selectable objects
self._plan_lock = create_rlock(self._conn._thread_safe_session_enabled)
self._custom_package_usage_config: Dict = {}
self._conf = self.RuntimeConfig(self, options or {})
self._runtime_version_from_requirement: str = None
self._temp_table_auto_cleaner: TempTableAutoCleaner = TempTableAutoCleaner(self)
self._sp_profiler = StoredProcedureProfiler(session=self)
self._catalog = None
self._ast_batch = AstBatch(self)
_logger.info("Snowpark Session information: %s", self._session_info)
# Register self._close_at_exit so it will be called at interpreter shutdown
atexit.register(self._close_at_exit)
def _close_at_exit(self) -> None:
"""
This is the helper function to close the current session at interpreter shutdown.
For example, when a jupyter notebook is shutting down, this will also close
the current session and make sure send all telemetry to the server.
"""
with _session_management_lock:
try:
self.close()
except Exception:
pass
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if not is_in_stored_procedure():
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 is_feature_enabled_for_version(self, parameter_name: str) -> bool:
"""
This method checks if a feature is enabled for the current session based on
the server side parameter.
"""
version = self._conn._get_client_side_session_parameter(parameter_name, "")
return (
isinstance(version, str)
and version != ""
and pkg_resources.parse_version(self.version)
>= pkg_resources.parse_version(version)
)
def _generate_new_action_id(self) -> int:
with self._lock:
self._last_action_id += 1
return self._last_action_id
@property
def _analyzer(self) -> Analyzer:
if not hasattr(self._thread_store, "analyzer"):
analyzer: Union[Analyzer, MockAnalyzer, NopAnalyzer, None] = None
if isinstance(self._conn, NopConnection):
analyzer = NopAnalyzer(self)
elif isinstance(self._conn, MockServerConnection):
analyzer = MockAnalyzer(self)
else:
analyzer = Analyzer(self)
self._thread_store.analyzer = analyzer
return self._thread_store.analyzer
@classmethod
def get_active_session(cls) -> Optional["Session"]:
"""Gets the active session if one is created. If no session is created, returns None."""
try:
return _get_active_session()
except SnowparkClientException as ex:
# If there is no active session, return None
if ex.error_code == "1403":
return None
raise ex
getActiveSession = get_active_session
@property
@experimental(version="1.27.0")
def catalog(self) -> Catalog:
"""Returns the catalog object."""
if self._catalog is None:
if isinstance(self._conn, MockServerConnection):
self._conn.log_not_supported_error(
external_feature_name="Session.catalog",
raise_error=NotImplementedError,
)
self._catalog = Catalog(self)
return self._catalog
def close(self) -> None:
"""Close this session."""
if is_in_stored_procedure():
_logger.warning("Closing a session in a stored procedure is a no-op.")
return
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._temp_table_auto_cleaner.stop()
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:
"""Set to ``True`` to use the SQL simplifier (defaults to ``True``).
The generated SQLs from ``DataFrame`` transformations would have fewer layers of nested queries if the SQL simplifier is enabled.
"""
return self._sql_simplifier_enabled
@property
def ast_enabled(self) -> bool:
return self._ast_enabled
@ast_enabled.setter
def ast_enabled(self, value: bool) -> None:
# TODO: we could send here explicit telemetry if a user changes the behavior.
# In addition, we could introduce a server-side parameter to enable AST capture or not.
# self._conn._telemetry_client.send_ast_enabled_telemetry(
# self._session_id, value
# )
# try:
# self._conn._cursor.execute(
# f"alter session set {_PYTHON_SNOWPARK_USE_AST} = {value}"
# )
# except Exception:
# pass
self._ast_enabled = value
# Auto temp cleaner has bad interactions with AST at the moment, disable when enabling AST.
# This feature should get moved server-side anyways.
if self._ast_enabled:
_logger.warning(
"TODO SNOW-1770278: Ensure auto temp table cleaner works with AST."
" Disabling auto temp cleaner for full test suite due to buggy behavior."
)
self.auto_clean_up_temp_table_enabled = False
@property
def cte_optimization_enabled(self) -> bool:
"""Set to ``True`` to enable the CTE optimization (defaults to ``False``).
The generated SQLs from ``DataFrame`` transformations would have duplicate subquery as CTEs if the CTE optimization is enabled.
"""
return self._cte_optimization_enabled
@property
def eliminate_numeric_sql_value_cast_enabled(self) -> bool:
return self._eliminate_numeric_sql_value_cast_enabled
@property
def auto_clean_up_temp_table_enabled(self) -> bool:
"""
When setting this parameter to ``True``, Snowpark will automatically clean up temporary tables created by
:meth:`DataFrame.cache_result` in the current session when the DataFrame is no longer referenced (i.e., gets garbage collected).
The default value is ``False``.
Note:
Temporary tables will only be dropped if this parameter is enabled during garbage collection.
If a temporary table is no longer referenced when the parameter is on, it will be dropped during garbage collection.
However, if garbage collection occurs while the parameter is off, the table will not be removed.
Note that Python's garbage collection is triggered opportunistically, with no guaranteed timing.
"""
return self._auto_clean_up_temp_table_enabled
@property
def large_query_breakdown_enabled(self) -> bool:
return self._large_query_breakdown_enabled
@property
def large_query_breakdown_complexity_bounds(self) -> Tuple[int, int]:
return self._large_query_breakdown_complexity_bounds
@property
def reduce_describe_query_enabled(self) -> bool:
"""
When setting this parameter to ``True``, Snowpark will infer the schema of DataFrame locally if possible,
instead of issuing an internal `describe query
<https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-example#retrieving-column-metadata>`_
to get the schema from the Snowflake server. This optimization improves the performance of your workloads by
reducing the number of describe queries issued to the server.
The default value is ``False``.
"""
return self._reduce_describe_query_enabled
@property
def custom_package_usage_config(self) -> Dict:
"""Get or set configuration parameters related to usage of custom Python packages in Snowflake.
If enabled, pure Python packages that are not available in Snowflake will be installed locally via pip and made available
as an import (see :func:`add_import` for more information on imports). You can speed up this process by mentioning
a remote stage path as ``cache_path`` where unsupported pure Python packages will be persisted. To use a specific
version of pip, you can set the environment variable ``PIP_PATH`` to point to your pip executable. To use custom
Python packages which are not purely Python, specify the ``force_push`` configuration parameter (*note that using
non-pure Python packages is not recommended!*).
This feature is **experimental**, please do not use it in production!
Configurations:
- **enabled** (*bool*): Turn on usage of custom pure Python packages.
- **force_push** (*bool*): Use Python packages regardless of whether the packages are pure Python or not.
- **cache_path** (*str*): Cache custom Python packages on a stage directory. This parameter greatly reduces latency of custom package import.
- **force_cache** (*bool*): Use this parameter if you specified a ``cache_path`` but wish to create a fresh cache of your environment.
Args:
config (dict): Dictionary containing configuration parameters mentioned above (defaults to empty dictionary).
Example::
>>> from snowflake.snowpark.functions import udf
>>> session.custom_package_usage_config = {"enabled": True, "cache_path": "@my_permanent_stage/folder"} # doctest: +SKIP
>>> session.add_packages("package_unavailable_in_snowflake") # doctest: +SKIP
>>> @udf
... def use_my_custom_package() -> str:
... import package_unavailable_in_snowflake
... return "works"
>>> session.clear_packages()
>>> session.clear_imports()
Note:
- These configurations allow custom package addition via :func:`Session.add_requirements` and :func:`Session.add_packages`.
- These configurations also allow custom package addition for all UDFs or stored procedures created later in the current session. If you only want to add custom packages for a specific UDF, you can use ``packages`` argument in :func:`functions.udf` or :meth:`session.udf.register() <snowflake.snowpark.udf.UDFRegistration.register>`.
"""
return self._custom_package_usage_config
@sql_simplifier_enabled.setter
def sql_simplifier_enabled(self, value: bool) -> None:
warn_session_config_update_in_multithreaded_mode(
"sql_simplifier_enabled", self._conn._thread_safe_session_enabled
)
with self._lock:
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
@cte_optimization_enabled.setter
@experimental_parameter(version="1.15.0")
def cte_optimization_enabled(self, value: bool) -> None:
warn_session_config_update_in_multithreaded_mode(
"cte_optimization_enabled", self._conn._thread_safe_session_enabled
)
with self._lock:
if value:
self._conn._telemetry_client.send_cte_optimization_telemetry(
self._session_id
)
self._cte_optimization_enabled = value
@eliminate_numeric_sql_value_cast_enabled.setter
@experimental_parameter(version="1.20.0")
def eliminate_numeric_sql_value_cast_enabled(self, value: bool) -> None:
"""Set the value for eliminate_numeric_sql_value_cast_enabled"""
warn_session_config_update_in_multithreaded_mode(
"eliminate_numeric_sql_value_cast_enabled",
self._conn._thread_safe_session_enabled,
)
if value in [True, False]:
with self._lock:
self._conn._telemetry_client.send_eliminate_numeric_sql_value_cast_telemetry(
self._session_id, value
)
self._eliminate_numeric_sql_value_cast_enabled = value
else:
raise ValueError(
"value for eliminate_numeric_sql_value_cast_enabled must be True or False!"
)
@auto_clean_up_temp_table_enabled.setter
@experimental_parameter(version="1.21.0")
def auto_clean_up_temp_table_enabled(self, value: bool) -> None:
"""Set the value for auto_clean_up_temp_table_enabled"""
warn_session_config_update_in_multithreaded_mode(
"auto_clean_up_temp_table_enabled", self._conn._thread_safe_session_enabled
)
if value in [True, False]:
with self._lock:
self._conn._telemetry_client.send_auto_clean_up_temp_table_telemetry(
self._session_id, value
)
self._auto_clean_up_temp_table_enabled = value
else:
raise ValueError(
"value for auto_clean_up_temp_table_enabled must be True or False!"
)
@large_query_breakdown_enabled.setter
@experimental_parameter(version="1.22.0")
def large_query_breakdown_enabled(self, value: bool) -> None:
"""Set the value for large_query_breakdown_enabled. When enabled, the client will
automatically detect large query plans and break them down into smaller partitions,
materialize the partitions, and then combine them to execute the query to improve
overall performance.
"""
warn_session_config_update_in_multithreaded_mode(
"large_query_breakdown_enabled", self._conn._thread_safe_session_enabled
)
if value in [True, False]:
with self._lock:
self._conn._telemetry_client.send_large_query_breakdown_telemetry(
self._session_id, value
)
self._large_query_breakdown_enabled = value
else:
raise ValueError(
"value for large_query_breakdown_enabled must be True or False!"
)
@large_query_breakdown_complexity_bounds.setter
def large_query_breakdown_complexity_bounds(self, value: Tuple[int, int]) -> None:
"""Set the lower and upper bounds for the complexity score used in large query breakdown optimization."""
warn_session_config_update_in_multithreaded_mode(