Skip to content

Commit 75f9e23

Browse files
authored
add an option to goose runner to run migrations only if db is empty (Netflix#307)
1 parent f4ba47c commit 75f9e23

File tree

1 file changed

+41
-2
lines changed

1 file changed

+41
-2
lines changed

run_goose.py

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,35 @@
1-
from subprocess import Popen
21
import os
2+
import sys
3+
import argparse
4+
from subprocess import Popen
35
from urllib.parse import quote
6+
import psycopg2
7+
8+
9+
def check_if_goose_table_exists(db_connection_string: str):
10+
conn = psycopg2.connect(db_connection_string)
11+
cur = conn.cursor()
12+
try:
13+
cur.execute("SELECT schemaname,tablename FROM pg_tables")
14+
tables = [name for schema, name in cur.fetchall() if schema == "public"]
15+
if "goose_db_version" not in tables:
16+
print(
17+
f"Goose migration table not found among tables in schema public. Found: {', '.join(tables)}",
18+
file=sys.stderr,
19+
)
20+
return False
21+
else:
22+
print(f"Goose migration table found in schema public", file=sys.stderr)
23+
return True
24+
finally:
25+
conn.close()
26+
27+
28+
def main():
29+
parser = argparse.ArgumentParser(description="Run goose migrations")
30+
parser.add_argument("--only-if-empty-db", default=False, action="store_true")
31+
args = parser.parse_args()
432

5-
if __name__ == "__main__":
633
db_connection_string = "postgresql://{}:{}@{}:{}/{}?sslmode=disable".format(
734
quote(os.environ["MF_METADATA_DB_USER"]),
835
quote(os.environ["MF_METADATA_DB_PSWD"]),
@@ -11,6 +38,14 @@
1138
os.environ["MF_METADATA_DB_NAME"],
1239
)
1340

41+
if args.only_if_empty_db:
42+
if check_if_goose_table_exists(db_connection_string):
43+
print(
44+
f"Skipping migrations since --only-if-empty-db flag is used",
45+
file=sys.stderr,
46+
)
47+
sys.exit(0)
48+
1449
p = Popen(
1550
[
1651
"/go/bin/goose",
@@ -23,3 +58,7 @@
2358
)
2459
if p.wait() != 0:
2560
raise Exception("Failed to run initial migration")
61+
62+
63+
if __name__ == "__main__":
64+
main()

0 commit comments

Comments
 (0)