datadouble-mysql 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.
@@ -0,0 +1,200 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The MySQL engine adapter for Datadouble.
5
+
6
+ Spec settings::
7
+
8
+ sources:
9
+ app:
10
+ engine: mysql
11
+ connection:
12
+ url: {env: SHOP_MYSQL_URL} # mysql://user:password@host:3306/database, by reference
13
+ databases: [shop, "billing_*"] # names or globs; the URL's database by default
14
+
15
+ The catalog spans the databases ``databases`` lists (``["*"]`` for every one
16
+ but MySQL's own), or the URL's database; each table is named
17
+ ``database.table``. Working databases, restores and ``mysqldump`` run in the
18
+ official MySQL image of exactly the source's version (``mysql:<version>``), or
19
+ in ``sources.<name>.image``, through the spec's container runtime. ``mysqldump``
20
+ connects to the source from a container, so the source must be reachable from
21
+ there at the URL's address.
22
+ """
23
+
24
+ from collections.abc import Generator, Mapping
25
+ from contextlib import contextmanager
26
+ from pathlib import Path
27
+ from typing import Annotated
28
+ from urllib.parse import unquote, urlsplit
29
+
30
+ import pymysql
31
+ from pydantic import BaseModel, ConfigDict, Field, JsonValue
32
+ from pymysql.connections import Connection
33
+
34
+ from datadouble.engine import (
35
+ EngineError,
36
+ ServerPlan,
37
+ SourceSession,
38
+ Tooling,
39
+ WorkingDatabases,
40
+ choose_databases,
41
+ )
42
+ from datadouble.names import EngineName
43
+ from datadouble.planner import AccountNames, Capabilities
44
+ from datadouble.secrets import resolve_secret
45
+ from datadouble.settings import NoSettings, parse_settings
46
+ from datadouble.spec import ImageFormat, SecretRef
47
+ from datadouble_mysql.errors import database_error
48
+ from datadouble_mysql.introspect import ENGINE, SYSTEM_DATABASES
49
+ from datadouble_mysql.server import USER, Tools, create_user, default_image
50
+ from datadouble_mysql.source import MysqlSession
51
+ from datadouble_mysql.working import DatabaseInfo, MysqlWorking
52
+
53
+ MOUNT = "/var/lib/datadouble"
54
+ """Where container servers mount a copy."""
55
+ COPY_USER = "datadouble"
56
+ """The user an instance copy's server gets, with the copy's password."""
57
+
58
+
59
+ class MysqlConnection(BaseModel):
60
+ """The ``sources.<name>.connection`` settings."""
61
+
62
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
63
+
64
+ url: SecretRef
65
+ databases: tuple[Annotated[str, Field(min_length=1)], ...] = ()
66
+ """The databases to read, as names or globs (``["*"]`` for all but MySQL's
67
+ own); the URL's database when empty."""
68
+
69
+
70
+ def parse_url(url: str) -> tuple[dict[str, str], str | None]:
71
+ """Connection settings (host, port, user, password) and the database, if any, from a URL."""
72
+ parts = urlsplit(url)
73
+ database = unquote(parts.path.lstrip("/")) or None
74
+ if parts.scheme != "mysql" or not parts.hostname:
75
+ message = "the mysql url must look like mysql://user:password@host:3306/database"
76
+ raise EngineError(message)
77
+ password = unquote(parts.password or "")
78
+ if "\n" in password or "\r" in password:
79
+ # mysqldump reads the password from an option file, one option a line.
80
+ message = (
81
+ "the mysql connection url's password holds a line break, which"
82
+ " mysqldump's option file cannot carry; choose a password without one"
83
+ )
84
+ raise EngineError(message)
85
+ return (
86
+ {
87
+ "host": parts.hostname,
88
+ "port": str(parts.port or 3306),
89
+ "user": unquote(parts.username or ""),
90
+ "password": password,
91
+ },
92
+ database,
93
+ )
94
+
95
+
96
+ def list_databases(connection: Connection) -> tuple[str, ...]:
97
+ """Every database the user can see."""
98
+ try:
99
+ with connection.cursor() as cursor:
100
+ cursor.execute("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA")
101
+ return tuple(str(row[0]) for row in cursor.fetchall())
102
+ except pymysql.MySQLError as error:
103
+ raise database_error(error, "listing the databases") from None
104
+
105
+
106
+ class MysqlEngine:
107
+ """Implements :class:`datadouble.engine.EngineAdapter` for MySQL."""
108
+
109
+ @property
110
+ def name(self) -> EngineName:
111
+ """``mysql``."""
112
+ return ENGINE
113
+
114
+ @property
115
+ def owner(self) -> str:
116
+ """``999:999``, the user the official MySQL image serves as."""
117
+ return "999:999"
118
+
119
+ def capabilities(self) -> Capabilities:
120
+ """Both image formats, SQL expressions, the nested strategy, hooks and accounts."""
121
+ # Minor releases (8.0, 8.4) change the data directory; 8.0 cannot open 8.4's.
122
+ return Capabilities(
123
+ formats=(ImageFormat.PHYSICAL, ImageFormat.LOGICAL),
124
+ expressions=True,
125
+ nested=True,
126
+ version_line=2,
127
+ accounts=AccountNames(max_characters=32, reserved=(USER, COPY_USER)),
128
+ standalone=True,
129
+ several_sources=True,
130
+ )
131
+
132
+ @contextmanager
133
+ def connect(self, connection: Mapping[str, JsonValue]) -> Generator[SourceSession]:
134
+ """Connect to the source and find the databases to read."""
135
+ settings = parse_settings(MysqlConnection, connection, "mysql connection")
136
+ options, database = parse_url(resolve_secret(settings.url))
137
+ if not settings.databases and database is None:
138
+ message = "name a database in the mysql url, or list connection.databases"
139
+ raise EngineError(message)
140
+ try:
141
+ opened = pymysql.connect(
142
+ host=options["host"],
143
+ port=int(options["port"]),
144
+ user=options["user"],
145
+ password=options["password"],
146
+ database=database,
147
+ charset="utf8mb4",
148
+ autocommit=True,
149
+ )
150
+ except pymysql.MySQLError as error:
151
+ raise database_error(error, "connecting to the source") from None
152
+ try:
153
+ wanted = settings.databases or (str(database),)
154
+ databases = choose_databases(list_databases(opened), wanted, SYSTEM_DATABASES)
155
+ default = database if database in databases else databases[0]
156
+ yield MysqlSession(opened, options, databases, default)
157
+ finally:
158
+ if opened.open:
159
+ opened.close()
160
+
161
+ def working(self, scratch: Path, tooling: Tooling, source_version: str) -> WorkingDatabases:
162
+ """Servers under ``scratch``, in the image for the source's version."""
163
+ parse_settings(NoSettings, tooling.server, "mysql server")
164
+ image = tooling.image or default_image(source_version)
165
+ return MysqlWorking(Tools(tooling.runtime, image), scratch)
166
+
167
+ def server(self, image: Path, server_image: str | None) -> ServerPlan:
168
+ """The official MySQL image of the image's version, on the copy.
169
+
170
+ At start the user ``datadouble`` is created on the copy, or its
171
+ password reset, to the copy's password, and the server then listens on
172
+ the network.
173
+ """
174
+ info = DatabaseInfo.model_validate_json((image / "database.json").read_bytes())
175
+ data = f"{MOUNT}/mysql"
176
+ ready = f"{MOUNT}/.datadouble-ready"
177
+ options = f"--datadir={data} --mysqlx=OFF"
178
+ start = (
179
+ f"rm -f {ready}"
180
+ f" && mysqld {options} --bind-address=127.0.0.1 --daemonize > /dev/null"
181
+ f" && {create_user(COPY_USER)}"
182
+ " && mysqladmin -uroot shutdown"
183
+ f" && touch {ready}"
184
+ f" && exec mysqld {options} --bind-address=*"
185
+ )
186
+ return ServerPlan(
187
+ image=server_image or default_image(info.server_version),
188
+ mount=MOUNT,
189
+ owner=self.owner,
190
+ command=("sh", "-c", start),
191
+ ready=("sh", "-c", f"test -f {ready} && mysqladmin -uroot ping"),
192
+ port=3306,
193
+ database=info.default,
194
+ user=COPY_USER,
195
+ )
196
+
197
+
198
+ def engine() -> MysqlEngine:
199
+ """The entry point named in ``datadouble.engines``."""
200
+ return MysqlEngine()
@@ -0,0 +1,160 @@
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
+ MySQL messages can quote the data that caused them (``Duplicate entry 'x'
7
+ for key``, a value that does not fit). Messages leaving this adapter keep the
8
+ error number and the message with data values hidden; quoted object names and
9
+ identifiers in backticks are kept (decisions 54 and 139).
10
+ """
11
+
12
+ import re
13
+
14
+ import pymysql
15
+
16
+ from datadouble.engine import EngineError
17
+ from datadouble.redaction import Redactor, kinds
18
+ from datadouble.runtime import runtime_failure
19
+
20
+ _NOISE = ("mysql: [Warning]", "mysqldump: [Warning]", "Warning:")
21
+
22
+ # The shapes in which MySQL reports data values; the ``value`` group is
23
+ # hidden. Message texts are the server's (share/messages_to_clients.txt),
24
+ # named by error; a new one is one more line. Any other quoted string that no
25
+ # kind word names is hidden anyway. Data too long (1406), data truncated
26
+ # (1265) and out of range (1264) name only the column.
27
+ _VALUES = (
28
+ r"Duplicate entry '(?P<value>.*)' for key", # ER_DUP_ENTRY 1062
29
+ # ER_TRUNCATED_WRONG_VALUE_FOR_FIELD 1366, ER_WRONG_VALUE 1525
30
+ r"Incorrect [\w ]+? value: '(?P<value>.*)'(?= for column|$)",
31
+ r"Truncated incorrect [\w ]+? value: '(?P<value>.*)'$", # ER_TRUNCATED_WRONG_VALUE 1292
32
+ r"can't be set to the value of '(?P<value>.*)'$", # ER_WRONG_VALUE_FOR_VAR 1231
33
+ r"Invalid \w+ character string: '(?P<value>.*)'$", # ER_INVALID_CHARACTER_STRING 1300
34
+ r"Cannot convert string '(?P<value>.*)' from", # ER_CANNOT_CONVERT_STRING 3854
35
+ r"near '(?P<value>.*)' at line \d+", # ER_PARSE_ERROR 1064: the statement, literals and all
36
+ )
37
+ # What says a quoted string names an object: an account ('app'@'%'), a kind
38
+ # word (``column 'email'``), or a clause (``in 'field list'``).
39
+ _KINDS = (
40
+ "table column key index constraint database schema user role procedure"
41
+ " function trigger view event file directory tablespace partition"
42
+ " plugin component engine server"
43
+ )
44
+ _NAMES = (
45
+ rf"{kinds('user role')}'[^']*'@",
46
+ kinds(_KINDS),
47
+ r"\bin\s+(?='[\w ]+ (?:list|clause|statement)')",
48
+ )
49
+
50
+ # A message a user raised (SIGNAL or RESIGNAL) can quote any value after any
51
+ # word, so every quoted string in it is hidden. A trigger can SIGNAL with any
52
+ # error number, a real one such as 1062 included, and pymysql drops the
53
+ # SQLSTATE, so names are kept only in a message that matches, whole, the
54
+ # server's own text for its number; any other has every quoted string
55
+ # hidden. The texts are from share/messages_to_clients.txt; a quoted name is
56
+ # '[^']*', a quoted value '.*'.
57
+ _NAME = "'[^']*'"
58
+ _ACCOUNT = f"{_NAME}@{_NAME}"
59
+ _TEMPLATES = {
60
+ 1044: f"Access denied for user {_ACCOUNT} to database {_NAME}",
61
+ 1045: rf"Access denied for user {_ACCOUNT} \(using password: (?:YES|NO)\)",
62
+ 1048: f"Column {_NAME} cannot be null",
63
+ 1049: f"Unknown database {_NAME}",
64
+ 1050: f"Table {_NAME} already exists",
65
+ 1051: f"Unknown table {_NAME}",
66
+ 1054: f"Unknown column {_NAME} in {_NAME}",
67
+ 1062: f"Duplicate entry '.*' for key {_NAME}",
68
+ 1064: (
69
+ r"You have an error in your SQL syntax; check the manual that corresponds to your"
70
+ r" (?:MySQL|MariaDB) server version for the right syntax to use near '.*' at line \d+"
71
+ ),
72
+ 1142: rf"[\w ]+ command denied to user {_ACCOUNT} for table {_NAME}",
73
+ 1143: rf"[\w ]+ command denied to user {_ACCOUNT} for column {_NAME} in table {_NAME}",
74
+ 1146: f"Table {_NAME} doesn't exist",
75
+ 1231: f"Variable {_NAME} can't be set to the value of '.*'",
76
+ 1264: rf"Out of range value for column {_NAME} at row \d+",
77
+ 1265: rf"Data truncated for column {_NAME} at row \d+",
78
+ 1292: r"Truncated incorrect [\w ]+ value: '.*'",
79
+ 1300: r"Invalid \w+ character string: '.*'",
80
+ 1366: rf"Incorrect [\w ]+ value: '.*' for column {_NAME} at row \d+",
81
+ 1406: rf"Data too long for column {_NAME} at row \d+",
82
+ 1451: r"Cannot delete or update a parent row: a foreign key constraint fails \([^']*\)",
83
+ 1452: r"Cannot add or update a child row: a foreign key constraint fails \([^']*\)",
84
+ 1525: r"Incorrect [\w ]+ value: '.*'",
85
+ 3819: f"Check constraint {_NAME} is violated\\.",
86
+ 3854: r"Cannot convert string '.*' from \w+ to \w+",
87
+ }
88
+ _KNOWN = {code: re.compile(text, re.DOTALL) for code, text in _TEMPLATES.items()}
89
+ # The client's line for a server error: ERROR 1062 (23000) at line 1: ...
90
+ _CLIENT = re.compile(r"ERROR (?P<code>\d+) \(\w+\)(?: at line \d+)?[^:]*: (?P<message>.*)")
91
+ # mysqldump's: Got error: 1146: Table 'shop.t' doesn't exist when using LOCK TABLES
92
+ _DUMP = re.compile(r"Got error: (?P<code>\d+): (?P<message>.*?)(?: when [\w ]+)?$")
93
+
94
+
95
+ def _error_line(line: str) -> re.Match[str] | None:
96
+ """The code and message of a client's or mysqldump's line for a server error."""
97
+ return _CLIENT.search(line) or _DUMP.search(line)
98
+
99
+
100
+ # SIGNAL's SQLSTATE class 45 and error 1644, as the client prints them.
101
+ _RAISED = (r"\b1644\b", r"\(45\d{3}\)")
102
+
103
+ redact = Redactor(values=_VALUES, names=_NAMES, marks="'\"", raised=_RAISED)
104
+ """Hide the data values in a MySQL message, keeping the objects it names."""
105
+
106
+
107
+ def genuine(code: object, message: str) -> bool:
108
+ """Whether ``message`` is the server's own text for error ``code``, not a user's."""
109
+ known = _KNOWN.get(code) if isinstance(code, int) else None
110
+ return known is not None and known.fullmatch(message.strip()) is not None
111
+
112
+
113
+ def _raised_in_client(output: str) -> bool:
114
+ """Whether the client's output holds an error a user may have raised.
115
+
116
+ Each ``ERROR n (state)`` line, and mysqldump's ``Got error: n:`` line
117
+ (with its trailing ``when ...``), must be the server's own text for ``n``,
118
+ and the whole of its error: a further line before the next one could be
119
+ a user's text continuing it.
120
+ """
121
+ lines = [
122
+ line.strip()
123
+ for line in output.splitlines()
124
+ if line.strip() and not line.strip().startswith(_NOISE)
125
+ ]
126
+ for index, line in enumerate(lines):
127
+ match = _error_line(line)
128
+ if match is None:
129
+ continue
130
+ rest = lines[index + 1 :]
131
+ follows = bool(rest) and _error_line(rest[0]) is None
132
+ if follows or not genuine(int(match["code"]), match["message"]):
133
+ return True
134
+ return False
135
+
136
+
137
+ def database_error(error: pymysql.MySQLError, action: str) -> EngineError:
138
+ """An :class:`EngineError` for a failed database operation."""
139
+ arguments: tuple[object, ...] = error.args
140
+ code = f"[{arguments[0]}] " if len(arguments) > 1 else ""
141
+ detail = str(arguments[1]) if len(arguments) > 1 else type(error).__name__
142
+ raised = len(arguments) > 1 and not genuine(arguments[0], detail)
143
+ return EngineError(f"{action} failed: {code}{redact(detail, raised=raised)}")
144
+
145
+
146
+ def tool_error(tool: str, status: int, stderr: str) -> EngineError:
147
+ """An :class:`EngineError` for a failed MySQL command-line tool.
148
+
149
+ Its output is redacted, unless the status says the container runtime
150
+ failed before the program ran (:func:`~datadouble.runtime.runtime_failure`).
151
+ """
152
+ keep = runtime_failure(status)
153
+ raised = redact.raises(stderr) or _raised_in_client(stderr)
154
+ lines = [
155
+ line.strip() if keep else redact(line.strip(), raised=raised)
156
+ for line in stderr.splitlines()
157
+ if line.strip() and not line.strip().startswith(_NOISE)
158
+ ]
159
+ summary = "; ".join(lines[-3:]) or "no output"
160
+ return EngineError(f"{tool} exited with status {status}: {summary}")