35 lines
1.1 KiB
Python
35 lines
1.1 KiB
Python
from functools import cache
|
|
import dlt
|
|
from sqlalchemy import Engine, create_engine, event, make_url
|
|
from persistance.config import DATA_DIR, platform_url
|
|
|
|
SCHEMAS = ("bronze", "silver", "gold", "config")
|
|
|
|
|
|
def _sqlite(attach: bool) -> Engine:
|
|
eng = create_engine(platform_url())
|
|
|
|
@event.listens_for(eng, "connect")
|
|
def _setup(dbapi_connection, _record):
|
|
dbapi_connection.execute("PRAGMA journal_mode=WAL")
|
|
for schema in SCHEMAS if attach else ():
|
|
path = DATA_DIR / f"platform__{schema}.db"
|
|
dbapi_connection.execute(f"ATTACH DATABASE '{path}' AS {schema}")
|
|
dbapi_connection.execute(f"PRAGMA {schema}.journal_mode=WAL")
|
|
|
|
return eng
|
|
|
|
|
|
def platform():
|
|
if platform_url().startswith("sqlite"):
|
|
return dlt.destinations.sqlalchemy(_sqlite(attach=False))
|
|
return dlt.destinations.postgres(platform_url())
|
|
|
|
|
|
@cache
|
|
def engine() -> Engine:
|
|
url = platform_url()
|
|
if url.startswith("sqlite"):
|
|
return _sqlite(attach=True)
|
|
return create_engine(make_url(url).set(drivername="postgresql+psycopg2"))
|