Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(workspace): link a SQLite reader's tables only within its own repo (#4584)
Raghav Chamadiyae19c709b314b
diff --git a/docs/reference/WORKSPACE_CONTRACTS.md b/docs/reference/WORKSPACE_CONTRACTS.mdindex 3c74983b8..d030344c9 100644--- a/docs/reference/WORKSPACE_CONTRACTS.md+++ b/docs/reference/WORKSPACE_CONTRACTS.md@@ -89,7 +89,7 @@ binding site itself is linked. A publish to the default exchange## Data contracts-Data/DB contracts use the id scheme `data::<table>` and render as a `db` edge in the [system graph](../scale/WORKSPACES.md#system-graph). An ORM model with no explicit table name takes its library's default: the Prisma model name, the TypeORM class name in snake case, the Sequelize model name pluralized, the Eloquent class name in snake case and plural. A service that only models a table (an ORM class, no migration) is linked to the service whose migration or DDL defines that table's schema, when exactly one service defines it; two services that each migrate a table of one name are read as separate databases and not linked. The consumer side (SQL string matching) is heuristic and lower-confidence than the ORM-based providers; unlike HTTP and gRPC, there is no field-level breaking-change diffing for data contracts, only table/route-level removal.+Data/DB contracts use the id scheme `data::<table>` and render as a `db` edge in the [system graph](../scale/WORKSPACES.md#system-graph). An ORM model with no explicit table name takes its library's default: the Prisma model name, the TypeORM class name in snake case, the Sequelize model name pluralized, the Eloquent class name in snake case and plural. A service that only models a table (an ORM class, no migration) is linked to the service whose migration or DDL defines that table's schema, when exactly one service defines it; two services that each migrate a table of one name are read as separate databases and not linked. A reader in a file that opens an embedded database (SQLite) links only to tables declared in its own repo, since that file is its own database. The consumer side (SQL string matching) is heuristic and lower-confidence than the ORM-based providers; unlike HTTP and gRPC, there is no field-level breaking-change diffing for data contracts, only table/route-level removal.## HTTP routes and callsdiff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.pyindex d7dec572d..f6bcb39e0 100644--- a/packages/core/src/repowise/core/workspace/contracts.py+++ b/packages/core/src/repowise/core/workspace/contracts.py@@ -75,6 +75,8 @@ CONTRACTS_FILENAME = "contracts.json"# (see :mod:`.network_probe`). Gateway routes (Spring Cloud Gateway, Zuul)# rewrite the calls they forward and add gateway-to-service service links.# Go routes from chi, fiber, gorilla/mux and Go 1.22 method patterns are read.+# A data consumer in a file that opens SQLite carries ``meta['embedded']`` and+# links only within its repo.CONTRACTS_VERSION = 15#: ``meta["kind"]`` of a topic contract: the destination a broker call names.diff --git a/packages/core/src/repowise/core/workspace/extractors/data/dialect.py b/packages/core/src/repowise/core/workspace/extractors/data/dialect.pyindex 64fd8c450..56dc92e1e 100644--- a/packages/core/src/repowise/core/workspace/extractors/data/dialect.py+++ b/packages/core/src/repowise/core/workspace/extractors/data/dialect.py@@ -57,6 +57,39 @@ def build_table_provider()+#: Driver and connection-string tokens that place a file's tables in an+#: embedded database, one row per engine. An embedded database is a file the+#: program opens itself, so its tables are never another repo's server tables.+#: Deliberate ceiling: server engines (Postgres vs MySQL) are not told apart;+#: upgrade path is a row per server engine and comparing both ends' engines.+_EMBEDDED_ENGINES: tuple[tuple[str, tuple[str, ...]], ...] = (+ (+ "sqlite",+ (+ "sqlite3",+ "SQLite3",+ "aiosqlite",+ "bun:sqlite",+ "modernc.org/sqlite",+ "jdbc:sqlite",+ "sqlite://",+ "PDO('sqlite:",+ 'PDO("sqlite:',+ "Microsoft.Data.Sqlite",+ "UseSqlite",+ ),+ ),+)+++def embedded_engine(ctx: ScanContext) -> str | None:+ """The embedded engine *ctx*'s file opens (``sqlite``), or ``None``."""+ for engine, tokens in _EMBEDDED_ENGINES:+ if ctx.has_any(tokens):+ return engine+ return None++def build_table_consumer(ctx: ScanContext,*,@@ -70,11 +103,13 @@ def build_table_consumer(``verb`` is the SQL operation that touched the table (``select`` /``insert`` / ``update`` / ``delete`` / ``join``), carried in ``meta`` so- downstream views can distinguish readers from writers.+ downstream views can distinguish readers from writers. ``embedded``+ names the embedded engine the file opens, when it opens one."""table = normalize_table_name(table_raw)if table is None:return None+ engine = embedded_engine(ctx)return build_contract(ctx,contract_id=f"data::{table}",@@ -83,7 +118,12 @@ def build_table_consumer(symbol_name=f"{client}:{verb} {table}",origin=origin,line=line,- meta={"table": table, "verb": verb, "client": client},+ meta={+ "table": table,+ "verb": verb,+ "client": client,+ **({"embedded": engine} if engine else {}),+ },)diff --git a/packages/core/src/repowise/core/workspace/matching/__init__.py b/packages/core/src/repowise/core/workspace/matching/__init__.pyindex 1e0fd671c..e4fc3cf1c 100644--- a/packages/core/src/repowise/core/workspace/matching/__init__.py+++ b/packages/core/src/repowise/core/workspace/matching/__init__.py@@ -59,7 +59,7 @@ MATCHERS: dict[str, TypeMatcher] = {passes=(topic.binding_pass,),keys=topic.matching_keys,),- "data": TypeMatcher(passes=(data.shared_table_pass,)),+ "data": TypeMatcher(accepts=data.accepts, passes=(data.shared_table_pass,)),}_NO_RULES = TypeMatcher()diff --git a/packages/core/src/repowise/core/workspace/matching/data.py b/packages/core/src/repowise/core/workspace/matching/data.pyindex 438506377..2b0a86519 100644--- a/packages/core/src/repowise/core/workspace/matching/data.py+++ b/packages/core/src/repowise/core/workspace/matching/data.py@@ -30,6 +30,16 @@ def _rank(c: Contract) -> tuple[int, str, int]:return (_SCHEMA_RANK.get(c.meta.get("schema", ""), _MODEL_RANK), c.file_path, c.line or 0)+def accepts(provider: Contract, consumer: Contract) -> bool:+ """Whether *consumer* can read *provider*'s table.++ A consumer in a file that opens an embedded database (SQLite) reads that+ file's tables, which no other repo's schema declares: two repos sharing a+ table name there have two databases. Within one repo the name still links.+ """+ return not consumer.meta.get("embedded") or provider.repo == consumer.repo++def shared_table_pass(state: MatchState) -> None:"""Link each service that only models a table to the one defining its schema.diff --git a/tests/unit/workspace/test_data_contracts.py b/tests/unit/workspace/test_data_contracts.pyindex 87d115a0e..71425a9d5 100644--- a/tests/unit/workspace/test_data_contracts.py+++ b/tests/unit/workspace/test_data_contracts.py@@ -333,6 +333,55 @@ class TestDataMatching:contracts += DataExtractor().extract(worker, "worker")assert len(match_contracts(contracts)) == 1+ def test_embedded_database_reader_not_linked_across_repos(self, tmp_path: Path) -> None:+ # A table name shared with another repo's server schema is a second+ # database when the reader opens a SQLite file of its own.+ backend = tmp_path / "backend"+ tool = tmp_path / "tool"+ _write(backend, "migrations/001.sql", "CREATE TABLE repos (id INT);")+ _write(+ tool,+ "store.py",+ 'import sqlite3\nq = "SELECT id FROM repos WHERE x = 1"\n',+ )+ _write(+ tool,+ "web/db.ts",+ "import Database from 'better-sqlite3';\n"+ "const q = 'SELECT id FROM repos WHERE x = 1';\n",+ )+ consumers = DataExtractor().extract(tool, "tool")+ assert [c.meta.get("embedded") for c in consumers] == ["sqlite", "sqlite"]+ contracts = DataExtractor().extract(backend, "backend") + consumers+ assert match_contracts(contracts) == []++ def test_embedded_database_reader_linked_within_its_repo(self, tmp_path: Path) -> None:+ from repowise.core.workspace.matching.data import accepts++ repo = tmp_path / "app"+ _write(repo, "schema.sql", "CREATE TABLE repos (id INT);")+ _write(repo, "store.py", 'import sqlite3\nq = "SELECT id FROM repos WHERE x = 1"\n')+ contracts = DataExtractor().extract(repo, "app")+ (consumer,) = [c for c in contracts if c.role == "consumer"]+ (provider,) = [c for c in contracts if c.role == "provider"]+ assert consumer.meta.get("embedded") == "sqlite"+ assert accepts(provider, consumer)++ def test_server_database_reader_still_linked_across_repos(self, tmp_path: Path) -> None:+ backend = tmp_path / "backend"+ worker = tmp_path / "worker"+ _write(backend, "migrations/001.sql", "CREATE TABLE repos (id INT);")+ _write(+ worker,+ "job.py",+ "import psycopg\n"+ 'URL = "postgresql://db/app"\n'+ 'q = "SELECT id FROM repos WHERE x = 1"\n',+ )+ contracts = DataExtractor().extract(backend, "backend")+ contracts += DataExtractor().extract(worker, "worker")+ assert len(match_contracts(contracts)) == 1+_ELOQUENT_HEAD = "<?php\nnamespace App\\Models;\nuse Illuminate\\Database\\Eloquent\\Model;\n"