To understand your dbt codebase and identify model dependencies/sources, follow this structured approach:
1. Use dbt's Built-in Documentation (Recommended)
Generate a detailed project documentation to extract model relationships and source mappings:
bash Copy code
# Generate documentation
dbt docs generate
# Serve the documentation locally
dbt docs serve
Open the generated index.html in a browser to explore the Lineage Graph , which visually shows model dependencies and source relationships.
2. Automated Analysis with Python Script
If you prefer a programmatic approach, use this Python script to scan your dbt project:
python Copy code
import os
import re
import yaml
from pathlib import Path
def analyze_dbt_project(models_dir):
model_sources = {}
# Scan SQL files for source references
for root, _, files in os.walk(models_dir):
for file in files:
if file.endswith(".sql"):
model_name = Path(file).stem
file_path = os.path.join(root, file)
with open(file_path, 'r') as f:
content = f.read()
# Find source references (e.g. {{ source('src_name', 'table') }})
sources = re.findall(r'\{\{\s*source\(\s*[\'\"](.*?)[\'\"]\s*,\s*[\'\"](.*?)[\'\"]\s*\)\s*\}\}', content)
if sources:
model_sources[model_name] = {
'sources': sources,
'path': file_path
}
# Optional: Parse YAML files for model descriptions
# Add YAML parsing here if needed
return model_sources
# Usage
models_dir = "./models" # Update to your dbt models directory
analysis = analyze_dbt_project(models_dir)
# Print results
for model, data in analysis.items():
print(f"Model: {model}")
print(f" Sources: {data['sources']}")
print(f" Path: {data['path']}\n")
Output Example :
code Copy code
Model: customer_orders
Sources: [('raw_sales', 'orders'), ('raw_customers', 'customers')]
Path: ./models/marts/customer_orders.sql
3. AI-Powered Analysis
Use the MiniMax-AI to interpret the results or analyze specific code snippets:
Ask for Code Summarization :
Paste a model’s SQL code into the chat and ask:
“What does this SQL model do? List its input sources and transformations.”
Request Dependency Mapping :
Share the Python script’s output and ask:
“Explain the relationship between customer_orders and its sources.”
Schema Understanding :
If you have YAML schema files, ask:
“What is the purpose of the orders source table based on this schema definition?”
4. Key dbt Concepts to Know
Sources : Defined in YAML files (e.g., schema.yml) using sources blocks.
Ref Function : {{ ref('model_name') }} links models together.
Model Descriptions : Add description fields in YAML files for model purpose.
Final Recommendation
Start with dbt docs generate for a visual overview.
Use the Python script for a text-based report.
Ask the AI to clarify specific model logic or relationships.
This combination gives you both automation and AI-powered insights. Let me know if you need help adapting the script to your project structure!