TorbatYar/backend/services/identity-access/scripts/ensure_db.py
Mortezakoohjani 800b0ba2c5 Deploy TorbatYar for torbatyar.ir with nginx multi-tenant routing.
Wire production domain, CORS for tenant subdomains, celery volume mounts, and nginx reverse proxy configs for apex, API, identity, auth, and wildcard tenants.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-21 21:43:33 +03:30

46 lines
1.4 KiB
Python

"""اطمینان از وجود دیتابیس identity_access_db قبل از migration.
اگر volume قبلی PostgreSQL قبل از init-dbs.sql ساخته شده باشد،
این اسکریپت دیتابیس را در صورت نبود ایجاد می‌کند.
"""
from __future__ import annotations
import os
import sys
from urllib.parse import urlparse
def main() -> None:
sync_url = os.environ.get("DATABASE_URL_SYNC", "")
if not sync_url:
print("DATABASE_URL_SYNC not set", file=sys.stderr)
return
parsed = urlparse(sync_url.replace("+psycopg", ""))
db_name = (parsed.path or "").lstrip("/") or "identity_access_db"
import psycopg
conn = psycopg.connect(
host=parsed.hostname or "localhost",
port=parsed.port or 5432,
user=parsed.username,
password=parsed.password,
dbname="postgres",
autocommit=True,
)
try:
with conn.cursor() as cur:
cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", (db_name,))
if cur.fetchone() is None:
cur.execute(f'CREATE DATABASE "{db_name}"')
print(f"Created database: {db_name}")
else:
print(f"Database exists: {db_name}")
finally:
conn.close()
if __name__ == "__main__":
main()