Files
absdev-deployment/adapters/mysql/adapter.py
2026-11-27 17:15:42 +00:00

109 lines
2.9 KiB
Python

"""MySQL database command construction."""
from core.database import DatabaseAdapter, DatabaseError
class MySQLAdapter(DatabaseAdapter):
backup_extension = ".sql"
client_configuration = (
"--defaults-file=/run/secrets/absdev-client.cnf"
)
def __init__(self, config, *, read_only_backup=False):
super().__init__(config)
if type(read_only_backup) is not bool:
raise DatabaseError("Invalid MySQL backup option")
self.read_only_backup = read_only_backup
def backup_inventory_command(self):
if not self.read_only_backup:
return None
# The trusted definer procedure is installed outside the protected database.
return self.query_command("CALL absdev_backup_control.check_inventory(DATABASE())")
def backup_grants_command(self):
return self.query_command("SELECT @@GLOBAL.partial_revokes; SHOW GRANTS FOR CURRENT_USER()")
def connection_arguments(self):
return [
"--protocol=TCP",
f"--host={self.database['host']}",
f"--port={self.database['port']}",
f"--user={self.database['username']}",
]
def query_command(self, query):
return (
self.docker_exec()
+ [
"mysql",
self.client_configuration,
]
+ self.connection_arguments()
+ [
"--batch",
"--skip-column-names",
f"--database={self.database['name']}",
"--execute",
query,
]
)
def ping_command(self):
return self.query_command("SELECT 1")
def version_command(self):
return self.query_command("SELECT VERSION()")
def identity_command(self):
return self.query_command(
"SELECT DATABASE(), CURRENT_USER(), @@server_uuid"
)
def backup_command(self):
return (
self.docker_exec()
+ [
"mysqldump",
self.client_configuration,
]
+ self.connection_arguments()
+ [
"--single-transaction",
"--quick",
"--no-tablespaces",
"--skip-lock-tables",
"--set-gtid-purged=OFF",
"--hex-blob",
*(
("--skip-triggers", "--skip-routines", "--skip-events")
if self.read_only_backup else ("--triggers", "--routines", "--events")
),
self.database["name"],
]
)
def restore_command(self, target):
target = self.validate_restore_target(target)
return (
self.docker_exec(interactive=True)
+ [
"mysql",
self.client_configuration,
]
+ self.connection_arguments()
+ [
f"--database={target}",
]
)