-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbackup_database.py
More file actions
74 lines (56 loc) · 2.02 KB
/
Copy pathbackup_database.py
File metadata and controls
74 lines (56 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import os
import sqlite3
import sys
from datetime import datetime
import dotenv
dotenv.load_dotenv()
def backup_database(db_path, backup_path):
"""Backup the database at db_path."""
conn = None
if not os.path.exists(db_path):
print(f"Database not found: {db_path}")
return False
if not os.path.exists(backup_path):
os.makedirs(backup_path)
try:
date_and_time = datetime.now().strftime("%Y%m%d-%H%M%S")
db_filename = os.path.basename(db_path)
backup_path = f"{backup_path}/{date_and_time}.{db_filename}.backup"
conn = sqlite3.connect(db_path)
with sqlite3.connect(backup_path) as backup_conn:
conn.backup(backup_conn)
print(f"Database backed up successfully to: {backup_path}")
return True
except Exception as e:
print(f"Error during backup: {e}")
return False
finally:
if conn:
conn.close()
def main():
"""Main entry point."""
try:
pacs_db_path = os.getenv("PACS_DB_PATH")
mwl_db_path = os.getenv("MWL_DB_PATH")
backup_path = os.getenv("BACKUP_PATH", "./backups")
print("Starting database backup...")
print("PACS_DB_PATH:", pacs_db_path, "MWL_DB_PATH:", mwl_db_path)
success = True
if pacs_db_path:
print(f"Backing up PACS database: {pacs_db_path} to {backup_path}")
success = success and backup_database(pacs_db_path, backup_path)
else:
print("PACS_DB_PATH not set, skipping PACS database backup")
if mwl_db_path:
print(f"Backing up MWL database: {mwl_db_path} to {backup_path}")
success = success and backup_database(mwl_db_path, backup_path)
else:
print("MWL_DB_PATH not set, skipping MWL database backup")
sys.exit(0 if success else 1)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()