Fix schema init: use psycopg2 directly to bypass SQLAlchemy param parsing

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
jtricerolph 2026-07-05 09:18:37 +00:00
parent c11914a66b
commit 3e9442b1b9

View file

@ -29,19 +29,23 @@ from scheduler import start_scheduler, shutdown_scheduler
@asynccontextmanager
async def lifespan(app: FastAPI):
# Apply database schema (idempotent CREATE TABLE IF NOT EXISTS)
# Uses exec_driver_sql to bypass SQLAlchemy parameter parsing — schema.sql
# contains PL/pgSQL with $1/$2 syntax that text() misinterprets as bindparams.
# Uses psycopg2 directly — schema.sql contains PL/pgSQL with $1/$2 syntax
# that SQLAlchemy text() misinterprets as bindparams.
try:
import os
from database import sync_engine
import os, psycopg2
from database import DATABASE_URL
schema_path = os.path.join(os.path.dirname(__file__), 'schema.sql')
if os.path.exists(schema_path):
with open(schema_path) as f:
sql = f.read()
with sync_engine.connect() as conn:
conn.exec_driver_sql(sql)
conn.commit()
logging.getLogger(__name__).info("Schema applied successfully")
conn = psycopg2.connect(DATABASE_URL)
try:
conn.autocommit = True
with conn.cursor() as cur:
cur.execute(sql)
logging.getLogger(__name__).info("Schema applied successfully")
finally:
conn.close()
except Exception as e:
logging.getLogger(__name__).warning(f"Schema init failed: {e}")