codekingpro commited on
Commit
ed8fda8
·
verified ·
1 Parent(s): c36ba33

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. python/user_packages/Python313/site-packages/__pycache__/brotli.cpython-313.pyc +0 -0
  2. python/user_packages/Python313/site-packages/__pycache__/jsonpatch.cpython-313.pyc +0 -0
  3. python/user_packages/Python313/site-packages/__pycache__/jsonpointer.cpython-313.pyc +0 -0
  4. python/user_packages/Python313/site-packages/__pycache__/kaitaistruct.cpython-313.pyc +0 -0
  5. python/user_packages/Python313/site-packages/__pycache__/mypy_extensions.cpython-313.pyc +0 -0
  6. python/user_packages/Python313/site-packages/__pycache__/six.cpython-313.pyc +0 -0
  7. python/user_packages/Python313/site-packages/__pycache__/socks.cpython-313.pyc +0 -0
  8. python/user_packages/Python313/site-packages/__pycache__/sockshandler.cpython-313.pyc +0 -0
  9. python/user_packages/Python313/site-packages/__pycache__/typing_inspect.cpython-313.pyc +0 -0
  10. python/user_packages/Python313/site-packages/_argon2_cffi_bindings/__init__.py +6 -0
  11. python/user_packages/Python313/site-packages/_argon2_cffi_bindings/__pycache__/__init__.cpython-313.pyc +0 -0
  12. python/user_packages/Python313/site-packages/_argon2_cffi_bindings/__pycache__/_ffi_build.cpython-313.pyc +0 -0
  13. python/user_packages/Python313/site-packages/_argon2_cffi_bindings/_ffi.pyd +0 -0
  14. python/user_packages/Python313/site-packages/_argon2_cffi_bindings/_ffi_build.py +233 -0
  15. python/user_packages/Python313/site-packages/_distutils_hack/__init__.py +239 -0
  16. python/user_packages/Python313/site-packages/_distutils_hack/__pycache__/__init__.cpython-313.pyc +0 -0
  17. python/user_packages/Python313/site-packages/_distutils_hack/__pycache__/override.cpython-313.pyc +0 -0
  18. python/user_packages/Python313/site-packages/_distutils_hack/override.py +1 -0
  19. python/user_packages/Python313/site-packages/_yaml/__init__.py +33 -0
  20. python/user_packages/Python313/site-packages/_yaml/__pycache__/__init__.cpython-313.pyc +0 -0
  21. python/user_packages/Python313/site-packages/sqlalchemy-2.0.49.dist-info/licenses/LICENSE +19 -0
  22. python/user_packages/Python313/site-packages/sqlalchemy/connectors/__init__.py +18 -0
  23. python/user_packages/Python313/site-packages/sqlalchemy/connectors/aioodbc.py +194 -0
  24. python/user_packages/Python313/site-packages/sqlalchemy/connectors/asyncio.py +429 -0
  25. python/user_packages/Python313/site-packages/sqlalchemy/connectors/pyodbc.py +250 -0
  26. python/user_packages/Python313/site-packages/sqlalchemy/cyextension/__init__.py +6 -0
  27. python/user_packages/Python313/site-packages/sqlalchemy/cyextension/collections.pyx +409 -0
  28. python/user_packages/Python313/site-packages/sqlalchemy/cyextension/immutabledict.cp313-win_amd64.pyd +0 -0
  29. python/user_packages/Python313/site-packages/sqlalchemy/cyextension/immutabledict.pxd +8 -0
  30. python/user_packages/Python313/site-packages/sqlalchemy/cyextension/immutabledict.pyx +133 -0
  31. python/user_packages/Python313/site-packages/sqlalchemy/cyextension/processors.cp313-win_amd64.pyd +0 -0
  32. python/user_packages/Python313/site-packages/sqlalchemy/cyextension/processors.pyx +68 -0
  33. python/user_packages/Python313/site-packages/sqlalchemy/cyextension/resultproxy.cp313-win_amd64.pyd +0 -0
  34. python/user_packages/Python313/site-packages/sqlalchemy/cyextension/resultproxy.pyx +102 -0
  35. python/user_packages/Python313/site-packages/sqlalchemy/cyextension/util.cp313-win_amd64.pyd +0 -0
  36. python/user_packages/Python313/site-packages/sqlalchemy/cyextension/util.pyx +90 -0
  37. python/user_packages/Python313/site-packages/sqlalchemy/dialects/__init__.py +62 -0
  38. python/user_packages/Python313/site-packages/sqlalchemy/dialects/_typing.py +30 -0
  39. python/user_packages/Python313/site-packages/sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  40. python/user_packages/Python313/site-packages/sqlalchemy/engine/__init__.py +62 -0
  41. python/user_packages/Python313/site-packages/sqlalchemy/engine/_py_processors.py +136 -0
  42. python/user_packages/Python313/site-packages/sqlalchemy/engine/_py_row.py +128 -0
  43. python/user_packages/Python313/site-packages/sqlalchemy/engine/_py_util.py +74 -0
  44. python/user_packages/Python313/site-packages/sqlalchemy/engine/base.py +0 -0
  45. python/user_packages/Python313/site-packages/sqlalchemy/engine/characteristics.py +155 -0
  46. python/user_packages/Python313/site-packages/sqlalchemy/engine/create.py +899 -0
  47. python/user_packages/Python313/site-packages/sqlalchemy/engine/cursor.py +2303 -0
  48. python/user_packages/Python313/site-packages/sqlalchemy/engine/default.py +2394 -0
  49. python/user_packages/Python313/site-packages/sqlalchemy/engine/events.py +965 -0
  50. python/user_packages/Python313/site-packages/sqlalchemy/engine/interfaces.py +0 -0
python/user_packages/Python313/site-packages/__pycache__/brotli.cpython-313.pyc ADDED
Binary file (1.95 kB). View file
 
python/user_packages/Python313/site-packages/__pycache__/jsonpatch.cpython-313.pyc ADDED
Binary file (35.4 kB). View file
 
python/user_packages/Python313/site-packages/__pycache__/jsonpointer.cpython-313.pyc ADDED
Binary file (13.1 kB). View file
 
python/user_packages/Python313/site-packages/__pycache__/kaitaistruct.cpython-313.pyc ADDED
Binary file (44.7 kB). View file
 
python/user_packages/Python313/site-packages/__pycache__/mypy_extensions.cpython-313.pyc ADDED
Binary file (10.6 kB). View file
 
python/user_packages/Python313/site-packages/__pycache__/six.cpython-313.pyc ADDED
Binary file (42.1 kB). View file
 
python/user_packages/Python313/site-packages/__pycache__/socks.cpython-313.pyc ADDED
Binary file (34.5 kB). View file
 
python/user_packages/Python313/site-packages/__pycache__/sockshandler.cpython-313.pyc ADDED
Binary file (6.93 kB). View file
 
python/user_packages/Python313/site-packages/__pycache__/typing_inspect.cpython-313.pyc ADDED
Binary file (33.4 kB). View file
 
python/user_packages/Python313/site-packages/_argon2_cffi_bindings/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ from ._ffi import ffi, lib
4
+
5
+
6
+ __all__ = ["ffi", "lib"]
python/user_packages/Python313/site-packages/_argon2_cffi_bindings/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (286 Bytes). View file
 
python/user_packages/Python313/site-packages/_argon2_cffi_bindings/__pycache__/_ffi_build.cpython-313.pyc ADDED
Binary file (6.94 kB). View file
 
python/user_packages/Python313/site-packages/_argon2_cffi_bindings/_ffi.pyd ADDED
Binary file (60.9 kB). View file
 
python/user_packages/Python313/site-packages/_argon2_cffi_bindings/_ffi_build.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+
3
+ import os
4
+ import platform
5
+ import sysconfig
6
+
7
+ from pathlib import Path
8
+
9
+ from cffi import FFI
10
+
11
+
12
+ use_system_argon2 = os.environ.get("ARGON2_CFFI_USE_SYSTEM", "0") == "1"
13
+ use_sse2 = os.environ.get("ARGON2_CFFI_USE_SSE2", None)
14
+ windows = platform.system() == "Windows"
15
+ # Free-threaded CPython doesn't support limited API.
16
+ limited_api = not sysconfig.get_config_var("Py_GIL_DISABLED")
17
+
18
+
19
+ # Try to detect cross-compilation.
20
+ def _get_target_platform(arch_flags, default):
21
+ flags = [f for f in arch_flags.split(" ") if f.strip() != ""]
22
+ try:
23
+ pos = flags.index("-arch")
24
+
25
+ return flags[pos + 1].lower()
26
+ except ValueError:
27
+ pass
28
+
29
+ return default
30
+
31
+
32
+ target_platform = _get_target_platform(
33
+ os.environ.get("ARCHFLAGS", ""), platform.machine()
34
+ )
35
+
36
+
37
+ if use_sse2 == "1":
38
+ optimized = True
39
+ elif use_sse2 == "0":
40
+ optimized = False
41
+ else:
42
+ # Optimized version requires SSE2 extensions. They have been around since
43
+ # 2001 so we try to compile it on every recent-ish x86.
44
+ optimized = target_platform in ("i686", "x86", "x86_64", "AMD64")
45
+
46
+
47
+ ffi = FFI()
48
+
49
+ if use_system_argon2:
50
+ ffi.set_source(
51
+ "_ffi",
52
+ "#include <argon2.h>",
53
+ libraries=["argon2"],
54
+ py_limited_api=limited_api,
55
+ )
56
+ else:
57
+ lib_base = Path("extras") / "libargon2" / "src"
58
+ ffi.set_source(
59
+ "_ffi",
60
+ "#include <argon2.h>",
61
+ extra_compile_args=["-msse2"] if (optimized and not windows) else None,
62
+ include_dirs=[str(Path("extras", "libargon2", "include"))],
63
+ py_limited_api=limited_api,
64
+ sources=[
65
+ str(lib_base / path)
66
+ for path in [
67
+ "argon2.c",
68
+ Path("blake2") / "blake2b.c",
69
+ "core.c",
70
+ "encoding.c",
71
+ "opt.c" if optimized else "ref.c",
72
+ "thread.c",
73
+ ]
74
+ ],
75
+ )
76
+
77
+
78
+ ffi.cdef(
79
+ """\
80
+ typedef enum Argon2_type {
81
+ Argon2_d = ...,
82
+ Argon2_i = ...,
83
+ Argon2_id = ...,
84
+ } argon2_type;
85
+ typedef enum Argon2_version {
86
+ ARGON2_VERSION_10 = ...,
87
+ ARGON2_VERSION_13 = ...,
88
+ ARGON2_VERSION_NUMBER = ...
89
+ } argon2_version;
90
+
91
+ int argon2_hash(const uint32_t t_cost, const uint32_t m_cost,
92
+ const uint32_t parallelism, const void *pwd,
93
+ const size_t pwdlen, const void *salt,
94
+ const size_t saltlen, void *hash,
95
+ const size_t hashlen, char *encoded,
96
+ const size_t encodedlen, argon2_type type,
97
+ const uint32_t version);
98
+
99
+ int argon2_verify(const char *encoded, const void *pwd,
100
+ const size_t pwdlen, argon2_type type);
101
+
102
+ const char *argon2_error_message(int error_code);
103
+
104
+
105
+ typedef int (*allocate_fptr)(uint8_t **memory, size_t bytes_to_allocate);
106
+ typedef void (*deallocate_fptr)(uint8_t *memory, size_t bytes_to_allocate);
107
+
108
+ typedef struct Argon2_Context {
109
+ uint8_t *out; /* output array */
110
+ uint32_t outlen; /* digest length */
111
+
112
+ uint8_t *pwd; /* password array */
113
+ uint32_t pwdlen; /* password length */
114
+
115
+ uint8_t *salt; /* salt array */
116
+ uint32_t saltlen; /* salt length */
117
+
118
+ uint8_t *secret; /* key array */
119
+ uint32_t secretlen; /* key length */
120
+
121
+ uint8_t *ad; /* associated data array */
122
+ uint32_t adlen; /* associated data length */
123
+
124
+ uint32_t t_cost; /* number of passes */
125
+ uint32_t m_cost; /* amount of memory requested (KB) */
126
+ uint32_t lanes; /* number of lanes */
127
+ uint32_t threads; /* maximum number of threads */
128
+
129
+ uint32_t version; /* version number */
130
+
131
+ allocate_fptr allocate_cbk; /* pointer to memory allocator */
132
+ deallocate_fptr free_cbk; /* pointer to memory deallocator */
133
+
134
+ uint32_t flags; /* array of bool options */
135
+ } argon2_context;
136
+
137
+ int argon2_ctx(argon2_context *context, argon2_type type);
138
+
139
+ /* Error codes */
140
+ typedef enum Argon2_ErrorCodes {
141
+ ARGON2_OK = ...,
142
+
143
+ ARGON2_OUTPUT_PTR_NULL = ...,
144
+
145
+ ARGON2_OUTPUT_TOO_SHORT = ...,
146
+ ARGON2_OUTPUT_TOO_LONG = ...,
147
+
148
+ ARGON2_PWD_TOO_SHORT = ...,
149
+ ARGON2_PWD_TOO_LONG = ...,
150
+
151
+ ARGON2_SALT_TOO_SHORT = ...,
152
+ ARGON2_SALT_TOO_LONG = ...,
153
+
154
+ ARGON2_AD_TOO_SHORT = ...,
155
+ ARGON2_AD_TOO_LONG = ...,
156
+
157
+ ARGON2_SECRET_TOO_SHORT = ...,
158
+ ARGON2_SECRET_TOO_LONG = ...,
159
+
160
+ ARGON2_TIME_TOO_SMALL = ...,
161
+ ARGON2_TIME_TOO_LARGE = ...,
162
+
163
+ ARGON2_MEMORY_TOO_LITTLE = ...,
164
+ ARGON2_MEMORY_TOO_MUCH = ...,
165
+
166
+ ARGON2_LANES_TOO_FEW = ...,
167
+ ARGON2_LANES_TOO_MANY = ...,
168
+
169
+ ARGON2_PWD_PTR_MISMATCH = ..., /* NULL ptr with non-zero length */
170
+ ARGON2_SALT_PTR_MISMATCH = ..., /* NULL ptr with non-zero length */
171
+ ARGON2_SECRET_PTR_MISMATCH = ..., /* NULL ptr with non-zero length */
172
+ ARGON2_AD_PTR_MISMATCH = ..., /* NULL ptr with non-zero length */
173
+
174
+ ARGON2_MEMORY_ALLOCATION_ERROR = ...,
175
+
176
+ ARGON2_FREE_MEMORY_CBK_NULL = ...,
177
+ ARGON2_ALLOCATE_MEMORY_CBK_NULL = ...,
178
+
179
+ ARGON2_INCORRECT_PARAMETER = ...,
180
+ ARGON2_INCORRECT_TYPE = ...,
181
+
182
+ ARGON2_OUT_PTR_MISMATCH = ...,
183
+
184
+ ARGON2_THREADS_TOO_FEW = ...,
185
+ ARGON2_THREADS_TOO_MANY = ...,
186
+
187
+ ARGON2_MISSING_ARGS = ...,
188
+
189
+ ARGON2_ENCODING_FAIL = ...,
190
+
191
+ ARGON2_DECODING_FAIL = ...,
192
+
193
+ ARGON2_THREAD_FAIL = ...,
194
+
195
+ ARGON2_DECODING_LENGTH_FAIL= ...,
196
+
197
+ ARGON2_VERIFY_MISMATCH = ...,
198
+ } argon2_error_codes;
199
+
200
+ #define ARGON2_FLAG_CLEAR_PASSWORD ...
201
+ #define ARGON2_FLAG_CLEAR_SECRET ...
202
+ #define ARGON2_DEFAULT_FLAGS ...
203
+
204
+ #define ARGON2_MIN_LANES ...
205
+ #define ARGON2_MAX_LANES ...
206
+ #define ARGON2_MIN_THREADS ...
207
+ #define ARGON2_MAX_THREADS ...
208
+ #define ARGON2_SYNC_POINTS ...
209
+ #define ARGON2_MIN_OUTLEN ...
210
+ #define ARGON2_MAX_OUTLEN ...
211
+ #define ARGON2_MIN_MEMORY ...
212
+ #define ARGON2_MAX_MEMORY_BITS ...
213
+ #define ARGON2_MAX_MEMORY ...
214
+ #define ARGON2_MIN_TIME ...
215
+ #define ARGON2_MAX_TIME ...
216
+ #define ARGON2_MIN_PWD_LENGTH ...
217
+ #define ARGON2_MAX_PWD_LENGTH ...
218
+ #define ARGON2_MIN_AD_LENGTH ...
219
+ #define ARGON2_MAX_AD_LENGTH ...
220
+ #define ARGON2_MIN_SALT_LENGTH ...
221
+ #define ARGON2_MAX_SALT_LENGTH ...
222
+ #define ARGON2_MIN_SECRET ...
223
+ #define ARGON2_MAX_SECRET ...
224
+
225
+ uint32_t argon2_encodedlen(uint32_t t_cost, uint32_t m_cost,
226
+ uint32_t parallelism, uint32_t saltlen,
227
+ uint32_t hashlen, argon2_type type);
228
+
229
+ """
230
+ )
231
+
232
+ if __name__ == "__main__":
233
+ ffi.compile()
python/user_packages/Python313/site-packages/_distutils_hack/__init__.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # don't import any costly modules
2
+ import os
3
+ import sys
4
+
5
+ report_url = (
6
+ "https://github.com/pypa/setuptools/issues/new?template=distutils-deprecation.yml"
7
+ )
8
+
9
+
10
+ def warn_distutils_present():
11
+ if 'distutils' not in sys.modules:
12
+ return
13
+ import warnings
14
+
15
+ warnings.warn(
16
+ "Distutils was imported before Setuptools, but importing Setuptools "
17
+ "also replaces the `distutils` module in `sys.modules`. This may lead "
18
+ "to undesirable behaviors or errors. To avoid these issues, avoid "
19
+ "using distutils directly, ensure that setuptools is installed in the "
20
+ "traditional way (e.g. not an editable install), and/or make sure "
21
+ "that setuptools is always imported before distutils."
22
+ )
23
+
24
+
25
+ def clear_distutils():
26
+ if 'distutils' not in sys.modules:
27
+ return
28
+ import warnings
29
+
30
+ warnings.warn(
31
+ "Setuptools is replacing distutils. Support for replacing "
32
+ "an already imported distutils is deprecated. In the future, "
33
+ "this condition will fail. "
34
+ f"Register concerns at {report_url}"
35
+ )
36
+ mods = [
37
+ name
38
+ for name in sys.modules
39
+ if name == "distutils" or name.startswith("distutils.")
40
+ ]
41
+ for name in mods:
42
+ del sys.modules[name]
43
+
44
+
45
+ def enabled():
46
+ """
47
+ Allow selection of distutils by environment variable.
48
+ """
49
+ which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local')
50
+ if which == 'stdlib':
51
+ import warnings
52
+
53
+ warnings.warn(
54
+ "Reliance on distutils from stdlib is deprecated. Users "
55
+ "must rely on setuptools to provide the distutils module. "
56
+ "Avoid importing distutils or import setuptools first, "
57
+ "and avoid setting SETUPTOOLS_USE_DISTUTILS=stdlib. "
58
+ f"Register concerns at {report_url}"
59
+ )
60
+ return which == 'local'
61
+
62
+
63
+ def ensure_local_distutils():
64
+ import importlib
65
+
66
+ clear_distutils()
67
+
68
+ # With the DistutilsMetaFinder in place,
69
+ # perform an import to cause distutils to be
70
+ # loaded from setuptools._distutils. Ref #2906.
71
+ with shim():
72
+ importlib.import_module('distutils')
73
+
74
+ # check that submodules load as expected
75
+ core = importlib.import_module('distutils.core')
76
+ assert '_distutils' in core.__file__, core.__file__
77
+ assert 'setuptools._distutils.log' not in sys.modules
78
+
79
+
80
+ def do_override():
81
+ """
82
+ Ensure that the local copy of distutils is preferred over stdlib.
83
+
84
+ See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
85
+ for more motivation.
86
+ """
87
+ if enabled():
88
+ warn_distutils_present()
89
+ ensure_local_distutils()
90
+
91
+
92
+ class _TrivialRe:
93
+ def __init__(self, *patterns) -> None:
94
+ self._patterns = patterns
95
+
96
+ def match(self, string):
97
+ return all(pat in string for pat in self._patterns)
98
+
99
+
100
+ class DistutilsMetaFinder:
101
+ def find_spec(self, fullname, path, target=None):
102
+ # optimization: only consider top level modules and those
103
+ # found in the CPython test suite.
104
+ if path is not None and not fullname.startswith('test.'):
105
+ return None
106
+
107
+ method_name = 'spec_for_{fullname}'.format(**locals())
108
+ method = getattr(self, method_name, lambda: None)
109
+ return method()
110
+
111
+ def spec_for_distutils(self):
112
+ if self.is_cpython():
113
+ return None
114
+
115
+ import importlib
116
+ import importlib.abc
117
+ import importlib.util
118
+
119
+ try:
120
+ mod = importlib.import_module('setuptools._distutils')
121
+ except Exception:
122
+ # There are a couple of cases where setuptools._distutils
123
+ # may not be present:
124
+ # - An older Setuptools without a local distutils is
125
+ # taking precedence. Ref #2957.
126
+ # - Path manipulation during sitecustomize removes
127
+ # setuptools from the path but only after the hook
128
+ # has been loaded. Ref #2980.
129
+ # In either case, fall back to stdlib behavior.
130
+ return None
131
+
132
+ class DistutilsLoader(importlib.abc.Loader):
133
+ def create_module(self, spec):
134
+ mod.__name__ = 'distutils'
135
+ return mod
136
+
137
+ def exec_module(self, module):
138
+ pass
139
+
140
+ return importlib.util.spec_from_loader(
141
+ 'distutils', DistutilsLoader(), origin=mod.__file__
142
+ )
143
+
144
+ @staticmethod
145
+ def is_cpython():
146
+ """
147
+ Suppress supplying distutils for CPython (build and tests).
148
+ Ref #2965 and #3007.
149
+ """
150
+ return os.path.isfile('pybuilddir.txt')
151
+
152
+ def spec_for_pip(self):
153
+ """
154
+ Ensure stdlib distutils when running under pip.
155
+ See pypa/pip#8761 for rationale.
156
+ """
157
+ if sys.version_info >= (3, 12) or self.pip_imported_during_build():
158
+ return
159
+ clear_distutils()
160
+ self.spec_for_distutils = lambda: None
161
+
162
+ @classmethod
163
+ def pip_imported_during_build(cls):
164
+ """
165
+ Detect if pip is being imported in a build script. Ref #2355.
166
+ """
167
+ import traceback
168
+
169
+ return any(
170
+ cls.frame_file_is_setup(frame) for frame, line in traceback.walk_stack(None)
171
+ )
172
+
173
+ @staticmethod
174
+ def frame_file_is_setup(frame):
175
+ """
176
+ Return True if the indicated frame suggests a setup.py file.
177
+ """
178
+ # some frames may not have __file__ (#2940)
179
+ return frame.f_globals.get('__file__', '').endswith('setup.py')
180
+
181
+ def spec_for_sensitive_tests(self):
182
+ """
183
+ Ensure stdlib distutils when running select tests under CPython.
184
+
185
+ python/cpython#91169
186
+ """
187
+ clear_distutils()
188
+ self.spec_for_distutils = lambda: None
189
+
190
+ sensitive_tests = (
191
+ [
192
+ 'test.test_distutils',
193
+ 'test.test_peg_generator',
194
+ 'test.test_importlib',
195
+ ]
196
+ if sys.version_info < (3, 10)
197
+ else [
198
+ 'test.test_distutils',
199
+ ]
200
+ )
201
+
202
+
203
+ for name in DistutilsMetaFinder.sensitive_tests:
204
+ setattr(
205
+ DistutilsMetaFinder,
206
+ f'spec_for_{name}',
207
+ DistutilsMetaFinder.spec_for_sensitive_tests,
208
+ )
209
+
210
+
211
+ DISTUTILS_FINDER = DistutilsMetaFinder()
212
+
213
+
214
+ def add_shim():
215
+ DISTUTILS_FINDER in sys.meta_path or insert_shim()
216
+
217
+
218
+ class shim:
219
+ def __enter__(self) -> None:
220
+ insert_shim()
221
+
222
+ def __exit__(self, exc: object, value: object, tb: object) -> None:
223
+ _remove_shim()
224
+
225
+
226
+ def insert_shim():
227
+ sys.meta_path.insert(0, DISTUTILS_FINDER)
228
+
229
+
230
+ def _remove_shim():
231
+ try:
232
+ sys.meta_path.remove(DISTUTILS_FINDER)
233
+ except ValueError:
234
+ pass
235
+
236
+
237
+ if sys.version_info < (3, 12):
238
+ # DistutilsMetaFinder can only be disabled in Python < 3.12 (PEP 632)
239
+ remove_shim = _remove_shim
python/user_packages/Python313/site-packages/_distutils_hack/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (10.8 kB). View file
 
python/user_packages/Python313/site-packages/_distutils_hack/__pycache__/override.cpython-313.pyc ADDED
Binary file (292 Bytes). View file
 
python/user_packages/Python313/site-packages/_distutils_hack/override.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __import__('_distutils_hack').do_override()
python/user_packages/Python313/site-packages/_yaml/__init__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This is a stub package designed to roughly emulate the _yaml
2
+ # extension module, which previously existed as a standalone module
3
+ # and has been moved into the `yaml` package namespace.
4
+ # It does not perfectly mimic its old counterpart, but should get
5
+ # close enough for anyone who's relying on it even when they shouldn't.
6
+ import yaml
7
+
8
+ # in some circumstances, the yaml module we imoprted may be from a different version, so we need
9
+ # to tread carefully when poking at it here (it may not have the attributes we expect)
10
+ if not getattr(yaml, '__with_libyaml__', False):
11
+ from sys import version_info
12
+
13
+ exc = ModuleNotFoundError if version_info >= (3, 6) else ImportError
14
+ raise exc("No module named '_yaml'")
15
+ else:
16
+ from yaml._yaml import *
17
+ import warnings
18
+ warnings.warn(
19
+ 'The _yaml extension module is now located at yaml._yaml'
20
+ ' and its location is subject to change. To use the'
21
+ ' LibYAML-based parser and emitter, import from `yaml`:'
22
+ ' `from yaml import CLoader as Loader, CDumper as Dumper`.',
23
+ DeprecationWarning
24
+ )
25
+ del warnings
26
+ # Don't `del yaml` here because yaml is actually an existing
27
+ # namespace member of _yaml.
28
+
29
+ __name__ = '_yaml'
30
+ # If the module is top-level (i.e. not a part of any specific package)
31
+ # then the attribute should be set to ''.
32
+ # https://docs.python.org/3.8/library/types.html
33
+ __package__ = ''
python/user_packages/Python313/site-packages/_yaml/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (876 Bytes). View file
 
python/user_packages/Python313/site-packages/sqlalchemy-2.0.49.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2005-2026 SQLAlchemy authors and contributors <see AUTHORS file>.
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ this software and associated documentation files (the "Software"), to deal in
5
+ the Software without restriction, including without limitation the rights to
6
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7
+ of the Software, and to permit persons to whom the Software is furnished to do
8
+ so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
python/user_packages/Python313/site-packages/sqlalchemy/connectors/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # connectors/__init__.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+
9
+ from ..engine.interfaces import Dialect
10
+
11
+
12
+ class Connector(Dialect):
13
+ """Base class for dialect mixins, for DBAPIs that work
14
+ across entirely different database backends.
15
+
16
+ Currently the only such mixin is pyodbc.
17
+
18
+ """
python/user_packages/Python313/site-packages/sqlalchemy/connectors/aioodbc.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # connectors/aioodbc.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: ignore-errors
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import TYPE_CHECKING
12
+
13
+ from .asyncio import AsyncAdapt_dbapi_connection
14
+ from .asyncio import AsyncAdapt_dbapi_cursor
15
+ from .asyncio import AsyncAdapt_dbapi_ss_cursor
16
+ from .asyncio import AsyncAdaptFallback_dbapi_connection
17
+ from .pyodbc import PyODBCConnector
18
+ from .. import pool
19
+ from .. import util
20
+ from ..util.concurrency import await_fallback
21
+ from ..util.concurrency import await_only
22
+
23
+
24
+ if TYPE_CHECKING:
25
+ from ..engine.interfaces import ConnectArgsType
26
+ from ..engine.url import URL
27
+
28
+
29
+ class AsyncAdapt_aioodbc_cursor(AsyncAdapt_dbapi_cursor):
30
+ __slots__ = ()
31
+
32
+ def setinputsizes(self, *inputsizes):
33
+ # see https://github.com/aio-libs/aioodbc/issues/451
34
+ return self._cursor._impl.setinputsizes(*inputsizes)
35
+
36
+ # how it's supposed to work
37
+ # return self.await_(self._cursor.setinputsizes(*inputsizes))
38
+
39
+ @property
40
+ def fast_executemany(self):
41
+ return self._cursor._impl.fast_executemany
42
+
43
+ @fast_executemany.setter
44
+ def fast_executemany(self, value):
45
+ self._cursor._impl.fast_executemany = value
46
+
47
+
48
+ class AsyncAdapt_aioodbc_ss_cursor(
49
+ AsyncAdapt_aioodbc_cursor, AsyncAdapt_dbapi_ss_cursor
50
+ ):
51
+ __slots__ = ()
52
+
53
+
54
+ class AsyncAdapt_aioodbc_connection(AsyncAdapt_dbapi_connection):
55
+ _cursor_cls = AsyncAdapt_aioodbc_cursor
56
+ _ss_cursor_cls = AsyncAdapt_aioodbc_ss_cursor
57
+ __slots__ = ()
58
+
59
+ @property
60
+ def autocommit(self):
61
+ return self._connection.autocommit
62
+
63
+ @autocommit.setter
64
+ def autocommit(self, value):
65
+ # https://github.com/aio-libs/aioodbc/issues/448
66
+ # self._connection.autocommit = value
67
+
68
+ self._connection._conn.autocommit = value
69
+
70
+ def ping(self, reconnect):
71
+ return self.await_(self._connection.ping(reconnect))
72
+
73
+ def add_output_converter(self, *arg, **kw):
74
+ self._connection.add_output_converter(*arg, **kw)
75
+
76
+ def character_set_name(self):
77
+ return self._connection.character_set_name()
78
+
79
+ def cursor(self, server_side=False):
80
+ # aioodbc sets connection=None when closed and just fails with
81
+ # AttributeError here. Here we use the same ProgrammingError +
82
+ # message that pyodbc uses, so it triggers is_disconnect() as well.
83
+ if self._connection.closed:
84
+ raise self.dbapi.ProgrammingError(
85
+ "Attempt to use a closed connection."
86
+ )
87
+ return super().cursor(server_side=server_side)
88
+
89
+ def rollback(self):
90
+ # aioodbc sets connection=None when closed and just fails with
91
+ # AttributeError here. should be a no-op
92
+ if not self._connection.closed:
93
+ super().rollback()
94
+
95
+ def commit(self):
96
+ # aioodbc sets connection=None when closed and just fails with
97
+ # AttributeError here. should be a no-op
98
+ if not self._connection.closed:
99
+ super().commit()
100
+
101
+ def close(self):
102
+ # aioodbc sets connection=None when closed and just fails with
103
+ # AttributeError here. should be a no-op
104
+ if not self._connection.closed:
105
+ super().close()
106
+
107
+
108
+ class AsyncAdaptFallback_aioodbc_connection(
109
+ AsyncAdaptFallback_dbapi_connection, AsyncAdapt_aioodbc_connection
110
+ ):
111
+ __slots__ = ()
112
+
113
+
114
+ class AsyncAdapt_aioodbc_dbapi:
115
+ def __init__(self, aioodbc, pyodbc):
116
+ self.aioodbc = aioodbc
117
+ self.pyodbc = pyodbc
118
+ self.paramstyle = pyodbc.paramstyle
119
+ self._init_dbapi_attributes()
120
+ self.Cursor = AsyncAdapt_dbapi_cursor
121
+ self.version = pyodbc.version
122
+
123
+ def _init_dbapi_attributes(self):
124
+ for name in (
125
+ "Warning",
126
+ "Error",
127
+ "InterfaceError",
128
+ "DataError",
129
+ "DatabaseError",
130
+ "OperationalError",
131
+ "InterfaceError",
132
+ "IntegrityError",
133
+ "ProgrammingError",
134
+ "InternalError",
135
+ "NotSupportedError",
136
+ "SQL_DRIVER_NAME",
137
+ "NUMBER",
138
+ "STRING",
139
+ "DATETIME",
140
+ "BINARY",
141
+ "Binary",
142
+ "BinaryNull",
143
+ "SQL_VARCHAR",
144
+ "SQL_WVARCHAR",
145
+ "SQL_DECIMAL",
146
+ ):
147
+ setattr(self, name, getattr(self.pyodbc, name))
148
+
149
+ def connect(self, *arg, **kw):
150
+ async_fallback = kw.pop("async_fallback", False)
151
+ creator_fn = kw.pop("async_creator_fn", self.aioodbc.connect)
152
+
153
+ if util.asbool(async_fallback):
154
+ return AsyncAdaptFallback_aioodbc_connection(
155
+ self,
156
+ await_fallback(creator_fn(*arg, **kw)),
157
+ )
158
+ else:
159
+ return AsyncAdapt_aioodbc_connection(
160
+ self,
161
+ await_only(creator_fn(*arg, **kw)),
162
+ )
163
+
164
+
165
+ class aiodbcConnector(PyODBCConnector):
166
+ is_async = True
167
+ supports_statement_cache = True
168
+
169
+ supports_server_side_cursors = True
170
+
171
+ @classmethod
172
+ def import_dbapi(cls):
173
+ return AsyncAdapt_aioodbc_dbapi(
174
+ __import__("aioodbc"), __import__("pyodbc")
175
+ )
176
+
177
+ def create_connect_args(self, url: URL) -> ConnectArgsType:
178
+ arg, kw = super().create_connect_args(url)
179
+ if arg and arg[0]:
180
+ kw["dsn"] = arg[0]
181
+
182
+ return (), kw
183
+
184
+ @classmethod
185
+ def get_pool_class(cls, url):
186
+ async_fallback = url.query.get("async_fallback", False)
187
+
188
+ if util.asbool(async_fallback):
189
+ return pool.FallbackAsyncAdaptedQueuePool
190
+ else:
191
+ return pool.AsyncAdaptedQueuePool
192
+
193
+ def get_driver_connection(self, connection):
194
+ return connection._connection
python/user_packages/Python313/site-packages/sqlalchemy/connectors/asyncio.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # connectors/asyncio.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ """generic asyncio-adapted versions of DBAPI connection and cursor"""
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import collections
14
+ import sys
15
+ from typing import Any
16
+ from typing import AsyncIterator
17
+ from typing import Deque
18
+ from typing import Iterator
19
+ from typing import NoReturn
20
+ from typing import Optional
21
+ from typing import Sequence
22
+ from typing import Tuple
23
+ from typing import Type
24
+ from typing import TYPE_CHECKING
25
+
26
+ from ..engine import AdaptedConnection
27
+ from ..util import EMPTY_DICT
28
+ from ..util.concurrency import await_fallback
29
+ from ..util.concurrency import await_only
30
+ from ..util.concurrency import in_greenlet
31
+ from ..util.typing import Protocol
32
+
33
+ if TYPE_CHECKING:
34
+ from ..engine.interfaces import _DBAPICursorDescription
35
+ from ..engine.interfaces import _DBAPIMultiExecuteParams
36
+ from ..engine.interfaces import _DBAPISingleExecuteParams
37
+ from ..engine.interfaces import DBAPIModule
38
+ from ..util.typing import Self
39
+
40
+
41
+ class AsyncIODBAPIConnection(Protocol):
42
+ """protocol representing an async adapted version of a
43
+ :pep:`249` database connection.
44
+
45
+
46
+ """
47
+
48
+ # note that async DBAPIs dont agree if close() should be awaitable,
49
+ # so it is omitted here and picked up by the __getattr__ hook below
50
+
51
+ async def commit(self) -> None: ...
52
+
53
+ def cursor(self, *args: Any, **kwargs: Any) -> AsyncIODBAPICursor: ...
54
+
55
+ async def rollback(self) -> None: ...
56
+
57
+ def __getattr__(self, key: str) -> Any: ...
58
+
59
+ def __setattr__(self, key: str, value: Any) -> None: ...
60
+
61
+
62
+ class AsyncIODBAPICursor(Protocol):
63
+ """protocol representing an async adapted version
64
+ of a :pep:`249` database cursor.
65
+
66
+
67
+ """
68
+
69
+ def __aenter__(self) -> Any: ...
70
+
71
+ @property
72
+ def description(
73
+ self,
74
+ ) -> _DBAPICursorDescription:
75
+ """The description attribute of the Cursor."""
76
+ ...
77
+
78
+ @property
79
+ def rowcount(self) -> int: ...
80
+
81
+ arraysize: int
82
+
83
+ lastrowid: int
84
+
85
+ async def close(self) -> None: ...
86
+
87
+ async def execute(
88
+ self,
89
+ operation: Any,
90
+ parameters: Optional[_DBAPISingleExecuteParams] = None,
91
+ ) -> Any: ...
92
+
93
+ async def executemany(
94
+ self,
95
+ operation: Any,
96
+ parameters: _DBAPIMultiExecuteParams,
97
+ ) -> Any: ...
98
+
99
+ async def fetchone(self) -> Optional[Any]: ...
100
+
101
+ async def fetchmany(self, size: Optional[int] = ...) -> Sequence[Any]: ...
102
+
103
+ async def fetchall(self) -> Sequence[Any]: ...
104
+
105
+ async def setinputsizes(self, sizes: Sequence[Any]) -> None: ...
106
+
107
+ def setoutputsize(self, size: Any, column: Any) -> None: ...
108
+
109
+ async def callproc(
110
+ self, procname: str, parameters: Sequence[Any] = ...
111
+ ) -> Any: ...
112
+
113
+ async def nextset(self) -> Optional[bool]: ...
114
+
115
+ def __aiter__(self) -> AsyncIterator[Any]: ...
116
+
117
+
118
+ class AsyncAdapt_dbapi_module:
119
+ if TYPE_CHECKING:
120
+ Error = DBAPIModule.Error
121
+ OperationalError = DBAPIModule.OperationalError
122
+ InterfaceError = DBAPIModule.InterfaceError
123
+ IntegrityError = DBAPIModule.IntegrityError
124
+
125
+ def __getattr__(self, key: str) -> Any: ...
126
+
127
+
128
+ class AsyncAdapt_dbapi_cursor:
129
+ server_side = False
130
+ __slots__ = (
131
+ "_adapt_connection",
132
+ "_connection",
133
+ "await_",
134
+ "_cursor",
135
+ "_rows",
136
+ "_soft_closed_memoized",
137
+ )
138
+
139
+ _awaitable_cursor_close: bool = True
140
+
141
+ _cursor: AsyncIODBAPICursor
142
+ _adapt_connection: AsyncAdapt_dbapi_connection
143
+ _connection: AsyncIODBAPIConnection
144
+ _rows: Deque[Any]
145
+
146
+ def __init__(self, adapt_connection: AsyncAdapt_dbapi_connection):
147
+ self._adapt_connection = adapt_connection
148
+ self._connection = adapt_connection._connection
149
+
150
+ self.await_ = adapt_connection.await_
151
+
152
+ cursor = self._make_new_cursor(self._connection)
153
+ self._cursor = self._aenter_cursor(cursor)
154
+ self._soft_closed_memoized = EMPTY_DICT
155
+ if not self.server_side:
156
+ self._rows = collections.deque()
157
+
158
+ def _aenter_cursor(self, cursor: AsyncIODBAPICursor) -> AsyncIODBAPICursor:
159
+ return self.await_(cursor.__aenter__()) # type: ignore[no-any-return]
160
+
161
+ def _make_new_cursor(
162
+ self, connection: AsyncIODBAPIConnection
163
+ ) -> AsyncIODBAPICursor:
164
+ return connection.cursor()
165
+
166
+ @property
167
+ def description(self) -> Optional[_DBAPICursorDescription]:
168
+ if "description" in self._soft_closed_memoized:
169
+ return self._soft_closed_memoized["description"] # type: ignore[no-any-return] # noqa: E501
170
+ return self._cursor.description
171
+
172
+ @property
173
+ def rowcount(self) -> int:
174
+ return self._cursor.rowcount
175
+
176
+ @property
177
+ def arraysize(self) -> int:
178
+ return self._cursor.arraysize
179
+
180
+ @arraysize.setter
181
+ def arraysize(self, value: int) -> None:
182
+ self._cursor.arraysize = value
183
+
184
+ @property
185
+ def lastrowid(self) -> int:
186
+ return self._cursor.lastrowid
187
+
188
+ async def _async_soft_close(self) -> None:
189
+ """close the cursor but keep the results pending, and memoize the
190
+ description.
191
+
192
+ .. versionadded:: 2.0.44
193
+
194
+ """
195
+
196
+ if not self._awaitable_cursor_close or self.server_side:
197
+ return
198
+
199
+ self._soft_closed_memoized = self._soft_closed_memoized.union(
200
+ {
201
+ "description": self._cursor.description,
202
+ }
203
+ )
204
+ await self._cursor.close()
205
+
206
+ def close(self) -> None:
207
+ self._rows.clear()
208
+
209
+ # updated as of 2.0.44
210
+ # try to "close" the cursor based on what we know about the driver
211
+ # and if we are able to. otherwise, hope that the asyncio
212
+ # extension called _async_soft_close() if the cursor is going into
213
+ # a sync context
214
+ if self._cursor is None or bool(self._soft_closed_memoized):
215
+ return
216
+
217
+ if not self._awaitable_cursor_close:
218
+ self._cursor.close() # type: ignore[unused-coroutine]
219
+ elif in_greenlet():
220
+ self.await_(self._cursor.close())
221
+
222
+ def execute(
223
+ self,
224
+ operation: Any,
225
+ parameters: Optional[_DBAPISingleExecuteParams] = None,
226
+ ) -> Any:
227
+ try:
228
+ return self.await_(self._execute_async(operation, parameters))
229
+ except Exception as error:
230
+ self._adapt_connection._handle_exception(error)
231
+
232
+ def executemany(
233
+ self,
234
+ operation: Any,
235
+ seq_of_parameters: _DBAPIMultiExecuteParams,
236
+ ) -> Any:
237
+ try:
238
+ return self.await_(
239
+ self._executemany_async(operation, seq_of_parameters)
240
+ )
241
+ except Exception as error:
242
+ self._adapt_connection._handle_exception(error)
243
+
244
+ async def _execute_async(
245
+ self, operation: Any, parameters: Optional[_DBAPISingleExecuteParams]
246
+ ) -> Any:
247
+ async with self._adapt_connection._execute_mutex:
248
+ if parameters is None:
249
+ result = await self._cursor.execute(operation)
250
+ else:
251
+ result = await self._cursor.execute(operation, parameters)
252
+
253
+ if self._cursor.description and not self.server_side:
254
+ self._rows = collections.deque(await self._cursor.fetchall())
255
+ return result
256
+
257
+ async def _executemany_async(
258
+ self,
259
+ operation: Any,
260
+ seq_of_parameters: _DBAPIMultiExecuteParams,
261
+ ) -> Any:
262
+ async with self._adapt_connection._execute_mutex:
263
+ return await self._cursor.executemany(operation, seq_of_parameters)
264
+
265
+ def nextset(self) -> None:
266
+ self.await_(self._cursor.nextset())
267
+ if self._cursor.description and not self.server_side:
268
+ self._rows = collections.deque(
269
+ self.await_(self._cursor.fetchall())
270
+ )
271
+
272
+ def setinputsizes(self, *inputsizes: Any) -> None:
273
+ # NOTE: this is overridden in aioodbc due to
274
+ # see https://github.com/aio-libs/aioodbc/issues/451
275
+ # right now
276
+
277
+ return self.await_(self._cursor.setinputsizes(*inputsizes))
278
+
279
+ def __enter__(self) -> Self:
280
+ return self
281
+
282
+ def __exit__(self, type_: Any, value: Any, traceback: Any) -> None:
283
+ self.close()
284
+
285
+ def __iter__(self) -> Iterator[Any]:
286
+ while self._rows:
287
+ yield self._rows.popleft()
288
+
289
+ def fetchone(self) -> Optional[Any]:
290
+ if self._rows:
291
+ return self._rows.popleft()
292
+ else:
293
+ return None
294
+
295
+ def fetchmany(self, size: Optional[int] = None) -> Sequence[Any]:
296
+ if size is None:
297
+ size = self.arraysize
298
+ rr = self._rows
299
+ return [rr.popleft() for _ in range(min(size, len(rr)))]
300
+
301
+ def fetchall(self) -> Sequence[Any]:
302
+ retval = list(self._rows)
303
+ self._rows.clear()
304
+ return retval
305
+
306
+
307
+ class AsyncAdapt_dbapi_ss_cursor(AsyncAdapt_dbapi_cursor):
308
+ __slots__ = ()
309
+ server_side = True
310
+
311
+ def close(self) -> None:
312
+ if self._cursor is not None:
313
+ self.await_(self._cursor.close())
314
+ self._cursor = None # type: ignore
315
+
316
+ def fetchone(self) -> Optional[Any]:
317
+ return self.await_(self._cursor.fetchone())
318
+
319
+ def fetchmany(self, size: Optional[int] = None) -> Any:
320
+ return self.await_(self._cursor.fetchmany(size=size))
321
+
322
+ def fetchall(self) -> Sequence[Any]:
323
+ return self.await_(self._cursor.fetchall())
324
+
325
+ def __iter__(self) -> Iterator[Any]:
326
+ iterator = self._cursor.__aiter__()
327
+ while True:
328
+ try:
329
+ yield self.await_(iterator.__anext__())
330
+ except StopAsyncIteration:
331
+ break
332
+
333
+
334
+ class AsyncAdapt_dbapi_connection(AdaptedConnection):
335
+ _cursor_cls = AsyncAdapt_dbapi_cursor
336
+ _ss_cursor_cls = AsyncAdapt_dbapi_ss_cursor
337
+
338
+ await_ = staticmethod(await_only)
339
+
340
+ __slots__ = ("dbapi", "_execute_mutex")
341
+
342
+ _connection: AsyncIODBAPIConnection
343
+
344
+ def __init__(self, dbapi: Any, connection: AsyncIODBAPIConnection):
345
+ self.dbapi = dbapi
346
+ self._connection = connection
347
+ self._execute_mutex = asyncio.Lock()
348
+
349
+ def cursor(self, server_side: bool = False) -> AsyncAdapt_dbapi_cursor:
350
+ if server_side:
351
+ return self._ss_cursor_cls(self)
352
+ else:
353
+ return self._cursor_cls(self)
354
+
355
+ def execute(
356
+ self,
357
+ operation: Any,
358
+ parameters: Optional[_DBAPISingleExecuteParams] = None,
359
+ ) -> Any:
360
+ """lots of DBAPIs seem to provide this, so include it"""
361
+ cursor = self.cursor()
362
+ cursor.execute(operation, parameters)
363
+ return cursor
364
+
365
+ def _handle_exception(self, error: Exception) -> NoReturn:
366
+ exc_info = sys.exc_info()
367
+
368
+ raise error.with_traceback(exc_info[2])
369
+
370
+ def rollback(self) -> None:
371
+ try:
372
+ self.await_(self._connection.rollback())
373
+ except Exception as error:
374
+ self._handle_exception(error)
375
+
376
+ def commit(self) -> None:
377
+ try:
378
+ self.await_(self._connection.commit())
379
+ except Exception as error:
380
+ self._handle_exception(error)
381
+
382
+ def close(self) -> None:
383
+ self.await_(self._connection.close())
384
+
385
+
386
+ class AsyncAdaptFallback_dbapi_connection(AsyncAdapt_dbapi_connection):
387
+ __slots__ = ()
388
+
389
+ await_ = staticmethod(await_fallback)
390
+
391
+
392
+ class AsyncAdapt_terminate:
393
+ """Mixin for a AsyncAdapt_dbapi_connection to add terminate support."""
394
+
395
+ __slots__ = ()
396
+
397
+ def terminate(self) -> None:
398
+ if in_greenlet():
399
+ # in a greenlet; this is the connection was invalidated case.
400
+ try:
401
+ # try to gracefully close; see #10717
402
+ self.await_(asyncio.shield(self._terminate_graceful_close())) # type: ignore[attr-defined] # noqa: E501
403
+ except self._terminate_handled_exceptions() as e:
404
+ # in the case where we are recycling an old connection
405
+ # that may have already been disconnected, close() will
406
+ # fail. In this case, terminate
407
+ # the connection without any further waiting.
408
+ # see issue #8419
409
+ self._terminate_force_close()
410
+ if isinstance(e, asyncio.CancelledError):
411
+ # re-raise CancelledError if we were cancelled
412
+ raise
413
+ else:
414
+ # not in a greenlet; this is the gc cleanup case
415
+ self._terminate_force_close()
416
+
417
+ def _terminate_handled_exceptions(self) -> Tuple[Type[BaseException], ...]:
418
+ """Returns the exceptions that should be handled when
419
+ calling _graceful_close.
420
+ """
421
+ return (asyncio.TimeoutError, asyncio.CancelledError, OSError)
422
+
423
+ async def _terminate_graceful_close(self) -> None:
424
+ """Try to close connection gracefully"""
425
+ raise NotImplementedError
426
+
427
+ def _terminate_force_close(self) -> None:
428
+ """Terminate the connection"""
429
+ raise NotImplementedError
python/user_packages/Python313/site-packages/sqlalchemy/connectors/pyodbc.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # connectors/pyodbc.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import typing
12
+ from typing import Any
13
+ from typing import Dict
14
+ from typing import List
15
+ from typing import Optional
16
+ from typing import Tuple
17
+ from typing import Union
18
+ from urllib.parse import unquote_plus
19
+
20
+ from . import Connector
21
+ from .. import ExecutionContext
22
+ from .. import pool
23
+ from .. import util
24
+ from ..engine import ConnectArgsType
25
+ from ..engine import Connection
26
+ from ..engine import interfaces
27
+ from ..engine import URL
28
+ from ..sql.type_api import TypeEngine
29
+
30
+ if typing.TYPE_CHECKING:
31
+ from ..engine.interfaces import DBAPIModule
32
+ from ..engine.interfaces import IsolationLevel
33
+
34
+
35
+ class PyODBCConnector(Connector):
36
+ driver = "pyodbc"
37
+
38
+ # this is no longer False for pyodbc in general
39
+ supports_sane_rowcount_returning = True
40
+ supports_sane_multi_rowcount = False
41
+
42
+ supports_native_decimal = True
43
+ default_paramstyle = "named"
44
+
45
+ fast_executemany = False
46
+
47
+ # for non-DSN connections, this *may* be used to
48
+ # hold the desired driver name
49
+ pyodbc_driver_name: Optional[str] = None
50
+
51
+ def __init__(self, use_setinputsizes: bool = False, **kw: Any):
52
+ super().__init__(**kw)
53
+ if use_setinputsizes:
54
+ self.bind_typing = interfaces.BindTyping.SETINPUTSIZES
55
+
56
+ @classmethod
57
+ def import_dbapi(cls) -> DBAPIModule:
58
+ return __import__("pyodbc")
59
+
60
+ def create_connect_args(self, url: URL) -> ConnectArgsType:
61
+ opts = url.translate_connect_args(username="user")
62
+ opts.update(url.query)
63
+
64
+ keys = opts
65
+
66
+ query = url.query
67
+
68
+ connect_args: Dict[str, Any] = {}
69
+ connectors: List[str]
70
+
71
+ for param in ("ansi", "unicode_results", "autocommit"):
72
+ if param in keys:
73
+ connect_args[param] = util.asbool(keys.pop(param))
74
+
75
+ if "odbc_connect" in keys:
76
+ connectors = [unquote_plus(keys.pop("odbc_connect"))]
77
+ else:
78
+
79
+ def check_quote(token: str) -> str:
80
+ if ";" in str(token) or str(token).startswith("{"):
81
+ token = "{%s}" % token.replace("}", "}}")
82
+ return token
83
+
84
+ keys = {k: check_quote(v) for k, v in keys.items()}
85
+
86
+ dsn_connection = "dsn" in keys or (
87
+ "host" in keys and "database" not in keys
88
+ )
89
+ if dsn_connection:
90
+ connectors = [
91
+ "dsn=%s" % (keys.pop("host", "") or keys.pop("dsn", ""))
92
+ ]
93
+ else:
94
+ port = ""
95
+ if "port" in keys and "port" not in query:
96
+ port = ",%d" % int(keys.pop("port"))
97
+
98
+ connectors = []
99
+ driver = keys.pop("driver", self.pyodbc_driver_name)
100
+ if driver is None and keys:
101
+ # note if keys is empty, this is a totally blank URL
102
+ util.warn(
103
+ "No driver name specified; "
104
+ "this is expected by PyODBC when using "
105
+ "DSN-less connections"
106
+ )
107
+ else:
108
+ connectors.append("DRIVER={%s}" % driver)
109
+
110
+ connectors.extend(
111
+ [
112
+ "Server=%s%s" % (keys.pop("host", ""), port),
113
+ "Database=%s" % keys.pop("database", ""),
114
+ ]
115
+ )
116
+
117
+ user = keys.pop("user", None)
118
+ if user:
119
+ connectors.append("UID=%s" % user)
120
+ pwd = keys.pop("password", "")
121
+ if pwd:
122
+ connectors.append("PWD=%s" % pwd)
123
+ else:
124
+ authentication = keys.pop("authentication", None)
125
+ if authentication:
126
+ connectors.append("Authentication=%s" % authentication)
127
+ else:
128
+ connectors.append("Trusted_Connection=Yes")
129
+
130
+ # if set to 'Yes', the ODBC layer will try to automagically
131
+ # convert textual data from your database encoding to your
132
+ # client encoding. This should obviously be set to 'No' if
133
+ # you query a cp1253 encoded database from a latin1 client...
134
+ if "odbc_autotranslate" in keys:
135
+ connectors.append(
136
+ "AutoTranslate=%s" % keys.pop("odbc_autotranslate")
137
+ )
138
+
139
+ connectors.extend(["%s=%s" % (k, v) for k, v in keys.items()])
140
+
141
+ return ((";".join(connectors),), connect_args)
142
+
143
+ def is_disconnect(
144
+ self,
145
+ e: Exception,
146
+ connection: Optional[
147
+ Union[pool.PoolProxiedConnection, interfaces.DBAPIConnection]
148
+ ],
149
+ cursor: Optional[interfaces.DBAPICursor],
150
+ ) -> bool:
151
+ if isinstance(e, self.loaded_dbapi.ProgrammingError):
152
+ return "The cursor's connection has been closed." in str(
153
+ e
154
+ ) or "Attempt to use a closed connection." in str(e)
155
+ else:
156
+ return False
157
+
158
+ def _dbapi_version(self) -> interfaces.VersionInfoType:
159
+ if not self.dbapi:
160
+ return ()
161
+ return self._parse_dbapi_version(self.dbapi.version)
162
+
163
+ def _parse_dbapi_version(self, vers: str) -> interfaces.VersionInfoType:
164
+ m = re.match(r"(?:py.*-)?([\d\.]+)(?:-(\w+))?", vers)
165
+ if not m:
166
+ return ()
167
+ vers_tuple: interfaces.VersionInfoType = tuple(
168
+ [int(x) for x in m.group(1).split(".")]
169
+ )
170
+ if m.group(2):
171
+ vers_tuple += (m.group(2),)
172
+ return vers_tuple
173
+
174
+ def _get_server_version_info(
175
+ self, connection: Connection
176
+ ) -> interfaces.VersionInfoType:
177
+ # NOTE: this function is not reliable, particularly when
178
+ # freetds is in use. Implement database-specific server version
179
+ # queries.
180
+ dbapi_con = connection.connection.dbapi_connection
181
+ version: Tuple[Union[int, str], ...] = ()
182
+ r = re.compile(r"[.\-]")
183
+ for n in r.split(dbapi_con.getinfo(self.dbapi.SQL_DBMS_VER)): # type: ignore[union-attr] # noqa: E501
184
+ try:
185
+ version += (int(n),)
186
+ except ValueError:
187
+ pass
188
+ return tuple(version)
189
+
190
+ def do_set_input_sizes(
191
+ self,
192
+ cursor: interfaces.DBAPICursor,
193
+ list_of_tuples: List[Tuple[str, Any, TypeEngine[Any]]],
194
+ context: ExecutionContext,
195
+ ) -> None:
196
+ # the rules for these types seems a little strange, as you can pass
197
+ # non-tuples as well as tuples, however it seems to assume "0"
198
+ # for the subsequent values if you don't pass a tuple which fails
199
+ # for types such as pyodbc.SQL_WLONGVARCHAR, which is the datatype
200
+ # that ticket #5649 is targeting.
201
+
202
+ # NOTE: as of #6058, this won't be called if the use_setinputsizes
203
+ # parameter were not passed to the dialect, or if no types were
204
+ # specified in list_of_tuples
205
+
206
+ # as of #8177 for 2.0 we assume use_setinputsizes=True and only
207
+ # omit the setinputsizes calls for .executemany() with
208
+ # fast_executemany=True
209
+
210
+ if (
211
+ context.execute_style is interfaces.ExecuteStyle.EXECUTEMANY
212
+ and self.fast_executemany
213
+ ):
214
+ return
215
+
216
+ cursor.setinputsizes(
217
+ [
218
+ (
219
+ (dbtype, None, None)
220
+ if not isinstance(dbtype, tuple)
221
+ else dbtype
222
+ )
223
+ for key, dbtype, sqltype in list_of_tuples
224
+ ]
225
+ )
226
+
227
+ def get_isolation_level_values(
228
+ self, dbapi_conn: interfaces.DBAPIConnection
229
+ ) -> List[IsolationLevel]:
230
+ return [*super().get_isolation_level_values(dbapi_conn), "AUTOCOMMIT"]
231
+
232
+ def set_isolation_level(
233
+ self,
234
+ dbapi_connection: interfaces.DBAPIConnection,
235
+ level: IsolationLevel,
236
+ ) -> None:
237
+ # adjust for ConnectionFairy being present
238
+ # allows attribute set e.g. "connection.autocommit = True"
239
+ # to work properly
240
+
241
+ if level == "AUTOCOMMIT":
242
+ dbapi_connection.autocommit = True
243
+ else:
244
+ dbapi_connection.autocommit = False
245
+ super().set_isolation_level(dbapi_connection, level)
246
+
247
+ def detect_autocommit_setting(
248
+ self, dbapi_conn: interfaces.DBAPIConnection
249
+ ) -> bool:
250
+ return bool(dbapi_conn.autocommit)
python/user_packages/Python313/site-packages/sqlalchemy/cyextension/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # cyextension/__init__.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
python/user_packages/Python313/site-packages/sqlalchemy/cyextension/collections.pyx ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cyextension/collections.pyx
2
+ # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ cimport cython
8
+ from cpython.long cimport PyLong_FromLongLong
9
+ from cpython.set cimport PySet_Add
10
+
11
+ from collections.abc import Collection
12
+ from itertools import filterfalse
13
+
14
+ cdef bint add_not_present(set seen, object item, hashfunc):
15
+ hash_value = hashfunc(item)
16
+ if hash_value not in seen:
17
+ PySet_Add(seen, hash_value)
18
+ return True
19
+ else:
20
+ return False
21
+
22
+ cdef list cunique_list(seq, hashfunc=None):
23
+ cdef set seen = set()
24
+ if not hashfunc:
25
+ return [x for x in seq if x not in seen and not PySet_Add(seen, x)]
26
+ else:
27
+ return [x for x in seq if add_not_present(seen, x, hashfunc)]
28
+
29
+ def unique_list(seq, hashfunc=None):
30
+ return cunique_list(seq, hashfunc)
31
+
32
+ cdef class OrderedSet(set):
33
+
34
+ cdef list _list
35
+
36
+ @classmethod
37
+ def __class_getitem__(cls, key):
38
+ return cls
39
+
40
+ def __init__(self, d=None):
41
+ set.__init__(self)
42
+ if d is not None:
43
+ self._list = cunique_list(d)
44
+ set.update(self, self._list)
45
+ else:
46
+ self._list = []
47
+
48
+ cpdef OrderedSet copy(self):
49
+ cdef OrderedSet cp = OrderedSet.__new__(OrderedSet)
50
+ cp._list = list(self._list)
51
+ set.update(cp, cp._list)
52
+ return cp
53
+
54
+ @cython.final
55
+ cdef OrderedSet _from_list(self, list new_list):
56
+ cdef OrderedSet new = OrderedSet.__new__(OrderedSet)
57
+ new._list = new_list
58
+ set.update(new, new_list)
59
+ return new
60
+
61
+ def add(self, element):
62
+ if element not in self:
63
+ self._list.append(element)
64
+ PySet_Add(self, element)
65
+
66
+ def remove(self, element):
67
+ # set.remove will raise if element is not in self
68
+ set.remove(self, element)
69
+ self._list.remove(element)
70
+
71
+ def pop(self):
72
+ try:
73
+ value = self._list.pop()
74
+ except IndexError:
75
+ raise KeyError("pop from an empty set") from None
76
+ set.remove(self, value)
77
+ return value
78
+
79
+ def insert(self, Py_ssize_t pos, element):
80
+ if element not in self:
81
+ self._list.insert(pos, element)
82
+ PySet_Add(self, element)
83
+
84
+ def discard(self, element):
85
+ if element in self:
86
+ set.remove(self, element)
87
+ self._list.remove(element)
88
+
89
+ def clear(self):
90
+ set.clear(self)
91
+ self._list = []
92
+
93
+ def __getitem__(self, key):
94
+ return self._list[key]
95
+
96
+ def __iter__(self):
97
+ return iter(self._list)
98
+
99
+ def __add__(self, other):
100
+ return self.union(other)
101
+
102
+ def __repr__(self):
103
+ return "%s(%r)" % (self.__class__.__name__, self._list)
104
+
105
+ __str__ = __repr__
106
+
107
+ def update(self, *iterables):
108
+ for iterable in iterables:
109
+ for e in iterable:
110
+ if e not in self:
111
+ self._list.append(e)
112
+ set.add(self, e)
113
+
114
+ def __ior__(self, iterable):
115
+ self.update(iterable)
116
+ return self
117
+
118
+ def union(self, *other):
119
+ result = self.copy()
120
+ result.update(*other)
121
+ return result
122
+
123
+ def __or__(self, other):
124
+ return self.union(other)
125
+
126
+ def intersection(self, *other):
127
+ cdef set other_set = set.intersection(self, *other)
128
+ return self._from_list([a for a in self._list if a in other_set])
129
+
130
+ def __and__(self, other):
131
+ return self.intersection(other)
132
+
133
+ def symmetric_difference(self, other):
134
+ cdef set other_set
135
+ if isinstance(other, set):
136
+ other_set = <set> other
137
+ collection = other_set
138
+ elif isinstance(other, Collection):
139
+ collection = other
140
+ other_set = set(other)
141
+ else:
142
+ collection = list(other)
143
+ other_set = set(collection)
144
+ result = self._from_list([a for a in self._list if a not in other_set])
145
+ result.update(a for a in collection if a not in self)
146
+ return result
147
+
148
+ def __xor__(self, other):
149
+ return self.symmetric_difference(other)
150
+
151
+ def difference(self, *other):
152
+ cdef set other_set = set.difference(self, *other)
153
+ return self._from_list([a for a in self._list if a in other_set])
154
+
155
+ def __sub__(self, other):
156
+ return self.difference(other)
157
+
158
+ def intersection_update(self, *other):
159
+ set.intersection_update(self, *other)
160
+ self._list = [a for a in self._list if a in self]
161
+
162
+ def __iand__(self, other):
163
+ self.intersection_update(other)
164
+ return self
165
+
166
+ cpdef symmetric_difference_update(self, other):
167
+ collection = other if isinstance(other, Collection) else list(other)
168
+ set.symmetric_difference_update(self, collection)
169
+ self._list = [a for a in self._list if a in self]
170
+ self._list += [a for a in collection if a in self]
171
+
172
+ def __ixor__(self, other):
173
+ self.symmetric_difference_update(other)
174
+ return self
175
+
176
+ def difference_update(self, *other):
177
+ set.difference_update(self, *other)
178
+ self._list = [a for a in self._list if a in self]
179
+
180
+ def __isub__(self, other):
181
+ self.difference_update(other)
182
+ return self
183
+
184
+ cdef object cy_id(object item):
185
+ return PyLong_FromLongLong(<long long> (<void *>item))
186
+
187
+ # NOTE: cython 0.x will call __add__, __sub__, etc with the parameter swapped
188
+ # instead of the __rmeth__, so they need to check that also self is of the
189
+ # correct type. This is fixed in cython 3.x. See:
190
+ # https://docs.cython.org/en/latest/src/userguide/special_methods.html#arithmetic-methods
191
+ cdef class IdentitySet:
192
+ """A set that considers only object id() for uniqueness.
193
+
194
+ This strategy has edge cases for builtin types- it's possible to have
195
+ two 'foo' strings in one of these sets, for example. Use sparingly.
196
+
197
+ """
198
+
199
+ cdef dict _members
200
+
201
+ def __init__(self, iterable=None):
202
+ self._members = {}
203
+ if iterable:
204
+ self.update(iterable)
205
+
206
+ def add(self, value):
207
+ self._members[cy_id(value)] = value
208
+
209
+ def __contains__(self, value):
210
+ return cy_id(value) in self._members
211
+
212
+ cpdef remove(self, value):
213
+ del self._members[cy_id(value)]
214
+
215
+ def discard(self, value):
216
+ try:
217
+ self.remove(value)
218
+ except KeyError:
219
+ pass
220
+
221
+ def pop(self):
222
+ cdef tuple pair
223
+ try:
224
+ pair = self._members.popitem()
225
+ return pair[1]
226
+ except KeyError:
227
+ raise KeyError("pop from an empty set")
228
+
229
+ def clear(self):
230
+ self._members.clear()
231
+
232
+ def __eq__(self, other):
233
+ cdef IdentitySet other_
234
+ if isinstance(other, IdentitySet):
235
+ other_ = other
236
+ return self._members == other_._members
237
+ else:
238
+ return False
239
+
240
+ def __ne__(self, other):
241
+ cdef IdentitySet other_
242
+ if isinstance(other, IdentitySet):
243
+ other_ = other
244
+ return self._members != other_._members
245
+ else:
246
+ return True
247
+
248
+ cpdef issubset(self, iterable):
249
+ cdef IdentitySet other
250
+ if isinstance(iterable, self.__class__):
251
+ other = iterable
252
+ else:
253
+ other = self.__class__(iterable)
254
+
255
+ if len(self) > len(other):
256
+ return False
257
+ for m in filterfalse(other._members.__contains__, self._members):
258
+ return False
259
+ return True
260
+
261
+ def __le__(self, other):
262
+ if not isinstance(other, IdentitySet):
263
+ return NotImplemented
264
+ return self.issubset(other)
265
+
266
+ def __lt__(self, other):
267
+ if not isinstance(other, IdentitySet):
268
+ return NotImplemented
269
+ return len(self) < len(other) and self.issubset(other)
270
+
271
+ cpdef issuperset(self, iterable):
272
+ cdef IdentitySet other
273
+ if isinstance(iterable, self.__class__):
274
+ other = iterable
275
+ else:
276
+ other = self.__class__(iterable)
277
+
278
+ if len(self) < len(other):
279
+ return False
280
+ for m in filterfalse(self._members.__contains__, other._members):
281
+ return False
282
+ return True
283
+
284
+ def __ge__(self, other):
285
+ if not isinstance(other, IdentitySet):
286
+ return NotImplemented
287
+ return self.issuperset(other)
288
+
289
+ def __gt__(self, other):
290
+ if not isinstance(other, IdentitySet):
291
+ return NotImplemented
292
+ return len(self) > len(other) and self.issuperset(other)
293
+
294
+ cpdef IdentitySet union(self, iterable):
295
+ cdef IdentitySet result = self.__class__()
296
+ result._members.update(self._members)
297
+ result.update(iterable)
298
+ return result
299
+
300
+ def __or__(self, other):
301
+ if not isinstance(other, IdentitySet) or not isinstance(self, IdentitySet):
302
+ return NotImplemented
303
+ return self.union(other)
304
+
305
+ cpdef update(self, iterable):
306
+ for obj in iterable:
307
+ self._members[cy_id(obj)] = obj
308
+
309
+ def __ior__(self, other):
310
+ if not isinstance(other, IdentitySet):
311
+ return NotImplemented
312
+ self.update(other)
313
+ return self
314
+
315
+ cpdef IdentitySet difference(self, iterable):
316
+ cdef IdentitySet result = self.__new__(self.__class__)
317
+ if isinstance(iterable, self.__class__):
318
+ other = (<IdentitySet>iterable)._members
319
+ else:
320
+ other = {cy_id(obj) for obj in iterable}
321
+ result._members = {k:v for k, v in self._members.items() if k not in other}
322
+ return result
323
+
324
+ def __sub__(self, other):
325
+ if not isinstance(other, IdentitySet) or not isinstance(self, IdentitySet):
326
+ return NotImplemented
327
+ return self.difference(other)
328
+
329
+ cpdef difference_update(self, iterable):
330
+ cdef IdentitySet other = self.difference(iterable)
331
+ self._members = other._members
332
+
333
+ def __isub__(self, other):
334
+ if not isinstance(other, IdentitySet):
335
+ return NotImplemented
336
+ self.difference_update(other)
337
+ return self
338
+
339
+ cpdef IdentitySet intersection(self, iterable):
340
+ cdef IdentitySet result = self.__new__(self.__class__)
341
+ if isinstance(iterable, self.__class__):
342
+ other = (<IdentitySet>iterable)._members
343
+ else:
344
+ other = {cy_id(obj) for obj in iterable}
345
+ result._members = {k: v for k, v in self._members.items() if k in other}
346
+ return result
347
+
348
+ def __and__(self, other):
349
+ if not isinstance(other, IdentitySet) or not isinstance(self, IdentitySet):
350
+ return NotImplemented
351
+ return self.intersection(other)
352
+
353
+ cpdef intersection_update(self, iterable):
354
+ cdef IdentitySet other = self.intersection(iterable)
355
+ self._members = other._members
356
+
357
+ def __iand__(self, other):
358
+ if not isinstance(other, IdentitySet):
359
+ return NotImplemented
360
+ self.intersection_update(other)
361
+ return self
362
+
363
+ cpdef IdentitySet symmetric_difference(self, iterable):
364
+ cdef IdentitySet result = self.__new__(self.__class__)
365
+ cdef dict other
366
+ if isinstance(iterable, self.__class__):
367
+ other = (<IdentitySet>iterable)._members
368
+ else:
369
+ other = {cy_id(obj): obj for obj in iterable}
370
+ result._members = {k: v for k, v in self._members.items() if k not in other}
371
+ result._members.update(
372
+ [(k, v) for k, v in other.items() if k not in self._members]
373
+ )
374
+ return result
375
+
376
+ def __xor__(self, other):
377
+ if not isinstance(other, IdentitySet) or not isinstance(self, IdentitySet):
378
+ return NotImplemented
379
+ return self.symmetric_difference(other)
380
+
381
+ cpdef symmetric_difference_update(self, iterable):
382
+ cdef IdentitySet other = self.symmetric_difference(iterable)
383
+ self._members = other._members
384
+
385
+ def __ixor__(self, other):
386
+ if not isinstance(other, IdentitySet):
387
+ return NotImplemented
388
+ self.symmetric_difference(other)
389
+ return self
390
+
391
+ cpdef IdentitySet copy(self):
392
+ cdef IdentitySet cp = self.__new__(self.__class__)
393
+ cp._members = self._members.copy()
394
+ return cp
395
+
396
+ def __copy__(self):
397
+ return self.copy()
398
+
399
+ def __len__(self):
400
+ return len(self._members)
401
+
402
+ def __iter__(self):
403
+ return iter(self._members.values())
404
+
405
+ def __hash__(self):
406
+ raise TypeError("set objects are unhashable")
407
+
408
+ def __repr__(self):
409
+ return "%s(%r)" % (type(self).__name__, list(self._members.values()))
python/user_packages/Python313/site-packages/sqlalchemy/cyextension/immutabledict.cp313-win_amd64.pyd ADDED
Binary file (67.1 kB). View file
 
python/user_packages/Python313/site-packages/sqlalchemy/cyextension/immutabledict.pxd ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # cyextension/immutabledict.pxd
2
+ # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ cdef class immutabledict(dict):
8
+ pass
python/user_packages/Python313/site-packages/sqlalchemy/cyextension/immutabledict.pyx ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cyextension/immutabledict.pyx
2
+ # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ from cpython.dict cimport PyDict_New, PyDict_Update, PyDict_Size
8
+
9
+
10
+ def _readonly_fn(obj):
11
+ raise TypeError(
12
+ "%s object is immutable and/or readonly" % obj.__class__.__name__)
13
+
14
+
15
+ def _immutable_fn(obj):
16
+ raise TypeError(
17
+ "%s object is immutable" % obj.__class__.__name__)
18
+
19
+
20
+ class ReadOnlyContainer:
21
+
22
+ __slots__ = ()
23
+
24
+ def _readonly(self, *a,**kw):
25
+ _readonly_fn(self)
26
+
27
+ __delitem__ = __setitem__ = __setattr__ = _readonly
28
+
29
+
30
+ class ImmutableDictBase(dict):
31
+ def _immutable(self, *a,**kw):
32
+ _immutable_fn(self)
33
+
34
+ @classmethod
35
+ def __class_getitem__(cls, key):
36
+ return cls
37
+
38
+ __delitem__ = __setitem__ = __setattr__ = _immutable
39
+ clear = pop = popitem = setdefault = update = _immutable
40
+
41
+
42
+ cdef class immutabledict(dict):
43
+ def __repr__(self):
44
+ return f"immutabledict({dict.__repr__(self)})"
45
+
46
+ @classmethod
47
+ def __class_getitem__(cls, key):
48
+ return cls
49
+
50
+ def union(self, *args, **kw):
51
+ cdef dict to_merge = None
52
+ cdef immutabledict result
53
+ cdef Py_ssize_t args_len = len(args)
54
+ if args_len > 1:
55
+ raise TypeError(
56
+ f'union expected at most 1 argument, got {args_len}'
57
+ )
58
+ if args_len == 1:
59
+ attribute = args[0]
60
+ if isinstance(attribute, dict):
61
+ to_merge = <dict> attribute
62
+ if to_merge is None:
63
+ to_merge = dict(*args, **kw)
64
+
65
+ if PyDict_Size(to_merge) == 0:
66
+ return self
67
+
68
+ # new + update is faster than immutabledict(self)
69
+ result = immutabledict()
70
+ PyDict_Update(result, self)
71
+ PyDict_Update(result, to_merge)
72
+ return result
73
+
74
+ def merge_with(self, *other):
75
+ cdef immutabledict result = None
76
+ cdef object d
77
+ cdef bint update = False
78
+ if not other:
79
+ return self
80
+ for d in other:
81
+ if d:
82
+ if update == False:
83
+ update = True
84
+ # new + update is faster than immutabledict(self)
85
+ result = immutabledict()
86
+ PyDict_Update(result, self)
87
+ PyDict_Update(
88
+ result, <dict>(d if isinstance(d, dict) else dict(d))
89
+ )
90
+
91
+ return self if update == False else result
92
+
93
+ def copy(self):
94
+ return self
95
+
96
+ def __reduce__(self):
97
+ return immutabledict, (dict(self), )
98
+
99
+ def __delitem__(self, k):
100
+ _immutable_fn(self)
101
+
102
+ def __setitem__(self, k, v):
103
+ _immutable_fn(self)
104
+
105
+ def __setattr__(self, k, v):
106
+ _immutable_fn(self)
107
+
108
+ def clear(self, *args, **kw):
109
+ _immutable_fn(self)
110
+
111
+ def pop(self, *args, **kw):
112
+ _immutable_fn(self)
113
+
114
+ def popitem(self, *args, **kw):
115
+ _immutable_fn(self)
116
+
117
+ def setdefault(self, *args, **kw):
118
+ _immutable_fn(self)
119
+
120
+ def update(self, *args, **kw):
121
+ _immutable_fn(self)
122
+
123
+ # PEP 584
124
+ def __ior__(self, other):
125
+ _immutable_fn(self)
126
+
127
+ def __or__(self, other):
128
+ return immutabledict(dict.__or__(self, other))
129
+
130
+ def __ror__(self, other):
131
+ # NOTE: this is used only in cython 3.x;
132
+ # version 0.x will call __or__ with args inversed
133
+ return immutabledict(dict.__ror__(self, other))
python/user_packages/Python313/site-packages/sqlalchemy/cyextension/processors.cp313-win_amd64.pyd ADDED
Binary file (57.9 kB). View file
 
python/user_packages/Python313/site-packages/sqlalchemy/cyextension/processors.pyx ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cyextension/processors.pyx
2
+ # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ import datetime
8
+ from datetime import datetime as datetime_cls
9
+ from datetime import time as time_cls
10
+ from datetime import date as date_cls
11
+ import re
12
+
13
+ from cpython.object cimport PyObject_Str
14
+ from cpython.unicode cimport PyUnicode_AsASCIIString, PyUnicode_Check, PyUnicode_Decode
15
+ from libc.stdio cimport sscanf
16
+
17
+
18
+ def int_to_boolean(value):
19
+ if value is None:
20
+ return None
21
+ return True if value else False
22
+
23
+ def to_str(value):
24
+ return PyObject_Str(value) if value is not None else None
25
+
26
+ def to_float(value):
27
+ return float(value) if value is not None else None
28
+
29
+ cdef inline bytes to_bytes(object value, str type_name):
30
+ try:
31
+ return PyUnicode_AsASCIIString(value)
32
+ except Exception as e:
33
+ raise ValueError(
34
+ f"Couldn't parse {type_name} string '{value!r}' "
35
+ "- value is not a string."
36
+ ) from e
37
+
38
+ def str_to_datetime(value):
39
+ if value is not None:
40
+ value = datetime_cls.fromisoformat(value)
41
+ return value
42
+
43
+ def str_to_time(value):
44
+ if value is not None:
45
+ value = time_cls.fromisoformat(value)
46
+ return value
47
+
48
+
49
+ def str_to_date(value):
50
+ if value is not None:
51
+ value = date_cls.fromisoformat(value)
52
+ return value
53
+
54
+
55
+
56
+ cdef class DecimalResultProcessor:
57
+ cdef object type_
58
+ cdef str format_
59
+
60
+ def __cinit__(self, type_, format_):
61
+ self.type_ = type_
62
+ self.format_ = format_
63
+
64
+ def process(self, object value):
65
+ if value is None:
66
+ return None
67
+ else:
68
+ return self.type_(self.format_ % value)
python/user_packages/Python313/site-packages/sqlalchemy/cyextension/resultproxy.cp313-win_amd64.pyd ADDED
Binary file (58.4 kB). View file
 
python/user_packages/Python313/site-packages/sqlalchemy/cyextension/resultproxy.pyx ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cyextension/resultproxy.pyx
2
+ # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ import operator
8
+
9
+ cdef class BaseRow:
10
+ cdef readonly object _parent
11
+ cdef readonly dict _key_to_index
12
+ cdef readonly tuple _data
13
+
14
+ def __init__(self, object parent, object processors, dict key_to_index, object data):
15
+ """Row objects are constructed by CursorResult objects."""
16
+
17
+ self._parent = parent
18
+
19
+ self._key_to_index = key_to_index
20
+
21
+ if processors:
22
+ self._data = _apply_processors(processors, data)
23
+ else:
24
+ self._data = tuple(data)
25
+
26
+ def __reduce__(self):
27
+ return (
28
+ rowproxy_reconstructor,
29
+ (self.__class__, self.__getstate__()),
30
+ )
31
+
32
+ def __getstate__(self):
33
+ return {"_parent": self._parent, "_data": self._data}
34
+
35
+ def __setstate__(self, dict state):
36
+ parent = state["_parent"]
37
+ self._parent = parent
38
+ self._data = state["_data"]
39
+ self._key_to_index = parent._key_to_index
40
+
41
+ def _values_impl(self):
42
+ return list(self)
43
+
44
+ def __iter__(self):
45
+ return iter(self._data)
46
+
47
+ def __len__(self):
48
+ return len(self._data)
49
+
50
+ def __hash__(self):
51
+ return hash(self._data)
52
+
53
+ def __getitem__(self, index):
54
+ return self._data[index]
55
+
56
+ def _get_by_key_impl_mapping(self, key):
57
+ return self._get_by_key_impl(key, 0)
58
+
59
+ cdef _get_by_key_impl(self, object key, int attr_err):
60
+ index = self._key_to_index.get(key)
61
+ if index is not None:
62
+ return self._data[<int>index]
63
+ self._parent._key_not_found(key, attr_err != 0)
64
+
65
+ def __getattr__(self, name):
66
+ return self._get_by_key_impl(name, 1)
67
+
68
+ def _to_tuple_instance(self):
69
+ return self._data
70
+
71
+
72
+ cdef tuple _apply_processors(proc, data):
73
+ res = []
74
+ for i in range(len(proc)):
75
+ p = proc[i]
76
+ if p is None:
77
+ res.append(data[i])
78
+ else:
79
+ res.append(p(data[i]))
80
+ return tuple(res)
81
+
82
+
83
+ def rowproxy_reconstructor(cls, state):
84
+ obj = cls.__new__(cls)
85
+ obj.__setstate__(state)
86
+ return obj
87
+
88
+
89
+ cdef int is_contiguous(tuple indexes):
90
+ cdef int i
91
+ for i in range(1, len(indexes)):
92
+ if indexes[i-1] != indexes[i] -1:
93
+ return 0
94
+ return 1
95
+
96
+
97
+ def tuplegetter(*indexes):
98
+ if len(indexes) == 1 or is_contiguous(indexes) != 0:
99
+ # slice form is faster but returns a list if input is list
100
+ return operator.itemgetter(slice(indexes[0], indexes[-1] + 1))
101
+ else:
102
+ return operator.itemgetter(*indexes)
python/user_packages/Python313/site-packages/sqlalchemy/cyextension/util.cp313-win_amd64.pyd ADDED
Binary file (69.1 kB). View file
 
python/user_packages/Python313/site-packages/sqlalchemy/cyextension/util.pyx ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cyextension/util.pyx
2
+ # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ from collections.abc import Mapping
8
+
9
+ from sqlalchemy import exc
10
+
11
+ cdef tuple _Empty_Tuple = ()
12
+
13
+ cdef inline bint _is_mapping_or_tuple(object value):
14
+ return isinstance(value, dict) or isinstance(value, tuple) or isinstance(value, Mapping)
15
+
16
+
17
+ cdef inline bint _is_mapping(object value):
18
+ return isinstance(value, dict) or isinstance(value, Mapping)
19
+
20
+
21
+ def _distill_params_20(object params):
22
+ if params is None:
23
+ return _Empty_Tuple
24
+ elif isinstance(params, list) or isinstance(params, tuple):
25
+ if params and not _is_mapping(params[0]):
26
+ raise exc.ArgumentError(
27
+ "List argument must consist only of dictionaries"
28
+ )
29
+ return params
30
+ elif _is_mapping(params):
31
+ return [params]
32
+ else:
33
+ raise exc.ArgumentError("mapping or list expected for parameters")
34
+
35
+
36
+ def _distill_raw_params(object params):
37
+ if params is None:
38
+ return _Empty_Tuple
39
+ elif isinstance(params, list):
40
+ if params and not _is_mapping_or_tuple(params[0]):
41
+ raise exc.ArgumentError(
42
+ "List argument must consist only of tuples or dictionaries"
43
+ )
44
+ return params
45
+ elif _is_mapping_or_tuple(params):
46
+ return [params]
47
+ else:
48
+ raise exc.ArgumentError("mapping or sequence expected for parameters")
49
+
50
+ cdef class prefix_anon_map(dict):
51
+ def __missing__(self, str key):
52
+ cdef str derived
53
+ cdef int anonymous_counter
54
+ cdef dict self_dict = self
55
+
56
+ derived = key.split(" ", 1)[1]
57
+
58
+ anonymous_counter = self_dict.get(derived, 1)
59
+ self_dict[derived] = anonymous_counter + 1
60
+ value = f"{derived}_{anonymous_counter}"
61
+ self_dict[key] = value
62
+ return value
63
+
64
+
65
+ cdef class cache_anon_map(dict):
66
+ cdef int _index
67
+
68
+ def __init__(self):
69
+ self._index = 0
70
+
71
+ def get_anon(self, obj):
72
+ cdef long long idself
73
+ cdef str id_
74
+ cdef dict self_dict = self
75
+
76
+ idself = id(obj)
77
+ if idself in self_dict:
78
+ return self_dict[idself], True
79
+ else:
80
+ id_ = self.__missing__(idself)
81
+ return id_, False
82
+
83
+ def __missing__(self, key):
84
+ cdef str val
85
+ cdef dict self_dict = self
86
+
87
+ self_dict[key] = val = str(self._index)
88
+ self._index += 1
89
+ return val
90
+
python/user_packages/Python313/site-packages/sqlalchemy/dialects/__init__.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/__init__.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+ from typing import Callable
12
+ from typing import Optional
13
+ from typing import Type
14
+ from typing import TYPE_CHECKING
15
+
16
+ from .. import util
17
+
18
+ if TYPE_CHECKING:
19
+ from ..engine.interfaces import Dialect
20
+
21
+ __all__ = ("mssql", "mysql", "oracle", "postgresql", "sqlite")
22
+
23
+
24
+ def _auto_fn(name: str) -> Optional[Callable[[], Type[Dialect]]]:
25
+ """default dialect importer.
26
+
27
+ plugs into the :class:`.PluginLoader`
28
+ as a first-hit system.
29
+
30
+ """
31
+ if "." in name:
32
+ dialect, driver = name.split(".")
33
+ else:
34
+ dialect = name
35
+ driver = "base"
36
+
37
+ try:
38
+ if dialect == "mariadb":
39
+ # it's "OK" for us to hardcode here since _auto_fn is already
40
+ # hardcoded. if mysql / mariadb etc were third party dialects
41
+ # they would just publish all the entrypoints, which would actually
42
+ # look much nicer.
43
+ module: Any = __import__(
44
+ "sqlalchemy.dialects.mysql.mariadb"
45
+ ).dialects.mysql.mariadb
46
+ return module.loader(driver) # type: ignore
47
+ else:
48
+ module = __import__("sqlalchemy.dialects.%s" % (dialect,)).dialects
49
+ module = getattr(module, dialect)
50
+ except ImportError:
51
+ return None
52
+
53
+ if hasattr(module, driver):
54
+ module = getattr(module, driver)
55
+ return lambda: module.dialect
56
+ else:
57
+ return None
58
+
59
+
60
+ registry = util.PluginLoader("sqlalchemy.dialects", auto_fn=_auto_fn)
61
+
62
+ plugins = util.PluginLoader("sqlalchemy.plugins")
python/user_packages/Python313/site-packages/sqlalchemy/dialects/_typing.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dialects/_typing.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+ from typing import Iterable
11
+ from typing import Mapping
12
+ from typing import Optional
13
+ from typing import Union
14
+
15
+ from ..sql import roles
16
+ from ..sql.base import ColumnCollection
17
+ from ..sql.schema import Column
18
+ from ..sql.schema import ColumnCollectionConstraint
19
+ from ..sql.schema import Index
20
+
21
+
22
+ _OnConflictConstraintT = Union[str, ColumnCollectionConstraint, Index, None]
23
+ _OnConflictIndexElementsT = Optional[
24
+ Iterable[Union[Column[Any], str, roles.DDLConstraintColumnRole]]
25
+ ]
26
+ _OnConflictIndexWhereT = Optional[roles.WhereHavingRole]
27
+ _OnConflictSetT = Optional[
28
+ Union[Mapping[Any, Any], ColumnCollection[Any, Any]]
29
+ ]
30
+ _OnConflictWhereT = Optional[roles.WhereHavingRole]
python/user_packages/Python313/site-packages/sqlalchemy/dialects/type_migration_guidelines.txt ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Rules for Migrating TypeEngine classes to 0.6
2
+ ---------------------------------------------
3
+
4
+ 1. the TypeEngine classes are used for:
5
+
6
+ a. Specifying behavior which needs to occur for bind parameters
7
+ or result row columns.
8
+
9
+ b. Specifying types that are entirely specific to the database
10
+ in use and have no analogue in the sqlalchemy.types package.
11
+
12
+ c. Specifying types where there is an analogue in sqlalchemy.types,
13
+ but the database in use takes vendor-specific flags for those
14
+ types.
15
+
16
+ d. If a TypeEngine class doesn't provide any of this, it should be
17
+ *removed* from the dialect.
18
+
19
+ 2. the TypeEngine classes are *no longer* used for generating DDL. Dialects
20
+ now have a TypeCompiler subclass which uses the same visit_XXX model as
21
+ other compilers.
22
+
23
+ 3. the "ischema_names" and "colspecs" dictionaries are now required members on
24
+ the Dialect class.
25
+
26
+ 4. The names of types within dialects are now important. If a dialect-specific type
27
+ is a subclass of an existing generic type and is only provided for bind/result behavior,
28
+ the current mixed case naming can remain, i.e. _PGNumeric for Numeric - in this case,
29
+ end users would never need to use _PGNumeric directly. However, if a dialect-specific
30
+ type is specifying a type *or* arguments that are not present generically, it should
31
+ match the real name of the type on that backend, in uppercase. E.g. postgresql.INET,
32
+ mysql.ENUM, postgresql.ARRAY.
33
+
34
+ Or follow this handy flowchart:
35
+
36
+ is the type meant to provide bind/result is the type the same name as an
37
+ behavior to a generic type (i.e. MixedCase) ---- no ---> UPPERCASE type in types.py ?
38
+ type in types.py ? | |
39
+ | no yes
40
+ yes | |
41
+ | | does your type need special
42
+ | +<--- yes --- behavior or arguments ?
43
+ | | |
44
+ | | no
45
+ name the type using | |
46
+ _MixedCase, i.e. v V
47
+ _OracleBoolean. it name the type don't make a
48
+ stays private to the dialect identically as that type, make sure the dialect's
49
+ and is invoked *only* via within the DB, base.py imports the types.py
50
+ the colspecs dict. using UPPERCASE UPPERCASE name into its namespace
51
+ | (i.e. BIT, NCHAR, INTERVAL).
52
+ | Users can import it.
53
+ | |
54
+ v v
55
+ subclass the closest is the name of this type
56
+ MixedCase type types.py, identical to an UPPERCASE
57
+ i.e. <--- no ------- name in types.py ?
58
+ class _DateTime(types.DateTime),
59
+ class DATETIME2(types.DateTime), |
60
+ class BIT(types.TypeEngine). yes
61
+ |
62
+ v
63
+ the type should
64
+ subclass the
65
+ UPPERCASE
66
+ type in types.py
67
+ (i.e. class BLOB(types.BLOB))
68
+
69
+
70
+ Example 1. pysqlite needs bind/result processing for the DateTime type in types.py,
71
+ which applies to all DateTimes and subclasses. It's named _SLDateTime and
72
+ subclasses types.DateTime.
73
+
74
+ Example 2. MS-SQL has a TIME type which takes a non-standard "precision" argument
75
+ that is rendered within DDL. So it's named TIME in the MS-SQL dialect's base.py,
76
+ and subclasses types.TIME. Users can then say mssql.TIME(precision=10).
77
+
78
+ Example 3. MS-SQL dialects also need special bind/result processing for date
79
+ But its DATE type doesn't render DDL differently than that of a plain
80
+ DATE, i.e. it takes no special arguments. Therefore we are just adding behavior
81
+ to types.Date, so it's named _MSDate in the MS-SQL dialect's base.py, and subclasses
82
+ types.Date.
83
+
84
+ Example 4. MySQL has a SET type, there's no analogue for this in types.py. So
85
+ MySQL names it SET in the dialect's base.py, and it subclasses types.String, since
86
+ it ultimately deals with strings.
87
+
88
+ Example 5. PostgreSQL has a DATETIME type. The DBAPIs handle dates correctly,
89
+ and no special arguments are used in PG's DDL beyond what types.py provides.
90
+ PostgreSQL dialect therefore imports types.DATETIME into its base.py.
91
+
92
+ Ideally one should be able to specify a schema using names imported completely from a
93
+ dialect, all matching the real name on that backend:
94
+
95
+ from sqlalchemy.dialects.postgresql import base as pg
96
+
97
+ t = Table('mytable', metadata,
98
+ Column('id', pg.INTEGER, primary_key=True),
99
+ Column('name', pg.VARCHAR(300)),
100
+ Column('inetaddr', pg.INET)
101
+ )
102
+
103
+ where above, the INTEGER and VARCHAR types are ultimately from sqlalchemy.types,
104
+ but the PG dialect makes them available in its own namespace.
105
+
106
+ 5. "colspecs" now is a dictionary of generic or uppercased types from sqlalchemy.types
107
+ linked to types specified in the dialect. Again, if a type in the dialect does not
108
+ specify any special behavior for bind_processor() or result_processor() and does not
109
+ indicate a special type only available in this database, it must be *removed* from the
110
+ module and from this dictionary.
111
+
112
+ 6. "ischema_names" indicates string descriptions of types as returned from the database
113
+ linked to TypeEngine classes.
114
+
115
+ a. The string name should be matched to the most specific type possible within
116
+ sqlalchemy.types, unless there is no matching type within sqlalchemy.types in which
117
+ case it points to a dialect type. *It doesn't matter* if the dialect has its
118
+ own subclass of that type with special bind/result behavior - reflect to the types.py
119
+ UPPERCASE type as much as possible. With very few exceptions, all types
120
+ should reflect to an UPPERCASE type.
121
+
122
+ b. If the dialect contains a matching dialect-specific type that takes extra arguments
123
+ which the generic one does not, then point to the dialect-specific type. E.g.
124
+ mssql.VARCHAR takes a "collation" parameter which should be preserved.
125
+
126
+ 5. DDL, or what was formerly issued by "get_col_spec()", is now handled exclusively by
127
+ a subclass of compiler.GenericTypeCompiler.
128
+
129
+ a. your TypeCompiler class will receive generic and uppercase types from
130
+ sqlalchemy.types. Do not assume the presence of dialect-specific attributes on
131
+ these types.
132
+
133
+ b. the visit_UPPERCASE methods on GenericTypeCompiler should *not* be overridden with
134
+ methods that produce a different DDL name. Uppercase types don't do any kind of
135
+ "guessing" - if visit_TIMESTAMP is called, the DDL should render as TIMESTAMP in
136
+ all cases, regardless of whether or not that type is legal on the backend database.
137
+
138
+ c. the visit_UPPERCASE methods *should* be overridden with methods that add additional
139
+ arguments and flags to those types.
140
+
141
+ d. the visit_lowercase methods are overridden to provide an interpretation of a generic
142
+ type. E.g. visit_large_binary() might be overridden to say "return self.visit_BIT(type_)".
143
+
144
+ e. visit_lowercase methods should *never* render strings directly - it should always
145
+ be via calling a visit_UPPERCASE() method.
python/user_packages/Python313/site-packages/sqlalchemy/engine/__init__.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # engine/__init__.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ """SQL connections, SQL execution and high-level DB-API interface.
9
+
10
+ The engine package defines the basic components used to interface
11
+ DB-API modules with higher-level statement construction,
12
+ connection-management, execution and result contexts. The primary
13
+ "entry point" class into this package is the Engine and its public
14
+ constructor ``create_engine()``.
15
+
16
+ """
17
+
18
+ from . import events as events
19
+ from . import util as util
20
+ from .base import Connection as Connection
21
+ from .base import Engine as Engine
22
+ from .base import NestedTransaction as NestedTransaction
23
+ from .base import RootTransaction as RootTransaction
24
+ from .base import Transaction as Transaction
25
+ from .base import TwoPhaseTransaction as TwoPhaseTransaction
26
+ from .create import create_engine as create_engine
27
+ from .create import create_pool_from_url as create_pool_from_url
28
+ from .create import engine_from_config as engine_from_config
29
+ from .cursor import CursorResult as CursorResult
30
+ from .cursor import ResultProxy as ResultProxy
31
+ from .interfaces import AdaptedConnection as AdaptedConnection
32
+ from .interfaces import BindTyping as BindTyping
33
+ from .interfaces import Compiled as Compiled
34
+ from .interfaces import Connectable as Connectable
35
+ from .interfaces import ConnectArgsType as ConnectArgsType
36
+ from .interfaces import ConnectionEventsTarget as ConnectionEventsTarget
37
+ from .interfaces import CreateEnginePlugin as CreateEnginePlugin
38
+ from .interfaces import Dialect as Dialect
39
+ from .interfaces import ExceptionContext as ExceptionContext
40
+ from .interfaces import ExecutionContext as ExecutionContext
41
+ from .interfaces import TypeCompiler as TypeCompiler
42
+ from .mock import create_mock_engine as create_mock_engine
43
+ from .reflection import Inspector as Inspector
44
+ from .reflection import ObjectKind as ObjectKind
45
+ from .reflection import ObjectScope as ObjectScope
46
+ from .result import ChunkedIteratorResult as ChunkedIteratorResult
47
+ from .result import FilterResult as FilterResult
48
+ from .result import FrozenResult as FrozenResult
49
+ from .result import IteratorResult as IteratorResult
50
+ from .result import MappingResult as MappingResult
51
+ from .result import MergedResult as MergedResult
52
+ from .result import Result as Result
53
+ from .result import result_tuple as result_tuple
54
+ from .result import ScalarResult as ScalarResult
55
+ from .result import TupleResult as TupleResult
56
+ from .row import BaseRow as BaseRow
57
+ from .row import Row as Row
58
+ from .row import RowMapping as RowMapping
59
+ from .url import make_url as make_url
60
+ from .url import URL as URL
61
+ from .util import connection_memoize as connection_memoize
62
+ from ..sql import ddl as ddl
python/user_packages/Python313/site-packages/sqlalchemy/engine/_py_processors.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # engine/_py_processors.py
2
+ # Copyright (C) 2010-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ # Copyright (C) 2010 Gaetan de Menten gdementen@gmail.com
5
+ #
6
+ # This module is part of SQLAlchemy and is released under
7
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
8
+
9
+ """defines generic type conversion functions, as used in bind and result
10
+ processors.
11
+
12
+ They all share one common characteristic: None is passed through unchanged.
13
+
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import datetime
19
+ from datetime import date as date_cls
20
+ from datetime import datetime as datetime_cls
21
+ from datetime import time as time_cls
22
+ from decimal import Decimal
23
+ import typing
24
+ from typing import Any
25
+ from typing import Callable
26
+ from typing import Optional
27
+ from typing import Type
28
+ from typing import TypeVar
29
+ from typing import Union
30
+
31
+
32
+ _DT = TypeVar(
33
+ "_DT", bound=Union[datetime.datetime, datetime.time, datetime.date]
34
+ )
35
+
36
+
37
+ def str_to_datetime_processor_factory(
38
+ regexp: typing.Pattern[str], type_: Callable[..., _DT]
39
+ ) -> Callable[[Optional[str]], Optional[_DT]]:
40
+ rmatch = regexp.match
41
+ # Even on python2.6 datetime.strptime is both slower than this code
42
+ # and it does not support microseconds.
43
+ has_named_groups = bool(regexp.groupindex)
44
+
45
+ def process(value: Optional[str]) -> Optional[_DT]:
46
+ if value is None:
47
+ return None
48
+ else:
49
+ try:
50
+ m = rmatch(value)
51
+ except TypeError as err:
52
+ raise ValueError(
53
+ "Couldn't parse %s string '%r' "
54
+ "- value is not a string." % (type_.__name__, value)
55
+ ) from err
56
+
57
+ if m is None:
58
+ raise ValueError(
59
+ "Couldn't parse %s string: "
60
+ "'%s'" % (type_.__name__, value)
61
+ )
62
+ if has_named_groups:
63
+ groups = m.groupdict(0)
64
+ return type_(
65
+ **dict(
66
+ list(
67
+ zip(
68
+ iter(groups.keys()),
69
+ list(map(int, iter(groups.values()))),
70
+ )
71
+ )
72
+ )
73
+ )
74
+ else:
75
+ return type_(*list(map(int, m.groups(0))))
76
+
77
+ return process
78
+
79
+
80
+ def to_decimal_processor_factory(
81
+ target_class: Type[Decimal], scale: int
82
+ ) -> Callable[[Optional[float]], Optional[Decimal]]:
83
+ fstring = "%%.%df" % scale
84
+
85
+ def process(value: Optional[float]) -> Optional[Decimal]:
86
+ if value is None:
87
+ return None
88
+ else:
89
+ return target_class(fstring % value)
90
+
91
+ return process
92
+
93
+
94
+ def to_float(value: Optional[Union[int, float]]) -> Optional[float]:
95
+ if value is None:
96
+ return None
97
+ else:
98
+ return float(value)
99
+
100
+
101
+ def to_str(value: Optional[Any]) -> Optional[str]:
102
+ if value is None:
103
+ return None
104
+ else:
105
+ return str(value)
106
+
107
+
108
+ def int_to_boolean(value: Optional[int]) -> Optional[bool]:
109
+ if value is None:
110
+ return None
111
+ else:
112
+ return bool(value)
113
+
114
+
115
+ def str_to_datetime(value: Optional[str]) -> Optional[datetime.datetime]:
116
+ if value is not None:
117
+ dt_value = datetime_cls.fromisoformat(value)
118
+ else:
119
+ dt_value = None
120
+ return dt_value
121
+
122
+
123
+ def str_to_time(value: Optional[str]) -> Optional[datetime.time]:
124
+ if value is not None:
125
+ dt_value = time_cls.fromisoformat(value)
126
+ else:
127
+ dt_value = None
128
+ return dt_value
129
+
130
+
131
+ def str_to_date(value: Optional[str]) -> Optional[datetime.date]:
132
+ if value is not None:
133
+ dt_value = date_cls.fromisoformat(value)
134
+ else:
135
+ dt_value = None
136
+ return dt_value
python/user_packages/Python313/site-packages/sqlalchemy/engine/_py_row.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # engine/_py_row.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ from __future__ import annotations
8
+
9
+ import operator
10
+ import typing
11
+ from typing import Any
12
+ from typing import Callable
13
+ from typing import Dict
14
+ from typing import Iterator
15
+ from typing import List
16
+ from typing import Mapping
17
+ from typing import Optional
18
+ from typing import Tuple
19
+ from typing import Type
20
+
21
+ if typing.TYPE_CHECKING:
22
+ from .result import _KeyType
23
+ from .result import _ProcessorsType
24
+ from .result import _RawRowType
25
+ from .result import _TupleGetterType
26
+ from .result import ResultMetaData
27
+
28
+ MD_INDEX = 0 # integer index in cursor.description
29
+
30
+
31
+ class BaseRow:
32
+ __slots__ = ("_parent", "_data", "_key_to_index")
33
+
34
+ _parent: ResultMetaData
35
+ _key_to_index: Mapping[_KeyType, int]
36
+ _data: _RawRowType
37
+
38
+ def __init__(
39
+ self,
40
+ parent: ResultMetaData,
41
+ processors: Optional[_ProcessorsType],
42
+ key_to_index: Mapping[_KeyType, int],
43
+ data: _RawRowType,
44
+ ):
45
+ """Row objects are constructed by CursorResult objects."""
46
+ object.__setattr__(self, "_parent", parent)
47
+
48
+ object.__setattr__(self, "_key_to_index", key_to_index)
49
+
50
+ if processors:
51
+ object.__setattr__(
52
+ self,
53
+ "_data",
54
+ tuple(
55
+ [
56
+ proc(value) if proc else value
57
+ for proc, value in zip(processors, data)
58
+ ]
59
+ ),
60
+ )
61
+ else:
62
+ object.__setattr__(self, "_data", tuple(data))
63
+
64
+ def __reduce__(self) -> Tuple[Callable[..., BaseRow], Tuple[Any, ...]]:
65
+ return (
66
+ rowproxy_reconstructor,
67
+ (self.__class__, self.__getstate__()),
68
+ )
69
+
70
+ def __getstate__(self) -> Dict[str, Any]:
71
+ return {"_parent": self._parent, "_data": self._data}
72
+
73
+ def __setstate__(self, state: Dict[str, Any]) -> None:
74
+ parent = state["_parent"]
75
+ object.__setattr__(self, "_parent", parent)
76
+ object.__setattr__(self, "_data", state["_data"])
77
+ object.__setattr__(self, "_key_to_index", parent._key_to_index)
78
+
79
+ def _values_impl(self) -> List[Any]:
80
+ return list(self)
81
+
82
+ def __iter__(self) -> Iterator[Any]:
83
+ return iter(self._data)
84
+
85
+ def __len__(self) -> int:
86
+ return len(self._data)
87
+
88
+ def __hash__(self) -> int:
89
+ return hash(self._data)
90
+
91
+ def __getitem__(self, key: Any) -> Any:
92
+ return self._data[key]
93
+
94
+ def _get_by_key_impl_mapping(self, key: str) -> Any:
95
+ try:
96
+ return self._data[self._key_to_index[key]]
97
+ except KeyError:
98
+ pass
99
+ self._parent._key_not_found(key, False)
100
+
101
+ def __getattr__(self, name: str) -> Any:
102
+ try:
103
+ return self._data[self._key_to_index[name]]
104
+ except KeyError:
105
+ pass
106
+ self._parent._key_not_found(name, True)
107
+
108
+ def _to_tuple_instance(self) -> Tuple[Any, ...]:
109
+ return self._data
110
+
111
+
112
+ # This reconstructor is necessary so that pickles with the Cy extension or
113
+ # without use the same Binary format.
114
+ def rowproxy_reconstructor(
115
+ cls: Type[BaseRow], state: Dict[str, Any]
116
+ ) -> BaseRow:
117
+ obj = cls.__new__(cls)
118
+ obj.__setstate__(state)
119
+ return obj
120
+
121
+
122
+ def tuplegetter(*indexes: int) -> _TupleGetterType:
123
+ if len(indexes) != 1:
124
+ for i in range(1, len(indexes)):
125
+ if indexes[i - 1] != indexes[i] - 1:
126
+ return operator.itemgetter(*indexes)
127
+ # slice form is faster but returns a list if input is list
128
+ return operator.itemgetter(slice(indexes[0], indexes[-1] + 1))
python/user_packages/Python313/site-packages/sqlalchemy/engine/_py_util.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # engine/_py_util.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ from __future__ import annotations
8
+
9
+ import typing
10
+ from typing import Any
11
+ from typing import Mapping
12
+ from typing import Optional
13
+ from typing import Tuple
14
+
15
+ from .. import exc
16
+
17
+ if typing.TYPE_CHECKING:
18
+ from .interfaces import _CoreAnyExecuteParams
19
+ from .interfaces import _CoreMultiExecuteParams
20
+ from .interfaces import _DBAPIAnyExecuteParams
21
+ from .interfaces import _DBAPIMultiExecuteParams
22
+
23
+
24
+ _no_tuple: Tuple[Any, ...] = ()
25
+
26
+
27
+ def _distill_params_20(
28
+ params: Optional[_CoreAnyExecuteParams],
29
+ ) -> _CoreMultiExecuteParams:
30
+ if params is None:
31
+ return _no_tuple
32
+ # Assume list is more likely than tuple
33
+ elif isinstance(params, list) or isinstance(params, tuple):
34
+ # collections_abc.MutableSequence): # avoid abc.__instancecheck__
35
+ if params and not isinstance(params[0], Mapping):
36
+ raise exc.ArgumentError(
37
+ "List argument must consist only of dictionaries"
38
+ )
39
+
40
+ return params
41
+ elif isinstance(params, dict) or isinstance(
42
+ # only do immutabledict or abc.__instancecheck__ for Mapping after
43
+ # we've checked for plain dictionaries and would otherwise raise
44
+ params,
45
+ Mapping,
46
+ ):
47
+ return [params]
48
+ else:
49
+ raise exc.ArgumentError("mapping or list expected for parameters")
50
+
51
+
52
+ def _distill_raw_params(
53
+ params: Optional[_DBAPIAnyExecuteParams],
54
+ ) -> _DBAPIMultiExecuteParams:
55
+ if params is None:
56
+ return _no_tuple
57
+ elif isinstance(params, list):
58
+ # collections_abc.MutableSequence): # avoid abc.__instancecheck__
59
+ if params and not isinstance(params[0], (tuple, Mapping)):
60
+ raise exc.ArgumentError(
61
+ "List argument must consist only of tuples or dictionaries"
62
+ )
63
+
64
+ return params
65
+ elif isinstance(params, (tuple, dict)) or isinstance(
66
+ # only do abc.__instancecheck__ for Mapping after we've checked
67
+ # for plain dictionaries and would otherwise raise
68
+ params,
69
+ Mapping,
70
+ ):
71
+ # cast("Union[List[Mapping[str, Any]], Tuple[Any, ...]]", [params])
72
+ return [params] # type: ignore
73
+ else:
74
+ raise exc.ArgumentError("mapping or sequence expected for parameters")
python/user_packages/Python313/site-packages/sqlalchemy/engine/base.py ADDED
The diff for this file is too large to render. See raw diff
 
python/user_packages/Python313/site-packages/sqlalchemy/engine/characteristics.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # engine/characteristics.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ from __future__ import annotations
8
+
9
+ import abc
10
+ import typing
11
+ from typing import Any
12
+ from typing import ClassVar
13
+
14
+ if typing.TYPE_CHECKING:
15
+ from .base import Connection
16
+ from .interfaces import DBAPIConnection
17
+ from .interfaces import Dialect
18
+
19
+
20
+ class ConnectionCharacteristic(abc.ABC):
21
+ """An abstract base for an object that can set, get and reset a
22
+ per-connection characteristic, typically one that gets reset when the
23
+ connection is returned to the connection pool.
24
+
25
+ transaction isolation is the canonical example, and the
26
+ ``IsolationLevelCharacteristic`` implementation provides this for the
27
+ ``DefaultDialect``.
28
+
29
+ The ``ConnectionCharacteristic`` class should call upon the ``Dialect`` for
30
+ the implementation of each method. The object exists strictly to serve as
31
+ a dialect visitor that can be placed into the
32
+ ``DefaultDialect.connection_characteristics`` dictionary where it will take
33
+ effect for calls to :meth:`_engine.Connection.execution_options` and
34
+ related APIs.
35
+
36
+ .. versionadded:: 1.4
37
+
38
+ """
39
+
40
+ __slots__ = ()
41
+
42
+ transactional: ClassVar[bool] = False
43
+
44
+ @abc.abstractmethod
45
+ def reset_characteristic(
46
+ self, dialect: Dialect, dbapi_conn: DBAPIConnection
47
+ ) -> None:
48
+ """Reset the characteristic on the DBAPI connection to its default
49
+ value."""
50
+
51
+ @abc.abstractmethod
52
+ def set_characteristic(
53
+ self, dialect: Dialect, dbapi_conn: DBAPIConnection, value: Any
54
+ ) -> None:
55
+ """set characteristic on the DBAPI connection to a given value."""
56
+
57
+ def set_connection_characteristic(
58
+ self,
59
+ dialect: Dialect,
60
+ conn: Connection,
61
+ dbapi_conn: DBAPIConnection,
62
+ value: Any,
63
+ ) -> None:
64
+ """set characteristic on the :class:`_engine.Connection` to a given
65
+ value.
66
+
67
+ .. versionadded:: 2.0.30 - added to support elements that are local
68
+ to the :class:`_engine.Connection` itself.
69
+
70
+ """
71
+ self.set_characteristic(dialect, dbapi_conn, value)
72
+
73
+ @abc.abstractmethod
74
+ def get_characteristic(
75
+ self, dialect: Dialect, dbapi_conn: DBAPIConnection
76
+ ) -> Any:
77
+ """Given a DBAPI connection, get the current value of the
78
+ characteristic.
79
+
80
+ """
81
+
82
+ def get_connection_characteristic(
83
+ self, dialect: Dialect, conn: Connection, dbapi_conn: DBAPIConnection
84
+ ) -> Any:
85
+ """Given a :class:`_engine.Connection`, get the current value of the
86
+ characteristic.
87
+
88
+ .. versionadded:: 2.0.30 - added to support elements that are local
89
+ to the :class:`_engine.Connection` itself.
90
+
91
+ """
92
+ return self.get_characteristic(dialect, dbapi_conn)
93
+
94
+
95
+ class IsolationLevelCharacteristic(ConnectionCharacteristic):
96
+ """Manage the isolation level on a DBAPI connection"""
97
+
98
+ transactional: ClassVar[bool] = True
99
+
100
+ def reset_characteristic(
101
+ self, dialect: Dialect, dbapi_conn: DBAPIConnection
102
+ ) -> None:
103
+ dialect.reset_isolation_level(dbapi_conn)
104
+
105
+ def set_characteristic(
106
+ self, dialect: Dialect, dbapi_conn: DBAPIConnection, value: Any
107
+ ) -> None:
108
+ dialect._assert_and_set_isolation_level(dbapi_conn, value)
109
+
110
+ def get_characteristic(
111
+ self, dialect: Dialect, dbapi_conn: DBAPIConnection
112
+ ) -> Any:
113
+ return dialect.get_isolation_level(dbapi_conn)
114
+
115
+
116
+ class LoggingTokenCharacteristic(ConnectionCharacteristic):
117
+ """Manage the 'logging_token' option of a :class:`_engine.Connection`.
118
+
119
+ .. versionadded:: 2.0.30
120
+
121
+ """
122
+
123
+ transactional: ClassVar[bool] = False
124
+
125
+ def reset_characteristic(
126
+ self, dialect: Dialect, dbapi_conn: DBAPIConnection
127
+ ) -> None:
128
+ pass
129
+
130
+ def set_characteristic(
131
+ self, dialect: Dialect, dbapi_conn: DBAPIConnection, value: Any
132
+ ) -> None:
133
+ raise NotImplementedError()
134
+
135
+ def set_connection_characteristic(
136
+ self,
137
+ dialect: Dialect,
138
+ conn: Connection,
139
+ dbapi_conn: DBAPIConnection,
140
+ value: Any,
141
+ ) -> None:
142
+ if value:
143
+ conn._message_formatter = lambda msg: "[%s] %s" % (value, msg)
144
+ else:
145
+ del conn._message_formatter
146
+
147
+ def get_characteristic(
148
+ self, dialect: Dialect, dbapi_conn: DBAPIConnection
149
+ ) -> Any:
150
+ raise NotImplementedError()
151
+
152
+ def get_connection_characteristic(
153
+ self, dialect: Dialect, conn: Connection, dbapi_conn: DBAPIConnection
154
+ ) -> Any:
155
+ return conn._execution_options.get("logging_token", None)
python/user_packages/Python313/site-packages/sqlalchemy/engine/create.py ADDED
@@ -0,0 +1,899 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # engine/create.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ from __future__ import annotations
9
+
10
+ import inspect
11
+ import typing
12
+ from typing import Any
13
+ from typing import Callable
14
+ from typing import cast
15
+ from typing import Dict
16
+ from typing import List
17
+ from typing import Optional
18
+ from typing import overload
19
+ from typing import Type
20
+ from typing import Union
21
+
22
+ from . import base
23
+ from . import url as _url
24
+ from .interfaces import DBAPIConnection
25
+ from .mock import create_mock_engine
26
+ from .. import event
27
+ from .. import exc
28
+ from .. import util
29
+ from ..pool import _AdhocProxiedConnection
30
+ from ..pool import ConnectionPoolEntry
31
+ from ..sql import compiler
32
+ from ..util import immutabledict
33
+
34
+ if typing.TYPE_CHECKING:
35
+ from .base import Engine
36
+ from .interfaces import _ExecuteOptions
37
+ from .interfaces import _ParamStyle
38
+ from .interfaces import IsolationLevel
39
+ from .url import URL
40
+ from ..log import _EchoFlagType
41
+ from ..pool import _CreatorFnType
42
+ from ..pool import _CreatorWRecFnType
43
+ from ..pool import _ResetStyleArgType
44
+ from ..pool import Pool
45
+ from ..util.typing import Literal
46
+
47
+
48
+ @overload
49
+ def create_engine(
50
+ url: Union[str, URL],
51
+ *,
52
+ connect_args: Dict[Any, Any] = ...,
53
+ convert_unicode: bool = ...,
54
+ creator: Union[_CreatorFnType, _CreatorWRecFnType] = ...,
55
+ echo: _EchoFlagType = ...,
56
+ echo_pool: _EchoFlagType = ...,
57
+ enable_from_linting: bool = ...,
58
+ execution_options: _ExecuteOptions = ...,
59
+ future: Literal[True],
60
+ hide_parameters: bool = ...,
61
+ implicit_returning: Literal[True] = ...,
62
+ insertmanyvalues_page_size: int = ...,
63
+ isolation_level: IsolationLevel = ...,
64
+ json_deserializer: Callable[..., Any] = ...,
65
+ json_serializer: Callable[..., Any] = ...,
66
+ label_length: Optional[int] = ...,
67
+ logging_name: str = ...,
68
+ max_identifier_length: Optional[int] = ...,
69
+ max_overflow: int = ...,
70
+ module: Optional[Any] = ...,
71
+ paramstyle: Optional[_ParamStyle] = ...,
72
+ pool: Optional[Pool] = ...,
73
+ poolclass: Optional[Type[Pool]] = ...,
74
+ pool_logging_name: str = ...,
75
+ pool_pre_ping: bool = ...,
76
+ pool_size: int = ...,
77
+ pool_recycle: int = ...,
78
+ pool_reset_on_return: Optional[_ResetStyleArgType] = ...,
79
+ pool_timeout: float = ...,
80
+ pool_use_lifo: bool = ...,
81
+ plugins: List[str] = ...,
82
+ query_cache_size: int = ...,
83
+ use_insertmanyvalues: bool = ...,
84
+ **kwargs: Any,
85
+ ) -> Engine: ...
86
+
87
+
88
+ @overload
89
+ def create_engine(url: Union[str, URL], **kwargs: Any) -> Engine: ...
90
+
91
+
92
+ @util.deprecated_params(
93
+ strategy=(
94
+ "1.4",
95
+ "The :paramref:`_sa.create_engine.strategy` keyword is deprecated, "
96
+ "and the only argument accepted is 'mock'; please use "
97
+ ":func:`.create_mock_engine` going forward. For general "
98
+ "customization of create_engine which may have been accomplished "
99
+ "using strategies, see :class:`.CreateEnginePlugin`.",
100
+ ),
101
+ empty_in_strategy=(
102
+ "1.4",
103
+ "The :paramref:`_sa.create_engine.empty_in_strategy` keyword is "
104
+ "deprecated, and no longer has any effect. All IN expressions "
105
+ "are now rendered using "
106
+ 'the "expanding parameter" strategy which renders a set of bound'
107
+ 'expressions, or an "empty set" SELECT, at statement execution'
108
+ "time.",
109
+ ),
110
+ implicit_returning=(
111
+ "2.0",
112
+ "The :paramref:`_sa.create_engine.implicit_returning` parameter "
113
+ "is deprecated and will be removed in a future release. ",
114
+ ),
115
+ )
116
+ def create_engine(url: Union[str, _url.URL], **kwargs: Any) -> Engine:
117
+ """Create a new :class:`_engine.Engine` instance.
118
+
119
+ The standard calling form is to send the :ref:`URL <database_urls>` as the
120
+ first positional argument, usually a string
121
+ that indicates database dialect and connection arguments::
122
+
123
+ engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/test")
124
+
125
+ .. note::
126
+
127
+ Please review :ref:`database_urls` for general guidelines in composing
128
+ URL strings. In particular, special characters, such as those often
129
+ part of passwords, must be URL encoded to be properly parsed.
130
+
131
+ Additional keyword arguments may then follow it which
132
+ establish various options on the resulting :class:`_engine.Engine`
133
+ and its underlying :class:`.Dialect` and :class:`_pool.Pool`
134
+ constructs::
135
+
136
+ engine = create_engine(
137
+ "mysql+mysqldb://scott:tiger@hostname/dbname",
138
+ pool_recycle=3600,
139
+ echo=True,
140
+ )
141
+
142
+ The string form of the URL is
143
+ ``dialect[+driver]://user:password@host/dbname[?key=value..]``, where
144
+ ``dialect`` is a database name such as ``mysql``, ``oracle``,
145
+ ``postgresql``, etc., and ``driver`` the name of a DBAPI, such as
146
+ ``psycopg2``, ``pyodbc``, ``cx_oracle``, etc. Alternatively,
147
+ the URL can be an instance of :class:`~sqlalchemy.engine.url.URL`.
148
+
149
+ ``**kwargs`` takes a wide variety of options which are routed
150
+ towards their appropriate components. Arguments may be specific to
151
+ the :class:`_engine.Engine`, the underlying :class:`.Dialect`,
152
+ as well as the
153
+ :class:`_pool.Pool`. Specific dialects also accept keyword arguments that
154
+ are unique to that dialect. Here, we describe the parameters
155
+ that are common to most :func:`_sa.create_engine()` usage.
156
+
157
+ Once established, the newly resulting :class:`_engine.Engine` will
158
+ request a connection from the underlying :class:`_pool.Pool` once
159
+ :meth:`_engine.Engine.connect` is called, or a method which depends on it
160
+ such as :meth:`_engine.Engine.execute` is invoked. The
161
+ :class:`_pool.Pool` in turn
162
+ will establish the first actual DBAPI connection when this request
163
+ is received. The :func:`_sa.create_engine` call itself does **not**
164
+ establish any actual DBAPI connections directly.
165
+
166
+ .. seealso::
167
+
168
+ :doc:`/core/engines`
169
+
170
+ :doc:`/dialects/index`
171
+
172
+ :ref:`connections_toplevel`
173
+
174
+ :param connect_args: a dictionary of options which will be
175
+ passed directly to the DBAPI's ``connect()`` method as
176
+ additional keyword arguments. See the example
177
+ at :ref:`custom_dbapi_args`.
178
+
179
+ :param creator: a callable which returns a DBAPI connection.
180
+ This creation function will be passed to the underlying
181
+ connection pool and will be used to create all new database
182
+ connections. Usage of this function causes connection
183
+ parameters specified in the URL argument to be bypassed.
184
+
185
+ This hook is not as flexible as the newer
186
+ :meth:`_events.DialectEvents.do_connect` hook which allows complete
187
+ control over how a connection is made to the database, given the full
188
+ set of URL arguments and state beforehand.
189
+
190
+ .. seealso::
191
+
192
+ :meth:`_events.DialectEvents.do_connect` - event hook that allows
193
+ full control over DBAPI connection mechanics.
194
+
195
+ :ref:`custom_dbapi_args`
196
+
197
+ :param echo=False: if True, the Engine will log all statements
198
+ as well as a ``repr()`` of their parameter lists to the default log
199
+ handler, which defaults to ``sys.stdout`` for output. If set to the
200
+ string ``"debug"``, result rows will be printed to the standard output
201
+ as well. The ``echo`` attribute of ``Engine`` can be modified at any
202
+ time to turn logging on and off; direct control of logging is also
203
+ available using the standard Python ``logging`` module.
204
+
205
+ .. seealso::
206
+
207
+ :ref:`dbengine_logging` - further detail on how to configure
208
+ logging.
209
+
210
+
211
+ :param echo_pool=False: if True, the connection pool will log
212
+ informational output such as when connections are invalidated
213
+ as well as when connections are recycled to the default log handler,
214
+ which defaults to ``sys.stdout`` for output. If set to the string
215
+ ``"debug"``, the logging will include pool checkouts and checkins.
216
+ Direct control of logging is also available using the standard Python
217
+ ``logging`` module.
218
+
219
+ .. seealso::
220
+
221
+ :ref:`dbengine_logging` - further detail on how to configure
222
+ logging.
223
+
224
+
225
+ :param empty_in_strategy: No longer used; SQLAlchemy now uses
226
+ "empty set" behavior for IN in all cases.
227
+
228
+ :param enable_from_linting: defaults to True. Will emit a warning
229
+ if a given SELECT statement is found to have un-linked FROM elements
230
+ which would cause a cartesian product.
231
+
232
+ .. versionadded:: 1.4
233
+
234
+ .. seealso::
235
+
236
+ :ref:`change_4737`
237
+
238
+ :param execution_options: Dictionary execution options which will
239
+ be applied to all connections. See
240
+ :meth:`~sqlalchemy.engine.Connection.execution_options`
241
+
242
+ :param future: Use the 2.0 style :class:`_engine.Engine` and
243
+ :class:`_engine.Connection` API.
244
+
245
+ As of SQLAlchemy 2.0, this parameter is present for backwards
246
+ compatibility only and must remain at its default value of ``True``.
247
+
248
+ The :paramref:`_sa.create_engine.future` parameter will be
249
+ deprecated in a subsequent 2.x release and eventually removed.
250
+
251
+ .. versionadded:: 1.4
252
+
253
+ .. versionchanged:: 2.0 All :class:`_engine.Engine` objects are
254
+ "future" style engines and there is no longer a ``future=False``
255
+ mode of operation.
256
+
257
+ .. seealso::
258
+
259
+ :ref:`migration_20_toplevel`
260
+
261
+ :param hide_parameters: Boolean, when set to True, SQL statement parameters
262
+ will not be displayed in INFO logging nor will they be formatted into
263
+ the string representation of :class:`.StatementError` objects.
264
+
265
+ .. versionadded:: 1.3.8
266
+
267
+ .. seealso::
268
+
269
+ :ref:`dbengine_logging` - further detail on how to configure
270
+ logging.
271
+
272
+ :param implicit_returning=True: Legacy parameter that may only be set
273
+ to True. In SQLAlchemy 2.0, this parameter does nothing. In order to
274
+ disable "implicit returning" for statements invoked by the ORM,
275
+ configure this on a per-table basis using the
276
+ :paramref:`.Table.implicit_returning` parameter.
277
+
278
+
279
+ :param insertmanyvalues_page_size: number of rows to format into an
280
+ INSERT statement when the statement uses "insertmanyvalues" mode, which is
281
+ a paged form of bulk insert that is used for many backends when using
282
+ :term:`executemany` execution typically in conjunction with RETURNING.
283
+ Defaults to 1000, but may also be subject to dialect-specific limiting
284
+ factors which may override this value on a per-statement basis.
285
+
286
+ .. versionadded:: 2.0
287
+
288
+ .. seealso::
289
+
290
+ :ref:`engine_insertmanyvalues`
291
+
292
+ :ref:`engine_insertmanyvalues_page_size`
293
+
294
+ :paramref:`_engine.Connection.execution_options.insertmanyvalues_page_size`
295
+
296
+ :param isolation_level: optional string name of an isolation level
297
+ which will be set on all new connections unconditionally.
298
+ Isolation levels are typically some subset of the string names
299
+ ``"SERIALIZABLE"``, ``"REPEATABLE READ"``,
300
+ ``"READ COMMITTED"``, ``"READ UNCOMMITTED"`` and ``"AUTOCOMMIT"``
301
+ based on backend.
302
+
303
+ The :paramref:`_sa.create_engine.isolation_level` parameter is
304
+ in contrast to the
305
+ :paramref:`.Connection.execution_options.isolation_level`
306
+ execution option, which may be set on an individual
307
+ :class:`.Connection`, as well as the same parameter passed to
308
+ :meth:`.Engine.execution_options`, where it may be used to create
309
+ multiple engines with different isolation levels that share a common
310
+ connection pool and dialect.
311
+
312
+ .. versionchanged:: 2.0 The
313
+ :paramref:`_sa.create_engine.isolation_level`
314
+ parameter has been generalized to work on all dialects which support
315
+ the concept of isolation level, and is provided as a more succinct,
316
+ up front configuration switch in contrast to the execution option
317
+ which is more of an ad-hoc programmatic option.
318
+
319
+ .. seealso::
320
+
321
+ :ref:`dbapi_autocommit`
322
+
323
+ :param json_deserializer: for dialects that support the
324
+ :class:`_types.JSON`
325
+ datatype, this is a Python callable that will convert a JSON string
326
+ to a Python object. By default, the Python ``json.loads`` function is
327
+ used.
328
+
329
+ .. versionchanged:: 1.3.7 The SQLite dialect renamed this from
330
+ ``_json_deserializer``.
331
+
332
+ :param json_serializer: for dialects that support the :class:`_types.JSON`
333
+ datatype, this is a Python callable that will render a given object
334
+ as JSON. By default, the Python ``json.dumps`` function is used.
335
+
336
+ .. versionchanged:: 1.3.7 The SQLite dialect renamed this from
337
+ ``_json_serializer``.
338
+
339
+
340
+ :param label_length=None: optional integer value which limits
341
+ the size of dynamically generated column labels to that many
342
+ characters. If less than 6, labels are generated as
343
+ "_(counter)". If ``None``, the value of
344
+ ``dialect.max_identifier_length``, which may be affected via the
345
+ :paramref:`_sa.create_engine.max_identifier_length` parameter,
346
+ is used instead. The value of
347
+ :paramref:`_sa.create_engine.label_length`
348
+ may not be larger than that of
349
+ :paramref:`_sa.create_engine.max_identfier_length`.
350
+
351
+ .. seealso::
352
+
353
+ :paramref:`_sa.create_engine.max_identifier_length`
354
+
355
+ :param logging_name: String identifier which will be used within
356
+ the "name" field of logging records generated within the
357
+ "sqlalchemy.engine" logger. Defaults to a hexstring of the
358
+ object's id.
359
+
360
+ .. seealso::
361
+
362
+ :ref:`dbengine_logging` - further detail on how to configure
363
+ logging.
364
+
365
+ :paramref:`_engine.Connection.execution_options.logging_token`
366
+
367
+ :param max_identifier_length: integer; override the max_identifier_length
368
+ determined by the dialect. if ``None`` or zero, has no effect. This
369
+ is the database's configured maximum number of characters that may be
370
+ used in a SQL identifier such as a table name, column name, or label
371
+ name. All dialects determine this value automatically, however in the
372
+ case of a new database version for which this value has changed but
373
+ SQLAlchemy's dialect has not been adjusted, the value may be passed
374
+ here.
375
+
376
+ .. versionadded:: 1.3.9
377
+
378
+ .. seealso::
379
+
380
+ :paramref:`_sa.create_engine.label_length`
381
+
382
+ :param max_overflow=10: the number of connections to allow in
383
+ connection pool "overflow", that is connections that can be
384
+ opened above and beyond the pool_size setting, which defaults
385
+ to five. this is only used with :class:`~sqlalchemy.pool.QueuePool`.
386
+
387
+ :param module=None: reference to a Python module object (the module
388
+ itself, not its string name). Specifies an alternate DBAPI module to
389
+ be used by the engine's dialect. Each sub-dialect references a
390
+ specific DBAPI which will be imported before first connect. This
391
+ parameter causes the import to be bypassed, and the given module to
392
+ be used instead. Can be used for testing of DBAPIs as well as to
393
+ inject "mock" DBAPI implementations into the :class:`_engine.Engine`.
394
+
395
+ :param paramstyle=None: The `paramstyle <https://legacy.python.org/dev/peps/pep-0249/#paramstyle>`_
396
+ to use when rendering bound parameters. This style defaults to the
397
+ one recommended by the DBAPI itself, which is retrieved from the
398
+ ``.paramstyle`` attribute of the DBAPI. However, most DBAPIs accept
399
+ more than one paramstyle, and in particular it may be desirable
400
+ to change a "named" paramstyle into a "positional" one, or vice versa.
401
+ When this attribute is passed, it should be one of the values
402
+ ``"qmark"``, ``"numeric"``, ``"named"``, ``"format"`` or
403
+ ``"pyformat"``, and should correspond to a parameter style known
404
+ to be supported by the DBAPI in use.
405
+
406
+ :param pool=None: an already-constructed instance of
407
+ :class:`~sqlalchemy.pool.Pool`, such as a
408
+ :class:`~sqlalchemy.pool.QueuePool` instance. If non-None, this
409
+ pool will be used directly as the underlying connection pool
410
+ for the engine, bypassing whatever connection parameters are
411
+ present in the URL argument. For information on constructing
412
+ connection pools manually, see :ref:`pooling_toplevel`.
413
+
414
+ :param poolclass=None: a :class:`~sqlalchemy.pool.Pool`
415
+ subclass, which will be used to create a connection pool
416
+ instance using the connection parameters given in the URL. Note
417
+ this differs from ``pool`` in that you don't actually
418
+ instantiate the pool in this case, you just indicate what type
419
+ of pool to be used.
420
+
421
+ :param pool_logging_name: String identifier which will be used within
422
+ the "name" field of logging records generated within the
423
+ "sqlalchemy.pool" logger. Defaults to a hexstring of the object's
424
+ id.
425
+
426
+ .. seealso::
427
+
428
+ :ref:`dbengine_logging` - further detail on how to configure
429
+ logging.
430
+
431
+ :param pool_pre_ping: boolean, if True will enable the connection pool
432
+ "pre-ping" feature that tests connections for liveness upon
433
+ each checkout.
434
+
435
+ .. versionadded:: 1.2
436
+
437
+ .. seealso::
438
+
439
+ :ref:`pool_disconnects_pessimistic`
440
+
441
+ :param pool_size=5: the number of connections to keep open
442
+ inside the connection pool. This used with
443
+ :class:`~sqlalchemy.pool.QueuePool` as
444
+ well as :class:`~sqlalchemy.pool.SingletonThreadPool`. With
445
+ :class:`~sqlalchemy.pool.QueuePool`, a ``pool_size`` setting
446
+ of 0 indicates no limit; to disable pooling, set ``poolclass`` to
447
+ :class:`~sqlalchemy.pool.NullPool` instead.
448
+
449
+ :param pool_recycle=-1: this setting causes the pool to recycle
450
+ connections after the given number of seconds has passed. It
451
+ defaults to -1, or no timeout. For example, setting to 3600
452
+ means connections will be recycled after one hour. Note that
453
+ MySQL in particular will disconnect automatically if no
454
+ activity is detected on a connection for eight hours (although
455
+ this is configurable with the MySQLDB connection itself and the
456
+ server configuration as well).
457
+
458
+ .. seealso::
459
+
460
+ :ref:`pool_setting_recycle`
461
+
462
+ :param pool_reset_on_return='rollback': set the
463
+ :paramref:`_pool.Pool.reset_on_return` parameter of the underlying
464
+ :class:`_pool.Pool` object, which can be set to the values
465
+ ``"rollback"``, ``"commit"``, or ``None``.
466
+
467
+ .. seealso::
468
+
469
+ :ref:`pool_reset_on_return`
470
+
471
+ :ref:`dbapi_autocommit_skip_rollback` - a more modern approach
472
+ to using connections with no transactional instructions
473
+
474
+ :param pool_timeout=30: number of seconds to wait before giving
475
+ up on getting a connection from the pool. This is only used
476
+ with :class:`~sqlalchemy.pool.QueuePool`. This can be a float but is
477
+ subject to the limitations of Python time functions which may not be
478
+ reliable in the tens of milliseconds.
479
+
480
+ .. note: don't use 30.0 above, it seems to break with the :param tag
481
+
482
+ :param pool_use_lifo=False: use LIFO (last-in-first-out) when retrieving
483
+ connections from :class:`.QueuePool` instead of FIFO
484
+ (first-in-first-out). Using LIFO, a server-side timeout scheme can
485
+ reduce the number of connections used during non- peak periods of
486
+ use. When planning for server-side timeouts, ensure that a recycle or
487
+ pre-ping strategy is in use to gracefully handle stale connections.
488
+
489
+ .. versionadded:: 1.3
490
+
491
+ .. seealso::
492
+
493
+ :ref:`pool_use_lifo`
494
+
495
+ :ref:`pool_disconnects`
496
+
497
+ :param plugins: string list of plugin names to load. See
498
+ :class:`.CreateEnginePlugin` for background.
499
+
500
+ .. versionadded:: 1.2.3
501
+
502
+ :param query_cache_size: size of the cache used to cache the SQL string
503
+ form of queries. Set to zero to disable caching.
504
+
505
+ The cache is pruned of its least recently used items when its size reaches
506
+ N * 1.5. Defaults to 500, meaning the cache will always store at least
507
+ 500 SQL statements when filled, and will grow up to 750 items at which
508
+ point it is pruned back down to 500 by removing the 250 least recently
509
+ used items.
510
+
511
+ Caching is accomplished on a per-statement basis by generating a
512
+ cache key that represents the statement's structure, then generating
513
+ string SQL for the current dialect only if that key is not present
514
+ in the cache. All statements support caching, however some features
515
+ such as an INSERT with a large set of parameters will intentionally
516
+ bypass the cache. SQL logging will indicate statistics for each
517
+ statement whether or not it were pull from the cache.
518
+
519
+ .. note:: some ORM functions related to unit-of-work persistence as well
520
+ as some attribute loading strategies will make use of individual
521
+ per-mapper caches outside of the main cache.
522
+
523
+
524
+ .. seealso::
525
+
526
+ :ref:`sql_caching`
527
+
528
+ .. versionadded:: 1.4
529
+
530
+ :param skip_autocommit_rollback: When True, the dialect will
531
+ unconditionally skip all calls to the DBAPI ``connection.rollback()``
532
+ method if the DBAPI connection is confirmed to be in "autocommit" mode.
533
+ The availability of this feature is dialect specific; if not available,
534
+ a ``NotImplementedError`` is raised by the dialect when rollback occurs.
535
+
536
+ .. seealso::
537
+
538
+ :ref:`dbapi_autocommit_skip_rollback`
539
+
540
+ .. versionadded:: 2.0.43
541
+
542
+ :param use_insertmanyvalues: True by default, use the "insertmanyvalues"
543
+ execution style for INSERT..RETURNING statements by default.
544
+
545
+ .. versionadded:: 2.0
546
+
547
+ .. seealso::
548
+
549
+ :ref:`engine_insertmanyvalues`
550
+
551
+ """ # noqa
552
+
553
+ if "strategy" in kwargs:
554
+ strat = kwargs.pop("strategy")
555
+ if strat == "mock":
556
+ # this case is deprecated
557
+ return create_mock_engine(url, **kwargs) # type: ignore
558
+ else:
559
+ raise exc.ArgumentError("unknown strategy: %r" % strat)
560
+
561
+ kwargs.pop("empty_in_strategy", None)
562
+
563
+ # create url.URL object
564
+ u = _url.make_url(url)
565
+
566
+ u, plugins, kwargs = u._instantiate_plugins(kwargs)
567
+
568
+ entrypoint = u._get_entrypoint()
569
+ _is_async = kwargs.pop("_is_async", False)
570
+ if _is_async:
571
+ dialect_cls = entrypoint.get_async_dialect_cls(u)
572
+ else:
573
+ dialect_cls = entrypoint.get_dialect_cls(u)
574
+
575
+ if kwargs.pop("_coerce_config", False):
576
+
577
+ def pop_kwarg(key: str, default: Optional[Any] = None) -> Any:
578
+ value = kwargs.pop(key, default)
579
+ if key in dialect_cls.engine_config_types:
580
+ value = dialect_cls.engine_config_types[key](value)
581
+ return value
582
+
583
+ else:
584
+ pop_kwarg = kwargs.pop # type: ignore
585
+
586
+ dialect_args = {}
587
+ # consume dialect arguments from kwargs
588
+ for k in util.get_cls_kwargs(dialect_cls):
589
+ if k in kwargs:
590
+ dialect_args[k] = pop_kwarg(k)
591
+
592
+ dbapi = kwargs.pop("module", None)
593
+ if dbapi is None:
594
+ dbapi_args = {}
595
+
596
+ if "import_dbapi" in dialect_cls.__dict__:
597
+ dbapi_meth = dialect_cls.import_dbapi
598
+
599
+ elif hasattr(dialect_cls, "dbapi") and inspect.ismethod(
600
+ dialect_cls.dbapi
601
+ ):
602
+ util.warn_deprecated(
603
+ "The dbapi() classmethod on dialect classes has been "
604
+ "renamed to import_dbapi(). Implement an import_dbapi() "
605
+ f"classmethod directly on class {dialect_cls} to remove this "
606
+ "warning; the old .dbapi() classmethod may be maintained for "
607
+ "backwards compatibility.",
608
+ "2.0",
609
+ )
610
+ dbapi_meth = dialect_cls.dbapi
611
+ else:
612
+ dbapi_meth = dialect_cls.import_dbapi
613
+
614
+ for k in util.get_func_kwargs(dbapi_meth):
615
+ if k in kwargs:
616
+ dbapi_args[k] = pop_kwarg(k)
617
+ dbapi = dbapi_meth(**dbapi_args)
618
+
619
+ dialect_args["dbapi"] = dbapi
620
+
621
+ dialect_args.setdefault("compiler_linting", compiler.NO_LINTING)
622
+ enable_from_linting = kwargs.pop("enable_from_linting", True)
623
+ if enable_from_linting:
624
+ dialect_args["compiler_linting"] ^= compiler.COLLECT_CARTESIAN_PRODUCTS
625
+
626
+ for plugin in plugins:
627
+ plugin.handle_dialect_kwargs(dialect_cls, dialect_args)
628
+
629
+ # create dialect
630
+ dialect = dialect_cls(**dialect_args)
631
+
632
+ # assemble connection arguments
633
+ (cargs_tup, _cparams) = dialect.create_connect_args(u)
634
+ cparams = util.immutabledict(_cparams).union(pop_kwarg("connect_args", {}))
635
+
636
+ if "async_fallback" in cparams and util.asbool(cparams["async_fallback"]):
637
+ util.warn_deprecated(
638
+ "The async_fallback dialect argument is deprecated and will be "
639
+ "removed in SQLAlchemy 2.1.",
640
+ "2.0",
641
+ )
642
+
643
+ # look for existing pool or create
644
+ pool = pop_kwarg("pool", None)
645
+ if pool is None:
646
+
647
+ def connect(
648
+ connection_record: Optional[ConnectionPoolEntry] = None,
649
+ ) -> DBAPIConnection:
650
+ if dialect._has_events:
651
+ mutable_cargs = list(cargs_tup)
652
+ mutable_cparams = dict(cparams)
653
+ for fn in dialect.dispatch.do_connect:
654
+ connection = cast(
655
+ DBAPIConnection,
656
+ fn(
657
+ dialect,
658
+ connection_record,
659
+ mutable_cargs,
660
+ mutable_cparams,
661
+ ),
662
+ )
663
+ if connection is not None:
664
+ return connection
665
+ return dialect.connect(*mutable_cargs, **mutable_cparams)
666
+ else:
667
+ return dialect.connect(*cargs_tup, **cparams)
668
+
669
+ creator = pop_kwarg("creator", connect)
670
+
671
+ poolclass = pop_kwarg("poolclass", None)
672
+ if poolclass is None:
673
+ poolclass = dialect.get_dialect_pool_class(u)
674
+ pool_args = {"dialect": dialect}
675
+
676
+ # consume pool arguments from kwargs, translating a few of
677
+ # the arguments
678
+ for k in util.get_cls_kwargs(poolclass):
679
+ tk = _pool_translate_kwargs.get(k, k)
680
+ if tk in kwargs:
681
+ pool_args[k] = pop_kwarg(tk)
682
+
683
+ for plugin in plugins:
684
+ plugin.handle_pool_kwargs(poolclass, pool_args)
685
+
686
+ pool = poolclass(creator, **pool_args)
687
+ else:
688
+ pool._dialect = dialect
689
+
690
+ if (
691
+ hasattr(pool, "_is_asyncio")
692
+ and pool._is_asyncio is not dialect.is_async
693
+ ):
694
+ raise exc.ArgumentError(
695
+ f"Pool class {pool.__class__.__name__} cannot be "
696
+ f"used with {'non-' if not dialect.is_async else ''}"
697
+ "asyncio engine",
698
+ code="pcls",
699
+ )
700
+
701
+ # create engine.
702
+ if not pop_kwarg("future", True):
703
+ raise exc.ArgumentError(
704
+ "The 'future' parameter passed to "
705
+ "create_engine() may only be set to True."
706
+ )
707
+
708
+ engineclass = base.Engine
709
+
710
+ engine_args = {}
711
+ for k in util.get_cls_kwargs(engineclass):
712
+ if k in kwargs:
713
+ engine_args[k] = pop_kwarg(k)
714
+
715
+ # internal flags used by the test suite for instrumenting / proxying
716
+ # engines with mocks etc.
717
+ _initialize = kwargs.pop("_initialize", True)
718
+
719
+ # all kwargs should be consumed
720
+ if kwargs:
721
+ raise TypeError(
722
+ "Invalid argument(s) %s sent to create_engine(), "
723
+ "using configuration %s/%s/%s. Please check that the "
724
+ "keyword arguments are appropriate for this combination "
725
+ "of components."
726
+ % (
727
+ ",".join("'%s'" % k for k in kwargs),
728
+ dialect.__class__.__name__,
729
+ pool.__class__.__name__,
730
+ engineclass.__name__,
731
+ )
732
+ )
733
+
734
+ engine = engineclass(pool, dialect, u, **engine_args)
735
+
736
+ if _initialize:
737
+ do_on_connect = dialect.on_connect_url(u)
738
+ if do_on_connect:
739
+
740
+ def on_connect(
741
+ dbapi_connection: DBAPIConnection,
742
+ connection_record: ConnectionPoolEntry,
743
+ ) -> None:
744
+ assert do_on_connect is not None
745
+ do_on_connect(dbapi_connection)
746
+
747
+ event.listen(pool, "connect", on_connect)
748
+
749
+ builtin_on_connect = dialect._builtin_onconnect()
750
+ if builtin_on_connect:
751
+ event.listen(pool, "connect", builtin_on_connect)
752
+
753
+ def first_connect(
754
+ dbapi_connection: DBAPIConnection,
755
+ connection_record: ConnectionPoolEntry,
756
+ ) -> None:
757
+ c = base.Connection(
758
+ engine,
759
+ connection=_AdhocProxiedConnection(
760
+ dbapi_connection, connection_record
761
+ ),
762
+ _has_events=False,
763
+ # reconnecting will be a reentrant condition, so if the
764
+ # connection goes away, Connection is then closed
765
+ _allow_revalidate=False,
766
+ # dont trigger the autobegin sequence
767
+ # within the up front dialect checks
768
+ _allow_autobegin=False,
769
+ )
770
+ c._execution_options = util.EMPTY_DICT
771
+
772
+ try:
773
+ dialect.initialize(c)
774
+ finally:
775
+ # note that "invalidated" and "closed" are mutually
776
+ # exclusive in 1.4 Connection.
777
+ if not c.invalidated and not c.closed:
778
+ # transaction is rolled back otherwise, tested by
779
+ # test/dialect/postgresql/test_dialect.py
780
+ # ::MiscBackendTest::test_initial_transaction_state
781
+ dialect.do_rollback(c.connection)
782
+
783
+ # previously, the "first_connect" event was used here, which was then
784
+ # scaled back if the "on_connect" handler were present. now,
785
+ # since "on_connect" is virtually always present, just use
786
+ # "connect" event with once_unless_exception in all cases so that
787
+ # the connection event flow is consistent in all cases.
788
+ event.listen(
789
+ pool, "connect", first_connect, _once_unless_exception=True
790
+ )
791
+
792
+ dialect_cls.engine_created(engine)
793
+ if entrypoint is not dialect_cls:
794
+ entrypoint.engine_created(engine)
795
+
796
+ for plugin in plugins:
797
+ plugin.engine_created(engine)
798
+
799
+ return engine
800
+
801
+
802
+ def engine_from_config(
803
+ configuration: Dict[str, Any], prefix: str = "sqlalchemy.", **kwargs: Any
804
+ ) -> Engine:
805
+ """Create a new Engine instance using a configuration dictionary.
806
+
807
+ The dictionary is typically produced from a config file.
808
+
809
+ The keys of interest to ``engine_from_config()`` should be prefixed, e.g.
810
+ ``sqlalchemy.url``, ``sqlalchemy.echo``, etc. The 'prefix' argument
811
+ indicates the prefix to be searched for. Each matching key (after the
812
+ prefix is stripped) is treated as though it were the corresponding keyword
813
+ argument to a :func:`_sa.create_engine` call.
814
+
815
+ The only required key is (assuming the default prefix) ``sqlalchemy.url``,
816
+ which provides the :ref:`database URL <database_urls>`.
817
+
818
+ A select set of keyword arguments will be "coerced" to their
819
+ expected type based on string values. The set of arguments
820
+ is extensible per-dialect using the ``engine_config_types`` accessor.
821
+
822
+ :param configuration: A dictionary (typically produced from a config file,
823
+ but this is not a requirement). Items whose keys start with the value
824
+ of 'prefix' will have that prefix stripped, and will then be passed to
825
+ :func:`_sa.create_engine`.
826
+
827
+ :param prefix: Prefix to match and then strip from keys
828
+ in 'configuration'.
829
+
830
+ :param kwargs: Each keyword argument to ``engine_from_config()`` itself
831
+ overrides the corresponding item taken from the 'configuration'
832
+ dictionary. Keyword arguments should *not* be prefixed.
833
+
834
+ """
835
+
836
+ options = {
837
+ key[len(prefix) :]: configuration[key]
838
+ for key in configuration
839
+ if key.startswith(prefix)
840
+ }
841
+ options["_coerce_config"] = True
842
+ options.update(kwargs)
843
+ url = options.pop("url")
844
+ return create_engine(url, **options)
845
+
846
+
847
+ @overload
848
+ def create_pool_from_url(
849
+ url: Union[str, URL],
850
+ *,
851
+ poolclass: Optional[Type[Pool]] = ...,
852
+ logging_name: str = ...,
853
+ pre_ping: bool = ...,
854
+ size: int = ...,
855
+ recycle: int = ...,
856
+ reset_on_return: Optional[_ResetStyleArgType] = ...,
857
+ timeout: float = ...,
858
+ use_lifo: bool = ...,
859
+ **kwargs: Any,
860
+ ) -> Pool: ...
861
+
862
+
863
+ @overload
864
+ def create_pool_from_url(url: Union[str, URL], **kwargs: Any) -> Pool: ...
865
+
866
+
867
+ def create_pool_from_url(url: Union[str, URL], **kwargs: Any) -> Pool:
868
+ """Create a pool instance from the given url.
869
+
870
+ If ``poolclass`` is not provided the pool class used
871
+ is selected using the dialect specified in the URL.
872
+
873
+ The arguments passed to :func:`_sa.create_pool_from_url` are
874
+ identical to the pool argument passed to the :func:`_sa.create_engine`
875
+ function.
876
+
877
+ .. versionadded:: 2.0.10
878
+ """
879
+
880
+ for key in _pool_translate_kwargs:
881
+ if key in kwargs:
882
+ kwargs[_pool_translate_kwargs[key]] = kwargs.pop(key)
883
+
884
+ engine = create_engine(url, **kwargs, _initialize=False)
885
+ return engine.pool
886
+
887
+
888
+ _pool_translate_kwargs = immutabledict(
889
+ {
890
+ "logging_name": "pool_logging_name",
891
+ "echo": "echo_pool",
892
+ "timeout": "pool_timeout",
893
+ "recycle": "pool_recycle",
894
+ "events": "pool_events", # deprecated
895
+ "reset_on_return": "pool_reset_on_return",
896
+ "pre_ping": "pool_pre_ping",
897
+ "use_lifo": "pool_use_lifo",
898
+ }
899
+ )
python/user_packages/Python313/site-packages/sqlalchemy/engine/cursor.py ADDED
@@ -0,0 +1,2303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # engine/cursor.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ """Define cursor-specific result set constructs including
9
+ :class:`.CursorResult`."""
10
+
11
+
12
+ from __future__ import annotations
13
+
14
+ import collections
15
+ import functools
16
+ import operator
17
+ import typing
18
+ from typing import Any
19
+ from typing import cast
20
+ from typing import ClassVar
21
+ from typing import Deque
22
+ from typing import Dict
23
+ from typing import Iterable
24
+ from typing import Iterator
25
+ from typing import List
26
+ from typing import Mapping
27
+ from typing import NoReturn
28
+ from typing import Optional
29
+ from typing import Sequence
30
+ from typing import Tuple
31
+ from typing import TYPE_CHECKING
32
+ from typing import TypeVar
33
+ from typing import Union
34
+
35
+ from .result import IteratorResult
36
+ from .result import MergedResult
37
+ from .result import Result
38
+ from .result import ResultMetaData
39
+ from .result import SimpleResultMetaData
40
+ from .result import tuplegetter
41
+ from .row import Row
42
+ from .. import exc
43
+ from .. import util
44
+ from ..sql import elements
45
+ from ..sql import sqltypes
46
+ from ..sql import util as sql_util
47
+ from ..sql.base import _generative
48
+ from ..sql.compiler import ResultColumnsEntry
49
+ from ..sql.compiler import RM_NAME
50
+ from ..sql.compiler import RM_OBJECTS
51
+ from ..sql.compiler import RM_RENDERED_NAME
52
+ from ..sql.compiler import RM_TYPE
53
+ from ..sql.type_api import TypeEngine
54
+ from ..util import compat
55
+ from ..util.typing import Final
56
+ from ..util.typing import Literal
57
+ from ..util.typing import Self
58
+
59
+
60
+ if typing.TYPE_CHECKING:
61
+ from .base import Connection
62
+ from .default import DefaultExecutionContext
63
+ from .interfaces import _DBAPICursorDescription
64
+ from .interfaces import _MutableCoreSingleExecuteParams
65
+ from .interfaces import CoreExecuteOptionsParameter
66
+ from .interfaces import DBAPICursor
67
+ from .interfaces import DBAPIType
68
+ from .interfaces import Dialect
69
+ from .interfaces import ExecutionContext
70
+ from .result import _KeyIndexType
71
+ from .result import _KeyMapRecType
72
+ from .result import _KeyMapType
73
+ from .result import _KeyType
74
+ from .result import _ProcessorsType
75
+ from .result import _TupleGetterType
76
+ from ..sql.schema import Column
77
+ from ..sql.type_api import _ResultProcessorType
78
+
79
+
80
+ _T = TypeVar("_T", bound=Any)
81
+ TupleAny = Tuple[Any, ...]
82
+
83
+ # metadata entry tuple indexes.
84
+ # using raw tuple is faster than namedtuple.
85
+ # these match up to the positions in
86
+ # _CursorKeyMapRecType
87
+ MD_INDEX: Final[Literal[0]] = 0
88
+ """integer index in cursor.description
89
+
90
+ """
91
+
92
+ MD_RESULT_MAP_INDEX: Final[Literal[1]] = 1
93
+ """integer index in compiled._result_columns"""
94
+
95
+ MD_OBJECTS: Final[Literal[2]] = 2
96
+ """other string keys and ColumnElement obj that can match.
97
+
98
+ This comes from compiler.RM_OBJECTS / compiler.ResultColumnsEntry.objects
99
+
100
+ """
101
+
102
+ MD_LOOKUP_KEY: Final[Literal[3]] = 3
103
+ """string key we usually expect for key-based lookup
104
+
105
+ this comes from compiler.RM_NAME / compiler.ResultColumnsEntry.name
106
+ """
107
+
108
+
109
+ MD_RENDERED_NAME: Final[Literal[4]] = 4
110
+ """name that is usually in cursor.description
111
+
112
+ this comes from compiler.RENDERED_NAME / compiler.ResultColumnsEntry.keyname
113
+ """
114
+
115
+
116
+ MD_PROCESSOR: Final[Literal[5]] = 5
117
+ """callable to process a result value into a row"""
118
+
119
+ MD_UNTRANSLATED: Final[Literal[6]] = 6
120
+ """raw name from cursor.description"""
121
+
122
+
123
+ _CursorKeyMapRecType = Tuple[
124
+ Optional[int], # MD_INDEX, None means the record is ambiguously named
125
+ int, # MD_RESULT_MAP_INDEX, -1 if MD_INDEX is None
126
+ TupleAny, # MD_OBJECTS
127
+ str, # MD_LOOKUP_KEY
128
+ str, # MD_RENDERED_NAME
129
+ Optional["_ResultProcessorType[Any]"], # MD_PROCESSOR
130
+ Optional[str], # MD_UNTRANSLATED
131
+ ]
132
+
133
+ _CursorKeyMapType = Mapping["_KeyType", _CursorKeyMapRecType]
134
+
135
+ # same as _CursorKeyMapRecType except the MD_INDEX value is definitely
136
+ # not None
137
+ _NonAmbigCursorKeyMapRecType = Tuple[
138
+ int,
139
+ int,
140
+ List[Any],
141
+ str,
142
+ str,
143
+ Optional["_ResultProcessorType[Any]"],
144
+ str,
145
+ ]
146
+
147
+ _MergeColTuple = Tuple[
148
+ int,
149
+ Optional[int],
150
+ str,
151
+ TypeEngine[Any],
152
+ "DBAPIType",
153
+ Optional[TupleAny],
154
+ Optional[str],
155
+ ]
156
+
157
+
158
+ class CursorResultMetaData(ResultMetaData):
159
+ """Result metadata for DBAPI cursors."""
160
+
161
+ __slots__ = (
162
+ "_keymap",
163
+ "_processors",
164
+ "_keys",
165
+ "_keymap_by_result_column_idx",
166
+ "_tuplefilter",
167
+ "_translated_indexes",
168
+ "_safe_for_cache",
169
+ "_unpickled",
170
+ "_key_to_index",
171
+ # don't need _unique_filters support here for now. Can be added
172
+ # if a need arises.
173
+ )
174
+
175
+ _keymap: _CursorKeyMapType
176
+ _processors: _ProcessorsType
177
+ _keymap_by_result_column_idx: Optional[Dict[int, _KeyMapRecType]]
178
+ _unpickled: bool
179
+ _safe_for_cache: bool
180
+ _translated_indexes: Optional[List[int]]
181
+
182
+ returns_rows: ClassVar[bool] = True
183
+
184
+ def _has_key(self, key: Any) -> bool:
185
+ return key in self._keymap
186
+
187
+ def _for_freeze(self) -> ResultMetaData:
188
+ return SimpleResultMetaData(
189
+ self._keys,
190
+ extra=[self._keymap[key][MD_OBJECTS] for key in self._keys],
191
+ )
192
+
193
+ def _make_new_metadata(
194
+ self,
195
+ *,
196
+ unpickled: bool,
197
+ processors: _ProcessorsType,
198
+ keys: Sequence[str],
199
+ keymap: _KeyMapType,
200
+ tuplefilter: Optional[_TupleGetterType],
201
+ translated_indexes: Optional[List[int]],
202
+ safe_for_cache: bool,
203
+ keymap_by_result_column_idx: Any,
204
+ ) -> CursorResultMetaData:
205
+ new_obj = self.__class__.__new__(self.__class__)
206
+ new_obj._unpickled = unpickled
207
+ new_obj._processors = processors
208
+ new_obj._keys = keys
209
+ new_obj._keymap = keymap
210
+ new_obj._tuplefilter = tuplefilter
211
+ new_obj._translated_indexes = translated_indexes
212
+ new_obj._safe_for_cache = safe_for_cache
213
+ new_obj._keymap_by_result_column_idx = keymap_by_result_column_idx
214
+ new_obj._key_to_index = self._make_key_to_index(keymap, MD_INDEX)
215
+ return new_obj
216
+
217
+ def _remove_processors(self) -> CursorResultMetaData:
218
+ assert not self._tuplefilter
219
+ return self._make_new_metadata(
220
+ unpickled=self._unpickled,
221
+ processors=[None] * len(self._processors),
222
+ tuplefilter=None,
223
+ translated_indexes=None,
224
+ keymap={
225
+ key: value[0:5] + (None,) + value[6:]
226
+ for key, value in self._keymap.items()
227
+ },
228
+ keys=self._keys,
229
+ safe_for_cache=self._safe_for_cache,
230
+ keymap_by_result_column_idx=self._keymap_by_result_column_idx,
231
+ )
232
+
233
+ def _splice_horizontally(
234
+ self, other: CursorResultMetaData
235
+ ) -> CursorResultMetaData:
236
+ assert not self._tuplefilter
237
+
238
+ keymap = dict(self._keymap)
239
+ offset = len(self._keys)
240
+
241
+ for key, value in other._keymap.items():
242
+ # int index should be None for ambiguous key
243
+ if value[MD_INDEX] is not None and key not in keymap:
244
+ md_index = value[MD_INDEX] + offset
245
+ md_object = value[MD_RESULT_MAP_INDEX] + offset
246
+ else:
247
+ md_index = None
248
+ md_object = -1
249
+ keymap[key] = (md_index, md_object, *value[2:])
250
+
251
+ return self._make_new_metadata(
252
+ unpickled=self._unpickled,
253
+ processors=self._processors + other._processors, # type: ignore
254
+ tuplefilter=None,
255
+ translated_indexes=None,
256
+ keys=self._keys + other._keys, # type: ignore
257
+ keymap=keymap,
258
+ safe_for_cache=self._safe_for_cache,
259
+ keymap_by_result_column_idx={
260
+ metadata_entry[MD_RESULT_MAP_INDEX]: metadata_entry
261
+ for metadata_entry in keymap.values()
262
+ },
263
+ )
264
+
265
+ def _reduce(self, keys: Sequence[_KeyIndexType]) -> ResultMetaData:
266
+ recs = list(self._metadata_for_keys(keys))
267
+
268
+ indexes = [rec[MD_INDEX] for rec in recs]
269
+ new_keys: List[str] = [rec[MD_LOOKUP_KEY] for rec in recs]
270
+
271
+ if self._translated_indexes:
272
+ indexes = [self._translated_indexes[idx] for idx in indexes]
273
+ tup = tuplegetter(*indexes)
274
+ new_recs = [(index,) + rec[1:] for index, rec in enumerate(recs)]
275
+
276
+ keymap = {rec[MD_LOOKUP_KEY]: rec for rec in new_recs}
277
+ # TODO: need unit test for:
278
+ # result = connection.execute("raw sql, no columns").scalars()
279
+ # without the "or ()" it's failing because MD_OBJECTS is None
280
+ keymap.update(
281
+ (e, new_rec)
282
+ for new_rec in new_recs
283
+ for e in new_rec[MD_OBJECTS] or ()
284
+ )
285
+
286
+ return self._make_new_metadata(
287
+ unpickled=self._unpickled,
288
+ processors=self._processors,
289
+ keys=new_keys,
290
+ tuplefilter=tup,
291
+ translated_indexes=indexes,
292
+ keymap=keymap, # type: ignore[arg-type]
293
+ safe_for_cache=self._safe_for_cache,
294
+ keymap_by_result_column_idx=self._keymap_by_result_column_idx,
295
+ )
296
+
297
+ def _adapt_to_context(self, context: ExecutionContext) -> ResultMetaData:
298
+ """When using a cached Compiled construct that has a _result_map,
299
+ for a new statement that used the cached Compiled, we need to ensure
300
+ the keymap has the Column objects from our new statement as keys.
301
+ So here we rewrite keymap with new entries for the new columns
302
+ as matched to those of the cached statement.
303
+
304
+ """
305
+
306
+ if not context.compiled or not context.compiled._result_columns:
307
+ return self
308
+
309
+ compiled_statement = context.compiled.statement
310
+ invoked_statement = context.invoked_statement
311
+
312
+ if TYPE_CHECKING:
313
+ assert isinstance(invoked_statement, elements.ClauseElement)
314
+
315
+ if compiled_statement is invoked_statement:
316
+ return self
317
+
318
+ assert invoked_statement is not None
319
+
320
+ # this is the most common path for Core statements when
321
+ # caching is used. In ORM use, this codepath is not really used
322
+ # as the _result_disable_adapt_to_context execution option is
323
+ # set by the ORM.
324
+
325
+ # make a copy and add the columns from the invoked statement
326
+ # to the result map.
327
+
328
+ keymap_by_position = self._keymap_by_result_column_idx
329
+
330
+ if keymap_by_position is None:
331
+ # first retrieval from cache, this map will not be set up yet,
332
+ # initialize lazily
333
+ keymap_by_position = self._keymap_by_result_column_idx = {
334
+ metadata_entry[MD_RESULT_MAP_INDEX]: metadata_entry
335
+ for metadata_entry in self._keymap.values()
336
+ }
337
+
338
+ assert not self._tuplefilter
339
+ return self._make_new_metadata(
340
+ keymap=compat.dict_union(
341
+ self._keymap,
342
+ {
343
+ new: keymap_by_position[idx]
344
+ for idx, new in enumerate(
345
+ invoked_statement._all_selected_columns
346
+ )
347
+ if idx in keymap_by_position
348
+ },
349
+ ),
350
+ unpickled=self._unpickled,
351
+ processors=self._processors,
352
+ tuplefilter=None,
353
+ translated_indexes=None,
354
+ keys=self._keys,
355
+ safe_for_cache=self._safe_for_cache,
356
+ keymap_by_result_column_idx=self._keymap_by_result_column_idx,
357
+ )
358
+
359
+ def __init__(
360
+ self,
361
+ parent: CursorResult[Any],
362
+ cursor_description: _DBAPICursorDescription,
363
+ ):
364
+ context = parent.context
365
+ self._tuplefilter = None
366
+ self._translated_indexes = None
367
+ self._safe_for_cache = self._unpickled = False
368
+
369
+ if context.result_column_struct:
370
+ (
371
+ result_columns,
372
+ cols_are_ordered,
373
+ textual_ordered,
374
+ ad_hoc_textual,
375
+ loose_column_name_matching,
376
+ ) = context.result_column_struct
377
+ num_ctx_cols = len(result_columns)
378
+ else:
379
+ result_columns = cols_are_ordered = ( # type: ignore
380
+ num_ctx_cols
381
+ ) = ad_hoc_textual = loose_column_name_matching = (
382
+ textual_ordered
383
+ ) = False
384
+
385
+ # merge cursor.description with the column info
386
+ # present in the compiled structure, if any
387
+ raw = self._merge_cursor_description(
388
+ context,
389
+ cursor_description,
390
+ result_columns,
391
+ num_ctx_cols,
392
+ cols_are_ordered,
393
+ textual_ordered,
394
+ ad_hoc_textual,
395
+ loose_column_name_matching,
396
+ )
397
+
398
+ # processors in key order which are used when building up
399
+ # a row
400
+ self._processors = [
401
+ metadata_entry[MD_PROCESSOR] for metadata_entry in raw
402
+ ]
403
+
404
+ # this is used when using this ResultMetaData in a Core-only cache
405
+ # retrieval context. it's initialized on first cache retrieval
406
+ # when the _result_disable_adapt_to_context execution option
407
+ # (which the ORM generally sets) is not set.
408
+ self._keymap_by_result_column_idx = None
409
+
410
+ # for compiled SQL constructs, copy additional lookup keys into
411
+ # the key lookup map, such as Column objects, labels,
412
+ # column keys and other names
413
+ if num_ctx_cols:
414
+ # keymap by primary string...
415
+ by_key: Dict[_KeyType, _CursorKeyMapRecType] = {
416
+ metadata_entry[MD_LOOKUP_KEY]: metadata_entry
417
+ for metadata_entry in raw
418
+ }
419
+
420
+ if len(by_key) != num_ctx_cols:
421
+ # if by-primary-string dictionary smaller than
422
+ # number of columns, assume we have dupes; (this check
423
+ # is also in place if string dictionary is bigger, as
424
+ # can occur when '*' was used as one of the compiled columns,
425
+ # which may or may not be suggestive of dupes), rewrite
426
+ # dupe records with "None" for index which results in
427
+ # ambiguous column exception when accessed.
428
+ #
429
+ # this is considered to be the less common case as it is not
430
+ # common to have dupe column keys in a SELECT statement.
431
+ #
432
+ # new in 1.4: get the complete set of all possible keys,
433
+ # strings, objects, whatever, that are dupes across two
434
+ # different records, first.
435
+ index_by_key: Dict[Any, Any] = {}
436
+ dupes = set()
437
+ for metadata_entry in raw:
438
+ for key in (metadata_entry[MD_RENDERED_NAME],) + (
439
+ metadata_entry[MD_OBJECTS] or ()
440
+ ):
441
+ idx = metadata_entry[MD_INDEX]
442
+ # if this key has been associated with more than one
443
+ # positional index, it's a dupe
444
+ if index_by_key.setdefault(key, idx) != idx:
445
+ dupes.add(key)
446
+
447
+ # then put everything we have into the keymap excluding only
448
+ # those keys that are dupes.
449
+ self._keymap = {
450
+ obj_elem: metadata_entry
451
+ for metadata_entry in raw
452
+ if metadata_entry[MD_OBJECTS]
453
+ for obj_elem in metadata_entry[MD_OBJECTS]
454
+ if obj_elem not in dupes
455
+ }
456
+
457
+ # then for the dupe keys, put the "ambiguous column"
458
+ # record into by_key.
459
+ by_key.update(
460
+ {
461
+ key: (None, -1, (), key, key, None, None)
462
+ for key in dupes
463
+ }
464
+ )
465
+
466
+ else:
467
+ # no dupes - copy secondary elements from compiled
468
+ # columns into self._keymap. this is the most common
469
+ # codepath for Core / ORM statement executions before the
470
+ # result metadata is cached
471
+ self._keymap = {
472
+ obj_elem: metadata_entry
473
+ for metadata_entry in raw
474
+ if metadata_entry[MD_OBJECTS]
475
+ for obj_elem in metadata_entry[MD_OBJECTS]
476
+ }
477
+ # update keymap with primary string names taking
478
+ # precedence
479
+ self._keymap.update(by_key)
480
+ else:
481
+ # no compiled objects to map, just create keymap by primary string
482
+ self._keymap = {
483
+ metadata_entry[MD_LOOKUP_KEY]: metadata_entry
484
+ for metadata_entry in raw
485
+ }
486
+
487
+ # update keymap with "translated" names. In SQLAlchemy this is a
488
+ # sqlite only thing, and in fact impacting only extremely old SQLite
489
+ # versions unlikely to be present in modern Python versions.
490
+ # however, the pyhive third party dialect is
491
+ # also using this hook, which means others still might use it as well.
492
+ # I dislike having this awkward hook here but as long as we need
493
+ # to use names in cursor.description in some cases we need to have
494
+ # some hook to accomplish this.
495
+ if not num_ctx_cols and context._translate_colname:
496
+ self._keymap.update(
497
+ {
498
+ metadata_entry[MD_UNTRANSLATED]: self._keymap[
499
+ metadata_entry[MD_LOOKUP_KEY]
500
+ ]
501
+ for metadata_entry in raw
502
+ if metadata_entry[MD_UNTRANSLATED]
503
+ }
504
+ )
505
+
506
+ self._key_to_index = self._make_key_to_index(self._keymap, MD_INDEX)
507
+
508
+ def _merge_cursor_description(
509
+ self,
510
+ context: DefaultExecutionContext,
511
+ cursor_description: _DBAPICursorDescription,
512
+ result_columns: Sequence[ResultColumnsEntry],
513
+ num_ctx_cols: int,
514
+ cols_are_ordered: bool,
515
+ textual_ordered: bool,
516
+ ad_hoc_textual: bool,
517
+ loose_column_name_matching: bool,
518
+ ) -> List[_CursorKeyMapRecType]:
519
+ """Merge a cursor.description with compiled result column information.
520
+
521
+ There are at least four separate strategies used here, selected
522
+ depending on the type of SQL construct used to start with.
523
+
524
+ The most common case is that of the compiled SQL expression construct,
525
+ which generated the column names present in the raw SQL string and
526
+ which has the identical number of columns as were reported by
527
+ cursor.description. In this case, we assume a 1-1 positional mapping
528
+ between the entries in cursor.description and the compiled object.
529
+ This is also the most performant case as we disregard extracting /
530
+ decoding the column names present in cursor.description since we
531
+ already have the desired name we generated in the compiled SQL
532
+ construct.
533
+
534
+ The next common case is that of the completely raw string SQL,
535
+ such as passed to connection.execute(). In this case we have no
536
+ compiled construct to work with, so we extract and decode the
537
+ names from cursor.description and index those as the primary
538
+ result row target keys.
539
+
540
+ The remaining fairly common case is that of the textual SQL
541
+ that includes at least partial column information; this is when
542
+ we use a :class:`_expression.TextualSelect` construct.
543
+ This construct may have
544
+ unordered or ordered column information. In the ordered case, we
545
+ merge the cursor.description and the compiled construct's information
546
+ positionally, and warn if there are additional description names
547
+ present, however we still decode the names in cursor.description
548
+ as we don't have a guarantee that the names in the columns match
549
+ on these. In the unordered case, we match names in cursor.description
550
+ to that of the compiled construct based on name matching.
551
+ In both of these cases, the cursor.description names and the column
552
+ expression objects and names are indexed as result row target keys.
553
+
554
+ The final case is much less common, where we have a compiled
555
+ non-textual SQL expression construct, but the number of columns
556
+ in cursor.description doesn't match what's in the compiled
557
+ construct. We make the guess here that there might be textual
558
+ column expressions in the compiled construct that themselves include
559
+ a comma in them causing them to split. We do the same name-matching
560
+ as with textual non-ordered columns.
561
+
562
+ The name-matched system of merging is the same as that used by
563
+ SQLAlchemy for all cases up through the 0.9 series. Positional
564
+ matching for compiled SQL expressions was introduced in 1.0 as a
565
+ major performance feature, and positional matching for textual
566
+ :class:`_expression.TextualSelect` objects in 1.1.
567
+ As name matching is no longer
568
+ a common case, it was acceptable to factor it into smaller generator-
569
+ oriented methods that are easier to understand, but incur slightly
570
+ more performance overhead.
571
+
572
+ """
573
+
574
+ if (
575
+ num_ctx_cols
576
+ and cols_are_ordered
577
+ and not textual_ordered
578
+ and num_ctx_cols == len(cursor_description)
579
+ ):
580
+ self._keys = [elem[0] for elem in result_columns]
581
+ # pure positional 1-1 case; doesn't need to read
582
+ # the names from cursor.description
583
+
584
+ # most common case for Core and ORM
585
+
586
+ # this metadata is safe to cache because we are guaranteed
587
+ # to have the columns in the same order for new executions
588
+ self._safe_for_cache = True
589
+ return [
590
+ (
591
+ idx,
592
+ idx,
593
+ rmap_entry[RM_OBJECTS],
594
+ rmap_entry[RM_NAME],
595
+ rmap_entry[RM_RENDERED_NAME],
596
+ context.get_result_processor(
597
+ rmap_entry[RM_TYPE],
598
+ rmap_entry[RM_RENDERED_NAME],
599
+ cursor_description[idx][1],
600
+ ),
601
+ None,
602
+ )
603
+ for idx, rmap_entry in enumerate(result_columns)
604
+ ]
605
+ else:
606
+ # name-based or text-positional cases, where we need
607
+ # to read cursor.description names
608
+
609
+ if textual_ordered or (
610
+ ad_hoc_textual and len(cursor_description) == num_ctx_cols
611
+ ):
612
+ self._safe_for_cache = True
613
+ # textual positional case
614
+ raw_iterator = self._merge_textual_cols_by_position(
615
+ context, cursor_description, result_columns
616
+ )
617
+ elif num_ctx_cols:
618
+ # compiled SQL with a mismatch of description cols
619
+ # vs. compiled cols, or textual w/ unordered columns
620
+ # the order of columns can change if the query is
621
+ # against a "select *", so not safe to cache
622
+ self._safe_for_cache = False
623
+ raw_iterator = self._merge_cols_by_name(
624
+ context,
625
+ cursor_description,
626
+ result_columns,
627
+ loose_column_name_matching,
628
+ )
629
+ else:
630
+ # no compiled SQL, just a raw string, order of columns
631
+ # can change for "select *"
632
+ self._safe_for_cache = False
633
+ raw_iterator = self._merge_cols_by_none(
634
+ context, cursor_description
635
+ )
636
+
637
+ return [
638
+ (
639
+ idx,
640
+ ridx,
641
+ obj,
642
+ cursor_colname,
643
+ cursor_colname,
644
+ context.get_result_processor(
645
+ mapped_type, cursor_colname, coltype
646
+ ),
647
+ untranslated,
648
+ ) # type: ignore[misc]
649
+ for (
650
+ idx,
651
+ ridx,
652
+ cursor_colname,
653
+ mapped_type,
654
+ coltype,
655
+ obj,
656
+ untranslated,
657
+ ) in raw_iterator
658
+ ]
659
+
660
+ def _colnames_from_description(
661
+ self,
662
+ context: DefaultExecutionContext,
663
+ cursor_description: _DBAPICursorDescription,
664
+ ) -> Iterator[Tuple[int, str, Optional[str], DBAPIType]]:
665
+ """Extract column names and data types from a cursor.description.
666
+
667
+ Applies unicode decoding, column translation, "normalization",
668
+ and case sensitivity rules to the names based on the dialect.
669
+
670
+ """
671
+
672
+ dialect = context.dialect
673
+ translate_colname = context._translate_colname
674
+ normalize_name = (
675
+ dialect.normalize_name if dialect.requires_name_normalize else None
676
+ )
677
+ untranslated = None
678
+
679
+ self._keys = []
680
+
681
+ for idx, rec in enumerate(cursor_description):
682
+ colname = rec[0]
683
+ coltype = rec[1]
684
+
685
+ if translate_colname:
686
+ colname, untranslated = translate_colname(colname)
687
+
688
+ if normalize_name:
689
+ colname = normalize_name(colname)
690
+
691
+ self._keys.append(colname)
692
+
693
+ yield idx, colname, untranslated, coltype
694
+
695
+ def _merge_textual_cols_by_position(
696
+ self,
697
+ context: DefaultExecutionContext,
698
+ cursor_description: _DBAPICursorDescription,
699
+ result_columns: Sequence[ResultColumnsEntry],
700
+ ) -> Iterator[_MergeColTuple]:
701
+ num_ctx_cols = len(result_columns)
702
+
703
+ if num_ctx_cols > len(cursor_description):
704
+ util.warn(
705
+ "Number of columns in textual SQL (%d) is "
706
+ "smaller than number of columns requested (%d)"
707
+ % (num_ctx_cols, len(cursor_description))
708
+ )
709
+ seen = set()
710
+
711
+ for (
712
+ idx,
713
+ colname,
714
+ untranslated,
715
+ coltype,
716
+ ) in self._colnames_from_description(context, cursor_description):
717
+ if idx < num_ctx_cols:
718
+ ctx_rec = result_columns[idx]
719
+ obj = ctx_rec[RM_OBJECTS]
720
+ ridx = idx
721
+ mapped_type = ctx_rec[RM_TYPE]
722
+ if obj[0] in seen:
723
+ raise exc.InvalidRequestError(
724
+ "Duplicate column expression requested "
725
+ "in textual SQL: %r" % obj[0]
726
+ )
727
+ seen.add(obj[0])
728
+ else:
729
+ mapped_type = sqltypes.NULLTYPE
730
+ obj = None
731
+ ridx = None
732
+ yield idx, ridx, colname, mapped_type, coltype, obj, untranslated
733
+
734
+ def _merge_cols_by_name(
735
+ self,
736
+ context: DefaultExecutionContext,
737
+ cursor_description: _DBAPICursorDescription,
738
+ result_columns: Sequence[ResultColumnsEntry],
739
+ loose_column_name_matching: bool,
740
+ ) -> Iterator[_MergeColTuple]:
741
+ match_map = self._create_description_match_map(
742
+ result_columns, loose_column_name_matching
743
+ )
744
+ mapped_type: TypeEngine[Any]
745
+
746
+ for (
747
+ idx,
748
+ colname,
749
+ untranslated,
750
+ coltype,
751
+ ) in self._colnames_from_description(context, cursor_description):
752
+ try:
753
+ ctx_rec = match_map[colname]
754
+ except KeyError:
755
+ mapped_type = sqltypes.NULLTYPE
756
+ obj = None
757
+ result_columns_idx = None
758
+ else:
759
+ obj = ctx_rec[1]
760
+ mapped_type = ctx_rec[2]
761
+ result_columns_idx = ctx_rec[3]
762
+ yield (
763
+ idx,
764
+ result_columns_idx,
765
+ colname,
766
+ mapped_type,
767
+ coltype,
768
+ obj,
769
+ untranslated,
770
+ )
771
+
772
+ @classmethod
773
+ def _create_description_match_map(
774
+ cls,
775
+ result_columns: Sequence[ResultColumnsEntry],
776
+ loose_column_name_matching: bool = False,
777
+ ) -> Dict[Union[str, object], Tuple[str, TupleAny, TypeEngine[Any], int]]:
778
+ """when matching cursor.description to a set of names that are present
779
+ in a Compiled object, as is the case with TextualSelect, get all the
780
+ names we expect might match those in cursor.description.
781
+ """
782
+
783
+ d: Dict[
784
+ Union[str, object],
785
+ Tuple[str, TupleAny, TypeEngine[Any], int],
786
+ ] = {}
787
+ for ridx, elem in enumerate(result_columns):
788
+ key = elem[RM_RENDERED_NAME]
789
+ if key in d:
790
+ # conflicting keyname - just add the column-linked objects
791
+ # to the existing record. if there is a duplicate column
792
+ # name in the cursor description, this will allow all of those
793
+ # objects to raise an ambiguous column error
794
+ e_name, e_obj, e_type, e_ridx = d[key]
795
+ d[key] = e_name, e_obj + elem[RM_OBJECTS], e_type, ridx
796
+ else:
797
+ d[key] = (elem[RM_NAME], elem[RM_OBJECTS], elem[RM_TYPE], ridx)
798
+
799
+ if loose_column_name_matching:
800
+ # when using a textual statement with an unordered set
801
+ # of columns that line up, we are expecting the user
802
+ # to be using label names in the SQL that match to the column
803
+ # expressions. Enable more liberal matching for this case;
804
+ # duplicate keys that are ambiguous will be fixed later.
805
+ for r_key in elem[RM_OBJECTS]:
806
+ d.setdefault(
807
+ r_key,
808
+ (elem[RM_NAME], elem[RM_OBJECTS], elem[RM_TYPE], ridx),
809
+ )
810
+ return d
811
+
812
+ def _merge_cols_by_none(
813
+ self,
814
+ context: DefaultExecutionContext,
815
+ cursor_description: _DBAPICursorDescription,
816
+ ) -> Iterator[_MergeColTuple]:
817
+ self._keys = []
818
+
819
+ for (
820
+ idx,
821
+ colname,
822
+ untranslated,
823
+ coltype,
824
+ ) in self._colnames_from_description(context, cursor_description):
825
+ yield (
826
+ idx,
827
+ None,
828
+ colname,
829
+ sqltypes.NULLTYPE,
830
+ coltype,
831
+ None,
832
+ untranslated,
833
+ )
834
+
835
+ if not TYPE_CHECKING:
836
+
837
+ def _key_fallback(
838
+ self, key: Any, err: Optional[Exception], raiseerr: bool = True
839
+ ) -> Optional[NoReturn]:
840
+ if raiseerr:
841
+ if self._unpickled and isinstance(key, elements.ColumnElement):
842
+ raise exc.NoSuchColumnError(
843
+ "Row was unpickled; lookup by ColumnElement "
844
+ "is unsupported"
845
+ ) from err
846
+ else:
847
+ raise exc.NoSuchColumnError(
848
+ "Could not locate column in row for column '%s'"
849
+ % util.string_or_unprintable(key)
850
+ ) from err
851
+ else:
852
+ return None
853
+
854
+ def _raise_for_ambiguous_column_name(
855
+ self, rec: _KeyMapRecType
856
+ ) -> NoReturn:
857
+ raise exc.InvalidRequestError(
858
+ "Ambiguous column name '%s' in "
859
+ "result set column descriptions" % rec[MD_LOOKUP_KEY]
860
+ )
861
+
862
+ def _index_for_key(
863
+ self, key: _KeyIndexType, raiseerr: bool = True
864
+ ) -> Optional[int]:
865
+ # TODO: can consider pre-loading ints and negative ints
866
+ # into _keymap - also no coverage here
867
+ if isinstance(key, int):
868
+ key = self._keys[key]
869
+
870
+ try:
871
+ rec = self._keymap[key]
872
+ except KeyError as ke:
873
+ x = self._key_fallback(key, ke, raiseerr)
874
+ assert x is None
875
+ return None
876
+
877
+ index = rec[0]
878
+
879
+ if index is None:
880
+ self._raise_for_ambiguous_column_name(rec)
881
+ return index
882
+
883
+ def _indexes_for_keys(
884
+ self, keys: Sequence[_KeyIndexType]
885
+ ) -> Sequence[int]:
886
+ try:
887
+ return [self._keymap[key][0] for key in keys] # type: ignore[index,misc] # noqa: E501
888
+ except KeyError as ke:
889
+ # ensure it raises
890
+ CursorResultMetaData._key_fallback(self, ke.args[0], ke)
891
+
892
+ def _metadata_for_keys(
893
+ self, keys: Sequence[_KeyIndexType]
894
+ ) -> Iterator[_NonAmbigCursorKeyMapRecType]:
895
+ for key in keys:
896
+ if int in key.__class__.__mro__:
897
+ key = self._keys[key] # type: ignore[index]
898
+
899
+ try:
900
+ rec = self._keymap[key] # type: ignore[index]
901
+ except KeyError as ke:
902
+ # ensure it raises
903
+ CursorResultMetaData._key_fallback(self, ke.args[0], ke)
904
+
905
+ index = rec[MD_INDEX]
906
+
907
+ if index is None:
908
+ self._raise_for_ambiguous_column_name(rec)
909
+
910
+ yield cast(_NonAmbigCursorKeyMapRecType, rec)
911
+
912
+ def __getstate__(self) -> Dict[str, Any]:
913
+ # TODO: consider serializing this as SimpleResultMetaData
914
+ return {
915
+ "_keymap": {
916
+ key: (
917
+ rec[MD_INDEX],
918
+ rec[MD_RESULT_MAP_INDEX],
919
+ [],
920
+ key,
921
+ rec[MD_RENDERED_NAME],
922
+ None,
923
+ None,
924
+ )
925
+ for key, rec in self._keymap.items()
926
+ if isinstance(key, (str, int))
927
+ },
928
+ "_keys": self._keys,
929
+ "_translated_indexes": self._translated_indexes,
930
+ }
931
+
932
+ def __setstate__(self, state: Dict[str, Any]) -> None:
933
+ self._processors = [None for _ in range(len(state["_keys"]))]
934
+ self._keymap = state["_keymap"]
935
+ self._keymap_by_result_column_idx = None
936
+ self._key_to_index = self._make_key_to_index(self._keymap, MD_INDEX)
937
+ self._keys = state["_keys"]
938
+ self._unpickled = True
939
+ if state["_translated_indexes"]:
940
+ self._translated_indexes = cast(
941
+ "List[int]", state["_translated_indexes"]
942
+ )
943
+ self._tuplefilter = tuplegetter(*self._translated_indexes)
944
+ else:
945
+ self._translated_indexes = self._tuplefilter = None
946
+
947
+
948
+ class ResultFetchStrategy:
949
+ """Define a fetching strategy for a result object.
950
+
951
+
952
+ .. versionadded:: 1.4
953
+
954
+ """
955
+
956
+ __slots__ = ()
957
+
958
+ alternate_cursor_description: Optional[_DBAPICursorDescription] = None
959
+
960
+ def soft_close(
961
+ self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
962
+ ) -> None:
963
+ raise NotImplementedError()
964
+
965
+ def hard_close(
966
+ self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
967
+ ) -> None:
968
+ raise NotImplementedError()
969
+
970
+ def yield_per(
971
+ self,
972
+ result: CursorResult[Any],
973
+ dbapi_cursor: DBAPICursor,
974
+ num: int,
975
+ ) -> None:
976
+ return
977
+
978
+ def fetchone(
979
+ self,
980
+ result: CursorResult[Any],
981
+ dbapi_cursor: DBAPICursor,
982
+ hard_close: bool = False,
983
+ ) -> Any:
984
+ raise NotImplementedError()
985
+
986
+ def fetchmany(
987
+ self,
988
+ result: CursorResult[Any],
989
+ dbapi_cursor: DBAPICursor,
990
+ size: Optional[int] = None,
991
+ ) -> Any:
992
+ raise NotImplementedError()
993
+
994
+ def fetchall(
995
+ self,
996
+ result: CursorResult[Any],
997
+ dbapi_cursor: DBAPICursor,
998
+ ) -> Any:
999
+ raise NotImplementedError()
1000
+
1001
+ def handle_exception(
1002
+ self,
1003
+ result: CursorResult[Any],
1004
+ dbapi_cursor: Optional[DBAPICursor],
1005
+ err: BaseException,
1006
+ ) -> NoReturn:
1007
+ raise err
1008
+
1009
+
1010
+ class NoCursorFetchStrategy(ResultFetchStrategy):
1011
+ """Cursor strategy for a result that has no open cursor.
1012
+
1013
+ There are two varieties of this strategy, one for DQL and one for
1014
+ DML (and also DDL), each of which represent a result that had a cursor
1015
+ but no longer has one.
1016
+
1017
+ """
1018
+
1019
+ __slots__ = ()
1020
+
1021
+ def soft_close(
1022
+ self,
1023
+ result: CursorResult[Any],
1024
+ dbapi_cursor: Optional[DBAPICursor],
1025
+ ) -> None:
1026
+ pass
1027
+
1028
+ def hard_close(
1029
+ self,
1030
+ result: CursorResult[Any],
1031
+ dbapi_cursor: Optional[DBAPICursor],
1032
+ ) -> None:
1033
+ pass
1034
+
1035
+ def fetchone(
1036
+ self,
1037
+ result: CursorResult[Any],
1038
+ dbapi_cursor: DBAPICursor,
1039
+ hard_close: bool = False,
1040
+ ) -> Any:
1041
+ return self._non_result(result, None)
1042
+
1043
+ def fetchmany(
1044
+ self,
1045
+ result: CursorResult[Any],
1046
+ dbapi_cursor: DBAPICursor,
1047
+ size: Optional[int] = None,
1048
+ ) -> Any:
1049
+ return self._non_result(result, [])
1050
+
1051
+ def fetchall(
1052
+ self, result: CursorResult[Any], dbapi_cursor: DBAPICursor
1053
+ ) -> Any:
1054
+ return self._non_result(result, [])
1055
+
1056
+ def _non_result(
1057
+ self,
1058
+ result: CursorResult[Any],
1059
+ default: Any,
1060
+ err: Optional[BaseException] = None,
1061
+ ) -> Any:
1062
+ raise NotImplementedError()
1063
+
1064
+
1065
+ class NoCursorDQLFetchStrategy(NoCursorFetchStrategy):
1066
+ """Cursor strategy for a DQL result that has no open cursor.
1067
+
1068
+ This is a result set that can return rows, i.e. for a SELECT, or for an
1069
+ INSERT, UPDATE, DELETE that includes RETURNING. However it is in the state
1070
+ where the cursor is closed and no rows remain available. The owning result
1071
+ object may or may not be "hard closed", which determines if the fetch
1072
+ methods send empty results or raise for closed result.
1073
+
1074
+ """
1075
+
1076
+ __slots__ = ()
1077
+
1078
+ def _non_result(
1079
+ self,
1080
+ result: CursorResult[Any],
1081
+ default: Any,
1082
+ err: Optional[BaseException] = None,
1083
+ ) -> Any:
1084
+ if result.closed:
1085
+ raise exc.ResourceClosedError(
1086
+ "This result object is closed."
1087
+ ) from err
1088
+ else:
1089
+ return default
1090
+
1091
+
1092
+ _NO_CURSOR_DQL = NoCursorDQLFetchStrategy()
1093
+
1094
+
1095
+ class NoCursorDMLFetchStrategy(NoCursorFetchStrategy):
1096
+ """Cursor strategy for a DML result that has no open cursor.
1097
+
1098
+ This is a result set that does not return rows, i.e. for an INSERT,
1099
+ UPDATE, DELETE that does not include RETURNING.
1100
+
1101
+ """
1102
+
1103
+ __slots__ = ()
1104
+
1105
+ def _non_result(
1106
+ self,
1107
+ result: CursorResult[Any],
1108
+ default: Any,
1109
+ err: Optional[BaseException] = None,
1110
+ ) -> Any:
1111
+ # we only expect to have a _NoResultMetaData() here right now.
1112
+ assert not result._metadata.returns_rows
1113
+ result._metadata._we_dont_return_rows(err) # type: ignore[union-attr]
1114
+
1115
+
1116
+ _NO_CURSOR_DML = NoCursorDMLFetchStrategy()
1117
+
1118
+
1119
+ class CursorFetchStrategy(ResultFetchStrategy):
1120
+ """Call fetch methods from a DBAPI cursor.
1121
+
1122
+ Alternate versions of this class may instead buffer the rows from
1123
+ cursors or not use cursors at all.
1124
+
1125
+ """
1126
+
1127
+ __slots__ = ()
1128
+
1129
+ def soft_close(
1130
+ self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
1131
+ ) -> None:
1132
+ result.cursor_strategy = _NO_CURSOR_DQL
1133
+
1134
+ def hard_close(
1135
+ self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
1136
+ ) -> None:
1137
+ result.cursor_strategy = _NO_CURSOR_DQL
1138
+
1139
+ def handle_exception(
1140
+ self,
1141
+ result: CursorResult[Any],
1142
+ dbapi_cursor: Optional[DBAPICursor],
1143
+ err: BaseException,
1144
+ ) -> NoReturn:
1145
+ result.connection._handle_dbapi_exception(
1146
+ err, None, None, dbapi_cursor, result.context
1147
+ )
1148
+
1149
+ def yield_per(
1150
+ self, result: CursorResult[Any], dbapi_cursor: DBAPICursor, num: int
1151
+ ) -> None:
1152
+ result.cursor_strategy = BufferedRowCursorFetchStrategy(
1153
+ dbapi_cursor,
1154
+ {"max_row_buffer": num},
1155
+ initial_buffer=collections.deque(),
1156
+ growth_factor=0,
1157
+ )
1158
+
1159
+ def fetchone(
1160
+ self,
1161
+ result: CursorResult[Any],
1162
+ dbapi_cursor: DBAPICursor,
1163
+ hard_close: bool = False,
1164
+ ) -> Any:
1165
+ try:
1166
+ row = dbapi_cursor.fetchone()
1167
+ if row is None:
1168
+ result._soft_close(hard=hard_close)
1169
+ return row
1170
+ except BaseException as e:
1171
+ self.handle_exception(result, dbapi_cursor, e)
1172
+
1173
+ def fetchmany(
1174
+ self,
1175
+ result: CursorResult[Any],
1176
+ dbapi_cursor: DBAPICursor,
1177
+ size: Optional[int] = None,
1178
+ ) -> Any:
1179
+ try:
1180
+ if size is None:
1181
+ l = dbapi_cursor.fetchmany()
1182
+ else:
1183
+ l = dbapi_cursor.fetchmany(size)
1184
+
1185
+ if not l:
1186
+ result._soft_close()
1187
+ return l
1188
+ except BaseException as e:
1189
+ self.handle_exception(result, dbapi_cursor, e)
1190
+
1191
+ def fetchall(
1192
+ self,
1193
+ result: CursorResult[Any],
1194
+ dbapi_cursor: DBAPICursor,
1195
+ ) -> Any:
1196
+ try:
1197
+ rows = dbapi_cursor.fetchall()
1198
+ result._soft_close()
1199
+ return rows
1200
+ except BaseException as e:
1201
+ self.handle_exception(result, dbapi_cursor, e)
1202
+
1203
+
1204
+ _DEFAULT_FETCH = CursorFetchStrategy()
1205
+
1206
+
1207
+ class BufferedRowCursorFetchStrategy(CursorFetchStrategy):
1208
+ """A cursor fetch strategy with row buffering behavior.
1209
+
1210
+ This strategy buffers the contents of a selection of rows
1211
+ before ``fetchone()`` is called. This is to allow the results of
1212
+ ``cursor.description`` to be available immediately, when
1213
+ interfacing with a DB-API that requires rows to be consumed before
1214
+ this information is available (currently psycopg2, when used with
1215
+ server-side cursors).
1216
+
1217
+ The pre-fetching behavior fetches only one row initially, and then
1218
+ grows its buffer size by a fixed amount with each successive need
1219
+ for additional rows up the ``max_row_buffer`` size, which defaults
1220
+ to 1000::
1221
+
1222
+ with psycopg2_engine.connect() as conn:
1223
+
1224
+ result = conn.execution_options(
1225
+ stream_results=True, max_row_buffer=50
1226
+ ).execute(text("select * from table"))
1227
+
1228
+ .. versionadded:: 1.4 ``max_row_buffer`` may now exceed 1000 rows.
1229
+
1230
+ .. seealso::
1231
+
1232
+ :ref:`psycopg2_execution_options`
1233
+ """
1234
+
1235
+ __slots__ = ("_max_row_buffer", "_rowbuffer", "_bufsize", "_growth_factor")
1236
+
1237
+ def __init__(
1238
+ self,
1239
+ dbapi_cursor: DBAPICursor,
1240
+ execution_options: CoreExecuteOptionsParameter,
1241
+ growth_factor: int = 5,
1242
+ initial_buffer: Optional[Deque[Any]] = None,
1243
+ ) -> None:
1244
+ self._max_row_buffer = execution_options.get("max_row_buffer", 1000)
1245
+
1246
+ if initial_buffer is not None:
1247
+ self._rowbuffer = initial_buffer
1248
+ else:
1249
+ self._rowbuffer = collections.deque(dbapi_cursor.fetchmany(1))
1250
+ self._growth_factor = growth_factor
1251
+
1252
+ if growth_factor:
1253
+ self._bufsize = min(self._max_row_buffer, self._growth_factor)
1254
+ else:
1255
+ self._bufsize = self._max_row_buffer
1256
+
1257
+ @classmethod
1258
+ def create(
1259
+ cls, result: CursorResult[Any]
1260
+ ) -> BufferedRowCursorFetchStrategy:
1261
+ return BufferedRowCursorFetchStrategy(
1262
+ result.cursor,
1263
+ result.context.execution_options,
1264
+ )
1265
+
1266
+ def _buffer_rows(
1267
+ self, result: CursorResult[Any], dbapi_cursor: DBAPICursor
1268
+ ) -> None:
1269
+ """this is currently used only by fetchone()."""
1270
+
1271
+ size = self._bufsize
1272
+ try:
1273
+ if size < 1:
1274
+ new_rows = dbapi_cursor.fetchall()
1275
+ else:
1276
+ new_rows = dbapi_cursor.fetchmany(size)
1277
+ except BaseException as e:
1278
+ self.handle_exception(result, dbapi_cursor, e)
1279
+
1280
+ if not new_rows:
1281
+ return
1282
+ self._rowbuffer = collections.deque(new_rows)
1283
+ if self._growth_factor and size < self._max_row_buffer:
1284
+ self._bufsize = min(
1285
+ self._max_row_buffer, size * self._growth_factor
1286
+ )
1287
+
1288
+ def yield_per(
1289
+ self, result: CursorResult[Any], dbapi_cursor: DBAPICursor, num: int
1290
+ ) -> None:
1291
+ self._growth_factor = 0
1292
+ self._max_row_buffer = self._bufsize = num
1293
+
1294
+ def soft_close(
1295
+ self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
1296
+ ) -> None:
1297
+ self._rowbuffer.clear()
1298
+ super().soft_close(result, dbapi_cursor)
1299
+
1300
+ def hard_close(
1301
+ self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
1302
+ ) -> None:
1303
+ self._rowbuffer.clear()
1304
+ super().hard_close(result, dbapi_cursor)
1305
+
1306
+ def fetchone(
1307
+ self,
1308
+ result: CursorResult[Any],
1309
+ dbapi_cursor: DBAPICursor,
1310
+ hard_close: bool = False,
1311
+ ) -> Any:
1312
+ if not self._rowbuffer:
1313
+ self._buffer_rows(result, dbapi_cursor)
1314
+ if not self._rowbuffer:
1315
+ try:
1316
+ result._soft_close(hard=hard_close)
1317
+ except BaseException as e:
1318
+ self.handle_exception(result, dbapi_cursor, e)
1319
+ return None
1320
+ return self._rowbuffer.popleft()
1321
+
1322
+ def fetchmany(
1323
+ self,
1324
+ result: CursorResult[Any],
1325
+ dbapi_cursor: DBAPICursor,
1326
+ size: Optional[int] = None,
1327
+ ) -> Any:
1328
+ if size is None:
1329
+ return self.fetchall(result, dbapi_cursor)
1330
+
1331
+ rb = self._rowbuffer
1332
+ lb = len(rb)
1333
+ close = False
1334
+ if size > lb:
1335
+ try:
1336
+ new = dbapi_cursor.fetchmany(size - lb)
1337
+ except BaseException as e:
1338
+ self.handle_exception(result, dbapi_cursor, e)
1339
+ else:
1340
+ if not new:
1341
+ # defer closing since it may clear the row buffer
1342
+ close = True
1343
+ else:
1344
+ rb.extend(new)
1345
+
1346
+ res = [rb.popleft() for _ in range(min(size, len(rb)))]
1347
+ if close:
1348
+ result._soft_close()
1349
+ return res
1350
+
1351
+ def fetchall(
1352
+ self, result: CursorResult[Any], dbapi_cursor: DBAPICursor
1353
+ ) -> Any:
1354
+ try:
1355
+ ret = list(self._rowbuffer) + list(dbapi_cursor.fetchall())
1356
+ self._rowbuffer.clear()
1357
+ result._soft_close()
1358
+ return ret
1359
+ except BaseException as e:
1360
+ self.handle_exception(result, dbapi_cursor, e)
1361
+
1362
+
1363
+ class FullyBufferedCursorFetchStrategy(CursorFetchStrategy):
1364
+ """A cursor strategy that buffers rows fully upon creation.
1365
+
1366
+ Used for operations where a result is to be delivered
1367
+ after the database conversation can not be continued,
1368
+ such as MSSQL INSERT...OUTPUT after an autocommit.
1369
+
1370
+ """
1371
+
1372
+ __slots__ = ("_rowbuffer", "alternate_cursor_description")
1373
+
1374
+ def __init__(
1375
+ self,
1376
+ dbapi_cursor: Optional[DBAPICursor],
1377
+ alternate_description: Optional[_DBAPICursorDescription] = None,
1378
+ initial_buffer: Optional[Iterable[Any]] = None,
1379
+ ):
1380
+ self.alternate_cursor_description = alternate_description
1381
+ if initial_buffer is not None:
1382
+ self._rowbuffer = collections.deque(initial_buffer)
1383
+ else:
1384
+ assert dbapi_cursor is not None
1385
+ self._rowbuffer = collections.deque(dbapi_cursor.fetchall())
1386
+
1387
+ def yield_per(
1388
+ self, result: CursorResult[Any], dbapi_cursor: DBAPICursor, num: int
1389
+ ) -> Any:
1390
+ pass
1391
+
1392
+ def soft_close(
1393
+ self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
1394
+ ) -> None:
1395
+ self._rowbuffer.clear()
1396
+ super().soft_close(result, dbapi_cursor)
1397
+
1398
+ def hard_close(
1399
+ self, result: CursorResult[Any], dbapi_cursor: Optional[DBAPICursor]
1400
+ ) -> None:
1401
+ self._rowbuffer.clear()
1402
+ super().hard_close(result, dbapi_cursor)
1403
+
1404
+ def fetchone(
1405
+ self,
1406
+ result: CursorResult[Any],
1407
+ dbapi_cursor: DBAPICursor,
1408
+ hard_close: bool = False,
1409
+ ) -> Any:
1410
+ if self._rowbuffer:
1411
+ return self._rowbuffer.popleft()
1412
+ else:
1413
+ result._soft_close(hard=hard_close)
1414
+ return None
1415
+
1416
+ def fetchmany(
1417
+ self,
1418
+ result: CursorResult[Any],
1419
+ dbapi_cursor: DBAPICursor,
1420
+ size: Optional[int] = None,
1421
+ ) -> Any:
1422
+ if size is None:
1423
+ return self.fetchall(result, dbapi_cursor)
1424
+
1425
+ rb = self._rowbuffer
1426
+ rows = [rb.popleft() for _ in range(min(size, len(rb)))]
1427
+ if not rows:
1428
+ result._soft_close()
1429
+ return rows
1430
+
1431
+ def fetchall(
1432
+ self, result: CursorResult[Any], dbapi_cursor: DBAPICursor
1433
+ ) -> Any:
1434
+ ret = self._rowbuffer
1435
+ self._rowbuffer = collections.deque()
1436
+ result._soft_close()
1437
+ return ret
1438
+
1439
+
1440
+ class _NoResultMetaData(ResultMetaData):
1441
+ __slots__ = ()
1442
+
1443
+ returns_rows = False
1444
+
1445
+ def _we_dont_return_rows(
1446
+ self, err: Optional[BaseException] = None
1447
+ ) -> NoReturn:
1448
+ raise exc.ResourceClosedError(
1449
+ "This result object does not return rows. "
1450
+ "It has been closed automatically."
1451
+ ) from err
1452
+
1453
+ def _index_for_key(self, keys: _KeyIndexType, raiseerr: bool) -> NoReturn:
1454
+ self._we_dont_return_rows()
1455
+
1456
+ def _metadata_for_keys(self, keys: Sequence[_KeyIndexType]) -> NoReturn:
1457
+ self._we_dont_return_rows()
1458
+
1459
+ def _reduce(self, keys: Sequence[_KeyIndexType]) -> NoReturn:
1460
+ self._we_dont_return_rows()
1461
+
1462
+ @property
1463
+ def _keymap(self) -> NoReturn: # type: ignore[override]
1464
+ self._we_dont_return_rows()
1465
+
1466
+ @property
1467
+ def _key_to_index(self) -> NoReturn: # type: ignore[override]
1468
+ self._we_dont_return_rows()
1469
+
1470
+ @property
1471
+ def _processors(self) -> NoReturn: # type: ignore[override]
1472
+ self._we_dont_return_rows()
1473
+
1474
+ @property
1475
+ def keys(self) -> NoReturn:
1476
+ self._we_dont_return_rows()
1477
+
1478
+
1479
+ _NO_RESULT_METADATA = _NoResultMetaData()
1480
+
1481
+
1482
+ def null_dml_result() -> IteratorResult[Any]:
1483
+ it: IteratorResult[Any] = IteratorResult(_NoResultMetaData(), iter([]))
1484
+ it._soft_close()
1485
+ return it
1486
+
1487
+
1488
+ class CursorResult(Result[_T]):
1489
+ """A Result that is representing state from a DBAPI cursor.
1490
+
1491
+ .. versionchanged:: 1.4 The :class:`.CursorResult``
1492
+ class replaces the previous :class:`.ResultProxy` interface.
1493
+ This classes are based on the :class:`.Result` calling API
1494
+ which provides an updated usage model and calling facade for
1495
+ SQLAlchemy Core and SQLAlchemy ORM.
1496
+
1497
+ Returns database rows via the :class:`.Row` class, which provides
1498
+ additional API features and behaviors on top of the raw data returned by
1499
+ the DBAPI. Through the use of filters such as the :meth:`.Result.scalars`
1500
+ method, other kinds of objects may also be returned.
1501
+
1502
+ .. seealso::
1503
+
1504
+ :ref:`tutorial_selecting_data` - introductory material for accessing
1505
+ :class:`_engine.CursorResult` and :class:`.Row` objects.
1506
+
1507
+ """
1508
+
1509
+ __slots__ = (
1510
+ "context",
1511
+ "dialect",
1512
+ "cursor",
1513
+ "cursor_strategy",
1514
+ "_echo",
1515
+ "connection",
1516
+ )
1517
+
1518
+ _metadata: Union[CursorResultMetaData, _NoResultMetaData]
1519
+ _no_result_metadata = _NO_RESULT_METADATA
1520
+ _soft_closed: bool = False
1521
+ closed: bool = False
1522
+ _is_cursor = True
1523
+
1524
+ context: DefaultExecutionContext
1525
+ dialect: Dialect
1526
+ cursor_strategy: ResultFetchStrategy
1527
+ connection: Connection
1528
+
1529
+ def __init__(
1530
+ self,
1531
+ context: DefaultExecutionContext,
1532
+ cursor_strategy: ResultFetchStrategy,
1533
+ cursor_description: Optional[_DBAPICursorDescription],
1534
+ ):
1535
+ self.context = context
1536
+ self.dialect = context.dialect
1537
+ self.cursor = context.cursor
1538
+ self.cursor_strategy = cursor_strategy
1539
+ self.connection = context.root_connection
1540
+ self._echo = echo = (
1541
+ self.connection._echo and context.engine._should_log_debug()
1542
+ )
1543
+
1544
+ if cursor_description is not None:
1545
+ # inline of Result._row_getter(), set up an initial row
1546
+ # getter assuming no transformations will be called as this
1547
+ # is the most common case
1548
+
1549
+ metadata = self._init_metadata(context, cursor_description)
1550
+
1551
+ _make_row: Any
1552
+ _make_row = functools.partial(
1553
+ Row,
1554
+ metadata,
1555
+ metadata._effective_processors,
1556
+ metadata._key_to_index,
1557
+ )
1558
+
1559
+ if context._num_sentinel_cols:
1560
+ sentinel_filter = operator.itemgetter(
1561
+ slice(-context._num_sentinel_cols)
1562
+ )
1563
+
1564
+ def _sliced_row(raw_data: Any) -> Any:
1565
+ return _make_row(sentinel_filter(raw_data))
1566
+
1567
+ sliced_row = _sliced_row
1568
+ else:
1569
+ sliced_row = _make_row
1570
+
1571
+ if echo:
1572
+ log = self.context.connection._log_debug
1573
+
1574
+ def _log_row(row: Any) -> Any:
1575
+ log("Row %r", sql_util._repr_row(row))
1576
+ return row
1577
+
1578
+ self._row_logging_fn = _log_row
1579
+
1580
+ def _make_row_2(row: Any) -> Any:
1581
+ return _log_row(sliced_row(row))
1582
+
1583
+ make_row = _make_row_2
1584
+ else:
1585
+ make_row = sliced_row # type: ignore[assignment]
1586
+ self._set_memoized_attribute("_row_getter", make_row)
1587
+
1588
+ else:
1589
+ assert context._num_sentinel_cols == 0
1590
+ self._metadata = self._no_result_metadata
1591
+
1592
+ def _init_metadata(
1593
+ self,
1594
+ context: DefaultExecutionContext,
1595
+ cursor_description: _DBAPICursorDescription,
1596
+ ) -> CursorResultMetaData:
1597
+
1598
+ if context.compiled:
1599
+ compiled = context.compiled
1600
+
1601
+ if compiled._cached_metadata:
1602
+ metadata = compiled._cached_metadata
1603
+ else:
1604
+ metadata = CursorResultMetaData(self, cursor_description)
1605
+ if metadata._safe_for_cache:
1606
+ compiled._cached_metadata = metadata
1607
+
1608
+ # result rewrite/ adapt step. this is to suit the case
1609
+ # when we are invoked against a cached Compiled object, we want
1610
+ # to rewrite the ResultMetaData to reflect the Column objects
1611
+ # that are in our current SQL statement object, not the one
1612
+ # that is associated with the cached Compiled object.
1613
+ # the Compiled object may also tell us to not
1614
+ # actually do this step; this is to support the ORM where
1615
+ # it is to produce a new Result object in any case, and will
1616
+ # be using the cached Column objects against this database result
1617
+ # so we don't want to rewrite them.
1618
+ #
1619
+ # Basically this step suits the use case where the end user
1620
+ # is using Core SQL expressions and is accessing columns in the
1621
+ # result row using row._mapping[table.c.column].
1622
+ if (
1623
+ not context.execution_options.get(
1624
+ "_result_disable_adapt_to_context", False
1625
+ )
1626
+ and compiled._result_columns
1627
+ and context.cache_hit is context.dialect.CACHE_HIT
1628
+ and compiled.statement is not context.invoked_statement # type: ignore[comparison-overlap] # noqa: E501
1629
+ ):
1630
+ metadata = metadata._adapt_to_context(context) # type: ignore[assignment] # noqa: E501
1631
+
1632
+ self._metadata = metadata
1633
+
1634
+ else:
1635
+ self._metadata = metadata = CursorResultMetaData(
1636
+ self, cursor_description
1637
+ )
1638
+ if self._echo:
1639
+ context.connection._log_debug(
1640
+ "Col %r", tuple(x[0] for x in cursor_description)
1641
+ )
1642
+ return metadata
1643
+
1644
+ def _soft_close(self, hard: bool = False) -> None:
1645
+ """Soft close this :class:`_engine.CursorResult`.
1646
+
1647
+ This releases all DBAPI cursor resources, but leaves the
1648
+ CursorResult "open" from a semantic perspective, meaning the
1649
+ fetchXXX() methods will continue to return empty results.
1650
+
1651
+ This method is called automatically when:
1652
+
1653
+ * all result rows are exhausted using the fetchXXX() methods.
1654
+ * cursor.description is None.
1655
+
1656
+ This method is **not public**, but is documented in order to clarify
1657
+ the "autoclose" process used.
1658
+
1659
+ .. seealso::
1660
+
1661
+ :meth:`_engine.CursorResult.close`
1662
+
1663
+
1664
+ """
1665
+
1666
+ if (not hard and self._soft_closed) or (hard and self.closed):
1667
+ return
1668
+
1669
+ if hard:
1670
+ self.closed = True
1671
+ self.cursor_strategy.hard_close(self, self.cursor)
1672
+ else:
1673
+ self.cursor_strategy.soft_close(self, self.cursor)
1674
+
1675
+ if not self._soft_closed:
1676
+ cursor = self.cursor
1677
+ self.cursor = None # type: ignore
1678
+ self.connection._safe_close_cursor(cursor)
1679
+ self._soft_closed = True
1680
+
1681
+ @property
1682
+ def inserted_primary_key_rows(self) -> List[Optional[Any]]:
1683
+ """Return the value of
1684
+ :attr:`_engine.CursorResult.inserted_primary_key`
1685
+ as a row contained within a list; some dialects may support a
1686
+ multiple row form as well.
1687
+
1688
+ .. note:: As indicated below, in current SQLAlchemy versions this
1689
+ accessor is only useful beyond what's already supplied by
1690
+ :attr:`_engine.CursorResult.inserted_primary_key` when using the
1691
+ :ref:`postgresql_psycopg2` dialect. Future versions hope to
1692
+ generalize this feature to more dialects.
1693
+
1694
+ This accessor is added to support dialects that offer the feature
1695
+ that is currently implemented by the :ref:`psycopg2_executemany_mode`
1696
+ feature, currently **only the psycopg2 dialect**, which provides
1697
+ for many rows to be INSERTed at once while still retaining the
1698
+ behavior of being able to return server-generated primary key values.
1699
+
1700
+ * **When using the psycopg2 dialect, or other dialects that may support
1701
+ "fast executemany" style inserts in upcoming releases** : When
1702
+ invoking an INSERT statement while passing a list of rows as the
1703
+ second argument to :meth:`_engine.Connection.execute`, this accessor
1704
+ will then provide a list of rows, where each row contains the primary
1705
+ key value for each row that was INSERTed.
1706
+
1707
+ * **When using all other dialects / backends that don't yet support
1708
+ this feature**: This accessor is only useful for **single row INSERT
1709
+ statements**, and returns the same information as that of the
1710
+ :attr:`_engine.CursorResult.inserted_primary_key` within a
1711
+ single-element list. When an INSERT statement is executed in
1712
+ conjunction with a list of rows to be INSERTed, the list will contain
1713
+ one row per row inserted in the statement, however it will contain
1714
+ ``None`` for any server-generated values.
1715
+
1716
+ Future releases of SQLAlchemy will further generalize the
1717
+ "fast execution helper" feature of psycopg2 to suit other dialects,
1718
+ thus allowing this accessor to be of more general use.
1719
+
1720
+ .. versionadded:: 1.4
1721
+
1722
+ .. seealso::
1723
+
1724
+ :attr:`_engine.CursorResult.inserted_primary_key`
1725
+
1726
+ """
1727
+ if not self.context.compiled:
1728
+ raise exc.InvalidRequestError(
1729
+ "Statement is not a compiled expression construct."
1730
+ )
1731
+ elif not self.context.isinsert:
1732
+ raise exc.InvalidRequestError(
1733
+ "Statement is not an insert() expression construct."
1734
+ )
1735
+ elif self.context._is_explicit_returning:
1736
+ raise exc.InvalidRequestError(
1737
+ "Can't call inserted_primary_key "
1738
+ "when returning() "
1739
+ "is used."
1740
+ )
1741
+ return self.context.inserted_primary_key_rows # type: ignore[no-any-return] # noqa: E501
1742
+
1743
+ @property
1744
+ def inserted_primary_key(self) -> Optional[Any]:
1745
+ """Return the primary key for the row just inserted.
1746
+
1747
+ The return value is a :class:`_result.Row` object representing
1748
+ a named tuple of primary key values in the order in which the
1749
+ primary key columns are configured in the source
1750
+ :class:`_schema.Table`.
1751
+
1752
+ .. versionchanged:: 1.4.8 - the
1753
+ :attr:`_engine.CursorResult.inserted_primary_key`
1754
+ value is now a named tuple via the :class:`_result.Row` class,
1755
+ rather than a plain tuple.
1756
+
1757
+ This accessor only applies to single row :func:`_expression.insert`
1758
+ constructs which did not explicitly specify
1759
+ :meth:`_expression.Insert.returning`. Support for multirow inserts,
1760
+ while not yet available for most backends, would be accessed using
1761
+ the :attr:`_engine.CursorResult.inserted_primary_key_rows` accessor.
1762
+
1763
+ Note that primary key columns which specify a server_default clause, or
1764
+ otherwise do not qualify as "autoincrement" columns (see the notes at
1765
+ :class:`_schema.Column`), and were generated using the database-side
1766
+ default, will appear in this list as ``None`` unless the backend
1767
+ supports "returning" and the insert statement executed with the
1768
+ "implicit returning" enabled.
1769
+
1770
+ Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
1771
+ statement is not a compiled expression construct
1772
+ or is not an insert() construct.
1773
+
1774
+ """
1775
+
1776
+ if self.context.executemany:
1777
+ raise exc.InvalidRequestError(
1778
+ "This statement was an executemany call; if primary key "
1779
+ "returning is supported, please "
1780
+ "use .inserted_primary_key_rows."
1781
+ )
1782
+
1783
+ ikp = self.inserted_primary_key_rows
1784
+ if ikp:
1785
+ return ikp[0]
1786
+ else:
1787
+ return None
1788
+
1789
+ def last_updated_params(
1790
+ self,
1791
+ ) -> Union[
1792
+ List[_MutableCoreSingleExecuteParams], _MutableCoreSingleExecuteParams
1793
+ ]:
1794
+ """Return the collection of updated parameters from this
1795
+ execution.
1796
+
1797
+ Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
1798
+ statement is not a compiled expression construct
1799
+ or is not an update() construct.
1800
+
1801
+ """
1802
+ if not self.context.compiled:
1803
+ raise exc.InvalidRequestError(
1804
+ "Statement is not a compiled expression construct."
1805
+ )
1806
+ elif not self.context.isupdate:
1807
+ raise exc.InvalidRequestError(
1808
+ "Statement is not an update() expression construct."
1809
+ )
1810
+ elif self.context.executemany:
1811
+ return self.context.compiled_parameters
1812
+ else:
1813
+ return self.context.compiled_parameters[0]
1814
+
1815
+ def last_inserted_params(
1816
+ self,
1817
+ ) -> Union[
1818
+ List[_MutableCoreSingleExecuteParams], _MutableCoreSingleExecuteParams
1819
+ ]:
1820
+ """Return the collection of inserted parameters from this
1821
+ execution.
1822
+
1823
+ Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
1824
+ statement is not a compiled expression construct
1825
+ or is not an insert() construct.
1826
+
1827
+ """
1828
+ if not self.context.compiled:
1829
+ raise exc.InvalidRequestError(
1830
+ "Statement is not a compiled expression construct."
1831
+ )
1832
+ elif not self.context.isinsert:
1833
+ raise exc.InvalidRequestError(
1834
+ "Statement is not an insert() expression construct."
1835
+ )
1836
+ elif self.context.executemany:
1837
+ return self.context.compiled_parameters
1838
+ else:
1839
+ return self.context.compiled_parameters[0]
1840
+
1841
+ @property
1842
+ def returned_defaults_rows(
1843
+ self,
1844
+ ) -> Optional[Sequence[Row[Any]]]:
1845
+ """Return a list of rows each containing the values of default
1846
+ columns that were fetched using
1847
+ the :meth:`.ValuesBase.return_defaults` feature.
1848
+
1849
+ The return value is a list of :class:`.Row` objects.
1850
+
1851
+ .. versionadded:: 1.4
1852
+
1853
+ """
1854
+ return self.context.returned_default_rows
1855
+
1856
+ def splice_horizontally(self, other: CursorResult[Any]) -> Self:
1857
+ """Return a new :class:`.CursorResult` that "horizontally splices"
1858
+ together the rows of this :class:`.CursorResult` with that of another
1859
+ :class:`.CursorResult`.
1860
+
1861
+ .. tip:: This method is for the benefit of the SQLAlchemy ORM and is
1862
+ not intended for general use.
1863
+
1864
+ "horizontally splices" means that for each row in the first and second
1865
+ result sets, a new row that concatenates the two rows together is
1866
+ produced, which then becomes the new row. The incoming
1867
+ :class:`.CursorResult` must have the identical number of rows. It is
1868
+ typically expected that the two result sets come from the same sort
1869
+ order as well, as the result rows are spliced together based on their
1870
+ position in the result.
1871
+
1872
+ The expected use case here is so that multiple INSERT..RETURNING
1873
+ statements (which definitely need to be sorted) against different
1874
+ tables can produce a single result that looks like a JOIN of those two
1875
+ tables.
1876
+
1877
+ E.g.::
1878
+
1879
+ r1 = connection.execute(
1880
+ users.insert().returning(
1881
+ users.c.user_name, users.c.user_id, sort_by_parameter_order=True
1882
+ ),
1883
+ user_values,
1884
+ )
1885
+
1886
+ r2 = connection.execute(
1887
+ addresses.insert().returning(
1888
+ addresses.c.address_id,
1889
+ addresses.c.address,
1890
+ addresses.c.user_id,
1891
+ sort_by_parameter_order=True,
1892
+ ),
1893
+ address_values,
1894
+ )
1895
+
1896
+ rows = r1.splice_horizontally(r2).all()
1897
+ assert rows == [
1898
+ ("john", 1, 1, "foo@bar.com", 1),
1899
+ ("jack", 2, 2, "bar@bat.com", 2),
1900
+ ]
1901
+
1902
+ .. versionadded:: 2.0
1903
+
1904
+ .. seealso::
1905
+
1906
+ :meth:`.CursorResult.splice_vertically`
1907
+
1908
+
1909
+ """ # noqa: E501
1910
+
1911
+ clone = self._generate()
1912
+ total_rows = [
1913
+ tuple(r1) + tuple(r2)
1914
+ for r1, r2 in zip(
1915
+ list(self._raw_row_iterator()),
1916
+ list(other._raw_row_iterator()),
1917
+ )
1918
+ ]
1919
+
1920
+ clone._metadata = clone._metadata._splice_horizontally(other._metadata) # type: ignore[union-attr, arg-type] # noqa: E501
1921
+
1922
+ clone.cursor_strategy = FullyBufferedCursorFetchStrategy(
1923
+ None,
1924
+ initial_buffer=total_rows,
1925
+ )
1926
+ clone._reset_memoizations()
1927
+ return clone
1928
+
1929
+ def splice_vertically(self, other: CursorResult[Any]) -> Self:
1930
+ """Return a new :class:`.CursorResult` that "vertically splices",
1931
+ i.e. "extends", the rows of this :class:`.CursorResult` with that of
1932
+ another :class:`.CursorResult`.
1933
+
1934
+ .. tip:: This method is for the benefit of the SQLAlchemy ORM and is
1935
+ not intended for general use.
1936
+
1937
+ "vertically splices" means the rows of the given result are appended to
1938
+ the rows of this cursor result. The incoming :class:`.CursorResult`
1939
+ must have rows that represent the identical list of columns in the
1940
+ identical order as they are in this :class:`.CursorResult`.
1941
+
1942
+ .. versionadded:: 2.0
1943
+
1944
+ .. seealso::
1945
+
1946
+ :meth:`.CursorResult.splice_horizontally`
1947
+
1948
+ """
1949
+ clone = self._generate()
1950
+ total_rows = list(self._raw_row_iterator()) + list(
1951
+ other._raw_row_iterator()
1952
+ )
1953
+
1954
+ clone.cursor_strategy = FullyBufferedCursorFetchStrategy(
1955
+ None,
1956
+ initial_buffer=total_rows,
1957
+ )
1958
+ clone._reset_memoizations()
1959
+ return clone
1960
+
1961
+ def _rewind(self, rows: Any) -> Self:
1962
+ """rewind this result back to the given rowset.
1963
+
1964
+ this is used internally for the case where an :class:`.Insert`
1965
+ construct combines the use of
1966
+ :meth:`.Insert.return_defaults` along with the
1967
+ "supplemental columns" feature.
1968
+
1969
+ """
1970
+
1971
+ if self._echo:
1972
+ self.context.connection._log_debug(
1973
+ "CursorResult rewound %d row(s)", len(rows)
1974
+ )
1975
+
1976
+ # the rows given are expected to be Row objects, so we
1977
+ # have to clear out processors which have already run on these
1978
+ # rows
1979
+ self._metadata = cast(
1980
+ CursorResultMetaData, self._metadata
1981
+ )._remove_processors()
1982
+
1983
+ self.cursor_strategy = FullyBufferedCursorFetchStrategy(
1984
+ None,
1985
+ # TODO: if these are Row objects, can we save on not having to
1986
+ # re-make new Row objects out of them a second time? is that
1987
+ # what's actually happening right now? maybe look into this
1988
+ initial_buffer=rows,
1989
+ )
1990
+ self._reset_memoizations()
1991
+ return self
1992
+
1993
+ @property
1994
+ def returned_defaults(self) -> Optional[Row[Any]]:
1995
+ """Return the values of default columns that were fetched using
1996
+ the :meth:`.ValuesBase.return_defaults` feature.
1997
+
1998
+ The value is an instance of :class:`.Row`, or ``None``
1999
+ if :meth:`.ValuesBase.return_defaults` was not used or if the
2000
+ backend does not support RETURNING.
2001
+
2002
+ .. seealso::
2003
+
2004
+ :meth:`.ValuesBase.return_defaults`
2005
+
2006
+ """
2007
+
2008
+ if self.context.executemany:
2009
+ raise exc.InvalidRequestError(
2010
+ "This statement was an executemany call; if return defaults "
2011
+ "is supported, please use .returned_defaults_rows."
2012
+ )
2013
+
2014
+ rows = self.context.returned_default_rows
2015
+ if rows:
2016
+ return rows[0]
2017
+ else:
2018
+ return None
2019
+
2020
+ def lastrow_has_defaults(self) -> bool:
2021
+ """Return ``lastrow_has_defaults()`` from the underlying
2022
+ :class:`.ExecutionContext`.
2023
+
2024
+ See :class:`.ExecutionContext` for details.
2025
+
2026
+ """
2027
+
2028
+ return self.context.lastrow_has_defaults()
2029
+
2030
+ def postfetch_cols(self) -> Optional[Sequence[Column[Any]]]:
2031
+ """Return ``postfetch_cols()`` from the underlying
2032
+ :class:`.ExecutionContext`.
2033
+
2034
+ See :class:`.ExecutionContext` for details.
2035
+
2036
+ Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
2037
+ statement is not a compiled expression construct
2038
+ or is not an insert() or update() construct.
2039
+
2040
+ """
2041
+
2042
+ if not self.context.compiled:
2043
+ raise exc.InvalidRequestError(
2044
+ "Statement is not a compiled expression construct."
2045
+ )
2046
+ elif not self.context.isinsert and not self.context.isupdate:
2047
+ raise exc.InvalidRequestError(
2048
+ "Statement is not an insert() or update() "
2049
+ "expression construct."
2050
+ )
2051
+ return self.context.postfetch_cols
2052
+
2053
+ def prefetch_cols(self) -> Optional[Sequence[Column[Any]]]:
2054
+ """Return ``prefetch_cols()`` from the underlying
2055
+ :class:`.ExecutionContext`.
2056
+
2057
+ See :class:`.ExecutionContext` for details.
2058
+
2059
+ Raises :class:`~sqlalchemy.exc.InvalidRequestError` if the executed
2060
+ statement is not a compiled expression construct
2061
+ or is not an insert() or update() construct.
2062
+
2063
+ """
2064
+
2065
+ if not self.context.compiled:
2066
+ raise exc.InvalidRequestError(
2067
+ "Statement is not a compiled expression construct."
2068
+ )
2069
+ elif not self.context.isinsert and not self.context.isupdate:
2070
+ raise exc.InvalidRequestError(
2071
+ "Statement is not an insert() or update() "
2072
+ "expression construct."
2073
+ )
2074
+ return self.context.prefetch_cols
2075
+
2076
+ def supports_sane_rowcount(self) -> bool:
2077
+ """Return ``supports_sane_rowcount`` from the dialect.
2078
+
2079
+ See :attr:`_engine.CursorResult.rowcount` for background.
2080
+
2081
+ """
2082
+
2083
+ return self.dialect.supports_sane_rowcount
2084
+
2085
+ def supports_sane_multi_rowcount(self) -> bool:
2086
+ """Return ``supports_sane_multi_rowcount`` from the dialect.
2087
+
2088
+ See :attr:`_engine.CursorResult.rowcount` for background.
2089
+
2090
+ """
2091
+
2092
+ return self.dialect.supports_sane_multi_rowcount
2093
+
2094
+ @util.memoized_property
2095
+ def rowcount(self) -> int:
2096
+ """Return the 'rowcount' for this result.
2097
+
2098
+ The primary purpose of 'rowcount' is to report the number of rows
2099
+ matched by the WHERE criterion of an UPDATE or DELETE statement
2100
+ executed once (i.e. for a single parameter set), which may then be
2101
+ compared to the number of rows expected to be updated or deleted as a
2102
+ means of asserting data integrity.
2103
+
2104
+ This attribute is transferred from the ``cursor.rowcount`` attribute
2105
+ of the DBAPI before the cursor is closed, to support DBAPIs that
2106
+ don't make this value available after cursor close. Some DBAPIs may
2107
+ offer meaningful values for other kinds of statements, such as INSERT
2108
+ and SELECT statements as well. In order to retrieve ``cursor.rowcount``
2109
+ for these statements, set the
2110
+ :paramref:`.Connection.execution_options.preserve_rowcount`
2111
+ execution option to True, which will cause the ``cursor.rowcount``
2112
+ value to be unconditionally memoized before any results are returned
2113
+ or the cursor is closed, regardless of statement type.
2114
+
2115
+ For cases where the DBAPI does not support rowcount for a particular
2116
+ kind of statement and/or execution, the returned value will be ``-1``,
2117
+ which is delivered directly from the DBAPI and is part of :pep:`249`.
2118
+ All DBAPIs should support rowcount for single-parameter-set
2119
+ UPDATE and DELETE statements, however.
2120
+
2121
+ .. note::
2122
+
2123
+ Notes regarding :attr:`_engine.CursorResult.rowcount`:
2124
+
2125
+
2126
+ * This attribute returns the number of rows *matched*,
2127
+ which is not necessarily the same as the number of rows
2128
+ that were actually *modified*. For example, an UPDATE statement
2129
+ may have no net change on a given row if the SET values
2130
+ given are the same as those present in the row already.
2131
+ Such a row would be matched but not modified.
2132
+ On backends that feature both styles, such as MySQL,
2133
+ rowcount is configured to return the match
2134
+ count in all cases.
2135
+
2136
+ * :attr:`_engine.CursorResult.rowcount` in the default case is
2137
+ *only* useful in conjunction with an UPDATE or DELETE statement,
2138
+ and only with a single set of parameters. For other kinds of
2139
+ statements, SQLAlchemy will not attempt to pre-memoize the value
2140
+ unless the
2141
+ :paramref:`.Connection.execution_options.preserve_rowcount`
2142
+ execution option is used. Note that contrary to :pep:`249`, many
2143
+ DBAPIs do not support rowcount values for statements that are not
2144
+ UPDATE or DELETE, particularly when rows are being returned which
2145
+ are not fully pre-buffered. DBAPIs that dont support rowcount
2146
+ for a particular kind of statement should return the value ``-1``
2147
+ for such statements.
2148
+
2149
+ * :attr:`_engine.CursorResult.rowcount` may not be meaningful
2150
+ when executing a single statement with multiple parameter sets
2151
+ (i.e. an :term:`executemany`). Most DBAPIs do not sum "rowcount"
2152
+ values across multiple parameter sets and will return ``-1``
2153
+ when accessed.
2154
+
2155
+ * SQLAlchemy's :ref:`engine_insertmanyvalues` feature does support
2156
+ a correct population of :attr:`_engine.CursorResult.rowcount`
2157
+ when the :paramref:`.Connection.execution_options.preserve_rowcount`
2158
+ execution option is set to True.
2159
+
2160
+ * Statements that use RETURNING may not support rowcount, returning
2161
+ a ``-1`` value instead.
2162
+
2163
+ .. seealso::
2164
+
2165
+ :ref:`tutorial_update_delete_rowcount` - in the :ref:`unified_tutorial`
2166
+
2167
+ :paramref:`.Connection.execution_options.preserve_rowcount`
2168
+
2169
+ """ # noqa: E501
2170
+ try:
2171
+ return self.context.rowcount
2172
+ except BaseException as e:
2173
+ self.cursor_strategy.handle_exception(self, self.cursor, e)
2174
+ raise # not called
2175
+
2176
+ @property
2177
+ def lastrowid(self) -> int:
2178
+ """Return the 'lastrowid' accessor on the DBAPI cursor.
2179
+
2180
+ This is a DBAPI specific method and is only functional
2181
+ for those backends which support it, for statements
2182
+ where it is appropriate. It's behavior is not
2183
+ consistent across backends.
2184
+
2185
+ Usage of this method is normally unnecessary when
2186
+ using insert() expression constructs; the
2187
+ :attr:`~CursorResult.inserted_primary_key` attribute provides a
2188
+ tuple of primary key values for a newly inserted row,
2189
+ regardless of database backend.
2190
+
2191
+ """
2192
+ try:
2193
+ return self.context.get_lastrowid()
2194
+ except BaseException as e:
2195
+ self.cursor_strategy.handle_exception(self, self.cursor, e)
2196
+
2197
+ @property
2198
+ def returns_rows(self) -> bool:
2199
+ """True if this :class:`_engine.CursorResult` returns zero or more
2200
+ rows.
2201
+
2202
+ I.e. if it is legal to call the methods
2203
+ :meth:`_engine.CursorResult.fetchone`,
2204
+ :meth:`_engine.CursorResult.fetchmany`
2205
+ :meth:`_engine.CursorResult.fetchall`.
2206
+
2207
+ Overall, the value of :attr:`_engine.CursorResult.returns_rows` should
2208
+ always be synonymous with whether or not the DBAPI cursor had a
2209
+ ``.description`` attribute, indicating the presence of result columns,
2210
+ noting that a cursor that returns zero rows still has a
2211
+ ``.description`` if a row-returning statement was emitted.
2212
+
2213
+ This attribute should be True for all results that are against
2214
+ SELECT statements, as well as for DML statements INSERT/UPDATE/DELETE
2215
+ that use RETURNING. For INSERT/UPDATE/DELETE statements that were
2216
+ not using RETURNING, the value will usually be False, however
2217
+ there are some dialect-specific exceptions to this, such as when
2218
+ using the MSSQL / pyodbc dialect a SELECT is emitted inline in
2219
+ order to retrieve an inserted primary key value.
2220
+
2221
+ .. seealso::
2222
+
2223
+ :meth:`.Result.close`
2224
+
2225
+ :attr:`.Result.closed`
2226
+
2227
+ """
2228
+ return self._metadata.returns_rows
2229
+
2230
+ @property
2231
+ def is_insert(self) -> bool:
2232
+ """True if this :class:`_engine.CursorResult` is the result
2233
+ of a executing an expression language compiled
2234
+ :func:`_expression.insert` construct.
2235
+
2236
+ When True, this implies that the
2237
+ :attr:`inserted_primary_key` attribute is accessible,
2238
+ assuming the statement did not include
2239
+ a user defined "returning" construct.
2240
+
2241
+ """
2242
+ return self.context.isinsert
2243
+
2244
+ def _fetchiter_impl(self) -> Iterator[Any]:
2245
+ fetchone = self.cursor_strategy.fetchone
2246
+
2247
+ while True:
2248
+ row = fetchone(self, self.cursor)
2249
+ if row is None:
2250
+ break
2251
+ yield row
2252
+
2253
+ def _fetchone_impl(self, hard_close: bool = False) -> Any:
2254
+ return self.cursor_strategy.fetchone(self, self.cursor, hard_close)
2255
+
2256
+ def _fetchall_impl(self) -> Any:
2257
+ return self.cursor_strategy.fetchall(self, self.cursor)
2258
+
2259
+ def _fetchmany_impl(self, size: Optional[int] = None) -> Any:
2260
+ return self.cursor_strategy.fetchmany(self, self.cursor, size)
2261
+
2262
+ def _raw_row_iterator(self) -> Any:
2263
+ return self._fetchiter_impl()
2264
+
2265
+ def merge(self, *others: Result[Any]) -> MergedResult[Any]:
2266
+ merged_result = super().merge(*others)
2267
+ if self.context._has_rowcount:
2268
+ merged_result.rowcount = sum(
2269
+ cast("CursorResult[Any]", result).rowcount
2270
+ for result in (self,) + others
2271
+ )
2272
+ return merged_result
2273
+
2274
+ def close(self) -> None:
2275
+ """Close this :class:`_engine.CursorResult`.
2276
+
2277
+ This closes out the underlying DBAPI cursor corresponding to the
2278
+ statement execution, if one is still present. Note that the DBAPI
2279
+ cursor is automatically released when the :class:`_engine.CursorResult`
2280
+ exhausts all available rows. :meth:`_engine.CursorResult.close` is
2281
+ generally an optional method except in the case when discarding a
2282
+ :class:`_engine.CursorResult` that still has additional rows pending
2283
+ for fetch.
2284
+
2285
+ After this method is called, it is no longer valid to call upon
2286
+ the fetch methods, which will raise a :class:`.ResourceClosedError`
2287
+ on subsequent use.
2288
+
2289
+ .. seealso::
2290
+
2291
+ :ref:`connections_toplevel`
2292
+
2293
+ """
2294
+ self._soft_close(hard=True)
2295
+
2296
+ @_generative
2297
+ def yield_per(self, num: int) -> Self:
2298
+ self._yield_per = num
2299
+ self.cursor_strategy.yield_per(self, self.cursor, num)
2300
+ return self
2301
+
2302
+
2303
+ ResultProxy = CursorResult
python/user_packages/Python313/site-packages/sqlalchemy/engine/default.py ADDED
@@ -0,0 +1,2394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # engine/default.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: allow-untyped-defs, allow-untyped-calls
8
+
9
+ """Default implementations of per-dialect sqlalchemy.engine classes.
10
+
11
+ These are semi-private implementation classes which are only of importance
12
+ to database dialect authors; dialects will usually use the classes here
13
+ as the base class for their own corresponding classes.
14
+
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import functools
20
+ import operator
21
+ import random
22
+ import re
23
+ from time import perf_counter
24
+ import typing
25
+ from typing import Any
26
+ from typing import Callable
27
+ from typing import cast
28
+ from typing import Dict
29
+ from typing import List
30
+ from typing import Mapping
31
+ from typing import MutableMapping
32
+ from typing import MutableSequence
33
+ from typing import Optional
34
+ from typing import Sequence
35
+ from typing import Set
36
+ from typing import Tuple
37
+ from typing import Type
38
+ from typing import TYPE_CHECKING
39
+ from typing import Union
40
+ import weakref
41
+
42
+ from . import characteristics
43
+ from . import cursor as _cursor
44
+ from . import interfaces
45
+ from .base import Connection
46
+ from .interfaces import CacheStats
47
+ from .interfaces import DBAPICursor
48
+ from .interfaces import Dialect
49
+ from .interfaces import ExecuteStyle
50
+ from .interfaces import ExecutionContext
51
+ from .reflection import ObjectKind
52
+ from .reflection import ObjectScope
53
+ from .. import event
54
+ from .. import exc
55
+ from .. import pool
56
+ from .. import util
57
+ from ..sql import compiler
58
+ from ..sql import dml
59
+ from ..sql import expression
60
+ from ..sql import type_api
61
+ from ..sql import util as sql_util
62
+ from ..sql._typing import is_tuple_type
63
+ from ..sql.base import _NoArg
64
+ from ..sql.compiler import DDLCompiler
65
+ from ..sql.compiler import InsertmanyvaluesSentinelOpts
66
+ from ..sql.compiler import SQLCompiler
67
+ from ..sql.elements import quoted_name
68
+ from ..util.typing import Final
69
+ from ..util.typing import Literal
70
+
71
+ if typing.TYPE_CHECKING:
72
+ from types import ModuleType
73
+
74
+ from .base import Engine
75
+ from .cursor import ResultFetchStrategy
76
+ from .interfaces import _CoreMultiExecuteParams
77
+ from .interfaces import _CoreSingleExecuteParams
78
+ from .interfaces import _DBAPICursorDescription
79
+ from .interfaces import _DBAPIMultiExecuteParams
80
+ from .interfaces import _DBAPISingleExecuteParams
81
+ from .interfaces import _ExecuteOptions
82
+ from .interfaces import _MutableCoreSingleExecuteParams
83
+ from .interfaces import _ParamStyle
84
+ from .interfaces import ConnectArgsType
85
+ from .interfaces import DBAPIConnection
86
+ from .interfaces import DBAPIModule
87
+ from .interfaces import DBAPIType
88
+ from .interfaces import IsolationLevel
89
+ from .row import Row
90
+ from .url import URL
91
+ from ..event import _ListenerFnType
92
+ from ..pool import Pool
93
+ from ..pool import PoolProxiedConnection
94
+ from ..sql import Executable
95
+ from ..sql.compiler import Compiled
96
+ from ..sql.compiler import Linting
97
+ from ..sql.compiler import ResultColumnsEntry
98
+ from ..sql.dml import DMLState
99
+ from ..sql.dml import UpdateBase
100
+ from ..sql.elements import BindParameter
101
+ from ..sql.schema import Column
102
+ from ..sql.type_api import _BindProcessorType
103
+ from ..sql.type_api import _ResultProcessorType
104
+ from ..sql.type_api import TypeEngine
105
+
106
+
107
+ # When we're handed literal SQL, ensure it's a SELECT query
108
+ SERVER_SIDE_CURSOR_RE = re.compile(r"\s*SELECT", re.I | re.UNICODE)
109
+
110
+
111
+ (
112
+ CACHE_HIT,
113
+ CACHE_MISS,
114
+ CACHING_DISABLED,
115
+ NO_CACHE_KEY,
116
+ NO_DIALECT_SUPPORT,
117
+ ) = list(CacheStats)
118
+
119
+
120
+ class DefaultDialect(Dialect):
121
+ """Default implementation of Dialect"""
122
+
123
+ statement_compiler = compiler.SQLCompiler
124
+ ddl_compiler = compiler.DDLCompiler
125
+ type_compiler_cls = compiler.GenericTypeCompiler
126
+
127
+ preparer = compiler.IdentifierPreparer
128
+ supports_alter = True
129
+ supports_comments = False
130
+ supports_constraint_comments = False
131
+ inline_comments = False
132
+ supports_statement_cache = True
133
+
134
+ div_is_floordiv = True
135
+
136
+ bind_typing = interfaces.BindTyping.NONE
137
+
138
+ include_set_input_sizes: Optional[Set[Any]] = None
139
+ exclude_set_input_sizes: Optional[Set[Any]] = None
140
+
141
+ # the first value we'd get for an autoincrement column.
142
+ default_sequence_base = 1
143
+
144
+ # most DBAPIs happy with this for execute().
145
+ # not cx_oracle.
146
+ execute_sequence_format = tuple
147
+
148
+ supports_schemas = True
149
+ supports_views = True
150
+ supports_sequences = False
151
+ sequences_optional = False
152
+ preexecute_autoincrement_sequences = False
153
+ supports_identity_columns = False
154
+ postfetch_lastrowid = True
155
+ favor_returning_over_lastrowid = False
156
+ insert_null_pk_still_autoincrements = False
157
+ update_returning = False
158
+ delete_returning = False
159
+ update_returning_multifrom = False
160
+ delete_returning_multifrom = False
161
+ insert_returning = False
162
+
163
+ cte_follows_insert = False
164
+
165
+ supports_native_enum = False
166
+ supports_native_boolean = False
167
+ supports_native_uuid = False
168
+ returns_native_bytes = False
169
+
170
+ non_native_boolean_check_constraint = True
171
+
172
+ supports_simple_order_by_label = True
173
+
174
+ tuple_in_values = False
175
+
176
+ connection_characteristics = util.immutabledict(
177
+ {
178
+ "isolation_level": characteristics.IsolationLevelCharacteristic(),
179
+ "logging_token": characteristics.LoggingTokenCharacteristic(),
180
+ }
181
+ )
182
+
183
+ engine_config_types: Mapping[str, Any] = util.immutabledict(
184
+ {
185
+ "pool_timeout": util.asint,
186
+ "echo": util.bool_or_str("debug"),
187
+ "echo_pool": util.bool_or_str("debug"),
188
+ "pool_recycle": util.asint,
189
+ "pool_size": util.asint,
190
+ "max_overflow": util.asint,
191
+ "future": util.asbool,
192
+ }
193
+ )
194
+
195
+ # if the NUMERIC type
196
+ # returns decimal.Decimal.
197
+ # *not* the FLOAT type however.
198
+ supports_native_decimal = False
199
+
200
+ name = "default"
201
+
202
+ # length at which to truncate
203
+ # any identifier.
204
+ max_identifier_length = 9999
205
+ _user_defined_max_identifier_length: Optional[int] = None
206
+
207
+ isolation_level: Optional[str] = None
208
+
209
+ # sub-categories of max_identifier_length.
210
+ # currently these accommodate for MySQL which allows alias names
211
+ # of 255 but DDL names only of 64.
212
+ max_index_name_length: Optional[int] = None
213
+ max_constraint_name_length: Optional[int] = None
214
+
215
+ supports_sane_rowcount = True
216
+ supports_sane_multi_rowcount = True
217
+ colspecs: MutableMapping[Type[TypeEngine[Any]], Type[TypeEngine[Any]]] = {}
218
+ default_paramstyle = "named"
219
+
220
+ supports_default_values = False
221
+ """dialect supports INSERT... DEFAULT VALUES syntax"""
222
+
223
+ supports_default_metavalue = False
224
+ """dialect supports INSERT... VALUES (DEFAULT) syntax"""
225
+
226
+ default_metavalue_token = "DEFAULT"
227
+ """for INSERT... VALUES (DEFAULT) syntax, the token to put in the
228
+ parenthesis."""
229
+
230
+ # not sure if this is a real thing but the compiler will deliver it
231
+ # if this is the only flag enabled.
232
+ supports_empty_insert = True
233
+ """dialect supports INSERT () VALUES ()"""
234
+
235
+ supports_multivalues_insert = False
236
+
237
+ use_insertmanyvalues: bool = False
238
+
239
+ use_insertmanyvalues_wo_returning: bool = False
240
+
241
+ insertmanyvalues_implicit_sentinel: InsertmanyvaluesSentinelOpts = (
242
+ InsertmanyvaluesSentinelOpts.NOT_SUPPORTED
243
+ )
244
+
245
+ insertmanyvalues_page_size: int = 1000
246
+ insertmanyvalues_max_parameters = 32700
247
+
248
+ supports_is_distinct_from = True
249
+
250
+ supports_server_side_cursors = False
251
+
252
+ server_side_cursors = False
253
+
254
+ # extra record-level locking features (#4860)
255
+ supports_for_update_of = False
256
+
257
+ server_version_info = None
258
+
259
+ default_schema_name: Optional[str] = None
260
+
261
+ # indicates symbol names are
262
+ # UPPERCASED if they are case insensitive
263
+ # within the database.
264
+ # if this is True, the methods normalize_name()
265
+ # and denormalize_name() must be provided.
266
+ requires_name_normalize = False
267
+
268
+ is_async = False
269
+
270
+ has_terminate = False
271
+
272
+ # TODO: this is not to be part of 2.0. implement rudimentary binary
273
+ # literals for SQLite, PostgreSQL, MySQL only within
274
+ # _Binary.literal_processor
275
+ _legacy_binary_type_literal_encoding = "utf-8"
276
+
277
+ @util.deprecated_params(
278
+ empty_in_strategy=(
279
+ "1.4",
280
+ "The :paramref:`_sa.create_engine.empty_in_strategy` keyword is "
281
+ "deprecated, and no longer has any effect. All IN expressions "
282
+ "are now rendered using "
283
+ 'the "expanding parameter" strategy which renders a set of bound'
284
+ 'expressions, or an "empty set" SELECT, at statement execution'
285
+ "time.",
286
+ ),
287
+ server_side_cursors=(
288
+ "1.4",
289
+ "The :paramref:`_sa.create_engine.server_side_cursors` parameter "
290
+ "is deprecated and will be removed in a future release. Please "
291
+ "use the "
292
+ ":paramref:`_engine.Connection.execution_options.stream_results` "
293
+ "parameter.",
294
+ ),
295
+ )
296
+ def __init__(
297
+ self,
298
+ paramstyle: Optional[_ParamStyle] = None,
299
+ isolation_level: Optional[IsolationLevel] = None,
300
+ dbapi: Optional[ModuleType] = None,
301
+ implicit_returning: Literal[True] = True,
302
+ supports_native_boolean: Optional[bool] = None,
303
+ max_identifier_length: Optional[int] = None,
304
+ label_length: Optional[int] = None,
305
+ insertmanyvalues_page_size: Union[_NoArg, int] = _NoArg.NO_ARG,
306
+ use_insertmanyvalues: Optional[bool] = None,
307
+ # util.deprecated_params decorator cannot render the
308
+ # Linting.NO_LINTING constant
309
+ compiler_linting: Linting = int(compiler.NO_LINTING), # type: ignore
310
+ server_side_cursors: bool = False,
311
+ skip_autocommit_rollback: bool = False,
312
+ **kwargs: Any,
313
+ ):
314
+ if server_side_cursors:
315
+ if not self.supports_server_side_cursors:
316
+ raise exc.ArgumentError(
317
+ "Dialect %s does not support server side cursors" % self
318
+ )
319
+ else:
320
+ self.server_side_cursors = True
321
+
322
+ if getattr(self, "use_setinputsizes", False):
323
+ util.warn_deprecated(
324
+ "The dialect-level use_setinputsizes attribute is "
325
+ "deprecated. Please use "
326
+ "bind_typing = BindTyping.SETINPUTSIZES",
327
+ "2.0",
328
+ )
329
+ self.bind_typing = interfaces.BindTyping.SETINPUTSIZES
330
+
331
+ self.positional = False
332
+ self._ischema = None
333
+
334
+ self.dbapi = dbapi
335
+
336
+ self.skip_autocommit_rollback = skip_autocommit_rollback
337
+
338
+ if paramstyle is not None:
339
+ self.paramstyle = paramstyle
340
+ elif self.dbapi is not None:
341
+ self.paramstyle = self.dbapi.paramstyle
342
+ else:
343
+ self.paramstyle = self.default_paramstyle
344
+ self.positional = self.paramstyle in (
345
+ "qmark",
346
+ "format",
347
+ "numeric",
348
+ "numeric_dollar",
349
+ )
350
+ self.identifier_preparer = self.preparer(self)
351
+ self._on_connect_isolation_level = isolation_level
352
+
353
+ legacy_tt_callable = getattr(self, "type_compiler", None)
354
+ if legacy_tt_callable is not None:
355
+ tt_callable = cast(
356
+ Type[compiler.GenericTypeCompiler],
357
+ self.type_compiler,
358
+ )
359
+ else:
360
+ tt_callable = self.type_compiler_cls
361
+
362
+ self.type_compiler_instance = self.type_compiler = tt_callable(self)
363
+
364
+ if supports_native_boolean is not None:
365
+ self.supports_native_boolean = supports_native_boolean
366
+
367
+ self._user_defined_max_identifier_length = max_identifier_length
368
+ if self._user_defined_max_identifier_length:
369
+ self.max_identifier_length = (
370
+ self._user_defined_max_identifier_length
371
+ )
372
+ self.label_length = label_length
373
+ self.compiler_linting = compiler_linting
374
+
375
+ if use_insertmanyvalues is not None:
376
+ self.use_insertmanyvalues = use_insertmanyvalues
377
+
378
+ if insertmanyvalues_page_size is not _NoArg.NO_ARG:
379
+ self.insertmanyvalues_page_size = insertmanyvalues_page_size
380
+
381
+ @property
382
+ @util.deprecated(
383
+ "2.0",
384
+ "full_returning is deprecated, please use insert_returning, "
385
+ "update_returning, delete_returning",
386
+ )
387
+ def full_returning(self):
388
+ return (
389
+ self.insert_returning
390
+ and self.update_returning
391
+ and self.delete_returning
392
+ )
393
+
394
+ @util.memoized_property
395
+ def insert_executemany_returning(self):
396
+ """Default implementation for insert_executemany_returning, if not
397
+ otherwise overridden by the specific dialect.
398
+
399
+ The default dialect determines "insert_executemany_returning" is
400
+ available if the dialect in use has opted into using the
401
+ "use_insertmanyvalues" feature. If they haven't opted into that, then
402
+ this attribute is False, unless the dialect in question overrides this
403
+ and provides some other implementation (such as the Oracle Database
404
+ dialects).
405
+
406
+ """
407
+ return self.insert_returning and self.use_insertmanyvalues
408
+
409
+ @util.memoized_property
410
+ def insert_executemany_returning_sort_by_parameter_order(self):
411
+ """Default implementation for
412
+ insert_executemany_returning_deterministic_order, if not otherwise
413
+ overridden by the specific dialect.
414
+
415
+ The default dialect determines "insert_executemany_returning" can have
416
+ deterministic order only if the dialect in use has opted into using the
417
+ "use_insertmanyvalues" feature, which implements deterministic ordering
418
+ using client side sentinel columns only by default. The
419
+ "insertmanyvalues" feature also features alternate forms that can
420
+ use server-generated PK values as "sentinels", but those are only
421
+ used if the :attr:`.Dialect.insertmanyvalues_implicit_sentinel`
422
+ bitflag enables those alternate SQL forms, which are disabled
423
+ by default.
424
+
425
+ If the dialect in use hasn't opted into that, then this attribute is
426
+ False, unless the dialect in question overrides this and provides some
427
+ other implementation (such as the Oracle Database dialects).
428
+
429
+ """
430
+ return self.insert_returning and self.use_insertmanyvalues
431
+
432
+ update_executemany_returning = False
433
+ delete_executemany_returning = False
434
+
435
+ @util.memoized_property
436
+ def loaded_dbapi(self) -> DBAPIModule:
437
+ if self.dbapi is None:
438
+ raise exc.InvalidRequestError(
439
+ f"Dialect {self} does not have a Python DBAPI established "
440
+ "and cannot be used for actual database interaction"
441
+ )
442
+ return self.dbapi
443
+
444
+ @util.memoized_property
445
+ def _bind_typing_render_casts(self):
446
+ return self.bind_typing is interfaces.BindTyping.RENDER_CASTS
447
+
448
+ def _ensure_has_table_connection(self, arg: Connection) -> None:
449
+ if not isinstance(arg, Connection):
450
+ raise exc.ArgumentError(
451
+ "The argument passed to Dialect.has_table() should be a "
452
+ "%s, got %s. "
453
+ "Additionally, the Dialect.has_table() method is for "
454
+ "internal dialect "
455
+ "use only; please use "
456
+ "``inspect(some_engine).has_table(<tablename>>)`` "
457
+ "for public API use." % (Connection, type(arg))
458
+ )
459
+
460
+ @util.memoized_property
461
+ def _supports_statement_cache(self):
462
+ ssc = self.__class__.__dict__.get("supports_statement_cache", None)
463
+ if ssc is None:
464
+ util.warn(
465
+ "Dialect %s:%s will not make use of SQL compilation caching "
466
+ "as it does not set the 'supports_statement_cache' attribute "
467
+ "to ``True``. This can have "
468
+ "significant performance implications including some "
469
+ "performance degradations in comparison to prior SQLAlchemy "
470
+ "versions. Dialect maintainers should seek to set this "
471
+ "attribute to True after appropriate development and testing "
472
+ "for SQLAlchemy 1.4 caching support. Alternatively, this "
473
+ "attribute may be set to False which will disable this "
474
+ "warning." % (self.name, self.driver),
475
+ code="cprf",
476
+ )
477
+
478
+ return bool(ssc)
479
+
480
+ @util.memoized_property
481
+ def _type_memos(self):
482
+ return weakref.WeakKeyDictionary()
483
+
484
+ @property
485
+ def dialect_description(self): # type: ignore[override]
486
+ return self.name + "+" + self.driver
487
+
488
+ @property
489
+ def supports_sane_rowcount_returning(self):
490
+ """True if this dialect supports sane rowcount even if RETURNING is
491
+ in use.
492
+
493
+ For dialects that don't support RETURNING, this is synonymous with
494
+ ``supports_sane_rowcount``.
495
+
496
+ """
497
+ return self.supports_sane_rowcount
498
+
499
+ @classmethod
500
+ def get_pool_class(cls, url: URL) -> Type[Pool]:
501
+ return getattr(cls, "poolclass", pool.QueuePool)
502
+
503
+ def get_dialect_pool_class(self, url: URL) -> Type[Pool]:
504
+ return self.get_pool_class(url)
505
+
506
+ @classmethod
507
+ def load_provisioning(cls):
508
+ package = ".".join(cls.__module__.split(".")[0:-1])
509
+ try:
510
+ __import__(package + ".provision")
511
+ except ImportError:
512
+ pass
513
+
514
+ def _builtin_onconnect(self) -> Optional[_ListenerFnType]:
515
+ if self._on_connect_isolation_level is not None:
516
+
517
+ def builtin_connect(dbapi_conn, conn_rec):
518
+ self._assert_and_set_isolation_level(
519
+ dbapi_conn, self._on_connect_isolation_level
520
+ )
521
+
522
+ return builtin_connect
523
+ else:
524
+ return None
525
+
526
+ def initialize(self, connection: Connection) -> None:
527
+ try:
528
+ self.server_version_info = self._get_server_version_info(
529
+ connection
530
+ )
531
+ except NotImplementedError:
532
+ self.server_version_info = None
533
+ try:
534
+ self.default_schema_name = self._get_default_schema_name(
535
+ connection
536
+ )
537
+ except NotImplementedError:
538
+ self.default_schema_name = None
539
+
540
+ try:
541
+ self.default_isolation_level = self.get_default_isolation_level(
542
+ connection.connection.dbapi_connection
543
+ )
544
+ except NotImplementedError:
545
+ self.default_isolation_level = None
546
+
547
+ if not self._user_defined_max_identifier_length:
548
+ max_ident_length = self._check_max_identifier_length(connection)
549
+ if max_ident_length:
550
+ self.max_identifier_length = max_ident_length
551
+
552
+ if (
553
+ self.label_length
554
+ and self.label_length > self.max_identifier_length
555
+ ):
556
+ raise exc.ArgumentError(
557
+ "Label length of %d is greater than this dialect's"
558
+ " maximum identifier length of %d"
559
+ % (self.label_length, self.max_identifier_length)
560
+ )
561
+
562
+ def on_connect(self) -> Optional[Callable[[Any], None]]:
563
+ # inherits the docstring from interfaces.Dialect.on_connect
564
+ return None
565
+
566
+ def _check_max_identifier_length(self, connection):
567
+ """Perform a connection / server version specific check to determine
568
+ the max_identifier_length.
569
+
570
+ If the dialect's class level max_identifier_length should be used,
571
+ can return None.
572
+
573
+ .. versionadded:: 1.3.9
574
+
575
+ """
576
+ return None
577
+
578
+ def get_default_isolation_level(self, dbapi_conn):
579
+ """Given a DBAPI connection, return its isolation level, or
580
+ a default isolation level if one cannot be retrieved.
581
+
582
+ May be overridden by subclasses in order to provide a
583
+ "fallback" isolation level for databases that cannot reliably
584
+ retrieve the actual isolation level.
585
+
586
+ By default, calls the :meth:`_engine.Interfaces.get_isolation_level`
587
+ method, propagating any exceptions raised.
588
+
589
+ .. versionadded:: 1.3.22
590
+
591
+ """
592
+ return self.get_isolation_level(dbapi_conn)
593
+
594
+ def type_descriptor(self, typeobj):
595
+ """Provide a database-specific :class:`.TypeEngine` object, given
596
+ the generic object which comes from the types module.
597
+
598
+ This method looks for a dictionary called
599
+ ``colspecs`` as a class or instance-level variable,
600
+ and passes on to :func:`_types.adapt_type`.
601
+
602
+ """
603
+ return type_api.adapt_type(typeobj, self.colspecs)
604
+
605
+ def has_index(self, connection, table_name, index_name, schema=None, **kw):
606
+ if not self.has_table(connection, table_name, schema=schema, **kw):
607
+ return False
608
+ for idx in self.get_indexes(
609
+ connection, table_name, schema=schema, **kw
610
+ ):
611
+ if idx["name"] == index_name:
612
+ return True
613
+ else:
614
+ return False
615
+
616
+ def has_schema(
617
+ self, connection: Connection, schema_name: str, **kw: Any
618
+ ) -> bool:
619
+ return schema_name in self.get_schema_names(connection, **kw)
620
+
621
+ def validate_identifier(self, ident: str) -> None:
622
+ if len(ident) > self.max_identifier_length:
623
+ raise exc.IdentifierError(
624
+ "Identifier '%s' exceeds maximum length of %d characters"
625
+ % (ident, self.max_identifier_length)
626
+ )
627
+
628
+ def connect(self, *cargs: Any, **cparams: Any) -> DBAPIConnection:
629
+ # inherits the docstring from interfaces.Dialect.connect
630
+ return self.loaded_dbapi.connect(*cargs, **cparams) # type: ignore[no-any-return] # NOQA: E501
631
+
632
+ def create_connect_args(self, url: URL) -> ConnectArgsType:
633
+ # inherits the docstring from interfaces.Dialect.create_connect_args
634
+ opts = url.translate_connect_args()
635
+ opts.update(url.query)
636
+ return ([], opts)
637
+
638
+ def set_engine_execution_options(
639
+ self, engine: Engine, opts: Mapping[str, Any]
640
+ ) -> None:
641
+ supported_names = set(self.connection_characteristics).intersection(
642
+ opts
643
+ )
644
+ if supported_names:
645
+ characteristics: Mapping[str, Any] = util.immutabledict(
646
+ (name, opts[name]) for name in supported_names
647
+ )
648
+
649
+ @event.listens_for(engine, "engine_connect")
650
+ def set_connection_characteristics(connection):
651
+ self._set_connection_characteristics(
652
+ connection, characteristics
653
+ )
654
+
655
+ def set_connection_execution_options(
656
+ self, connection: Connection, opts: Mapping[str, Any]
657
+ ) -> None:
658
+ supported_names = set(self.connection_characteristics).intersection(
659
+ opts
660
+ )
661
+ if supported_names:
662
+ characteristics: Mapping[str, Any] = util.immutabledict(
663
+ (name, opts[name]) for name in supported_names
664
+ )
665
+ self._set_connection_characteristics(connection, characteristics)
666
+
667
+ def _set_connection_characteristics(self, connection, characteristics):
668
+ characteristic_values = [
669
+ (name, self.connection_characteristics[name], value)
670
+ for name, value in characteristics.items()
671
+ ]
672
+
673
+ if connection.in_transaction():
674
+ trans_objs = [
675
+ (name, obj)
676
+ for name, obj, _ in characteristic_values
677
+ if obj.transactional
678
+ ]
679
+ if trans_objs:
680
+ raise exc.InvalidRequestError(
681
+ "This connection has already initialized a SQLAlchemy "
682
+ "Transaction() object via begin() or autobegin; "
683
+ "%s may not be altered unless rollback() or commit() "
684
+ "is called first."
685
+ % (", ".join(name for name, obj in trans_objs))
686
+ )
687
+
688
+ dbapi_connection = connection.connection.dbapi_connection
689
+ for _, characteristic, value in characteristic_values:
690
+ characteristic.set_connection_characteristic(
691
+ self, connection, dbapi_connection, value
692
+ )
693
+ connection.connection._connection_record.finalize_callback.append(
694
+ functools.partial(self._reset_characteristics, characteristics)
695
+ )
696
+
697
+ def _reset_characteristics(self, characteristics, dbapi_connection):
698
+ for characteristic_name in characteristics:
699
+ characteristic = self.connection_characteristics[
700
+ characteristic_name
701
+ ]
702
+ characteristic.reset_characteristic(self, dbapi_connection)
703
+
704
+ def do_begin(self, dbapi_connection):
705
+ pass
706
+
707
+ def do_rollback(self, dbapi_connection):
708
+ if self.skip_autocommit_rollback and self.detect_autocommit_setting(
709
+ dbapi_connection
710
+ ):
711
+ return
712
+ dbapi_connection.rollback()
713
+
714
+ def do_commit(self, dbapi_connection):
715
+ dbapi_connection.commit()
716
+
717
+ def do_terminate(self, dbapi_connection):
718
+ self.do_close(dbapi_connection)
719
+
720
+ def do_close(self, dbapi_connection):
721
+ dbapi_connection.close()
722
+
723
+ @util.memoized_property
724
+ def _dialect_specific_select_one(self):
725
+ return str(expression.select(1).compile(dialect=self))
726
+
727
+ def _do_ping_w_event(self, dbapi_connection: DBAPIConnection) -> bool:
728
+ try:
729
+ return self.do_ping(dbapi_connection)
730
+ except self.loaded_dbapi.Error as err:
731
+ is_disconnect = self.is_disconnect(err, dbapi_connection, None)
732
+
733
+ if self._has_events:
734
+ try:
735
+ Connection._handle_dbapi_exception_noconnection(
736
+ err,
737
+ self,
738
+ is_disconnect=is_disconnect,
739
+ invalidate_pool_on_disconnect=False,
740
+ is_pre_ping=True,
741
+ )
742
+ except exc.StatementError as new_err:
743
+ is_disconnect = new_err.connection_invalidated
744
+
745
+ if is_disconnect:
746
+ return False
747
+ else:
748
+ raise
749
+
750
+ def do_ping(self, dbapi_connection: DBAPIConnection) -> bool:
751
+ cursor = dbapi_connection.cursor()
752
+ try:
753
+ cursor.execute(self._dialect_specific_select_one)
754
+ finally:
755
+ cursor.close()
756
+ return True
757
+
758
+ def create_xid(self):
759
+ """Create a random two-phase transaction ID.
760
+
761
+ This id will be passed to do_begin_twophase(), do_rollback_twophase(),
762
+ do_commit_twophase(). Its format is unspecified.
763
+ """
764
+
765
+ return "_sa_%032x" % random.randint(0, 2**128)
766
+
767
+ def do_savepoint(self, connection, name):
768
+ connection.execute(expression.SavepointClause(name))
769
+
770
+ def do_rollback_to_savepoint(self, connection, name):
771
+ connection.execute(expression.RollbackToSavepointClause(name))
772
+
773
+ def do_release_savepoint(self, connection, name):
774
+ connection.execute(expression.ReleaseSavepointClause(name))
775
+
776
+ def _deliver_insertmanyvalues_batches(
777
+ self,
778
+ connection,
779
+ cursor,
780
+ statement,
781
+ parameters,
782
+ generic_setinputsizes,
783
+ context,
784
+ ):
785
+ context = cast(DefaultExecutionContext, context)
786
+ compiled = cast(SQLCompiler, context.compiled)
787
+
788
+ _composite_sentinel_proc: Sequence[
789
+ Optional[_ResultProcessorType[Any]]
790
+ ] = ()
791
+ _scalar_sentinel_proc: Optional[_ResultProcessorType[Any]] = None
792
+ _sentinel_proc_initialized: bool = False
793
+
794
+ compiled_parameters = context.compiled_parameters
795
+
796
+ imv = compiled._insertmanyvalues
797
+ assert imv is not None
798
+
799
+ is_returning: Final[bool] = bool(compiled.effective_returning)
800
+ batch_size = context.execution_options.get(
801
+ "insertmanyvalues_page_size", self.insertmanyvalues_page_size
802
+ )
803
+
804
+ if compiled.schema_translate_map:
805
+ schema_translate_map = context.execution_options.get(
806
+ "schema_translate_map", {}
807
+ )
808
+ else:
809
+ schema_translate_map = None
810
+
811
+ if is_returning:
812
+ result: Optional[List[Any]] = []
813
+ context._insertmanyvalues_rows = result
814
+
815
+ sort_by_parameter_order = imv.sort_by_parameter_order
816
+
817
+ else:
818
+ sort_by_parameter_order = False
819
+ result = None
820
+
821
+ for imv_batch in compiled._deliver_insertmanyvalues_batches(
822
+ statement,
823
+ parameters,
824
+ compiled_parameters,
825
+ generic_setinputsizes,
826
+ batch_size,
827
+ sort_by_parameter_order,
828
+ schema_translate_map,
829
+ ):
830
+ yield imv_batch
831
+
832
+ if is_returning:
833
+
834
+ try:
835
+ rows = context.fetchall_for_returning(cursor)
836
+ except BaseException as be:
837
+ connection._handle_dbapi_exception(
838
+ be,
839
+ sql_util._long_statement(imv_batch.replaced_statement),
840
+ imv_batch.replaced_parameters,
841
+ None,
842
+ context,
843
+ is_sub_exec=True,
844
+ )
845
+
846
+ # I would have thought "is_returning: Final[bool]"
847
+ # would have assured this but pylance thinks not
848
+ assert result is not None
849
+
850
+ if imv.num_sentinel_columns and not imv_batch.is_downgraded:
851
+ composite_sentinel = imv.num_sentinel_columns > 1
852
+ if imv.implicit_sentinel:
853
+ # for implicit sentinel, which is currently single-col
854
+ # integer autoincrement, do a simple sort.
855
+ assert not composite_sentinel
856
+ result.extend(
857
+ sorted(rows, key=operator.itemgetter(-1))
858
+ )
859
+ continue
860
+
861
+ # otherwise, create dictionaries to match up batches
862
+ # with parameters
863
+ assert imv.sentinel_param_keys
864
+ assert imv.sentinel_columns
865
+
866
+ _nsc = imv.num_sentinel_columns
867
+
868
+ if not _sentinel_proc_initialized:
869
+ if composite_sentinel:
870
+ _composite_sentinel_proc = [
871
+ col.type._cached_result_processor(
872
+ self, cursor_desc[1]
873
+ )
874
+ for col, cursor_desc in zip(
875
+ imv.sentinel_columns,
876
+ cursor.description[-_nsc:],
877
+ )
878
+ ]
879
+ else:
880
+ _scalar_sentinel_proc = (
881
+ imv.sentinel_columns[0]
882
+ ).type._cached_result_processor(
883
+ self, cursor.description[-1][1]
884
+ )
885
+ _sentinel_proc_initialized = True
886
+
887
+ rows_by_sentinel: Union[
888
+ Dict[Tuple[Any, ...], Any],
889
+ Dict[Any, Any],
890
+ ]
891
+ if composite_sentinel:
892
+ rows_by_sentinel = {
893
+ tuple(
894
+ (proc(val) if proc else val)
895
+ for val, proc in zip(
896
+ row[-_nsc:], _composite_sentinel_proc
897
+ )
898
+ ): row
899
+ for row in rows
900
+ }
901
+ elif _scalar_sentinel_proc:
902
+ rows_by_sentinel = {
903
+ _scalar_sentinel_proc(row[-1]): row for row in rows
904
+ }
905
+ else:
906
+ rows_by_sentinel = {row[-1]: row for row in rows}
907
+
908
+ if len(rows_by_sentinel) != len(imv_batch.batch):
909
+ # see test_insert_exec.py::
910
+ # IMVSentinelTest::test_sentinel_incorrect_rowcount
911
+ # for coverage / demonstration
912
+ raise exc.InvalidRequestError(
913
+ f"Sentinel-keyed result set did not produce "
914
+ f"correct number of rows {len(imv_batch.batch)}; "
915
+ "produced "
916
+ f"{len(rows_by_sentinel)}. Please ensure the "
917
+ "sentinel column is fully unique and populated in "
918
+ "all cases."
919
+ )
920
+
921
+ try:
922
+ ordered_rows = [
923
+ rows_by_sentinel[sentinel_keys]
924
+ for sentinel_keys in imv_batch.sentinel_values
925
+ ]
926
+ except KeyError as ke:
927
+ # see test_insert_exec.py::
928
+ # IMVSentinelTest::test_sentinel_cant_match_keys
929
+ # for coverage / demonstration
930
+ raise exc.InvalidRequestError(
931
+ f"Can't match sentinel values in result set to "
932
+ f"parameter sets; key {ke.args[0]!r} was not "
933
+ "found. "
934
+ "There may be a mismatch between the datatype "
935
+ "passed to the DBAPI driver vs. that which it "
936
+ "returns in a result row. Ensure the given "
937
+ "Python value matches the expected result type "
938
+ "*exactly*, taking care to not rely upon implicit "
939
+ "conversions which may occur such as when using "
940
+ "strings in place of UUID or integer values, etc. "
941
+ ) from ke
942
+
943
+ result.extend(ordered_rows)
944
+
945
+ else:
946
+ result.extend(rows)
947
+
948
+ def do_executemany(self, cursor, statement, parameters, context=None):
949
+ cursor.executemany(statement, parameters)
950
+
951
+ def do_execute(self, cursor, statement, parameters, context=None):
952
+ cursor.execute(statement, parameters)
953
+
954
+ def do_execute_no_params(self, cursor, statement, context=None):
955
+ cursor.execute(statement)
956
+
957
+ def is_disconnect(
958
+ self,
959
+ e: DBAPIModule.Error,
960
+ connection: Union[
961
+ pool.PoolProxiedConnection, interfaces.DBAPIConnection, None
962
+ ],
963
+ cursor: Optional[interfaces.DBAPICursor],
964
+ ) -> bool:
965
+ return False
966
+
967
+ @util.memoized_instancemethod
968
+ def _gen_allowed_isolation_levels(self, dbapi_conn):
969
+ try:
970
+ raw_levels = list(self.get_isolation_level_values(dbapi_conn))
971
+ except NotImplementedError:
972
+ return None
973
+ else:
974
+ normalized_levels = [
975
+ level.replace("_", " ").upper() for level in raw_levels
976
+ ]
977
+ if raw_levels != normalized_levels:
978
+ raise ValueError(
979
+ f"Dialect {self.name!r} get_isolation_level_values() "
980
+ f"method should return names as UPPERCASE using spaces, "
981
+ f"not underscores; got "
982
+ f"{sorted(set(raw_levels).difference(normalized_levels))}"
983
+ )
984
+ return tuple(normalized_levels)
985
+
986
+ def _assert_and_set_isolation_level(self, dbapi_conn, level):
987
+ level = level.replace("_", " ").upper()
988
+
989
+ _allowed_isolation_levels = self._gen_allowed_isolation_levels(
990
+ dbapi_conn
991
+ )
992
+ if (
993
+ _allowed_isolation_levels
994
+ and level not in _allowed_isolation_levels
995
+ ):
996
+ raise exc.ArgumentError(
997
+ f"Invalid value {level!r} for isolation_level. "
998
+ f"Valid isolation levels for {self.name!r} are "
999
+ f"{', '.join(_allowed_isolation_levels)}"
1000
+ )
1001
+
1002
+ self.set_isolation_level(dbapi_conn, level)
1003
+
1004
+ def reset_isolation_level(self, dbapi_conn):
1005
+ if self._on_connect_isolation_level is not None:
1006
+ assert (
1007
+ self._on_connect_isolation_level == "AUTOCOMMIT"
1008
+ or self._on_connect_isolation_level
1009
+ == self.default_isolation_level
1010
+ )
1011
+ self._assert_and_set_isolation_level(
1012
+ dbapi_conn, self._on_connect_isolation_level
1013
+ )
1014
+ else:
1015
+ assert self.default_isolation_level is not None
1016
+ self._assert_and_set_isolation_level(
1017
+ dbapi_conn,
1018
+ self.default_isolation_level,
1019
+ )
1020
+
1021
+ def normalize_name(self, name):
1022
+ if name is None:
1023
+ return None
1024
+
1025
+ name_lower = name.lower()
1026
+ name_upper = name.upper()
1027
+
1028
+ if name_upper == name_lower:
1029
+ # name has no upper/lower conversion, e.g. non-european characters.
1030
+ # return unchanged
1031
+ return name
1032
+ elif name_upper == name and not (
1033
+ self.identifier_preparer._requires_quotes
1034
+ )(name_lower):
1035
+ # name is all uppercase and doesn't require quoting; normalize
1036
+ # to all lower case
1037
+ return name_lower
1038
+ elif name_lower == name:
1039
+ # name is all lower case, which if denormalized means we need to
1040
+ # force quoting on it
1041
+ return quoted_name(name, quote=True)
1042
+ else:
1043
+ # name is mixed case, means it will be quoted in SQL when used
1044
+ # later, no normalizes
1045
+ return name
1046
+
1047
+ def denormalize_name(self, name):
1048
+ if name is None:
1049
+ return None
1050
+
1051
+ name_lower = name.lower()
1052
+ name_upper = name.upper()
1053
+
1054
+ if name_upper == name_lower:
1055
+ # name has no upper/lower conversion, e.g. non-european characters.
1056
+ # return unchanged
1057
+ return name
1058
+ elif name_lower == name and not (
1059
+ self.identifier_preparer._requires_quotes
1060
+ )(name_lower):
1061
+ name = name_upper
1062
+ return name
1063
+
1064
+ def get_driver_connection(self, connection: DBAPIConnection) -> Any:
1065
+ return connection
1066
+
1067
+ def _overrides_default(self, method):
1068
+ return (
1069
+ getattr(type(self), method).__code__
1070
+ is not getattr(DefaultDialect, method).__code__
1071
+ )
1072
+
1073
+ def _default_multi_reflect(
1074
+ self,
1075
+ single_tbl_method,
1076
+ connection,
1077
+ kind,
1078
+ schema,
1079
+ filter_names,
1080
+ scope,
1081
+ **kw,
1082
+ ):
1083
+ names_fns = []
1084
+ temp_names_fns = []
1085
+ if ObjectKind.TABLE in kind:
1086
+ names_fns.append(self.get_table_names)
1087
+ temp_names_fns.append(self.get_temp_table_names)
1088
+ if ObjectKind.VIEW in kind:
1089
+ names_fns.append(self.get_view_names)
1090
+ temp_names_fns.append(self.get_temp_view_names)
1091
+ if ObjectKind.MATERIALIZED_VIEW in kind:
1092
+ names_fns.append(self.get_materialized_view_names)
1093
+ # no temp materialized view at the moment
1094
+ # temp_names_fns.append(self.get_temp_materialized_view_names)
1095
+
1096
+ unreflectable = kw.pop("unreflectable", {})
1097
+
1098
+ if (
1099
+ filter_names
1100
+ and scope is ObjectScope.ANY
1101
+ and kind is ObjectKind.ANY
1102
+ ):
1103
+ # if names are given and no qualification on type of table
1104
+ # (i.e. the Table(..., autoload) case), take the names as given,
1105
+ # don't run names queries. If a table does not exit
1106
+ # NoSuchTableError is raised and it's skipped
1107
+
1108
+ # this also suits the case for mssql where we can reflect
1109
+ # individual temp tables but there's no temp_names_fn
1110
+ names = filter_names
1111
+ else:
1112
+ names = []
1113
+ name_kw = {"schema": schema, **kw}
1114
+ fns = []
1115
+ if ObjectScope.DEFAULT in scope:
1116
+ fns.extend(names_fns)
1117
+ if ObjectScope.TEMPORARY in scope:
1118
+ fns.extend(temp_names_fns)
1119
+
1120
+ for fn in fns:
1121
+ try:
1122
+ names.extend(fn(connection, **name_kw))
1123
+ except NotImplementedError:
1124
+ pass
1125
+
1126
+ if filter_names:
1127
+ filter_names = set(filter_names)
1128
+
1129
+ # iterate over all the tables/views and call the single table method
1130
+ for table in names:
1131
+ if not filter_names or table in filter_names:
1132
+ key = (schema, table)
1133
+ try:
1134
+ yield (
1135
+ key,
1136
+ single_tbl_method(
1137
+ connection, table, schema=schema, **kw
1138
+ ),
1139
+ )
1140
+ except exc.UnreflectableTableError as err:
1141
+ if key not in unreflectable:
1142
+ unreflectable[key] = err
1143
+ except exc.NoSuchTableError:
1144
+ pass
1145
+
1146
+ def get_multi_table_options(self, connection, **kw):
1147
+ return self._default_multi_reflect(
1148
+ self.get_table_options, connection, **kw
1149
+ )
1150
+
1151
+ def get_multi_columns(self, connection, **kw):
1152
+ return self._default_multi_reflect(self.get_columns, connection, **kw)
1153
+
1154
+ def get_multi_pk_constraint(self, connection, **kw):
1155
+ return self._default_multi_reflect(
1156
+ self.get_pk_constraint, connection, **kw
1157
+ )
1158
+
1159
+ def get_multi_foreign_keys(self, connection, **kw):
1160
+ return self._default_multi_reflect(
1161
+ self.get_foreign_keys, connection, **kw
1162
+ )
1163
+
1164
+ def get_multi_indexes(self, connection, **kw):
1165
+ return self._default_multi_reflect(self.get_indexes, connection, **kw)
1166
+
1167
+ def get_multi_unique_constraints(self, connection, **kw):
1168
+ return self._default_multi_reflect(
1169
+ self.get_unique_constraints, connection, **kw
1170
+ )
1171
+
1172
+ def get_multi_check_constraints(self, connection, **kw):
1173
+ return self._default_multi_reflect(
1174
+ self.get_check_constraints, connection, **kw
1175
+ )
1176
+
1177
+ def get_multi_table_comment(self, connection, **kw):
1178
+ return self._default_multi_reflect(
1179
+ self.get_table_comment, connection, **kw
1180
+ )
1181
+
1182
+
1183
+ class StrCompileDialect(DefaultDialect):
1184
+ statement_compiler = compiler.StrSQLCompiler
1185
+ ddl_compiler = compiler.DDLCompiler
1186
+ type_compiler_cls = compiler.StrSQLTypeCompiler
1187
+ preparer = compiler.IdentifierPreparer
1188
+
1189
+ insert_returning = True
1190
+ update_returning = True
1191
+ delete_returning = True
1192
+
1193
+ supports_statement_cache = True
1194
+
1195
+ supports_identity_columns = True
1196
+
1197
+ supports_sequences = True
1198
+ sequences_optional = True
1199
+ preexecute_autoincrement_sequences = False
1200
+
1201
+ supports_native_boolean = True
1202
+
1203
+ supports_multivalues_insert = True
1204
+ supports_simple_order_by_label = True
1205
+
1206
+
1207
+ class DefaultExecutionContext(ExecutionContext):
1208
+ isinsert = False
1209
+ isupdate = False
1210
+ isdelete = False
1211
+ is_crud = False
1212
+ is_text = False
1213
+ isddl = False
1214
+
1215
+ execute_style: ExecuteStyle = ExecuteStyle.EXECUTE
1216
+
1217
+ compiled: Optional[Compiled] = None
1218
+ result_column_struct: Optional[
1219
+ Tuple[List[ResultColumnsEntry], bool, bool, bool, bool]
1220
+ ] = None
1221
+ returned_default_rows: Optional[Sequence[Row[Any]]] = None
1222
+
1223
+ execution_options: _ExecuteOptions = util.EMPTY_DICT
1224
+
1225
+ cursor_fetch_strategy = _cursor._DEFAULT_FETCH
1226
+
1227
+ invoked_statement: Optional[Executable] = None
1228
+
1229
+ _is_implicit_returning = False
1230
+ _is_explicit_returning = False
1231
+ _is_supplemental_returning = False
1232
+ _is_server_side = False
1233
+
1234
+ _soft_closed = False
1235
+
1236
+ _rowcount: Optional[int] = None
1237
+
1238
+ # a hook for SQLite's translation of
1239
+ # result column names
1240
+ # NOTE: pyhive is using this hook, can't remove it :(
1241
+ _translate_colname: Optional[
1242
+ Callable[[str], Tuple[str, Optional[str]]]
1243
+ ] = None
1244
+
1245
+ _expanded_parameters: Mapping[str, List[str]] = util.immutabledict()
1246
+ """used by set_input_sizes().
1247
+
1248
+ This collection comes from ``ExpandedState.parameter_expansion``.
1249
+
1250
+ """
1251
+
1252
+ cache_hit = NO_CACHE_KEY
1253
+
1254
+ root_connection: Connection
1255
+ _dbapi_connection: PoolProxiedConnection
1256
+ dialect: Dialect
1257
+ unicode_statement: str
1258
+ cursor: DBAPICursor
1259
+ compiled_parameters: List[_MutableCoreSingleExecuteParams]
1260
+ parameters: _DBAPIMultiExecuteParams
1261
+ extracted_parameters: Optional[Sequence[BindParameter[Any]]]
1262
+
1263
+ _empty_dict_params = cast("Mapping[str, Any]", util.EMPTY_DICT)
1264
+
1265
+ _insertmanyvalues_rows: Optional[List[Tuple[Any, ...]]] = None
1266
+ _num_sentinel_cols: int = 0
1267
+
1268
+ @classmethod
1269
+ def _init_ddl(
1270
+ cls,
1271
+ dialect: Dialect,
1272
+ connection: Connection,
1273
+ dbapi_connection: PoolProxiedConnection,
1274
+ execution_options: _ExecuteOptions,
1275
+ compiled_ddl: DDLCompiler,
1276
+ ) -> ExecutionContext:
1277
+ """Initialize execution context for an ExecutableDDLElement
1278
+ construct."""
1279
+
1280
+ self = cls.__new__(cls)
1281
+ self.root_connection = connection
1282
+ self._dbapi_connection = dbapi_connection
1283
+ self.dialect = connection.dialect
1284
+
1285
+ self.compiled = compiled = compiled_ddl
1286
+ self.isddl = True
1287
+
1288
+ self.execution_options = execution_options
1289
+
1290
+ self.unicode_statement = str(compiled)
1291
+ if compiled.schema_translate_map:
1292
+ schema_translate_map = self.execution_options.get(
1293
+ "schema_translate_map", {}
1294
+ )
1295
+
1296
+ rst = compiled.preparer._render_schema_translates
1297
+ self.unicode_statement = rst(
1298
+ self.unicode_statement, schema_translate_map
1299
+ )
1300
+
1301
+ self.statement = self.unicode_statement
1302
+
1303
+ self.cursor = self.create_cursor()
1304
+ self.compiled_parameters = []
1305
+
1306
+ if dialect.positional:
1307
+ self.parameters = [dialect.execute_sequence_format()]
1308
+ else:
1309
+ self.parameters = [self._empty_dict_params]
1310
+
1311
+ return self
1312
+
1313
+ @classmethod
1314
+ def _init_compiled(
1315
+ cls,
1316
+ dialect: Dialect,
1317
+ connection: Connection,
1318
+ dbapi_connection: PoolProxiedConnection,
1319
+ execution_options: _ExecuteOptions,
1320
+ compiled: SQLCompiler,
1321
+ parameters: _CoreMultiExecuteParams,
1322
+ invoked_statement: Executable,
1323
+ extracted_parameters: Optional[Sequence[BindParameter[Any]]],
1324
+ cache_hit: CacheStats = CacheStats.CACHING_DISABLED,
1325
+ ) -> ExecutionContext:
1326
+ """Initialize execution context for a Compiled construct."""
1327
+
1328
+ self = cls.__new__(cls)
1329
+ self.root_connection = connection
1330
+ self._dbapi_connection = dbapi_connection
1331
+ self.dialect = connection.dialect
1332
+ self.extracted_parameters = extracted_parameters
1333
+ self.invoked_statement = invoked_statement
1334
+ self.compiled = compiled
1335
+ self.cache_hit = cache_hit
1336
+
1337
+ self.execution_options = execution_options
1338
+
1339
+ self.result_column_struct = (
1340
+ compiled._result_columns,
1341
+ compiled._ordered_columns,
1342
+ compiled._textual_ordered_columns,
1343
+ compiled._ad_hoc_textual,
1344
+ compiled._loose_column_name_matching,
1345
+ )
1346
+
1347
+ self.isinsert = ii = compiled.isinsert
1348
+ self.isupdate = iu = compiled.isupdate
1349
+ self.isdelete = id_ = compiled.isdelete
1350
+ self.is_text = compiled.isplaintext
1351
+
1352
+ if ii or iu or id_:
1353
+ dml_statement = compiled.compile_state.statement # type: ignore
1354
+ if TYPE_CHECKING:
1355
+ assert isinstance(dml_statement, UpdateBase)
1356
+ self.is_crud = True
1357
+ self._is_explicit_returning = ier = bool(dml_statement._returning)
1358
+ self._is_implicit_returning = iir = bool(
1359
+ compiled.implicit_returning
1360
+ )
1361
+ if iir and dml_statement._supplemental_returning:
1362
+ self._is_supplemental_returning = True
1363
+
1364
+ # dont mix implicit and explicit returning
1365
+ assert not (iir and ier)
1366
+
1367
+ if (ier or iir) and compiled.for_executemany:
1368
+ if ii and not self.dialect.insert_executemany_returning:
1369
+ raise exc.InvalidRequestError(
1370
+ f"Dialect {self.dialect.dialect_description} with "
1371
+ f"current server capabilities does not support "
1372
+ "INSERT..RETURNING when executemany is used"
1373
+ )
1374
+ elif (
1375
+ ii
1376
+ and dml_statement._sort_by_parameter_order
1377
+ and not self.dialect.insert_executemany_returning_sort_by_parameter_order # noqa: E501
1378
+ ):
1379
+ raise exc.InvalidRequestError(
1380
+ f"Dialect {self.dialect.dialect_description} with "
1381
+ f"current server capabilities does not support "
1382
+ "INSERT..RETURNING with deterministic row ordering "
1383
+ "when executemany is used"
1384
+ )
1385
+ elif (
1386
+ ii
1387
+ and self.dialect.use_insertmanyvalues
1388
+ and not compiled._insertmanyvalues
1389
+ ):
1390
+ raise exc.InvalidRequestError(
1391
+ 'Statement does not have "insertmanyvalues" '
1392
+ "enabled, can't use INSERT..RETURNING with "
1393
+ "executemany in this case."
1394
+ )
1395
+ elif iu and not self.dialect.update_executemany_returning:
1396
+ raise exc.InvalidRequestError(
1397
+ f"Dialect {self.dialect.dialect_description} with "
1398
+ f"current server capabilities does not support "
1399
+ "UPDATE..RETURNING when executemany is used"
1400
+ )
1401
+ elif id_ and not self.dialect.delete_executemany_returning:
1402
+ raise exc.InvalidRequestError(
1403
+ f"Dialect {self.dialect.dialect_description} with "
1404
+ f"current server capabilities does not support "
1405
+ "DELETE..RETURNING when executemany is used"
1406
+ )
1407
+
1408
+ if not parameters:
1409
+ self.compiled_parameters = [
1410
+ compiled.construct_params(
1411
+ extracted_parameters=extracted_parameters,
1412
+ escape_names=False,
1413
+ )
1414
+ ]
1415
+ else:
1416
+ self.compiled_parameters = [
1417
+ compiled.construct_params(
1418
+ m,
1419
+ escape_names=False,
1420
+ _group_number=grp,
1421
+ extracted_parameters=extracted_parameters,
1422
+ )
1423
+ for grp, m in enumerate(parameters)
1424
+ ]
1425
+
1426
+ if len(parameters) > 1:
1427
+ if self.isinsert and compiled._insertmanyvalues:
1428
+ self.execute_style = ExecuteStyle.INSERTMANYVALUES
1429
+
1430
+ imv = compiled._insertmanyvalues
1431
+ if imv.sentinel_columns is not None:
1432
+ self._num_sentinel_cols = imv.num_sentinel_columns
1433
+ else:
1434
+ self.execute_style = ExecuteStyle.EXECUTEMANY
1435
+
1436
+ self.unicode_statement = compiled.string
1437
+
1438
+ self.cursor = self.create_cursor()
1439
+
1440
+ if self.compiled.insert_prefetch or self.compiled.update_prefetch:
1441
+ self._process_execute_defaults()
1442
+
1443
+ processors = compiled._bind_processors
1444
+
1445
+ flattened_processors: Mapping[
1446
+ str, _BindProcessorType[Any]
1447
+ ] = processors # type: ignore[assignment]
1448
+
1449
+ if compiled.literal_execute_params or compiled.post_compile_params:
1450
+ if self.executemany:
1451
+ raise exc.InvalidRequestError(
1452
+ "'literal_execute' or 'expanding' parameters can't be "
1453
+ "used with executemany()"
1454
+ )
1455
+
1456
+ expanded_state = compiled._process_parameters_for_postcompile(
1457
+ self.compiled_parameters[0]
1458
+ )
1459
+
1460
+ # re-assign self.unicode_statement
1461
+ self.unicode_statement = expanded_state.statement
1462
+
1463
+ self._expanded_parameters = expanded_state.parameter_expansion
1464
+
1465
+ flattened_processors = dict(processors) # type: ignore
1466
+ flattened_processors.update(expanded_state.processors)
1467
+ positiontup = expanded_state.positiontup
1468
+ elif compiled.positional:
1469
+ positiontup = self.compiled.positiontup
1470
+ else:
1471
+ positiontup = None
1472
+
1473
+ if compiled.schema_translate_map:
1474
+ schema_translate_map = self.execution_options.get(
1475
+ "schema_translate_map", {}
1476
+ )
1477
+ rst = compiled.preparer._render_schema_translates
1478
+ self.unicode_statement = rst(
1479
+ self.unicode_statement, schema_translate_map
1480
+ )
1481
+
1482
+ # final self.unicode_statement is now assigned, encode if needed
1483
+ # by dialect
1484
+ self.statement = self.unicode_statement
1485
+
1486
+ # Convert the dictionary of bind parameter values
1487
+ # into a dict or list to be sent to the DBAPI's
1488
+ # execute() or executemany() method.
1489
+
1490
+ if compiled.positional:
1491
+ core_positional_parameters: MutableSequence[Sequence[Any]] = []
1492
+ assert positiontup is not None
1493
+ for compiled_params in self.compiled_parameters:
1494
+ l_param: List[Any] = [
1495
+ (
1496
+ flattened_processors[key](compiled_params[key])
1497
+ if key in flattened_processors
1498
+ else compiled_params[key]
1499
+ )
1500
+ for key in positiontup
1501
+ ]
1502
+ core_positional_parameters.append(
1503
+ dialect.execute_sequence_format(l_param)
1504
+ )
1505
+
1506
+ self.parameters = core_positional_parameters
1507
+ else:
1508
+ core_dict_parameters: MutableSequence[Dict[str, Any]] = []
1509
+ escaped_names = compiled.escaped_bind_names
1510
+
1511
+ # note that currently, "expanded" parameters will be present
1512
+ # in self.compiled_parameters in their quoted form. This is
1513
+ # slightly inconsistent with the approach taken as of
1514
+ # #8056 where self.compiled_parameters is meant to contain unquoted
1515
+ # param names.
1516
+ d_param: Dict[str, Any]
1517
+ for compiled_params in self.compiled_parameters:
1518
+ if escaped_names:
1519
+ d_param = {
1520
+ escaped_names.get(key, key): (
1521
+ flattened_processors[key](compiled_params[key])
1522
+ if key in flattened_processors
1523
+ else compiled_params[key]
1524
+ )
1525
+ for key in compiled_params
1526
+ }
1527
+ else:
1528
+ d_param = {
1529
+ key: (
1530
+ flattened_processors[key](compiled_params[key])
1531
+ if key in flattened_processors
1532
+ else compiled_params[key]
1533
+ )
1534
+ for key in compiled_params
1535
+ }
1536
+
1537
+ core_dict_parameters.append(d_param)
1538
+
1539
+ self.parameters = core_dict_parameters
1540
+
1541
+ return self
1542
+
1543
+ @classmethod
1544
+ def _init_statement(
1545
+ cls,
1546
+ dialect: Dialect,
1547
+ connection: Connection,
1548
+ dbapi_connection: PoolProxiedConnection,
1549
+ execution_options: _ExecuteOptions,
1550
+ statement: str,
1551
+ parameters: _DBAPIMultiExecuteParams,
1552
+ ) -> ExecutionContext:
1553
+ """Initialize execution context for a string SQL statement."""
1554
+
1555
+ self = cls.__new__(cls)
1556
+ self.root_connection = connection
1557
+ self._dbapi_connection = dbapi_connection
1558
+ self.dialect = connection.dialect
1559
+ self.is_text = True
1560
+
1561
+ self.execution_options = execution_options
1562
+
1563
+ if not parameters:
1564
+ if self.dialect.positional:
1565
+ self.parameters = [dialect.execute_sequence_format()]
1566
+ else:
1567
+ self.parameters = [self._empty_dict_params]
1568
+ elif isinstance(parameters[0], dialect.execute_sequence_format):
1569
+ self.parameters = parameters
1570
+ elif isinstance(parameters[0], dict):
1571
+ self.parameters = parameters
1572
+ else:
1573
+ self.parameters = [
1574
+ dialect.execute_sequence_format(p) for p in parameters
1575
+ ]
1576
+
1577
+ if len(parameters) > 1:
1578
+ self.execute_style = ExecuteStyle.EXECUTEMANY
1579
+
1580
+ self.statement = self.unicode_statement = statement
1581
+
1582
+ self.cursor = self.create_cursor()
1583
+ return self
1584
+
1585
+ @classmethod
1586
+ def _init_default(
1587
+ cls,
1588
+ dialect: Dialect,
1589
+ connection: Connection,
1590
+ dbapi_connection: PoolProxiedConnection,
1591
+ execution_options: _ExecuteOptions,
1592
+ ) -> ExecutionContext:
1593
+ """Initialize execution context for a ColumnDefault construct."""
1594
+
1595
+ self = cls.__new__(cls)
1596
+ self.root_connection = connection
1597
+ self._dbapi_connection = dbapi_connection
1598
+ self.dialect = connection.dialect
1599
+
1600
+ self.execution_options = execution_options
1601
+
1602
+ self.cursor = self.create_cursor()
1603
+ return self
1604
+
1605
+ def _get_cache_stats(self) -> str:
1606
+ if self.compiled is None:
1607
+ return "raw sql"
1608
+
1609
+ now = perf_counter()
1610
+
1611
+ ch = self.cache_hit
1612
+
1613
+ gen_time = self.compiled._gen_time
1614
+ assert gen_time is not None
1615
+
1616
+ if ch is NO_CACHE_KEY:
1617
+ return "no key %.5fs" % (now - gen_time,)
1618
+ elif ch is CACHE_HIT:
1619
+ return "cached since %.4gs ago" % (now - gen_time,)
1620
+ elif ch is CACHE_MISS:
1621
+ return "generated in %.5fs" % (now - gen_time,)
1622
+ elif ch is CACHING_DISABLED:
1623
+ if "_cache_disable_reason" in self.execution_options:
1624
+ return "caching disabled (%s) %.5fs " % (
1625
+ self.execution_options["_cache_disable_reason"],
1626
+ now - gen_time,
1627
+ )
1628
+ else:
1629
+ return "caching disabled %.5fs" % (now - gen_time,)
1630
+ elif ch is NO_DIALECT_SUPPORT:
1631
+ return "dialect %s+%s does not support caching %.5fs" % (
1632
+ self.dialect.name,
1633
+ self.dialect.driver,
1634
+ now - gen_time,
1635
+ )
1636
+ else:
1637
+ return "unknown"
1638
+
1639
+ @property
1640
+ def executemany(self): # type: ignore[override]
1641
+ return self.execute_style in (
1642
+ ExecuteStyle.EXECUTEMANY,
1643
+ ExecuteStyle.INSERTMANYVALUES,
1644
+ )
1645
+
1646
+ @util.memoized_property
1647
+ def identifier_preparer(self):
1648
+ if self.compiled:
1649
+ return self.compiled.preparer
1650
+ elif "schema_translate_map" in self.execution_options:
1651
+ return self.dialect.identifier_preparer._with_schema_translate(
1652
+ self.execution_options["schema_translate_map"]
1653
+ )
1654
+ else:
1655
+ return self.dialect.identifier_preparer
1656
+
1657
+ @util.memoized_property
1658
+ def engine(self):
1659
+ return self.root_connection.engine
1660
+
1661
+ @util.memoized_property
1662
+ def postfetch_cols(self) -> Optional[Sequence[Column[Any]]]:
1663
+ if TYPE_CHECKING:
1664
+ assert isinstance(self.compiled, SQLCompiler)
1665
+ return self.compiled.postfetch
1666
+
1667
+ @util.memoized_property
1668
+ def prefetch_cols(self) -> Optional[Sequence[Column[Any]]]:
1669
+ if TYPE_CHECKING:
1670
+ assert isinstance(self.compiled, SQLCompiler)
1671
+ if self.isinsert:
1672
+ return self.compiled.insert_prefetch
1673
+ elif self.isupdate:
1674
+ return self.compiled.update_prefetch
1675
+ else:
1676
+ return ()
1677
+
1678
+ @util.memoized_property
1679
+ def no_parameters(self):
1680
+ return self.execution_options.get("no_parameters", False)
1681
+
1682
+ def _execute_scalar(
1683
+ self,
1684
+ stmt: str,
1685
+ type_: Optional[TypeEngine[Any]],
1686
+ parameters: Optional[_DBAPISingleExecuteParams] = None,
1687
+ ) -> Any:
1688
+ """Execute a string statement on the current cursor, returning a
1689
+ scalar result.
1690
+
1691
+ Used to fire off sequences, default phrases, and "select lastrowid"
1692
+ types of statements individually or in the context of a parent INSERT
1693
+ or UPDATE statement.
1694
+
1695
+ """
1696
+
1697
+ conn = self.root_connection
1698
+
1699
+ if "schema_translate_map" in self.execution_options:
1700
+ schema_translate_map = self.execution_options.get(
1701
+ "schema_translate_map", {}
1702
+ )
1703
+
1704
+ rst = self.identifier_preparer._render_schema_translates
1705
+ stmt = rst(stmt, schema_translate_map)
1706
+
1707
+ if not parameters:
1708
+ if self.dialect.positional:
1709
+ parameters = self.dialect.execute_sequence_format()
1710
+ else:
1711
+ parameters = {}
1712
+
1713
+ conn._cursor_execute(self.cursor, stmt, parameters, context=self)
1714
+ row = self.cursor.fetchone()
1715
+ if row is not None:
1716
+ r = row[0]
1717
+ else:
1718
+ r = None
1719
+ if type_ is not None:
1720
+ # apply type post processors to the result
1721
+ proc = type_._cached_result_processor(
1722
+ self.dialect, self.cursor.description[0][1]
1723
+ )
1724
+ if proc:
1725
+ return proc(r)
1726
+ return r
1727
+
1728
+ @util.memoized_property
1729
+ def connection(self):
1730
+ return self.root_connection
1731
+
1732
+ def _use_server_side_cursor(self):
1733
+ if not self.dialect.supports_server_side_cursors:
1734
+ return False
1735
+
1736
+ if self.dialect.server_side_cursors:
1737
+ # this is deprecated
1738
+ use_server_side = self.execution_options.get(
1739
+ "stream_results", True
1740
+ ) and (
1741
+ self.compiled
1742
+ and isinstance(self.compiled.statement, expression.Selectable)
1743
+ or (
1744
+ (
1745
+ not self.compiled
1746
+ or isinstance(
1747
+ self.compiled.statement, expression.TextClause
1748
+ )
1749
+ )
1750
+ and self.unicode_statement
1751
+ and SERVER_SIDE_CURSOR_RE.match(self.unicode_statement)
1752
+ )
1753
+ )
1754
+ else:
1755
+ use_server_side = self.execution_options.get(
1756
+ "stream_results", False
1757
+ )
1758
+
1759
+ return use_server_side
1760
+
1761
+ def create_cursor(self) -> DBAPICursor:
1762
+ if (
1763
+ # inlining initial preference checks for SS cursors
1764
+ self.dialect.supports_server_side_cursors
1765
+ and (
1766
+ self.execution_options.get("stream_results", False)
1767
+ or (
1768
+ self.dialect.server_side_cursors
1769
+ and self._use_server_side_cursor()
1770
+ )
1771
+ )
1772
+ ):
1773
+ self._is_server_side = True
1774
+ return self.create_server_side_cursor()
1775
+ else:
1776
+ self._is_server_side = False
1777
+ return self.create_default_cursor()
1778
+
1779
+ def fetchall_for_returning(self, cursor):
1780
+ return cursor.fetchall()
1781
+
1782
+ def create_default_cursor(self) -> DBAPICursor:
1783
+ return self._dbapi_connection.cursor()
1784
+
1785
+ def create_server_side_cursor(self) -> DBAPICursor:
1786
+ raise NotImplementedError()
1787
+
1788
+ def pre_exec(self):
1789
+ pass
1790
+
1791
+ def get_out_parameter_values(self, names):
1792
+ raise NotImplementedError(
1793
+ "This dialect does not support OUT parameters"
1794
+ )
1795
+
1796
+ def post_exec(self):
1797
+ pass
1798
+
1799
+ def get_result_processor(
1800
+ self, type_: TypeEngine[Any], colname: str, coltype: DBAPIType
1801
+ ) -> Optional[_ResultProcessorType[Any]]:
1802
+ """Return a 'result processor' for a given type as present in
1803
+ cursor.description.
1804
+
1805
+ This has a default implementation that dialects can override
1806
+ for context-sensitive result type handling.
1807
+
1808
+ """
1809
+ return type_._cached_result_processor(self.dialect, coltype)
1810
+
1811
+ def get_lastrowid(self) -> int:
1812
+ """return self.cursor.lastrowid, or equivalent, after an INSERT.
1813
+
1814
+ This may involve calling special cursor functions, issuing a new SELECT
1815
+ on the cursor (or a new one), or returning a stored value that was
1816
+ calculated within post_exec().
1817
+
1818
+ This function will only be called for dialects which support "implicit"
1819
+ primary key generation, keep preexecute_autoincrement_sequences set to
1820
+ False, and when no explicit id value was bound to the statement.
1821
+
1822
+ The function is called once for an INSERT statement that would need to
1823
+ return the last inserted primary key for those dialects that make use
1824
+ of the lastrowid concept. In these cases, it is called directly after
1825
+ :meth:`.ExecutionContext.post_exec`.
1826
+
1827
+ """
1828
+ return self.cursor.lastrowid
1829
+
1830
+ def handle_dbapi_exception(self, e):
1831
+ pass
1832
+
1833
+ @util.non_memoized_property
1834
+ def rowcount(self) -> int:
1835
+ if self._rowcount is not None:
1836
+ return self._rowcount
1837
+ else:
1838
+ return self.cursor.rowcount
1839
+
1840
+ @property
1841
+ def _has_rowcount(self):
1842
+ return self._rowcount is not None
1843
+
1844
+ def supports_sane_rowcount(self):
1845
+ return self.dialect.supports_sane_rowcount
1846
+
1847
+ def supports_sane_multi_rowcount(self):
1848
+ return self.dialect.supports_sane_multi_rowcount
1849
+
1850
+ def _setup_result_proxy(self):
1851
+ exec_opt = self.execution_options
1852
+
1853
+ if self._rowcount is None and exec_opt.get("preserve_rowcount", False):
1854
+ self._rowcount = self.cursor.rowcount
1855
+
1856
+ yp: Optional[Union[int, bool]]
1857
+ if self.is_crud or self.is_text:
1858
+ result = self._setup_dml_or_text_result()
1859
+ yp = False
1860
+ else:
1861
+ yp = exec_opt.get("yield_per", None)
1862
+ sr = self._is_server_side or exec_opt.get("stream_results", False)
1863
+ strategy = self.cursor_fetch_strategy
1864
+ if sr and strategy is _cursor._DEFAULT_FETCH:
1865
+ strategy = _cursor.BufferedRowCursorFetchStrategy(
1866
+ self.cursor, self.execution_options
1867
+ )
1868
+ cursor_description: _DBAPICursorDescription = (
1869
+ strategy.alternate_cursor_description
1870
+ or self.cursor.description
1871
+ )
1872
+ if cursor_description is None:
1873
+ strategy = _cursor._NO_CURSOR_DQL
1874
+
1875
+ result = _cursor.CursorResult(self, strategy, cursor_description)
1876
+
1877
+ compiled = self.compiled
1878
+
1879
+ if (
1880
+ compiled
1881
+ and not self.isddl
1882
+ and cast(SQLCompiler, compiled).has_out_parameters
1883
+ ):
1884
+ self._setup_out_parameters(result)
1885
+
1886
+ self._soft_closed = result._soft_closed
1887
+
1888
+ if yp:
1889
+ result = result.yield_per(yp)
1890
+
1891
+ return result
1892
+
1893
+ def _setup_out_parameters(self, result):
1894
+ compiled = cast(SQLCompiler, self.compiled)
1895
+
1896
+ out_bindparams = [
1897
+ (param, name)
1898
+ for param, name in compiled.bind_names.items()
1899
+ if param.isoutparam
1900
+ ]
1901
+ out_parameters = {}
1902
+
1903
+ for bindparam, raw_value in zip(
1904
+ [param for param, name in out_bindparams],
1905
+ self.get_out_parameter_values(
1906
+ [name for param, name in out_bindparams]
1907
+ ),
1908
+ ):
1909
+ type_ = bindparam.type
1910
+ impl_type = type_.dialect_impl(self.dialect)
1911
+ dbapi_type = impl_type.get_dbapi_type(self.dialect.loaded_dbapi)
1912
+ result_processor = impl_type.result_processor(
1913
+ self.dialect, dbapi_type
1914
+ )
1915
+ if result_processor is not None:
1916
+ raw_value = result_processor(raw_value)
1917
+ out_parameters[bindparam.key] = raw_value
1918
+
1919
+ result.out_parameters = out_parameters
1920
+
1921
+ def _setup_dml_or_text_result(self):
1922
+ compiled = cast(SQLCompiler, self.compiled)
1923
+
1924
+ strategy: ResultFetchStrategy = self.cursor_fetch_strategy
1925
+
1926
+ if self.isinsert:
1927
+ if (
1928
+ self.execute_style is ExecuteStyle.INSERTMANYVALUES
1929
+ and compiled.effective_returning
1930
+ ):
1931
+ strategy = _cursor.FullyBufferedCursorFetchStrategy(
1932
+ self.cursor,
1933
+ initial_buffer=self._insertmanyvalues_rows,
1934
+ # maintain alt cursor description if set by the
1935
+ # dialect, e.g. mssql preserves it
1936
+ alternate_description=(
1937
+ strategy.alternate_cursor_description
1938
+ ),
1939
+ )
1940
+
1941
+ if compiled.postfetch_lastrowid:
1942
+ self.inserted_primary_key_rows = (
1943
+ self._setup_ins_pk_from_lastrowid()
1944
+ )
1945
+ # else if not self._is_implicit_returning,
1946
+ # the default inserted_primary_key_rows accessor will
1947
+ # return an "empty" primary key collection when accessed.
1948
+
1949
+ if self._is_server_side and strategy is _cursor._DEFAULT_FETCH:
1950
+ strategy = _cursor.BufferedRowCursorFetchStrategy(
1951
+ self.cursor, self.execution_options
1952
+ )
1953
+
1954
+ if strategy is _cursor._NO_CURSOR_DML:
1955
+ cursor_description = None
1956
+ else:
1957
+ cursor_description = (
1958
+ strategy.alternate_cursor_description
1959
+ or self.cursor.description
1960
+ )
1961
+
1962
+ if cursor_description is None:
1963
+ strategy = _cursor._NO_CURSOR_DML
1964
+ elif self._num_sentinel_cols:
1965
+ assert self.execute_style is ExecuteStyle.INSERTMANYVALUES
1966
+ # strip out the sentinel columns from cursor description
1967
+ # a similar logic is done to the rows only in CursorResult
1968
+ cursor_description = cursor_description[
1969
+ 0 : -self._num_sentinel_cols
1970
+ ]
1971
+
1972
+ result: _cursor.CursorResult[Any] = _cursor.CursorResult(
1973
+ self, strategy, cursor_description
1974
+ )
1975
+
1976
+ if self.isinsert:
1977
+ if self._is_implicit_returning:
1978
+ rows = result.all()
1979
+
1980
+ self.returned_default_rows = rows
1981
+
1982
+ self.inserted_primary_key_rows = (
1983
+ self._setup_ins_pk_from_implicit_returning(result, rows)
1984
+ )
1985
+
1986
+ # test that it has a cursor metadata that is accurate. the
1987
+ # first row will have been fetched and current assumptions
1988
+ # are that the result has only one row, until executemany()
1989
+ # support is added here.
1990
+ assert result._metadata.returns_rows
1991
+
1992
+ # Insert statement has both return_defaults() and
1993
+ # returning(). rewind the result on the list of rows
1994
+ # we just used.
1995
+ if self._is_supplemental_returning:
1996
+ result._rewind(rows)
1997
+ else:
1998
+ result._soft_close()
1999
+ elif not self._is_explicit_returning:
2000
+ result._soft_close()
2001
+
2002
+ # we assume here the result does not return any rows.
2003
+ # *usually*, this will be true. However, some dialects
2004
+ # such as that of MSSQL/pyodbc need to SELECT a post fetch
2005
+ # function so this is not necessarily true.
2006
+ # assert not result.returns_rows
2007
+
2008
+ elif self._is_implicit_returning:
2009
+ rows = result.all()
2010
+
2011
+ if rows:
2012
+ self.returned_default_rows = rows
2013
+ self._rowcount = len(rows)
2014
+
2015
+ if self._is_supplemental_returning:
2016
+ result._rewind(rows)
2017
+ else:
2018
+ result._soft_close()
2019
+
2020
+ # test that it has a cursor metadata that is accurate.
2021
+ # the rows have all been fetched however.
2022
+ assert result._metadata.returns_rows
2023
+
2024
+ elif not result._metadata.returns_rows:
2025
+ # no results, get rowcount
2026
+ # (which requires open cursor on some drivers)
2027
+ if self._rowcount is None:
2028
+ self._rowcount = self.cursor.rowcount
2029
+ result._soft_close()
2030
+ elif self.isupdate or self.isdelete:
2031
+ if self._rowcount is None:
2032
+ self._rowcount = self.cursor.rowcount
2033
+ return result
2034
+
2035
+ @util.memoized_property
2036
+ def inserted_primary_key_rows(self):
2037
+ # if no specific "get primary key" strategy was set up
2038
+ # during execution, return a "default" primary key based
2039
+ # on what's in the compiled_parameters and nothing else.
2040
+ return self._setup_ins_pk_from_empty()
2041
+
2042
+ def _setup_ins_pk_from_lastrowid(self):
2043
+ getter = cast(
2044
+ SQLCompiler, self.compiled
2045
+ )._inserted_primary_key_from_lastrowid_getter
2046
+ lastrowid = self.get_lastrowid()
2047
+ return [getter(lastrowid, self.compiled_parameters[0])]
2048
+
2049
+ def _setup_ins_pk_from_empty(self):
2050
+ getter = cast(
2051
+ SQLCompiler, self.compiled
2052
+ )._inserted_primary_key_from_lastrowid_getter
2053
+ return [getter(None, param) for param in self.compiled_parameters]
2054
+
2055
+ def _setup_ins_pk_from_implicit_returning(self, result, rows):
2056
+ if not rows:
2057
+ return []
2058
+
2059
+ getter = cast(
2060
+ SQLCompiler, self.compiled
2061
+ )._inserted_primary_key_from_returning_getter
2062
+ compiled_params = self.compiled_parameters
2063
+
2064
+ return [
2065
+ getter(row, param) for row, param in zip(rows, compiled_params)
2066
+ ]
2067
+
2068
+ def lastrow_has_defaults(self) -> bool:
2069
+ return (self.isinsert or self.isupdate) and bool(
2070
+ cast(SQLCompiler, self.compiled).postfetch
2071
+ )
2072
+
2073
+ def _prepare_set_input_sizes(
2074
+ self,
2075
+ ) -> Optional[List[Tuple[str, Any, TypeEngine[Any]]]]:
2076
+ """Given a cursor and ClauseParameters, prepare arguments
2077
+ in order to call the appropriate
2078
+ style of ``setinputsizes()`` on the cursor, using DB-API types
2079
+ from the bind parameter's ``TypeEngine`` objects.
2080
+
2081
+ This method only called by those dialects which set the
2082
+ :attr:`.Dialect.bind_typing` attribute to
2083
+ :attr:`.BindTyping.SETINPUTSIZES`. Python-oracledb and cx_Oracle are
2084
+ the only DBAPIs that requires setinputsizes(); pyodbc offers it as an
2085
+ option.
2086
+
2087
+ Prior to SQLAlchemy 2.0, the setinputsizes() approach was also used
2088
+ for pg8000 and asyncpg, which has been changed to inline rendering
2089
+ of casts.
2090
+
2091
+ """
2092
+ if self.isddl or self.is_text:
2093
+ return None
2094
+
2095
+ compiled = cast(SQLCompiler, self.compiled)
2096
+
2097
+ inputsizes = compiled._get_set_input_sizes_lookup()
2098
+
2099
+ if inputsizes is None:
2100
+ return None
2101
+
2102
+ dialect = self.dialect
2103
+
2104
+ # all of the rest of this... cython?
2105
+
2106
+ if dialect._has_events:
2107
+ inputsizes = dict(inputsizes)
2108
+ dialect.dispatch.do_setinputsizes(
2109
+ inputsizes, self.cursor, self.statement, self.parameters, self
2110
+ )
2111
+
2112
+ if compiled.escaped_bind_names:
2113
+ escaped_bind_names = compiled.escaped_bind_names
2114
+ else:
2115
+ escaped_bind_names = None
2116
+
2117
+ if dialect.positional:
2118
+ items = [
2119
+ (key, compiled.binds[key])
2120
+ for key in compiled.positiontup or ()
2121
+ ]
2122
+ else:
2123
+ items = [
2124
+ (key, bindparam)
2125
+ for bindparam, key in compiled.bind_names.items()
2126
+ ]
2127
+
2128
+ generic_inputsizes: List[Tuple[str, Any, TypeEngine[Any]]] = []
2129
+ for key, bindparam in items:
2130
+ if bindparam in compiled.literal_execute_params:
2131
+ continue
2132
+
2133
+ if key in self._expanded_parameters:
2134
+ if is_tuple_type(bindparam.type):
2135
+ num = len(bindparam.type.types)
2136
+ dbtypes = inputsizes[bindparam]
2137
+ generic_inputsizes.extend(
2138
+ (
2139
+ (
2140
+ escaped_bind_names.get(paramname, paramname)
2141
+ if escaped_bind_names is not None
2142
+ else paramname
2143
+ ),
2144
+ dbtypes[idx % num],
2145
+ bindparam.type.types[idx % num],
2146
+ )
2147
+ for idx, paramname in enumerate(
2148
+ self._expanded_parameters[key]
2149
+ )
2150
+ )
2151
+ else:
2152
+ dbtype = inputsizes.get(bindparam, None)
2153
+ generic_inputsizes.extend(
2154
+ (
2155
+ (
2156
+ escaped_bind_names.get(paramname, paramname)
2157
+ if escaped_bind_names is not None
2158
+ else paramname
2159
+ ),
2160
+ dbtype,
2161
+ bindparam.type,
2162
+ )
2163
+ for paramname in self._expanded_parameters[key]
2164
+ )
2165
+ else:
2166
+ dbtype = inputsizes.get(bindparam, None)
2167
+
2168
+ escaped_name = (
2169
+ escaped_bind_names.get(key, key)
2170
+ if escaped_bind_names is not None
2171
+ else key
2172
+ )
2173
+
2174
+ generic_inputsizes.append(
2175
+ (escaped_name, dbtype, bindparam.type)
2176
+ )
2177
+
2178
+ return generic_inputsizes
2179
+
2180
+ def _exec_default(self, column, default, type_):
2181
+ if default.is_sequence:
2182
+ return self.fire_sequence(default, type_)
2183
+ elif default.is_callable:
2184
+ # this codepath is not normally used as it's inlined
2185
+ # into _process_execute_defaults
2186
+ self.current_column = column
2187
+ return default.arg(self)
2188
+ elif default.is_clause_element:
2189
+ return self._exec_default_clause_element(column, default, type_)
2190
+ else:
2191
+ # this codepath is not normally used as it's inlined
2192
+ # into _process_execute_defaults
2193
+ return default.arg
2194
+
2195
+ def _exec_default_clause_element(self, column, default, type_):
2196
+ # execute a default that's a complete clause element. Here, we have
2197
+ # to re-implement a miniature version of the compile->parameters->
2198
+ # cursor.execute() sequence, since we don't want to modify the state
2199
+ # of the connection / result in progress or create new connection/
2200
+ # result objects etc.
2201
+ # .. versionchanged:: 1.4
2202
+
2203
+ if not default._arg_is_typed:
2204
+ default_arg = expression.type_coerce(default.arg, type_)
2205
+ else:
2206
+ default_arg = default.arg
2207
+ compiled = expression.select(default_arg).compile(dialect=self.dialect)
2208
+ compiled_params = compiled.construct_params()
2209
+ processors = compiled._bind_processors
2210
+ if compiled.positional:
2211
+ parameters = self.dialect.execute_sequence_format(
2212
+ [
2213
+ (
2214
+ processors[key](compiled_params[key]) # type: ignore
2215
+ if key in processors
2216
+ else compiled_params[key]
2217
+ )
2218
+ for key in compiled.positiontup or ()
2219
+ ]
2220
+ )
2221
+ else:
2222
+ parameters = {
2223
+ key: (
2224
+ processors[key](compiled_params[key]) # type: ignore
2225
+ if key in processors
2226
+ else compiled_params[key]
2227
+ )
2228
+ for key in compiled_params
2229
+ }
2230
+ return self._execute_scalar(
2231
+ str(compiled), type_, parameters=parameters
2232
+ )
2233
+
2234
+ current_parameters: Optional[_CoreSingleExecuteParams] = None
2235
+ """A dictionary of parameters applied to the current row.
2236
+
2237
+ This attribute is only available in the context of a user-defined default
2238
+ generation function, e.g. as described at :ref:`context_default_functions`.
2239
+ It consists of a dictionary which includes entries for each column/value
2240
+ pair that is to be part of the INSERT or UPDATE statement. The keys of the
2241
+ dictionary will be the key value of each :class:`_schema.Column`,
2242
+ which is usually
2243
+ synonymous with the name.
2244
+
2245
+ Note that the :attr:`.DefaultExecutionContext.current_parameters` attribute
2246
+ does not accommodate for the "multi-values" feature of the
2247
+ :meth:`_expression.Insert.values` method. The
2248
+ :meth:`.DefaultExecutionContext.get_current_parameters` method should be
2249
+ preferred.
2250
+
2251
+ .. seealso::
2252
+
2253
+ :meth:`.DefaultExecutionContext.get_current_parameters`
2254
+
2255
+ :ref:`context_default_functions`
2256
+
2257
+ """
2258
+
2259
+ def get_current_parameters(self, isolate_multiinsert_groups=True):
2260
+ """Return a dictionary of parameters applied to the current row.
2261
+
2262
+ This method can only be used in the context of a user-defined default
2263
+ generation function, e.g. as described at
2264
+ :ref:`context_default_functions`. When invoked, a dictionary is
2265
+ returned which includes entries for each column/value pair that is part
2266
+ of the INSERT or UPDATE statement. The keys of the dictionary will be
2267
+ the key value of each :class:`_schema.Column`,
2268
+ which is usually synonymous
2269
+ with the name.
2270
+
2271
+ :param isolate_multiinsert_groups=True: indicates that multi-valued
2272
+ INSERT constructs created using :meth:`_expression.Insert.values`
2273
+ should be
2274
+ handled by returning only the subset of parameters that are local
2275
+ to the current column default invocation. When ``False``, the
2276
+ raw parameters of the statement are returned including the
2277
+ naming convention used in the case of multi-valued INSERT.
2278
+
2279
+ .. versionadded:: 1.2 added
2280
+ :meth:`.DefaultExecutionContext.get_current_parameters`
2281
+ which provides more functionality over the existing
2282
+ :attr:`.DefaultExecutionContext.current_parameters`
2283
+ attribute.
2284
+
2285
+ .. seealso::
2286
+
2287
+ :attr:`.DefaultExecutionContext.current_parameters`
2288
+
2289
+ :ref:`context_default_functions`
2290
+
2291
+ """
2292
+ try:
2293
+ parameters = self.current_parameters
2294
+ column = self.current_column
2295
+ except AttributeError:
2296
+ raise exc.InvalidRequestError(
2297
+ "get_current_parameters() can only be invoked in the "
2298
+ "context of a Python side column default function"
2299
+ )
2300
+ else:
2301
+ assert column is not None
2302
+ assert parameters is not None
2303
+ compile_state = cast(
2304
+ "DMLState", cast(SQLCompiler, self.compiled).compile_state
2305
+ )
2306
+ assert compile_state is not None
2307
+ if (
2308
+ isolate_multiinsert_groups
2309
+ and dml.isinsert(compile_state)
2310
+ and compile_state._has_multi_parameters
2311
+ ):
2312
+ if column._is_multiparam_column:
2313
+ index = column.index + 1
2314
+ d = {column.original.key: parameters[column.key]}
2315
+ else:
2316
+ d = {column.key: parameters[column.key]}
2317
+ index = 0
2318
+ assert compile_state._dict_parameters is not None
2319
+ keys = compile_state._dict_parameters.keys()
2320
+ d.update(
2321
+ (key, parameters["%s_m%d" % (key, index)]) for key in keys
2322
+ )
2323
+ return d
2324
+ else:
2325
+ return parameters
2326
+
2327
+ def get_insert_default(self, column):
2328
+ if column.default is None:
2329
+ return None
2330
+ else:
2331
+ return self._exec_default(column, column.default, column.type)
2332
+
2333
+ def get_update_default(self, column):
2334
+ if column.onupdate is None:
2335
+ return None
2336
+ else:
2337
+ return self._exec_default(column, column.onupdate, column.type)
2338
+
2339
+ def _process_execute_defaults(self):
2340
+ compiled = cast(SQLCompiler, self.compiled)
2341
+
2342
+ key_getter = compiled._within_exec_param_key_getter
2343
+
2344
+ sentinel_counter = 0
2345
+
2346
+ if compiled.insert_prefetch:
2347
+ prefetch_recs = [
2348
+ (
2349
+ c,
2350
+ key_getter(c),
2351
+ c._default_description_tuple,
2352
+ self.get_insert_default,
2353
+ )
2354
+ for c in compiled.insert_prefetch
2355
+ ]
2356
+ elif compiled.update_prefetch:
2357
+ prefetch_recs = [
2358
+ (
2359
+ c,
2360
+ key_getter(c),
2361
+ c._onupdate_description_tuple,
2362
+ self.get_update_default,
2363
+ )
2364
+ for c in compiled.update_prefetch
2365
+ ]
2366
+ else:
2367
+ prefetch_recs = []
2368
+
2369
+ for param in self.compiled_parameters:
2370
+ self.current_parameters = param
2371
+
2372
+ for (
2373
+ c,
2374
+ param_key,
2375
+ (arg, is_scalar, is_callable, is_sentinel),
2376
+ fallback,
2377
+ ) in prefetch_recs:
2378
+ if is_sentinel:
2379
+ param[param_key] = sentinel_counter
2380
+ sentinel_counter += 1
2381
+ elif is_scalar:
2382
+ param[param_key] = arg
2383
+ elif is_callable:
2384
+ self.current_column = c
2385
+ param[param_key] = arg(self)
2386
+ else:
2387
+ val = fallback(c)
2388
+ if val is not None:
2389
+ param[param_key] = val
2390
+
2391
+ del self.current_parameters
2392
+
2393
+
2394
+ DefaultDialect.execution_ctx_cls = DefaultExecutionContext
python/user_packages/Python313/site-packages/sqlalchemy/engine/events.py ADDED
@@ -0,0 +1,965 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # engine/events.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+
9
+ from __future__ import annotations
10
+
11
+ import typing
12
+ from typing import Any
13
+ from typing import Dict
14
+ from typing import Optional
15
+ from typing import Tuple
16
+ from typing import Type
17
+ from typing import Union
18
+
19
+ from .base import Connection
20
+ from .base import Engine
21
+ from .interfaces import ConnectionEventsTarget
22
+ from .interfaces import DBAPIConnection
23
+ from .interfaces import DBAPICursor
24
+ from .interfaces import Dialect
25
+ from .. import event
26
+ from .. import exc
27
+ from ..util.typing import Literal
28
+
29
+ if typing.TYPE_CHECKING:
30
+ from .interfaces import _CoreMultiExecuteParams
31
+ from .interfaces import _CoreSingleExecuteParams
32
+ from .interfaces import _DBAPIAnyExecuteParams
33
+ from .interfaces import _DBAPIMultiExecuteParams
34
+ from .interfaces import _DBAPISingleExecuteParams
35
+ from .interfaces import _ExecuteOptions
36
+ from .interfaces import ExceptionContext
37
+ from .interfaces import ExecutionContext
38
+ from .result import Result
39
+ from ..pool import ConnectionPoolEntry
40
+ from ..sql import Executable
41
+ from ..sql.elements import BindParameter
42
+
43
+
44
+ class ConnectionEvents(event.Events[ConnectionEventsTarget]):
45
+ """Available events for
46
+ :class:`_engine.Connection` and :class:`_engine.Engine`.
47
+
48
+ The methods here define the name of an event as well as the names of
49
+ members that are passed to listener functions.
50
+
51
+ An event listener can be associated with any
52
+ :class:`_engine.Connection` or :class:`_engine.Engine`
53
+ class or instance, such as an :class:`_engine.Engine`, e.g.::
54
+
55
+ from sqlalchemy import event, create_engine
56
+
57
+
58
+ def before_cursor_execute(
59
+ conn, cursor, statement, parameters, context, executemany
60
+ ):
61
+ log.info("Received statement: %s", statement)
62
+
63
+
64
+ engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/test")
65
+ event.listen(engine, "before_cursor_execute", before_cursor_execute)
66
+
67
+ or with a specific :class:`_engine.Connection`::
68
+
69
+ with engine.begin() as conn:
70
+
71
+ @event.listens_for(conn, "before_cursor_execute")
72
+ def before_cursor_execute(
73
+ conn, cursor, statement, parameters, context, executemany
74
+ ):
75
+ log.info("Received statement: %s", statement)
76
+
77
+ When the methods are called with a `statement` parameter, such as in
78
+ :meth:`.after_cursor_execute` or :meth:`.before_cursor_execute`,
79
+ the statement is the exact SQL string that was prepared for transmission
80
+ to the DBAPI ``cursor`` in the connection's :class:`.Dialect`.
81
+
82
+ The :meth:`.before_execute` and :meth:`.before_cursor_execute`
83
+ events can also be established with the ``retval=True`` flag, which
84
+ allows modification of the statement and parameters to be sent
85
+ to the database. The :meth:`.before_cursor_execute` event is
86
+ particularly useful here to add ad-hoc string transformations, such
87
+ as comments, to all executions::
88
+
89
+ from sqlalchemy.engine import Engine
90
+ from sqlalchemy import event
91
+
92
+
93
+ @event.listens_for(Engine, "before_cursor_execute", retval=True)
94
+ def comment_sql_calls(
95
+ conn, cursor, statement, parameters, context, executemany
96
+ ):
97
+ statement = statement + " -- some comment"
98
+ return statement, parameters
99
+
100
+ .. note:: :class:`_events.ConnectionEvents` can be established on any
101
+ combination of :class:`_engine.Engine`, :class:`_engine.Connection`,
102
+ as well
103
+ as instances of each of those classes. Events across all
104
+ four scopes will fire off for a given instance of
105
+ :class:`_engine.Connection`. However, for performance reasons, the
106
+ :class:`_engine.Connection` object determines at instantiation time
107
+ whether or not its parent :class:`_engine.Engine` has event listeners
108
+ established. Event listeners added to the :class:`_engine.Engine`
109
+ class or to an instance of :class:`_engine.Engine`
110
+ *after* the instantiation
111
+ of a dependent :class:`_engine.Connection` instance will usually
112
+ *not* be available on that :class:`_engine.Connection` instance.
113
+ The newly
114
+ added listeners will instead take effect for
115
+ :class:`_engine.Connection`
116
+ instances created subsequent to those event listeners being
117
+ established on the parent :class:`_engine.Engine` class or instance.
118
+
119
+ :param retval=False: Applies to the :meth:`.before_execute` and
120
+ :meth:`.before_cursor_execute` events only. When True, the
121
+ user-defined event function must have a return value, which
122
+ is a tuple of parameters that replace the given statement
123
+ and parameters. See those methods for a description of
124
+ specific return arguments.
125
+
126
+ """ # noqa
127
+
128
+ _target_class_doc = "SomeEngine"
129
+ _dispatch_target = ConnectionEventsTarget
130
+
131
+ @classmethod
132
+ def _accept_with(
133
+ cls,
134
+ target: Union[ConnectionEventsTarget, Type[ConnectionEventsTarget]],
135
+ identifier: str,
136
+ ) -> Optional[Union[ConnectionEventsTarget, Type[ConnectionEventsTarget]]]:
137
+ default_dispatch = super()._accept_with(target, identifier)
138
+ if default_dispatch is None and hasattr(
139
+ target, "_no_async_engine_events"
140
+ ):
141
+ target._no_async_engine_events()
142
+
143
+ return default_dispatch
144
+
145
+ @classmethod
146
+ def _listen(
147
+ cls,
148
+ event_key: event._EventKey[ConnectionEventsTarget],
149
+ *,
150
+ retval: bool = False,
151
+ **kw: Any,
152
+ ) -> None:
153
+ target, identifier, fn = (
154
+ event_key.dispatch_target,
155
+ event_key.identifier,
156
+ event_key._listen_fn,
157
+ )
158
+ target._has_events = True
159
+
160
+ if not retval:
161
+ if identifier == "before_execute":
162
+ orig_fn = fn
163
+
164
+ def wrap_before_execute( # type: ignore
165
+ conn, clauseelement, multiparams, params, execution_options
166
+ ):
167
+ orig_fn(
168
+ conn,
169
+ clauseelement,
170
+ multiparams,
171
+ params,
172
+ execution_options,
173
+ )
174
+ return clauseelement, multiparams, params
175
+
176
+ fn = wrap_before_execute
177
+ elif identifier == "before_cursor_execute":
178
+ orig_fn = fn
179
+
180
+ def wrap_before_cursor_execute( # type: ignore
181
+ conn, cursor, statement, parameters, context, executemany
182
+ ):
183
+ orig_fn(
184
+ conn,
185
+ cursor,
186
+ statement,
187
+ parameters,
188
+ context,
189
+ executemany,
190
+ )
191
+ return statement, parameters
192
+
193
+ fn = wrap_before_cursor_execute
194
+ elif retval and identifier not in (
195
+ "before_execute",
196
+ "before_cursor_execute",
197
+ ):
198
+ raise exc.ArgumentError(
199
+ "Only the 'before_execute', "
200
+ "'before_cursor_execute' and 'handle_error' engine "
201
+ "event listeners accept the 'retval=True' "
202
+ "argument."
203
+ )
204
+ event_key.with_wrapper(fn).base_listen()
205
+
206
+ @event._legacy_signature(
207
+ "1.4",
208
+ ["conn", "clauseelement", "multiparams", "params"],
209
+ lambda conn, clauseelement, multiparams, params, execution_options: (
210
+ conn,
211
+ clauseelement,
212
+ multiparams,
213
+ params,
214
+ ),
215
+ )
216
+ def before_execute(
217
+ self,
218
+ conn: Connection,
219
+ clauseelement: Executable,
220
+ multiparams: _CoreMultiExecuteParams,
221
+ params: _CoreSingleExecuteParams,
222
+ execution_options: _ExecuteOptions,
223
+ ) -> Optional[
224
+ Tuple[Executable, _CoreMultiExecuteParams, _CoreSingleExecuteParams]
225
+ ]:
226
+ """Intercept high level execute() events, receiving uncompiled
227
+ SQL constructs and other objects prior to rendering into SQL.
228
+
229
+ This event is good for debugging SQL compilation issues as well
230
+ as early manipulation of the parameters being sent to the database,
231
+ as the parameter lists will be in a consistent format here.
232
+
233
+ This event can be optionally established with the ``retval=True``
234
+ flag. The ``clauseelement``, ``multiparams``, and ``params``
235
+ arguments should be returned as a three-tuple in this case::
236
+
237
+ @event.listens_for(Engine, "before_execute", retval=True)
238
+ def before_execute(conn, clauseelement, multiparams, params):
239
+ # do something with clauseelement, multiparams, params
240
+ return clauseelement, multiparams, params
241
+
242
+ :param conn: :class:`_engine.Connection` object
243
+ :param clauseelement: SQL expression construct, :class:`.Compiled`
244
+ instance, or string statement passed to
245
+ :meth:`_engine.Connection.execute`.
246
+ :param multiparams: Multiple parameter sets, a list of dictionaries.
247
+ :param params: Single parameter set, a single dictionary.
248
+ :param execution_options: dictionary of execution
249
+ options passed along with the statement, if any. This is a merge
250
+ of all options that will be used, including those of the statement,
251
+ the connection, and those passed in to the method itself for
252
+ the 2.0 style of execution.
253
+
254
+ .. versionadded: 1.4
255
+
256
+ .. seealso::
257
+
258
+ :meth:`.before_cursor_execute`
259
+
260
+ """
261
+
262
+ @event._legacy_signature(
263
+ "1.4",
264
+ ["conn", "clauseelement", "multiparams", "params", "result"],
265
+ lambda conn, clauseelement, multiparams, params, execution_options, result: ( # noqa
266
+ conn,
267
+ clauseelement,
268
+ multiparams,
269
+ params,
270
+ result,
271
+ ),
272
+ )
273
+ def after_execute(
274
+ self,
275
+ conn: Connection,
276
+ clauseelement: Executable,
277
+ multiparams: _CoreMultiExecuteParams,
278
+ params: _CoreSingleExecuteParams,
279
+ execution_options: _ExecuteOptions,
280
+ result: Result[Any],
281
+ ) -> None:
282
+ """Intercept high level execute() events after execute.
283
+
284
+
285
+ :param conn: :class:`_engine.Connection` object
286
+ :param clauseelement: SQL expression construct, :class:`.Compiled`
287
+ instance, or string statement passed to
288
+ :meth:`_engine.Connection.execute`.
289
+ :param multiparams: Multiple parameter sets, a list of dictionaries.
290
+ :param params: Single parameter set, a single dictionary.
291
+ :param execution_options: dictionary of execution
292
+ options passed along with the statement, if any. This is a merge
293
+ of all options that will be used, including those of the statement,
294
+ the connection, and those passed in to the method itself for
295
+ the 2.0 style of execution.
296
+
297
+ .. versionadded: 1.4
298
+
299
+ :param result: :class:`_engine.CursorResult` generated by the
300
+ execution.
301
+
302
+ """
303
+
304
+ def before_cursor_execute(
305
+ self,
306
+ conn: Connection,
307
+ cursor: DBAPICursor,
308
+ statement: str,
309
+ parameters: _DBAPIAnyExecuteParams,
310
+ context: Optional[ExecutionContext],
311
+ executemany: bool,
312
+ ) -> Optional[Tuple[str, _DBAPIAnyExecuteParams]]:
313
+ """Intercept low-level cursor execute() events before execution,
314
+ receiving the string SQL statement and DBAPI-specific parameter list to
315
+ be invoked against a cursor.
316
+
317
+ This event is a good choice for logging as well as late modifications
318
+ to the SQL string. It's less ideal for parameter modifications except
319
+ for those which are specific to a target backend.
320
+
321
+ This event can be optionally established with the ``retval=True``
322
+ flag. The ``statement`` and ``parameters`` arguments should be
323
+ returned as a two-tuple in this case::
324
+
325
+ @event.listens_for(Engine, "before_cursor_execute", retval=True)
326
+ def before_cursor_execute(
327
+ conn, cursor, statement, parameters, context, executemany
328
+ ):
329
+ # do something with statement, parameters
330
+ return statement, parameters
331
+
332
+ See the example at :class:`_events.ConnectionEvents`.
333
+
334
+ :param conn: :class:`_engine.Connection` object
335
+ :param cursor: DBAPI cursor object
336
+ :param statement: string SQL statement, as to be passed to the DBAPI
337
+ :param parameters: Dictionary, tuple, or list of parameters being
338
+ passed to the ``execute()`` or ``executemany()`` method of the
339
+ DBAPI ``cursor``. In some cases may be ``None``.
340
+ :param context: :class:`.ExecutionContext` object in use. May
341
+ be ``None``.
342
+ :param executemany: boolean, if ``True``, this is an ``executemany()``
343
+ call, if ``False``, this is an ``execute()`` call.
344
+
345
+ .. seealso::
346
+
347
+ :meth:`.before_execute`
348
+
349
+ :meth:`.after_cursor_execute`
350
+
351
+ """
352
+
353
+ def after_cursor_execute(
354
+ self,
355
+ conn: Connection,
356
+ cursor: DBAPICursor,
357
+ statement: str,
358
+ parameters: _DBAPIAnyExecuteParams,
359
+ context: Optional[ExecutionContext],
360
+ executemany: bool,
361
+ ) -> None:
362
+ """Intercept low-level cursor execute() events after execution.
363
+
364
+ :param conn: :class:`_engine.Connection` object
365
+ :param cursor: DBAPI cursor object. Will have results pending
366
+ if the statement was a SELECT, but these should not be consumed
367
+ as they will be needed by the :class:`_engine.CursorResult`.
368
+ :param statement: string SQL statement, as passed to the DBAPI
369
+ :param parameters: Dictionary, tuple, or list of parameters being
370
+ passed to the ``execute()`` or ``executemany()`` method of the
371
+ DBAPI ``cursor``. In some cases may be ``None``.
372
+ :param context: :class:`.ExecutionContext` object in use. May
373
+ be ``None``.
374
+ :param executemany: boolean, if ``True``, this is an ``executemany()``
375
+ call, if ``False``, this is an ``execute()`` call.
376
+
377
+ """
378
+
379
+ @event._legacy_signature(
380
+ "2.0", ["conn", "branch"], converter=lambda conn: (conn, False)
381
+ )
382
+ def engine_connect(self, conn: Connection) -> None:
383
+ """Intercept the creation of a new :class:`_engine.Connection`.
384
+
385
+ This event is called typically as the direct result of calling
386
+ the :meth:`_engine.Engine.connect` method.
387
+
388
+ It differs from the :meth:`_events.PoolEvents.connect` method, which
389
+ refers to the actual connection to a database at the DBAPI level;
390
+ a DBAPI connection may be pooled and reused for many operations.
391
+ In contrast, this event refers only to the production of a higher level
392
+ :class:`_engine.Connection` wrapper around such a DBAPI connection.
393
+
394
+ It also differs from the :meth:`_events.PoolEvents.checkout` event
395
+ in that it is specific to the :class:`_engine.Connection` object,
396
+ not the
397
+ DBAPI connection that :meth:`_events.PoolEvents.checkout` deals with,
398
+ although
399
+ this DBAPI connection is available here via the
400
+ :attr:`_engine.Connection.connection` attribute.
401
+ But note there can in fact
402
+ be multiple :meth:`_events.PoolEvents.checkout`
403
+ events within the lifespan
404
+ of a single :class:`_engine.Connection` object, if that
405
+ :class:`_engine.Connection`
406
+ is invalidated and re-established.
407
+
408
+ :param conn: :class:`_engine.Connection` object.
409
+
410
+ .. seealso::
411
+
412
+ :meth:`_events.PoolEvents.checkout`
413
+ the lower-level pool checkout event
414
+ for an individual DBAPI connection
415
+
416
+ """
417
+
418
+ def set_connection_execution_options(
419
+ self, conn: Connection, opts: Dict[str, Any]
420
+ ) -> None:
421
+ """Intercept when the :meth:`_engine.Connection.execution_options`
422
+ method is called.
423
+
424
+ This method is called after the new :class:`_engine.Connection`
425
+ has been
426
+ produced, with the newly updated execution options collection, but
427
+ before the :class:`.Dialect` has acted upon any of those new options.
428
+
429
+ Note that this method is not called when a new
430
+ :class:`_engine.Connection`
431
+ is produced which is inheriting execution options from its parent
432
+ :class:`_engine.Engine`; to intercept this condition, use the
433
+ :meth:`_events.ConnectionEvents.engine_connect` event.
434
+
435
+ :param conn: The newly copied :class:`_engine.Connection` object
436
+
437
+ :param opts: dictionary of options that were passed to the
438
+ :meth:`_engine.Connection.execution_options` method.
439
+ This dictionary may be modified in place to affect the ultimate
440
+ options which take effect.
441
+
442
+ .. versionadded:: 2.0 the ``opts`` dictionary may be modified
443
+ in place.
444
+
445
+
446
+ .. seealso::
447
+
448
+ :meth:`_events.ConnectionEvents.set_engine_execution_options`
449
+ - event
450
+ which is called when :meth:`_engine.Engine.execution_options`
451
+ is called.
452
+
453
+
454
+ """
455
+
456
+ def set_engine_execution_options(
457
+ self, engine: Engine, opts: Dict[str, Any]
458
+ ) -> None:
459
+ """Intercept when the :meth:`_engine.Engine.execution_options`
460
+ method is called.
461
+
462
+ The :meth:`_engine.Engine.execution_options` method produces a shallow
463
+ copy of the :class:`_engine.Engine` which stores the new options.
464
+ That new
465
+ :class:`_engine.Engine` is passed here.
466
+ A particular application of this
467
+ method is to add a :meth:`_events.ConnectionEvents.engine_connect`
468
+ event
469
+ handler to the given :class:`_engine.Engine`
470
+ which will perform some per-
471
+ :class:`_engine.Connection` task specific to these execution options.
472
+
473
+ :param conn: The newly copied :class:`_engine.Engine` object
474
+
475
+ :param opts: dictionary of options that were passed to the
476
+ :meth:`_engine.Connection.execution_options` method.
477
+ This dictionary may be modified in place to affect the ultimate
478
+ options which take effect.
479
+
480
+ .. versionadded:: 2.0 the ``opts`` dictionary may be modified
481
+ in place.
482
+
483
+ .. seealso::
484
+
485
+ :meth:`_events.ConnectionEvents.set_connection_execution_options`
486
+ - event
487
+ which is called when :meth:`_engine.Connection.execution_options`
488
+ is
489
+ called.
490
+
491
+ """
492
+
493
+ def engine_disposed(self, engine: Engine) -> None:
494
+ """Intercept when the :meth:`_engine.Engine.dispose` method is called.
495
+
496
+ The :meth:`_engine.Engine.dispose` method instructs the engine to
497
+ "dispose" of it's connection pool (e.g. :class:`_pool.Pool`), and
498
+ replaces it with a new one. Disposing of the old pool has the
499
+ effect that existing checked-in connections are closed. The new
500
+ pool does not establish any new connections until it is first used.
501
+
502
+ This event can be used to indicate that resources related to the
503
+ :class:`_engine.Engine` should also be cleaned up,
504
+ keeping in mind that the
505
+ :class:`_engine.Engine`
506
+ can still be used for new requests in which case
507
+ it re-acquires connection resources.
508
+
509
+ """
510
+
511
+ def begin(self, conn: Connection) -> None:
512
+ """Intercept begin() events.
513
+
514
+ :param conn: :class:`_engine.Connection` object
515
+
516
+ """
517
+
518
+ def rollback(self, conn: Connection) -> None:
519
+ """Intercept rollback() events, as initiated by a
520
+ :class:`.Transaction`.
521
+
522
+ Note that the :class:`_pool.Pool` also "auto-rolls back"
523
+ a DBAPI connection upon checkin, if the ``reset_on_return``
524
+ flag is set to its default value of ``'rollback'``.
525
+ To intercept this
526
+ rollback, use the :meth:`_events.PoolEvents.reset` hook.
527
+
528
+ :param conn: :class:`_engine.Connection` object
529
+
530
+ .. seealso::
531
+
532
+ :meth:`_events.PoolEvents.reset`
533
+
534
+ """
535
+
536
+ def commit(self, conn: Connection) -> None:
537
+ """Intercept commit() events, as initiated by a
538
+ :class:`.Transaction`.
539
+
540
+ Note that the :class:`_pool.Pool` may also "auto-commit"
541
+ a DBAPI connection upon checkin, if the ``reset_on_return``
542
+ flag is set to the value ``'commit'``. To intercept this
543
+ commit, use the :meth:`_events.PoolEvents.reset` hook.
544
+
545
+ :param conn: :class:`_engine.Connection` object
546
+ """
547
+
548
+ def savepoint(self, conn: Connection, name: str) -> None:
549
+ """Intercept savepoint() events.
550
+
551
+ :param conn: :class:`_engine.Connection` object
552
+ :param name: specified name used for the savepoint.
553
+
554
+ """
555
+
556
+ def rollback_savepoint(
557
+ self, conn: Connection, name: str, context: None
558
+ ) -> None:
559
+ """Intercept rollback_savepoint() events.
560
+
561
+ :param conn: :class:`_engine.Connection` object
562
+ :param name: specified name used for the savepoint.
563
+ :param context: not used
564
+
565
+ """
566
+ # TODO: deprecate "context"
567
+
568
+ def release_savepoint(
569
+ self, conn: Connection, name: str, context: None
570
+ ) -> None:
571
+ """Intercept release_savepoint() events.
572
+
573
+ :param conn: :class:`_engine.Connection` object
574
+ :param name: specified name used for the savepoint.
575
+ :param context: not used
576
+
577
+ """
578
+ # TODO: deprecate "context"
579
+
580
+ def begin_twophase(self, conn: Connection, xid: Any) -> None:
581
+ """Intercept begin_twophase() events.
582
+
583
+ :param conn: :class:`_engine.Connection` object
584
+ :param xid: two-phase XID identifier
585
+
586
+ """
587
+
588
+ def prepare_twophase(self, conn: Connection, xid: Any) -> None:
589
+ """Intercept prepare_twophase() events.
590
+
591
+ :param conn: :class:`_engine.Connection` object
592
+ :param xid: two-phase XID identifier
593
+ """
594
+
595
+ def rollback_twophase(
596
+ self, conn: Connection, xid: Any, is_prepared: bool
597
+ ) -> None:
598
+ """Intercept rollback_twophase() events.
599
+
600
+ :param conn: :class:`_engine.Connection` object
601
+ :param xid: two-phase XID identifier
602
+ :param is_prepared: boolean, indicates if
603
+ :meth:`.TwoPhaseTransaction.prepare` was called.
604
+
605
+ """
606
+
607
+ def commit_twophase(
608
+ self, conn: Connection, xid: Any, is_prepared: bool
609
+ ) -> None:
610
+ """Intercept commit_twophase() events.
611
+
612
+ :param conn: :class:`_engine.Connection` object
613
+ :param xid: two-phase XID identifier
614
+ :param is_prepared: boolean, indicates if
615
+ :meth:`.TwoPhaseTransaction.prepare` was called.
616
+
617
+ """
618
+
619
+
620
+ class DialectEvents(event.Events[Dialect]):
621
+ """event interface for execution-replacement functions.
622
+
623
+ These events allow direct instrumentation and replacement
624
+ of key dialect functions which interact with the DBAPI.
625
+
626
+ .. note::
627
+
628
+ :class:`.DialectEvents` hooks should be considered **semi-public**
629
+ and experimental.
630
+ These hooks are not for general use and are only for those situations
631
+ where intricate re-statement of DBAPI mechanics must be injected onto
632
+ an existing dialect. For general-use statement-interception events,
633
+ please use the :class:`_events.ConnectionEvents` interface.
634
+
635
+ .. seealso::
636
+
637
+ :meth:`_events.ConnectionEvents.before_cursor_execute`
638
+
639
+ :meth:`_events.ConnectionEvents.before_execute`
640
+
641
+ :meth:`_events.ConnectionEvents.after_cursor_execute`
642
+
643
+ :meth:`_events.ConnectionEvents.after_execute`
644
+
645
+ """
646
+
647
+ _target_class_doc = "SomeEngine"
648
+ _dispatch_target = Dialect
649
+
650
+ @classmethod
651
+ def _listen(
652
+ cls,
653
+ event_key: event._EventKey[Dialect],
654
+ *,
655
+ retval: bool = False,
656
+ **kw: Any,
657
+ ) -> None:
658
+ target = event_key.dispatch_target
659
+
660
+ target._has_events = True
661
+ event_key.base_listen()
662
+
663
+ @classmethod
664
+ def _accept_with(
665
+ cls,
666
+ target: Union[Engine, Type[Engine], Dialect, Type[Dialect]],
667
+ identifier: str,
668
+ ) -> Optional[Union[Dialect, Type[Dialect]]]:
669
+ if isinstance(target, type):
670
+ if issubclass(target, Engine):
671
+ return Dialect
672
+ elif issubclass(target, Dialect):
673
+ return target
674
+ elif isinstance(target, Engine):
675
+ return target.dialect
676
+ elif isinstance(target, Dialect):
677
+ return target
678
+ elif isinstance(target, Connection) and identifier == "handle_error":
679
+ raise exc.InvalidRequestError(
680
+ "The handle_error() event hook as of SQLAlchemy 2.0 is "
681
+ "established on the Dialect, and may only be applied to the "
682
+ "Engine as a whole or to a specific Dialect as a whole, "
683
+ "not on a per-Connection basis."
684
+ )
685
+ elif hasattr(target, "_no_async_engine_events"):
686
+ target._no_async_engine_events()
687
+ else:
688
+ return None
689
+
690
+ def handle_error(
691
+ self, exception_context: ExceptionContext
692
+ ) -> Optional[BaseException]:
693
+ r"""Intercept all exceptions processed by the
694
+ :class:`_engine.Dialect`, typically but not limited to those
695
+ emitted within the scope of a :class:`_engine.Connection`.
696
+
697
+ .. versionchanged:: 2.0 the :meth:`.DialectEvents.handle_error` event
698
+ is moved to the :class:`.DialectEvents` class, moved from the
699
+ :class:`.ConnectionEvents` class, so that it may also participate in
700
+ the "pre ping" operation configured with the
701
+ :paramref:`_sa.create_engine.pool_pre_ping` parameter. The event
702
+ remains registered by using the :class:`_engine.Engine` as the event
703
+ target, however note that using the :class:`_engine.Connection` as
704
+ an event target for :meth:`.DialectEvents.handle_error` is no longer
705
+ supported.
706
+
707
+ This includes all exceptions emitted by the DBAPI as well as
708
+ within SQLAlchemy's statement invocation process, including
709
+ encoding errors and other statement validation errors. Other areas
710
+ in which the event is invoked include transaction begin and end,
711
+ result row fetching, cursor creation.
712
+
713
+ Note that :meth:`.handle_error` may support new kinds of exceptions
714
+ and new calling scenarios at *any time*. Code which uses this
715
+ event must expect new calling patterns to be present in minor
716
+ releases.
717
+
718
+ To support the wide variety of members that correspond to an exception,
719
+ as well as to allow extensibility of the event without backwards
720
+ incompatibility, the sole argument received is an instance of
721
+ :class:`.ExceptionContext`. This object contains data members
722
+ representing detail about the exception.
723
+
724
+ Use cases supported by this hook include:
725
+
726
+ * read-only, low-level exception handling for logging and
727
+ debugging purposes
728
+ * Establishing whether a DBAPI connection error message indicates
729
+ that the database connection needs to be reconnected, including
730
+ for the "pre_ping" handler used by **some** dialects
731
+ * Establishing or disabling whether a connection or the owning
732
+ connection pool is invalidated or expired in response to a
733
+ specific exception
734
+ * exception re-writing
735
+
736
+ The hook is called while the cursor from the failed operation
737
+ (if any) is still open and accessible. Special cleanup operations
738
+ can be called on this cursor; SQLAlchemy will attempt to close
739
+ this cursor subsequent to this hook being invoked.
740
+
741
+ As of SQLAlchemy 2.0, the "pre_ping" handler enabled using the
742
+ :paramref:`_sa.create_engine.pool_pre_ping` parameter will also
743
+ participate in the :meth:`.handle_error` process, **for those dialects
744
+ that rely upon disconnect codes to detect database liveness**. Note
745
+ that some dialects such as psycopg, psycopg2, and most MySQL dialects
746
+ make use of a native ``ping()`` method supplied by the DBAPI which does
747
+ not make use of disconnect codes.
748
+
749
+ .. versionchanged:: 2.0.0 The :meth:`.DialectEvents.handle_error`
750
+ event hook participates in connection pool "pre-ping" operations.
751
+ Within this usage, the :attr:`.ExceptionContext.engine` attribute
752
+ will be ``None``, however the :class:`.Dialect` in use is always
753
+ available via the :attr:`.ExceptionContext.dialect` attribute.
754
+
755
+ .. versionchanged:: 2.0.5 Added :attr:`.ExceptionContext.is_pre_ping`
756
+ attribute which will be set to ``True`` when the
757
+ :meth:`.DialectEvents.handle_error` event hook is triggered within
758
+ a connection pool pre-ping operation.
759
+
760
+ .. versionchanged:: 2.0.5 An issue was repaired that allows for the
761
+ PostgreSQL ``psycopg`` and ``psycopg2`` drivers, as well as all
762
+ MySQL drivers, to properly participate in the
763
+ :meth:`.DialectEvents.handle_error` event hook during
764
+ connection pool "pre-ping" operations; previously, the
765
+ implementation was non-working for these drivers.
766
+
767
+
768
+ A handler function has two options for replacing
769
+ the SQLAlchemy-constructed exception into one that is user
770
+ defined. It can either raise this new exception directly, in
771
+ which case all further event listeners are bypassed and the
772
+ exception will be raised, after appropriate cleanup as taken
773
+ place::
774
+
775
+ @event.listens_for(Engine, "handle_error")
776
+ def handle_exception(context):
777
+ if isinstance(
778
+ context.original_exception, psycopg2.OperationalError
779
+ ) and "failed" in str(context.original_exception):
780
+ raise MySpecialException("failed operation")
781
+
782
+ .. warning:: Because the
783
+ :meth:`_events.DialectEvents.handle_error`
784
+ event specifically provides for exceptions to be re-thrown as
785
+ the ultimate exception raised by the failed statement,
786
+ **stack traces will be misleading** if the user-defined event
787
+ handler itself fails and throws an unexpected exception;
788
+ the stack trace may not illustrate the actual code line that
789
+ failed! It is advised to code carefully here and use
790
+ logging and/or inline debugging if unexpected exceptions are
791
+ occurring.
792
+
793
+ Alternatively, a "chained" style of event handling can be
794
+ used, by configuring the handler with the ``retval=True``
795
+ modifier and returning the new exception instance from the
796
+ function. In this case, event handling will continue onto the
797
+ next handler. The "chained" exception is available using
798
+ :attr:`.ExceptionContext.chained_exception`::
799
+
800
+ @event.listens_for(Engine, "handle_error", retval=True)
801
+ def handle_exception(context):
802
+ if (
803
+ context.chained_exception is not None
804
+ and "special" in context.chained_exception.message
805
+ ):
806
+ return MySpecialException(
807
+ "failed", cause=context.chained_exception
808
+ )
809
+
810
+ Handlers that return ``None`` may be used within the chain; when
811
+ a handler returns ``None``, the previous exception instance,
812
+ if any, is maintained as the current exception that is passed onto the
813
+ next handler.
814
+
815
+ When a custom exception is raised or returned, SQLAlchemy raises
816
+ this new exception as-is, it is not wrapped by any SQLAlchemy
817
+ object. If the exception is not a subclass of
818
+ :class:`sqlalchemy.exc.StatementError`,
819
+ certain features may not be available; currently this includes
820
+ the ORM's feature of adding a detail hint about "autoflush" to
821
+ exceptions raised within the autoflush process.
822
+
823
+ :param context: an :class:`.ExceptionContext` object. See this
824
+ class for details on all available members.
825
+
826
+
827
+ .. seealso::
828
+
829
+ :ref:`pool_new_disconnect_codes`
830
+
831
+ """
832
+
833
+ def do_connect(
834
+ self,
835
+ dialect: Dialect,
836
+ conn_rec: ConnectionPoolEntry,
837
+ cargs: Tuple[Any, ...],
838
+ cparams: Dict[str, Any],
839
+ ) -> Optional[DBAPIConnection]:
840
+ """Receive connection arguments before a connection is made.
841
+
842
+ This event is useful in that it allows the handler to manipulate the
843
+ cargs and/or cparams collections that control how the DBAPI
844
+ ``connect()`` function will be called. ``cargs`` will always be a
845
+ Python list that can be mutated in-place, and ``cparams`` a Python
846
+ dictionary that may also be mutated::
847
+
848
+ e = create_engine("postgresql+psycopg2://user@host/dbname")
849
+
850
+
851
+ @event.listens_for(e, "do_connect")
852
+ def receive_do_connect(dialect, conn_rec, cargs, cparams):
853
+ cparams["password"] = "some_password"
854
+
855
+ The event hook may also be used to override the call to ``connect()``
856
+ entirely, by returning a non-``None`` DBAPI connection object::
857
+
858
+ e = create_engine("postgresql+psycopg2://user@host/dbname")
859
+
860
+
861
+ @event.listens_for(e, "do_connect")
862
+ def receive_do_connect(dialect, conn_rec, cargs, cparams):
863
+ return psycopg2.connect(*cargs, **cparams)
864
+
865
+ .. seealso::
866
+
867
+ :ref:`custom_dbapi_args`
868
+
869
+ """
870
+
871
+ def do_executemany(
872
+ self,
873
+ cursor: DBAPICursor,
874
+ statement: str,
875
+ parameters: _DBAPIMultiExecuteParams,
876
+ context: ExecutionContext,
877
+ ) -> Optional[Literal[True]]:
878
+ """Receive a cursor to have executemany() called.
879
+
880
+ Return the value True to halt further events from invoking,
881
+ and to indicate that the cursor execution has already taken
882
+ place within the event handler.
883
+
884
+ """
885
+
886
+ def do_execute_no_params(
887
+ self, cursor: DBAPICursor, statement: str, context: ExecutionContext
888
+ ) -> Optional[Literal[True]]:
889
+ """Receive a cursor to have execute() with no parameters called.
890
+
891
+ Return the value True to halt further events from invoking,
892
+ and to indicate that the cursor execution has already taken
893
+ place within the event handler.
894
+
895
+ """
896
+
897
+ def do_execute(
898
+ self,
899
+ cursor: DBAPICursor,
900
+ statement: str,
901
+ parameters: _DBAPISingleExecuteParams,
902
+ context: ExecutionContext,
903
+ ) -> Optional[Literal[True]]:
904
+ """Receive a cursor to have execute() called.
905
+
906
+ Return the value True to halt further events from invoking,
907
+ and to indicate that the cursor execution has already taken
908
+ place within the event handler.
909
+
910
+ """
911
+
912
+ def do_setinputsizes(
913
+ self,
914
+ inputsizes: Dict[BindParameter[Any], Any],
915
+ cursor: DBAPICursor,
916
+ statement: str,
917
+ parameters: _DBAPIAnyExecuteParams,
918
+ context: ExecutionContext,
919
+ ) -> None:
920
+ """Receive the setinputsizes dictionary for possible modification.
921
+
922
+ This event is emitted in the case where the dialect makes use of the
923
+ DBAPI ``cursor.setinputsizes()`` method which passes information about
924
+ parameter binding for a particular statement. The given
925
+ ``inputsizes`` dictionary will contain :class:`.BindParameter` objects
926
+ as keys, linked to DBAPI-specific type objects as values; for
927
+ parameters that are not bound, they are added to the dictionary with
928
+ ``None`` as the value, which means the parameter will not be included
929
+ in the ultimate setinputsizes call. The event may be used to inspect
930
+ and/or log the datatypes that are being bound, as well as to modify the
931
+ dictionary in place. Parameters can be added, modified, or removed
932
+ from this dictionary. Callers will typically want to inspect the
933
+ :attr:`.BindParameter.type` attribute of the given bind objects in
934
+ order to make decisions about the DBAPI object.
935
+
936
+ After the event, the ``inputsizes`` dictionary is converted into
937
+ an appropriate datastructure to be passed to ``cursor.setinputsizes``;
938
+ either a list for a positional bound parameter execution style,
939
+ or a dictionary of string parameter keys to DBAPI type objects for
940
+ a named bound parameter execution style.
941
+
942
+ The setinputsizes hook overall is only used for dialects which include
943
+ the flag ``use_setinputsizes=True``. Dialects which use this
944
+ include python-oracledb, cx_Oracle, pg8000, asyncpg, and pyodbc
945
+ dialects.
946
+
947
+ .. note::
948
+
949
+ For use with pyodbc, the ``use_setinputsizes`` flag
950
+ must be passed to the dialect, e.g.::
951
+
952
+ create_engine("mssql+pyodbc://...", use_setinputsizes=True)
953
+
954
+ .. seealso::
955
+
956
+ :ref:`mssql_pyodbc_setinputsizes`
957
+
958
+ .. versionadded:: 1.2.9
959
+
960
+ .. seealso::
961
+
962
+ :ref:`cx_oracle_setinputsizes`
963
+
964
+ """
965
+ pass
python/user_packages/Python313/site-packages/sqlalchemy/engine/interfaces.py ADDED
The diff for this file is too large to render. See raw diff