diff --git a/README.md b/README.md index 384ab66..4035be1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # dbterd -Generate the ERD-as-a-code ([DBML](https://dbdiagram.io/d), [Mermaid](https://mermaid-js.github.io/mermaid-live-editor/), [PlantUML](https://plantuml.com/ie-diagram), [GraphViz](https://graphviz.org/), [D2](https://d2lang.com/), [DrawDB](https://drawdb.vercel.app/)) from dbt artifact files (`dbt Core`) or from dbt metadata (`dbt Cloud`) +Generate the ERD-as-a-code ([DBML](https://dbdiagram.io/d), [Mermaid](https://mermaid-js.github.io/mermaid-live-editor/), [PlantUML](https://plantuml.com/ie-diagram), [GraphViz](https://graphviz.org/), [D2](https://d2lang.com/), [DrawDB](https://drawdb.vercel.app/), [JSON](https://json.org/)) from dbt artifact files (`dbt Core`) or from dbt metadata (`dbt Cloud`) Entity Relationships are configurably detected by ([docs](https://dbterd.datnguyen.de/latest/nav/guide/cli-references.html#dbterd-run-algo-a)): diff --git a/dbterd/adapters/targets/json.py b/dbterd/adapters/targets/json.py new file mode 100644 index 0000000..13b938b --- /dev/null +++ b/dbterd/adapters/targets/json.py @@ -0,0 +1,50 @@ +from typing import Optional, Tuple +import json + +from dbterd.adapters import adapter +from dbterd.types import Catalog, Manifest + + + +def run(manifest: Manifest, catalog: Catalog, **kwargs) -> Tuple[str, str]: + """Parse dbt artifacts and export Mermaid file + + Args: + manifest (dict): Manifest json + catalog (dict): Catalog json + + Returns: + Tuple(str, str): File name and the Mermaid content + """ + output_file_name = kwargs.get("output_file_name") or "output.json" + return (output_file_name, parse(manifest, catalog, **kwargs)) + + +def parse(manifest: Manifest, catalog: Catalog, **kwargs) -> str: + """Get the DBML content from dbt artifacts + + Args: + manifest (dict): Manifest json + catalog (dict): Catalog json + + Returns: + str: JSON content + """ + algo_module = adapter.load_algo(name=kwargs["algo"]) + tables, relationships = algo_module.parse( + manifest=manifest, catalog=catalog, **kwargs + ) + + json_data = {"tables": {}, "relationships": []} + for table in tables: + json_data["tables"][table.name] = {"columns": [{"name": x.name, "type": x.data_type} for x in table.columns]} + + + for rel in relationships: + json_data["relationships"].append({ + "from": rel.table_map[1], + "to": rel.table_map[0], + "type": rel.type + }) + + return json.dumps(json_data, indent=4) \ No newline at end of file