Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(core): SQL DDL symbols and dbt lineage (#683)

Raghav Chamadiya312010445d86
diff --git a/README.md b/README.md
index 9e6fd4321..7df524ca8 100644
--- a/README.md
+++ b/README.md
@@ -355,7 +355,8 @@ Install from the Marketplace (search **Repowise**) or Open VSX, then run
|------|-----------|------------|
| **Full** | Python · TypeScript · JavaScript · Java · Kotlin · Go · Rust · C++ · C# | AST parsing, import resolution, named bindings, call resolution, heritage extraction, docstrings; multi-project workspace resolvers; framework-aware edges; per-language dynamic-hint extractors; **code-health markers** |
| **Good** | C · Ruby · Swift · Scala · PHP | AST parsing, import resolution, named bindings, call resolution, heritage (mixins / derive / extensions / traits), docstrings; dedicated workspace-aware resolvers; Rails / Laravel / TYPO3 framework edges; dynamic-hint extractors |
-| **Config / data** | OpenAPI · Protobuf · GraphQL · Dockerfile · Makefile · YAML · JSON · TOML · SQL · Terraform · Markdown · Shell | Included in the file tree; special handlers extract endpoints / targets where applicable |
+| **SQL / dbt** | `.sql` via sqlglot (postgres, mysql, tsql, clickhouse, ...) | Tables / views / functions / procedures as symbols with wiki pages; dbt projects get real `ref()` / `source()` lineage edges: model-level DAG, hotspots, co-change, ownership |
+| **Config / data** | OpenAPI · Protobuf · GraphQL · Dockerfile · Makefile · YAML · JSON · TOML · Terraform · Markdown · Shell | Included in the file tree; special handlers extract endpoints / targets where applicable |
| **Git-blame only** | Objective-C · Elixir · Erlang · Dart · Zig · Julia · Clojure · Haskell · OCaml · F# · … | Tracked in git history (blame, hotspots, co-change); no AST parsing yet |
Adding a language needs **one `.scm` query file and one config entry**, with no
diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.md
index 698cb163b..c18f45279 100644
--- a/docs/LANGUAGE_SUPPORT.md
+++ b/docs/LANGUAGE_SUPPORT.md
@@ -141,7 +141,7 @@ endpoints or targets where applicable.
| **TOML** | `.toml` | -- |
| **Markdown** | `.md` `.mdx` `.markdown` `.mdown` | -- |
| **AsciiDoc** | `.adoc` `.asciidoc` | -- |
-| **SQL** | `.sql` | -- |
+| **SQL** | `.sql` | Graduated: DDL symbols + dbt lineage, see [SQL + dbt](#sql--dbt) |
| **Shell** | `.sh` `.bash` `.zsh` | -- |
### Partial (Luau, Roblox)
@@ -178,6 +178,35 @@ honest file-to-file dependencies, no symbol-level claims.
| **Erlang** | `.erl` `.hrl` | `-include` / `-include_lib` / `-behaviour` + module-qualified calls (`mod:fun(`) -> `-module()` index; qualified calls are strict local-hit-or-drop (never mint externals) |
| **F#** | `.fs` `.fsi` `.fsx` | `open` -> file-level `namespace`/`module` index (unambiguous single-file declarations only), plus the fsproj `<Compile Include>` compile-order dependency spine (a real F# constraint: files may only reference earlier files) |
+### SQL + dbt
+
+SQL is parsed by a dedicated special handler (sqlglot, multi-dialect and
+error-tolerant) rather than tree-sitter, plus the lightweight import tier
+for dbt lineage. Two independent capabilities:
+
+**DDL symbols (any `.sql` file).** `CREATE TABLE` / `VIEW` /
+`MATERIALIZED VIEW` -> class-kind symbols with columns in the signature;
+`CREATE FUNCTION` / `PROCEDURE` -> function-kind symbols. Tables get wiki
+pages, search hits, and `get_symbol` lookups (`schema.sql::public.users`).
+Indexes and triggers are deliberately not symbols. Dialect is sqlglot's
+permissive default; set `sql_dialect` in `.repowise/config.yaml`
+(`postgres`, `mysql`, `tsql`, `clickhouse`, ...) for dialect-specific
+syntax like PL/pgSQL `$$` bodies. Any parse problem degrades the file to
+plain passthrough: no symbols, never a crash, never a guess.
+
+**dbt lineage (gated on `dbt_project.yml`).** `{{ ref('model') }}`,
+`{{ ref('package', 'model') }}`, and `{{ source('schema', 'table') }}`
+become real import edges: refs resolve against a per-project model-name
+index built from `dbt_project.yml`'s `model-paths` / `seed-paths` /
+`snapshot-paths` (defaults `models/` `seeds/` `snapshots/`; `.csv` seeds
+are ref-able), sources become typed `external:source:<schema>.<table>`
+nodes marking the warehouse boundary, and refs to uninstalled packages
+become `external:dbt:<package>.<model>`. When two projects in a monorepo
+declare the same model name, the importer's own project wins; two-arg
+refs prefer the project whose declared `name` matches. Everything that
+rides the import graph falls out free: model-level lineage, hotspots,
+co-change, ownership, and Leiden communities of the DAG.
+
### Structural (git + file tree only)
These languages are tracked in git history (blame, hotspot analysis,
@@ -200,7 +229,7 @@ File discovered by FileTraverser
Extension/filename -> LanguageTag (via LanguageRegistry)
|
+-- Config/data language? -> empty ParsedFile (passthrough)
- +-- Special format? -> special_handlers.py (OpenAPI/Dockerfile/Makefile)
+ +-- Special format? -> special_handlers.py (OpenAPI/Dockerfile/Makefile/SQL)
+-- Has grammar? -> tree-sitter AST parsing
|
v
@@ -226,8 +255,9 @@ Extension/filename -> LanguageTag (via LanguageRegistry)
Go: go.mod module path stripping
Rust: crate::/self::/super::, mod.rs probing
C/C++: compile_commands.json include directories
- Lightweight tier (Elixir/Dart/Clojure/Haskell/Erlang/F#):
+ Lightweight tier (Elixir/Dart/Clojure/Haskell/Erlang/F#/dbt SQL):
regex-extracted imports vs a declared-module-name index
+ (dbt: ref()/source() vs a per-project model-name index)
Other: stem-map fallback (filename matching)
|
v
@@ -643,3 +673,4 @@ edits. The current coverage:
| Dart | Good | Lightweight tier shipped; AST upgrade planned (`tree-sitter-dart` available) |
| Elixir | Good | Lightweight tier shipped; AST upgrade planned (`tree-sitter-elixir` available) |
| F# | Good | Lightweight tier shipped; AST upgrade planned (`tree-sitter-f-sharp` available) |
+| SQL / dbt | -- | DDL symbols (sqlglot) + dbt lineage shipped; next: app-to-database contracts (workspace data extractor), then precision-gated SQL health markers |
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/sql.py b/packages/core/src/repowise/core/ingestion/languages/specs/sql.py
index 4f54980bc..e731927c2 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/sql.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/sql.py
@@ -8,4 +8,7 @@ SPEC = LanguageSpec(
extensions=frozenset({".sql"}),
is_code=False,
is_passthrough=True,
+ # dbt ref()/source() resolution via the lightweight tier: real edges
+ # inside dbt projects, nothing claimed for plain SQL files.
+ import_support="partial",
)
diff --git a/packages/core/src/repowise/core/ingestion/lightweight_imports/__init__.py b/packages/core/src/repowise/core/ingestion/lightweight_imports/__init__.py
index 0986b4b89..77d5f2e3c 100644
--- a/packages/core/src/repowise/core/ingestion/lightweight_imports/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/lightweight_imports/__init__.py
@@ -20,6 +20,7 @@ from .elixir import extract_elixir_imports
from .erlang import extract_erlang_imports
from .fsharp import extract_fsharp_imports
from .haskell import extract_haskell_imports
+from .sql import extract_dbt_imports
ExtractorFn = Callable[[str], list[Import]]
@@ -30,6 +31,9 @@ _EXTRACTORS: dict[str, ExtractorFn] = {
"haskell": extract_haskell_imports,
"erlang": extract_erlang_imports,
"fsharp": extract_fsharp_imports,
+ # dbt {{ ref() }} / {{ source() }}, the only import system .sql files
+ # have; plain SQL contains neither form, so this is a no-op outside dbt.
+ "sql": extract_dbt_imports,
}
LIGHTWEIGHT_IMPORT_LANGUAGES = frozenset(_EXTRACTORS)
diff --git a/packages/core/src/repowise/core/ingestion/lightweight_imports/sql.py b/packages/core/src/repowise/core/ingestion/lightweight_imports/sql.py
new file mode 100644
index 000000000..929f449be
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/lightweight_imports/sql.py
@@ -0,0 +1,72 @@
+"""Regex import extraction for dbt SQL models.
+
+dbt models are ``.sql`` files with an explicit import system rendered by
+Jinja at compile time:
+
+- ``{{ ref('model') }}`` / ``{{ ref('package', 'model') }}`` — model-to-model
+ dependency (the two-argument form names a package first).
+- ``{{ source('schema', 'table') }}`` — dependency on a table declared in a
+ sources yml, by definition outside the project.
+
+Plain (non-dbt) SQL files contain neither form, so extraction self-gates:
+no Jinja, no imports. ``source()`` targets are encoded as
+``source:<schema>.<table>`` module paths; the resolver turns them into
+typed ``external:source:`` nodes so the graph shows the warehouse boundary.
+"""
+
+from __future__ import annotations
+
+import re
+
+from ..models import Import
+
+# ref('model') / ref('pkg', 'model') inside a Jinja expression ({{ … }}) or
+# statement ({% set x = ref('y') %}). The opening delimiter is required —
+# a bare ref() call in plain SQL is a UDF, not a dbt dependency — but the
+# closing delimiter is not: refs are routinely piped ({{ ref('x') | … }})
+# or wrapped in further calls. Trailing kwargs (version=2) are tolerated.
+_REF_RE = re.compile(
+ r"\{[\{%][^{}]*?\bref\(\s*['\"]([^'\"]+)['\"]"
+ r"(?:\s*,\s*['\"]([^'\"]+)['\"])?"
+)
+
+_SOURCE_RE = re.compile(r"\{[\{%][^{}]*?\bsource\(\s*['\"]([^'\"]+)['\"]\s*,\s*['\"]([^'\"]+)['\"]")
+
+
+def extract_dbt_imports(text: str) -> list[Import]:
+ imports: list[Import] = []
+ seen: set[str] = set()
+
+ for match in _REF_RE.finditer(text):
+ first, second = match.group(1), match.group(2)
+ # Two positional strings = ref('package', 'model').
+ module = f"{first}.{second}" if second else first
+ if module in seen:
+ continue
+ seen.add(module)
+ imports.append(
+ Import(
+ raw_statement=match.group(0).split("\n", 1)[0].strip(),
+ module_path=module,
+ imported_names=[],
+ is_relative=False,
+ resolved_file=None,
+ )
+ )
+
+ for match in _SOURCE_RE.finditer(text):
+ module = f"source:{match.group(1)}.{match.group(2)}"
+ if module in seen:
+ continue
+ seen.add(module)
+ imports.append(
+ Import(
+ raw_statement=match.group(0).split("\n", 1)[0].strip(),
+ module_path=module,
+ imported_names=[],
+ is_relative=False,
+ resolved_file=None,
+ )
+ )
+
+ return imports
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 110061a4e..6342519b9 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -69,6 +69,7 @@ from .parser_helpers import (
_run_query,
)
from .python_local_refs import extract_python_local_refs
+from .special_handlers import SPECIAL_HANDLER_LANGUAGES, parse_special
log = structlog.get_logger(__name__)
@@ -226,6 +227,14 @@ class ASTParser:
def parse_file(self, file_info: FileInfo, source: bytes) -> ParsedFile:
"""Parse *source* bytes and return a fully populated ParsedFile."""
lang = file_info.language
+
+ # Non-tree-sitter formats (OpenAPI, Dockerfile, Makefile, SQL) parse
+ # via dedicated handlers. Checked before the grammar lookup: none of
+ # these tags carry a LanguageConfig, so the no-grammar fallback below
+ # would otherwise swallow them.
+ if lang in SPECIAL_HANDLER_LANGUAGES:
+ return parse_special(file_info, source, lang)
+
config = LANGUAGE_CONFIGS.get(lang)
# .tsx files need the JSX-aware grammar; tree-sitter-typescript's
# default `language_typescript` errors out on every `<Component />`
@@ -255,12 +264,6 @@ class ASTParser:
parse_errors=[],
)
- # Delegate to special handlers for non-tree-sitter formats
- if lang in ("openapi", "dockerfile", "makefile"):
- from .special_handlers import parse_special
-
- return parse_special(file_info, source, lang)
-
parser = Parser(language)
tree = parser.parse(source)
src = source.decode("utf-8", errors="replace")
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py b/packages/core/src/repowise/core/ingestion/resolvers/__init__.py
index e6d76b8b5..07ad52ebf 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/__init__.py
@@ -23,6 +23,7 @@ from .python import resolve_python_import
from .ruby import resolve_ruby_import
from .rust import resolve_rust_import
from .scala import resolve_scala_import
+from .sql import resolve_dbt_import
from .swift import resolve_swift_import
from .typescript import resolve_ts_js_import
@@ -51,6 +52,8 @@ _RESOLVERS: dict[str, ResolverFn] = {
"haskell": resolve_haskell_import,
"erlang": resolve_erlang_import,
"fsharp": resolve_fsharp_import,
+ # dbt ref()/source(), gated on dbt_project.yml via the model index.
+ "sql": resolve_dbt_import,
}
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/sql.py b/packages/core/src/repowise/core/ingestion/resolvers/sql.py
new file mode 100644
index 000000000..24b91cb4c
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/sql.py
@@ -0,0 +1,149 @@
+"""dbt import resolution for SQL files (lightweight regex tier).
+
+Gated on ``dbt_project.yml``: the model index is built only from files
+under a dbt project root, so a repo with no dbt project resolves nothing
+locally (and non-dbt SQL files carry no ``ref()``/``source()`` imports
+in the first place).
+
+Resolution order:
+
+1. ``source:<schema>.<table>`` → ``external:source:<schema>.<table>``.
+ Sources are by definition outside the project; the typed external
+ keeps the warehouse boundary visible in the graph.
+2. ``ref('model')`` → a model-name index built per dbt project from
+ ``dbt_project.yml``'s ``model-paths`` / ``seed-paths`` /
+ ``snapshot-paths`` (defaults ``models/`` / ``seeds/`` /
+ ``snapshots/``): every ``.sql`` stem under model and snapshot paths
+ plus every ``.csv`` stem under seed paths. When two projects declare
+ the same model name, the importer's own project wins.
+3. ``ref('package', 'model')`` → a project whose declared ``name``
+ matches the package wins; otherwise the bare model name is tried
+ across all indexed projects (monorepos index sibling packages);
+ otherwise ``external:dbt:<package>.<model>``.
+4. Anything else → ``external:dbt:<name>``.
+
+Installed dbt packages under ``dbt_packages/`` (and compiled output
+under ``target/``) are never indexed — refs into them stay external.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import structlog
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+log = structlog.get_logger(__name__)
+
+_PROJECT_FILE = "dbt_project.yml"
+
+_DEFAULT_MODEL_PATHS = ("models",)
+_DEFAULT_SEED_PATHS = ("seeds", "data") # "data" is the pre-1.0 default
+_DEFAULT_SNAPSHOT_PATHS = ("snapshots",)
+
+
+def _as_path_tuple(value: object, default: tuple[str, ...]) -> tuple[str, ...]:
+ if isinstance(value, list) and all(isinstance(v, str) for v in value):
+ return tuple(v.strip("/") for v in value if v) or default
+ return default
+
+
+def _read_project(repo_path, root: str) -> tuple[str, tuple[str, ...], tuple[str, ...]]:
+ """Return (project_name, sql_dirs, csv_dirs) for the project at *root*.
+
+ Directories are project-relative. Any yml problem degrades to the dbt
+ defaults — never a crash, never a guess beyond them.
+ """
+ name = ""
+ model_paths = _DEFAULT_MODEL_PATHS
+ seed_paths = _DEFAULT_SEED_PATHS
+ snapshot_paths = _DEFAULT_SNAPSHOT_PATHS
+ if repo_path is not None:
+ try:
+ import yaml
+
+ proj_file = repo_path / root / _PROJECT_FILE if root else repo_path / _PROJECT_FILE
+ with open(proj_file, encoding="utf-8", errors="replace") as f:
+ data = yaml.safe_load(f) or {}
+ if isinstance(data, dict):
+ name = str(data.get("name") or "")
+ # "source-paths" / "data-paths" are the pre-1.0 key names.
+ model_paths = _as_path_tuple(
+ data.get("model-paths") or data.get("source-paths"), _DEFAULT_MODEL_PATHS
+ )
+ seed_paths = _as_path_tuple(
+ data.get("seed-paths") or data.get("data-paths"), _DEFAULT_SEED_PATHS
+ )
+ snapshot_paths = _as_path_tuple(data.get("snapshot-paths"), _DEFAULT_SNAPSHOT_PATHS)
+ except Exception as exc:
+ log.debug("dbt_project.yml unreadable, using defaults", root=root, error=str(exc))
+ return name, model_paths + snapshot_paths, seed_paths
+
+
+def _get_index(ctx: ResolverContext) -> dict[str, list[tuple[str, str, str]]]:
+ """``{model_name: [(project_root, project_name, path), …]}``, built once."""
+ cached = getattr(ctx, "_dbt_model_index", None)
+ if cached is not None:
+ return cached
+
+ roots = [
+ "" if path == _PROJECT_FILE else path[: -len(_PROJECT_FILE) - 1]
+ for path in ctx.sorted_paths
+ if (path == _PROJECT_FILE or path.endswith("/" + _PROJECT_FILE))
+ and "dbt_packages/" not in path
+ ]
+
+ index: dict[str, list[tuple[str, str, str]]] = {}
+ for root in roots:
+ project_name, sql_dirs, csv_dirs = _read_project(ctx.repo_path, root)
+ sql_prefixes = tuple(f"{root}/{d}/" if root else f"{d}/" for d in sql_dirs)
+ csv_prefixes = tuple(f"{root}/{d}/" if root else f"{d}/" for d in csv_dirs)
+ for path in ctx.sorted_paths:
+ if "dbt_packages/" in path or "target/" in path:
+ continue
+ if path.endswith(".sql"):
+ prefixes = sql_prefixes
+ elif path.endswith(".csv"):
+ prefixes = csv_prefixes
+ else:
+ continue
+ if not path.startswith(prefixes):
+ continue
+ stem = path.rsplit("/", 1)[-1].rsplit(".", 1)[0]
+ index.setdefault(stem, []).append((root, project_name, path))
+
+ ctx._dbt_model_index = index # cached like every other lazy per-language index
+ if index:
+ log.debug("dbt model index built", projects=len(roots), models=len(index))
+ return index
+
+
+def resolve_dbt_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:
+ if module_path.startswith("source:"):
+ return f"external:source:{module_path[len('source:') :]}"
+
+ index = _get_index(ctx)
+ package = ""
+ candidates = index.get(module_path)
+ if candidates is None and "." in module_path:
+ # Two-arg form encoded as "package.model".
+ package, _, model = module_path.partition(".")
+ candidates = index.get(model)
+
+ if candidates:
+ chosen = None
+ if package:
+ chosen = next((p for _r, pname, p in candidates if pname == package), None)
+ if chosen is None:
+ importer_root = next(
+ (r for r, _n, _p in candidates if r and importer_path.startswith(r + "/")),
+ "",
+ )
+ chosen = next((p for r, _n, p in candidates if r == importer_root), candidates[0][2])
+ if chosen == importer_path:
+ return None # self-reference
+ return chosen
+
+ return f"external:dbt:{module_path}"
diff --git a/packages/core/src/repowise/core/ingestion/special_handlers.py b/packages/core/src/repowise/core/ingestion/special_handlers.py
index 0b929f9cc..328688bff 100644
--- a/packages/core/src/repowise/core/ingestion/special_handlers.py
+++ b/packages/core/src/repowise/core/ingestion/special_handlers.py
@@ -12,6 +12,8 @@ from __future__ import annotations
import re
from collections.abc import Callable
+from functools import lru_cache
+from pathlib import Path
import structlog
@@ -20,6 +22,11 @@ from .models import FileInfo, Import, ParsedFile, Symbol
log = structlog.get_logger(__name__)
+# Language tags routed to parse_special by the parser. Kept here, next to
+# the handler table, so the two can't drift apart.
+SPECIAL_HANDLER_LANGUAGES = frozenset({"openapi", "dockerfile", "makefile", "sql"})
+
+
# ---------------------------------------------------------------------------
# Dispatcher
# ---------------------------------------------------------------------------
@@ -31,6 +38,7 @@ def parse_special(file_info: FileInfo, source: bytes, lang: str) -> ParsedFile:
"openapi": _parse_openapi,
"dockerfile": _parse_dockerfile,
"makefile": _parse_makefile,
+ "sql": _parse_sql,
}.get(lang, _parse_unknown)
try:
return handler(file_info, source)
@@ -277,6 +285,162 @@ def _parse_makefile(file_info: FileInfo, source: bytes) -> ParsedFile:
)
+# ---------------------------------------------------------------------------
+# SQL handler (sqlglot)
+# ---------------------------------------------------------------------------
+
+# sqlglot Create.kind → repowise SymbolKind. Tables and views are the
+# "classes" of a schema (columns in the signature); routines are functions.
+# INDEX / TRIGGER / SCHEMA / DATABASE are deliberately not symbols.
+_SQL_SYMBOL_KINDS = {
+ "TABLE": "class",
+ "VIEW": "class",
+ "MATERIALIZED VIEW": "class",
+ "FUNCTION": "function",
+ "PROCEDURE": "function",
+}
+
+_SIGNATURE_MAX = 300
+
+
+def _parse_sql(file_info: FileInfo, source: bytes) -> ParsedFile:
+ """Parse .sql files: dbt ref()/source() imports plus DDL symbols.
+
+ Imports come from the same regex extractor the lightweight tier uses,
+ so dbt lineage survives even when sqlglot can't parse the file (dbt
+ models are Jinja templates, so sqlglot failure is the expected case
+ there, and models carry no DDL symbols anyway). Symbol extraction is
+ best-effort: any parse problem degrades to the pre-handler passthrough
+ behaviour (no symbols), never a crash.
+ """
+ text = source.decode("utf-8", errors="replace")
+
+ from .lightweight_imports.sql import extract_dbt_imports
+
+ imports = extract_dbt_imports(text)
+ symbols, parse_errors = _extract_sql_symbols(file_info, text)
+
+ return ParsedFile(
+ file_info=file_info,
+ symbols=symbols,
+ imports=imports,
+ exports=[s.name for s in symbols],
+ docstring=None,
+ parse_errors=parse_errors,
+ )
+
+
+def _extract_sql_symbols(file_info: FileInfo, text: str) -> tuple[list[Symbol], list[str]]:
+ try:
+ import sqlglot
+ from sqlglot import exp
+ except ImportError:
+ return [], ["sqlglot not installed"]
+
+ # sqlglot warns per statement it falls back to a generic Command for
+ # (procedural bodies, vendor syntax); routine here, so keep it quiet.
+ import logging
+
+ logging.getLogger("sqlglot").setLevel(logging.ERROR)
+
+ try:
+ statements = sqlglot.parse(
+ text,
+ read=_sql_dialect_for(file_info),
+ error_level=sqlglot.ErrorLevel.IGNORE,
+ )
+ except Exception as exc:
+ # Tokenizer errors and dialect-specific syntax sqlglot can't
+ # recover from: degrade the file to passthrough behaviour.
+ return [], [f"SQL parse error: {exc}"]
+
+ symbols: list[Symbol] = []
+ cursor = 0
+ for stmt in statements:
+ if not isinstance(stmt, exp.Create):
+ continue
+ kind = _SQL_SYMBOL_KINDS.get((stmt.kind or "").upper())
+ if kind is None:
+ continue
+
+ target = stmt.this
+ schema_node = target if isinstance(target, exp.Schema) else None
+ name_node = schema_node.this if schema_node is not None else target
+ if isinstance(name_node, exp.UserDefinedFunction):
+ name_node = name_node.this # CREATE FUNCTION wraps a Table node
+ name = getattr(name_node, "name", "") or ""
+ if not name:
+ continue
+ db = getattr(name_node, "db", "") or ""
+ qualified = f"{db}.{name}" if db else name
+
+ columns = (
+ [c.name for c in schema_node.expressions if isinstance(c, exp.ColumnDef)]
+ if schema_node is not None
+ else []
+ )
+ kind_text = (stmt.kind or "").upper()
+ signature = f"{kind_text} {qualified}"
+ if columns:
+ signature = f"{signature}({', '.join(columns)})"
+
+ line, cursor = _locate_line(text, name, cursor)
+ symbols.append(
+ Symbol(
+ id=f"{file_info.path}::{qualified}",
+ name=name,
+ qualified_name=qualified,
+ kind=kind, # type: ignore[arg-type]
+ signature=signature[:_SIGNATURE_MAX],
+ start_line=line,
+ end_line=line,
+ docstring=None,
+ visibility="public",
+ language="sql",
+ )
+ )
+
+ return symbols, []
+
+
+def _locate_line(text: str, name: str, cursor: int) -> tuple[int, int]:
+ """Best-effort line number: first whole-word occurrence of *name* at or
+ after *cursor* (statements arrive in source order, so the cursor only
+ moves forward). Falls back to line 1, matching the OpenAPI handler."""
+ pattern = re.compile(rf"\b{re.escape(name)}\b")
+ match = pattern.search(text, cursor) or pattern.search(text)
+ if match is None:
+ return 1, cursor
+ return text.count("\n", 0, match.start()) + 1, match.end()
+
+
+@lru_cache(maxsize=64)
+def _read_sql_dialect(repo_root: str) -> str | None:
+ """``sql_dialect`` from .repowise/config.yaml, validated against
+ sqlglot's dialect registry. None → sqlglot's permissive default."""
+ try:
+ from ..repo_config import load_repo_config
+
+ value = load_repo_config(Path(repo_root)).get("sql_dialect")
+ if not value:
+ return None
+ from sqlglot.dialects.dialect import Dialect
+
+ if Dialect.get(str(value).lower()) is None:
+ log.warning("Unknown sql_dialect in config.yaml, ignoring", sql_dialect=value)
+ return None
+ return str(value).lower()
+ except Exception:
+ return None
+
+
+def _sql_dialect_for(file_info: FileInfo) -> str | None:
+ abs_posix = file_info.abs_path.replace("\\", "/")
+ if abs_posix.endswith("/" + file_info.path):
+ return _read_sql_dialect(abs_posix[: -len(file_info.path) - 1])
+ return None
+
+
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
diff --git a/pyproject.toml b/pyproject.toml
index a50246507..42f470d86 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -49,6 +49,8 @@ dependencies = [
"tree-sitter-scala>=0.23,<1",
"tree-sitter-php>=0.23,<1",
"tree-sitter-luau>=1.2,<2",
+ # SQL parsing (multi-dialect, error-tolerant, pure Python)
+ "sqlglot>=26,<28",
# Dependency graph
"networkx>=3.3,<4",
"scipy>=1.11,<2",
diff --git a/tests/unit/ingestion/test_dbt_sql_imports.py b/tests/unit/ingestion/test_dbt_sql_imports.py
new file mode 100644
index 000000000..7dd3613bc
--- /dev/null
+++ b/tests/unit/ingestion/test_dbt_sql_imports.py
@@ -0,0 +1,284 @@
+"""Unit tests for dbt SQL import extraction + resolution (lightweight tier).
+
+Covers every ref()/source() form the extractor claims, the per-project
+model-name index (dbt_project.yml path config, seeds, snapshots), package
+qualification, multi-project preference, and the false-positive guards
+that keep plain SQL files import-free.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.lightweight_imports import extract_lightweight_imports
+from repowise.core.ingestion.lightweight_imports.sql import extract_dbt_imports
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.resolvers import resolve_import
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.ingestion.resolvers.sql import resolve_dbt_import
+
+
+def _ctx(repo: Path | None, files: dict[str, str]) -> ResolverContext:
+ """ResolverContext over *files* ({path: content}); writes them under *repo*."""
+ if repo is not None:
+ for rel, content in files.items():
+ target = repo / rel
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(content, encoding="utf-8")
+ stem_map: dict[str, list[str]] = {}
+ for p in files:
+ stem = p.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower()
+ stem_map.setdefault(stem, []).append(p)
+ return ResolverContext(
+ path_set=set(files),
+ stem_map=stem_map,
+ graph=nx.DiGraph(),
+ repo_path=repo,
+ )
+
+
+def _modules(imports) -> list[str]:
+ return [imp.module_path for imp in imports]
+
+
+def _file_info(rel: str, lang: str) -> FileInfo:
+ return FileInfo(
+ path=rel,
+ abs_path=f"/tmp/{rel}",
+ language=lang, # type: ignore[arg-type]
+ size_bytes=0,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Extraction
+# ---------------------------------------------------------------------------
+
+
+class TestDbtExtraction:
+ def test_single_arg_ref(self) -> None:
+ src = "select * from {{ ref('stg_orders') }}\n"
+ assert _modules(extract_dbt_imports(src)) == ["stg_orders"]
+
+ def test_double_quotes_and_no_spaces(self) -> None:
+ src = 'select * from {{ref("stg_orders")}}'
+ assert _modules(extract_dbt_imports(src)) == ["stg_orders"]
+
+ def test_two_arg_ref_is_package_qualified(self) -> None:
+ src = "select * from {{ ref('elementary', 'alerts') }}"
+ assert _modules(extract_dbt_imports(src)) == ["elementary.alerts"]
+
+ def test_ref_with_version_kwarg(self) -> None:
+ src = "select * from {{ ref('dim_customers', version=2) }}"
+ assert _modules(extract_dbt_imports(src)) == ["dim_customers"]
+
+ def test_ref_piped_through_a_filter(self) -> None:
+ src = "{{ ref('stg_payments') | string }}"
+ assert _modules(extract_dbt_imports(src)) == ["stg_payments"]
+
+ def test_ref_inside_jinja_statement_block(self) -> None:
+ src = "{% set payments = ref('stg_payments') %}\nselect * from {{ payments }}"
+ assert _modules(extract_dbt_imports(src)) == ["stg_payments"]
+
+ def test_source(self) -> None:
+ src = "select * from {{ source('jaffle_shop', 'raw_orders') }}"
+ assert _modules(extract_dbt_imports(src)) == ["source:jaffle_shop.raw_orders"]
+
+ def test_whitespace_and_trim_markers(self) -> None:
+ src = "select * from {{- ref( 'stg_orders' ) -}}"
+ assert _modules(extract_dbt_imports(src)) == ["stg_orders"]
+
+ def test_duplicates_collapse(self) -> None:
+ src = "select * from {{ ref('a') }} join {{ ref('a') }} using (id)"
+ assert _modules(extract_dbt_imports(src)) == ["a"]
+
+ def test_plain_sql_has_no_imports(self) -> None:
+ src = "CREATE TABLE users (id INT);\nSELECT * FROM orders;\n"
+ assert extract_dbt_imports(src) == []
+
+ def test_bare_ref_call_outside_jinja_is_not_a_dependency(self) -> None:
+ # ref() as a plain SQL function (a UDF) must not create edges.
+ src = "SELECT ref('foo') FROM t;"
+ assert extract_dbt_imports(src) == []
+
+ def test_dispatch_via_language_tag(self) -> None:
+ info = _file_info("models/orders.sql", "sql")
+ source = b"select * from {{ ref('stg_orders') }}"
+ assert _modules(extract_lightweight_imports(info, source)) == ["stg_orders"]
+
+
+# ---------------------------------------------------------------------------
+# Resolution
+# ---------------------------------------------------------------------------
+
+_PROJECT_YML = "name: jaffle_shop\nprofile: default\n"
+
+
+class TestDbtResolution:
+ def test_ref_resolves_to_model_file(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {
+ "dbt_project.yml": _PROJECT_YML,
+ "models/stg_orders.sql": "select 1",
+ "models/orders.sql": "select * from {{ ref('stg_orders') }}",
+ },
+ )
+ assert resolve_dbt_import("stg_orders", "models/orders.sql", ctx) == "models/stg_orders.sql"
+
+ def test_nested_model_dirs(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {
+ "dbt_project.yml": _PROJECT_YML,
+ "models/staging/stg_orders.sql": "select 1",
+ "models/marts/orders.sql": "",
+ },
+ )
+ assert (
+ resolve_dbt_import("stg_orders", "models/marts/orders.sql", ctx)
+ == "models/staging/stg_orders.sql"
+ )
+
+ def test_custom_model_paths_from_project_yml(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {
+ "dbt_project.yml": "name: p\nmodel-paths: ['transformations']\n",
+ "transformations/stg_orders.sql": "select 1",
+ "models/ignored.sql": "select 1",
+ },
+ )
+ assert (
+ resolve_dbt_import("stg_orders", "transformations/orders.sql", ctx)
+ == "transformations/stg_orders.sql"
+ )
+ # models/ is not a configured model path for this project
+ assert resolve_dbt_import("ignored", "transformations/orders.sql", ctx) == (
+ "external:dbt:ignored"
+ )
+
+ def test_seed_csv_is_ref_able(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {
+ "dbt_project.yml": _PROJECT_YML,
+ "seeds/raw_customers.csv": "id,name\n",
+ "models/customers.sql": "",
+ },
+ )
+ assert (
+ resolve_dbt_import("raw_customers", "models/customers.sql", ctx)
+ == "seeds/raw_customers.csv"
+ )
+
+ def test_snapshots_are_ref_able(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {
+ "dbt_project.yml": _PROJECT_YML,
+ "snapshots/orders_snapshot.sql": "select 1",
+ "models/orders.sql": "",
+ },
+ )
+ assert (
+ resolve_dbt_import("orders_snapshot", "models/orders.sql", ctx)
+ == "snapshots/orders_snapshot.sql"
+ )
+
+ def test_source_is_a_typed_external(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, {"dbt_project.yml": _PROJECT_YML})
+ assert (
+ resolve_dbt_import("source:jaffle_shop.raw_orders", "models/x.sql", ctx)
+ == "external:source:jaffle_shop.raw_orders"
+ )
+
+ def test_unknown_ref_is_external(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, {"dbt_project.yml": _PROJECT_YML, "models/a.sql": ""})
+ assert resolve_dbt_import("nope", "models/a.sql", ctx) == "external:dbt:nope"
+
+ def test_two_arg_ref_prefers_named_project(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {
+ "core/dbt_project.yml": "name: core_pkg\n",
+ "core/models/shared.sql": "select 1",
+ "analytics/dbt_project.yml": "name: analytics\n",
+ "analytics/models/shared.sql": "select 2",
+ "analytics/models/report.sql": "",
+ },
+ )
+ assert (
+ resolve_dbt_import("core_pkg.shared", "analytics/models/report.sql", ctx)
+ == "core/models/shared.sql"
+ )
+
+ def test_two_arg_ref_to_uninstalled_package_is_external(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, {"dbt_project.yml": _PROJECT_YML, "models/a.sql": ""})
+ assert (
+ resolve_dbt_import("dbt_utils.surrogate_key", "models/a.sql", ctx)
+ == "external:dbt:dbt_utils.surrogate_key"
+ )
+
+ def test_same_name_prefers_importer_project(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {
+ "core/dbt_project.yml": "name: core_pkg\n",
+ "core/models/shared.sql": "select 1",
+ "analytics/dbt_project.yml": "name: analytics\n",
+ "analytics/models/shared.sql": "select 2",
+ "analytics/models/report.sql": "",
+ },
+ )
+ assert (
+ resolve_dbt_import("shared", "analytics/models/report.sql", ctx)
+ == "analytics/models/shared.sql"
+ )
+
+ def test_dbt_packages_are_never_indexed(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {
+ "dbt_project.yml": _PROJECT_YML,
+ "dbt_packages/elementary/dbt_project.yml": "name: elementary\n",
+ "dbt_packages/elementary/models/alerts.sql": "select 1",
+ "models/orders.sql": "",
+ },
+ )
+ assert resolve_dbt_import("alerts", "models/orders.sql", ctx) == "external:dbt:alerts"
+
+ def test_self_reference_returns_none(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {"dbt_project.yml": _PROJECT_YML, "models/orders.sql": "select 1"},
+ )
+ assert resolve_dbt_import("orders", "models/orders.sql", ctx) is None
+
+ def test_no_dbt_project_means_external(self, tmp_path: Path) -> None:
+ # Gate: without dbt_project.yml no model index exists at all.
+ ctx = _ctx(tmp_path, {"models/stg_orders.sql": "select 1"})
+ assert (
+ resolve_dbt_import("stg_orders", "models/orders.sql", ctx) == "external:dbt:stg_orders"
+ )
+
+ def test_dispatch_through_resolve_import(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {
+ "dbt_project.yml": _PROJECT_YML,
+ "models/stg_orders.sql": "select 1",
+ },
+ )
+ assert (
+ resolve_import("stg_orders", "models/orders.sql", "sql", ctx) == "models/stg_orders.sql"
+ )
diff --git a/tests/unit/ingestion/test_language_capabilities.py b/tests/unit/ingestion/test_language_capabilities.py
index 5ca0342f0..01e5e3906 100644
--- a/tests/unit/ingestion/test_language_capabilities.py
+++ b/tests/unit/ingestion/test_language_capabilities.py
@@ -154,6 +154,8 @@ _PARTIAL = {
"haskell",
"erlang",
"fsharp",
+ # dbt ref()/source() lineage (model-name index gated on dbt_project.yml).
+ "sql",
}
diff --git a/tests/unit/ingestion/test_lightweight_resolvers.py b/tests/unit/ingestion/test_lightweight_resolvers.py
index 73e2e5dc8..93e2840c7 100644
--- a/tests/unit/ingestion/test_lightweight_resolvers.py
+++ b/tests/unit/ingestion/test_lightweight_resolvers.py
@@ -83,6 +83,7 @@ class TestDispatch:
"haskell",
"erlang",
"fsharp",
+ "sql",
} == LIGHTWEIGHT_IMPORT_LANGUAGES
def test_other_language_returns_empty(self) -> None:
diff --git a/tests/unit/ingestion/test_sql_handler.py b/tests/unit/ingestion/test_sql_handler.py
new file mode 100644
index 000000000..6676fcf9b
--- /dev/null
+++ b/tests/unit/ingestion/test_sql_handler.py
@@ -0,0 +1,159 @@
+"""Unit tests for the SQL special handler (sqlglot symbol extraction).
+
+Covers DDL symbol mapping per major dialect flavour, graceful degradation
+on malformed input, dbt-model Jinja tolerance, the ``sql_dialect`` config
+key, and the parse_file routing that sends .sql (and the other special
+formats) to their handlers.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.special_handlers import parse_special
+
+
+def _file_info(rel: str, lang: str, root: str = "/repo") -> FileInfo:
+ return FileInfo(
+ path=rel,
+ abs_path=f"{root}/{rel}",
+ language=lang, # type: ignore[arg-type]
+ size_bytes=0,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+def _symbols(source: str, rel: str = "schema.sql", root: str = "/repo"):
+ parsed = parse_special(_file_info(rel, "sql", root), source.encode(), "sql")
+ return parsed
+
+
+class TestSqlSymbols:
+ def test_create_table_with_columns(self) -> None:
+ parsed = _symbols("CREATE TABLE users (\n id INT PRIMARY KEY,\n email VARCHAR(255)\n);")
+ assert len(parsed.symbols) == 1
+ sym = parsed.symbols[0]
+ assert sym.name == "users"
+ assert sym.kind == "class"
+ assert sym.signature == "TABLE users(id, email)"
+ assert sym.start_line == 1
+ assert parsed.exports == ["users"]
+
+ def test_schema_qualified_table(self) -> None:
+ parsed = _symbols("CREATE TABLE public.orders (id SERIAL, total NUMERIC);")
+ sym = parsed.symbols[0]
+ assert sym.qualified_name == "public.orders"
+ assert sym.id.endswith("::public.orders")
+
+ def test_views_and_materialized_views(self) -> None:
+ parsed = _symbols(
+ "CREATE VIEW active_users AS SELECT 1;\nCREATE MATERIALIZED VIEW mv_daily AS SELECT 2;"
+ )
+ assert [(s.name, s.kind) for s in parsed.symbols] == [
+ ("active_users", "class"),
+ ("mv_daily", "class"),
+ ]
+ assert parsed.symbols[1].start_line == 2
+
+ def test_tsql_procedure(self) -> None:
+ parsed = _symbols("CREATE PROCEDURE dbo.GetUsers AS BEGIN SELECT 1 END;")
+ sym = parsed.symbols[0]
+ assert sym.name == "GetUsers"
+ assert sym.qualified_name == "dbo.GetUsers"
+ assert sym.kind == "function"
+
+ def test_index_and_trigger_are_not_symbols(self) -> None:
+ parsed = _symbols("CREATE TABLE t (a INT);\nCREATE INDEX idx_a ON t(a);")
+ assert [s.name for s in parsed.symbols] == ["t"]
+
+ def test_multiple_statements_keep_line_numbers(self) -> None:
+ parsed = _symbols("-- schema\nCREATE TABLE a (x INT);\n\nCREATE TABLE b (y INT);\n")
+ assert [(s.name, s.start_line) for s in parsed.symbols] == [("a", 2), ("b", 4)]
+
+ def test_malformed_sql_degrades_gracefully(self) -> None:
+ parsed = _symbols("CREATE TABLE (((((;;; garbage !!")
+ assert parsed.symbols == []
+ # No crash is the contract; error reporting is best-effort.
+
+ def test_dml_only_file_has_no_symbols(self) -> None:
+ parsed = _symbols("INSERT INTO t VALUES (1);\nUPDATE t SET x = 2;")
+ assert parsed.symbols == []
+ assert parsed.parse_errors == []
+
+
+class TestSqlDialectConfig:
+ def test_postgres_function_with_configured_dialect(self, tmp_path: Path) -> None:
+ (tmp_path / ".repowise").mkdir()
+ (tmp_path / ".repowise" / "config.yaml").write_text(
+ "sql_dialect: postgres\n", encoding="utf-8"
+ )
+ source = "CREATE FUNCTION add_one(x INT) RETURNS INT AS $$ SELECT x + 1 $$ LANGUAGE sql;"
+ parsed = _symbols(source, root=tmp_path.as_posix())
+ assert [(s.name, s.kind) for s in parsed.symbols] == [("add_one", "function")]
+
+ def test_unknown_dialect_falls_back_to_default(self, tmp_path: Path) -> None:
+ (tmp_path / ".repowise").mkdir()
+ (tmp_path / ".repowise" / "config.yaml").write_text(
+ "sql_dialect: not_a_dialect\n", encoding="utf-8"
+ )
+ parsed = _symbols("CREATE TABLE t (a INT);", root=tmp_path.as_posix())
+ assert [s.name for s in parsed.symbols] == ["t"]
+
+
+class TestDbtModelsThroughHandler:
+ def test_jinja_model_keeps_imports_and_never_crashes(self) -> None:
+ source = (
+ "with orders as (\n"
+ " select * from {{ ref('stg_orders') }}\n"
+ "),\n"
+ "payments as (\n"
+ " select * from {{ source('stripe', 'payment') }}\n"
+ ")\n"
+ "select * from orders join payments using (order_id)\n"
+ )
+ parsed = _symbols(source, rel="models/orders.sql")
+ assert [i.module_path for i in parsed.imports] == [
+ "stg_orders",
+ "source:stripe.payment",
+ ]
+ assert parsed.symbols == []
+
+
+class TestParserRouting:
+ def test_sql_reaches_special_handler(self) -> None:
+ parsed = ASTParser().parse_file(
+ _file_info("db/schema.sql", "sql"), b"CREATE TABLE t (a INT);"
+ )
+ assert [s.name for s in parsed.symbols] == ["t"]
+
+ def test_sql_dbt_imports_flow_through_parse_file(self) -> None:
+ parsed = ASTParser().parse_file(
+ _file_info("models/orders.sql", "sql"),
+ b"select * from {{ ref('stg_orders') }}",
+ )
+ assert [i.module_path for i in parsed.imports] == ["stg_orders"]
+
+ def test_dockerfile_reaches_special_handler(self) -> None:
+ # Regression: the special-handler branch used to sit below the
+ # no-grammar fallback and never fired for any of its languages.
+ parsed = ASTParser().parse_file(
+ _file_info("Dockerfile", "dockerfile"),
+ b"FROM python:3.12\nEXPOSE 8000\n",
+ )
+ assert [i.module_path for i in parsed.imports] == ["python:3.12"]
+ assert [s.name for s in parsed.symbols] == ["EXPOSE_8000"]
+
+ def test_makefile_reaches_special_handler(self) -> None:
+ parsed = ASTParser().parse_file(
+ _file_info("Makefile", "makefile"),
+ b"build: deps\n\tgo build ./...\n",
+ )
+ assert [s.name for s in parsed.symbols] == ["build"]