datadouble-mysql 0.0.3__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.
@@ -0,0 +1,21 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ __pycache__/
5
+ *.py[cod]
6
+ .venv/
7
+ .env
8
+ .coverage
9
+ .coverage.*
10
+ coverage.xml
11
+ .reports/
12
+ .pytest_cache/
13
+ .mypy_cache/
14
+ .ruff_cache/
15
+ dist/
16
+ site/
17
+ .cache/
18
+
19
+ # The default work directory of `datadouble run`.
20
+ .datadouble/
21
+ node_modules/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026- Tight Line LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,207 @@
1
+ Metadata-Version: 2.5
2
+ Name: datadouble-mysql
3
+ Version: 0.0.3
4
+ Summary: MySQL engine adapter for Datadouble
5
+ Project-URL: Homepage, https://datadouble.tightlinesoftware.com/
6
+ Project-URL: Source, https://github.com/datadouble/datadouble
7
+ Author: Tight Line LLC
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 2 - Pre-Alpha
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Programming Language :: Python :: 3.15
15
+ Classifier: Topic :: Database
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.13
18
+ Requires-Dist: datadouble
19
+ Requires-Dist: pymysql>=1.1.2
20
+ Description-Content-Type: text/markdown
21
+
22
+ # datadouble-mysql
23
+
24
+ The MySQL engine adapter for [Datadouble](https://datadouble.tightlinesoftware.com/).
25
+
26
+ It reads one consistent snapshot of one or more databases (`START TRANSACTION
27
+ WITH CONSISTENT SNAPSHOT`), writes the chosen rows as bulk-load files and the
28
+ schema with `mysqldump`, builds working databases as throwaway MySQL servers,
29
+ and packages golden images as a data directory (`physical`) or a `mysqldump`
30
+ script (`logical`). Servers, restores and `mysqldump` run in the official MySQL
31
+ image of exactly the source's version, through the spec's container runtime.
32
+
33
+ The adapter needs MySQL 8.0.13 or later, the first release that lists the
34
+ tables a view reads; reading an older server's catalog fails, naming its
35
+ version.
36
+
37
+ ```yaml
38
+ sources:
39
+ app:
40
+ engine: mysql
41
+ connection:
42
+ url: # mysql://user:password@host:3306/database, by reference
43
+ env: SHOP_MYSQL_URL
44
+ ```
45
+
46
+ The URL's password can't hold a line break (`%0A` or `%0D`): `mysqldump`
47
+ reads it from an option file, one option a line, so the connection is
48
+ refused with an error that names the URL and never the password.
49
+
50
+ Error messages keep quoted object names only when the message is the
51
+ server's own text for its error number (`Duplicate entry '…' for key
52
+ 'users.email'`). A trigger can `SIGNAL` with any number and text, so any
53
+ other message has every quoted string shown as `…`.
54
+
55
+ ## Accounts
56
+
57
+ A physical image carries no account that logs in over the network, so a
58
+ server started on a copy with the official image accepts only local
59
+ connections. `package.accounts` adds some:
60
+
61
+ ```yaml
62
+ package:
63
+ accounts:
64
+ - user: app # privileges: all
65
+ password: app-password
66
+ - user: reporting
67
+ password:
68
+ env: REPORTING_PW
69
+ privileges: read
70
+ ```
71
+
72
+ Each becomes `'user'@'%'`. `all` grants `ALL ON *.*` with the grant option.
73
+ `read` grants `SELECT, SHOW VIEW` on each of the image's databases at
74
+ packaging time, not on `*.*`, so it can't read the `mysql` schema's password
75
+ hashes; it can still change its own password. An existing user of that name,
76
+ such as `root`, gets the password and exactly the declared privileges, and
77
+ `root@localhost` keeps logging in over the socket without one. MySQL rewrites
78
+ the passwords out of the statements it logs. The build logs in with each
79
+ account over TCP, and checks that a wrong password is refused, before storing
80
+ the image.
81
+
82
+ Names longer than 32 characters fail the plan, as do `datadouble-build` (the
83
+ build user) and `datadouble` (the user instance copies reset).
84
+
85
+ ## Databases
86
+
87
+ The URL's database is the one read, unless `connection.databases` lists
88
+ others. Each table is named `database.table`, and a spec may leave the
89
+ database out wherever only one table fits (`orders` for `shop.orders`).
90
+
91
+ ```yaml
92
+ sources:
93
+ app:
94
+ engine: mysql
95
+ connection:
96
+ url: # the database in it is optional with databases
97
+ env: SHOP_MYSQL_URL
98
+ databases: [shop, "billing_*"] # names or globs; ["*"] for every database
99
+ ```
100
+
101
+ - **Choosing databases.** Each entry is a name or a glob. A name must exist
102
+ and a glob must match at least one database the URL's user can see, so a
103
+ typing mistake fails instead of quietly reading less. `["*"]` reads every
104
+ database except MySQL's own (`mysql`, `information_schema`,
105
+ `performance_schema`, `sys`), which cannot be named either. With a glob, a
106
+ database created later is read too, and strict mode stops the build at its
107
+ tables until they are locked.
108
+ - **One snapshot.** MySQL's consistent snapshot covers every InnoDB table on
109
+ the server, so every database is read at the same point in time, and
110
+ foreign keys, views, triggers and routines across databases are copied as
111
+ they are. A foreign key into a database that is not read keeps its target,
112
+ so the plan asks for a fallback, and the copies drop it. A view over a
113
+ database that is not read could not be created in a copy, so it is left out,
114
+ as a view over an excluded table is; the extract's `index.json` lists every
115
+ view left out (`omitted_views`).
116
+ - **The copies hold every database,** under its own name, in one server:
117
+ working databases, both image formats and every copy.
118
+ - **The default database.** Spec SQL that names no table (hooks and
119
+ assertions) runs with a default database: the URL's, when it is read, or
120
+ else the first database read in name order. `before_load` hooks run in it
121
+ too: it is created, with the source's character set, before them. Copies
122
+ announce it as their `database`. Qualify names in such SQL
123
+ (`billing.invoices`) to reach the others. Seeds, `when` clauses and
124
+ expression rules run against their own table, so unqualified column names
125
+ in them need nothing.
126
+
127
+ ## Several servers
128
+
129
+ A spec can read databases from several MySQL servers, one source per server,
130
+ into one image (see
131
+ [several sources](../../docs/architecture.md#several-sources)):
132
+
133
+ ```yaml
134
+ sources:
135
+ app:
136
+ engine: mysql
137
+ connection:
138
+ url:
139
+ env: APP_MYSQL_URL
140
+ databases: [shop, billing]
141
+ warehouse:
142
+ engine: mysql
143
+ connection:
144
+ url:
145
+ env: WAREHOUSE_MYSQL_URL
146
+ databases: [warehouse]
147
+ ```
148
+
149
+ - **Every database once.** A database name read from two servers fails the
150
+ plan, naming it; the working server holds every source's databases under
151
+ their own names, and loads each source's schema, then every source's rows,
152
+ then every source's triggers.
153
+ - **One version line.** The servers must share a compatibility line, the
154
+ major and minor version (`8.4`; 8.0 and 8.4 are separate lines); the working
155
+ server runs the newest of their versions. Every source gives the same
156
+ `image` and `server` settings, or none.
157
+ - **A snapshot per server.** Each server's consistent snapshot covers only
158
+ its own databases, so the image is not one point in time; its manifest
159
+ records each source's GTID set and when its snapshot was opened. A virtual
160
+ reference between sources is read with strategy B, its keys through each
161
+ server's own snapshot, and the plan lists it under `between_sources`.
162
+ - **The default database** for hooks and assertions is the first source's.
163
+
164
+ ## Plugins
165
+
166
+ Plugins the data needs, storage engines and full-text parsers installed from
167
+ a library, are requirements named by their library, such as
168
+ `plugin mypluglib.so`. Other plugins (authentication, password policy,
169
+ audit, replication) change how a server behaves, not what it can load, and
170
+ are not. Before reading the source, a build lists the libraries in the
171
+ working image's plugin directory and fails with `requirement_unmet` if one
172
+ is missing; the version is the server's, so it is not compared. `load`
173
+ installs each plugin in the working server, and the data directory keeps it,
174
+ so later servers and copies of a physical image load it too. A plugin from
175
+ another distribution, such as Percona's MyRocks, needs that distribution's
176
+ image in `sources.<name>.image`.
177
+
178
+ ## Objects
179
+
180
+ The catalog lists the views, stored functions and procedures, triggers and
181
+ events of every database read, named `database.object`, all under the one
182
+ snapshot. A view's tables, views and functions come from
183
+ `information_schema.VIEW_TABLE_USAGE` and `VIEW_ROUTINE_USAGE`, and a
184
+ trigger's table from `information_schema.TRIGGERS`: those edges are exact,
185
+ and may cross databases. MySQL counts the tables that a view's stored
186
+ functions read as the view's own, so a view calling a function that reads
187
+ `rental` has an exact edge to `rental` though its text never names it, and
188
+ removing `rental` fails the plan naming the view. A view that reads a
189
+ database not read, directly, through other views or through the functions
190
+ it calls, is left out of the catalog as it is left out of the copies. MySQL records nothing else, so what routine, trigger and event
191
+ bodies use is parsed from their text, matching names in any database read
192
+ (an unqualified name means the object's own database first), and those
193
+ edges are marked inferred. Reading a routine's body needs the `SHOW_ROUTINE` privilege, or
194
+ owning the routine; without it the body reads as empty, so the routine's
195
+ fingerprint cannot change and its edges are missing.
196
+
197
+ Tables need no objects in MySQL: it has no sequences or user-defined types,
198
+ and column defaults and generated columns cannot call stored functions. A
199
+ table's triggers depend on it, so package planning brings them, and the
200
+ routines they call, along with the table.
201
+
202
+ A standalone group's database holds exactly its closure: the pulled-in
203
+ tables with the rows of the group's own extract, and none of the routines,
204
+ triggers, events and views the closure lacks. Foreign keys into a pulled-in
205
+ table without rows are dropped. MySQL does not check what a routine body
206
+ calls, so one the catalog only inferred is not stopped from being dropped;
207
+ the plan warns about those.
@@ -0,0 +1,186 @@
1
+ # datadouble-mysql
2
+
3
+ The MySQL engine adapter for [Datadouble](https://datadouble.tightlinesoftware.com/).
4
+
5
+ It reads one consistent snapshot of one or more databases (`START TRANSACTION
6
+ WITH CONSISTENT SNAPSHOT`), writes the chosen rows as bulk-load files and the
7
+ schema with `mysqldump`, builds working databases as throwaway MySQL servers,
8
+ and packages golden images as a data directory (`physical`) or a `mysqldump`
9
+ script (`logical`). Servers, restores and `mysqldump` run in the official MySQL
10
+ image of exactly the source's version, through the spec's container runtime.
11
+
12
+ The adapter needs MySQL 8.0.13 or later, the first release that lists the
13
+ tables a view reads; reading an older server's catalog fails, naming its
14
+ version.
15
+
16
+ ```yaml
17
+ sources:
18
+ app:
19
+ engine: mysql
20
+ connection:
21
+ url: # mysql://user:password@host:3306/database, by reference
22
+ env: SHOP_MYSQL_URL
23
+ ```
24
+
25
+ The URL's password can't hold a line break (`%0A` or `%0D`): `mysqldump`
26
+ reads it from an option file, one option a line, so the connection is
27
+ refused with an error that names the URL and never the password.
28
+
29
+ Error messages keep quoted object names only when the message is the
30
+ server's own text for its error number (`Duplicate entry '…' for key
31
+ 'users.email'`). A trigger can `SIGNAL` with any number and text, so any
32
+ other message has every quoted string shown as `…`.
33
+
34
+ ## Accounts
35
+
36
+ A physical image carries no account that logs in over the network, so a
37
+ server started on a copy with the official image accepts only local
38
+ connections. `package.accounts` adds some:
39
+
40
+ ```yaml
41
+ package:
42
+ accounts:
43
+ - user: app # privileges: all
44
+ password: app-password
45
+ - user: reporting
46
+ password:
47
+ env: REPORTING_PW
48
+ privileges: read
49
+ ```
50
+
51
+ Each becomes `'user'@'%'`. `all` grants `ALL ON *.*` with the grant option.
52
+ `read` grants `SELECT, SHOW VIEW` on each of the image's databases at
53
+ packaging time, not on `*.*`, so it can't read the `mysql` schema's password
54
+ hashes; it can still change its own password. An existing user of that name,
55
+ such as `root`, gets the password and exactly the declared privileges, and
56
+ `root@localhost` keeps logging in over the socket without one. MySQL rewrites
57
+ the passwords out of the statements it logs. The build logs in with each
58
+ account over TCP, and checks that a wrong password is refused, before storing
59
+ the image.
60
+
61
+ Names longer than 32 characters fail the plan, as do `datadouble-build` (the
62
+ build user) and `datadouble` (the user instance copies reset).
63
+
64
+ ## Databases
65
+
66
+ The URL's database is the one read, unless `connection.databases` lists
67
+ others. Each table is named `database.table`, and a spec may leave the
68
+ database out wherever only one table fits (`orders` for `shop.orders`).
69
+
70
+ ```yaml
71
+ sources:
72
+ app:
73
+ engine: mysql
74
+ connection:
75
+ url: # the database in it is optional with databases
76
+ env: SHOP_MYSQL_URL
77
+ databases: [shop, "billing_*"] # names or globs; ["*"] for every database
78
+ ```
79
+
80
+ - **Choosing databases.** Each entry is a name or a glob. A name must exist
81
+ and a glob must match at least one database the URL's user can see, so a
82
+ typing mistake fails instead of quietly reading less. `["*"]` reads every
83
+ database except MySQL's own (`mysql`, `information_schema`,
84
+ `performance_schema`, `sys`), which cannot be named either. With a glob, a
85
+ database created later is read too, and strict mode stops the build at its
86
+ tables until they are locked.
87
+ - **One snapshot.** MySQL's consistent snapshot covers every InnoDB table on
88
+ the server, so every database is read at the same point in time, and
89
+ foreign keys, views, triggers and routines across databases are copied as
90
+ they are. A foreign key into a database that is not read keeps its target,
91
+ so the plan asks for a fallback, and the copies drop it. A view over a
92
+ database that is not read could not be created in a copy, so it is left out,
93
+ as a view over an excluded table is; the extract's `index.json` lists every
94
+ view left out (`omitted_views`).
95
+ - **The copies hold every database,** under its own name, in one server:
96
+ working databases, both image formats and every copy.
97
+ - **The default database.** Spec SQL that names no table (hooks and
98
+ assertions) runs with a default database: the URL's, when it is read, or
99
+ else the first database read in name order. `before_load` hooks run in it
100
+ too: it is created, with the source's character set, before them. Copies
101
+ announce it as their `database`. Qualify names in such SQL
102
+ (`billing.invoices`) to reach the others. Seeds, `when` clauses and
103
+ expression rules run against their own table, so unqualified column names
104
+ in them need nothing.
105
+
106
+ ## Several servers
107
+
108
+ A spec can read databases from several MySQL servers, one source per server,
109
+ into one image (see
110
+ [several sources](../../docs/architecture.md#several-sources)):
111
+
112
+ ```yaml
113
+ sources:
114
+ app:
115
+ engine: mysql
116
+ connection:
117
+ url:
118
+ env: APP_MYSQL_URL
119
+ databases: [shop, billing]
120
+ warehouse:
121
+ engine: mysql
122
+ connection:
123
+ url:
124
+ env: WAREHOUSE_MYSQL_URL
125
+ databases: [warehouse]
126
+ ```
127
+
128
+ - **Every database once.** A database name read from two servers fails the
129
+ plan, naming it; the working server holds every source's databases under
130
+ their own names, and loads each source's schema, then every source's rows,
131
+ then every source's triggers.
132
+ - **One version line.** The servers must share a compatibility line, the
133
+ major and minor version (`8.4`; 8.0 and 8.4 are separate lines); the working
134
+ server runs the newest of their versions. Every source gives the same
135
+ `image` and `server` settings, or none.
136
+ - **A snapshot per server.** Each server's consistent snapshot covers only
137
+ its own databases, so the image is not one point in time; its manifest
138
+ records each source's GTID set and when its snapshot was opened. A virtual
139
+ reference between sources is read with strategy B, its keys through each
140
+ server's own snapshot, and the plan lists it under `between_sources`.
141
+ - **The default database** for hooks and assertions is the first source's.
142
+
143
+ ## Plugins
144
+
145
+ Plugins the data needs, storage engines and full-text parsers installed from
146
+ a library, are requirements named by their library, such as
147
+ `plugin mypluglib.so`. Other plugins (authentication, password policy,
148
+ audit, replication) change how a server behaves, not what it can load, and
149
+ are not. Before reading the source, a build lists the libraries in the
150
+ working image's plugin directory and fails with `requirement_unmet` if one
151
+ is missing; the version is the server's, so it is not compared. `load`
152
+ installs each plugin in the working server, and the data directory keeps it,
153
+ so later servers and copies of a physical image load it too. A plugin from
154
+ another distribution, such as Percona's MyRocks, needs that distribution's
155
+ image in `sources.<name>.image`.
156
+
157
+ ## Objects
158
+
159
+ The catalog lists the views, stored functions and procedures, triggers and
160
+ events of every database read, named `database.object`, all under the one
161
+ snapshot. A view's tables, views and functions come from
162
+ `information_schema.VIEW_TABLE_USAGE` and `VIEW_ROUTINE_USAGE`, and a
163
+ trigger's table from `information_schema.TRIGGERS`: those edges are exact,
164
+ and may cross databases. MySQL counts the tables that a view's stored
165
+ functions read as the view's own, so a view calling a function that reads
166
+ `rental` has an exact edge to `rental` though its text never names it, and
167
+ removing `rental` fails the plan naming the view. A view that reads a
168
+ database not read, directly, through other views or through the functions
169
+ it calls, is left out of the catalog as it is left out of the copies. MySQL records nothing else, so what routine, trigger and event
170
+ bodies use is parsed from their text, matching names in any database read
171
+ (an unqualified name means the object's own database first), and those
172
+ edges are marked inferred. Reading a routine's body needs the `SHOW_ROUTINE` privilege, or
173
+ owning the routine; without it the body reads as empty, so the routine's
174
+ fingerprint cannot change and its edges are missing.
175
+
176
+ Tables need no objects in MySQL: it has no sequences or user-defined types,
177
+ and column defaults and generated columns cannot call stored functions. A
178
+ table's triggers depend on it, so package planning brings them, and the
179
+ routines they call, along with the table.
180
+
181
+ A standalone group's database holds exactly its closure: the pulled-in
182
+ tables with the rows of the group's own extract, and none of the routines,
183
+ triggers, events and views the closure lacks. Foreign keys into a pulled-in
184
+ table without rows are dropped. MySQL does not check what a routine body
185
+ calls, so one the catalog only inferred is not stopped from being dropped;
186
+ the plan warns about those.
@@ -0,0 +1,38 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ [project]
5
+ name = "datadouble-mysql"
6
+ # All packages share one version until 1.0 (decision 38); scripts/make_tag.py
7
+ # sets it at release time.
8
+ version = "0.0.3"
9
+ description = "MySQL engine adapter for Datadouble"
10
+ readme = "README.md"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Tight Line LLC" }]
14
+ requires-python = ">=3.13"
15
+ dependencies = ["datadouble", "pymysql>=1.1.2"]
16
+ classifiers = [
17
+ "Development Status :: 2 - Pre-Alpha",
18
+ "Programming Language :: Python :: 3 :: Only",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Programming Language :: Python :: 3.14",
21
+ "Programming Language :: Python :: 3.15",
22
+ "Topic :: Database",
23
+ "Typing :: Typed",
24
+ ]
25
+
26
+ [project.urls]
27
+ Homepage = "https://datadouble.tightlinesoftware.com/"
28
+ Source = "https://github.com/datadouble/datadouble"
29
+
30
+ [project.entry-points."datadouble.engines"]
31
+ mysql = "datadouble_mysql:engine"
32
+
33
+ [build-system]
34
+ requires = ["hatchling>=1.33.0"]
35
+ build-backend = "hatchling.build"
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["src/datadouble_mysql"]
@@ -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()