refactoring-dbt-models

For safely refactoring dbt models and performing downstream impact analysis. Use when tasks mention “refactor/reorganize/extract/split/decompose/restructure”, when extracting CTEs into intermediate models or creating macros, when changing logic of models with downstream consumers, or when renaming columns/changing types/reorganizing model dependencies. Analyze all downstream dependencies before making changes.

Last repository push
GitHub Stars
137
Forks
13
Issues / PRs
5

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "refactoring-dbt-models" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-e65e8cfef5a60768cd36ea6e2826434aad3244f4c84f594582f5eca03dad175b. Verify the upstream source and version against https://github.com/AltimateAI/data-engineering-skills before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

For safely refactoring dbt models and performing downstream impact analysis. Use when tasks mention “refactor/reorganize/extract/split/decompose/restructure”, when extracting CTEs into intermediate models or creating macros, when changing logic of models with downstream consumers, or when renaming columns/changing types/reorganizing model dependencies. Analyze all downstream dependencies before making changes.

0 Downloads

Introduction source: third_party · AltimateAI · 0.0.1 Reference

SkillPi interpretation

Tasks
Find ALL downstream dependencies before changing. Refactor in small steps. Verify output after each change.**
Inputs and outputs
CRITICAL: Refactoring should not change output.** ```bash
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: refactoring-dbt-models
description: |
  Safely refactors dbt models with downstream impact analysis. Use when restructuring dbt models for:
  (1) Task mentions "refactor", "restructure", "extract", "split", "break into", or "reorganize"
  (2) Extracting CTEs to intermediate models or creating macros
  (3) Modifying model logic that has downstream consumers
  (4) Renaming columns, changing types, or reorganizing model dependencies
  Analyzes all downstream dependencies BEFORE making changes.

dbt Refactoring

Find ALL downstream dependencies before changing. Refactor in small steps. Verify output after each change.

Workflow

1. Analyze Current Model

cat models/<path>/<model_name>.sql

Identify refactoring opportunities:

  • CTEs longer than 50 lines → extract to intermediate model
  • Logic repeated across models → extract to macro
  • Multiple joins in sequence → split into steps
  • Complex WHERE clauses → extract to staging filter

2. Find All Downstream Dependencies

CRITICAL: Never refactor without knowing impact.

# Get full dependency tree (model and all its children)
dbt ls --select model_name+ --output list

# Find all models referencing this one
grep -r "ref('model_name')" models/ --include="*.sql"

Report to user: "Found X downstream models: [list]. These will be affected by changes."

3. Check What Columns Downstream Models Use

BEFORE changing any columns, check what downstream models reference:

# For each downstream model, check what columns it uses
cat models/<path>/<downstream_model>.sql | grep -E "model_name\.\w+|alias\.\w+"

If downstream models reference specific columns, you MUST ensure those columns remain available after refactoring.

4. Plan Refactoring Strategy

Opportunity Strategy
Long CTE Extract to intermediate model
Repeated logic Create macro in macros/
Complex join Split into intermediate models
Multiple concerns Separate into focused models

5. Execute Refactoring

Pattern: Extract CTE to Model

Before:

-- orders.sql (200 lines)
with customer_metrics as (
    -- 50 lines of complex logic
),
order_enriched as (
    select ...
    from orders
    join customer_metrics on ...
)
select * from order_enriched

After:

-- customer_metrics.sql (new file)
select
    customer_id,
    -- complex logic here
from {{ ref('customers') }}

-- orders.sql (simplified)
with order_enriched as (
    select ...
    from {{ ref('raw_orders') }} orders
    join {{ ref('customer_metrics') }} cm on ...
)
select * from order_enriched

Pattern: Extract to Macro

Before (repeated in multiple models):

case
    when amount < 0 then 'refund'
    when amount = 0 then 'zero'
    else 'positive'
end as amount_category

After:

-- macros/categorize_amount.sql
{% macro categorize_amount(column_name) %}
case
    when {{ column_name }} < 0 then 'refund'
    when {{ column_name }} = 0 then 'zero'
    else 'positive'
end
{% endmacro %}

-- In models:
{{ categorize_amount('amount') }} as amount_category

6. Validate Changes

# Compile to check syntax
dbt compile --select +model_name+

# Build entire lineage
dbt build --select +model_name+

# Check row counts (manual)
# Before: Record expected counts
# After: Verify counts match

7. Verify Output Matches Original

CRITICAL: Refactoring should not change output.

# Compare row counts before and after
dbt show --inline "select count(*) from {{ ref('model_name') }}"

# Spot check key values
dbt show --select <model_name> --limit 10

8. Update Downstream Models

If changing output columns:

  1. Update all downstream refs
  2. Update schema.yml documentation
  3. Re-run downstream tests

Refactoring Checklist

  • [ ] All downstream dependencies identified
  • [ ] User informed of impact scope
  • [ ] One change at a time
  • [ ] Compile passes after each change
  • [ ] Build passes after each change
  • [ ] Output validated (row counts match)
  • [ ] Documentation updated
  • [ ] Tests still pass

Common Refactoring Triggers

Symptom Refactoring
Model > 200 lines Extract CTEs to models
Same logic in 3+ models Extract to macro
5+ joins in one model Create intermediate models
Hard to understand Add CTEs with clear names
Slow performance Split to allow parallelization

Anti-Patterns

  • Refactoring without checking downstream impact
  • Making multiple changes at once
  • Not validating output matches after refactoring
  • Extracting prematurely (wait for 3+ uses)
  • Breaking existing tests without updating them

Current listing version

0.0.1

Verify the source revision ↗

Safety and assessment details

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value85/100

Highlights

  • 针对 dbt 模型重构这一数据工程高频需求,提供端到端解决方案
  • 涵盖从依赖分析、重构执行到输出验证的完整闭环流程
Trigger Precision90/100

Highlights

  • 触发条件清晰明确,覆盖重构、提取、拆分等典型场景
  • 关键词定义准确,边界清晰,不易误触或漏触
Structure and Standards95/100

Areas to improve

  • 文档长度略长 Reported severity: Minor

    SKILL.md 内容约 600 行,超出建议的 500 行上限

    Recommendation: 可考虑将部分示例或检查清单移至独立文件,保持主文档简洁

Highlights

  • 结构完整,包含工作流、模式、检查清单和反模式
  • 步骤划分清晰,有明确的出口条件和验证机制
Execution Reliability90/100

Highlights

  • 提供具体的 dbt 命令和验证步骤,确保重构安全
  • 强调下游影响分析和输出一致性验证,降低执行风险
Evidence Verifiability (mean of the first four)90/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.