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
"""Node ORM tables: Prisma, TypeORM, Sequelize, Drizzle and Knex.
Each library names a table explicitly or derives it from a model by its own
rule; the rows here pin both, and the refusals where a name cannot be read.
Rows are compared as sorted lists, so a table read twice shows up.
"""
from __future__ import annotations
from pathlib import Path
from repowise.core.ingestion.traverser import FileTraverser
from repowise.core.workspace.extractors.base import iter_source_files
from repowise.core.workspace.extractors.data import DataExtractor
from repowise.core.workspace.matching import match_contracts
def _write(repo: Path, files: dict[str, str]) -> Path:
for rel, text in files.items():
path = repo / rel
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
return repo
def _rows(repo: Path, framework: str) -> list[tuple[str, str, str]]:
"""``(role, table, schema-or-verb)`` for *framework*'s rows, sorted."""
return sorted(
(c.role, c.meta["table"], c.meta.get("schema") or c.meta.get("verb") or "")
for c in DataExtractor().extract(repo, "app")
if c.meta.get("framework", c.meta.get("client")) == framework
)
def _tables(repo: Path, framework: str) -> list[str]:
return [table for _role, table, _ in _rows(repo, framework)]
def _links(*repos: tuple[Path, str]) -> set[tuple[str, str, str]]:
contracts = [c for path, alias in repos for c in DataExtractor().extract(path, alias)]
return {(lk.provider_repo, lk.consumer_repo, lk.contract_id) for lk in match_contracts(contracts)}
class TestPrisma:
_SCHEMA = """// Don't edit: generated by hand
datasource db {
provider = "postgresql"
schemas = ["public", "billing"]
}
model User {
id Int @id @default(autoincrement())
teamId Int @map("team_id")
site String @default("https://x.io//a")
posts Post[]
// @@map("legacy_users")
}
model Post {
id Int @id
@@map("blog_posts")
}
model Invoice {
id Int @id
@@map(name: "invoices")
@@schema("billing")
}
view Summary {
id Int @unique
}
type Address {
street String
}
enum Role {
ADMIN
}
"""
def test_models_maps_and_schemas(self, tmp_path: Path) -> None:
repo = _write(tmp_path, {"prisma/schema.prisma": self._SCHEMA})
assert _rows(repo, "prisma") == [
("provider", "billing.invoices", ""),
("provider", "blog_posts", ""),
("provider", "user", ""),
]
def test_the_contract_walk_reads_a_file_the_index_skips(self, tmp_path: Path) -> None:
repo = _write(
tmp_path,
{
"prisma/schema.prisma": self._SCHEMA,
"notes.txt": "x",
".gitignore": "generated/\n",
"generated/client/schema.prisma": self._SCHEMA,
},
)
assert [info.path for info in FileTraverser(repo).traverse()] == []
walked = [rel for rel, _, _ in iter_source_files(repo, frozenset({".prisma"}))]
assert walked == ["prisma/schema.prisma"]
class TestTypeOrm:
def test_names_options_and_the_snake_case_default(self, tmp_path: Path) -> None:
text = (
"import { Entity, ViewEntity, ChildEntity } from 'typeorm';\n"
"const TABLE = 'accounts';\n"
"@Entity()\nexport class PhotoMetadata {}\n"
"@Entity()\nexport class APIKey {}\n"
"@Entity('users')\nexport class User {}\n"
"@Entity({ name: 'orders', schema: 'sales' })\nexport class Order {}\n"
"@Entity(TABLE, { schema: 'auth' })\nexport class Account {}\n"
"@Entity({ schema: 'audit' })\nexport class AuditLog {}\n"
"@ViewEntity({ name: 'totals' })\nexport class Totals {}\n"
"@ChildEntity()\nexport class Admin extends User {}\n"
"@Entity(config.name)\nexport class Unknown {}\n"
"@Entity('ledger', { schema: SCHEMA })\nexport class Ledger {}\n"
"// @Entity('old_things')\n@Entity('things')\nexport class Thing {}\n"
)
repo = _write(tmp_path, {"src/entities.ts": text})
assert _tables(repo, "typeorm") == [
"api_key",
"audit.audit_log",
"auth.accounts",
"photo_metadata",
"sales.orders",
"things",
"users",
]
def test_another_librarys_entity_decorator_is_not_read(self, tmp_path: Path) -> None:
repo = _write(
tmp_path,
{
"b.ts": "import { Entity } from '@mikro-orm/core';\n@Entity()\nexport class Book {}\n",
"c.ts": "import { Entity } from 'typeorm';\n@Entity()\nexport class Cover {}\n",
},
)
assert _tables(repo, "typeorm") == ["cover"]
class TestSequelize:
def test_define_and_init(self, tmp_path: Path) -> None:
text = (
"const { Sequelize, Model, DataTypes } = require('sequelize');\n"
"const sequelize = new Sequelize('sqlite::memory:');\n"
"const db = new Sequelize(url);\n"
"sequelize.define('Category', {});\n"
"sequelize.define('Tag', {}, { tableName: 'labels' });\n"
"db.define('Person', {}, { freezeTableName: true });\n"
"sequelize.define('OrderLine', {}, { underscored: true });\n"
"sequelize.define('UserProfile', {}, { freezeTableName: true, underscored: true });\n"
"sequelize.define('users', {});\n"
"sequelize.define('Secret', {}, { tableName: config.table });\n"
"customElements.define('app-root', AppRoot);\n"
"class Project extends Model {}\n"
"Project.init({}, { sequelize, modelName: 'workItem' });\n"
"class Task extends Model {}\n"
"Task.init({}, { sequelize: db });\n"
"class Member extends Model {\n"
" static init(s) { return super.init({}, { sequelize: s }); }\n}\n"
"Chart.init(el, { theme: 'dark' });\n"
)
assert _tables(_write(tmp_path, {"models.js": text}), "sequelize") == [
"categories",
"labels",
"members",
"order_lines",
"person",
"tasks",
"userprofile",
"users",
"workitems",
]
def test_sequelize_typescript_tables(self, tmp_path: Path) -> None:
text = (
"import { Column, Model, Table } from 'sequelize-typescript';\n"
"@Table\nexport class User extends Model {}\n"
"@Table({ tableName: 'pets', timestamps: false })\nexport class Dog extends Model {}\n"
"// @Table({ tableName: 'gone' })\n"
)
assert _tables(_write(tmp_path, {"m.ts": text}), "sequelize") == ["pets", "users"]
class TestDrizzle:
def test_tables_and_schema_tables(self, tmp_path: Path) -> None:
text = (
"import { pgTable, pgSchema, pgTableCreator, serial } from 'drizzle-orm/pg-core';\n"
"const USERS = 'users';\n"
"export const users = pgTable(USERS, { id: serial('id') });\n"
"export const auth = pgSchema('auth');\n"
"export const sessions = auth.table('sessions', {});\n"
"export const t = mysqlTable('things', {});\n"
"export const k = sqliteTable(`kv`, {});\n"
"export const s = singlestoreTable('events', {});\n"
"export const x = pgTable(name, {});\n"
"const createTable = pgTableCreator((n) => `app_${n}`);\n"
"export const p = createTable('posts', {});\n"
"export const q = mySchema.table('nope', {});\n"
)
assert _tables(_write(tmp_path, {"schema.ts": text}), "drizzle") == [
"auth.sessions",
"events",
"kv",
"things",
"users",
]
def test_without_the_import_nothing_is_read(self, tmp_path: Path) -> None:
repo = _write(
tmp_path,
{
"a.ts": "pgTable('users', {});\n",
"b.ts": "import { pgTable } from 'drizzle-orm/pg-core';\npgTable('teams', {});\n",
},
)
assert _tables(repo, "drizzle") == ["teams"]
class TestKnex:
def test_migrations_create_and_alter(self, tmp_path: Path) -> None:
text = (
"exports.up = async function (knex) {\n"
" await knex.schema.createTable('todos', (t) => { t.increments(); });\n"
" await knex.schema.createTableIfNotExists('tags', (t) => {});\n"
" await knex.schema.withSchema('audit').createTable('events', (t) => {});\n"
" await knex.schema.withSchema(SCHEMA).createTable('hidden', (t) => {});\n"
" await knex.schema.alterTable('users', (t) => {});\n"
" await knex.schema.table('orders', (t) => {});\n"
"};\n"
)
assert _rows(_write(tmp_path, {"migrations/1_init.js": text}), "knex") == [
("provider", "audit.events", "create"),
("provider", "orders", "alter"),
("provider", "tags", "create"),
("provider", "todos", "create"),
("provider", "users", "alter"),
]
def test_queries_and_their_verbs(self, tmp_path: Path) -> None:
text = (
"import knex from 'knex';\n"
"const db = knex({ client: 'pg' });\n"
"const pg = require('knex')(config);\n"
"await db('todos').where({ id }).first();\n"
"await db('todos').where({ done: true });\n"
"await db('todos').insert(row);\n"
"await knex('users as u').where('u.id', id).update({ name });\n"
"await this.knex('sessions').where({ id }).del();\n"
"await knex.select('id').from('orders');\n"
"await knex.from('audit.events');\n"
"await pg.into('logs').insert(entry);\n"
"await db.count('*').from('carts');\n"
"await other('nope');\n"
"await supabase.from('profiles');\n"
"await mydb('nope');\n"
)
assert _rows(_write(tmp_path, {"repo.ts": text}), "knex") == [
("consumer", "audit.events", "select"),
("consumer", "carts", "select"),
("consumer", "logs", "insert"),
("consumer", "orders", "select"),
("consumer", "sessions", "delete"),
("consumer", "todos", "insert"),
("consumer", "todos", "select"),
("consumer", "users", "update"),
]
def test_a_knex_query_links_to_a_prisma_model(tmp_path: Path) -> None:
owner = _write(tmp_path / "api", {"prisma/schema.prisma": 'model Order {\n id Int @id\n @@map("orders")\n}\n'})
reader = _write(tmp_path / "reports", {"q.ts": "import knex from 'knex';\nknex('orders').count();\n"})
assert _links((owner, "api"), (reader, "reports")) == {("api", "reports", "data::orders")}
def test_a_knex_migration_owns_the_table_other_services_model(tmp_path: Path) -> None:
owner = _write(
tmp_path / "api",
{"migrations/1.js": "exports.up = (knex) => knex.schema.createTable('invoices', (t) => {});\n"},
)
model = _write(
tmp_path / "billing",
{"e.ts": "import { Entity } from 'typeorm';\n@Entity('invoices')\nexport class Invoice {}\n"},
)
alter_only = _write(
tmp_path / "ops",
{"migrations/2.js": "exports.up = (knex) => knex.schema.alterTable('invoices', (t) => {});\n"},
)
links = _links((owner, "api"), (model, "billing"), (alter_only, "ops"))
# Two services define the table's schema (a create and an alter), so no one owner.
assert links == set()
assert _links((owner, "api"), (model, "billing")) == {("api", "billing", "data::invoices")}