Extract tables, views, functions, and relationships from .sql files via tree-sitter.
(path: Path, content: str | bytes | None = None)
| 548 | |
| 549 | |
| 550 | def extract_sql(path: Path, content: str | bytes | None = None) -> dict: |
| 551 | """Extract tables, views, functions, and relationships from .sql files via tree-sitter.""" |
| 552 | try: |
| 553 | import tree_sitter_sql as tssql |
| 554 | from tree_sitter import Language, Parser |
| 555 | except ImportError as e: |
| 556 | import importlib.util |
| 557 | # An installed-but-broken grammar (e.g. a C extension built for a |
| 558 | # different Python ABI, #2602) raises ImportError here too. Reporting |
| 559 | # that as "not installed" sends the user to a no-op `pip install`, so |
| 560 | # distinguish a genuinely-absent module from one that failed to load |
| 561 | # and surface the real exception in the latter case. |
| 562 | if importlib.util.find_spec("tree_sitter_sql") is None: |
| 563 | return {"nodes": [], "edges": [], |
| 564 | "error": "tree_sitter_sql not installed. Run: pip install tree-sitter-sql"} |
| 565 | return {"nodes": [], "edges": [], |
| 566 | "error": f"tree_sitter_sql is installed but failed to load: {e}"} |
| 567 | |
| 568 | try: |
| 569 | language = Language(tssql.language()) |
| 570 | parser = Parser(language) |
| 571 | source = ( |
| 572 | content.encode("utf-8") if isinstance(content, str) |
| 573 | else content if content is not None |
| 574 | else _read_source_bytes(path) |
| 575 | ) |
| 576 | # `GO` is not SQL; as `;` (same length, so offsets and lines hold) it ends the statement. |
| 577 | patched = bytearray(source) |
| 578 | for start, end in _go_separators(source): |
| 579 | patched[start:end] = b";" + b" " * (end - start - 1) |
| 580 | tree = parser.parse(bytes(patched)) |
| 581 | root = tree.root_node |
| 582 | except Exception as e: |
| 583 | return {"nodes": [], "edges": [], "error": str(e)} |
| 584 | |
| 585 | |
| 586 | stem = _file_stem(path) |
| 587 | str_path = str(path) |
| 588 | file_nid = _make_id(str_path) |
| 589 | nodes: list[dict] = [{"id": file_nid, "label": path.name, "file_type": "code", |
| 590 | "source_file": str_path, "source_location": None}] |
| 591 | edges: list[dict] = [] |
| 592 | seen_ids: set[str] = {file_nid} |
| 593 | table_nids: dict[str, str] = {} # name → nid for reference resolution |
| 594 | routine_nids: dict[str, str] = {} # function/procedure name → nid, for trigger links |
| 595 | # Structured routine nid → 1-based line. On tree-sitter-sql 0.3.13 a package's |
| 596 | # first member partially parses as a top-level create_procedure, so the |
| 597 | # structured walk mints a plain node for it; the package recovery below uses |
| 598 | # this to drop that duplicate once it owns the package-qualified member. |
| 599 | structured_routine_lines: dict[str, int] = {} |
| 600 | error_routines: set[str] = set() # walk routines whose node holds an ERROR |
| 601 | |
| 602 | def _read(n) -> str: |
| 603 | return source[n.start_byte:n.end_byte].decode("utf-8", errors="replace") |
| 604 | |
| 605 | def _obj_name(n) -> str | None: |
| 606 | for c in n.children: |
| 607 | if c.type == "object_reference": |