-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathutils.py
More file actions
1459 lines (1198 loc) · 50.5 KB
/
utils.py
File metadata and controls
1459 lines (1198 loc) · 50.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# Copyright (c) 2012-2024 Snowflake Computing Inc. All rights reserved.
#
import array
import contextlib
import datetime
import decimal
import functools
import hashlib
import importlib
import io
import itertools
import logging
import os
import platform
import random
import re
import string
import sys
import threading
import traceback
import zipfile
from enum import Enum
from functools import lru_cache
from itertools import count
from json import JSONEncoder
from random import choice
from typing import (
IO,
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Literal,
Optional,
Set,
Tuple,
Type,
Union,
)
import snowflake.snowpark
from snowflake.connector.constants import FIELD_ID_TO_NAME
from snowflake.connector.cursor import ResultMetadata, SnowflakeCursor
from snowflake.connector.description import OPERATING_SYSTEM, PLATFORM
from snowflake.connector.options import MissingOptionalDependency, ModuleLikeObject
from snowflake.connector.version import VERSION as connector_version
from snowflake.snowpark._internal.error_message import SnowparkClientExceptionMessages
from snowflake.snowpark.context import _should_use_structured_type_semantics
from snowflake.snowpark.row import Row
from snowflake.snowpark.version import VERSION as snowpark_version
if TYPE_CHECKING:
try:
from snowflake.connector.cursor import ResultMetadataV2
except ImportError:
ResultMetadataV2 = ResultMetadata
_logger = logging.getLogger("snowflake.snowpark")
STAGE_PREFIX = "@"
SNOWURL_PREFIX = "snow://"
SNOWFLAKE_PATH_PREFIXES = [
STAGE_PREFIX,
SNOWURL_PREFIX,
]
# Scala uses 3 but this can be larger. Consider allowing users to configure it.
QUERY_TAG_TRACEBACK_LIMIT = 3
# https://docs.snowflake.com/en/sql-reference/identifiers-syntax.html
SNOWFLAKE_UNQUOTED_ID_PATTERN = r"([a-zA-Z_][\w\$]{0,255})"
SNOWFLAKE_QUOTED_ID_PATTERN = '("([^"]|""){1,255}")'
SNOWFLAKE_ID_PATTERN = (
f"({SNOWFLAKE_UNQUOTED_ID_PATTERN}|{SNOWFLAKE_QUOTED_ID_PATTERN})"
)
SNOWFLAKE_CASE_INSENSITIVE_QUOTED_ID_PATTERN = r'("([A-Z_][A-Z0-9_\$]{0,255})")'
SNOWFLAKE_CASE_INSENSITIVE_UNQUOTED_SUFFIX_PATTERN = r"([a-zA-Z0-9_\$]{0,255})"
# Valid name can be:
# identifier
# identifier.identifier
# identifier.identifier.identifier
# identifier..identifier
SNOWFLAKE_OBJECT_RE_PATTERN = re.compile(
f"^(({SNOWFLAKE_ID_PATTERN}\\.){{0,2}}|({SNOWFLAKE_ID_PATTERN}\\.\\.)){SNOWFLAKE_ID_PATTERN}$"
)
SNOWFLAKE_CASE_INSENSITIVE_QUOTED_ID_RE_PATTERN = re.compile(
SNOWFLAKE_CASE_INSENSITIVE_QUOTED_ID_PATTERN
)
SNOWFLAKE_CASE_INSENSITIVE_UNQUOTED_SUFFIX_RE_PATTERN = re.compile(
SNOWFLAKE_CASE_INSENSITIVE_UNQUOTED_SUFFIX_PATTERN
)
# "%?" is for table stage
SNOWFLAKE_STAGE_NAME_PATTERN = f"(%?{SNOWFLAKE_ID_PATTERN})"
# Prefix for allowed temp object names in stored proc
TEMP_OBJECT_NAME_PREFIX = "SNOWPARK_TEMP_"
ALPHANUMERIC = string.digits + string.ascii_lowercase
# select and CTE (https://docs.snowflake.com/en/sql-reference/constructs/with.html) are select statements in Snowflake.
SNOWFLAKE_SELECT_SQL_PREFIX_PATTERN = re.compile(
r"^(\s|\()*(select|with)", re.IGNORECASE
)
# Anonymous stored procedures: https://docs.snowflake.com/en/sql-reference/sql/call-with
SNOWFLAKE_ANONYMOUS_CALL_WITH_PATTERN = re.compile(
r"^\s*with\s+\w+\s+as\s+procedure", re.IGNORECASE
)
# A set of widely-used packages,
# whose names in pypi are different from their package name
PACKAGE_NAME_TO_MODULE_NAME_MAP = {
"absl-py": "absl",
"async-timeout": "async_timeout",
"attrs": "attr",
"brotlipy": "brotli",
"charset-normalizer": "charset_normalizer",
"google-auth": "google.auth",
"google-auth-oauthlib": "google_auth_oauthlib",
"google-pasta": "pasta",
"grpcio": "grpc",
"importlib-metadata": "importlib_metadata",
"ncurses": "curses",
"py-xgboost": "xgboost",
"pyasn1-modules": "pyasn1_modules",
"pyjwt": "jwt",
"pyopenssl": "OpenSSL",
"pysocks": "socks",
"python-dateutil": "dateutil",
"python-flatbuffers": "flatbuffers",
"pytorch": "torch",
"pyyaml": "yaml",
"requests-oauthlib": "requests_oauthlib",
"scikit-learn": "sklearn",
"sqlite": "sqlite3",
"tensorboard-plugin-wit": "tensorboard_plugin_wit",
"tensorflow-estimator": "tensorflow_estimator",
"typing-extensions": "typing_extensions",
}
MODULE_NAME_TO_PACKAGE_NAME_MAP = {
v: k for k, v in PACKAGE_NAME_TO_MODULE_NAME_MAP.items()
}
GENERATED_PY_FILE_EXT = (".pyc", ".pyo", ".pyd", ".pyi")
INFER_SCHEMA_FORMAT_TYPES = ("PARQUET", "ORC", "AVRO", "JSON", "CSV")
COPY_INTO_TABLE_COPY_OPTIONS = {
"ON_ERROR",
"SIZE_LIMIT",
"PURGE",
"RETURN_FAILED_ONLY",
"MATCH_BY_COLUMN_NAME",
"ENFORCE_LENGTH",
"TRUNCATECOLUMNS",
"FORCE",
"LOAD_UNCERTAIN_FILES",
}
COPY_INTO_LOCATION_COPY_OPTIONS = {
"OVERWRITE",
"SINGLE",
"MAX_FILE_SIZE",
"INCLUDE_QUERY_ID",
"DETAILED_OUTPUT",
}
NON_FORMAT_TYPE_OPTIONS = {
"PATTERN",
"VALIDATION_MODE",
"FILE_FORMAT",
"FORMAT_NAME",
"FILES",
# The following are not copy into SQL command options but client side options.
"INFER_SCHEMA",
"INFER_SCHEMA_OPTIONS",
"FORMAT_TYPE_OPTIONS",
"TARGET_COLUMNS",
"TRANSFORMATIONS",
"COPY_OPTIONS",
}
QUERY_TAG_STRING = "QUERY_TAG"
SKIP_LEVELS_TWO = (
2 # limit traceback to return up to 2 stack trace entries from traceback object tb
)
SKIP_LEVELS_THREE = (
3 # limit traceback to return up to 3 stack trace entries from traceback object tb
)
TEMPORARY_STRING = "TEMPORARY"
SCOPED_TEMPORARY_STRING = "SCOPED TEMPORARY"
SUPPORTED_TABLE_TYPES = ["temp", "temporary", "transient"]
# TODO: merge fixed pandas importer changes to connector.
def _pandas_importer(): # noqa: E302
"""Helper function to lazily import pandas and return MissingPandas if not installed."""
from snowflake.connector.options import MissingPandas
pandas = MissingPandas()
try:
pandas = importlib.import_module("pandas")
# since we enable relative imports without dots this import gives us an issues when ran from test directory
from pandas import DataFrame # NOQA
except ImportError as e:
_logger.error(f"pandas is not installed {e}")
return pandas
pandas = _pandas_importer()
installed_pandas = not isinstance(pandas, MissingOptionalDependency)
class TempObjectType(Enum):
TABLE = "TABLE"
VIEW = "VIEW"
STAGE = "STAGE"
FUNCTION = "FUNCTION"
FILE_FORMAT = "FILE_FORMAT"
QUERY_TAG = "QUERY_TAG"
COLUMN = "COLUMN"
PROCEDURE = "PROCEDURE"
TABLE_FUNCTION = "TABLE_FUNCTION"
DYNAMIC_TABLE = "DYNAMIC_TABLE"
AGGREGATE_FUNCTION = "AGGREGATE_FUNCTION"
CTE = "CTE"
# More info about all allowed aliases here:
# https://docs.snowflake.com/en/sql-reference/functions-date-time#label-supported-date-time-parts
DATETIME_PART_TO_ALIASES = {
"year": {"year", "y", "yy", "yyy", "yyyy", "yr", "years", "yrs"},
"quarter": {"quarter", "q", "qtr", "qtrs", "quarters"},
"month": {"month", "mm", "mon", "mons", "months"},
"week": {"week", "w", "wk", "weekofyear", "woy", "wy"},
"day": {"day", "d", "dd", "days", "dayofmonth"},
"hour": {"hour", "h", "hh", "hr", "hours", "hrs"},
"minute": {"minute", "m", "mi", "min", "minutes", "mins"},
"second": {"second", "s", "sec", "seconds", "secs"},
"millisecond": {"millisecond", "ms", "msec", "milliseconds"},
"microsecond": {"microsecond", "us", "usec", "microseconds"},
"nanosecond": {
"nanosecond",
"ns",
"nsec",
"nanosec",
"nsecond",
"nanoseconds",
"nanosecs",
"nseconds",
},
"dayofweek": {"dayofweek", "weekday", "dow", "dw"},
"dayofweekiso": {"dayofweekiso", "weekday_iso", "dow_iso", "dw_iso"},
"dayofyear": {"dayofyear", "yearday", "doy", "dy"},
"weekiso": {"weekiso", "week_iso", "weekofyeariso", "weekofyear_iso"},
"yearofweek": {"yearofweek"},
"yearofweekiso": {"yearofweekiso"},
"epoch_second": {"epoch_second", "epoch", "epoch_seconds"},
"epoch_millisecond": {"epoch_millisecond", "epoch_milliseconds"},
"epoch_microsecond": {"epoch_microsecond", "epoch_microseconds"},
"epoch_nanosecond": {"epoch_nanosecond", "epoch_nanoseconds"},
"timezone_hour": {"timezone_hour", "tzh"},
"timezone_minute": {"timezone_minute", "tzm"},
}
DATETIME_PARTS = set(DATETIME_PART_TO_ALIASES.keys())
ALIASES_TO_DATETIME_PART = {
v: k for k, l in DATETIME_PART_TO_ALIASES.items() for v in l
}
DATETIME_ALIASES = set(ALIASES_TO_DATETIME_PART.keys())
def unalias_datetime_part(part):
lowered_part = part.lower()
if lowered_part in DATETIME_ALIASES:
return ALIASES_TO_DATETIME_PART[lowered_part]
else:
raise ValueError(f"{part} is not a recognized date or time part.")
def parse_duration_string(duration: str) -> Tuple[int, str]:
length, unit = duration.split(" ")
length = int(length)
unit = unalias_datetime_part(unit)
return length, unit
def validate_object_name(name: str):
if not SNOWFLAKE_OBJECT_RE_PATTERN.match(name):
raise SnowparkClientExceptionMessages.GENERAL_INVALID_OBJECT_NAME(name)
@lru_cache
def get_version() -> str:
return ".".join([str(d) for d in snowpark_version if d is not None])
@lru_cache
def get_python_version() -> str:
return platform.python_version()
@lru_cache
def get_connector_version() -> str:
return ".".join([str(d) for d in connector_version if d is not None])
@lru_cache
def get_os_name() -> str:
return platform.system()
@lru_cache
def get_application_name() -> str:
return "PythonSnowpark"
def is_single_quoted(name: str) -> bool:
return name.startswith("'") and name.endswith("'")
def is_snowflake_quoted_id_case_insensitive(name: str) -> bool:
return SNOWFLAKE_CASE_INSENSITIVE_QUOTED_ID_RE_PATTERN.fullmatch(name) is not None
def is_snowflake_unquoted_suffix_case_insensitive(name: str) -> bool:
return (
SNOWFLAKE_CASE_INSENSITIVE_UNQUOTED_SUFFIX_RE_PATTERN.fullmatch(name)
is not None
)
def unwrap_single_quote(name: str) -> str:
new_name = name.strip()
if is_single_quoted(new_name):
new_name = new_name[1:-1]
new_name = new_name.replace("\\'", "'")
return new_name
def escape_single_quotes(input_str):
return input_str.replace("'", r"\'")
def is_sql_select_statement(sql: str) -> bool:
return (
SNOWFLAKE_SELECT_SQL_PREFIX_PATTERN.match(sql) is not None
and SNOWFLAKE_ANONYMOUS_CALL_WITH_PATTERN.match(sql) is None
)
def normalize_path(path: str, is_local: bool) -> str:
"""
Get a normalized path of a local file or remote stage location for PUT/GET commands.
If there are any special characters including spaces in the path, it needs to be
quoted with single quote. For example, 'file:///tmp/load data' for a path containing
a directory named "load data". Therefore, if `path` is already wrapped by single quotes,
we do nothing.
"""
prefixes = ["file://"] if is_local else SNOWFLAKE_PATH_PREFIXES
if is_single_quoted(path):
return path
if is_local and OPERATING_SYSTEM == "Windows":
path = path.replace("\\", "/")
path = path.strip().replace("'", "\\'")
if not any(path.startswith(prefix) for prefix in prefixes):
path = f"{prefixes[0]}{path}"
return f"'{path}'"
def warn_session_config_update_in_multithreaded_mode(
config: str, thread_safe_mode_enabled: bool
) -> None:
if not thread_safe_mode_enabled:
return
if threading.active_count() > 1:
_logger.warning(
"You might have more than one threads sharing the Session object trying to update "
f"{config}. Updating this while other tasks are running can potentially cause "
"unexpected behavior. Please update the session configuration before starting the threads."
)
def normalize_remote_file_or_dir(name: str) -> str:
return normalize_path(name, is_local=False)
def normalize_local_file(file: str) -> str:
return normalize_path(file, is_local=True)
def split_path(path: str) -> Tuple[str, str]:
"""Split a file path into directory and file name."""
path = unwrap_single_quote(path)
return path.rsplit("/", maxsplit=1)
def unwrap_stage_location_single_quote(name: str) -> str:
new_name = unwrap_single_quote(name)
if any(new_name.startswith(prefix) for prefix in SNOWFLAKE_PATH_PREFIXES):
return new_name
return f"{STAGE_PREFIX}{new_name}"
def get_local_file_path(file: str) -> str:
trim_file = file.strip()
if is_single_quoted(trim_file):
trim_file = trim_file[1:-1] # remove the pair of single quotes
if trim_file.startswith("file://"):
return trim_file[7:] # remove "file://"
return trim_file
def get_udf_upload_prefix(udf_name: str) -> str:
"""Get the valid stage prefix when uploading a UDF."""
if re.match("[\\w]+$", udf_name):
return udf_name
else:
return "{}_{}".format(re.sub("\\W", "", udf_name), abs(hash(udf_name)))
def random_number() -> int:
"""Get a random unsigned integer."""
return random.randint(0, 2**31)
@contextlib.contextmanager
def zip_file_or_directory_to_stream(
path: str,
leading_path: Optional[str] = None,
add_init_py: bool = False,
ignore_generated_py_file: bool = True,
) -> IO[bytes]:
"""Compresses the file or directory as a zip file to a binary stream.
Args:
path: The absolute path to a file or directory.
leading_path: This argument is used to determine where directory should
start in the zip file. Basically, this argument works as the role
of `start` argument in os.path.relpath(path, start), i.e.,
absolute path = [leading path]/[relative path]. For example,
when the path is "/tmp/dir1/dir2/test.py", and the leading path
is "/tmp/dir1", the generated filesystem structure in the zip file
will be "dir2/test.py". The leading path will compose a namespace package
that is used for zipimport on the server side.
ignore_generated_py_file: Whether to ignore some generated python files
in the directory.
Returns:
A byte stream.
"""
if not os.path.exists(path):
raise FileNotFoundError(f"{path} is not found")
if leading_path and not path.startswith(leading_path):
raise ValueError(f"{leading_path} doesn't lead to {path}")
# if leading_path is not provided, just use the parent path,
# and the compression will start from the parent directory
start_path = leading_path if leading_path else os.path.join(path, "..")
input_stream = io.BytesIO()
with zipfile.ZipFile(
input_stream, mode="w", compression=zipfile.ZIP_DEFLATED
) as zf:
# Write the folders on the leading path to the zip file to build a namespace package
cur_path = os.path.dirname(path)
while os.path.realpath(cur_path) != os.path.realpath(start_path):
# according to .zip file format specification, only / is valid
zf.writestr(f"{os.path.relpath(cur_path, start_path)}/", "")
cur_path = os.path.dirname(cur_path)
if os.path.isdir(path):
for dirname, _, files in os.walk(path):
# ignore __pycache__
if ignore_generated_py_file and "__pycache__" in dirname:
continue
zf.write(dirname, os.path.relpath(dirname, start_path))
for file in files:
# ignore generated python files
if ignore_generated_py_file and file.endswith(
GENERATED_PY_FILE_EXT
):
continue
filename = os.path.join(dirname, file)
zf.write(filename, os.path.relpath(filename, start_path))
else:
zf.write(path, os.path.relpath(path, start_path))
yield input_stream
input_stream.close()
def parse_positional_args_to_list(*inputs: Any) -> List:
"""Convert the positional arguments to a list."""
if len(inputs) == 1:
return (
[*inputs[0]] if isinstance(inputs[0], (list, tuple, set)) else [inputs[0]]
)
else:
return [*inputs]
def parse_positional_args_to_list_variadic(*inputs: Any) -> Tuple[List, bool]:
"""Convert the positional arguments to a list, indicating whether to treat the argument list as a variadic list."""
if len(inputs) == 1 and isinstance(inputs[0], (list, tuple, set)):
return ([*inputs[0]], False)
else:
return ([*inputs], True)
def _hash_file(
hash_algo: "hashlib._hashlib.HASH",
path: str,
chunk_size: int,
whole_file_hash: bool,
):
"""
Reads from a file and updates the given hash algorithm with the read text.
Args:
hash_algo: The hash algorithm to updated.
path: The path to the file to be read.
chunk_size: How much of the file to read at a time.
whole_file_hash: When True the whole file is hashed rather than stopping after the first chunk.
"""
with open(path, "rb") as f:
data = f.read(chunk_size)
hash_algo.update(data)
while data and whole_file_hash:
data = f.read(chunk_size)
hash_algo.update(data)
def calculate_checksum(
path: str,
chunk_size: int = 8192,
ignore_generated_py_file: bool = True,
additional_info: Optional[str] = None,
algorithm: str = "sha256",
whole_file_hash: bool = False,
) -> str:
"""Calculates the checksum of a file or a directory.
Args:
path: the path to a local file or directory.
If it points to a file, we read a small chunk from the file and
calculate the checksum based on it.
If it points to a directory, the names of all files and subdirectories
in this directory will also be included for checksum computation.
chunk_size: The size in byte we will read from the file/directory for
checksum computation.
ignore_generated_py_file: Whether to ignore some generated python files
in the directory.
additional_info: Any additional information we might want to include
for checksum computation.
algorithm: the hash algorithm.
whole_file_hash: When set to True the files will be completely read while hashing.
Returns:
The result checksum.
"""
if not os.path.exists(path):
raise FileNotFoundError(f"{path} is not found")
hash_algo = hashlib.new(algorithm)
if os.path.isfile(path):
_hash_file(hash_algo, path, chunk_size, whole_file_hash)
elif os.path.isdir(path):
current_size = 0
for dirname, dirs, files in os.walk(path):
# ignore __pycache__
if ignore_generated_py_file and "__pycache__" in dirname:
continue
# sort dirs and files so the result is consistent across different os
for dir in sorted(dirs):
if ignore_generated_py_file and dir == "__pycache__":
continue
hash_algo.update(dir.encode("utf8"))
for file in sorted(files):
# ignore generated python files
if ignore_generated_py_file and file.endswith(GENERATED_PY_FILE_EXT):
continue
hash_algo.update(file.encode("utf8"))
filename = os.path.join(dirname, file)
file_size = os.path.getsize(filename)
if whole_file_hash:
_hash_file(hash_algo, filename, chunk_size, whole_file_hash)
current_size += file_size
elif current_size < chunk_size:
read_size = min(file_size, chunk_size - current_size)
current_size += read_size
_hash_file(hash_algo, filename, read_size, False)
else:
raise ValueError(f"{algorithm} can only be calculated for a file or directory")
if additional_info:
hash_algo.update(additional_info.encode("utf8"))
return hash_algo.hexdigest()
def str_to_enum(value: str, enum_class: Type[Enum], except_str: str) -> Enum:
try:
return enum_class(value)
except ValueError:
raise ValueError(
f"{except_str} must be one of {', '.join([e.value for e in enum_class])}"
)
def create_statement_query_tag(skip_levels: int = 0) -> str:
stack = traceback.format_stack(limit=QUERY_TAG_TRACEBACK_LIMIT + skip_levels)
return "".join(stack[:-skip_levels] if skip_levels else stack)
def create_or_update_statement_params_with_query_tag(
statement_params: Optional[Dict[str, str]] = None,
exists_session_query_tag: Optional[str] = None,
skip_levels: int = 0,
) -> Dict[str, str]:
if exists_session_query_tag or (
statement_params and QUERY_TAG_STRING in statement_params
):
return statement_params
ret = statement_params or {}
# as create_statement_query_tag is called by the method, skip_levels needs to +1 to skip the current call
ret[QUERY_TAG_STRING] = create_statement_query_tag(skip_levels + 1)
return ret
def get_stage_file_prefix_length(stage_location: str) -> int:
normalized = unwrap_stage_location_single_quote(stage_location)
if not normalized.endswith("/"):
normalized = f"{normalized}/"
# Remove the first three characters from @~/...
if normalized.startswith(f"{STAGE_PREFIX}~"):
return len(normalized) - 3
is_quoted = False
for i, c in enumerate(normalized):
if c == '"':
is_quoted = not is_quoted
elif c == "/" and not is_quoted:
# Find the first unquoted '/', then the stage name is before it,
# the path is after it
full_stage_name = normalized[:i]
path = normalized[i + 1 :]
# Find the last match of the first group, which should be the stage name.
# If not found, the stage name should be invalid
res = re.findall(SNOWFLAKE_STAGE_NAME_PATTERN, full_stage_name)
if not res:
break
stage_name = res[-1][0]
# For a table stage, stage name is not in the prefix,
# so the prefix is path. Otherwise, the prefix is stageName + "/" + path
return (
len(path)
if stage_name.startswith("%")
else len(path) + len(stage_name.strip('"')) + 1
)
raise ValueError(f"Invalid stage {stage_location}")
def is_in_stored_procedure():
return PLATFORM == "XP"
def random_name_for_temp_object(object_type: TempObjectType) -> str:
return f"{TEMP_OBJECT_NAME_PREFIX}{object_type.value}_{generate_random_alphanumeric().upper()}"
def generate_random_alphanumeric(length: int = 10) -> str:
return "".join(choice(ALPHANUMERIC) for _ in range(length))
def column_to_bool(col_):
"""A replacement to bool(col_) to check if ``col_`` is None or Empty.
``Column.__bool__` raises an exception to remind users to use &, |, ~ instead of and, or, not for logical operations.
The side-effect is the implicit call like ``if col_`` also raises an exception.
Our internal code sometimes needs to check an input column is None, "", or []. So this method will help it by writeint ``if column_to_bool(col_): ...``
"""
if isinstance(col_, snowflake.snowpark.Column):
return True
return bool(col_)
def _parse_result_meta(
result_meta: Union[List[ResultMetadata], List["ResultMetadataV2"]]
) -> Tuple[Optional[List[str]], Optional[List[Callable]]]:
"""
Takes a list of result metadata objects and returns a list containing the names of all fields as
well as a list of functions that wrap specific columns.
A column type may need to be wrapped if the connector is unable to provide the columns data in
an expected format. For example StructType columns are returned as dict objects, but are better
represented as Row objects.
"""
if not result_meta:
return None, None
col_names = []
wrappers = []
for col in result_meta:
col_names.append(col.name)
if (
_should_use_structured_type_semantics()
and FIELD_ID_TO_NAME[col.type_code] == "OBJECT"
and col.fields is not None
):
wrappers.append(lambda x: Row(**x))
else:
wrappers.append(None)
return col_names, wrappers
def result_set_to_rows(
result_set: List[Any],
result_meta: Optional[Union[List[ResultMetadata], List["ResultMetadataV2"]]] = None,
case_sensitive: bool = True,
) -> List[Row]:
col_names, wrappers = _parse_result_meta(result_meta or [])
rows = []
row_struct = Row
if col_names:
row_struct = (
Row._builder.build(*col_names).set_case_sensitive(case_sensitive).to_row()
)
for data in result_set:
if wrappers:
data = [wrap(d) if wrap else d for wrap, d in zip(wrappers, data)]
if data is None:
raise ValueError("Result returned from Python connector is None")
row = row_struct(*data)
rows.append(row)
return rows
def result_set_to_iter(
result_set: SnowflakeCursor,
result_meta: Optional[List[ResultMetadata]] = None,
case_sensitive: bool = True,
) -> Iterator[Row]:
col_names, wrappers = _parse_result_meta(result_meta)
row_struct = Row
if col_names:
row_struct = (
Row._builder.build(*col_names).set_case_sensitive(case_sensitive).to_row()
)
for data in result_set:
if data is None:
raise ValueError("Result returned from Python connector is None")
if wrappers:
data = [wrap(d) if wrap else d for wrap, d in zip(wrappers, data)]
row = row_struct(*data)
yield row
class PythonObjJSONEncoder(JSONEncoder):
"""Converts common Python objects to json serializable objects."""
def default(self, value):
if isinstance(value, (bytes, bytearray)):
return value.hex()
elif isinstance(value, decimal.Decimal):
return float(value)
elif isinstance(value, (datetime.date, datetime.time, datetime.datetime)):
return value.isoformat()
elif isinstance(value, array.array):
return value.tolist()
else:
return super().default(value)
class WarningHelper:
def __init__(self, warning_times: int) -> None:
self.warning_times = warning_times
self.count = 0
def warning(self, text: str) -> None:
if self.count < self.warning_times:
_logger.warning(text)
self.count += 1
# TODO: SNOW-1720855: Remove DummyRLock and DummyThreadLocal after the rollout
class DummyRLock:
"""This is a dummy lock that is used in place of threading.Rlock when multithreading is
disabled."""
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def acquire(self, *args, **kwargs):
pass # pragma: no cover
def release(self, *args, **kwargs):
pass # pragma: no cover
class DummyThreadLocal:
"""This is a dummy thread local class that is used in place of threading.local when
multithreading is disabled."""
pass
def create_thread_local(
thread_safe_session_enabled: bool,
) -> Union[threading.local, DummyThreadLocal]:
if thread_safe_session_enabled:
return threading.local()
return DummyThreadLocal()
def create_rlock(
thread_safe_session_enabled: bool,
) -> Union[threading.RLock, DummyRLock]:
if thread_safe_session_enabled:
return threading.RLock()
return DummyRLock()
warning_dict: Dict[str, WarningHelper] = {}
def warning(name: str, text: str, warning_times: int = 1) -> None:
if name not in warning_dict:
warning_dict[name] = WarningHelper(warning_times)
warning_dict[name].warning(text)
# TODO(SNOW-1491199) - This method is not covered by tests until the end of phase 0. Drop the pragma when it is covered.
def infer_ast_enabled_from_global_sessions(func: Callable) -> bool: # pragma: no cover
session = None
try:
# Multiple default session attempts:
session = snowflake.snowpark.session._get_sandbox_conditional_active_session(
None
)
assert session is not None
except (
snowflake.snowpark.exceptions.SnowparkSessionException,
AssertionError,
):
# Use modin session retrieval first, as it supports multiple sessions.
# Expect this to fail if modin was not installed, for Python 3.8, ... but that's ok.
try:
import modin.pandas as pd
session = pd.session
except Exception as e: # noqa: F841
try:
# Get from default session.
from snowflake.snowpark.context import get_active_session
session = get_active_session()
except Exception as e: # noqa: F841
pass
finally:
if session is None:
_logger.debug(
f"Could not retrieve default session "
f"for function {func.__qualname__}, capturing AST by default."
)
# session has not been created yet. To not lose information, always encode AST.
return True # noqa: B012
else:
return session.ast_enabled # noqa: B012
def publicapi(func) -> Callable:
"""decorator to safeguard public APIs with global feature flags."""
# TODO(SNOW-1491199) - This method is not covered by tests until the end of phase 0. Drop the pragma when it is covered.
@functools.wraps(func)
def func_call_wrapper(*args, **kwargs): # pragma: no cover
# warning(func.__qualname__, warning_text)
# Handle AST encoding, by modifying default behavior.
# If a function supports AST encoding, it must have a parameter _emit_ast.
# If now _emit_ast is passed as part of kwargs (we do not allow for the positional syntax!)
# then we use this value directly. If not, but the function supports _emit_ast,
# we override _emit_ast with the session parameter.
if "_emit_ast" in func.__code__.co_varnames and "_emit_ast" not in kwargs:
# No arguments, or single argument with function.
if len(args) == 0 or (len(args) == 1 and isinstance(args[0], Callable)):
if func.__name__ in {
"udf",
"udtf",
"udaf",
"pandas_udf",
"pandas_udtf",
"sproc",
}:
session = kwargs.get("session")
# Lookup session directly as in implementation of these decorators.
session = snowflake.snowpark.session._get_sandbox_conditional_active_session(
session
)
# If session is None, do nothing (i.e., keep encoding AST).
# This happens when the decorator is called before a session is started.
if session is not None:
kwargs["_emit_ast"] = session.ast_enabled
# Function passed fully with kwargs only (i.e., not a method - self will always be passed positionally)
elif len(kwargs) != 0:
# Check if one of the kwargs holds a session object. If so, retrieve AST enabled from there.
session_vars = [
var
for var in kwargs.values()
if isinstance(var, snowflake.snowpark.session.Session)
]
if session_vars:
kwargs["_emit_ast"] = session_vars[0].ast_enabled
else:
kwargs["_emit_ast"] = infer_ast_enabled_from_global_sessions(
func
)
elif isinstance(args[0], snowflake.snowpark.dataframe.DataFrame):
# special case: __init__ called, self._session is then not initialized yet.
if func.__qualname__.endswith(".__init__"):
# Try to find a session argument.
session_args = [
arg
for arg in args
if isinstance(arg, snowflake.snowpark.session.Session)
]
assert (
len(session_args) != 0
), f"{func.__qualname__} must have at least one session arg."
kwargs["_emit_ast"] = session_args[0].ast_enabled
else:
kwargs["_emit_ast"] = args[0]._session.ast_enabled
elif isinstance(
args[0], snowflake.snowpark.dataframe_reader.DataFrameReader
):
if func.__qualname__.endswith(".__init__"):
assert isinstance(
args[1], snowflake.snowpark.session.Session
), f"{func.__qualname__} second arg must be session."
kwargs["_emit_ast"] = args[1].ast_enabled
else:
kwargs["_emit_ast"] = args[0]._session.ast_enabled
elif isinstance(
args[0], snowflake.snowpark.dataframe_writer.DataFrameWriter
):
if func.__qualname__.endswith(".__init__"):
assert isinstance(
args[1], snowflake.snowpark.DataFrame
), f"{func.__qualname__} second arg must be dataframe."
kwargs["_emit_ast"] = args[1]._session.ast_enabled
else:
kwargs["_emit_ast"] = args[0]._dataframe._session.ast_enabled
elif isinstance(
args[0],
(
snowflake.snowpark.dataframe_stat_functions.DataFrameStatFunctions,
snowflake.snowpark.dataframe_analytics_functions.DataFrameAnalyticsFunctions,
snowflake.snowpark.dataframe_na_functions.DataFrameNaFunctions,
),
):
kwargs["_emit_ast"] = args[0]._dataframe._session.ast_enabled
elif hasattr(args[0], "_session") and args[0]._session is not None:
kwargs["_emit_ast"] = args[0]._session.ast_enabled
elif isinstance(args[0], snowflake.snowpark.session.Session):
kwargs["_emit_ast"] = args[0].ast_enabled
elif isinstance(
args[0],
snowflake.snowpark.relational_grouped_dataframe.RelationalGroupedDataFrame,
):
kwargs["_emit_ast"] = args[0]._dataframe._session.ast_enabled
else:
kwargs["_emit_ast"] = infer_ast_enabled_from_global_sessions(func)
# TODO: Could modify internal docstring to display that users should not modify the _emit_ast parameter.
return func(*args, **kwargs)
return func_call_wrapper
def func_decorator(