Commit d215c77a authored by Jakob Moser's avatar Jakob Moser
Browse files

Add db config

parent 057a5e33
Loading
Loading
Loading
Loading

clams/db_config.py

0 → 100644
+28 −0
Original line number Diff line number Diff line
import json
from pathlib import Path
from typing import Optional


def get_database_uri(instance_path: Path) -> str:
    """
    Get the URI to the application database for use with SQLAlchemy.

    1. If ./instance/db.conf.json contains a "SQLALCHEMY_DATABASE_URI" key, this URI is returned.
    2. Otherwise, a URI pointing to the SQLite database ./instance/clams.db is returned.
    """
    return load_uri_from_config(instance_path / "db.conf.json") or get_uri_for_sqlite(
        instance_path / "clams.db"
    )


def get_uri_for_sqlite(db_path: Path) -> str:
    return f"sqlite+pysqlite:///{db_path.absolute().resolve()}"


def load_uri_from_config(db_conf_json: Path) -> Optional[str]:
    try:
        with open(db_conf_json) as f:
            db_conf = json.load(f)
            return db_conf["SQLALCHEMY_DATABASE_URI"]
    except (FileNotFoundError, KeyError):
        return None