|
| 1 | +import os |
| 2 | +from typing import Any |
| 3 | + |
| 4 | +from pydantic import BaseModel |
| 5 | + |
| 6 | +from sqlspec import SQLSpec |
| 7 | +from sqlspec.adapters.asyncpg import AsyncpgConfig |
| 8 | + |
| 9 | +__all__ = ("User", "test_quickstart_5") |
| 10 | + |
| 11 | + |
| 12 | +class User(BaseModel): |
| 13 | + id: int |
| 14 | + name: str |
| 15 | + email: str |
| 16 | + |
| 17 | + |
| 18 | +def _pool_config() -> "dict[str, Any]": |
| 19 | + return { |
| 20 | + "host": os.getenv("SQLSPEC_QUICKSTART_PG_HOST", "localhost"), |
| 21 | + "port": int(os.getenv("SQLSPEC_QUICKSTART_PG_PORT", "5432")), |
| 22 | + "user": os.getenv("SQLSPEC_QUICKSTART_PG_USER", "postgres"), |
| 23 | + "password": os.getenv("SQLSPEC_QUICKSTART_PG_PASSWORD", "postgres"), |
| 24 | + "database": os.getenv("SQLSPEC_QUICKSTART_PG_DATABASE", "mydb"), |
| 25 | + } |
| 26 | + |
| 27 | + |
| 28 | +async def _seed_users(session: Any) -> None: |
| 29 | + await session.execute( |
| 30 | + """ |
| 31 | + CREATE TABLE IF NOT EXISTS users ( |
| 32 | + id INTEGER PRIMARY KEY, |
| 33 | + name TEXT NOT NULL, |
| 34 | + email TEXT NOT NULL |
| 35 | + ) |
| 36 | + """ |
| 37 | + ) |
| 38 | + await session.execute("TRUNCATE TABLE users") |
| 39 | + await session.execute("INSERT INTO users (id, name, email) VALUES ($1, $2, $3)", 1, "Alice", "alice@example.com") |
| 40 | + |
| 41 | + |
| 42 | +async def test_quickstart_5() -> None: |
| 43 | + db_manager = SQLSpec() |
| 44 | + db = db_manager.add_config(AsyncpgConfig(pool_config=_pool_config())) |
| 45 | + |
| 46 | + async with db_manager.provide_session(db) as session: |
| 47 | + await _seed_users(session) |
| 48 | + |
| 49 | + # PostgreSQL uses $1, $2 for parameters instead of ? |
| 50 | + user = await session.select_one("SELECT * FROM users WHERE id = $1", 1, schema_type=User) |
| 51 | + print(f"User: {user.name}") |
| 52 | + |
| 53 | + assert user == User(id=1, name="Alice", email="alice@example.com") |
0 commit comments