-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdb.py
More file actions
58 lines (43 loc) · 1.8 KB
/
db.py
File metadata and controls
58 lines (43 loc) · 1.8 KB
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
53
54
55
56
57
58
"""Set up the database connection and session.""" ""
from collections.abc import AsyncGenerator
from typing import Any
from sqlalchemy import MetaData
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from sqlalchemy.orm import DeclarativeBase
DATABASE_URL = "postgresql+asyncpg://postgres:postgres@localhost/postgres"
# DATABASE_URL = "sqlite+aiosqlite:///./test.db" # noqa: ERA001
# Note that (as far as I can tell from the docs and searching) there is no need
# to add 'check_same_thread=False' to the sqlite connection string, as
# SQLAlchemy version 1.4+ will automatically add it for you when using SQLite.
class Base(DeclarativeBase):
"""Base class for SQLAlchemy models.
All other models should inherit from this class.
"""
metadata = MetaData(
naming_convention={
"ix": "ix_%(column_0_label)s",
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s",
}
)
async_engine = create_async_engine(DATABASE_URL, echo=False)
async_session = async_sessionmaker(async_engine, expire_on_commit=False)
async def get_db() -> AsyncGenerator[AsyncSession, Any]:
"""Get a database session.
To be used for dependency injection.
"""
async with async_session() as session, session.begin():
yield session
async def init_models() -> None:
"""Create tables if they don't already exist.
In a real-life example we would use Alembic to manage migrations.
"""
async with async_engine.begin() as conn:
# await conn.run_sync(Base.metadata.drop_all) # noqa: ERA001
await conn.run_sync(Base.metadata.create_all)