File size: 1,742 Bytes
e0381fc
 
 
 
 
 
 
 
fad3958
e0381fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b45d578
 
e0381fc
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import asyncio
import os
from sqlmodel import SQLModel
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.pool import NullPool
from dotenv import load_dotenv

# Load environment variables
load_dotenv(".env")

# Get database URL from environment
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql+asyncpg://user:pass@localhost/dbname")

# Handle URL conversion for asyncpg compatibility
database_url = DATABASE_URL
if database_url.startswith("postgresql://") and not database_url.startswith("postgresql+asyncpg://"):
    database_url = database_url.replace("postgresql://", "postgresql+asyncpg://", 1)

# asyncpg doesn't support sslmode/channel_binding in the URL query string the same way
# For Neon DB, we need to strip query parameters that asyncpg can't handle
# This is the same approach used in test_conn.py which works
if "?" in database_url:
    # Extract the base URL without query parameters for asyncpg compatibility
    base_url = database_url.split("?")[0]
    database_url = base_url

# Create engine directly with no connection pooling for Neon serverless
engine = create_async_engine(
    database_url,
    echo=False,
    future=True,
    poolclass=NullPool,  # Use null pool for serverless
    connect_args={
        "server_settings": {
            "application_name": "hack-2-web-app",
        }
    }
)

# Important: Import models so SQLModel knows about them
from models.task import Task
from models.user import User

async def init_db():
    async with engine.begin() as conn:
        # Create all tables defined in SQLModel.metadata
        await conn.run_sync(SQLModel.metadata.create_all)
    print("Database tables created successfully.")

if __name__ == "__main__":
    asyncio.run(init_db())