32 lines
899 B
Python
32 lines
899 B
Python
import os
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def main() -> int:
|
|
schema_path = Path(__file__).resolve().parent.parent / 'db' / 'schema.sql'
|
|
if not schema_path.exists():
|
|
print(f'missing schema file: {schema_path}', file=sys.stderr)
|
|
return 1
|
|
dsn = os.getenv('DATABASE_URL', '')
|
|
if not dsn:
|
|
print('DATABASE_URL is not set', file=sys.stderr)
|
|
return 1
|
|
try:
|
|
import psycopg
|
|
except Exception:
|
|
print('psycopg is not installed; cannot apply schema directly', file=sys.stderr)
|
|
return 1
|
|
dsn = dsn.replace('postgresql+psycopg://', 'postgresql://')
|
|
sql = schema_path.read_text()
|
|
with psycopg.connect(dsn) as conn:
|
|
with conn.cursor() as cur:
|
|
cur.execute(sql)
|
|
conn.commit()
|
|
print(f'Applied schema from {schema_path}')
|
|
return 0
|
|
|
|
|
|
if __name__ == '__main__':
|
|
raise SystemExit(main())
|