datadouble-mssql 0.0.3__py3-none-any.whl
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.
- datadouble_mssql/__init__.py +230 -0
- datadouble_mssql/errors.py +78 -0
- datadouble_mssql/introspect.py +267 -0
- datadouble_mssql/objects.py +257 -0
- datadouble_mssql/py.typed +0 -0
- datadouble_mssql/render.py +256 -0
- datadouble_mssql/script.py +514 -0
- datadouble_mssql/server.py +286 -0
- datadouble_mssql/source.py +294 -0
- datadouble_mssql/working.py +854 -0
- datadouble_mssql-0.0.3.dist-info/METADATA +77 -0
- datadouble_mssql-0.0.3.dist-info/RECORD +15 -0
- datadouble_mssql-0.0.3.dist-info/WHEEL +4 -0
- datadouble_mssql-0.0.3.dist-info/entry_points.txt +2 -0
- datadouble_mssql-0.0.3.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""The SQL Server engine adapter for Datadouble.
|
|
5
|
+
|
|
6
|
+
Spec settings::
|
|
7
|
+
|
|
8
|
+
sources:
|
|
9
|
+
app:
|
|
10
|
+
engine: mssql
|
|
11
|
+
connection:
|
|
12
|
+
url: {env: SHOP_MSSQL_URL} # mssql://user:password@host:1433/database, by reference
|
|
13
|
+
server:
|
|
14
|
+
accept_eula: true # required: you accept the SQL Server licence
|
|
15
|
+
edition: Developer # the default; any value MSSQL_PID takes
|
|
16
|
+
|
|
17
|
+
The catalog is the URL's database, which must allow snapshot isolation.
|
|
18
|
+
Extract runs no programs in containers. Working databases and restores run in
|
|
19
|
+
Microsoft's SQL Server image of the source's release and cumulative update
|
|
20
|
+
(``mcr.microsoft.com/mssql/server:2022-CU28-ubuntu-22.04``), or in
|
|
21
|
+
``sources.<name>.image``, through the spec's container runtime, as uid and gid 10001,
|
|
22
|
+
which Datadouble must run as too. They run SQL Server under its licence terms,
|
|
23
|
+
which the operator accepts with ``sources.<name>.server.accept_eula``; Developer
|
|
24
|
+
edition is licensed for development and testing, not production.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
import shlex
|
|
28
|
+
from collections.abc import Generator, Mapping
|
|
29
|
+
from contextlib import contextmanager
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
from typing import Literal
|
|
32
|
+
from urllib.parse import unquote, urlsplit
|
|
33
|
+
|
|
34
|
+
import pymssql
|
|
35
|
+
from pydantic import BaseModel, ConfigDict, JsonValue
|
|
36
|
+
|
|
37
|
+
from datadouble.engine import EngineError, ServerPlan, SourceSession, Tooling, WorkingDatabases
|
|
38
|
+
from datadouble.names import EngineName
|
|
39
|
+
from datadouble.planner import Capabilities
|
|
40
|
+
from datadouble.secrets import resolve_secret
|
|
41
|
+
from datadouble.settings import parse_settings
|
|
42
|
+
from datadouble.spec import ImageFormat, SecretRef
|
|
43
|
+
from datadouble_mssql.errors import database_error
|
|
44
|
+
from datadouble_mssql.introspect import ENGINE
|
|
45
|
+
from datadouble_mssql.render import compose, quote
|
|
46
|
+
from datadouble_mssql.server import (
|
|
47
|
+
DATA,
|
|
48
|
+
Tools,
|
|
49
|
+
configure,
|
|
50
|
+
default_image,
|
|
51
|
+
literal,
|
|
52
|
+
)
|
|
53
|
+
from datadouble_mssql.source import MssqlSession
|
|
54
|
+
from datadouble_mssql.working import DatabaseInfo, MssqlWorking
|
|
55
|
+
|
|
56
|
+
MOUNT = "/var/lib/datadouble"
|
|
57
|
+
"""Where container servers mount a copy."""
|
|
58
|
+
|
|
59
|
+
# A new instance beside the copy's files, with a random sa password; the
|
|
60
|
+
# database is attached and the login datadouble made with the copy's password,
|
|
61
|
+
# which reaches the server through a builtin and a pipe, never a command line.
|
|
62
|
+
_SERVE = """
|
|
63
|
+
set -eu
|
|
64
|
+
instance=@INSTANCE@
|
|
65
|
+
rm -rf "$instance" && mkdir -p "$instance"
|
|
66
|
+
export ACCEPT_EULA=Y MSSQL_PID=@EDITION@ MSSQL_DATA_DIR=@DATA@ MSSQL_LOG_DIR=@DATA@
|
|
67
|
+
export MSSQL_MASTER_DATA_FILE="$instance/master.mdf" MSSQL_MASTER_LOG_FILE="$instance/mastlog.ldf"
|
|
68
|
+
export MSSQL_DUMP_DIR="$instance"
|
|
69
|
+
MSSQL_SA_PASSWORD="Dd-$(od -An -N16 -tx1 /dev/urandom | tr -d ' \\n')"
|
|
70
|
+
export MSSQL_SA_PASSWORD SQLCMDPASSWORD="$MSSQL_SA_PASSWORD"
|
|
71
|
+
sqlcmd() {
|
|
72
|
+
if [ -x /opt/mssql-tools18/bin/sqlcmd ]; then /opt/mssql-tools18/bin/sqlcmd -C "$@"
|
|
73
|
+
else /opt/mssql-tools/bin/sqlcmd "$@"; fi
|
|
74
|
+
}
|
|
75
|
+
/opt/mssql/bin/sqlservr & server=$!
|
|
76
|
+
trap 'kill -TERM "$server"; wait "$server"' TERM INT
|
|
77
|
+
until grep -q 'Recovery is complete' /var/opt/mssql/log/errorlog 2> /dev/null \\
|
|
78
|
+
&& sqlcmd -S localhost -U sa -b -Q "SELECT 1" > /dev/null 2>&1; do sleep 1; done
|
|
79
|
+
password=$(printf %s "$DATADOUBLE_PASSWORD" | sed "s/'/''/g")
|
|
80
|
+
printf '%s\\n' "@ATTACH@" | sqlcmd -S localhost -U sa -b -I > /dev/null
|
|
81
|
+
touch "$instance/ready"
|
|
82
|
+
wait "$server"
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class MssqlConnection(BaseModel):
|
|
87
|
+
"""The ``sources.<name>.connection`` settings."""
|
|
88
|
+
|
|
89
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
90
|
+
|
|
91
|
+
url: SecretRef
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class MssqlServerSettings(BaseModel):
|
|
95
|
+
"""The ``sources.<name>.server`` settings."""
|
|
96
|
+
|
|
97
|
+
model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
|
|
98
|
+
|
|
99
|
+
accept_eula: Literal[True] | None = None
|
|
100
|
+
"""Set by the operator to accept the SQL Server licence; required."""
|
|
101
|
+
edition: str = "Developer"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def double_quoted(text: str) -> str:
|
|
105
|
+
"""``text`` escaped for a double-quoted shell string, so nothing in it expands."""
|
|
106
|
+
for special in ("\\", '"', "$", "`"):
|
|
107
|
+
text = text.replace(special, "\\" + special)
|
|
108
|
+
return text
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def parse_url(url: str) -> tuple[dict[str, str], str]:
|
|
112
|
+
"""Connection settings (server, port, user, password) and the database, from a URL."""
|
|
113
|
+
parts = urlsplit(url)
|
|
114
|
+
database = unquote(parts.path.lstrip("/"))
|
|
115
|
+
if parts.scheme != "mssql" or not parts.hostname or not database:
|
|
116
|
+
message = "the mssql url must look like mssql://user:password@host:1433/database"
|
|
117
|
+
raise EngineError(message)
|
|
118
|
+
return (
|
|
119
|
+
{
|
|
120
|
+
"server": parts.hostname,
|
|
121
|
+
"port": str(parts.port or 1433),
|
|
122
|
+
"user": unquote(parts.username or ""),
|
|
123
|
+
"password": unquote(parts.password or ""),
|
|
124
|
+
},
|
|
125
|
+
database,
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def server_settings(server: Mapping[str, JsonValue]) -> MssqlServerSettings:
|
|
130
|
+
"""The ``sources.<name>.server`` settings, which must accept the licence."""
|
|
131
|
+
settings = parse_settings(MssqlServerSettings, server, "mssql server")
|
|
132
|
+
if settings.accept_eula is None:
|
|
133
|
+
message = (
|
|
134
|
+
"SQL Server working databases run Microsoft's SQL Server image, whose licence the"
|
|
135
|
+
" operator must accept: set sources.<name>.server.accept_eula to true"
|
|
136
|
+
" (Developer edition, the default, is licensed for development and testing)"
|
|
137
|
+
)
|
|
138
|
+
raise EngineError(message)
|
|
139
|
+
return settings
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class MssqlEngine:
|
|
143
|
+
"""Implements :class:`datadouble.engine.EngineAdapter` for SQL Server."""
|
|
144
|
+
|
|
145
|
+
@property
|
|
146
|
+
def name(self) -> EngineName:
|
|
147
|
+
"""``mssql``."""
|
|
148
|
+
return ENGINE
|
|
149
|
+
|
|
150
|
+
@property
|
|
151
|
+
def owner(self) -> str:
|
|
152
|
+
"""``10001:10001``: SQL Server in Microsoft's image runs as no other user."""
|
|
153
|
+
return "10001:10001"
|
|
154
|
+
|
|
155
|
+
def capabilities(self) -> Capabilities:
|
|
156
|
+
"""Both image formats, SQL expressions, the nested strategy and hooks."""
|
|
157
|
+
return Capabilities(
|
|
158
|
+
formats=(ImageFormat.PHYSICAL, ImageFormat.LOGICAL),
|
|
159
|
+
expressions=True,
|
|
160
|
+
nested=True,
|
|
161
|
+
standalone=True,
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
@contextmanager
|
|
165
|
+
def connect(self, connection: Mapping[str, JsonValue]) -> Generator[SourceSession]:
|
|
166
|
+
"""Connect to the source."""
|
|
167
|
+
settings = parse_settings(MssqlConnection, connection, "mssql connection")
|
|
168
|
+
options, database = parse_url(resolve_secret(settings.url))
|
|
169
|
+
try:
|
|
170
|
+
opened = configure(
|
|
171
|
+
pymssql.connect(
|
|
172
|
+
server=options["server"],
|
|
173
|
+
port=options["port"],
|
|
174
|
+
user=options["user"],
|
|
175
|
+
password=options["password"],
|
|
176
|
+
database=database,
|
|
177
|
+
autocommit=True,
|
|
178
|
+
)
|
|
179
|
+
)
|
|
180
|
+
except pymssql.Error as error:
|
|
181
|
+
raise database_error(error, "connecting to the source") from None
|
|
182
|
+
try:
|
|
183
|
+
yield MssqlSession(opened, options, database)
|
|
184
|
+
finally:
|
|
185
|
+
opened.close()
|
|
186
|
+
|
|
187
|
+
def working(self, scratch: Path, tooling: Tooling, source_version: str) -> WorkingDatabases:
|
|
188
|
+
"""Instances under ``scratch``, in the image for the source's version."""
|
|
189
|
+
settings = server_settings(tooling.server)
|
|
190
|
+
image = tooling.image or default_image(source_version)
|
|
191
|
+
return MssqlWorking(Tools(tooling.runtime, image, settings.edition), scratch)
|
|
192
|
+
|
|
193
|
+
def server(self, image: Path, server_image: str | None) -> ServerPlan:
|
|
194
|
+
"""Microsoft's image of the image's version, attaching the copy's files.
|
|
195
|
+
|
|
196
|
+
At start a new instance is made in a directory beside the files, with a
|
|
197
|
+
random ``sa`` password; the database is attached, and the login
|
|
198
|
+
``datadouble`` is created with the copy's password.
|
|
199
|
+
"""
|
|
200
|
+
info = DatabaseInfo.model_validate_json((image / "database.json").read_bytes())
|
|
201
|
+
data = f"{MOUNT}/{DATA}"
|
|
202
|
+
attach = compose(
|
|
203
|
+
"CREATE DATABASE {} ON (FILENAME = {}), (FILENAME = {}) FOR ATTACH;"
|
|
204
|
+
" CREATE LOGIN [datadouble] WITH PASSWORD = N'@PASSWORD@', CHECK_POLICY = OFF;"
|
|
205
|
+
" ALTER SERVER ROLE sysadmin ADD MEMBER [datadouble];",
|
|
206
|
+
quote(info.database),
|
|
207
|
+
literal(f"{data}/database.mdf"),
|
|
208
|
+
literal(f"{data}/database_log.ldf"),
|
|
209
|
+
)
|
|
210
|
+
start = (
|
|
211
|
+
_SERVE.replace("@INSTANCE@", f"{MOUNT}/instance")
|
|
212
|
+
.replace("@DATA@", data)
|
|
213
|
+
.replace("@EDITION@", shlex.quote(info.edition))
|
|
214
|
+
.replace("@ATTACH@", double_quoted(attach).replace("@PASSWORD@", "$password"))
|
|
215
|
+
)
|
|
216
|
+
return ServerPlan(
|
|
217
|
+
image=server_image or default_image(info.server_version),
|
|
218
|
+
mount=MOUNT,
|
|
219
|
+
owner=self.owner,
|
|
220
|
+
command=("bash", "-c", start),
|
|
221
|
+
ready=("test", "-f", f"{MOUNT}/instance/ready"),
|
|
222
|
+
port=1433,
|
|
223
|
+
database=info.database,
|
|
224
|
+
user="datadouble",
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def engine() -> MssqlEngine:
|
|
229
|
+
"""The entry point named in ``datadouble.engines``."""
|
|
230
|
+
return MssqlEngine()
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""Error messages that are safe to show and log.
|
|
5
|
+
|
|
6
|
+
SQL Server messages can quote the data that caused them (``The duplicate key
|
|
7
|
+
value is (x)``, ``converting the varchar value 'x'``). Messages leaving this
|
|
8
|
+
adapter keep the error number and the message with data values hidden;
|
|
9
|
+
quoted object names and identifiers in brackets are kept (decisions 54 and
|
|
10
|
+
139). The driver's own trailer is dropped.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import pymssql
|
|
14
|
+
|
|
15
|
+
from datadouble.engine import EngineError
|
|
16
|
+
from datadouble.redaction import Redactor, kinds
|
|
17
|
+
from datadouble.runtime import runtime_failure
|
|
18
|
+
|
|
19
|
+
_TRAILER = "DB-Lib error message"
|
|
20
|
+
|
|
21
|
+
# The shapes in which SQL Server reports data values; the ``value`` group is
|
|
22
|
+
# hidden. Message texts are from sys.messages, named by number; a new one is
|
|
23
|
+
# one more line. Any other quoted string that no kind word names is hidden
|
|
24
|
+
# anyway. Truncation without a value (8152), NULL into a column (515) and
|
|
25
|
+
# conflicts with a constraint (547) name only objects.
|
|
26
|
+
_VALUES = (
|
|
27
|
+
r"duplicate key value is \((?P<value>.*)\)", # 2627, 2601
|
|
28
|
+
r"when converting the [\w ]+? value '(?P<value>.*)' to data type", # 245
|
|
29
|
+
r"conversion of the [\w ]+? value '(?P<value>.*)' overflowed", # 248
|
|
30
|
+
r"Truncated value: '(?P<value>.*)'", # 2628
|
|
31
|
+
r"character string '(?P<value>.*)'", # 105, 102: the statement, literals and all
|
|
32
|
+
)
|
|
33
|
+
# Words after which a quoted string names an object: ``column 'email'``,
|
|
34
|
+
# ``Invalid object name 'dbo.orders'``.
|
|
35
|
+
_NAMES = (
|
|
36
|
+
r"\b(?:object|column)\s+name\s+",
|
|
37
|
+
kinds(
|
|
38
|
+
"table column constraint index object database schema login user role"
|
|
39
|
+
" procedure function trigger view type statistics file partition"
|
|
40
|
+
),
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
# A message a user raised (RAISERROR or THROW, numbers from 50000) can quote
|
|
44
|
+
# any value, so every quoted string in it is hidden.
|
|
45
|
+
_USER_ERRORS = 50000
|
|
46
|
+
_RAISED = (r"\bMsg (?:[5-9]\d{4}|\d{6,})\b",)
|
|
47
|
+
|
|
48
|
+
redact = Redactor(values=_VALUES, names=_NAMES, marks="'\"", raised=_RAISED)
|
|
49
|
+
"""Hide the data values in a SQL Server message, keeping the objects it names."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def database_error(error: pymssql.Error, action: str) -> EngineError:
|
|
53
|
+
"""An :class:`EngineError` for a failed database operation."""
|
|
54
|
+
arguments: tuple[object, ...] = error.args
|
|
55
|
+
if len(arguments) > 1 and isinstance(arguments[0], int):
|
|
56
|
+
raw = arguments[1]
|
|
57
|
+
detail = raw.decode("utf-8", "replace") if isinstance(raw, bytes) else str(raw)
|
|
58
|
+
detail = detail.split(_TRAILER, 1)[0].strip()
|
|
59
|
+
raised = arguments[0] >= _USER_ERRORS
|
|
60
|
+
return EngineError(f"{action} failed: [{arguments[0]}] {redact(detail, raised=raised)}")
|
|
61
|
+
return EngineError(f"{action} failed: {type(error).__name__}")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def tool_error(tool: str, status: int, output: str) -> EngineError:
|
|
65
|
+
"""An :class:`EngineError` for a failed SQL Server program in a container.
|
|
66
|
+
|
|
67
|
+
Its output is redacted, unless the status says the container runtime
|
|
68
|
+
failed before the program ran (:func:`~datadouble.runtime.runtime_failure`).
|
|
69
|
+
"""
|
|
70
|
+
keep = runtime_failure(status)
|
|
71
|
+
raised = redact.raises(output)
|
|
72
|
+
lines = [
|
|
73
|
+
line.strip() if keep else redact(line.strip(), raised=raised)
|
|
74
|
+
for line in output.splitlines()
|
|
75
|
+
if line.strip()
|
|
76
|
+
]
|
|
77
|
+
summary = "; ".join(lines[-3:]) or "no output"
|
|
78
|
+
return EngineError(f"{tool} exited with status {status}: {summary}")
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
# Copyright (c) 2026- Tight Line LLC
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""Reading a SQL Server catalog into Datadouble's engine-neutral model.
|
|
5
|
+
|
|
6
|
+
The catalog is one database: the base tables of every user schema, their
|
|
7
|
+
columns, primary keys and foreign keys. Table names are ``schema.table``.
|
|
8
|
+
Beyond the neutral model, the adapter keeps each column's system type (for
|
|
9
|
+
reading it as text and loading it back), the columns loading cannot write
|
|
10
|
+
(computed columns and ``rowversion``), and what it does not support, which it
|
|
11
|
+
refuses to extract rather than copy wrongly. Objects besides tables are read
|
|
12
|
+
by :mod:`datadouble_mssql.objects`.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from collections import defaultdict
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
|
|
18
|
+
from pymssql import Connection
|
|
19
|
+
|
|
20
|
+
from datadouble.catalog import Catalog, Column, ColumnKind, ForeignKey, Table
|
|
21
|
+
from datadouble.names import ColumnName, EngineName, TableName
|
|
22
|
+
from datadouble_mssql.objects import read_objects
|
|
23
|
+
|
|
24
|
+
ENGINE = EngineName("mssql")
|
|
25
|
+
|
|
26
|
+
_TABLES = """
|
|
27
|
+
SELECT s.name, t.name, t.is_memory_optimized, t.temporal_type, t.is_external, t.is_filetable,
|
|
28
|
+
t.is_node | t.is_edge,
|
|
29
|
+
CASE WHEN EXISTS (
|
|
30
|
+
SELECT 1 FROM sys.indexes i JOIN sys.data_spaces d ON d.data_space_id = i.data_space_id
|
|
31
|
+
WHERE i.object_id = t.object_id AND d.type = 'PS') THEN 1 ELSE 0 END,
|
|
32
|
+
CASE WHEN EXISTS (
|
|
33
|
+
SELECT 1 FROM sys.columns c WHERE c.object_id = t.object_id AND c.is_filestream = 1)
|
|
34
|
+
THEN 1 ELSE 0 END,
|
|
35
|
+
CASE WHEN EXISTS (
|
|
36
|
+
SELECT 1 FROM sys.indexes i WHERE i.object_id = t.object_id AND i.type NOT IN (0, 1, 2))
|
|
37
|
+
OR EXISTS (SELECT 1 FROM sys.fulltext_indexes f WHERE f.object_id = t.object_id)
|
|
38
|
+
THEN 1 ELSE 0 END
|
|
39
|
+
FROM sys.tables t JOIN sys.schemas s ON s.schema_id = t.schema_id
|
|
40
|
+
WHERE t.is_ms_shipped = 0
|
|
41
|
+
ORDER BY s.name, t.name
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
_COLUMNS = """
|
|
45
|
+
SELECT s.name, t.name, c.name,
|
|
46
|
+
CASE WHEN ty.is_assembly_type = 1 OR ty.system_type_id = ty.user_type_id THEN ty.name
|
|
47
|
+
ELSE TYPE_NAME(ty.system_type_id) END,
|
|
48
|
+
ty.name, CAST(ty.is_user_defined AS INT),
|
|
49
|
+
c.max_length, c.precision, c.scale, CAST(c.is_nullable AS INT), CAST(c.is_computed AS INT)
|
|
50
|
+
FROM sys.columns c
|
|
51
|
+
JOIN sys.tables t ON t.object_id = c.object_id
|
|
52
|
+
JOIN sys.schemas s ON s.schema_id = t.schema_id
|
|
53
|
+
JOIN sys.types ty ON ty.user_type_id = c.user_type_id
|
|
54
|
+
WHERE t.is_ms_shipped = 0
|
|
55
|
+
ORDER BY s.name, t.name, c.column_id
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
_PRIMARY_KEYS = """
|
|
59
|
+
SELECT s.name, t.name, c.name
|
|
60
|
+
FROM sys.key_constraints k
|
|
61
|
+
JOIN sys.tables t ON t.object_id = k.parent_object_id
|
|
62
|
+
JOIN sys.schemas s ON s.schema_id = t.schema_id
|
|
63
|
+
JOIN sys.index_columns ic ON ic.object_id = k.parent_object_id AND ic.index_id = k.unique_index_id
|
|
64
|
+
JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
|
|
65
|
+
WHERE k.type = 'PK' AND t.is_ms_shipped = 0
|
|
66
|
+
ORDER BY s.name, t.name, ic.key_ordinal
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
_FOREIGN_KEYS = """
|
|
70
|
+
SELECT s.name, t.name, f.name, c.name, rs.name, rt.name, rc.name
|
|
71
|
+
FROM sys.foreign_keys f
|
|
72
|
+
JOIN sys.foreign_key_columns fc ON fc.constraint_object_id = f.object_id
|
|
73
|
+
JOIN sys.tables t ON t.object_id = f.parent_object_id
|
|
74
|
+
JOIN sys.schemas s ON s.schema_id = t.schema_id
|
|
75
|
+
JOIN sys.columns c ON c.object_id = fc.parent_object_id AND c.column_id = fc.parent_column_id
|
|
76
|
+
JOIN sys.tables rt ON rt.object_id = f.referenced_object_id
|
|
77
|
+
JOIN sys.schemas rs ON rs.schema_id = rt.schema_id
|
|
78
|
+
JOIN sys.columns rc
|
|
79
|
+
ON rc.object_id = fc.referenced_object_id AND rc.column_id = fc.referenced_column_id
|
|
80
|
+
WHERE t.is_ms_shipped = 0
|
|
81
|
+
ORDER BY s.name, t.name, f.name, fc.constraint_column_id
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
_KINDS = {
|
|
85
|
+
"tinyint": ColumnKind.INTEGER,
|
|
86
|
+
"smallint": ColumnKind.INTEGER,
|
|
87
|
+
"int": ColumnKind.INTEGER,
|
|
88
|
+
"bigint": ColumnKind.INTEGER,
|
|
89
|
+
"bit": ColumnKind.BOOLEAN,
|
|
90
|
+
"decimal": ColumnKind.DECIMAL,
|
|
91
|
+
"numeric": ColumnKind.DECIMAL,
|
|
92
|
+
"money": ColumnKind.DECIMAL,
|
|
93
|
+
"smallmoney": ColumnKind.DECIMAL,
|
|
94
|
+
"float": ColumnKind.FLOAT,
|
|
95
|
+
"real": ColumnKind.FLOAT,
|
|
96
|
+
"date": ColumnKind.DATE,
|
|
97
|
+
"datetime": ColumnKind.TIMESTAMP,
|
|
98
|
+
"datetime2": ColumnKind.TIMESTAMP,
|
|
99
|
+
"smalldatetime": ColumnKind.TIMESTAMP,
|
|
100
|
+
"datetimeoffset": ColumnKind.TIMESTAMP,
|
|
101
|
+
"time": ColumnKind.TIME,
|
|
102
|
+
"char": ColumnKind.TEXT,
|
|
103
|
+
"varchar": ColumnKind.TEXT,
|
|
104
|
+
"nchar": ColumnKind.TEXT,
|
|
105
|
+
"nvarchar": ColumnKind.TEXT,
|
|
106
|
+
"text": ColumnKind.TEXT,
|
|
107
|
+
"ntext": ColumnKind.TEXT,
|
|
108
|
+
"binary": ColumnKind.BINARY,
|
|
109
|
+
"varbinary": ColumnKind.BINARY,
|
|
110
|
+
"image": ColumnKind.BINARY,
|
|
111
|
+
"uniqueidentifier": ColumnKind.UUID,
|
|
112
|
+
"json": ColumnKind.JSON,
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
SUPPORTED_TYPES = frozenset({*_KINDS, "xml", "geometry", "geography", "hierarchyid", "timestamp"})
|
|
116
|
+
"""System types the adapter can read as text and load back exactly."""
|
|
117
|
+
|
|
118
|
+
_LENGTHS = frozenset({"char", "varchar", "binary", "varbinary"})
|
|
119
|
+
_WIDE = frozenset({"nchar", "nvarchar"})
|
|
120
|
+
_PRECISION = frozenset({"decimal", "numeric"})
|
|
121
|
+
_SCALE = frozenset({"datetime2", "time", "datetimeoffset"})
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def kind_of(system_type: str) -> ColumnKind:
|
|
125
|
+
"""The engine-neutral kind of a SQL Server system type.
|
|
126
|
+
|
|
127
|
+
``xml``, ``sql_variant``, the spatial types, ``hierarchyid`` and
|
|
128
|
+
``rowversion`` are ``other``, since a generated value would not fit them.
|
|
129
|
+
"""
|
|
130
|
+
return _KINDS.get(system_type.lower(), ColumnKind.OTHER)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def type_text(system_type: str, max_length: int, precision: int, scale: int) -> str:
|
|
134
|
+
"""The type as T-SQL writes it, such as ``nvarchar(50)`` or ``decimal(5,2)``."""
|
|
135
|
+
if system_type in _LENGTHS | _WIDE:
|
|
136
|
+
if max_length == -1:
|
|
137
|
+
return f"{system_type}(max)"
|
|
138
|
+
return f"{system_type}({max_length // 2 if system_type in _WIDE else max_length})"
|
|
139
|
+
if system_type in _PRECISION:
|
|
140
|
+
return f"{system_type}({precision},{scale})"
|
|
141
|
+
if system_type in _SCALE:
|
|
142
|
+
return f"{system_type}({scale})"
|
|
143
|
+
return "rowversion" if system_type == "timestamp" else system_type
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@dataclass(frozen=True, slots=True)
|
|
147
|
+
class Physical:
|
|
148
|
+
"""What the adapter needs beyond the engine-neutral catalog."""
|
|
149
|
+
|
|
150
|
+
types: dict[TableName, dict[ColumnName, str]] = field(
|
|
151
|
+
default_factory=dict[TableName, dict[ColumnName, str]]
|
|
152
|
+
)
|
|
153
|
+
"""Each column's system type, such as ``nvarchar``."""
|
|
154
|
+
unloadable: dict[TableName, frozenset[ColumnName]] = field(
|
|
155
|
+
default_factory=dict[TableName, frozenset[ColumnName]]
|
|
156
|
+
)
|
|
157
|
+
"""Computed and ``rowversion`` columns, which the server fills in itself."""
|
|
158
|
+
unsupported: dict[TableName, str] = field(default_factory=dict[TableName, str])
|
|
159
|
+
"""Tables this adapter cannot copy, and why."""
|
|
160
|
+
|
|
161
|
+
def loaded(self, table: TableName) -> tuple[ColumnName, ...]:
|
|
162
|
+
"""The columns extract writes and load reads, in table order."""
|
|
163
|
+
skipped = self.unloadable.get(table, frozenset())
|
|
164
|
+
return tuple(c for c in self.types.get(table, {}) if c not in skipped)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def table_problem(flags: tuple[object, ...]) -> str | None:
|
|
168
|
+
"""Why a table with these flags (from ``_TABLES``) cannot be copied, if it cannot."""
|
|
169
|
+
names = (
|
|
170
|
+
"is a memory-optimized table",
|
|
171
|
+
"is a system-versioned temporal table or its history",
|
|
172
|
+
"is an external table",
|
|
173
|
+
"is a FileTable",
|
|
174
|
+
"is a graph table",
|
|
175
|
+
"is a partitioned table",
|
|
176
|
+
"has a FILESTREAM column",
|
|
177
|
+
"has a columnstore, XML, spatial or full-text index",
|
|
178
|
+
)
|
|
179
|
+
found = [name for name, flag in zip(names, flags, strict=True) if bool(flag)]
|
|
180
|
+
return f"{found[0]}, which the SQL Server adapter does not support yet" if found else None
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def introspect(connection: Connection) -> tuple[Catalog, Physical]:
|
|
184
|
+
"""Read the catalog of the connection's database."""
|
|
185
|
+
with connection.cursor() as cursor:
|
|
186
|
+
cursor.execute(_TABLES)
|
|
187
|
+
names: list[TableName] = []
|
|
188
|
+
unsupported: dict[TableName, str] = {}
|
|
189
|
+
for schema, table, *flags in cursor.fetchall():
|
|
190
|
+
name = TableName.of(str(schema), str(table))
|
|
191
|
+
names.append(name)
|
|
192
|
+
if problem := table_problem(tuple(flags)):
|
|
193
|
+
unsupported[name] = problem
|
|
194
|
+
columns: defaultdict[TableName, list[Column]] = defaultdict(list)
|
|
195
|
+
types: defaultdict[TableName, dict[ColumnName, str]] = defaultdict(dict)
|
|
196
|
+
unloadable: defaultdict[TableName, set[ColumnName]] = defaultdict(set)
|
|
197
|
+
cursor.execute(_COLUMNS)
|
|
198
|
+
for row in cursor.fetchall():
|
|
199
|
+
schema, table, column, system_type, declared = (str(v) for v in row[:5])
|
|
200
|
+
user_defined, max_length, precision, scale, nullable, computed = (
|
|
201
|
+
int(str(v)) for v in row[5:]
|
|
202
|
+
)
|
|
203
|
+
name = TableName.of(schema, table)
|
|
204
|
+
columns[name].append(
|
|
205
|
+
Column(
|
|
206
|
+
name=ColumnName(column),
|
|
207
|
+
type=type_text(system_type, max_length, precision, scale),
|
|
208
|
+
kind=kind_of(system_type),
|
|
209
|
+
nullable=bool(nullable),
|
|
210
|
+
)
|
|
211
|
+
)
|
|
212
|
+
types[name][ColumnName(column)] = system_type
|
|
213
|
+
if computed or system_type == "timestamp":
|
|
214
|
+
unloadable[name].add(ColumnName(column))
|
|
215
|
+
elif user_defined or system_type not in SUPPORTED_TYPES:
|
|
216
|
+
# Alias and CLR types defined in the database, and system
|
|
217
|
+
# types without an exact text form (sql_variant).
|
|
218
|
+
unsupported.setdefault(
|
|
219
|
+
name, f"has column {column} of type {declared}, which is not supported yet"
|
|
220
|
+
)
|
|
221
|
+
primary: defaultdict[TableName, list[ColumnName]] = defaultdict(list)
|
|
222
|
+
cursor.execute(_PRIMARY_KEYS)
|
|
223
|
+
for key_row in cursor.fetchall():
|
|
224
|
+
owner = TableName.of(str(key_row[0]), str(key_row[1]))
|
|
225
|
+
primary[owner].append(ColumnName(str(key_row[2])))
|
|
226
|
+
foreign: dict[tuple[TableName, str], tuple[TableName, list[ColumnName], list[ColumnName]]]
|
|
227
|
+
foreign = {}
|
|
228
|
+
cursor.execute(_FOREIGN_KEYS)
|
|
229
|
+
for key_row in cursor.fetchall():
|
|
230
|
+
text = [str(value) for value in key_row]
|
|
231
|
+
entry = foreign.setdefault(
|
|
232
|
+
(TableName.of(text[0], text[1]), text[2]), (TableName.of(text[4], text[5]), [], [])
|
|
233
|
+
)
|
|
234
|
+
entry[1].append(ColumnName(text[3]))
|
|
235
|
+
entry[2].append(ColumnName(text[6]))
|
|
236
|
+
objects, needs = read_objects(cursor)
|
|
237
|
+
catalog = Catalog(
|
|
238
|
+
engine=ENGINE,
|
|
239
|
+
tables=tuple(
|
|
240
|
+
Table(
|
|
241
|
+
name=name,
|
|
242
|
+
columns=tuple(columns[name]),
|
|
243
|
+
primary_key=tuple(primary.get(name, [])),
|
|
244
|
+
foreign_keys=tuple(
|
|
245
|
+
ForeignKey(
|
|
246
|
+
name=constraint,
|
|
247
|
+
columns=tuple(own),
|
|
248
|
+
target=target,
|
|
249
|
+
target_columns=tuple(theirs),
|
|
250
|
+
)
|
|
251
|
+
for (table, constraint), (target, own, theirs) in sorted(
|
|
252
|
+
foreign.items(), key=lambda item: (str(item[0][0]), item[0][1])
|
|
253
|
+
)
|
|
254
|
+
if table == name
|
|
255
|
+
),
|
|
256
|
+
depends_on=needs.get(name, ()),
|
|
257
|
+
)
|
|
258
|
+
for name in names
|
|
259
|
+
),
|
|
260
|
+
objects=objects,
|
|
261
|
+
)
|
|
262
|
+
physical = Physical(
|
|
263
|
+
types=dict(types),
|
|
264
|
+
unloadable={t: frozenset(c) for t, c in unloadable.items()},
|
|
265
|
+
unsupported=unsupported,
|
|
266
|
+
)
|
|
267
|
+
return catalog, physical
|