summit/backend/init_db.py

79 lines
2.5 KiB
Python

import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
import asyncio
import sys
import os
# Add backend directory to path so we can import app
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from app.core.config import settings
from app.models.base import Base
from app.models.peak import Peak
from app.models.route import Route
from app.models.camp import Camp
from app.core.database import engine
def create_database():
try:
print(f"Connecting to postgres on {settings.POSTGRES_SERVER}...")
conn = psycopg2.connect(
user=settings.POSTGRES_USER,
password=settings.POSTGRES_PASSWORD,
host=settings.POSTGRES_SERVER,
port=settings.POSTGRES_PORT,
dbname="postgres"
)
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = conn.cursor()
cur.execute(f"SELECT 1 FROM pg_catalog.pg_database WHERE datname = '{settings.POSTGRES_DB}'")
exists = cur.fetchone()
if not exists:
print(f"Creating database {settings.POSTGRES_DB}...")
cur.execute(f"CREATE DATABASE {settings.POSTGRES_DB}")
print("Database created.")
else:
print(f"Database {settings.POSTGRES_DB} already exists.")
cur.close()
conn.close()
except Exception as e:
print(f"Error creating database: {e}")
# Don't exit, maybe it already exists and connection failed for other reasons?
# But if connection failed, next steps will likely fail too.
def enable_postgis():
try:
print(f"Connecting to {settings.POSTGRES_DB} to enable PostGIS...")
conn = psycopg2.connect(
user=settings.POSTGRES_USER,
password=settings.POSTGRES_PASSWORD,
host=settings.POSTGRES_SERVER,
port=settings.POSTGRES_PORT,
dbname=settings.POSTGRES_DB
)
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = conn.cursor()
cur.execute("CREATE EXTENSION IF NOT EXISTS postgis;")
print("PostGIS extension enabled.")
cur.close()
conn.close()
except Exception as e:
print(f"Error enabling PostGIS: {e}")
async def create_tables():
print("Creating tables via SQLAlchemy...")
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
print("Tables created successfully.")
if __name__ == "__main__":
create_database()
enable_postgis()
asyncio.run(create_tables())