File size: 1,017 Bytes
bef5e76
 
 
 
08df5ae
bef5e76
 
 
 
 
 
 
 
 
 
 
 
 
08df5ae
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
"""Database initialization."""

from sqlalchemy import text
from src.db.postgres.connection import engine, Base
from src.db.postgres.models import Document, Room, ChatMessage, User


async def init_db():
    """Initialize database tables and required extensions."""
    async with engine.begin() as conn:
        # Create pgvector extension using two separate statements.
        # Must NOT be combined into one string — asyncpg rejects multi-statement
        # prepared statements (langchain_postgres bug workaround via create_extension=False).
        await conn.execute(text("SELECT pg_advisory_xact_lock(1573678846307946496)"))
        await conn.execute(text("CREATE EXTENSION IF NOT EXISTS vector"))

        # Create application tables
        await conn.run_sync(Base.metadata.create_all)

        # Schema migrations (idempotent — safe to run on every startup)
        await conn.execute(text(
            "ALTER TABLE rooms ADD COLUMN IF NOT EXISTS status VARCHAR NOT NULL DEFAULT 'active'"
        ))