sqlalchemy-spanner 1.21.0__tar.gz → 1.21.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/PKG-INFO +1 -1
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/google/cloud/sqlalchemy_spanner/sqlalchemy_spanner.py +650 -156
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/google/cloud/sqlalchemy_spanner/version.py +1 -1
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/sqlalchemy_spanner.egg-info/PKG-INFO +1 -1
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/LICENSE +0 -0
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/README.rst +0 -0
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/google/cloud/sqlalchemy_spanner/__init__.py +0 -0
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/google/cloud/sqlalchemy_spanner/_opentelemetry_tracing.py +0 -0
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/google/cloud/sqlalchemy_spanner/dml.py +0 -0
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/google/cloud/sqlalchemy_spanner/provision.py +0 -0
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/google/cloud/sqlalchemy_spanner/requirements.py +0 -0
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/setup.cfg +0 -0
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/setup.py +0 -0
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/sqlalchemy_spanner.egg-info/SOURCES.txt +0 -0
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/sqlalchemy_spanner.egg-info/dependency_links.txt +0 -0
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/sqlalchemy_spanner.egg-info/entry_points.txt +0 -0
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/sqlalchemy_spanner.egg-info/not-zip-safe +0 -0
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/sqlalchemy_spanner.egg-info/requires.txt +0 -0
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/sqlalchemy_spanner.egg-info/top_level.txt +0 -0
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/tests/test_suite_13.py +0 -0
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/tests/test_suite_14.py +0 -0
- {sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/tests/test_suite_20.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: sqlalchemy-spanner
|
|
3
|
-
Version: 1.21.
|
|
3
|
+
Version: 1.21.1
|
|
4
4
|
Summary: SQLAlchemy dialect integrated into Cloud Spanner database
|
|
5
5
|
Home-page: https://github.com/googleapis/google-cloud-python/tree/main/packages/sqlalchemy-spanner
|
|
6
6
|
Author: Google LLC
|
|
@@ -13,12 +13,15 @@
|
|
|
13
13
|
# limitations under the License.
|
|
14
14
|
import base64
|
|
15
15
|
import collections.abc
|
|
16
|
+
import functools
|
|
16
17
|
import re
|
|
18
|
+
import string
|
|
19
|
+
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
|
17
20
|
|
|
18
21
|
import sqlalchemy
|
|
19
22
|
from google.api_core.client_options import ClientOptions
|
|
20
23
|
from google.auth.credentials import AnonymousCredentials
|
|
21
|
-
from google.cloud.spanner_v1 import Client, TransactionOptions
|
|
24
|
+
from google.cloud.spanner_v1 import Client, TransactionOptions, param_types
|
|
22
25
|
from google.cloud.spanner_v1.data_types import JsonObject
|
|
23
26
|
from sqlalchemy import ForeignKeyConstraint, PickleType, TypeDecorator, types
|
|
24
27
|
from sqlalchemy.engine.base import Engine
|
|
@@ -29,7 +32,6 @@ from sqlalchemy.ext.compiler import compiles
|
|
|
29
32
|
from sqlalchemy.pool import Pool
|
|
30
33
|
from sqlalchemy.sql import elements, expression
|
|
31
34
|
from sqlalchemy.sql.compiler import (
|
|
32
|
-
OPERATORS,
|
|
33
35
|
RESERVED_WORDS,
|
|
34
36
|
DDLCompiler,
|
|
35
37
|
GenericTypeCompiler,
|
|
@@ -37,8 +39,7 @@ from sqlalchemy.sql.compiler import (
|
|
|
37
39
|
SQLCompiler,
|
|
38
40
|
selectable,
|
|
39
41
|
)
|
|
40
|
-
from sqlalchemy.sql.
|
|
41
|
-
from sqlalchemy.sql.operators import json_getitem_op, json_path_getitem_op
|
|
42
|
+
from sqlalchemy.sql.operators import json_path_getitem_op
|
|
42
43
|
|
|
43
44
|
from google.cloud import spanner_dbapi
|
|
44
45
|
from google.cloud.sqlalchemy_spanner import version as sqlalchemy_spanner_version
|
|
@@ -85,39 +86,212 @@ def reset_connection(dbapi_conn, connection_record, reset_state=None):
|
|
|
85
86
|
dbapi_conn.read_only = False
|
|
86
87
|
|
|
87
88
|
|
|
88
|
-
#
|
|
89
|
-
|
|
90
|
-
|
|
89
|
+
# TODO(https://github.com/googleapis/google-cloud-python/issues/19209): Move the
|
|
90
|
+
# GoogleSQL identifier escaping, unquoted-identifier check, and backslash-escape
|
|
91
|
+
# decoding helpers below into google.cloud.spanner_dbapi (once
|
|
92
|
+
# sqlalchemy-spanner can depend on a release that includes them) so
|
|
93
|
+
# spanner_dbapi, sqlalchemy-spanner, and django-google-spanner share a single
|
|
94
|
+
# implementation.
|
|
95
|
+
|
|
96
|
+
# GoogleSQL rejects raw newlines and unescaped ASCII control characters
|
|
97
|
+
# (0x00-0x1F and 0x7F) inside quoted strings and identifiers.
|
|
98
|
+
# Write them using equivalent GoogleSQL escape sequences (\n, \r, \t, or \u00xx)
|
|
99
|
+
# so Spanner decodes them back to the original characters.
|
|
100
|
+
_CONTROL_CHAR_ESCAPE_MAP = {
|
|
101
|
+
"\n": "\\n",
|
|
102
|
+
"\r": "\\r",
|
|
103
|
+
"\t": "\\t",
|
|
104
|
+
**{
|
|
105
|
+
chr(codepoint): f"\\u{codepoint:04x}"
|
|
106
|
+
for codepoint in (*range(0x00, 0x20), 0x7F)
|
|
107
|
+
if chr(codepoint) not in ("\n", "\r", "\t")
|
|
108
|
+
},
|
|
109
|
+
}
|
|
91
110
|
|
|
92
111
|
_SPANNER_STRING_ESCAPE_TABLE = str.maketrans(
|
|
93
112
|
{
|
|
94
113
|
"\\": "\\\\",
|
|
95
114
|
'"': '\\"',
|
|
96
115
|
"'": "\\'",
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
116
|
+
**_CONTROL_CHAR_ESCAPE_MAP,
|
|
117
|
+
}
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
# Escape backticks as \u0060 instead of \` because spanner_dbapi currently uses
|
|
121
|
+
# sqlparse to split DDLs and strip comments, and sqlparse treats \` inside a
|
|
122
|
+
# backtick-quoted identifier as the closing backtick. GoogleSQL decodes \u0060
|
|
123
|
+
# to a literal backtick just like \`.
|
|
124
|
+
# TODO(https://github.com/googleapis/google-cloud-python/issues/19209): Switch
|
|
125
|
+
# backtick escaping to \` once spanner_dbapi uses a lexical parser that
|
|
126
|
+
# understands GoogleSQL backslash escapes.
|
|
127
|
+
_SPANNER_IDENTIFIER_ESCAPE_TABLE = str.maketrans(
|
|
128
|
+
{
|
|
129
|
+
"\\": "\\\\",
|
|
130
|
+
"`": "\\u0060",
|
|
131
|
+
**_CONTROL_CHAR_ESCAPE_MAP,
|
|
105
132
|
}
|
|
106
133
|
)
|
|
107
134
|
|
|
135
|
+
# Single-character GoogleSQL backslash escapes decoded during identifier unescaping.
|
|
136
|
+
_GOOGLESQL_SINGLE_CHAR_UNESCAPE_TABLE = {
|
|
137
|
+
"a": "\a",
|
|
138
|
+
"b": "\b",
|
|
139
|
+
"f": "\f",
|
|
140
|
+
"n": "\n",
|
|
141
|
+
"r": "\r",
|
|
142
|
+
"t": "\t",
|
|
143
|
+
"v": "\v",
|
|
144
|
+
"\\": "\\",
|
|
145
|
+
"?": "?",
|
|
146
|
+
'"': '"',
|
|
147
|
+
"'": "'",
|
|
148
|
+
"`": "`",
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
# Expected hex digit counts for GoogleSQL numeric escapes (\xHH, \uHHHH, \UHHHHHHHH).
|
|
152
|
+
_HEX_ESCAPE_DIGIT_COUNTS = {"x": 2, "X": 2, "u": 4, "U": 8}
|
|
153
|
+
|
|
154
|
+
# GoogleSQL unquoted identifiers must start with an ASCII letter or '_' and
|
|
155
|
+
# continue with ASCII letters, digits, or '_'.
|
|
156
|
+
_UNQUOTED_IDENTIFIER_FIRST_CHARS = frozenset(string.ascii_letters + "_")
|
|
157
|
+
_UNQUOTED_IDENTIFIER_CHARS = frozenset(string.ascii_letters + string.digits + "_")
|
|
158
|
+
_OCTAL_DIGITS = frozenset("01234567")
|
|
159
|
+
_HEX_DIGITS = frozenset(string.hexdigits)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _is_valid_unquoted_identifier(value: str) -> bool:
|
|
163
|
+
"""Return True if value can be used unquoted in GoogleSQL.
|
|
164
|
+
|
|
165
|
+
Unquoted GoogleSQL identifiers must start with an ASCII letter or ``_``
|
|
166
|
+
and contain only ASCII letters, digits, or ``_``.
|
|
167
|
+
|
|
168
|
+
Example:
|
|
169
|
+
``"col_1"`` returns ``True``; ``"1col"`` and ``"col-1"`` return
|
|
170
|
+
``False``.
|
|
171
|
+
"""
|
|
172
|
+
return (
|
|
173
|
+
bool(value)
|
|
174
|
+
and value[0] in _UNQUOTED_IDENTIFIER_FIRST_CHARS
|
|
175
|
+
and all(character in _UNQUOTED_IDENTIFIER_CHARS for character in value[1:])
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _decode_octal_escape(value: str, escape_start_index: int) -> tuple[str, int]:
|
|
180
|
+
r"""Decode a 3-digit GoogleSQL octal escape (\ooo) for bytes 0x00-0xFF.
|
|
181
|
+
|
|
182
|
+
Starts at the first octal digit (after ``\``) and returns
|
|
183
|
+
``(decoded_character, next_index)``, where ``next_index`` points just past
|
|
184
|
+
the 3 octal digits.
|
|
185
|
+
|
|
186
|
+
Example:
|
|
187
|
+
Decoding ``r"a\101b"`` from ``escape_start_index=2`` returns
|
|
188
|
+
``("A", 5)``.
|
|
189
|
+
"""
|
|
190
|
+
end_index = escape_start_index + 3
|
|
191
|
+
octal_digits = value[escape_start_index:end_index]
|
|
192
|
+
if len(octal_digits) < 3 or not all(
|
|
193
|
+
digit in _OCTAL_DIGITS for digit in octal_digits
|
|
194
|
+
):
|
|
195
|
+
raise ValueError(
|
|
196
|
+
f"Invalid octal escape sequence in identifier: \\{octal_digits}"
|
|
197
|
+
)
|
|
198
|
+
octal_value = int(octal_digits, 8)
|
|
199
|
+
if octal_value > 0xFF:
|
|
200
|
+
raise ValueError(
|
|
201
|
+
f"Invalid octal escape sequence in identifier: \\{octal_digits}"
|
|
202
|
+
)
|
|
203
|
+
return chr(octal_value), end_index
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _decode_hex_escape(
|
|
207
|
+
value: str, escape_start_index: int, digit_count: int
|
|
208
|
+
) -> tuple[str, int]:
|
|
209
|
+
r"""Decode a GoogleSQL hex or Unicode escape (\xHH, \uHHHH, \UHHHHHHHH).
|
|
210
|
+
|
|
211
|
+
Starts at the escape prefix character (``x``, ``X``, ``u``, or ``U``) and
|
|
212
|
+
returns ``(decoded_character, next_index)``, where ``next_index`` points
|
|
213
|
+
just past the hex digits.
|
|
214
|
+
|
|
215
|
+
Example:
|
|
216
|
+
Decoding ``r"\u0060z"`` with ``escape_start_index=1, digit_count=4``
|
|
217
|
+
returns ``("`", 6)``.
|
|
218
|
+
"""
|
|
219
|
+
escape_character = value[escape_start_index]
|
|
220
|
+
digits_start_index = escape_start_index + 1
|
|
221
|
+
end_index = digits_start_index + digit_count
|
|
222
|
+
hex_digits = value[digits_start_index:end_index]
|
|
223
|
+
if len(hex_digits) < digit_count or not all(
|
|
224
|
+
digit in _HEX_DIGITS for digit in hex_digits
|
|
225
|
+
):
|
|
226
|
+
raise ValueError(
|
|
227
|
+
f"Invalid \\{escape_character} escape sequence in identifier: "
|
|
228
|
+
f"\\{escape_character}{hex_digits}"
|
|
229
|
+
)
|
|
230
|
+
codepoint = int(hex_digits, 16)
|
|
231
|
+
# UTF-16 surrogates (U+D800-U+DFFF) and values above U+10FFFF are invalid
|
|
232
|
+
# Unicode scalar values in GoogleSQL \u/\U escapes.
|
|
233
|
+
if escape_character in ("u", "U") and (
|
|
234
|
+
0xD800 <= codepoint <= 0xDFFF or codepoint > 0x10FFFF
|
|
235
|
+
):
|
|
236
|
+
raise ValueError(f"Invalid Unicode codepoint in identifier: U+{codepoint:04X}")
|
|
237
|
+
return chr(codepoint), end_index
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _decode_googlesql_escape(value: str, backslash_index: int) -> tuple[str, int]:
|
|
241
|
+
r"""Decode one GoogleSQL backslash escape sequence at ``backslash_index``.
|
|
242
|
+
|
|
243
|
+
Returns ``(decoded_character, next_index)``, where ``next_index`` is the
|
|
244
|
+
first index after the escape sequence.
|
|
245
|
+
|
|
246
|
+
Example:
|
|
247
|
+
Decoding ``r"a\nb"`` from ``backslash_index=1`` returns ``("\n", 3)``.
|
|
248
|
+
"""
|
|
249
|
+
escape_start_index = backslash_index + 1
|
|
250
|
+
if escape_start_index >= len(value):
|
|
251
|
+
raise ValueError(f"Unterminated escape sequence in identifier: {value!r}")
|
|
252
|
+
|
|
253
|
+
escape_character = value[escape_start_index]
|
|
254
|
+
|
|
255
|
+
# 1. Single-character escape (e.g. \n, \\, \`, \").
|
|
256
|
+
single_character = _GOOGLESQL_SINGLE_CHAR_UNESCAPE_TABLE.get(escape_character)
|
|
257
|
+
if single_character is not None:
|
|
258
|
+
return single_character, escape_start_index + 1
|
|
259
|
+
|
|
260
|
+
# 2. Fixed 3-digit octal escape (\ooo, restricted to single-byte 0x00-0xFF).
|
|
261
|
+
if escape_character in _OCTAL_DIGITS:
|
|
262
|
+
return _decode_octal_escape(value, escape_start_index)
|
|
108
263
|
|
|
109
|
-
|
|
110
|
-
|
|
264
|
+
# 3. Fixed-width hexadecimal or Unicode escape (\xHH, \uHHHH, \UHHHHHHHH).
|
|
265
|
+
digit_count = _HEX_ESCAPE_DIGIT_COUNTS.get(escape_character)
|
|
266
|
+
if digit_count is not None:
|
|
267
|
+
return _decode_hex_escape(value, escape_start_index, digit_count)
|
|
111
268
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
269
|
+
raise ValueError(f"Invalid escape sequence in identifier: \\{escape_character}")
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _escape_json_path_key(key: Any) -> str:
|
|
273
|
+
r"""Escape a JSON member key for use inside double-quoted GoogleSQL JSONPath.
|
|
274
|
+
|
|
275
|
+
GoogleSQL double-quoted JSONPath keys (``."..."``) unescape ``\"`` to
|
|
276
|
+
``"``, while keeping backslashes before any other character literal. As a
|
|
277
|
+
result, any run of backslashes immediately before a ``"`` or at the end of
|
|
278
|
+
the key (directly preceding the closing ``"``) must be doubled so it does
|
|
279
|
+
not escape the quote delimiter, while backslashes before other characters
|
|
280
|
+
are kept as-is.
|
|
117
281
|
"""
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
282
|
+
raw_key = str(key)
|
|
283
|
+
if "\\" not in raw_key:
|
|
284
|
+
return raw_key.replace('"', '\\"')
|
|
285
|
+
if '"' not in raw_key and not raw_key.endswith("\\"):
|
|
286
|
+
return raw_key
|
|
287
|
+
# Splitting on `"` puts every backslash run that precedes `"` or end-of-string
|
|
288
|
+
# at the end of a part, avoiding regex lookahead backtracking.
|
|
289
|
+
parts = raw_key.split('"')
|
|
290
|
+
for index, part in enumerate(parts):
|
|
291
|
+
if part.endswith("\\"):
|
|
292
|
+
stripped_length = len(part.rstrip("\\"))
|
|
293
|
+
parts[index] = part + part[stripped_length:]
|
|
294
|
+
return '\\"'.join(parts)
|
|
121
295
|
|
|
122
296
|
|
|
123
297
|
def _escape_spanner_string_literal(value, dialect=None):
|
|
@@ -286,6 +460,7 @@ def engine_to_connection(function):
|
|
|
286
460
|
database in case of an engine-related use.
|
|
287
461
|
"""
|
|
288
462
|
|
|
463
|
+
@functools.wraps(function)
|
|
289
464
|
def wrapper(self, connection, *args, **kwargs):
|
|
290
465
|
"""
|
|
291
466
|
Args:
|
|
@@ -296,7 +471,11 @@ def engine_to_connection(function):
|
|
|
296
471
|
SQLAlchemy connection or engine object.
|
|
297
472
|
"""
|
|
298
473
|
if isinstance(connection, Engine):
|
|
299
|
-
|
|
474
|
+
opened_connection = connection.connect()
|
|
475
|
+
try:
|
|
476
|
+
return function(self, opened_connection, *args, **kwargs)
|
|
477
|
+
finally:
|
|
478
|
+
opened_connection.close()
|
|
300
479
|
|
|
301
480
|
return function(self, connection, *args, **kwargs)
|
|
302
481
|
|
|
@@ -359,7 +538,8 @@ class SpannerExecutionContext(DefaultExecutionContext):
|
|
|
359
538
|
class SpannerIdentifierPreparer(IdentifierPreparer):
|
|
360
539
|
"""Identifiers compiler.
|
|
361
540
|
|
|
362
|
-
In Cloud Spanner backticks "`" are used for
|
|
541
|
+
In Cloud Spanner backticks "`" are used for identifier quoting, and
|
|
542
|
+
GoogleSQL backslash escape sequences are used inside backticks.
|
|
363
543
|
"""
|
|
364
544
|
|
|
365
545
|
reserved_words = RESERVED_WORDS.copy()
|
|
@@ -368,22 +548,220 @@ class SpannerIdentifierPreparer(IdentifierPreparer):
|
|
|
368
548
|
|
|
369
549
|
def __init__(self, dialect):
|
|
370
550
|
super(SpannerIdentifierPreparer, self).__init__(
|
|
371
|
-
dialect, initial_quote="`", final_quote="`"
|
|
551
|
+
dialect, initial_quote="`", final_quote="`", escape_quote="\\"
|
|
372
552
|
)
|
|
373
553
|
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
if
|
|
378
|
-
|
|
554
|
+
@staticmethod
|
|
555
|
+
def _validate_identifier(value: str) -> str:
|
|
556
|
+
"""Ensure value is a str (unwrapping subclasses like quoted_name)."""
|
|
557
|
+
if not isinstance(value, str):
|
|
558
|
+
raise TypeError(f"Identifier must be a string, got {type(value).__name__}")
|
|
559
|
+
return value if type(value) is str else str(value)
|
|
560
|
+
|
|
561
|
+
def _escape_identifier(self, value: str) -> str:
|
|
562
|
+
r"""Escape an identifier's contents for use inside backticks.
|
|
563
|
+
|
|
564
|
+
Replaces backslashes, backticks, and control characters with GoogleSQL
|
|
565
|
+
escape sequences (and doubles ``%`` when required by paramstyle).
|
|
566
|
+
|
|
567
|
+
Example:
|
|
568
|
+
``r"a`b\c"`` becomes ``r"a\u0060b\\c"``.
|
|
569
|
+
"""
|
|
570
|
+
identifier = self._validate_identifier(value)
|
|
571
|
+
escaped = identifier.translate(_SPANNER_IDENTIFIER_ESCAPE_TABLE)
|
|
572
|
+
# Under format/pyformat paramstyle, spanner_dbapi expects literal '%'
|
|
573
|
+
# characters in SQL templates to be doubled as '%%'.
|
|
574
|
+
if self._double_percents:
|
|
575
|
+
escaped = escaped.replace("%", "%%")
|
|
576
|
+
return escaped
|
|
577
|
+
|
|
578
|
+
# TODO(https://github.com/googleapis/google-cloud-python/issues/19209): Move
|
|
579
|
+
# the GoogleSQL identifier unescaping and qualified-segment scanning logic
|
|
580
|
+
# (_unescape_identifier, _read_quoted_identifier, _read_unquoted_identifier,
|
|
581
|
+
# and unformat_identifiers) to google.cloud.spanner_dbapi alongside the
|
|
582
|
+
# GoogleSQL escape helpers.
|
|
583
|
+
def _unescape_identifier(self, value: str) -> str:
|
|
584
|
+
r"""Decode GoogleSQL backslash escapes inside a quoted identifier body.
|
|
585
|
+
|
|
586
|
+
Example:
|
|
587
|
+
``r"a\u0060b\\c"`` becomes ``r"a`b\c"``.
|
|
588
|
+
"""
|
|
589
|
+
identifier = self._validate_identifier(value)
|
|
590
|
+
if "\\" not in identifier:
|
|
591
|
+
return identifier
|
|
592
|
+
|
|
593
|
+
unescaped_parts: list[str] = []
|
|
594
|
+
index = 0
|
|
595
|
+
length = len(identifier)
|
|
596
|
+
while index < length:
|
|
597
|
+
backslash_index = identifier.find("\\", index)
|
|
598
|
+
if backslash_index == -1:
|
|
599
|
+
unescaped_parts.append(identifier[index:])
|
|
600
|
+
break
|
|
601
|
+
if backslash_index > index:
|
|
602
|
+
unescaped_parts.append(identifier[index:backslash_index])
|
|
603
|
+
decoded_character, index = _decode_googlesql_escape(
|
|
604
|
+
identifier, backslash_index
|
|
605
|
+
)
|
|
606
|
+
unescaped_parts.append(decoded_character)
|
|
607
|
+
return "".join(unescaped_parts)
|
|
608
|
+
|
|
609
|
+
def _read_quoted_identifier(
|
|
610
|
+
self, qualified_identifiers: str, opening_backtick_index: int
|
|
611
|
+
) -> tuple[str, int]:
|
|
612
|
+
r"""Read and unescape one backtick-quoted segment in a qualified name.
|
|
613
|
+
|
|
614
|
+
Starts at ``opening_backtick_index`` and returns
|
|
615
|
+
``(unescaped_segment, next_index)``, where ``next_index`` is the
|
|
616
|
+
position of the following ``.`` separator or the end of the string.
|
|
617
|
+
|
|
618
|
+
Example:
|
|
619
|
+
Reading from index 0 of ``r"`a\`b`.c"`` returns ``("a`b", 6)``,
|
|
620
|
+
where index 6 is the ``.`` before ``"c"``.
|
|
621
|
+
"""
|
|
622
|
+
content_start_index = opening_backtick_index + 1
|
|
623
|
+
current_index = content_start_index
|
|
624
|
+
length = len(qualified_identifiers)
|
|
625
|
+
while current_index < length:
|
|
626
|
+
character = qualified_identifiers[current_index]
|
|
627
|
+
if character == "\\":
|
|
628
|
+
if current_index + 1 >= length:
|
|
629
|
+
raise ValueError(
|
|
630
|
+
f"Unterminated escape sequence in identifier: "
|
|
631
|
+
f"{qualified_identifiers!r}"
|
|
632
|
+
)
|
|
633
|
+
# Advance past both '\' and the escaped character so \` or \\ does
|
|
634
|
+
# not prematurely terminate the quoted identifier.
|
|
635
|
+
current_index += 2
|
|
636
|
+
elif character == "`":
|
|
637
|
+
unescaped_segment = self._unescape_identifier(
|
|
638
|
+
qualified_identifiers[content_start_index:current_index]
|
|
639
|
+
)
|
|
640
|
+
end_index = current_index + 1
|
|
641
|
+
# A closing backtick must be followed by '.' or end of string.
|
|
642
|
+
if end_index < length and qualified_identifiers[end_index] != ".":
|
|
643
|
+
raise ValueError(
|
|
644
|
+
"Unexpected character after quoted identifier: "
|
|
645
|
+
f"{qualified_identifiers!r}"
|
|
646
|
+
)
|
|
647
|
+
return unescaped_segment, end_index
|
|
648
|
+
else:
|
|
649
|
+
current_index += 1
|
|
650
|
+
raise ValueError(f"Unterminated quoted identifier: {qualified_identifiers!r}")
|
|
651
|
+
|
|
652
|
+
@staticmethod
|
|
653
|
+
def _read_unquoted_identifier(
|
|
654
|
+
qualified_identifiers: str, start_index: int
|
|
655
|
+
) -> tuple[str, int]:
|
|
656
|
+
"""Read and validate one unquoted segment in a qualified name.
|
|
657
|
+
|
|
658
|
+
Starts at ``start_index`` and returns ``(segment, next_index)``, where
|
|
659
|
+
``next_index`` is the position of the following ``.`` separator or the
|
|
660
|
+
end of the string.
|
|
661
|
+
|
|
662
|
+
Example:
|
|
663
|
+
Reading from index 0 of ``"schema.table"`` returns
|
|
664
|
+
``("schema", 6)``, where index 6 is the ``.`` before ``"table"``.
|
|
665
|
+
"""
|
|
666
|
+
dot_index = qualified_identifiers.find(".", start_index)
|
|
667
|
+
end_index = len(qualified_identifiers) if dot_index == -1 else dot_index
|
|
668
|
+
segment = qualified_identifiers[start_index:end_index]
|
|
669
|
+
if not _is_valid_unquoted_identifier(segment):
|
|
670
|
+
raise ValueError(
|
|
671
|
+
f"Invalid unquoted identifier segment: {qualified_identifiers!r}"
|
|
672
|
+
)
|
|
673
|
+
return segment, end_index
|
|
674
|
+
|
|
675
|
+
def unformat_identifiers(self, identifiers: str) -> list[str]:
|
|
676
|
+
r"""Split a dot-qualified SQL identifier into unescaped segments.
|
|
379
677
|
|
|
678
|
+
Example:
|
|
679
|
+
``r"`my.schema`.`a\u0060b`.col"`` returns
|
|
680
|
+
``["my.schema", "a`b", "col"]``.
|
|
681
|
+
"""
|
|
682
|
+
qualified_identifiers = self._validate_identifier(identifiers)
|
|
683
|
+
if not qualified_identifiers:
|
|
684
|
+
return []
|
|
685
|
+
|
|
686
|
+
segments: list[str] = []
|
|
687
|
+
position = 0
|
|
688
|
+
length = len(qualified_identifiers)
|
|
689
|
+
while position < length:
|
|
690
|
+
if qualified_identifiers[position] == "`":
|
|
691
|
+
segment, position = self._read_quoted_identifier(
|
|
692
|
+
qualified_identifiers, position
|
|
693
|
+
)
|
|
694
|
+
else:
|
|
695
|
+
segment, position = self._read_unquoted_identifier(
|
|
696
|
+
qualified_identifiers, position
|
|
697
|
+
)
|
|
698
|
+
segments.append(segment)
|
|
699
|
+
|
|
700
|
+
if position < length:
|
|
701
|
+
# Consume the '.' separator and reject a dangling trailing dot.
|
|
702
|
+
position += 1
|
|
703
|
+
if position == length:
|
|
704
|
+
raise ValueError(
|
|
705
|
+
f"Trailing dot in qualified identifier: {identifiers!r}"
|
|
706
|
+
)
|
|
707
|
+
return segments
|
|
708
|
+
|
|
709
|
+
def format_collation(
|
|
710
|
+
self, collation_name: str, collation_schema: str | None = None
|
|
711
|
+
) -> str:
|
|
712
|
+
"""Format a collation name, keeping Spanner's '"unicode"' literal unquoted.
|
|
713
|
+
|
|
714
|
+
Example:
|
|
715
|
+
``format_collation('"unicode"')`` returns ``'"unicode"'``.
|
|
716
|
+
"""
|
|
717
|
+
validated_name = self._validate_identifier(collation_name)
|
|
718
|
+
if validated_name.lower() == '"unicode"':
|
|
719
|
+
formatted_name = validated_name
|
|
720
|
+
else:
|
|
721
|
+
# Call super() with a single argument because SQLAlchemy < 2.1
|
|
722
|
+
# does not accept a collation_schema parameter.
|
|
723
|
+
formatted_name = super(SpannerIdentifierPreparer, self).format_collation(
|
|
724
|
+
validated_name
|
|
725
|
+
)
|
|
726
|
+
if collation_schema is not None:
|
|
727
|
+
return f"{self.quote_schema(collation_schema)}.{formatted_name}"
|
|
728
|
+
return formatted_name
|
|
729
|
+
|
|
730
|
+
def _requires_quotes(self, value: str) -> bool:
|
|
731
|
+
"""Return True if value needs backtick quoting as a SQL identifier.
|
|
732
|
+
|
|
733
|
+
Quotes empty names, reserved keywords, identifiers containing invalid
|
|
734
|
+
unquoted characters, and mixed/upper-case names.
|
|
735
|
+
|
|
736
|
+
Example:
|
|
737
|
+
``"users"`` returns ``False``; ``"Users"``, ``"select"``, and
|
|
738
|
+
``"a`b"`` return ``True``.
|
|
739
|
+
"""
|
|
740
|
+
identifier = self._validate_identifier(value)
|
|
741
|
+
if not identifier:
|
|
742
|
+
return True
|
|
743
|
+
lowercase_identifier = identifier.lower()
|
|
744
|
+
|
|
745
|
+
# Quote reserved keywords, identifiers with non-GoogleSQL characters, and
|
|
746
|
+
# mixed/upper-case names (matching SQLAlchemy's case-preserving convention).
|
|
380
747
|
return (
|
|
381
|
-
|
|
382
|
-
or
|
|
383
|
-
or
|
|
384
|
-
or (lc_value != value)
|
|
748
|
+
lowercase_identifier in self.reserved_words_lc
|
|
749
|
+
or not _is_valid_unquoted_identifier(identifier)
|
|
750
|
+
or (lowercase_identifier != identifier)
|
|
385
751
|
)
|
|
386
752
|
|
|
753
|
+
def _requires_quotes_illegal_chars(self, value: str) -> bool:
|
|
754
|
+
"""Return True if value cannot be written unquoted (ignoring case/keywords).
|
|
755
|
+
|
|
756
|
+
Used by SQLAlchemy when quoting function names (``sa.func``) so only
|
|
757
|
+
syntax-breaking names are wrapped in backticks.
|
|
758
|
+
|
|
759
|
+
Example:
|
|
760
|
+
``"MyCustomFn"`` returns ``False``; ``"1fn"`` and ``"fn`name"`` return
|
|
761
|
+
``True``.
|
|
762
|
+
"""
|
|
763
|
+
return not _is_valid_unquoted_identifier(self._validate_identifier(value))
|
|
764
|
+
|
|
387
765
|
|
|
388
766
|
class SpannerSQLCompiler(SQLCompiler):
|
|
389
767
|
"""Spanner SQL statements compiler."""
|
|
@@ -486,14 +864,6 @@ class SpannerSQLCompiler(SQLCompiler):
|
|
|
486
864
|
|
|
487
865
|
return "JSON_VALUE(%s, %s)" % (left_text, right_text)
|
|
488
866
|
|
|
489
|
-
def _generate_generic_binary(self, binary, opstring, eager_grouping=False, **kw):
|
|
490
|
-
"""The method is overriden to process JSON data type cases."""
|
|
491
|
-
if isinstance(opstring, str):
|
|
492
|
-
return super()._generate_generic_binary(
|
|
493
|
-
binary, opstring, eager_grouping=eager_grouping, **kw
|
|
494
|
-
)
|
|
495
|
-
return self._json_value_binary(binary, eager_grouping=eager_grouping, **kw)
|
|
496
|
-
|
|
497
867
|
def visit_json_getitem_op_binary(self, binary, operator, **kw):
|
|
498
868
|
"""Build a JSON_VALUE() function call for single-key JSON indexing."""
|
|
499
869
|
return self._json_value_binary(binary, **kw)
|
|
@@ -836,7 +1206,7 @@ class SpannerDDLCompiler(DDLCompiler):
|
|
|
836
1206
|
text += " NOT ENFORCED"
|
|
837
1207
|
return text
|
|
838
1208
|
|
|
839
|
-
def post_create_table(self, table):
|
|
1209
|
+
def post_create_table(self, table: sqlalchemy.Table) -> str:
|
|
840
1210
|
"""Build statements to be executed after CREATE TABLE.
|
|
841
1211
|
|
|
842
1212
|
Includes "primary key" and "interleaved table" statements generation.
|
|
@@ -847,17 +1217,30 @@ class SpannerDDLCompiler(DDLCompiler):
|
|
|
847
1217
|
Returns:
|
|
848
1218
|
str: primary key difinition to add to the table CREATE request.
|
|
849
1219
|
"""
|
|
850
|
-
|
|
851
|
-
|
|
1220
|
+
primary_key_columns = [
|
|
1221
|
+
self.preparer.quote(column.name) for column in table.primary_key.columns
|
|
1222
|
+
]
|
|
1223
|
+
post_cmds = f" PRIMARY KEY ({', '.join(primary_key_columns)})"
|
|
852
1224
|
|
|
853
1225
|
if "TEMPORARY" in table._prefixes:
|
|
854
1226
|
raise NotImplementedError("Temporary tables are not supported.")
|
|
855
1227
|
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
1228
|
+
interleave_in = table.kwargs.get("spanner_interleave_in")
|
|
1229
|
+
if interleave_in is None:
|
|
1230
|
+
parent_table = None
|
|
1231
|
+
elif isinstance(interleave_in, sqlalchemy.Table):
|
|
1232
|
+
parent_table = self.preparer.format_table(interleave_in)
|
|
1233
|
+
elif isinstance(interleave_in, str):
|
|
1234
|
+
parent_table = self.preparer.quote(interleave_in) if interleave_in else None
|
|
1235
|
+
else:
|
|
1236
|
+
raise TypeError(
|
|
1237
|
+
"spanner_interleave_in must be a string or Table, "
|
|
1238
|
+
f"got {type(interleave_in).__name__}"
|
|
859
1239
|
)
|
|
860
1240
|
|
|
1241
|
+
if parent_table is not None:
|
|
1242
|
+
post_cmds += f",\nINTERLEAVE IN PARENT {parent_table}"
|
|
1243
|
+
|
|
861
1244
|
if table.kwargs.get("spanner_interleave_on_delete_cascade"):
|
|
862
1245
|
post_cmds += " ON DELETE CASCADE"
|
|
863
1246
|
|
|
@@ -1116,27 +1499,142 @@ class SpannerDialect(DefaultDialect):
|
|
|
1116
1499
|
table_type_query = table_type_query + " AND "
|
|
1117
1500
|
return table_type_query
|
|
1118
1501
|
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1502
|
+
@staticmethod
|
|
1503
|
+
def _normalize_name_param(name: Optional[str]) -> Optional[str]:
|
|
1504
|
+
"""Convert SQLAlchemy ``str`` subclasses (e.g. ``quoted_name``) to ``str``.
|
|
1505
|
+
|
|
1506
|
+
Unwrapping ``str`` subclasses avoids custom string proxy objects in
|
|
1507
|
+
Spanner bind parameters while preserving ``None`` (bound as ``NULL``).
|
|
1508
|
+
|
|
1509
|
+
Example:
|
|
1510
|
+
``_normalize_name_param(quoted_name("users", True))`` -> ``"users"``
|
|
1511
|
+
``_normalize_name_param(None)`` -> ``None``
|
|
1512
|
+
"""
|
|
1513
|
+
return str(name) if isinstance(name, str) else name
|
|
1514
|
+
|
|
1515
|
+
@classmethod
|
|
1516
|
+
def _normalize_schema_param(cls, schema: Optional[str]) -> str:
|
|
1517
|
+
"""Normalize an optional schema name to Spanner's string representation.
|
|
1518
|
+
|
|
1519
|
+
Cloud Spanner's ``INFORMATION_SCHEMA`` stores the default schema as ``""``
|
|
1520
|
+
rather than ``NULL``, so both ``None`` and ``""`` map to ``""``.
|
|
1521
|
+
|
|
1522
|
+
Example:
|
|
1523
|
+
``_normalize_schema_param(None)`` -> ``""``
|
|
1524
|
+
``_normalize_schema_param("my_schema")`` -> ``"my_schema"``
|
|
1122
1525
|
"""
|
|
1123
|
-
|
|
1124
|
-
|
|
1526
|
+
if not schema:
|
|
1527
|
+
return ""
|
|
1528
|
+
normalized = cls._normalize_name_param(schema)
|
|
1529
|
+
return "" if normalized is None else normalized
|
|
1530
|
+
|
|
1531
|
+
def _get_table_filter_query(
|
|
1532
|
+
self,
|
|
1533
|
+
filter_names: Optional[Iterable[str]],
|
|
1534
|
+
info_schema_table: str,
|
|
1535
|
+
append_query: bool = False,
|
|
1536
|
+
) -> str:
|
|
1537
|
+
"""Generate a parameterized ``IN UNNEST`` predicate for ``filter_names``.
|
|
1538
|
+
|
|
1539
|
+
Example:
|
|
1540
|
+
``_get_table_filter_query(["users"], "col", append_query=True)`` ->
|
|
1541
|
+
``"(col.table_name IN UNNEST(@table_names)) AND "``
|
|
1542
|
+
``_get_table_filter_query(None, "col", append_query=True)`` -> ``""``
|
|
1125
1543
|
"""
|
|
1126
1544
|
table_filter_query = ""
|
|
1127
1545
|
if filter_names is not None:
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
table_filter_query = table_filter_query + " OR " + query
|
|
1132
|
-
else:
|
|
1133
|
-
table_filter_query = query
|
|
1134
|
-
table_filter_query = "(" + table_filter_query + ") "
|
|
1546
|
+
table_filter_query = (
|
|
1547
|
+
f"({info_schema_table}.table_name IN UNNEST(@table_names)) "
|
|
1548
|
+
)
|
|
1135
1549
|
if append_query:
|
|
1136
1550
|
table_filter_query = table_filter_query + " AND "
|
|
1137
1551
|
|
|
1138
1552
|
return table_filter_query
|
|
1139
1553
|
|
|
1554
|
+
def _prepare_multi_reflection_filters(
|
|
1555
|
+
self,
|
|
1556
|
+
schema: Optional[str],
|
|
1557
|
+
filter_names: Optional[Iterable[str]],
|
|
1558
|
+
info_schema_table: str,
|
|
1559
|
+
kind: Optional["ObjectKind"],
|
|
1560
|
+
) -> Optional[Tuple[str, str, Dict[str, Any], Dict[str, Any]]]:
|
|
1561
|
+
"""Build parameterized WHERE clauses and bind parameters for ``get_multi_*``.
|
|
1562
|
+
|
|
1563
|
+
Returns ``None`` when ``filter_names`` is an empty non-``None``
|
|
1564
|
+
collection so callers can return ``{}`` without issuing a query.
|
|
1565
|
+
|
|
1566
|
+
Example:
|
|
1567
|
+
``_prepare_multi_reflection_filters("s", ["users"], "col", None)``
|
|
1568
|
+
returns ``(table_filter_query, table_type_query, params, param_types)``
|
|
1569
|
+
where ``params={"table_schema": "s", "table_names": ["users"]}``.
|
|
1570
|
+
"""
|
|
1571
|
+
table_type_query = self._get_table_type_query(kind, True)
|
|
1572
|
+
params: Dict[str, Any] = {"table_schema": self._normalize_schema_param(schema)}
|
|
1573
|
+
query_param_types: Dict[str, Any] = {"table_schema": param_types.STRING}
|
|
1574
|
+
|
|
1575
|
+
if filter_names is not None:
|
|
1576
|
+
filter_name_list = [
|
|
1577
|
+
self._normalize_name_param(name) for name in filter_names
|
|
1578
|
+
]
|
|
1579
|
+
if not filter_name_list:
|
|
1580
|
+
return None
|
|
1581
|
+
params["table_names"] = filter_name_list
|
|
1582
|
+
query_param_types["table_names"] = param_types.Array(param_types.STRING)
|
|
1583
|
+
|
|
1584
|
+
table_filter_query = self._get_table_filter_query(
|
|
1585
|
+
filter_names, info_schema_table, True
|
|
1586
|
+
)
|
|
1587
|
+
return table_filter_query, table_type_query, params, query_param_types
|
|
1588
|
+
|
|
1589
|
+
def _query_schema_object_names(
|
|
1590
|
+
self, connection: Any, sql: str, schema: Optional[str]
|
|
1591
|
+
) -> List[str]:
|
|
1592
|
+
"""Run a single-column ``information_schema`` query filtered by schema.
|
|
1593
|
+
|
|
1594
|
+
Example:
|
|
1595
|
+
Used by ``get_table_names``, ``get_view_names``, and
|
|
1596
|
+
``get_sequence_names`` to return matching names such as
|
|
1597
|
+
``["singers", "albums"]``.
|
|
1598
|
+
"""
|
|
1599
|
+
params = {"table_schema": self._normalize_schema_param(schema)}
|
|
1600
|
+
query_param_types = {"table_schema": param_types.STRING}
|
|
1601
|
+
with connection.connection.database.snapshot() as snapshot:
|
|
1602
|
+
rows = list(
|
|
1603
|
+
snapshot.execute_sql(sql, params=params, param_types=query_param_types)
|
|
1604
|
+
)
|
|
1605
|
+
return [row[0] for row in rows]
|
|
1606
|
+
|
|
1607
|
+
def _record_exists_for_schema(
|
|
1608
|
+
self,
|
|
1609
|
+
connection: Any,
|
|
1610
|
+
sql: str,
|
|
1611
|
+
schema: Optional[str],
|
|
1612
|
+
name_param: str,
|
|
1613
|
+
name_value: Optional[str],
|
|
1614
|
+
) -> bool:
|
|
1615
|
+
"""Run a parameterized existence check and drain the result stream.
|
|
1616
|
+
|
|
1617
|
+
Materializes the ``LIMIT 1`` result via ``list(...)`` rather than
|
|
1618
|
+
returning inside a loop so the underlying gRPC stream reaches EOF.
|
|
1619
|
+
|
|
1620
|
+
Example:
|
|
1621
|
+
Used by ``has_table`` (``name_param="table_name"``) and
|
|
1622
|
+
``has_sequence`` (``name_param="sequence_name"``).
|
|
1623
|
+
"""
|
|
1624
|
+
params = {
|
|
1625
|
+
"table_schema": self._normalize_schema_param(schema),
|
|
1626
|
+
name_param: self._normalize_name_param(name_value),
|
|
1627
|
+
}
|
|
1628
|
+
query_param_types = {
|
|
1629
|
+
"table_schema": param_types.STRING,
|
|
1630
|
+
name_param: param_types.STRING,
|
|
1631
|
+
}
|
|
1632
|
+
with connection.connection.database.snapshot() as snapshot:
|
|
1633
|
+
rows = list(
|
|
1634
|
+
snapshot.execute_sql(sql, params=params, param_types=query_param_types)
|
|
1635
|
+
)
|
|
1636
|
+
return bool(rows)
|
|
1637
|
+
|
|
1140
1638
|
def create_connect_args(self, url):
|
|
1141
1639
|
"""Parse connection args from the given URL.
|
|
1142
1640
|
|
|
@@ -1199,16 +1697,9 @@ class SpannerDialect(DefaultDialect):
|
|
|
1199
1697
|
sql = """
|
|
1200
1698
|
SELECT table_name
|
|
1201
1699
|
FROM information_schema.views
|
|
1202
|
-
WHERE TABLE_SCHEMA=
|
|
1203
|
-
"""
|
|
1204
|
-
|
|
1205
|
-
all_views = []
|
|
1206
|
-
with connection.connection.database.snapshot() as snap:
|
|
1207
|
-
rows = list(snap.execute_sql(sql))
|
|
1208
|
-
for view in rows:
|
|
1209
|
-
all_views.append(view[0])
|
|
1210
|
-
|
|
1211
|
-
return all_views
|
|
1700
|
+
WHERE TABLE_SCHEMA = @table_schema
|
|
1701
|
+
"""
|
|
1702
|
+
return self._query_schema_object_names(connection, sql, schema)
|
|
1212
1703
|
|
|
1213
1704
|
@engine_to_connection
|
|
1214
1705
|
def get_sequence_names(self, connection, schema=None, **kw):
|
|
@@ -1228,15 +1719,9 @@ class SpannerDialect(DefaultDialect):
|
|
|
1228
1719
|
sql = """
|
|
1229
1720
|
SELECT name
|
|
1230
1721
|
FROM information_schema.sequences
|
|
1231
|
-
WHERE SCHEMA=
|
|
1232
|
-
"""
|
|
1233
|
-
|
|
1234
|
-
with connection.connection.database.snapshot() as snap:
|
|
1235
|
-
rows = list(snap.execute_sql(sql))
|
|
1236
|
-
for seq in rows:
|
|
1237
|
-
all_sequences.append(seq[0])
|
|
1238
|
-
|
|
1239
|
-
return all_sequences
|
|
1722
|
+
WHERE SCHEMA = @table_schema
|
|
1723
|
+
"""
|
|
1724
|
+
return self._query_schema_object_names(connection, sql, schema)
|
|
1240
1725
|
|
|
1241
1726
|
@engine_to_connection
|
|
1242
1727
|
def get_view_definition(self, connection, view_name, schema=None, **kw):
|
|
@@ -1257,11 +1742,21 @@ class SpannerDialect(DefaultDialect):
|
|
|
1257
1742
|
sql = """
|
|
1258
1743
|
SELECT view_definition
|
|
1259
1744
|
FROM information_schema.views
|
|
1260
|
-
WHERE TABLE_SCHEMA=
|
|
1261
|
-
"""
|
|
1745
|
+
WHERE TABLE_SCHEMA = @table_schema AND TABLE_NAME = @view_name
|
|
1746
|
+
"""
|
|
1747
|
+
params = {
|
|
1748
|
+
"table_schema": self._normalize_schema_param(schema),
|
|
1749
|
+
"view_name": self._normalize_name_param(view_name),
|
|
1750
|
+
}
|
|
1751
|
+
query_param_types = {
|
|
1752
|
+
"table_schema": param_types.STRING,
|
|
1753
|
+
"view_name": param_types.STRING,
|
|
1754
|
+
}
|
|
1262
1755
|
|
|
1263
1756
|
with connection.connection.database.snapshot() as snap:
|
|
1264
|
-
rows = list(
|
|
1757
|
+
rows = list(
|
|
1758
|
+
snap.execute_sql(sql, params=params, param_types=query_param_types)
|
|
1759
|
+
)
|
|
1265
1760
|
if rows == []:
|
|
1266
1761
|
raise NoSuchTableError(f"{schema if schema else ''}.{view_name}")
|
|
1267
1762
|
result = rows[0][0]
|
|
@@ -1296,11 +1791,12 @@ class SpannerDialect(DefaultDialect):
|
|
|
1296
1791
|
definition of a database column.
|
|
1297
1792
|
The schema is ``None`` if no schema is provided.
|
|
1298
1793
|
"""
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
schema=schema or ""
|
|
1794
|
+
filters = self._prepare_multi_reflection_filters(
|
|
1795
|
+
schema, filter_names, "col", kind
|
|
1302
1796
|
)
|
|
1303
|
-
|
|
1797
|
+
if filters is None:
|
|
1798
|
+
return {}
|
|
1799
|
+
table_filter_query, table_type_query, params, query_param_types = filters
|
|
1304
1800
|
|
|
1305
1801
|
sql = """
|
|
1306
1802
|
SELECT col.table_schema, col.table_name, col.column_name,
|
|
@@ -1312,7 +1808,7 @@ class SpannerDialect(DefaultDialect):
|
|
|
1312
1808
|
WHERE
|
|
1313
1809
|
{table_filter_query}
|
|
1314
1810
|
{table_type_query}
|
|
1315
|
-
|
|
1811
|
+
col.table_schema = @table_schema AND
|
|
1316
1812
|
col.table_catalog = ''
|
|
1317
1813
|
ORDER BY
|
|
1318
1814
|
col.table_catalog,
|
|
@@ -1322,10 +1818,11 @@ class SpannerDialect(DefaultDialect):
|
|
|
1322
1818
|
""".format(
|
|
1323
1819
|
table_filter_query=table_filter_query,
|
|
1324
1820
|
table_type_query=table_type_query,
|
|
1325
|
-
schema_filter_query=schema_filter_query,
|
|
1326
1821
|
)
|
|
1327
1822
|
with connection.connection.database.snapshot() as snap:
|
|
1328
|
-
columns = list(
|
|
1823
|
+
columns = list(
|
|
1824
|
+
snap.execute_sql(sql, params=params, param_types=query_param_types)
|
|
1825
|
+
)
|
|
1329
1826
|
result_dict = {}
|
|
1330
1827
|
|
|
1331
1828
|
for col in columns:
|
|
@@ -1425,11 +1922,12 @@ class SpannerDialect(DefaultDialect):
|
|
|
1425
1922
|
definition of an index.
|
|
1426
1923
|
The schema is ``None`` if no schema is provided.
|
|
1427
1924
|
"""
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
schema=schema or ""
|
|
1925
|
+
filters = self._prepare_multi_reflection_filters(
|
|
1926
|
+
schema, filter_names, "i", kind
|
|
1431
1927
|
)
|
|
1432
|
-
|
|
1928
|
+
if filters is None:
|
|
1929
|
+
return {}
|
|
1930
|
+
table_filter_query, table_type_query, params, query_param_types = filters
|
|
1433
1931
|
|
|
1434
1932
|
sql = """
|
|
1435
1933
|
SELECT
|
|
@@ -1475,7 +1973,7 @@ class SpannerDialect(DefaultDialect):
|
|
|
1475
1973
|
WHERE
|
|
1476
1974
|
{table_filter_query}
|
|
1477
1975
|
{table_type_query}
|
|
1478
|
-
|
|
1976
|
+
i.table_schema = @table_schema AND
|
|
1479
1977
|
i.index_type != 'PRIMARY_KEY'
|
|
1480
1978
|
AND i.index_type != 'SEARCH'
|
|
1481
1979
|
AND i.spanner_is_managed = FALSE
|
|
@@ -1485,11 +1983,12 @@ class SpannerDialect(DefaultDialect):
|
|
|
1485
1983
|
""".format(
|
|
1486
1984
|
table_filter_query=table_filter_query,
|
|
1487
1985
|
table_type_query=table_type_query,
|
|
1488
|
-
schema_filter_query=schema_filter_query,
|
|
1489
1986
|
)
|
|
1490
1987
|
|
|
1491
1988
|
with connection.connection.database.snapshot() as snap:
|
|
1492
|
-
rows = list(
|
|
1989
|
+
rows = list(
|
|
1990
|
+
snap.execute_sql(sql, params=params, param_types=query_param_types)
|
|
1991
|
+
)
|
|
1493
1992
|
result_dict = {}
|
|
1494
1993
|
|
|
1495
1994
|
for row in rows:
|
|
@@ -1566,11 +2065,12 @@ class SpannerDialect(DefaultDialect):
|
|
|
1566
2065
|
definition of a primary key constraint.
|
|
1567
2066
|
The schema is ``None`` if no schema is provided.
|
|
1568
2067
|
"""
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
schema=schema or ""
|
|
2068
|
+
filters = self._prepare_multi_reflection_filters(
|
|
2069
|
+
schema, filter_names, "tc", kind
|
|
1572
2070
|
)
|
|
1573
|
-
|
|
2071
|
+
if filters is None:
|
|
2072
|
+
return {}
|
|
2073
|
+
table_filter_query, table_type_query, params, query_param_types = filters
|
|
1574
2074
|
|
|
1575
2075
|
sql = """
|
|
1576
2076
|
SELECT tc.table_schema, tc.table_name, kcu.column_name
|
|
@@ -1582,17 +2082,18 @@ class SpannerDialect(DefaultDialect):
|
|
|
1582
2082
|
AND tc.TABLE_SCHEMA = t.TABLE_SCHEMA
|
|
1583
2083
|
AND tc.TABLE_NAME = t.TABLE_NAME
|
|
1584
2084
|
WHERE {table_filter_query} {table_type_query}
|
|
1585
|
-
|
|
2085
|
+
tc.table_schema = @table_schema AND tc.CONSTRAINT_TYPE = "PRIMARY KEY"
|
|
1586
2086
|
ORDER BY tc.table_catalog ASC, tc.table_schema ASC,
|
|
1587
2087
|
tc.table_name ASC, kcu.ordinal_position ASC
|
|
1588
2088
|
""".format(
|
|
1589
2089
|
table_filter_query=table_filter_query,
|
|
1590
2090
|
table_type_query=table_type_query,
|
|
1591
|
-
schema_filter_query=schema_filter_query,
|
|
1592
2091
|
)
|
|
1593
2092
|
|
|
1594
2093
|
with connection.connection.database.snapshot() as snap:
|
|
1595
|
-
rows = list(
|
|
2094
|
+
rows = list(
|
|
2095
|
+
snap.execute_sql(sql, params=params, param_types=query_param_types)
|
|
2096
|
+
)
|
|
1596
2097
|
result_dict = {}
|
|
1597
2098
|
|
|
1598
2099
|
for row in rows:
|
|
@@ -1677,11 +2178,12 @@ class SpannerDialect(DefaultDialect):
|
|
|
1677
2178
|
a foreign key definition.
|
|
1678
2179
|
The schema is ``None`` if no schema is provided.
|
|
1679
2180
|
"""
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
schema=schema or ""
|
|
2181
|
+
filters = self._prepare_multi_reflection_filters(
|
|
2182
|
+
schema, filter_names, "tc", kind
|
|
1683
2183
|
)
|
|
1684
|
-
|
|
2184
|
+
if filters is None:
|
|
2185
|
+
return {}
|
|
2186
|
+
table_filter_query, table_type_query, params, query_param_types = filters
|
|
1685
2187
|
|
|
1686
2188
|
sql = """
|
|
1687
2189
|
SELECT
|
|
@@ -1725,16 +2227,17 @@ class SpannerDialect(DefaultDialect):
|
|
|
1725
2227
|
WHERE
|
|
1726
2228
|
{table_filter_query}
|
|
1727
2229
|
{table_type_query}
|
|
1728
|
-
|
|
2230
|
+
tc.table_schema = @table_schema AND
|
|
1729
2231
|
tc.constraint_type = "FOREIGN KEY"
|
|
1730
2232
|
""".format(
|
|
1731
2233
|
table_filter_query=table_filter_query,
|
|
1732
2234
|
table_type_query=table_type_query,
|
|
1733
|
-
schema_filter_query=schema_filter_query,
|
|
1734
2235
|
)
|
|
1735
2236
|
|
|
1736
2237
|
with connection.connection.database.snapshot() as snap:
|
|
1737
|
-
rows = list(
|
|
2238
|
+
rows = list(
|
|
2239
|
+
snap.execute_sql(sql, params=params, param_types=query_param_types)
|
|
2240
|
+
)
|
|
1738
2241
|
result_dict = {}
|
|
1739
2242
|
|
|
1740
2243
|
for row in rows:
|
|
@@ -1794,17 +2297,9 @@ class SpannerDialect(DefaultDialect):
|
|
|
1794
2297
|
sql = """
|
|
1795
2298
|
SELECT table_name
|
|
1796
2299
|
FROM information_schema.tables
|
|
1797
|
-
WHERE table_type = 'BASE TABLE' AND table_schema =
|
|
1798
|
-
"""
|
|
1799
|
-
|
|
1800
|
-
table_names = []
|
|
1801
|
-
with connection.connection.database.snapshot() as snap:
|
|
1802
|
-
rows = snap.execute_sql(sql)
|
|
1803
|
-
|
|
1804
|
-
for row in rows:
|
|
1805
|
-
table_names.append(row[0])
|
|
1806
|
-
|
|
1807
|
-
return table_names
|
|
2300
|
+
WHERE table_type = 'BASE TABLE' AND table_schema = @table_schema
|
|
2301
|
+
"""
|
|
2302
|
+
return self._query_schema_object_names(connection, sql, schema)
|
|
1808
2303
|
|
|
1809
2304
|
@engine_to_connection
|
|
1810
2305
|
def get_unique_constraints(self, connection, table_name, schema=None, **kw):
|
|
@@ -1827,15 +2322,25 @@ FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc
|
|
|
1827
2322
|
JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS ccu
|
|
1828
2323
|
USING (TABLE_CATALOG, TABLE_SCHEMA, CONSTRAINT_NAME)
|
|
1829
2324
|
WHERE
|
|
1830
|
-
tc.TABLE_NAME=
|
|
1831
|
-
AND tc.TABLE_SCHEMA=
|
|
2325
|
+
tc.TABLE_NAME = @table_name
|
|
2326
|
+
AND tc.TABLE_SCHEMA = @table_schema
|
|
1832
2327
|
AND tc.CONSTRAINT_TYPE = "UNIQUE"
|
|
1833
2328
|
AND tc.CONSTRAINT_NAME IS NOT NULL
|
|
1834
|
-
"""
|
|
2329
|
+
"""
|
|
2330
|
+
params = {
|
|
2331
|
+
"table_schema": self._normalize_schema_param(schema),
|
|
2332
|
+
"table_name": self._normalize_name_param(table_name),
|
|
2333
|
+
}
|
|
2334
|
+
query_param_types = {
|
|
2335
|
+
"table_schema": param_types.STRING,
|
|
2336
|
+
"table_name": param_types.STRING,
|
|
2337
|
+
}
|
|
1835
2338
|
|
|
1836
2339
|
cols = []
|
|
1837
|
-
with connection.connection.database.snapshot() as
|
|
1838
|
-
rows =
|
|
2340
|
+
with connection.connection.database.snapshot() as snapshot:
|
|
2341
|
+
rows = list(
|
|
2342
|
+
snapshot.execute_sql(sql, params=params, param_types=query_param_types)
|
|
2343
|
+
)
|
|
1839
2344
|
|
|
1840
2345
|
for row in rows:
|
|
1841
2346
|
cols.append({"name": row[0], "column_names": [row[1]]})
|
|
@@ -1857,20 +2362,15 @@ WHERE
|
|
|
1857
2362
|
Returns:
|
|
1858
2363
|
bool: True, if the given table exists, False otherwise.
|
|
1859
2364
|
"""
|
|
1860
|
-
|
|
1861
|
-
rows = snap.execute_sql(
|
|
1862
|
-
"""
|
|
2365
|
+
sql = """
|
|
1863
2366
|
SELECT true
|
|
1864
2367
|
FROM INFORMATION_SCHEMA.TABLES
|
|
1865
|
-
WHERE TABLE_SCHEMA=
|
|
2368
|
+
WHERE TABLE_SCHEMA = @table_schema AND TABLE_NAME = @table_name
|
|
1866
2369
|
LIMIT 1
|
|
1867
|
-
"""
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
return True
|
|
1872
|
-
|
|
1873
|
-
return False
|
|
2370
|
+
"""
|
|
2371
|
+
return self._record_exists_for_schema(
|
|
2372
|
+
connection, sql, schema, "table_name", table_name
|
|
2373
|
+
)
|
|
1874
2374
|
|
|
1875
2375
|
@engine_to_connection
|
|
1876
2376
|
def has_sequence(self, connection, sequence_name, schema=None, **kw):
|
|
@@ -1880,22 +2380,16 @@ LIMIT 1
|
|
|
1880
2380
|
`sequence_name`, return True if the given sequence exists in
|
|
1881
2381
|
the database, False otherwise.
|
|
1882
2382
|
"""
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
)
|
|
1894
|
-
|
|
1895
|
-
for _ in rows:
|
|
1896
|
-
return True
|
|
1897
|
-
|
|
1898
|
-
return False
|
|
2383
|
+
sql = """
|
|
2384
|
+
SELECT true
|
|
2385
|
+
FROM INFORMATION_SCHEMA.SEQUENCES
|
|
2386
|
+
WHERE NAME = @sequence_name
|
|
2387
|
+
AND SCHEMA = @table_schema
|
|
2388
|
+
LIMIT 1
|
|
2389
|
+
"""
|
|
2390
|
+
return self._record_exists_for_schema(
|
|
2391
|
+
connection, sql, schema, "sequence_name", sequence_name
|
|
2392
|
+
)
|
|
1899
2393
|
|
|
1900
2394
|
def set_isolation_level(self, conn_proxy, level):
|
|
1901
2395
|
"""Set the connection isolation level.
|
{sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/sqlalchemy_spanner.egg-info/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: sqlalchemy-spanner
|
|
3
|
-
Version: 1.21.
|
|
3
|
+
Version: 1.21.1
|
|
4
4
|
Summary: SQLAlchemy dialect integrated into Cloud Spanner database
|
|
5
5
|
Home-page: https://github.com/googleapis/google-cloud-python/tree/main/packages/sqlalchemy-spanner
|
|
6
6
|
Author: Google LLC
|
|
File without changes
|
|
File without changes
|
{sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/google/cloud/sqlalchemy_spanner/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
{sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/google/cloud/sqlalchemy_spanner/dml.py
RENAMED
|
File without changes
|
{sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/google/cloud/sqlalchemy_spanner/provision.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/sqlalchemy_spanner.egg-info/SOURCES.txt
RENAMED
|
File without changes
|
|
File without changes
|
{sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/sqlalchemy_spanner.egg-info/entry_points.txt
RENAMED
|
File without changes
|
{sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/sqlalchemy_spanner.egg-info/not-zip-safe
RENAMED
|
File without changes
|
{sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/sqlalchemy_spanner.egg-info/requires.txt
RENAMED
|
File without changes
|
{sqlalchemy_spanner-1.21.0 → sqlalchemy_spanner-1.21.1}/sqlalchemy_spanner.egg-info/top_level.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|