141 lines
6.9 KiB
Python
141 lines
6.9 KiB
Python
"""One-off local COPY_ONLY backup/restore. Never overwrites existing databases."""
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import sys
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, r"C:\devel\python\ware_house")
|
|
from sqlalchemy import create_engine
|
|
from db_config import build_dsn_from_config, load_db_config
|
|
|
|
PAIRS = {"Mediseawall": "Xwmsdb", "SAMA1": "SAMA1_Xwmstest"}
|
|
BASE = Path(r"D:\db\XwmsTest")
|
|
BACKUPS = BASE / "baseline_20261029"
|
|
REPORT = ROOT / "local_setup"
|
|
ADMIN_CONFIG = Path(r"C:\devel\python\ware_house\db_connection.json")
|
|
|
|
|
|
def identifier(value):
|
|
return "[" + value.replace("]", "]]") + "]"
|
|
|
|
|
|
def literal(value):
|
|
return "N'" + str(value).replace("'", "''") + "'"
|
|
|
|
|
|
def rows(conn, sql):
|
|
return [dict(row._mapping) for row in conn.exec_driver_sql(sql)]
|
|
|
|
|
|
def complete_command(conn, sql):
|
|
# BACKUP/RESTORE emit intermediate messages; consume all results before closing.
|
|
cursor = conn.connection.driver_connection.cursor()
|
|
try:
|
|
cursor.execute(sql)
|
|
while cursor.nextset():
|
|
pass
|
|
finally:
|
|
cursor.close()
|
|
|
|
|
|
def snapshot(conn, database):
|
|
conn.exec_driver_sql("USE " + identifier(database))
|
|
modules = rows(conn, """SELECT SCHEMA_NAME(o.schema_id) AS schema_name,
|
|
o.name, o.type, m.definition, m.uses_ansi_nulls, m.uses_quoted_identifier
|
|
FROM sys.objects o JOIN sys.sql_modules m ON m.object_id=o.object_id
|
|
ORDER BY o.object_id""")
|
|
tables = rows(conn, """SELECT s.name AS schema_name,t.name,
|
|
SUM(p.rows) AS row_count FROM sys.tables t JOIN sys.schemas s
|
|
ON s.schema_id=t.schema_id JOIN sys.partitions p ON p.object_id=t.object_id
|
|
AND p.index_id IN (0,1) GROUP BY s.name,t.name ORDER BY s.name,t.name""")
|
|
triggers = rows(conn, "SELECT name,is_disabled,parent_class_desc FROM sys.triggers")
|
|
return {"database": database, "modules": modules, "tables": tables,
|
|
"triggers": triggers,
|
|
"module_hash": hashlib.sha256(json.dumps(modules, sort_keys=True).encode()).hexdigest()}
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("phase", choices=["backup", "restore", "verify-sources"])
|
|
args = parser.parse_args()
|
|
config = load_db_config(ADMIN_CONFIG)
|
|
if not config:
|
|
raise RuntimeError("Missing local administrator configuration")
|
|
config["database"] = "master"
|
|
engine = create_engine(build_dsn_from_config(config).replace(
|
|
"mssql+aioodbc:", "mssql+pyodbc:"), isolation_level="AUTOCOMMIT",
|
|
connect_args={"timeout": 10})
|
|
REPORT.mkdir(exist_ok=True)
|
|
with engine.connect() as conn:
|
|
machine = conn.exec_driver_sql("SELECT CAST(SERVERPROPERTY('MachineName') AS nvarchar(128))").scalar_one()
|
|
if machine.lower() != os.environ["COMPUTERNAME"].lower():
|
|
raise RuntimeError("Refusing non-local SQL Server")
|
|
if args.phase == "verify-sources":
|
|
for source in PAIRS:
|
|
before = json.loads((REPORT / (source + "_before.json")).read_text())
|
|
after = snapshot(conn, source)
|
|
assert before["module_hash"] == after["module_hash"], source + " module changes"
|
|
assert before["tables"] == after["tables"], source + " row count changes"
|
|
assert before["triggers"] == after["triggers"], source + " trigger changes"
|
|
print(source, "original modules, trigger states and table row counts unchanged", flush=True)
|
|
return
|
|
for target in PAIRS.values():
|
|
if conn.exec_driver_sql("SELECT DB_ID(?)", (target,)).scalar_one() is not None:
|
|
raise RuntimeError("Target already exists; no overwrite: " + target)
|
|
sizes = rows(conn, """SELECT DB_NAME(database_id) db,name,type_desc,CAST(size AS bigint)*8192 AS bytes
|
|
FROM sys.master_files WHERE database_id IN (DB_ID('Mediseawall'), DB_ID('SAMA1'))""")
|
|
# Reserve enough for restored files plus an uncompressed data backup and margin.
|
|
required = sum(int(r["bytes"]) for r in sizes) + 10 * 1024**3
|
|
if args.phase == "backup":
|
|
for source in PAIRS:
|
|
conn.exec_driver_sql("USE " + identifier(source))
|
|
required += int(conn.exec_driver_sql("SELECT SUM(CAST(FILEPROPERTY(name,'SpaceUsed') AS bigint)*8192) FROM sys.database_files WHERE type=0").scalar_one())
|
|
conn.exec_driver_sql("USE [master]")
|
|
if shutil.disk_usage("D:\\").free < required:
|
|
raise RuntimeError("Insufficient conservative disk reserve")
|
|
BASE.mkdir(exist_ok=True)
|
|
BACKUPS.mkdir(exist_ok=True)
|
|
for source, target in PAIRS.items():
|
|
backup = BACKUPS / (source + "_copy_only.bak")
|
|
conn.exec_driver_sql("USE [master]")
|
|
if args.phase == "backup":
|
|
if backup.exists():
|
|
raise RuntimeError("Backup already exists: " + str(backup))
|
|
snap = snapshot(conn, source)
|
|
(REPORT / (source + "_before.json")).write_text(json.dumps(snap, indent=2), encoding="utf-8")
|
|
conn.exec_driver_sql("USE [master]")
|
|
print("BACKUP", source, "->", backup, flush=True)
|
|
complete_command(conn, "BACKUP DATABASE " + identifier(source) + " TO DISK=" + literal(backup)
|
|
+ " WITH COPY_ONLY, COMPRESSION, CHECKSUM, STATS=10")
|
|
print("VERIFY", source, flush=True)
|
|
complete_command(conn, "RESTORE VERIFYONLY FROM DISK=" + literal(backup) + " WITH CHECKSUM")
|
|
else:
|
|
if not backup.is_file():
|
|
raise RuntimeError("Missing verified backup: " + str(backup))
|
|
files = rows(conn, "RESTORE FILELISTONLY FROM DISK=" + literal(backup))
|
|
moves = []
|
|
for index, file in enumerate(files):
|
|
if file["Type"] not in ("D", "L"):
|
|
raise RuntimeError("Unsupported file type")
|
|
suffix = ".ldf" if file["Type"] == "L" else ".mdf"
|
|
path = BASE / (target + "_" + str(index) + suffix)
|
|
if path.exists():
|
|
raise RuntimeError("Target file already exists: " + str(path))
|
|
moves.append("MOVE " + literal(file["LogicalName"]) + " TO " + literal(path))
|
|
print("RESTORE", target, flush=True)
|
|
complete_command(conn, "RESTORE DATABASE " + identifier(target) + " FROM DISK=" + literal(backup)
|
|
+ " WITH " + ", ".join(moves) + ", RECOVERY, CHECKSUM, STATS=10")
|
|
conn.exec_driver_sql("ALTER DATABASE " + identifier(target) + " SET DISABLE_BROKER")
|
|
conn.exec_driver_sql("ALTER DATABASE " + identifier(target) + " SET TRUSTWORTHY OFF")
|
|
conn.exec_driver_sql("ALTER DATABASE " + identifier(target) + " SET DB_CHAINING OFF")
|
|
print("RESTORED", target, flush=True)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|