3tears-backup 0.16.0__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,216 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+ #poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ #pdm.lock
116
+ #pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ #pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # SageMath parsed files
135
+ *.sage.py
136
+
137
+ # Environments
138
+ .env
139
+ .envrc
140
+ .venv
141
+ env/
142
+ venv/
143
+ ENV/
144
+ env.bak/
145
+ venv.bak/
146
+
147
+ # Spyder project settings
148
+ .spyderproject
149
+ .spyproject
150
+
151
+ # Rope project settings
152
+ .ropeproject
153
+
154
+ # mkdocs documentation
155
+ /site
156
+
157
+ # mypy
158
+ .mypy_cache/
159
+ .dmypy.json
160
+ dmypy.json
161
+
162
+ # Pyre type checker
163
+ .pyre/
164
+
165
+ # pytype static type analyzer
166
+ .pytype/
167
+
168
+ # Cython debug symbols
169
+ cython_debug/
170
+
171
+ # PyCharm
172
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
173
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
175
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
176
+ #.idea/
177
+
178
+ # Abstra
179
+ # Abstra is an AI-powered process automation framework.
180
+ # Ignore directories containing user credentials, local state, and settings.
181
+ # Learn more at https://abstra.io/docs
182
+ .abstra/
183
+
184
+ # Visual Studio Code
185
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
186
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
187
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
188
+ # you could uncomment the following to ignore the entire vscode folder
189
+ # .vscode/
190
+
191
+ # Ruff stuff:
192
+ .ruff_cache/
193
+
194
+ # PyPI configuration file
195
+ .pypirc
196
+
197
+ # Cursor
198
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
199
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
200
+ # refer to https://docs.cursor.com/context/ignore-files
201
+ .cursorignore
202
+ .cursorindexingignore
203
+
204
+ # Marimo
205
+ marimo/_static/
206
+ marimo/_lsp/
207
+ __marimo__/
208
+
209
+ # Claude Code local state
210
+ .claude/
211
+
212
+ # prawduct session evidence (local governance artifacts, never shipped)
213
+ .prawduct/
214
+
215
+ # macOS folder metadata
216
+ .DS_Store
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mark Pace
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,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: 3tears-backup
3
+ Version: 0.16.0
4
+ Summary: Encrypted, GFS-rotated database backups to any ObjectStore, with restore verification
5
+ Project-URL: Repository, https://github.com/pacepace/3tears
6
+ Author: pace
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Framework :: AsyncIO
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Topic :: Database
15
+ Classifier: Topic :: System :: Archiving :: Backup
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.14
18
+ Requires-Dist: 3tears-media-contracts
19
+ Requires-Dist: 3tears-object-store
20
+ Requires-Dist: 3tears-observe
21
+ Description-Content-Type: text/markdown
22
+
23
+ # 3tears-backup
24
+
25
+ Encrypted, grandfather-father-son (GFS) rotated **database backups** to any
26
+ `ObjectStore`, with **restore verification** — built on 3tears primitives so it
27
+ drops into any 3tears app.
28
+
29
+ - **Storage-agnostic.** The engine takes an injected `ObjectStore`
30
+ (`3tears-object-store` — S3 is the first driver, filesystem the second) and
31
+ streams the dump through `EncryptedObjectStore`, so a multi-GB dump is
32
+ client-side AES-256-GCM encrypted and never sits whole in memory.
33
+ - **Postgres *and* Yugabyte.** A pluggable `DbDumpDriver` wraps the right dump
34
+ tool; the engine autodetects the target from `version()`.
35
+ - **GFS retention.** Keep N daily / weekly / monthly backups; prune the rest.
36
+ - **Restore-verified.** Backups are proven by restoring into a throwaway
37
+ temporary database, with an optional hook to spin a stack against it.
38
+
39
+ Configuration is an injected, frozen `BackupConfig` — construct it however you
40
+ like (a `from_env` factory reads `THREETEARS_BACKUP_*` with defaults; most apps
41
+ will build it from control-plane settings instead).
@@ -0,0 +1,19 @@
1
+ # 3tears-backup
2
+
3
+ Encrypted, grandfather-father-son (GFS) rotated **database backups** to any
4
+ `ObjectStore`, with **restore verification** — built on 3tears primitives so it
5
+ drops into any 3tears app.
6
+
7
+ - **Storage-agnostic.** The engine takes an injected `ObjectStore`
8
+ (`3tears-object-store` — S3 is the first driver, filesystem the second) and
9
+ streams the dump through `EncryptedObjectStore`, so a multi-GB dump is
10
+ client-side AES-256-GCM encrypted and never sits whole in memory.
11
+ - **Postgres *and* Yugabyte.** A pluggable `DbDumpDriver` wraps the right dump
12
+ tool; the engine autodetects the target from `version()`.
13
+ - **GFS retention.** Keep N daily / weekly / monthly backups; prune the rest.
14
+ - **Restore-verified.** Backups are proven by restoring into a throwaway
15
+ temporary database, with an optional hook to spin a stack against it.
16
+
17
+ Configuration is an injected, frozen `BackupConfig` — construct it however you
18
+ like (a `from_env` factory reads `THREETEARS_BACKUP_*` with defaults; most apps
19
+ will build it from control-plane settings instead).
@@ -0,0 +1,44 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "3tears-backup"
7
+ version = "0.16.0"
8
+ description = "Encrypted, GFS-rotated database backups to any ObjectStore, with restore verification"
9
+ readme = "README.md"
10
+ requires-python = ">=3.14"
11
+ authors = [{name = "pace"}]
12
+ license = "MIT"
13
+ license-files = ["LICENSE"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Framework :: AsyncIO",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.14",
20
+ "Topic :: Database",
21
+ "Topic :: System :: Archiving :: Backup",
22
+ "Typing :: Typed",
23
+ ]
24
+ # storage-agnostic: the engine takes an injected ObjectStore (S3 is one driver,
25
+ # filesystem another), streams the dump through EncryptedObjectStore, and reads
26
+ # the dump tool from the DB driver. object-store brings the store + the streaming
27
+ # AEAD primitive; media-contracts is the ObjectStore protocol; observe is
28
+ # structured logging.
29
+ dependencies = [
30
+ "3tears-media-contracts",
31
+ "3tears-object-store",
32
+ "3tears-observe",
33
+ ]
34
+
35
+ [project.urls]
36
+ Repository = "https://github.com/pacepace/3tears"
37
+
38
+ [tool.uv.sources]
39
+ 3tears-media-contracts = { workspace = true }
40
+ 3tears-object-store = { workspace = true }
41
+ 3tears-observe = { workspace = true }
42
+
43
+ [tool.hatch.build.targets.wheel]
44
+ packages = ["src/threetears"]
@@ -0,0 +1,44 @@
1
+ """Encrypted, GFS-rotated database backups to any ObjectStore, with restore verification."""
2
+
3
+ from threetears.backup.config import BackupConfig
4
+ from threetears.backup.drivers import (
5
+ DbDumpDriver,
6
+ PostgresDriver,
7
+ YugabyteDriver,
8
+ detect_driver,
9
+ driver_for_version,
10
+ )
11
+ from threetears.backup.engine import BackupEngine, DeleteNotAllowedError
12
+ from threetears.backup.process import BackupToolError
13
+ from threetears.backup.retention import (
14
+ BackupRecord,
15
+ GfsRetention,
16
+ RetentionDecision,
17
+ )
18
+ from threetears.backup.verify import (
19
+ RestoreVerifier,
20
+ VerificationResult,
21
+ count_tables,
22
+ make_subprocess_hook,
23
+ make_temp_db_provisioner,
24
+ )
25
+
26
+ __all__ = [
27
+ "BackupConfig",
28
+ "BackupEngine",
29
+ "BackupRecord",
30
+ "BackupToolError",
31
+ "DbDumpDriver",
32
+ "DeleteNotAllowedError",
33
+ "GfsRetention",
34
+ "PostgresDriver",
35
+ "RestoreVerifier",
36
+ "RetentionDecision",
37
+ "VerificationResult",
38
+ "YugabyteDriver",
39
+ "count_tables",
40
+ "detect_driver",
41
+ "driver_for_version",
42
+ "make_subprocess_hook",
43
+ "make_temp_db_provisioner",
44
+ ]
@@ -0,0 +1,93 @@
1
+ """Injected configuration for the backup engine.
2
+
3
+ :class:`BackupConfig` is a frozen value object you *pass in* -- the engine never reaches for the
4
+ environment itself. Most apps build it from control-plane settings; :meth:`BackupConfig.from_env`
5
+ is a convenience that reads ``THREETEARS_BACKUP_*`` with sensible defaults for the simple case.
6
+
7
+ It is deliberately storage-agnostic: there is no bucket here. The backend is an injected
8
+ ``ObjectStore`` (which already knows where it writes), so the same config drives an S3 backup or a
9
+ filesystem one. What lives here is the encryption passphrase, the key prefix, the GFS retention
10
+ counts, and the delete safety switch.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ from collections.abc import Mapping
17
+ from dataclasses import dataclass
18
+
19
+ from pydantic import SecretStr
20
+
21
+ __all__ = ["BackupConfig"]
22
+
23
+ _ENV_PREFIX = "THREETEARS_BACKUP_"
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class BackupConfig:
28
+ """Backup engine configuration (injected; never self-loaded).
29
+
30
+ :param passphrase: AES-256-GCM encryption passphrase (per-object scrypt-derived key).
31
+ :param prefix: object-key prefix under which backups are written/listed.
32
+ :param retention_daily: number of daily backups to keep (>= 1).
33
+ :param retention_weekly: number of weekly backups to keep (>= 1).
34
+ :param retention_monthly: number of monthly backups to keep (>= 1).
35
+ :param allow_delete: master switch for destructive operations (delete / retention prune).
36
+ :param dump_timeout_seconds: wall-clock ceiling for a dump/restore subprocess (> 0).
37
+ :param encryption_work_factor: scrypt cost N for the per-object key (power of two > 1); the
38
+ default is deployment-grade, lower it only to trade brute-force resistance for speed.
39
+ """
40
+
41
+ passphrase: SecretStr
42
+ prefix: str = "backups"
43
+ retention_daily: int = 7
44
+ retention_weekly: int = 4
45
+ retention_monthly: int = 3
46
+ allow_delete: bool = False
47
+ dump_timeout_seconds: int = 3600
48
+ encryption_work_factor: int = 2**18
49
+
50
+ def __post_init__(self) -> None:
51
+ if not self.prefix or self.prefix != self.prefix.strip("/"):
52
+ raise ValueError("prefix must be non-empty with no leading/trailing '/'")
53
+ for name in ("retention_daily", "retention_weekly", "retention_monthly"):
54
+ if getattr(self, name) < 1:
55
+ raise ValueError(f"{name} must be >= 1")
56
+ if self.dump_timeout_seconds <= 0:
57
+ raise ValueError("dump_timeout_seconds must be > 0")
58
+ if self.encryption_work_factor <= 1 or (self.encryption_work_factor & (self.encryption_work_factor - 1)) != 0:
59
+ raise ValueError("encryption_work_factor must be a power of two greater than 1")
60
+ if not self.passphrase.get_secret_value():
61
+ raise ValueError("passphrase must not be empty")
62
+
63
+ @classmethod
64
+ def from_env(cls, env: Mapping[str, str] | None = None) -> BackupConfig:
65
+ """Build a config from ``THREETEARS_BACKUP_*`` variables (defaults fill the rest).
66
+
67
+ :param env: environment mapping to read (defaults to ``os.environ``).
68
+ :raises ValueError: when ``THREETEARS_BACKUP_PASSPHRASE`` is unset, or a value is invalid.
69
+ """
70
+ source = os.environ if env is None else env
71
+ passphrase = source.get(f"{_ENV_PREFIX}PASSPHRASE")
72
+ if not passphrase:
73
+ raise ValueError(f"{_ENV_PREFIX}PASSPHRASE is required")
74
+ return cls(
75
+ passphrase=SecretStr(passphrase),
76
+ prefix=source.get(f"{_ENV_PREFIX}PREFIX", "backups"),
77
+ retention_daily=_int(source, "RETENTION_DAILY", 7),
78
+ retention_weekly=_int(source, "RETENTION_WEEKLY", 4),
79
+ retention_monthly=_int(source, "RETENTION_MONTHLY", 3),
80
+ allow_delete=_bool(source, "ALLOW_DELETE", default=False),
81
+ dump_timeout_seconds=_int(source, "DUMP_TIMEOUT_SECONDS", 3600),
82
+ encryption_work_factor=_int(source, "ENCRYPTION_WORK_FACTOR", 2**18),
83
+ )
84
+
85
+
86
+ def _int(source: Mapping[str, str], suffix: str, default: int) -> int:
87
+ raw = source.get(f"{_ENV_PREFIX}{suffix}")
88
+ return default if raw is None else int(raw)
89
+
90
+
91
+ def _bool(source: Mapping[str, str], suffix: str, *, default: bool) -> bool:
92
+ raw = source.get(f"{_ENV_PREFIX}{suffix}")
93
+ return default if raw is None else raw.strip().lower() in {"1", "true", "yes", "on"}
@@ -0,0 +1,109 @@
1
+ """Pluggable database dump/restore drivers, with Postgres/Yugabyte autodetection.
2
+
3
+ A driver knows one thing the engine doesn't: which command-line tool dumps and restores its
4
+ database, and with which flags. :class:`PostgresDriver` uses ``pg_dump``/``pg_restore`` (custom
5
+ archive format); :class:`YugabyteDriver` uses ``ysql_dump``/``ysqlsh`` (plain SQL) — Yugabyte
6
+ ships its own fork of the tools. The engine picks one by asking the database ``SELECT version()``:
7
+ Yugabyte stamps ``-YB-`` into its version string (the same tell scriob's ``is_yugabyte`` uses).
8
+
9
+ The argv builders and :func:`driver_for_version` are pure (unit-tested without a database); the
10
+ actual dump/restore streams through the shared subprocess plumbing in :mod:`threetears.backup.process`.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from abc import ABC, abstractmethod
16
+ from collections.abc import AsyncIterator, Mapping
17
+ from typing import ClassVar, Protocol, runtime_checkable
18
+
19
+ from threetears.backup.process import feed_stdin, stream_stdout
20
+
21
+ __all__ = ["DbDumpDriver", "PostgresDriver", "YugabyteDriver", "detect_driver", "driver_for_version"]
22
+
23
+ #: the marker Yugabyte stamps into ``version()`` (e.g. "... (YugabyteDB 2.20 ... -YB-...)").
24
+ _YUGABYTE_MARKER = "-YB-"
25
+
26
+
27
+ class DbDumpDriver(ABC):
28
+ """Abstract dump/restore driver: declares the argv, inherits the streaming."""
29
+
30
+ name: ClassVar[str]
31
+ #: True when the dump format is already compressed (so the engine skips gzip).
32
+ compressed: ClassVar[bool]
33
+
34
+ @abstractmethod
35
+ def dump_argv(self, dsn: str) -> list[str]:
36
+ """Argv that dumps ``dsn`` to stdout."""
37
+
38
+ @abstractmethod
39
+ def restore_argv(self, dsn: str) -> list[str]:
40
+ """Argv that restores into ``dsn`` from stdin."""
41
+
42
+ def dump(
43
+ self, dsn: str, *, env: Mapping[str, str] | None = None, timeout: float | None = None
44
+ ) -> AsyncIterator[bytes]:
45
+ """Stream a dump of ``dsn`` as bytes (bounded by ``timeout`` seconds when given)."""
46
+ return stream_stdout(self.dump_argv(dsn), env=env, timeout=timeout)
47
+
48
+ async def restore(
49
+ self,
50
+ dsn: str,
51
+ source: AsyncIterator[bytes],
52
+ *,
53
+ env: Mapping[str, str] | None = None,
54
+ timeout: float | None = None,
55
+ ) -> None:
56
+ """Restore ``source`` (a dump stream) into ``dsn`` (bounded by ``timeout`` seconds)."""
57
+ await feed_stdin(self.restore_argv(dsn), source, env=env, timeout=timeout)
58
+
59
+
60
+ class PostgresDriver(DbDumpDriver):
61
+ """Vanilla PostgreSQL via ``pg_dump`` (custom format) + ``pg_restore``."""
62
+
63
+ name: ClassVar[str] = "postgres"
64
+ compressed: ClassVar[bool] = True # pg_dump custom format is zlib-compressed already
65
+
66
+ def dump_argv(self, dsn: str) -> list[str]:
67
+ return ["pg_dump", "--dbname", dsn, "--format=custom", "--no-owner", "--no-privileges"]
68
+
69
+ def restore_argv(self, dsn: str) -> list[str]:
70
+ # a fresh (empty) target — the verifier's temp db — so no --clean is needed; fail loudly.
71
+ return ["pg_restore", "--dbname", dsn, "--no-owner", "--no-privileges", "--exit-on-error"]
72
+
73
+
74
+ class YugabyteDriver(DbDumpDriver):
75
+ """YugabyteDB via ``ysql_dump`` (plain SQL) + ``ysqlsh``."""
76
+
77
+ name: ClassVar[str] = "yugabyte"
78
+ compressed: ClassVar[bool] = False # ysql_dump emits plain SQL — gzip it
79
+
80
+ def dump_argv(self, dsn: str) -> list[str]:
81
+ return ["ysql_dump", "--dbname", dsn, "--no-owner", "--no-privileges"]
82
+
83
+ def restore_argv(self, dsn: str) -> list[str]:
84
+ # ysqlsh reads SQL from stdin; ON_ERROR_STOP makes a bad statement a non-zero exit.
85
+ return ["ysqlsh", "--dbname", dsn, "--quiet", "--set", "ON_ERROR_STOP=1"]
86
+
87
+
88
+ def driver_for_version(version: str) -> DbDumpDriver:
89
+ """Pick a driver from a ``version()`` string.
90
+
91
+ :param version: the output of ``SELECT version()``.
92
+ :return: a :class:`YugabyteDriver` if the string carries the Yugabyte marker, else Postgres.
93
+ """
94
+ return YugabyteDriver() if _YUGABYTE_MARKER in version else PostgresDriver()
95
+
96
+
97
+ @runtime_checkable
98
+ class _VersionSource(Protocol):
99
+ async def fetchval(self, query: str) -> object: ...
100
+
101
+
102
+ async def detect_driver(conn: _VersionSource) -> DbDumpDriver:
103
+ """Autodetect the driver by querying ``version()`` on an open connection.
104
+
105
+ :param conn: anything with an async ``fetchval(query)`` (e.g. an asyncpg connection).
106
+ :return: the driver matching the connected database engine.
107
+ """
108
+ version = await conn.fetchval("SELECT version()")
109
+ return driver_for_version(str(version))