File size: 839 Bytes
2a8ebf2
4adfcf2
 
 
 
2a8ebf2
4adfcf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""SQLAlchemy connection helpers for reading SQLite market data."""

from __future__ import annotations

from contextlib import contextmanager
from sqlalchemy import create_engine, event


def _engine(database_url: str):
    engine = create_engine(database_url, connect_args={"timeout": 30})

    @event.listens_for(engine, "connect")
    def _configure_sqlite(dbapi_connection, _):
        cursor = dbapi_connection.cursor()
        cursor.execute("PRAGMA foreign_keys = ON")
        cursor.execute("PRAGMA journal_mode = WAL")
        cursor.execute("PRAGMA busy_timeout = 30000")
        cursor.close()

    return engine


@contextmanager
def read_connection(database_url: str):
    engine = _engine(database_url)
    try:
        with engine.connect() as connection:
            yield connection
    finally:
        engine.dispose()