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(salesforce): SObject and field metadata as symbols, bound from SOQL, DML and triggers (#4418)

Raghav Chamadiya363630a74fa3
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.md
index d01f64397..c807f2902 100644
--- a/docs/architecture/language-support.md
+++ b/docs/architecture/language-support.md
@@ -1011,6 +1011,14 @@ link back to it. Flexipages, quick actions, tabs, email services and Experience
sites mark what they name as live; names in another package's namespace are not
followed.
+Object and field metadata files (`.object-meta.xml`, `.field-meta.xml`,
+`.object`) become object and field symbols. SOQL and SOSL queries, DML
+statements, triggers, literal `Database.query` strings, `.soql` files and lookup
+fields reference them, matched case-insensitively, with one edge to one copy when
+an object is defined in several places (the default package directory first). A
+name with no definition in the repository gets no edge; `getDescribe()` schema
+tokens and `TYPEOF` branches are not read.
+
### Salesforce Visualforce
Pages and components link the Apex classes their `controller=` and
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index 50a2a305b..a2a0cf6c2 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -81,6 +81,8 @@ coverage report ([formats](TEST_INTELLIGENCE.md#supported-formats)). Health cove
complexity, class cohesion, and SOQL, DML and callouts inside loops.
Salesforce flows (`.flow-meta.xml`) are one symbol each, linked to the Apex
invocable actions, subflows and screen components they name.
+Salesforce object and field metadata become symbols that Apex SOQL, DML and
+triggers reference.
## How accurate is the graph per language
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index 729804330..a9699c39b 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -609,6 +609,9 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
# --- Phase 3: Resolve symbol-level calls ---
self._resolve_calls(import_targets, progress=progress)
+ # --- Salesforce objects and fields named by Apex and lookup fields ---
+ self._resolve_salesforce_schema()
+
# --- Phase 4: Base method → the implementations that answer for it ---
# Post-pass: needs heritage resolved and reads only the graph.
self._resolve_override_dispatch(progress=progress)
@@ -730,6 +733,13 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
_phase_done("graph.type_refs")
del type_use_counts # used only for logging inside resolve_type_refs
+ def _resolve_salesforce_schema(self) -> None:
+ """SOQL/DML/trigger objects and lookup fields, bound to schema symbols."""
+ from ..salesforce_schema import add_schema_edges
+
+ added = add_schema_edges(self._graph, self._parsed_files, self._repo_path)
+ log.info("Salesforce schema edges resolved", total=added)
+
def graph(self) -> nx.DiGraph:
"""Return the graph (building it first if necessary)."""
if not self._built:
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py
index 5ce33b3c9..5f24408cf 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py
@@ -57,8 +57,10 @@ from .razor import SPEC as _RAZOR
from .ruby import SPEC as _RUBY
from .rust import SPEC as _RUST
from .salesforce_flow import SPEC as _SALESFORCE_FLOW
+from .salesforce_object import SPEC as _SALESFORCE_OBJECT
from .scala import SPEC as _SCALA
from .shell import SPEC as _SHELL
+from .soql import SPEC as _SOQL
from .sql import SPEC as _SQL
from .svelte import SPEC as _SVELTE
from .swift import SPEC as _SWIFT
@@ -153,6 +155,9 @@ ALL_SPECS: tuple[LanguageSpec, ...] = (
_AURA,
# Salesforce flows. See the spec's docstring.
_SALESFORCE_FLOW,
+ # Salesforce object/field metadata and saved SOQL queries.
+ _SALESFORCE_OBJECT,
+ _SOQL,
# -----------------------------------------------------------------
# Extra languages — git blame coverage only (passthrough + is_code)
# These exist so git_indexer tracks their history even though
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/salesforce_object.py b/packages/core/src/repowise/core/ingestion/languages/specs/salesforce_object.py
new file mode 100644
index 000000000..f45d457a3
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/salesforce_object.py
@@ -0,0 +1,18 @@
+"""LanguageSpec for Salesforce object and field metadata.
+
+Each object becomes a class symbol and each field a property symbol (the SQL
+DDL precedent). Data, so dead code never reports them: layouts, permission sets
+and the org use objects and fields where no parser looks.
+"""
+
+from ..spec import LanguageSpec
+
+SPEC = LanguageSpec(
+ tag="salesforce_object",
+ display_name="Salesforce Object",
+ extensions=frozenset({".object"}),
+ name_suffixes=frozenset({".object-meta.xml", ".field-meta.xml"}),
+ is_code=False,
+ is_passthrough=True,
+ color_hex="#00A1E0",
+)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/soql.py b/packages/core/src/repowise/core/ingestion/languages/specs/soql.py
new file mode 100644
index 000000000..ab5b8f97e
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/soql.py
@@ -0,0 +1,12 @@
+"""LanguageSpec for ``.soql`` files: saved SOQL queries, read for the objects and fields they name."""
+
+from ..spec import LanguageSpec
+
+SPEC = LanguageSpec(
+ tag="soql",
+ display_name="SOQL",
+ extensions=frozenset({".soql"}),
+ is_code=False,
+ is_passthrough=True,
+ color_hex="#00A1E0",
+)
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index d2fe77f29..2311c8d60 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -95,6 +95,9 @@ LanguageTag = Literal[
"aura",
# Salesforce flows: one symbol per flow.
"salesforce_flow",
+ # Salesforce object and field metadata, and saved SOQL queries.
+ "salesforce_object",
+ "soql",
"unknown",
]
@@ -439,8 +442,8 @@ EdgeType = Literal[
# parser could have seen, and letting it read as one would put an inferred
# wiring hop into an execution flow as if it were source.
"framework_binds",
- # A data reference rather than a call: C# member access, file → file. It
- # used to name two unrelated things — the Express route wiring emitted it
+ # A data reference rather than a call, file → file: C# member access and
+ # Salesforce schema references. It used to name two unrelated things — the Express route wiring emitted it
# symbol → symbol — which is why one consumer set could not say which layer
# it meant. That producer now emits `framework_binds`.
"reads",
@@ -622,7 +625,8 @@ FILE_DEPENDENCY_EDGE_TYPES: frozenset[str] = frozenset(
"dynamic_imports",
"dynamic_url_route",
# C# member access (`var x = new T(); x.Prop`) resolves to the file
- # declaring the type, so this is a real file-level reference.
+ # declaring the type, so this is a real file-level reference, as is a
+ # SOQL query or DML statement naming an object the repository defines.
"reads",
}
)
@@ -732,6 +736,22 @@ class TypeReference:
] = "ctor_param"
+@dataclass(frozen=True)
+class SchemaReference:
+ """A Salesforce SObject, or a field path on one, named in a file.
+
+ ``path`` is empty for the object itself; otherwise the dotted field path
+ as written after it (``("Parent__r", "Name")`` for ``Parent__r.Name``),
+ resolved hop by hop through lookup metadata. Names keep their written case;
+ Salesforce compares them case-insensitively.
+ """
+
+ source_symbol_id: str # the method, trigger or field that names it
+ object_name: str
+ line: int
+ path: tuple[str, ...] = ()
+
+
@dataclass
class ParsedFile:
"""Full result of parsing a single source file."""
@@ -766,6 +786,8 @@ class ParsedFile:
# symbol enclosing it, and a line — and it lets these ride the same
# resolution tiers. They become ``references`` edges, not ``calls``.
references: list[CallSite] = field(default_factory=list)
+ # Salesforce objects and fields this file names (see ``salesforce_schema``).
+ schema_refs: list[SchemaReference] = field(default_factory=list)
@property
def symbol_count(self) -> int:
diff --git a/packages/core/src/repowise/core/ingestion/parser/__init__.py b/packages/core/src/repowise/core/ingestion/parser/__init__.py
index 372625da4..78bfc009b 100644
--- a/packages/core/src/repowise/core/ingestion/parser/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/parser/__init__.py
@@ -51,6 +51,7 @@ from ..models import FileInfo, Import, ParsedFile, Symbol, compute_content_hash
from ..parser_helpers import _collect_error_nodes, _run_query
from ..python_local_refs import local_refs_from_tree, parse_python_module
from ..python_registrars import registering_functions
+from ..salesforce_soql import apex_schema_refs
from ..sfc_source import component_call_sites, prepare_source
from ..special_handlers import SPECIAL_HANDLER_LANGUAGES, parse_special
from .calls import (
@@ -250,6 +251,10 @@ class ASTParser:
local_refs=local_refs,
registrars=registrars,
references=references,
+ # SOQL/SOSL, DML and trigger targets, bound to SObject metadata later.
+ schema_refs=(
+ apex_schema_refs(root, symbols, file_info.path) if lang == "apex" else []
+ ),
)
diff --git a/packages/core/src/repowise/core/ingestion/salesforce_schema.py b/packages/core/src/repowise/core/ingestion/salesforce_schema.py
new file mode 100644
index 000000000..6bf211020
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/salesforce_schema.py
@@ -0,0 +1,341 @@
+"""Salesforce object and field metadata as symbols, and the references bound to them.
+
+Objects (``.object-meta.xml``, legacy ``.object``) are class symbols and fields
+(``.field-meta.xml``, or inline in ``.object``) are property symbols. Names
+compare case-folded, without the repository's own namespace prefix or CumulusCI
+tokens. A reference binds one canonical copy; a name with no definition binds nothing.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from collections import defaultdict
+from collections.abc import Iterable, Iterator
+from dataclasses import dataclass, field
+from pathlib import Path, PurePosixPath
+from typing import TYPE_CHECKING
+from xml.parsers import expat
+
+import yaml
+
+from .models import FileInfo, ParsedFile, SchemaReference, Symbol
+
+if TYPE_CHECKING: # read paths import this module and must not load networkx
+ import networkx as nx
+
+_LANGUAGE = "salesforce_object"
+_OBJECT_META = ".object-meta.xml"
+_FIELD_META = ".field-meta.xml"
+_SIGNATURE_MAX = 300
+# An exact API-name match against metadata in the repository, not a guess.
+_CONFIDENCE = 0.95
+
+# CumulusCI rewrites these to the package namespace (or nothing) at deploy.
+_NAMESPACE_TOKEN_RE = re.compile(r"(?:%%%|___)[A-Z]+(?:_[A-Z]+)*(?:%%%|___)")
+
+
+# ---------------------------------------------------------------------------
+# Metadata files -> symbols
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class _Element:
+ tag: str
+ line: int
+ end_line: int = 0
+ text: str = ""
+ children: list[_Element] = field(default_factory=list)
+ parts: list[str] = field(default_factory=list)
+
+ def first(self, tag: str) -> str | None:
+ return next((c.text for c in self.children if c.tag == tag and c.text), None)
+
+ def all(self, tag: str) -> list[_Element]:
+ return [c for c in self.children if c.tag == tag]
+
+
+def _read_xml(source: bytes) -> _Element | None:
+ """The element tree with line spans, or None for malformed XML.
+
+ expat rather than ``xml.etree`` for the line numbers; it fetches no
+ external entity and refuses entity-expansion bombs.
+ """
+ parser = expat.ParserCreate()
+ stack: list[_Element] = []
+ roots: list[_Element] = []
+
+ def start(name: str, _attrs: dict[str, str]) -> None:
+ el = _Element(name.rpartition(":")[2], parser.CurrentLineNumber)
+ (stack[-1].children if stack else roots).append(el)
+ stack.append(el)
+
+ def end(_name: str) -> None:
+ el = stack.pop()
+ el.end_line = parser.CurrentLineNumber
+ el.text = "".join(el.parts).strip()
+ el.parts = []
+
+ def chars(data: str) -> None:
+ if stack:
+ stack[-1].parts.append(data)
+
+ parser.StartElementHandler = start
+ parser.EndElementHandler = end
+ parser.CharacterDataHandler = chars
+ try:
+ parser.Parse(source, True)
+ except expat.ExpatError:
+ return None
+ return roots[0] if roots else None
+
+
+def _strip_namespace_tokens(name: str) -> str:
+ return _NAMESPACE_TOKEN_RE.sub("", name)
+
+
+def _object_symbol(path: str, name: str, root: _Element) -> Symbol:
+ label = root.first("label")
+ signature = f'SObject {name} "{label}"' if label else f"SObject {name}"
+ return Symbol(
+ id=f"{path}::{name}",
+ name=name,
+ qualified_name=name,
+ kind="class",
+ signature=signature[:_SIGNATURE_MAX],
+ start_line=root.line,
+ end_line=max(root.end_line, root.line),
+ docstring=root.first("description") or label,
+ language=_LANGUAGE,
+ )
+
+
+def _field_symbol(
+ sym_id: str, obj: str | None, name: str, el: _Element, parent: str | None
+) -> tuple[Symbol, list[SchemaReference]]:
+ kind = el.first("type")
+ targets = el.all("referenceTo")
+ signature = f"{obj}.{name}" if obj else name
+ if kind:
+ signature += f": {kind}"
+ if targets:
+ signature += f" -> {', '.join(t.text for t in targets)}"
+ sym = Symbol(
+ id=sym_id,
+ name=name,
+ qualified_name=f"{obj}.{name}" if obj else name,
+ kind="property",
+ signature=signature[:_SIGNATURE_MAX],
+ start_line=el.line,
+ end_line=max(el.end_line, el.line),
+ docstring=el.first("description") or el.first("inlineHelpText") or el.first("label"),
+ language=_LANGUAGE,
+ parent_name=parent,
+ )
+ refs = [SchemaReference(sym_id, t.text, t.line) for t in targets if t.text]
+ return sym, refs
+
+
+def parse_object_metadata(file_info: FileInfo, source: bytes) -> ParsedFile:
+ """Symbols (and lookup references) of one object or field metadata file."""
+ path = file_info.path
+ root = _read_xml(source)
+ if root is None:
+ return ParsedFile(file_info, [], [], [], parse_errors=["malformed XML"])
+ pure = PurePosixPath(path)
+ lowered = pure.name.lower()
+ symbols: list[Symbol] = []
+ refs: list[SchemaReference] = []
+ if lowered.endswith(_FIELD_META) and root.tag == "CustomField":
+ name = _strip_namespace_tokens(pure.name[: -len(_FIELD_META)])
+ # objects/<Obj>/fields/<F>.field-meta.xml; any other layout names no object.
+ obj = pure.parent.parent.name if pure.parent.name == "fields" else None
+ obj = _strip_namespace_tokens(obj) if obj else None
+ sym, refs = _field_symbol(f"{path}::{name}", obj, name, root, None)
+ symbols.append(sym)
+ elif root.tag == "CustomObject":
+ suffix = _OBJECT_META if lowered.endswith(_OBJECT_META) else ".object"
+ obj = _strip_namespace_tokens(pure.name[: -len(suffix)])
+ symbols.append(_object_symbol(path, obj, root))
+ # Only the legacy single-file format carries fields inline.
+ for el in root.all("fields"):
+ name = el.first("fullName")
+ if not name:
+ continue
+ name = _strip_namespace_tokens(name)
+ sym, field_refs = _field_symbol(f"{path}::{obj}::{name}", obj, name, el, obj)
+ symbols.append(sym)
+ refs.extend(field_refs)
+ return ParsedFile(
+ file_info=file_info,
+ symbols=symbols,
+ imports=[],
+ exports=[s.name for s in symbols],
+ schema_refs=refs,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Resolution
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class _Project:
+ package_dirs: tuple[str, ...]
+ namespaces: frozenset[str] # lowercased, each with its trailing "__"
+
+ def key(self, name: str) -> str:
+ """The platform's comparison key for an object or field API name."""
+ folded = _strip_namespace_tokens(name.strip()).lower()
+ for prefix in self.namespaces:
+ rest = folded[len(prefix) :]
+ # ``ns__Foo__c``: strip only a prefix that leaves a custom name.
+ if folded.startswith(prefix) and "__" in rest:
+ return rest
+ return folded
+
+ def preferred(self, paths_ids: Iterable[tuple[str, str]]) -> list[str]:
+ """The one canonical copy of an org-wide object or field, or nothing.
+
+ Copies across package dirs and ``unpackaged/config/*`` are fragments of
+ the same object. Ranked: package dir (default first, then listed order),
+ then anything else; within a rank the shortest path, then lexicographic.
+ """
+
+ def rank(pair: tuple[str, str]) -> tuple[int, int, str]:
+ path = pair[0]
+ place = next(
+ (
+ i
+ for i, d in enumerate(self.package_dirs)
+ if path == d or path.startswith(d + "/")
+ ),
+ len(self.package_dirs),
+ )
+ return (place, len(path), path)
+
+ best = min(paths_ids, key=rank, default=None)
+ return [best[1]] if best is not None else []
+
+
+def _read_project(repo_path: Path | None) -> _Project:
+ dirs: list[str] = []
+ namespaces: set[str] = set()
+ if repo_path is not None:
+ try:
+ data = json.loads((repo_path / "sfdx-project.json").read_text(encoding="utf-8"))
+ entries = [e for e in data.get("packageDirectories") or [] if isinstance(e, dict)]
+ # The default package directory ranks first, the rest in listed order.
+ for entry in sorted(entries, key=lambda e: e.get("default") is not True):
+ d = str(entry.get("path") or "").replace("\\", "/").strip("/")
+ d = d[2:] if d.startswith("./") else d
+ if d:
+ dirs.append(d)
+ if data.get("namespace"):
+ namespaces.add(str(data["namespace"]))
+ except (OSError, ValueError, AttributeError):
+ pass
+ try:
+ config = yaml.safe_load((repo_path / "cumulusci.yml").read_text(encoding="utf-8"))
+ namespace = config["project"]["package"]["namespace"]
+ if namespace:
+ namespaces.add(str(namespace))
+ except (OSError, yaml.YAMLError, KeyError, TypeError):
+ pass
+ return _Project(tuple(dirs), frozenset(f"{ns.lower()}__" for ns in namespaces))
+
+
+@dataclass
+class _Index:
+ project: _Project
+ objects: dict[str, list[tuple[str, str]]] # key -> [(path, symbol id)]
+ fields: dict[tuple[str, str], list[tuple[str, str]]] # (object key, field key)
+ lookups: dict[str, set[str]] # field symbol id -> referenced object keys
+
+
+def _build_index(parsed_files: dict[str, ParsedFile], project: _Project) -> _Index:
+ objects: dict[str, list[tuple[str, str]]] = defaultdict(list)
+ fields: dict[tuple[str, str], list[tuple[str, str]]] = defaultdict(list)
+ lookups: dict[str, set[str]] = defaultdict(set)
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language != _LANGUAGE:
+ continue
+ for sym in parsed.symbols:
+ if sym.kind == "class":
+ objects[project.key(sym.name)].append((path, sym.id))
+ elif sym.kind == "property" and "." in sym.qualified_name:
+ obj = sym.qualified_name.rsplit(".", 1)[0]
+ fields[(project.key(obj), project.key(sym.name))].append((path, sym.id))
+ for ref in parsed.schema_refs:
+ lookups[ref.source_symbol_id].add(project.key(ref.object_name))
+ return _Index(project, objects, fields, lookups)
+
+
+def _resolve(index: _Index, ref: SchemaReference) -> Iterator[str]:
+ key = index.project.key
+ current = key(ref.object_name)
+ if not ref.path:
+ yield from index.project.preferred(index.objects.get(current, ()))
+ return
+ for i, segment in enumerate(ref.path):
+ seg = key(segment)
+ if i == len(ref.path) - 1:
+ yield from index.project.preferred(index.fields.get((current, seg), ()))
+ return
+ # ``Rel__r`` hops through lookup ``Rel__c`` (``Account`` through ``AccountId``) to one object.
+ lookup = seg[:-3] + "__c" if seg.endswith("__r") else seg + "id"
+ copies = index.fields.get((current, lookup), ())
+ yield from index.project.preferred(copies)
+ # Every copy is a fragment of one field, so any of them may carry the referenceTo.
+ targets = set().union(*(index.lookups.get(sid, set()) for _, sid in copies))
+ if len(targets) != 1:
+ return
+ current = next(iter(targets))
+
+
+def add_schema_edges(
+ graph: nx.DiGraph, parsed_files: dict[str, ParsedFile], repo_path: Path | None
+) -> int:
+ """Add a symbol ``references`` and a file ``reads`` edge per bound reference.
+
+ Returns the symbol edges added. Not ``calls``: a query runs no code.
+ """
+ if not any(p.schema_refs for p in parsed_files.values()):
+ return 0
+ index = _build_index(parsed_files, _read_project(repo_path))
+ added = 0
+ for parsed in parsed_files.values():
+ for ref in parsed.schema_refs:
+ source = ref.source_symbol_id
+ if source not in graph:
+ continue
+ for target in _resolve(index, ref):
+ if target not in graph:
+ continue
+ if not graph.has_edge(source, target):
+ graph.add_edge(
+ source,
+ target,
+ edge_type="references",
+ confidence=_CONFIDENCE,
+ hint_source="salesforce_schema",
+ )
+ added += 1
+ src_file = graph.nodes[source].get("file_path")
+ tgt_file = graph.nodes[target].get("file_path")
+ if (
+ src_file
+ and tgt_file
+ and src_file != tgt_file
+ and not graph.has_edge(src_file, tgt_file)
+ ):
+ graph.add_edge(
+ src_file,
+ tgt_file,
+ edge_type="reads",
+ confidence=_CONFIDENCE,
+ imported_names=[],
+ )
+ return added
diff --git a/packages/core/src/repowise/core/ingestion/salesforce_soql.py b/packages/core/src/repowise/core/ingestion/salesforce_soql.py
new file mode 100644
index 000000000..c820e5d6f
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/salesforce_soql.py
@@ -0,0 +1,355 @@
+"""SObject and field names written in Apex SOQL/SOSL, DML and triggers.
+
+Read: SOQL ``FROM`` objects and field paths (a select-list subquery names a
+child relationship, so it is skipped), SOSL ``RETURNING`` objects, DML targets
+by declared type, ``trigger ... on Obj``, single-literal ``Database.query`` /
+``Search.query`` strings and ``.soql`` files.
+
+Ceiling: ``Account.Name.getDescribe()`` tokens, ``TYPEOF`` branches and the
+child object behind a relationship name are not read.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from functools import lru_cache
+
+from tree_sitter import Language, Node, Parser
+
+from .models import FileInfo, ParsedFile, SchemaReference, Symbol
+from .parser_helpers import _find_enclosing_symbol
+
+_QUERY_METHODS = frozenset(
+ {
+ "query",
+ "querywithbinds",
+ "getquerylocator",
+ "getquerylocatorwithbinds",
+ "countquery",
+ "countquerywithbinds",
+ }
+)
+_DML_METHODS = frozenset({"insert", "update", "upsert", "delete", "undelete", "merge"})
+_COLLECTIONS = frozenset({"list", "set"})
+_BODIES = frozenset({"soql_query_body", "sosl_query_body"})
+_SCOPES = frozenset({"method_declaration", "constructor_declaration", "trigger_declaration"})
+_DECLARATIONS = frozenset(
+ {"local_variable_declaration", "formal_parameter", "enhanced_for_statement"}
+)
+
+# (node to report, object name, field path)
+_Emit = Callable[[Node, str, tuple[str, ...]], None]
+
+
+def _text(node: Node | None) -> str:
+ return node.text.decode("utf-8", errors="replace") if node is not None and node.text else ""
+
+
+@lru_cache(maxsize=2)
+def _language(grammar: str) -> Language | None:
+ try:
+ from tree_sitter_language_pack import get_language
+
+ return get_language(grammar) # type: ignore[arg-type]
+ except Exception:
+ return None
+
+
+def _parser(grammar: str) -> Parser | None:
+ """A fresh parser per use: a ``Parser`` is not safe to share across threads."""
+ language = _language(grammar)
+ return Parser(language) if language is not None else None
+
+
+# ---------------------------------------------------------------------------
+# Query bodies (shared by the Apex, SOQL and SOSL grammars)
+# ---------------------------------------------------------------------------
+
+
+def _field_path(node: Node, alias: str | None) -> tuple[str, ...]:
+ parts = [_text(c) for c in node.named_children if c.type == "identifier"]
+ if not parts:
+ parts = [
+ _text(c)
+ for d in node.named_children
+ if d.type == "dotted_identifier"
+ for c in d.named_children
+ ]
+ if alias and len(parts) > 1 and parts[0].lower() == alias:
+ parts = parts[1:]
+ return tuple(parts)
+
+
+def _soql(body: Node, emit: _Emit) -> None:
+ obj: str | None = None
+ alias: str | None = None
+ from_clause = body.child_by_field_name("from_clause")
+ if from_clause is not None:
+ storage = next(
+ (
+ n
+ for c in from_clause.named_children
+ for n in ([c] if c.type == "storage_identifier" else c.named_children)
+ if n.type == "storage_identifier"
+ ),
+ None,
+ )
+ name = _text(storage)
+ if storage is not None and name and "." not in name:
+ obj = name
+ emit(storage, obj, ())
+ holder = storage.parent
+ if holder is not None and holder.type == "storage_alias":
+ alias_node = next(
+ (c for c in holder.named_children if c.type == "identifier"), None
+ )
+ alias = _text(alias_node).lower() or None
+
+ def walk(node: Node, in_select: bool) -> None:
+ for child in node.named_children:
+ kind = child.type
+ if kind in ("from_clause", "type_of_clause", "bound_apex_expression"):
+ continue
+ if kind == "subquery":
+ # In the select list it names a child relationship, not an object.
+ inner = next((c for c in child.named_children if c.type == "soql_query_body"), None)
+ if inner is not None and not in_select:
+ _soql(inner, emit)
+ continue
+ if kind == "field_identifier":
+ path = _field_path(child, alias)
+ if obj and path:
+ emit(child, obj, path)
+ continue
+ walk(child, in_select or kind == "select_clause")
+
+ walk(body, False)
+
+
+def _descendants(node: Node, stop: frozenset[str] = frozenset()) -> list[Node]:
+ """Every named descendant, not entering node types in *stop*."""
+ out: list[Node] = []
+ stack = list(node.named_children)
+ while stack:
+ child = stack.pop()
+ out.append(child)
+ if child.type not in stop:
+ stack.extend(child.named_children)
+ return out
+
+
+def _sosl(body: Node, emit: _Emit) -> None:
+ for node in _descendants(body, frozenset({"sobject_return"})):
+ if node.type != "sobject_return":
+ continue
+ ident = next((c for c in node.named_children if c.type == "identifier"), None)
+ obj = _text(ident)
+ if ident is None or not obj:
+ continue
+ emit(ident, obj, ())
+ for field in _descendants(node, frozenset({"field_identifier", "bound_apex_expression"})):
+ path = _field_path(field, None) if field.type == "field_identifier" else ()
+ if path:
+ emit(field, obj, path)
+
+
+def _query(node: Node, emit: _Emit) -> None:
+ for child in node.named_children if node.type not in _BODIES else [node]:
+ if child.type == "soql_query_body":
+ _soql(child, emit)
+ elif child.type == "sosl_query_body":
+ _sosl(child, emit)
+
+
+def _literal_query(literal: Node, grammar: str, emit: _Emit) -> None:
+ """Re-parse one Apex string literal as a standalone query, reported at the literal."""
+ raw = _text(literal)
+ if len(raw) < 2 or raw[0] != "'" or raw[-1] != "'":
+ return
+ text = raw[1:-1].replace("\\'", "'").replace("\\\\", "\\")
+ parser = _parser(grammar)
+ if parser is None:
+ return
+ root = parser.parse(text.encode("utf-8")).root_node
+ _query(root, lambda _n, obj, path: emit(literal, obj, path))
+
+
+# ---------------------------------------------------------------------------
+# DML targets
+# ---------------------------------------------------------------------------
+
+
+def _type_name(node: Node | None) -> str | None:
+ """The SObject a declared type holds: ``Account``, ``List<Account>``, ``Account[]``."""
+ if node is None:
+ return None
+ if node.type == "generic_type":
+ base = next((c for c in node.named_children if c.type != "type_arguments"), None)
+ args = next((c for c in node.named_children if c.type == "type_arguments"), None)
+ if _text(base).lower() not in _COLLECTIONS or args is None or not args.named_children:
+ return None
+ return _type_name(args.named_children[0])
+ if node.type == "array_type":
+ return _type_name(node.child_by_field_name("element"))
+ if node.type in ("type_identifier", "scoped_type_identifier"):
+ return _text(node).rpartition(".")[2] or None
+ return None
+
+
+def _declared_names(decl: Node) -> list[str]:
+ name = decl.child_by_field_name("name")
+ if name is not None:
+ return [_text(name)]
+ return [
+ _text(d.child_by_field_name("name"))
+ for d in decl.named_children
+ if d.type == "variable_declarator"
+ ]
+
+
+def _key(node: Node) -> tuple[int, int, str]:
+ return (node.start_byte, node.end_byte, node.type)
+
+
+def _visible(decl: Node, ancestors: set[tuple[int, int, str]]) -> bool:
+ if decl.type == "formal_parameter":
+ return True
+ holder = decl if decl.type == "enhanced_for_statement" else decl.parent
+ return holder is not None and _key(holder) in ancestors
+
+
+def _declares(node: Node, wanted: str) -> bool:
+ return wanted in (n.lower() for n in _declared_names(node))
+
+
+def _local_declaration(scope: Node, use: Node, wanted: str) -> Node | None:
+ """The nearest earlier declaration of *wanted* in *scope* that is visible at *use*.
+
+ Visible means its scope encloses the use: a local's enclosing block, a
+ for-each's own statement, or the method's parameters.
+ """
+ ancestors: set[tuple[int, int, str]] = set()
+ node = use.parent
+ while node is not None and _key(node) != _key(scope):
+ ancestors.add(_key(node))
+ node = node.parent
+ candidates = [
+ n
+ for n in _descendants(scope)
+ if n.start_byte < use.start_byte
+ and n.type in _DECLARATIONS
+ and _declares(n, wanted)
+ and _visible(n, ancestors)
+ ]
+ return max(candidates, key=lambda n: n.start_byte, default=None)
+
+
+def _field_declaration(node: Node, wanted: str) -> Node | None:
+ klass = node.parent
+ while klass is not None and klass.type != "class_body":
+ klass = klass.parent
+ if klass is None:
+ return None
+ return next(
+ (f for f in klass.named_children if f.type == "field_declaration" and _declares(f, wanted)),
+ None,
+ )
+
+
+def _declared_type(use: Node, name: str) -> str | None:
+ """The type the nearest visible declaration of *name* gives it, method then class."""
+ wanted = name.lower()
+ scope = use.parent
+ while scope is not None and scope.type not in _SCOPES:
+ scope = scope.parent
+ best = _local_declaration(scope, use, wanted) if scope is not None else None
+ if best is None:
+ best = _field_declaration(scope or use, wanted)
+ return _type_name(best.child_by_field_name("type")) if best is not None else None
+
+
+def _dml_type(target: Node | None) -> str | None:
+ if target is None:
+ return None
+ # ``new Account(...)``, ``new Account[]{..}``, ``new List<Account>{..}``
+ if target.type in ("object_creation_expression", "array_creation_expression"):
+ return _type_name(target.child_by_field_name("type"))
+ if target.type == "identifier":
+ return _declared_type(target, _text(target))
+ if target.type == "field_access" and _text(target.child_by_field_name("object")) == "this":
+ field = target.child_by_field_name("field")
+ return _declared_type(target, _text(field)) if field is not None else None
+ return None
+
+
+def _database_call(node: Node, emit: _Emit) -> None:
+ receiver = node.child_by_field_name("object")
+ method = _text(node.child_by_field_name("name")).lower()
+ args = node.child_by_field_name("arguments")
+ if receiver is None or receiver.type != "identifier" or args is None:
+ return
+ first = args.named_children[0] if args.named_children else None
+ if first is None:
+ return
+ owner = _text(receiver).lower()
+ if owner == "database" and method in _QUERY_METHODS:
+ if first.type == "string_literal":
+ _literal_query(first, "soql", emit)
+ elif owner == "search" and method == "query":
+ if first.type == "string_literal":
+ _literal_query(first, "sosl", emit)
+ elif owner == "database" and method in _DML_METHODS:
+ obj = _dml_type(first)
+ if obj:
+ emit(node, obj, ())
+
+
+# ---------------------------------------------------------------------------
+# Entry points
+# ---------------------------------------------------------------------------
+
+
+def _collector(path: str, symbols: list[Symbol]) -> tuple[list[SchemaReference], _Emit]:
+ ranges = sorted(((s.start_line, s.end_line, s.id) for s in symbols), key=lambda t: (t[0], -t[1]))
+ module = f"{path}::__module__"
+ refs: list[SchemaReference] = []
+
+ def emit(node: Node, obj: str, field_path: tuple[str, ...]) -> None:
+ line = node.start_point[0] + 1
+ owner = _find_enclosing_symbol(line, ranges) or module
+ refs.append(SchemaReference(owner, obj, line, field_path))
+
+ return refs, emit
+
+
+def apex_schema_refs(root: Node, symbols: list[Symbol], path: str) -> list[SchemaReference]:
+ """Every SObject and field an Apex file names statically."""
+ refs, emit = _collector(path, symbols)
+ stack = [root]
+ while stack:
+ node = stack.pop()
+ kind = node.type
+ if kind in _BODIES:
+ _query(node, emit)
+ continue
+ if kind == "trigger_declaration":
+ obj = node.child_by_field_name("object")
+ if obj is not None and _text(obj):
+ emit(obj, _text(obj), ())
+ elif kind == "dml_expression":
+ obj_name = _dml_type(node.child_by_field_name("target"))
+ if obj_name:
+ emit(node, obj_name, ())
+ elif kind == "method_invocation":
+ _database_call(node, emit)
+ stack.extend(node.named_children)
+ return refs
+
+
+def parse_soql_file(file_info: FileInfo, source: bytes) -> ParsedFile:
+ """A ``.soql`` file: the objects and fields its query names, owned by the file."""
+ refs, emit = _collector(file_info.path, [])
+ parser = _parser("soql")
+ if parser is not None:
+ _query(parser.parse(source).root_node, emit)
+ return ParsedFile(file_info=file_info, symbols=[], imports=[], exports=[], schema_refs=refs)
diff --git a/packages/core/src/repowise/core/ingestion/special_handlers.py b/packages/core/src/repowise/core/ingestion/special_handlers.py
index e1f9e8db8..d554ca0c5 100644
--- a/packages/core/src/repowise/core/ingestion/special_handlers.py
+++ b/packages/core/src/repowise/core/ingestion/special_handlers.py
@@ -19,6 +19,8 @@ import structlog
from .models import FileInfo, Import, ParsedFile, Symbol
from .salesforce_flow import parse_flow_file
+from .salesforce_schema import parse_object_metadata
+from .salesforce_soql import parse_soql_file
log = structlog.get_logger(__name__)
@@ -26,7 +28,7 @@ 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", "salesforce_flow"}
+ {"openapi", "dockerfile", "makefile", "sql", "salesforce_flow", "salesforce_object", "soql"}
)
@@ -43,6 +45,8 @@ def parse_special(file_info: FileInfo, source: bytes, lang: str) -> ParsedFile:
"makefile": _parse_makefile,
"sql": _parse_sql,
"salesforce_flow": parse_flow_file,
+ "salesforce_object": parse_object_metadata,
+ "soql": parse_soql_file,
}.get(lang, _parse_unknown)
try:
return handler(file_info, source)
diff --git a/tests/unit/ingestion/parser/golden/apex.json b/tests/unit/ingestion/parser/golden/apex.json
index 14547f98c..d5cdcf86b 100644
--- a/tests/unit/ingestion/parser/golden/apex.json
+++ b/tests/unit/ingestion/parser/golden/apex.json
@@ -587,7 +587,45 @@
],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": [
+ {
+ "source_symbol_id": "lang_samples/apex/AccountService.cls::AccountService::execute",
+ "object_name": "Account",
+ "line": 28,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/AccountService.cls::AccountService::findByName",
+ "object_name": "Account",
+ "line": 23,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/AccountService.cls::AccountService::findByName",
+ "object_name": "Account",
+ "line": 23,
+ "path": [
+ "Id"
+ ]
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/AccountService.cls::AccountService::findByName",
+ "object_name": "Account",
+ "line": 23,
+ "path": [
+ "Name"
+ ]
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/AccountService.cls::AccountService::findByName",
+ "object_name": "Account",
+ "line": 23,
+ "path": [
+ "Name"
+ ]
+ }
+ ]
},
"apex/AccountTrigger.trigger": {
"file_info": {
@@ -691,7 +729,15 @@
],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": [
+ {
+ "source_symbol_id": "lang_samples/apex/AccountTrigger.trigger::AccountTrigger",
+ "object_name": "Account",
+ "line": 1,
+ "path": []
+ }
+ ]
},
"apex/assertions.cls": {
"file_info": {
@@ -1146,7 +1192,15 @@
],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": [
+ {
+ "source_symbol_id": "lang_samples/apex/assertions.cls::Assertions::makeData",
+ "object_name": "Account",
+ "line": 34,
+ "path": []
+ }
+ ]
},
"apex/classes.cls": {
"file_info": {
@@ -1631,7 +1685,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"apex/nested.cls": {
"file_info": {
@@ -1835,7 +1890,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"apex/perf_io_in_loop.cls": {
"file_info": {
@@ -2836,6 +2892,204 @@
],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": [
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::cursor",
+ "object_name": "Account",
+ "line": 141,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::cursor",
+ "object_name": "Account",
+ "line": 141,
+ "path": [
+ "ParentId"
+ ]
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::cursor",
+ "object_name": "Account",
+ "line": 141,
+ "path": [
+ "Id"
+ ]
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::mergeAll",
+ "object_name": "Account",
+ "line": 133,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::customMetadata",
+ "object_name": "Setting__mdt",
+ "line": 127,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::customMetadata",
+ "object_name": "Setting__mdt",
+ "line": 127,
+ "path": [
+ "Id"
+ ]
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::customMetadata",
+ "object_name": "Setting__mdt",
+ "line": 127,
+ "path": [
+ "DeveloperName"
+ ]
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::firstMatch",
+ "object_name": "Account",
+ "line": 106,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::cached",
+ "object_name": "Account",
+ "line": 98,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::cached",
+ "object_name": "Account",
+ "line": 98,
+ "path": [
+ "Id"
+ ]
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::flushAtSize",
+ "object_name": "Account",
+ "line": 88,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::chunked",
+ "object_name": "Account",
+ "line": 79,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::literalBound",
+ "object_name": "Task",
+ "line": 73,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::literalBound",
+ "object_name": "Task",
+ "line": 70,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::soqlForChunks",
+ "object_name": "Account",
+ "line": 64,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::soqlForChunks",
+ "object_name": "Account",
+ "line": 63,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::soqlForChunks",
+ "object_name": "Account",
+ "line": 63,
+ "path": [
+ "Id"
+ ]
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::queryInHeader",
+ "object_name": "Account",
+ "line": 57,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::queryInHeader",
+ "object_name": "Account",
+ "line": 57,
+ "path": [
+ "Id"
+ ]
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::bulk",
+ "object_name": "Contact",
+ "line": 53,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::bulk",
+ "object_name": "Contact",
+ "line": 53,
+ "path": [
+ "Id"
+ ]
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::bulk",
+ "object_name": "Contact",
+ "line": 53,
+ "path": [
+ "AccountId"
+ ]
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::bulk",
+ "object_name": "Account",
+ "line": 52,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::nested",
+ "object_name": "Task",
+ "line": 40,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::databaseAndCallout",
+ "object_name": "Id",
+ "line": 21,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::dmlPerRecord",
+ "object_name": "Account",
+ "line": 14,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::soqlPerRecord",
+ "object_name": "Account",
+ "line": 8,
+ "path": []
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::soqlPerRecord",
+ "object_name": "Account",
+ "line": 8,
+ "path": [
+ "Id"
+ ]
+ },
+ {
+ "source_symbol_id": "lang_samples/apex/perf_io_in_loop.cls::PerfIoInLoop::soqlPerRecord",
+ "object_name": "Account",
+ "line": 8,
+ "path": [
+ "Id"
+ ]
+ }
+ ]
}
}
diff --git a/tests/unit/ingestion/parser/golden/cpp.json b/tests/unit/ingestion/parser/golden/cpp.json
index 6fdf33ff3..110abe528 100644
--- a/tests/unit/ingestion/parser/golden/cpp.json
+++ b/tests/unit/ingestion/parser/golden/cpp.json
@@ -344,7 +344,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"cpp/classes.cpp": {
"file_info": {
@@ -673,7 +674,8 @@
"argument_types": null,
"argument_names": null
}
- ]
+ ],
+ "schema_refs": []
},
"cpp/nested.cpp": {
"file_info": {
@@ -773,6 +775,7 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
}
}
diff --git a/tests/unit/ingestion/parser/golden/csharp.json b/tests/unit/ingestion/parser/golden/csharp.json
index e0a98f0df..2bd809140 100644
--- a/tests/unit/ingestion/parser/golden/csharp.json
+++ b/tests/unit/ingestion/parser/golden/csharp.json
@@ -507,7 +507,8 @@
],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"csharp/assertions.cs": {
"file_info": {
@@ -874,7 +875,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"csharp/classes.cs": {
"file_info": {
@@ -1264,7 +1266,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"csharp/nested.cs": {
"file_info": {
@@ -1383,6 +1386,7 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
}
}
diff --git a/tests/unit/ingestion/parser/golden/dart.json b/tests/unit/ingestion/parser/golden/dart.json
index 5fab2093e..d6065a19d 100644
--- a/tests/unit/ingestion/parser/golden/dart.json
+++ b/tests/unit/ingestion/parser/golden/dart.json
@@ -73,7 +73,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"dart/classes.dart": {
"file_info": {
@@ -333,7 +334,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"dart/nested.dart": {
"file_info": {
@@ -433,7 +435,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"dart/perf_io_in_loop.dart": {
"file_info": {
@@ -736,6 +739,7 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
}
}
diff --git a/tests/unit/ingestion/parser/golden/go.json b/tests/unit/ingestion/parser/golden/go.json
index 74be72593..62a37050e 100644
--- a/tests/unit/ingestion/parser/golden/go.json
+++ b/tests/unit/ingestion/parser/golden/go.json
@@ -97,7 +97,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"go/nested.go": {
"file_info": {
@@ -173,7 +174,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"go/perf_io_in_loop.go": {
"file_info": {
@@ -660,6 +662,7 @@
],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
}
}
diff --git a/tests/unit/ingestion/parser/golden/java.json b/tests/unit/ingestion/parser/golden/java.json
index 40ea03d8f..ad96ebfc7 100644
--- a/tests/unit/ingestion/parser/golden/java.json
+++ b/tests/unit/ingestion/parser/golden/java.json
@@ -118,7 +118,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"java/Nested.java": {
"file_info": {
@@ -214,7 +215,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"java/PerfIoInLoop.java": {
"file_info": {
@@ -762,6 +764,7 @@
],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
}
}
diff --git a/tests/unit/ingestion/parser/golden/javascript.json b/tests/unit/ingestion/parser/golden/javascript.json
index 5b491350e..640984d9c 100644
--- a/tests/unit/ingestion/parser/golden/javascript.json
+++ b/tests/unit/ingestion/parser/golden/javascript.json
@@ -70,7 +70,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"javascript/route.js": {
"file_info": {
@@ -479,6 +480,7 @@
"argument_types": null,
"argument_names": null
}
- ]
+ ],
+ "schema_refs": []
}
}
diff --git a/tests/unit/ingestion/parser/golden/kotlin.json b/tests/unit/ingestion/parser/golden/kotlin.json
index 222848ef3..bb0a6a6d6 100644
--- a/tests/unit/ingestion/parser/golden/kotlin.json
+++ b/tests/unit/ingestion/parser/golden/kotlin.json
@@ -344,7 +344,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"kotlin/classes.kt": {
"file_info": {
@@ -719,7 +720,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"kotlin/nested.kt": {
"file_info": {
@@ -819,6 +821,7 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
}
}
diff --git a/tests/unit/ingestion/parser/golden/lean.json b/tests/unit/ingestion/parser/golden/lean.json
index 03801217e..4bb63a9f0 100644
--- a/tests/unit/ingestion/parser/golden/lean.json
+++ b/tests/unit/ingestion/parser/golden/lean.json
@@ -23,7 +23,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"lean/Main.lean": {
"file_info": {
@@ -86,7 +87,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"lean/Plain/Local.lean": {
"file_info": {
@@ -112,7 +114,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"lean/Public/Visible.lean": {
"file_info": {
@@ -138,6 +141,7 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
}
}
diff --git a/tests/unit/ingestion/parser/golden/pascal.json b/tests/unit/ingestion/parser/golden/pascal.json
index 770021141..0bdb65299 100644
--- a/tests/unit/ingestion/parser/golden/pascal.json
+++ b/tests/unit/ingestion/parser/golden/pascal.json
@@ -49,7 +49,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"pascal/nested.pas": {
"file_info": {
@@ -141,6 +142,7 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
}
}
diff --git a/tests/unit/ingestion/parser/golden/php.json b/tests/unit/ingestion/parser/golden/php.json
index 9ae0c53c4..9501408ab 100644
--- a/tests/unit/ingestion/parser/golden/php.json
+++ b/tests/unit/ingestion/parser/golden/php.json
@@ -234,7 +234,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"php/classes.php": {
"file_info": {
@@ -743,7 +744,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"php/clean.php": {
"file_info": {
@@ -819,7 +821,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"php/nested.php": {
"file_info": {
@@ -1115,6 +1118,7 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
}
}
diff --git a/tests/unit/ingestion/parser/golden/python.json b/tests/unit/ingestion/parser/golden/python.json
index d2b67819e..ea107592e 100644
--- a/tests/unit/ingestion/parser/golden/python.json
+++ b/tests/unit/ingestion/parser/golden/python.json
@@ -229,7 +229,8 @@
"do_work"
],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"python/classes.py": {
"file_info": {
@@ -551,7 +552,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"python/complex.py": {
"file_info": {
@@ -603,7 +605,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"python/conditionals.py": {
"file_info": {
@@ -703,7 +706,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"python/match.py": {
"file_info": {
@@ -779,7 +783,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"python/nested.py": {
"file_info": {
@@ -855,7 +860,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"python/perf_io_in_loop.py": {
"file_info": {
@@ -1614,7 +1620,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"python/py_overload_init.py": {
"file_info": {
@@ -1970,6 +1977,7 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
}
}
diff --git a/tests/unit/ingestion/parser/golden/ruby.json b/tests/unit/ingestion/parser/golden/ruby.json
index 6f963bb0b..492ed1cd7 100644
--- a/tests/unit/ingestion/parser/golden/ruby.json
+++ b/tests/unit/ingestion/parser/golden/ruby.json
@@ -234,7 +234,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"ruby/classes.rb": {
"file_info": {
@@ -564,7 +565,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"ruby/nested.rb": {
"file_info": {
@@ -947,7 +949,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"ruby/perf_io_in_loop.rb": {
"file_info": {
@@ -1725,6 +1728,7 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
}
}
diff --git a/tests/unit/ingestion/parser/golden/rust.json b/tests/unit/ingestion/parser/golden/rust.json
index dcca8bcca..d79ecb7e3 100644
--- a/tests/unit/ingestion/parser/golden/rust.json
+++ b/tests/unit/ingestion/parser/golden/rust.json
@@ -97,7 +97,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"rust/flat_match.rs": {
"file_info": {
@@ -193,7 +194,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"rust/nested.rs": {
"file_info": {
@@ -266,7 +268,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"rust/perf_io_in_loop.rs": {
"file_info": {
@@ -787,6 +790,7 @@
"argument_types": null,
"argument_names": null
}
- ]
+ ],
+ "schema_refs": []
}
}
diff --git a/tests/unit/ingestion/parser/golden/scala.json b/tests/unit/ingestion/parser/golden/scala.json
index 03f16a3ed..2d5da7362 100644
--- a/tests/unit/ingestion/parser/golden/scala.json
+++ b/tests/unit/ingestion/parser/golden/scala.json
@@ -231,7 +231,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"scala/classes.scala": {
"file_info": {
@@ -723,7 +724,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"scala/nested.scala": {
"file_info": {
@@ -913,7 +915,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"scala/perf_io_in_loop.scala": {
"file_info": {
@@ -1497,6 +1500,7 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
}
}
diff --git a/tests/unit/ingestion/parser/golden/shell.json b/tests/unit/ingestion/parser/golden/shell.json
index 918819b06..1b8c37425 100644
--- a/tests/unit/ingestion/parser/golden/shell.json
+++ b/tests/unit/ingestion/parser/golden/shell.json
@@ -119,7 +119,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"shell/functions.sh": {
"file_info": {
@@ -250,7 +251,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"shell/sourcing.sh": {
"file_info": {
@@ -400,7 +402,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"shell/zero_functions.sh": {
"file_info": {
@@ -442,7 +445,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"shell/zshisms.zsh": {
"file_info": {
@@ -510,6 +514,7 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
}
}
diff --git a/tests/unit/ingestion/parser/golden/swift.json b/tests/unit/ingestion/parser/golden/swift.json
index 6c0adc0c1..76e54ebcc 100644
--- a/tests/unit/ingestion/parser/golden/swift.json
+++ b/tests/unit/ingestion/parser/golden/swift.json
@@ -373,7 +373,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"swift/nested.swift": {
"file_info": {
@@ -469,6 +470,7 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
}
}
diff --git a/tests/unit/ingestion/parser/golden/typescript.json b/tests/unit/ingestion/parser/golden/typescript.json
index 68a726582..01eff4ef2 100644
--- a/tests/unit/ingestion/parser/golden/typescript.json
+++ b/tests/unit/ingestion/parser/golden/typescript.json
@@ -683,7 +683,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"typescript/classes.ts": {
"file_info": {
@@ -979,7 +980,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"typescript/conditionals.ts": {
"file_info": {
@@ -1079,7 +1081,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"typescript/nested.ts": {
"file_info": {
@@ -1155,7 +1158,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"typescript/perf_io_in_loop.ts": {
"file_info": {
@@ -1375,7 +1379,8 @@
],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"typescript/ts_class_modifiers.ts": {
"file_info": {
@@ -1789,7 +1794,8 @@
],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"typescript/ts_module_consts.ts": {
"file_info": {
@@ -1974,7 +1980,8 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
},
"typescript/ts_overload_fn_method.ts": {
"file_info": {
@@ -2299,6 +2306,7 @@
"type_refs": [],
"local_refs": [],
"registrars": [],
- "references": []
+ "references": [],
+ "schema_refs": []
}
}
diff --git a/tests/unit/ingestion/test_edge_type_vocabulary.py b/tests/unit/ingestion/test_edge_type_vocabulary.py
index e4bbb17ef..4269ae39e 100644
--- a/tests/unit/ingestion/test_edge_type_vocabulary.py
+++ b/tests/unit/ingestion/test_edge_type_vocabulary.py
@@ -443,10 +443,13 @@ def test_the_removed_phantoms_stay_removed(phantom: str) -> None:
def test_reads_edge_producer_is_strictly_file_level() -> None:
- """`reads` is produced exclusively by csharp_member_reads at the file level."""
+ """`reads` is produced only at the file level: C# member access and Salesforce schema."""
producers = [
path for path, types in _edge_type_literals().items() if "reads" in types
]
- assert producers == ["packages/core/src/repowise/core/ingestion/languages/csharp_member_reads.py"], (
+ assert sorted(producers) == [
+ "packages/core/src/repowise/core/ingestion/languages/csharp_member_reads.py",
+ "packages/core/src/repowise/core/ingestion/salesforce_schema.py",
+ ], (
f"`reads` edge emitted by unexpected producers: {producers}"
)
diff --git a/tests/unit/ingestion/test_salesforce_schema.py b/tests/unit/ingestion/test_salesforce_schema.py
new file mode 100644
index 000000000..45fc36609
--- /dev/null
+++ b/tests/unit/ingestion/test_salesforce_schema.py
@@ -0,0 +1,300 @@
+"""Salesforce object/field metadata as symbols, and the references bound to them."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+from repowise.core.ingestion.traverser import _detect_language, is_candidate_source_path
+
+_NS = 'xmlns="http://soap.sforce.com/2006/04/metadata"'
+
+
+def _object(label: str) -> str:
+ return f'<?xml version="1.0"?>\n<CustomObject {_NS}>\n <label>{label}</label>\n</CustomObject>\n'
+
+
+def _field(kind: str, reference_to: str | None = None) -> str:
+ ref = f" <referenceTo>{reference_to}</referenceTo>\n" if reference_to else ""
+ return (
+ f'<?xml version="1.0"?>\n<CustomField {_NS}>\n'
+ f" <fullName>X</fullName>\n <type>{kind}</type>\n{ref}</CustomField>\n"
+ )
+
+
+_MDAPI_OBJECT = f"""<?xml version="1.0"?>
+<CustomObject {_NS}>
+ <compactLayouts>
+ <fields>Name</fields>
+ </compactLayouts>
+ <fields>
+ <fullName>Job__c</fullName>
+ <referenceTo>Job__c</referenceTo>
+ <type>Lookup</type>
+ </fields>
+ <fields>
+ <fullName>Hours__c</fullName>
+ <type>Number</type>
+ </fields>
+ <label>Shift</label>
+</CustomObject>
+"""
+
+
+def _build(tmp_path: Path, files: dict[str, str]) -> nx.DiGraph:
+ for rel, text in files.items():
+ target = tmp_path / rel
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(text, encoding="utf-8")
+ parser = ASTParser()
+ builder = GraphBuilder(repo_path=tmp_path)
+ for fi in FileTraverser(tmp_path).traverse():
+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))
+ return builder.build()
+
+
+_ROOT = "force-app/main/default/objects"
+
+
+def test_only_object_and_field_metadata_are_claimed() -> None:
+ assert _detect_language(Path("objects/Account/Account.object-meta.xml")) == "salesforce_object"
+ assert _detect_language(Path("objects/A/fields/B__c.Field-Meta.XML")) == "salesforce_object"
+ assert _detect_language(Path("src/objects/Account.object")) == "salesforce_object"
+ assert _detect_language(Path("classes/Foo.cls-meta.xml")) == "unknown"
+ assert is_candidate_source_path("objects/A/fields/B__c.field-meta.xml")
+ assert not is_candidate_source_path("classes/Foo.cls-meta.xml")
+
+
+def test_object_and_field_symbols(tmp_path: Path) -> None:
+ g = _build(
+ tmp_path,
+ {
+ f"{_ROOT}/Job__c/Job__c.object-meta.xml": _object("Job"),
+ f"{_ROOT}/Job__c/fields/Due__c.field-meta.xml": _field("Date"),
+ },
+ )
+ obj = g.nodes[f"{_ROOT}/Job__c/Job__c.object-meta.xml::Job__c"]
+ assert obj["kind"] == "class"
+ field = g.nodes[f"{_ROOT}/Job__c/fields/Due__c.field-meta.xml::Due__c"]
+ assert field["kind"] == "property"
+ assert field["qualified_name"] == "Job__c.Due__c"
+
+
+def test_lookup_field_references_its_object(tmp_path: Path) -> None:
+ obj_file = f"{_ROOT}/Job__c/Job__c.object-meta.xml"
+ field_file = f"{_ROOT}/Shift__c/fields/Job__c.field-meta.xml"
+ g = _build(
+ tmp_path,
+ {
+ obj_file: _object("Job"),
+ field_file: _field("Lookup", "job__C"), # names compare case-insensitively
+ f"{_ROOT}/Shift__c/fields/Owner__c.field-meta.xml": _field("Lookup", "User"),
+ },
+ )
+ edge = g.get_edge_data(f"{field_file}::Job__c", f"{obj_file}::Job__c")
+ assert edge is not None and edge["edge_type"] == "references"
+ assert g.get_edge_data(field_file, obj_file)["edge_type"] == "reads"
+ # A standard object with no metadata in the repository: no edge, no guess.
+ owner = f"{_ROOT}/Shift__c/fields/Owner__c.field-meta.xml::Owner__c"
+ assert not [t for _, t, d in g.out_edges(owner, data=True) if d["edge_type"] == "references"]
+
+
+def test_mdapi_object_keeps_fields_inline(tmp_path: Path) -> None:
+ g = _build(
+ tmp_path,
+ {
+ "src/objects/Shift__c.object": _MDAPI_OBJECT,
+ "src/objects/Job__c.object": _object("Job"),
+ },
+ )
+ path = "src/objects/Shift__c.object"
+ fields = {
+ g.nodes[n]["name"]: g.nodes[n]
+ for n in g.nodes
+ if n.startswith(path + "::") and g.nodes[n].get("kind") == "property"
+ }
+ # compactLayouts/fields is a column list, not a field definition.
+ assert set(fields) == {"Job__c", "Hours__c"}
+ assert fields["Job__c"]["start_line"] == 6
+ edge = g.get_edge_data(f"{path}::Shift__c::Job__c", "src/objects/Job__c.object::Job__c")
+ assert edge is not None and edge["edge_type"] == "references"
+
+
+def test_package_directory_copy_wins_and_namespace_tokens_strip(tmp_path: Path) -> None:
+ (tmp_path / "sfdx-project.json").write_text(
+ json.dumps({"packageDirectories": [{"path": "force-app"}], "namespace": "acme"})
+ )
+ pkg_obj = f"{_ROOT}/Job__c/Job__c.object-meta.xml"
+ field_file = f"{_ROOT}/Shift__c/fields/Job__c.field-meta.xml"
+ g = _build(
+ tmp_path,
+ {
+ pkg_obj: _object("Job"),
+ "unpackaged/config/objects/___NAMESPACE___Job__c.object": _object("Job"),
+ field_file: _field("Lookup", "acme__Job__c"),
+ },
+ )
+ targets = {t for _, t, d in g.out_edges(f"{field_file}::Job__c", data=True)}
+ assert targets == {f"{pkg_obj}::Job__c"}
+ assert "unpackaged/config/objects/___NAMESPACE___Job__c.object::Job__c" in g
+
+
+def test_copies_of_one_object_bind_one_canonical_copy(tmp_path: Path) -> None:
+ (tmp_path / "sfdx-project.json").write_text(
+ json.dumps(
+ {"packageDirectories": [{"path": "pkg-a"}, {"path": "pkg-b", "default": True}]}
+ )
+ )
+ account = "objects/Account/Account.object-meta.xml"
+ contact = "objects/Contact.object"
+ mdapi_contact = _object("Contact").replace(
+ "</CustomObject>",
+ " <fields>\n <fullName>Level__c</fullName>\n <type>Text</type>\n"
+ " </fields>\n</CustomObject>",
+ )
+ lookup = "pkg-b/objects/Shift__c/fields/Who__c.field-meta.xml"
+ # A packaged fragment of Pay__c with no referenceTo; the test-org copy carries it.
+ pay = "pkg-b/objects/Shift__c/fields/Pay__c.field-meta.xml"
+ cls = "pkg-b/classes/Q.cls"
+ qa_contact = f"unpackaged/config/qa/{contact}"
+ g = _build(
+ tmp_path,
+ {
+ # Package copies in two dirs and a test-org copy: the default dir wins.
+ f"pkg-a/{account}": _object("Account"),
+ f"pkg-b/{account}": _object("Account"),
+ f"unpackaged/config/dev/{account}": _object("Account"),
+ # Only test-org copies: the shortest path wins.
+ f"unpackaged/config/dev/{contact}": mdapi_contact,
+ qa_contact: mdapi_contact,
+ lookup: _field("Lookup", "Contact"),
+ pay: _field("Lookup"),
+ "unpackaged/config/qa/objects/Shift__c/fields/Pay__c.field-meta.xml": _field(
+ "Lookup", "Contact"
+ ),
+ cls: "public class Q {\n void m() {\n List<Account> a = [SELECT Id FROM Account];"
+ "\n List<Contact> c = [SELECT Level__c FROM Contact];"
+ "\n List<Shift__c> s = [SELECT Who__r.Level__c FROM Shift__c];"
+ "\n List<Shift__c> p = [SELECT Pay__r.Level__c FROM Shift__c];\n }\n}\n",
+ },
+ )
+
+ def refs(source: str) -> set[str]:
+ return {t for _, t, d in g.out_edges(source, data=True) if d["edge_type"] == "references"}
+
+ assert refs(f"{cls}::Q::m") == {
+ f"pkg-b/{account}::Account",
+ f"{qa_contact}::Contact",
+ f"{qa_contact}::Contact::Level__c",
+ f"{lookup}::Who__c",
+ f"{pay}::Pay__c",
+ }
+ assert refs(f"{lookup}::Who__c") == {f"{qa_contact}::Contact"}
+
+
+def test_malformed_metadata_yields_no_symbols(tmp_path: Path) -> None:
+ g = _build(tmp_path, {f"{_ROOT}/Bad__c/Bad__c.object-meta.xml": "<CustomObject><label>"})
+ assert f"{_ROOT}/Bad__c/Bad__c.object-meta.xml" in g
+ assert f"{_ROOT}/Bad__c/Bad__c.object-meta.xml::Bad__c" not in g
+
+
+def test_soql_file_references_object_and_fields(tmp_path: Path) -> None:
+ obj_file = f"{_ROOT}/Job__c/Job__c.object-meta.xml"
+ field_file = f"{_ROOT}/Job__c/fields/Due__c.field-meta.xml"
+ g = _build(
+ tmp_path,
+ {
+ obj_file: _object("Job"),
+ field_file: _field("Date"),
+ "scripts/soql/jobs.soql": "// saved query\nSELECT Id, due__c FROM Job__c\n",
+ },
+ )
+ module = "scripts/soql/jobs.soql::__module__"
+ targets = {t for _, t, d in g.out_edges(module, data=True) if d["edge_type"] == "references"}
+ assert targets == {f"{obj_file}::Job__c", f"{field_file}::Due__c"}
+ assert g.get_edge_data("scripts/soql/jobs.soql", obj_file)["edge_type"] == "reads"
+
+
+_APEX = """public with sharing class JobService {
+ private List<Job__c> pending;
+ public static List<Job__c> open(Set<Id> ids) {
+ return [SELECT Id, due__c, Shift__r.Hours__c, (SELECT Id FROM Shifts__r)
+ FROM job__c j WHERE j.Due__c != null AND Id IN :ids];
+ }
+ public void save(Job__c job) {
+ insert job;
+ update this.pending;
+ Database.query('SELECT Id FROM Shift__c');
+ Database.query('SELECT Id FROM ' + job.Name);
+ Account a = new Account();
+ insert a;
+ }
+}
+"""
+
+
+def test_apex_soql_dml_and_trigger_reference_schema_symbols(tmp_path: Path) -> None:
+ job = f"{_ROOT}/Job__c/Job__c.object-meta.xml"
+ due = f"{_ROOT}/Job__c/fields/Due__c.field-meta.xml"
+ shift_lookup = f"{_ROOT}/Job__c/fields/Shift__c.field-meta.xml"
+ shift = f"{_ROOT}/Shift__c/Shift__c.object-meta.xml"
+ hours = f"{_ROOT}/Shift__c/fields/Hours__c.field-meta.xml"
+ cls = "force-app/main/default/classes/JobService.cls"
+ trigger = "force-app/main/default/triggers/JobTrigger.trigger"
+ g = _build(
+ tmp_path,
+ {
+ job: _object("Job"),
+ due: _field("Date"),
+ shift_lookup: _field("Lookup", "Shift__c"),
+ shift: _object("Shift"),
+ hours: _field("Number"),
+ cls: _APEX,
+ trigger: "trigger JobTrigger on JOB__C (before insert) { }\n",
+ },
+ )
+
+ def refs(source: str) -> set[str]:
+ return {
+ t for _, t, d in g.out_edges(source, data=True) if d["edge_type"] == "references"
+ }
+
+ # FROM object, selected and filtered fields, and a lookup hop; the child
+ # relationship subquery (Shifts__r) names no object.
+ assert refs(f"{cls}::JobService::open") == {
+ f"{job}::Job__c",
+ f"{due}::Due__c",
+ f"{shift_lookup}::Shift__c",
+ f"{hours}::Hours__c",
+ }
+ # DML on a parameter and a field, and a literal Database.query; the
+ # concatenated query and the standard Account (no metadata) bind nothing.
+ assert refs(f"{cls}::JobService::save") == {f"{job}::Job__c", f"{shift}::Shift__c"}
+ assert refs(f"{trigger}::JobTrigger") == {f"{job}::Job__c"}
+ assert g.get_edge_data(cls, job)["edge_type"] == "reads"
+
+
+def test_dml_target_type_respects_block_scope() -> None:
+ from tree_sitter import Parser
+ from tree_sitter_language_pack import get_language
+
+ from repowise.core.ingestion.salesforce_soql import apex_schema_refs
+
+ source = b"""class T {
+ void m(Boolean flag) {
+ if (flag) { Contact c = new Contact(); insert c; }
+ else { Lead c = new Lead(); insert c; }
+ update c;
+ insert new Case[]{ new Case() };
+ }
+}
+"""
+ root = Parser(get_language("apex")).parse(source).root_node
+ refs = apex_schema_refs(root, [], "T.cls")
+ # Each branch's insert sees its own declaration; the update after both
+ # blocks sees neither, so it names nothing rather than guessing. An array
+ # literal's element type is the target.
+ assert sorted((r.line, r.object_name) for r in refs) == [(3, "Contact"), (4, "Lead"), (6, "Case")]