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