dbt's manifest compiled at start-up for the deployment's engine; the image carries the dbt environments
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
"""dbt's manifest for the deployment's engine.
|
||||
|
||||
The measures are served from `manifest.json` (`DBT_MANIFEST`), whose compiled SQL is the dialect of the dbt target it
|
||||
was compiled with. The image ships SQLite's; on another engine the entrypoint runs this module, which compiles the
|
||||
project in `TRANSFORMATION_DIR` against the configured databases (the adapters for MySQL, PostgreSQL and SQL Server
|
||||
open a connection to compile) and prints the path of the manifest to serve. On SQLite it prints nothing: the image's
|
||||
manifest is the right one.
|
||||
|
||||
The three domains must share one engine: one manifest covers every domain's models.
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy.engine import make_url
|
||||
|
||||
DOMAINS = ("cacu", "cama", "tea")
|
||||
TARGETS = {"sqlite": "sqlite", "mssql": "sqlserver", "postgresql": "postgres", "mysql": "mysql", "mariadb": "mysql"}
|
||||
|
||||
|
||||
def target_of(urls: dict[str, str]) -> str:
|
||||
"""The dbt target the domains' database URLs share. `ValueError` for an engine dbt has no target for, or when
|
||||
the domains don't share one engine."""
|
||||
targets = {domain: TARGETS.get(make_url(url).get_backend_name()) for domain, url in urls.items()}
|
||||
if unknown := [domain for domain, target in targets.items() if target is None]:
|
||||
raise ValueError(f"no dbt target for the engine of {', '.join(unknown)}")
|
||||
if len(set(targets.values())) != 1:
|
||||
raise ValueError("the domains' databases must be on one engine: one manifest serves the three domains")
|
||||
return next(iter(targets.values()))
|
||||
|
||||
|
||||
def environment(urls: dict[str, str], target: str) -> dict[str, str]:
|
||||
"""What `Transformation/profiles.yml` reads: the server and credentials from CaCu's URL (one server for the three
|
||||
domains), each domain's database name, and on SQLite each domain's file."""
|
||||
env: dict[str, str] = {}
|
||||
for domain, url in urls.items():
|
||||
parsed = make_url(url)
|
||||
if target == "sqlite":
|
||||
env[f"{domain.upper()}_DB_PATH"] = parsed.database or f"{domain}.db"
|
||||
else:
|
||||
env[f"{domain.upper()}_DBT_DATABASE"] = parsed.database or domain
|
||||
first = make_url(urls["cacu"])
|
||||
if target != "sqlite":
|
||||
env["DBT_HOST"] = first.host or "localhost"
|
||||
if first.port:
|
||||
env["DBT_PORT"] = str(first.port)
|
||||
env["DBT_USER"] = first.username or ""
|
||||
env["DBT_PASSWORD"] = first.password or ""
|
||||
return env
|
||||
|
||||
|
||||
def dbt_executable(root: Path, target: str) -> Path:
|
||||
"""dbt-mysql runs on an older dbt-core, so it lives in its own environment next to the main one."""
|
||||
return root / (".venv-mysql" if target == "mysql" else ".venv") / "bin" / "dbt"
|
||||
|
||||
|
||||
def compile_manifest(root: Path, target: str, env: dict[str, str], out_dir: Path) -> Path:
|
||||
"""Compiles every model with placeholders for the question's parameters (`--no-introspect`: the target's
|
||||
tables needn't exist yet) and returns the manifest's path."""
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
command = [str(dbt_executable(root, target)), "compile", "--project-dir", str(root), "--profiles-dir", str(root),
|
||||
"--profile", "cacu", "--target", target, "--no-introspect", "--target-path", str(out_dir)]
|
||||
subprocess.run(command, check=True, env={**os.environ, **env}, stdout=sys.stderr)
|
||||
return out_dir / "manifest.json"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
from persistance.settings import settings
|
||||
|
||||
urls = {domain: getattr(settings, f"{domain}_database_url") for domain in DOMAINS}
|
||||
target = target_of(urls)
|
||||
if target == "sqlite":
|
||||
return 0
|
||||
root = Path(os.environ.get("TRANSFORMATION_DIR") or Path(__file__).resolve().parents[2] / "Transformation")
|
||||
out_dir = Path(os.environ.get("DBT_MANIFEST_DIR", "/data/dbt"))
|
||||
print(compile_manifest(root, target, environment(urls, target), out_dir))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user