briga-core-api / apply_schema_updates.py
yabeskn's picture
fix: resolve PgBouncer prepared statement name collisions using prepared_statement_name_func
1bad990
Raw History Blame Contribute Delete
4.63 kB
import asyncio
import os
import uuid
from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.pool import NullPool
# Load settings from environment/env file
def get_env_db_urls():
db_url_async = None
sqlite_url_async = "sqlite+aiosqlite:///./brigawan_dev.db"
# 1. Load from environment variable
env_val = os.getenv("DATABASE_URL")
if env_val:
db_url_async = env_val
# 2. Try parsing .env file for DATABASE_URL=
env_path = os.path.join(os.path.dirname(__file__), ".env")
if os.path.exists(env_path):
with open(env_path, "r") as f:
for line in f:
# Remove comments and strip whitespace
clean_line = line.split("#", 1)[0].strip()
if clean_line.startswith("DATABASE_URL="):
val = clean_line.split("=", 1)[1].strip()
# Strip quotes if they exist
if val.startswith('"') and val.endswith('"'):
val = val[1:-1]
elif val.startswith("'") and val.endswith("'"):
val = val[1:-1]
if val:
db_url_async = val
return db_url_async, sqlite_url_async
async def update_database(db_url, is_sqlite=False):
print(f"\nChecking database: {db_url.split('@')[-1] if '@' in db_url else db_url}")
if is_sqlite:
engine = create_async_engine(db_url)
else:
engine = create_async_engine(
db_url,
poolclass=NullPool,
connect_args={
"statement_cache_size": 0,
"prepared_statement_cache_size": 0,
"prepared_statement_name_func": lambda: f"__asyncpg_{uuid.uuid4().hex}__"
}
)
try:
async with engine.connect() as conn:
# Check if talents table exists
if is_sqlite:
table_check = await conn.execute(text("SELECT name FROM sqlite_master WHERE type='table' AND name='talents'"))
table_exists = table_check.scalar() is not None
else:
table_check = await conn.execute(text("SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = 'public' AND tablename = 'talents'"))
table_exists = table_check.scalar() is not None
if not table_exists:
print("❌ Table 'talents' does not exist in this database yet. init_db will create it.")
return
# Check if linkedin_token column exists
if is_sqlite:
col_check = await conn.execute(text("PRAGMA table_info(talents)"))
cols = [r[1] for r in col_check.fetchall()]
has_column = "linkedin_token" in cols
else:
col_check = await conn.execute(text(
"SELECT column_name FROM information_schema.columns WHERE table_name='talents' AND column_name='linkedin_token'"
))
has_column = col_check.scalar() is not None
if not has_column:
print("➕ Column 'linkedin_token' is missing. Adding it...")
# SQLite and PostgreSQL both support ALTER TABLE ADD COLUMN
await conn.execute(text("ALTER TABLE talents ADD COLUMN linkedin_token TEXT"))
# Commit is handled automatically in autocommit mode, but let's make sure
await conn.execute(text("commit"))
print("✅ Column 'linkedin_token' added successfully!")
else:
print("✨ Column 'linkedin_token' already exists.")
except Exception as e:
print(f"❌ Error updating database: {e}")
finally:
await engine.dispose()
async def main():
pg_url, sqlite_url = get_env_db_urls()
# 1. Update PostgreSQL
if pg_url and "postgresql" in pg_url:
# Replace asyncpg dialect with psycopg_async if needed or use asyncpg
# settings.py uses postgresql+asyncpg which works fine with sqlalchemy async.
await update_database(pg_url, is_sqlite=False)
else:
print("⚠️ Warning: No PostgreSQL DATABASE_URL found. Skipping PG database check/updates.")
# 2. Update SQLite
if os.path.exists("./brigawan_dev.db") or os.path.exists("brigawan_dev.db"):
await update_database(sqlite_url, is_sqlite=True)
if __name__ == "__main__":
if os.name == 'nt':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())