-
Notifications
You must be signed in to change notification settings - Fork 542
Expand file tree
/
Copy pathcursor.py
More file actions
1947 lines (1718 loc) · 72.3 KB
/
cursor.py
File metadata and controls
1947 lines (1718 loc) · 72.3 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 python
from __future__ import annotations
import collections
import logging
import os
import re
import signal
import sys
import time
import uuid
import warnings
from enum import Enum
from logging import getLogger
from threading import Lock
from types import TracebackType
from typing import (
IO,
TYPE_CHECKING,
Any,
Callable,
Iterator,
Literal,
NamedTuple,
NoReturn,
Sequence,
TypeVar,
overload,
)
from typing_extensions import Self
from snowflake.connector.result_batch import create_batches_from_response
from snowflake.connector.result_set import ResultSet
from . import compat
from ._sql_util import get_file_transfer_type
from ._utils import (
REQUEST_ID_STATEMENT_PARAM_NAME,
_TrackedQueryCancellationTimer,
is_uuid4,
)
from .bind_upload_agent import BindUploadAgent, BindUploadError
from .constants import (
CMD_TYPE_DOWNLOAD,
CMD_TYPE_UPLOAD,
FIELD_NAME_TO_ID,
PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT,
FileTransferType,
QueryStatus,
)
from .errorcode import (
ER_CURSOR_IS_CLOSED,
ER_FAILED_PROCESSING_PYFORMAT,
ER_FAILED_TO_REWRITE_MULTI_ROW_INSERT,
ER_INVALID_VALUE,
ER_NO_ARROW_RESULT,
ER_NO_PYARROW,
ER_NO_PYARROW_SNOWSQL,
ER_NOT_POSITIVE_SIZE,
ER_UNSUPPORTED_METHOD,
)
from .errors import (
DatabaseError,
Error,
IntegrityError,
InterfaceError,
NotSupportedError,
ProgrammingError,
)
from .options import installed_pandas
from .sqlstate import SQLSTATE_FEATURE_NOT_SUPPORTED
from .telemetry import TelemetryData, TelemetryField
from .time_util import get_time_millis
if TYPE_CHECKING: # pragma: no cover
from pandas import DataFrame
from pyarrow import Table
from .connection import SnowflakeConnection
from .file_transfer_agent import SnowflakeProgressPercentage
from .result_batch import ResultBatch
T = TypeVar("T", bound=collections.abc.Sequence)
logger = getLogger(__name__)
if not installed_pandas:
logger.debug(
"Failed to import pyarrow or pandas. Cannot use pandas fetch API. Please "
"install snowflake-connector-python with the `pandas` extra to use these "
"features."
)
try:
from .nanoarrow_arrow_iterator import PyArrowIterator # NOQA
CAN_USE_ARROW_RESULT_FORMAT = True
except ImportError as e: # pragma: no cover
logger.warning(
f"Failed to import ArrowResult. No Apache Arrow result set format can be used. ImportError: {e}",
)
CAN_USE_ARROW_RESULT_FORMAT = False
STATEMENT_TYPE_ID_DML = 0x3000
STATEMENT_TYPE_ID_INSERT = STATEMENT_TYPE_ID_DML + 0x100
STATEMENT_TYPE_ID_UPDATE = STATEMENT_TYPE_ID_DML + 0x200
STATEMENT_TYPE_ID_DELETE = STATEMENT_TYPE_ID_DML + 0x300
STATEMENT_TYPE_ID_MERGE = STATEMENT_TYPE_ID_DML + 0x400
STATEMENT_TYPE_ID_MULTI_TABLE_INSERT = STATEMENT_TYPE_ID_DML + 0x500
STATEMENT_TYPE_ID_DML_SET = frozenset(
[
STATEMENT_TYPE_ID_DML,
STATEMENT_TYPE_ID_INSERT,
STATEMENT_TYPE_ID_UPDATE,
STATEMENT_TYPE_ID_DELETE,
STATEMENT_TYPE_ID_MERGE,
STATEMENT_TYPE_ID_MULTI_TABLE_INSERT,
]
)
DESC_TABLE_RE = re.compile(r"desc(?:ribe)?\s+([\w_]+)\s*;?\s*$", flags=re.IGNORECASE)
LOG_MAX_QUERY_LENGTH = 80
ASYNC_NO_DATA_MAX_RETRY = 24
ASYNC_RETRY_PATTERN = [1, 1, 2, 3, 4, 8, 10]
class _NanoarrowUsage(str, Enum):
# follow the session parameter to use nanoarrow converter or not
FOLLOW_SESSION_PARAMETER = "follow_session_parameter"
# ignore the session parameter, use nanoarrow converter
ENABLE_NANOARROW = "enable_nanoarrow"
# ignore the session parameter, do not use nanoarrow converter
DISABLE_NANOARROW = "disable_nanoarrow"
class ResultMetadata(NamedTuple):
name: str
type_code: int
display_size: int | None
internal_size: int | None
precision: int | None
scale: int | None
is_nullable: bool
@classmethod
def from_column(cls, col: dict[str, Any]):
"""Initializes a ResultMetadata object from the column description in the query response."""
type_code = FIELD_NAME_TO_ID[
(
col["extTypeName"].upper()
if col.get("extTypeName")
else col["type"].upper()
)
]
return cls(
col["name"],
type_code,
None,
col["length"],
col["precision"],
col["scale"],
col["nullable"],
)
class ResultMetadataV2:
"""ResultMetadataV2 represents the type information of a single column.
It is a replacement for ResultMetadata that contains additional attributes, currently
`vector_dimension` and `fields`. This class will be unified with ResultMetadata in the
near future.
"""
def __init__(
self,
name: str,
type_code: int,
is_nullable: bool,
display_size: int | None = None,
internal_size: int | None = None,
precision: int | None = None,
scale: int | None = None,
vector_dimension: int | None = None,
fields: list[ResultMetadataV2] | None = None,
):
self._name = name
self._type_code = type_code
self._is_nullable = is_nullable
self._display_size = display_size
self._internal_size = internal_size
self._precision = precision
self._scale = scale
self._vector_dimension = vector_dimension
self._fields = fields
@classmethod
def from_column(cls, col: dict[str, Any]) -> ResultMetadataV2:
"""Initializes a ResultMetadataV2 object from the column description in the query response.
This differs from ResultMetadata in that it has newly-added fields which cannot be added to
ResultMetadata since it is a named tuple.
"""
col_type = (
col["extTypeName"].upper()
if col.get("extTypeName")
else col["type"].upper()
)
fields = col.get("fields")
processed_fields: Optional[List[ResultMetadataV2]] = None
if fields is not None:
if col_type in {"VECTOR", "ARRAY", "OBJECT", "MAP"}:
processed_fields = [
ResultMetadataV2.from_column({"name": None, **f})
for f in col["fields"]
]
else:
raise ValueError(
f"Field parsing is not supported for columns of type {col_type}."
)
return cls(
col["name"],
FIELD_NAME_TO_ID[col_type],
col["nullable"],
None,
col["length"],
col["precision"],
col["scale"],
col.get("vectorDimension"),
processed_fields,
)
def _to_result_metadata_v1(self):
"""Initializes a ResultMetadata object from a ResultMetadataV2 object.
This method is for internal use only.
"""
return ResultMetadata(
self._name,
self._type_code,
self._display_size,
self._internal_size,
self._precision,
self._scale,
self._is_nullable,
)
def __str__(self) -> str:
return (
f"ResultMetadataV2(name={self._name},type_code={self._type_code},"
+ f"is_nullable={self._is_nullable},display_size={self._display_size},"
+ "internal_size={self._internal_size},precision={self._precision},"
+ "scale={self._scale},vector_dimension={self._vector_dimension},"
+ "fields={self.fields})"
)
def __eq__(self, other) -> bool:
if not isinstance(other, self.__class__):
return False
return (
self._name == other._name
and self._type_code == other._type_code
and self._is_nullable == other._is_nullable
and self._display_size == other._display_size
and self._internal_size == other._internal_size
and self._precision == other._precision
and self._scale == other._scale
and self._vector_dimension == other._vector_dimension
and self._fields == other._fields
)
@property
def name(self) -> str:
return self._name
@property
def type_code(self) -> int:
return self._type_code
@property
def is_nullable(self) -> bool:
return self._is_nullable
@property
def internal_size(self) -> int | None:
return self._internal_size
@property
def display_size(self) -> int | None:
return self._display_size
@property
def precision(self) -> int | None:
return self._precision
@property
def scale(self) -> int | None:
return self._scale
@property
def vector_dimension(self) -> int | None:
return self._vector_dimension
@property
def fields(self) -> list[ResultMetadataV2] | None:
return self._fields
def exit_handler(*_) -> NoReturn:
"""Handler for signal. When called, it will raise SystemExit with exit code FORCE_EXIT."""
print("\nForce exit")
logger.info("Force exit")
sys.exit(1)
class ResultState(Enum):
DEFAULT = 1
VALID = 2
RESET = 3
class SnowflakeCursor:
"""Implementation of Cursor object that is returned from Connection.cursor() method.
Attributes:
description: A list of namedtuples about metadata for all columns.
rowcount: The number of records updated or selected. If not clear, -1 is returned.
rownumber: The current 0-based index of the cursor in the result set or None if the index cannot be
determined.
sfqid: Snowflake query id in UUID form. Include this in the problem report to the customer support.
sqlstate: Snowflake SQL State code.
timestamp_output_format: Snowflake timestamp_output_format for timestamps.
timestamp_ltz_output_format: Snowflake output format for LTZ timestamps.
timestamp_tz_output_format: Snowflake output format for TZ timestamps.
timestamp_ntz_output_format: Snowflake output format for NTZ timestamps.
date_output_format: Snowflake output format for dates.
time_output_format: Snowflake output format for times.
timezone: Snowflake timezone.
binary_output_format: Snowflake output format for binary fields.
arraysize: The default number of rows fetched by fetchmany.
connection: The connection object by which the cursor was created.
errorhandle: The class that handles error handling.
is_file_transfer: Whether, or not the current command is a put, or get.
"""
# TODO:
# Most of these attributes have no reason to be properties, we could just store them in public variables.
# Calling a function is expensive in Python and most of these getters are unnecessary.
INSERT_SQL_RE = re.compile(r"^insert\s+into", flags=re.IGNORECASE)
COMMENT_SQL_RE = re.compile(r"/\*.*\*/")
INSERT_SQL_VALUES_RE = re.compile(
r".*VALUES\s*(\(.*\)).*", re.IGNORECASE | re.MULTILINE | re.DOTALL
)
ALTER_SESSION_RE = re.compile(
r"alter\s+session\s+set\s+(\w*?)\s*=\s*\'?([^\']+?)\'?\s*(?:;|$)",
flags=re.IGNORECASE | re.MULTILINE | re.DOTALL,
)
@staticmethod
def get_file_transfer_type(sql: str) -> FileTransferType | None:
"""Decide whether a SQL is a file transfer and return its type.
None is returned if the SQL isn't a file transfer so that this function can be
used in an if-statement.
"""
return get_file_transfer_type(sql)
def __init__(
self,
connection: SnowflakeConnection,
use_dict_result: bool = False,
) -> None:
"""Inits a SnowflakeCursor with a connection.
Args:
connection: The connection that created this cursor.
use_dict_result: Decides whether to use dict result or not.
"""
self._connection: SnowflakeConnection = connection
self._errorhandler: Callable[
[SnowflakeConnection, SnowflakeCursor, type[Error], dict[str, str]],
None,
] = Error.default_errorhandler
self.messages: list[
tuple[type[Error] | type[Exception], dict[str, str | bool]]
] = []
self._timebomb: _TrackedQueryCancellationTimer | None = (
None # must be here for abort_exit method
)
self._description: list[ResultMetadataV2] | None = None
self._sfqid: str | None = None
self._sqlstate = None
self._total_rowcount = -1
self._sequence_counter = -1
self._request_id: uuid.UUID | None = None
self._is_file_transfer = False
self._multi_statement_resultIds: collections.deque[str] = collections.deque()
self.multi_statement_savedIds: list[str] = []
self._timestamp_output_format = None
self._timestamp_ltz_output_format = None
self._timestamp_ntz_output_format = None
self._timestamp_tz_output_format = None
self._date_output_format = None
self._time_output_format = None
self._timezone = None
self._binary_output_format = None
self._result: Iterator[tuple] | Iterator[dict] | None = None
self._result_set: ResultSet | None = None
self._result_state: ResultState = ResultState.DEFAULT
self._use_dict_result = use_dict_result
self.query: str | None = None
# TODO: self._query_result_format could be defined as an enum
self._query_result_format: str | None = None
self._arraysize = 1 # PEP-0249: defaults to 1
self._lock_canceling = Lock()
self._first_chunk_time = None
self._log_max_query_length = connection.log_max_query_length
self._inner_cursor: SnowflakeCursor | None = None
self._prefetch_hook = None
self._rownumber: int | None = None
self.reset()
def __del__(self) -> None: # pragma: no cover
try:
self.close()
except compat.BASE_EXCEPTION_CLASS as e:
if logger.getEffectiveLevel() <= logging.INFO:
logger.info(e)
@property
def description(self) -> list[ResultMetadata]:
if self._description is None:
return None
return [meta._to_result_metadata_v1() for meta in self._description]
@property
def _description_internal(self) -> list[ResultMetadataV2]:
"""Return the new format of result metadata for a query.
This method is for internal use only.
"""
return self._description
@property
def rowcount(self) -> int | None:
return self._total_rowcount if self._total_rowcount >= 0 else None
@property
def rownumber(self) -> int | None:
return self._rownumber if self._rownumber >= 0 else None
@property
def sfqid(self) -> str | None:
return self._sfqid
@property
def sqlstate(self):
return self._sqlstate
@property
def timestamp_output_format(self) -> str | None:
return self._timestamp_output_format
@property
def timestamp_ltz_output_format(self) -> str | None:
return (
self._timestamp_ltz_output_format
if self._timestamp_ltz_output_format
else self._timestamp_output_format
)
@property
def timestamp_tz_output_format(self) -> str | None:
return (
self._timestamp_tz_output_format
if self._timestamp_tz_output_format
else self._timestamp_output_format
)
@property
def timestamp_ntz_output_format(self) -> str | None:
return (
self._timestamp_ntz_output_format
if self._timestamp_ntz_output_format
else self._timestamp_output_format
)
@property
def date_output_format(self) -> str | None:
return self._date_output_format
@property
def time_output_format(self) -> str | None:
return self._time_output_format
@property
def timezone(self) -> str | None:
return self._timezone
@property
def binary_output_format(self) -> str | None:
return self._binary_output_format
@property
def arraysize(self) -> int:
return self._arraysize
@arraysize.setter
def arraysize(self, value) -> None:
self._arraysize = int(value)
@property
def connection(self) -> SnowflakeConnection:
return self._connection
@property
def errorhandler(self) -> Callable:
return self._errorhandler
@errorhandler.setter
def errorhandler(self, value: Callable | None) -> None:
logger.debug("setting errorhandler: %s", value)
if value is None:
raise ProgrammingError("Invalid errorhandler is specified")
self._errorhandler = value
@property
def is_file_transfer(self) -> bool:
"""Whether the command is PUT or GET."""
return hasattr(self, "_is_file_transfer") and self._is_file_transfer
@property
def lastrowid(self) -> None:
"""Snowflake does not support lastrowid in which case None should be returned as per PEP249."""
return None
@overload
def callproc(self, procname: str) -> tuple: ...
@overload
def callproc(self, procname: str, args: T) -> T: ...
def callproc(self, procname: str, args=tuple()):
"""Call a stored procedure.
Args:
procname: The stored procedure to be called.
args: Parameters to be passed into the stored procedure.
Returns:
The input parameters.
"""
marker_format = "%s" if self._connection.is_pyformat else "?"
command = (
f"CALL {procname}({', '.join([marker_format for _ in range(len(args))])})"
)
self.execute(command, args)
return args
def close(self) -> bool | None:
"""Closes the cursor object.
Returns whether the cursor was closed during this call.
"""
try:
if self.is_closed():
return False
with self._lock_canceling:
self.reset(closing=True)
self._connection = None
del self.messages[:]
return True
except Exception:
return None
def is_closed(self) -> bool:
return self._connection is None or self._connection.is_closed()
def _execute_helper(
self,
query: str,
timeout: int = 0,
statement_params: dict[str, str] | None = None,
binding_params: tuple | dict[str, dict[str, str]] = None,
binding_stage: str | None = None,
is_internal: bool = False,
describe_only: bool = False,
_no_results: bool = False,
_is_put_get=None,
_no_retry: bool = False,
dataframe_ast: str | None = None,
) -> dict[str, Any]:
del self.messages[:]
if statement_params is not None and not isinstance(statement_params, dict):
Error.errorhandler_wrapper(
self.connection,
self,
ProgrammingError,
{
"msg": "The data type of statement params is invalid. It must be dict.",
"errno": ER_INVALID_VALUE,
},
)
# check if current installation include arrow extension or not,
# if not, we set statement level query result format to be JSON
if not CAN_USE_ARROW_RESULT_FORMAT:
logger.debug("Cannot use arrow result format, fallback to json format")
if statement_params is None:
statement_params = {
PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT: "JSON"
}
else:
result_format_val = statement_params.get(
PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT
)
if str(result_format_val).upper() == "ARROW":
self.check_can_use_arrow_resultset()
elif result_format_val is None:
statement_params[PARAMETER_PYTHON_CONNECTOR_QUERY_RESULT_FORMAT] = (
"JSON"
)
self._sequence_counter = self._connection._next_sequence_counter()
# If requestId is contained in statement parameters, use it to set request id. Verify here it is a valid uuid4
# identifier.
if (
statement_params is not None
and REQUEST_ID_STATEMENT_PARAM_NAME in statement_params
):
request_id = statement_params[REQUEST_ID_STATEMENT_PARAM_NAME]
if not is_uuid4(request_id):
# uuid.UUID will throw an error if invalid, but we explicitly check and throw here.
raise ValueError(f"requestId {request_id} is not a valid UUID4.")
self._request_id = uuid.UUID(str(request_id), version=4)
# Create a (deep copy) and remove the statement param, there is no need to encode it as extra parameter
# one more time.
statement_params = statement_params.copy()
statement_params.pop(REQUEST_ID_STATEMENT_PARAM_NAME)
else:
# Generate UUID for query.
self._request_id = uuid.uuid4()
logger.debug(f"Request id: {self._request_id}")
logger.debug("running query [%s]", self._format_query_for_log(query))
if _is_put_get is not None:
# if told the query is PUT or GET, use the information
self._is_file_transfer = _is_put_get
else:
# or detect it.
self._is_file_transfer = get_file_transfer_type(query) is not None
logger.debug("is_file_transfer: %s", self._is_file_transfer is not None)
real_timeout = (
timeout if timeout and timeout > 0 else self._connection.network_timeout
)
if real_timeout is not None:
self._timebomb = _TrackedQueryCancellationTimer(
real_timeout, self.__cancel_query, [query]
)
self._timebomb.start()
logger.debug("started timebomb in %ss", real_timeout)
else:
self._timebomb = None
original_sigint = signal.getsignal(signal.SIGINT)
def interrupt_handler(*_): # pragma: no cover
try:
signal.signal(signal.SIGINT, exit_handler)
except (ValueError, TypeError):
# ignore failures
pass
try:
if self._timebomb is not None:
self._timebomb.cancel()
logger.debug("cancelled timebomb in finally")
self._timebomb = None
self.__cancel_query(query)
finally:
if original_sigint:
try:
signal.signal(signal.SIGINT, original_sigint)
except (ValueError, TypeError):
# ignore failures
pass
raise KeyboardInterrupt
try:
if not original_sigint == exit_handler:
signal.signal(signal.SIGINT, interrupt_handler)
except ValueError: # pragma: no cover
logger.debug(
"Failed to set SIGINT handler. " "Not in main thread. Ignored..."
)
ret: dict[str, Any] = {"data": {}}
try:
ret = self._connection.cmd_query(
query,
self._sequence_counter,
self._request_id,
binding_params=binding_params,
binding_stage=binding_stage,
is_file_transfer=bool(self._is_file_transfer),
statement_params=statement_params,
is_internal=is_internal,
describe_only=describe_only,
_no_results=_no_results,
_no_retry=_no_retry,
timeout=real_timeout,
dataframe_ast=dataframe_ast,
)
finally:
try:
if original_sigint:
signal.signal(signal.SIGINT, original_sigint)
except (ValueError, TypeError): # pragma: no cover
logger.debug(
"Failed to reset SIGINT handler. Not in main " "thread. Ignored..."
)
if self._timebomb is not None:
self._timebomb.cancel()
logger.debug("cancelled timebomb in finally")
if "data" in ret and "parameters" in ret["data"]:
parameters = ret["data"].get("parameters", list())
# Set session parameters for cursor object
for kv in parameters:
if "TIMESTAMP_OUTPUT_FORMAT" in kv["name"]:
self._timestamp_output_format = kv["value"]
elif "TIMESTAMP_NTZ_OUTPUT_FORMAT" in kv["name"]:
self._timestamp_ntz_output_format = kv["value"]
elif "TIMESTAMP_LTZ_OUTPUT_FORMAT" in kv["name"]:
self._timestamp_ltz_output_format = kv["value"]
elif "TIMESTAMP_TZ_OUTPUT_FORMAT" in kv["name"]:
self._timestamp_tz_output_format = kv["value"]
elif "DATE_OUTPUT_FORMAT" in kv["name"]:
self._date_output_format = kv["value"]
elif "TIME_OUTPUT_FORMAT" in kv["name"]:
self._time_output_format = kv["value"]
elif "TIMEZONE" in kv["name"]:
self._timezone = kv["value"]
elif "BINARY_OUTPUT_FORMAT" in kv["name"]:
self._binary_output_format = kv["value"]
# Set session parameters for connection object
self._connection._update_parameters(
{p["name"]: p["value"] for p in parameters}
)
self.query = query
self._sequence_counter = -1
return ret
def _preprocess_pyformat_query(
self,
command: str,
params: Sequence[Any] | dict[Any, Any] | None = None,
) -> str:
# pyformat/format paramstyle
# client side binding
processed_params = self._connection._process_params_pyformat(params, self)
# SNOW-513061 collect telemetry for empty sequence usage before we make the breaking change announcement
if params is not None and len(params) == 0:
self._log_telemetry_job_data(
TelemetryField.EMPTY_SEQ_INTERPOLATION,
(
TelemetryData.TRUE
if self.connection._interpolate_empty_sequences
else TelemetryData.FALSE
),
)
if logger.getEffectiveLevel() <= logging.DEBUG:
logger.debug(
f"binding: [{self._format_query_for_log(command)}] "
f"with input=[{params}], "
f"processed=[{processed_params}]",
)
if (
self.connection._interpolate_empty_sequences
and processed_params is not None
) or (
not self.connection._interpolate_empty_sequences
and len(processed_params) > 0
):
query = command % processed_params
else:
query = command
return query
@overload
def execute(
self,
command: str,
params: Sequence[Any] | dict[Any, Any] | None = None,
_bind_stage: str | None = None,
timeout: int | None = None,
_exec_async: bool = False,
_no_retry: bool = False,
_do_reset: bool = True,
_put_callback: SnowflakeProgressPercentage = None,
_put_azure_callback: SnowflakeProgressPercentage = None,
_put_callback_output_stream: IO[str] = sys.stdout,
_get_callback: SnowflakeProgressPercentage = None,
_get_azure_callback: SnowflakeProgressPercentage = None,
_get_callback_output_stream: IO[str] = sys.stdout,
_show_progress_bar: bool = True,
_statement_params: dict[str, str] | None = None,
_is_internal: bool = False,
_describe_only: bool = False,
_no_results: Literal[False] = False,
_is_put_get: bool | None = None,
_raise_put_get_error: bool = True,
_force_put_overwrite: bool = False,
_skip_upload_on_content_match: bool = False,
file_stream: IO[bytes] | None = None,
num_statements: int | None = None,
_dataframe_ast: str | None = None,
) -> Self | None: ...
@overload
def execute(
self,
command: str,
params: Sequence[Any] | dict[Any, Any] | None = None,
_bind_stage: str | None = None,
timeout: int | None = None,
_exec_async: bool = False,
_no_retry: bool = False,
_do_reset: bool = True,
_put_callback: SnowflakeProgressPercentage = None,
_put_azure_callback: SnowflakeProgressPercentage = None,
_put_callback_output_stream: IO[str] = sys.stdout,
_get_callback: SnowflakeProgressPercentage = None,
_get_azure_callback: SnowflakeProgressPercentage = None,
_get_callback_output_stream: IO[str] = sys.stdout,
_show_progress_bar: bool = True,
_statement_params: dict[str, str] | None = None,
_is_internal: bool = False,
_describe_only: bool = False,
_no_results: Literal[True] = True,
_is_put_get: bool | None = None,
_raise_put_get_error: bool = True,
_force_put_overwrite: bool = False,
_skip_upload_on_content_match: bool = False,
file_stream: IO[bytes] | None = None,
num_statements: int | None = None,
_dataframe_ast: str | None = None,
) -> dict[str, Any] | None: ...
def execute(
self,
command: str,
params: Sequence[Any] | dict[Any, Any] | None = None,
_bind_stage: str | None = None,
timeout: int | None = None,
_exec_async: bool = False,
_no_retry: bool = False,
_do_reset: bool = True,
_put_callback: SnowflakeProgressPercentage = None,
_put_azure_callback: SnowflakeProgressPercentage = None,
_put_callback_output_stream: IO[str] = sys.stdout,
_get_callback: SnowflakeProgressPercentage = None,
_get_azure_callback: SnowflakeProgressPercentage = None,
_get_callback_output_stream: IO[str] = sys.stdout,
_show_progress_bar: bool = True,
_statement_params: dict[str, str] | None = None,
_is_internal: bool = False,
_describe_only: bool = False,
_no_results: bool = False,
_is_put_get: bool | None = None,
_raise_put_get_error: bool = True,
_force_put_overwrite: bool = False,
_skip_upload_on_content_match: bool = False,
file_stream: IO[bytes] | None = None,
num_statements: int | None = None,
_force_qmark_paramstyle: bool = False,
_dataframe_ast: str | None = None,
) -> Self | dict[str, Any] | None:
"""Executes a command/query.
Args:
command: The SQL command to be executed.
params: Parameters to be bound into the SQL statement.
_bind_stage: Path in temporary stage where binding parameters are uploaded as CSV files.
timeout: Number of seconds after which to abort the query.
_exec_async: Whether to execute this query asynchronously.
_no_retry: Whether or not to retry on known errors.
_do_reset: Whether or not the result set needs to be reset before executing query.
_put_callback: Function to which PUT command should call back to.
_put_azure_callback: Function to which an Azure PUT command should call back to.
_put_callback_output_stream: The output stream a PUT command's callback should report on.
_get_callback: Function to which GET command should call back to.
_get_azure_callback: Function to which an Azure GET command should call back to.
_get_callback_output_stream: The output stream a GET command's callback should report on.
_show_progress_bar: Whether or not to show progress bar.
_statement_params: Extra information that should be sent to Snowflake with query. This dict will not be
modified by the connector.
_is_internal: This flag indicates whether the query is issued internally by the connector.
_describe_only: If true, the query will not be executed but return the schema/description of this query.
_no_results: This flag tells the back-end to not return the result, just fire the query and return the
response returned by Snowflake's server.
_use_ijson: This flag doesn't do anything as ijson support has ended.
_is_put_get: Force decision of this SQL query being a PUT, or GET command. This is detected otherwise.
_raise_put_get_error: Whether to raise PUT and GET errors.
_force_put_overwrite: If the SQL query is a PUT, then this flag can force overwriting of an already
existing file on stage.
_skip_upload_on_content_match: If the SQL query is a PUT with overwrite enabled, then this flag will skip upload
if the file contents match to ease concurrent uploads.
file_stream: File-like object to be uploaded with PUT
num_statements: Query level parameter submitted in _statement_params constraining exact number of
statements being submitted (or 0 if submitting an uncounted number) when using a multi-statement query.
_force_qmark_paramstyle: Force the use of qmark paramstyle regardless of the connection's paramstyle.
_dataframe_ast: Base64-encoded dataframe request abstract syntax tree.
Returns:
The cursor itself, or None if some error happened, or the response returned
by Snowflake if the _no_results flag is on.
"""
if _exec_async:
_no_results = True
logger.debug("executing SQL/command")
if self.is_closed():
Error.errorhandler_wrapper(
self.connection,
self,
InterfaceError,
{"msg": "Cursor is closed in execute.", "errno": ER_CURSOR_IS_CLOSED},
)
if _do_reset:
self.reset()
command = command.strip(" \t\n\r") if command else ""
if not command:
if _dataframe_ast:
logger.debug("dataframe ast: [%s]", _dataframe_ast)
else:
logger.warning("execute: no query is given to execute")
return None
logger.debug("query: [%s]", self._format_query_for_log(command))
_statement_params = _statement_params or dict()
# If we need to add another parameter, please consider introducing a dict for all extra params
# See discussion in https://github.com/snowflakedb/snowflake-connector-python/pull/1524#discussion_r1174061775
if num_statements is not None:
_statement_params = {
**_statement_params,
"MULTI_STATEMENT_COUNT": num_statements,
}
kwargs: dict[str, Any] = {
"timeout": timeout,
"statement_params": _statement_params,
"is_internal": _is_internal,
"describe_only": _describe_only,
"_no_results": _no_results,
"_is_put_get": _is_put_get,
"_no_retry": _no_retry,
"dataframe_ast": _dataframe_ast,
}
if self._connection.is_pyformat and not _force_qmark_paramstyle:
query = self._preprocess_pyformat_query(command, params)
else:
# qmark and numeric paramstyle
query = command
if _bind_stage:
kwargs["binding_stage"] = _bind_stage
else:
if params is not None and not isinstance(params, (list, tuple)):
errorvalue = {
"msg": f"Binding parameters must be a list: {params}",
"errno": ER_FAILED_PROCESSING_PYFORMAT,
}
Error.errorhandler_wrapper(
self.connection, self, ProgrammingError, errorvalue
)