File size: 1,577 Bytes
a783939
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from sqlalchemy import create_engine, event
from sqlalchemy.orm import sessionmaker

from ..config import settings
from .models import Base

_connect_args = {"check_same_thread": False} if settings.db_url.startswith("sqlite") else {}
engine = create_engine(
    settings.db_url,
    connect_args=_connect_args,
    echo=False,
    future=True,
    pool_pre_ping=True,
)

if settings.db_url.startswith("sqlite"):
    @event.listens_for(engine, "connect")
    def _tune_sqlite(dbapi_connection, _):
        """
        Apply SQLite tuning pragmas on every new connection:

        * WAL journaling — better concurrent read/write, dramatically reduces
          ``database is locked`` errors when multiple requests hit history.
        * synchronous=NORMAL — safe with WAL, ~2x faster commits than FULL.
        * foreign_keys=ON — needed for our ON DELETE CASCADE relationships.
        * temp_store=MEMORY — temp B-trees in RAM, faster ordering / grouping.
        * cache_size=-20000 — 20 MB page cache (negative = KiB), big help for
          history pagination workload.
        """
        cursor = dbapi_connection.cursor()
        cursor.execute("PRAGMA journal_mode=WAL")
        cursor.execute("PRAGMA synchronous=NORMAL")
        cursor.execute("PRAGMA foreign_keys=ON")
        cursor.execute("PRAGMA temp_store=MEMORY")
        cursor.execute("PRAGMA cache_size=-20000")
        cursor.close()

SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=False)


def init_db() -> None:
    Base.metadata.create_all(engine)