|
1 |
| -from subprocess import Popen |
2 | 1 | import os
|
| 2 | +import sys |
| 3 | +import argparse |
| 4 | +from subprocess import Popen |
3 | 5 | 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() |
4 | 32 |
|
5 |
| -if __name__ == "__main__": |
6 | 33 | db_connection_string = "postgresql://{}:{}@{}:{}/{}?sslmode=disable".format(
|
7 | 34 | quote(os.environ["MF_METADATA_DB_USER"]),
|
8 | 35 | quote(os.environ["MF_METADATA_DB_PSWD"]),
|
|
11 | 38 | os.environ["MF_METADATA_DB_NAME"],
|
12 | 39 | )
|
13 | 40 |
|
| 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 | + |
14 | 49 | p = Popen(
|
15 | 50 | [
|
16 | 51 | "/go/bin/goose",
|
|
23 | 58 | )
|
24 | 59 | if p.wait() != 0:
|
25 | 60 | raise Exception("Failed to run initial migration")
|
| 61 | + |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + main() |
0 commit comments