-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathmigrate-all.py
More file actions
executable file
·183 lines (147 loc) · 4.29 KB
/
Copy pathmigrate-all.py
File metadata and controls
executable file
·183 lines (147 loc) · 4.29 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#!/usr/bin/env python3
import atexit
import os
import shutil
import subprocess
import sys
import tempfile
from urllib.parse import urlparse
# Colors for output
RED = "\033[0;31m"
GREEN = "\033[0;32m"
YELLOW = "\033[1;33m"
BLUE = "\033[0;34m"
NC = "\033[0m" # No Color
# Database URLs
POSTGRES_URL = (
"postgresql://migration-user:migration-password@127.0.0.1:5432/migration-db?sslmode=disable"
)
MYSQL_URL = "mysql://migration-user:migration-password@127.0.0.1:3306/migration-db"
# Handle SQLite temp directory safely
SQLITE_DIR = tempfile.mkdtemp()
SQLITE_URL = f"sqlite:{SQLITE_DIR}/db.sqlite"
def cleanup():
"""Equivalent to the 'trap' in bash."""
if os.path.exists(SQLITE_DIR):
shutil.rmtree(SQLITE_DIR)
atexit.register(cleanup)
def log(msg, color=NC):
print(f"{color}{msg}{NC}")
def check_command(cmd_list, name):
"""
Checks connectivity using the provided command list.
Returns True if successful, False otherwise.
"""
try:
# Capture output to suppress it unless debugging is needed
subprocess.run(
cmd_list, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
log(f"✓ {name} is ready", GREEN)
return True
except (subprocess.CalledProcessError, FileNotFoundError):
log(f"ERROR: {name} is not running or accessible", RED)
return False
def run_dbmate(url):
"""
Runs dbmate drop, create, and up for the given URL.
Returns True on success.
"""
try:
# 1. Drop existing database (ignore errors if it doesn't exist)
# We suppress output to keep the console clean-ish, assuming
# 'dbmate drop' failing is often acceptable (e.g. first run).
subprocess.run(
["dbmate", "--url", url, "drop"],
check=False,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
# 2. Create fresh database
subprocess.run(["dbmate", "--url", url, "create"], check=True)
# 3. Run migrations
subprocess.run(["dbmate", "--url", url, "up"], check=True)
return True
except subprocess.CalledProcessError as e:
log(f"Migration failed during step '{e.cmd}': {e}", RED)
return False
def migrate_postgres():
log("1. Migrating PostgreSQL...", YELLOW)
parsed = urlparse(POSTGRES_URL)
cmd = [
"pg_isready",
"-h",
parsed.hostname,
"-p",
str(parsed.port),
"-U",
parsed.username,
]
if check_command(cmd, "PostgreSQL"):
if run_dbmate(POSTGRES_URL):
log("PostgreSQL migration complete.", GREEN)
print()
return True
else:
print()
return False
else:
# check_command logs the error
print()
return False
def migrate_mysql():
log("2. Migrating MySQL...", YELLOW)
parsed = urlparse(MYSQL_URL)
cmd = [
"mysqladmin",
"-h",
parsed.hostname,
"-P",
str(parsed.port),
"-u",
parsed.username,
f"--password={parsed.password}",
"ping",
]
if check_command(cmd, "MySQL"):
if run_dbmate(MYSQL_URL):
log("MySQL migration complete.", GREEN)
print()
return True
else:
print()
return False
else:
# check_command logs the error
print()
return False
def migrate_sqlite():
log("3. Migrating SQLite...", YELLOW)
if os.path.isdir(SQLITE_DIR):
log("✓ SQLite directory ready", GREEN)
if run_dbmate(SQLITE_URL):
log("SQLite migration complete.", GREEN)
print()
return True
else:
print()
return False
else:
log("SQLite directory error", RED)
print()
return False
def main():
log("Starting migrations for all detected database configurations...", BLUE)
print()
# Collect results
# Run migrations sequentially and fail immediately on error
if not migrate_postgres():
sys.exit(1)
if not migrate_mysql():
sys.exit(1)
if not migrate_sqlite():
sys.exit(1)
log("All requested migrations finished successfully.", GREEN)
sys.exit(0)
if __name__ == "__main__":
main()