2021-05-02 02:00:00+00:00

Documenting database models manually is a tedious task. Whenever fields are added or constraints change, developers must update diagrams. A cleaner solution is to write an automated UML Generator that parses python database files and exports visual graphs.

Using Python's built-in Abstract Syntax Tree (AST) module, we can read source files, identify class definitions, and compile DOT files.


1. Parsing Source Code using AST

The Python AST module allows inspecting the syntax tree of a script without executing the file, making it safe to run in CI pipelines:

# Abstract Syntax Tree Parser in Python
import ast

def parse_model_file(filepath):
    with open(filepath, "r") as f:
        node = ast.parse(f.read())
        
    for child in ast.iter_child_nodes(node):
        if isinstance(child, ast.ClassDef):
            # Print class name
            print(f"Class name detected: {child.name}")
            # Identify class properties
            for element in child.body:
                if isinstance(element, ast.Assign):
                    print(f"  Field: {element.targets[0].id}")

2. Automatic Visual Exports

The script exports these parsed classes to Graphviz syntax, compiling SVG diagrams during documentation phases in your repository build loop.

Walking `ast.ClassDef` Nodes to Extract ORM & NDB Field Graphs

Python's built-in ast.parse() module inspects source files statically without importing runtime dependencies or database credentials—making it safe to generate Mermaid/PlantUML ER diagrams in fast CI pipelines.


About the Author — Hire Freelance Programmer Aldian Fazrihady

Aldian Fazrihady is a Top-Rated Senior Freelance Programmer, Freelance Full Stack Developer, and AI Application Engineer with 15+ years of production software engineering experience and Google Cloud Professional Cloud Architect & Data Engineer certifications. He specializes in building custom LLM & autonomous AI agents, RAG pipelines, Next.js/React PWAs, Python (Django/FastAPI), Go microservices, and serverless cloud infrastructure on Google Cloud Run and AWS.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD via Polar) | View Live AI Portfolio | Portfolio Directory | Send a Direct Message

Related Engineering Articles

Freelance Programmer Specializations & Category Hubs