factcircuit
FactCircuit는 불변 출처와 단계별 검증, 제한된 검색, 재현 가능한 평가를 제공하는 감사 가능한 주장·증거 검증 루프입니다
SQLModel·SQLAlchemy용 시각 스키마 디자인, 데이터베이스를 다이어그램으로 편집하고 코드로 내보냅니다
Visual schema design for SQLModel and SQLAlchemy. Edit your database as a diagram, write it back as code.
데이터Python · JavaScriptGitHub @chimi-labs직접 설치운영자 미확인
써 보셨어요? 한 번만 눌러 주세요. 로그인은 필요 없어요.
아직 감지된 업데이트가 없습니다. GitHub 릴리스가 나오면 여기에 보입니다.
개인 계정의 공개 저장소 소유자는 GitHub로 로그인해 운영자를 확인하고 소개를 직접 관리할 수 있습니다. 관리자 승인은 필요하지 않습니다.
로그인한 뒤 확인 파일을 만들어 이 저장소의 기본 브랜치에 30분 안에 커밋해 주세요. 다른 브랜치나 포크의 파일은 인정하지 않습니다. 파일을 올린 뒤 아래에서 확인하면 관리자 승인 없이 관리할 수 있습니다. 자격을 유지하려면 파일을 남겨 두세요.
로그인이 필요하면 로그인 화면으로 이동합니다. 로그인 후 이곳으로 돌아와 원하는 확인 버튼을 다시 눌러 주세요.
설치형 프로젝트는 배포 도메인 없이도 확인할 수 있습니다. 개인 저장소는 GitHub 로그인으로, 조직 저장소는 위의 저장소 확인 파일로 직접 확인해 주세요.
README 전체를 불러오는 중입니다. 아래는 저장된 발췌입니다.
Lightweight, always up-to-date DB context for your AI. Query your database in human language.
Alter creates a schema.alter file, a lightweight JSON that captures your entire database structure: tables, columns, types, relations, indexes, and layout. It lives in your repo, gets versioned with your code, and stays in sync with your ORM models in both directions.
Everything runs on your machine. No cloud, no account, no data leaves your laptop.
Your AI gets full database context without wasting tokens
This is the core value.README 전문 보기 ↗Alter creates a schema.alter file, a lightweight JSON that captures your entire database structure: tables, columns, types, relations, indexes, and layout. It lives in your repo, gets versioned with your code, and stays in sync with your ORM models in both directions.
{
"version": 1,
"orm": "sqlmodel",
"tables": [
{
"name": "users",
"file_path": "app/models.py",
"columns": [
{ "name": "id", "type": "uuid", "primary_key": true, "default": "uuid4" },
{ "name": "email", "type": "string", "nullable": false, "unique": true }
]
}
]
}
Everything runs on your machine. No cloud, no account, no data leaves your laptop.
This is the core value.
When an AI assistant needs to work with your database, it typically has to inspect your DB connection, read migration files, or parse dozens of model files just to understand your schema. That costs tokens, takes time, and the result is often incomplete.
With schema.alter in your repo, the AI gets the full picture instantly: every table, every column, every relation, every foreign key, in a single, compact, structured JSON. No inspection needed. No guessing.
This means your AI can:
All through Alter's MCP server, which works with Claude Code, Cursor, and Windsurf.
This is what surprises people the most.
Connect the MCP server and you can ask questions about your actual data in natural language:
"Which customers placed orders last month but never came back?"
The AI already knows your schema. It sees the customers, orders, and order_items tables, understands the foreign keys, writes the correct JOINs, runs the query read-only, and gives you the answer. No SQL required. No context-switching to a SQL client. No remembering column names.
"How many users signed up in the last 30 days?"
"Which plan do most of our paying customers use?"
"Why is this query slow?"
It works because Alter exposes three database tools: query_db for running SELECT queries, describe_table_data for exploring table structure and sample rows, and explain_query for analyzing execution plans. All enforced as read-only at the database level.
The MCP server isn't just for querying, it's a full schema design interface:
"Add a payments table with id, amount, currency, and a foreign key to users."
The AI stages the change, shows you a diff, and waits for your approval. Nothing touches schema.alter until you commit. Nothing touches your code until you apply. You get undo, redo, migration SQL preview, and validation, all through conversation.
schema.alter also powers an interactive browser-based ERD canvas. But unlike standalone diagram tools, this diagram is always in sync with your code because it reads from the same JSON file that your AI uses and that your ORM models generate.
┌─────────────┐ ┌───────────────┐
│ Your Code │ ── alter sync ─────► │ Canvas │
│ (models.py) │ │ (visual ERD) │
│ │ ◄── alter apply ──── │ │
└─────────────┘ └───────────────┘
schema.alter
(keeps both in sync)
alter apply is surgical. It doesn't rewrite your file; it patches exactly what changed. Your docstrings, your Relationship() definitions, your trailing comments, your hand-written Field() kwarg order, your default={} on that one column: all preserved. New tables are appended as new classes. Modified columns are rebuilt in-place. Deleted tables are removed cleanly.
This is the difference between a code generator you try once and one you actually keep using.
schema.alter is a JSON file, and JSON files are merge conflict magnets. Alter ships a custom Git merge driver that resolves conflicts structurally (by table name, not by line number). Two developers add different tables on different branches? Auto-merged. No manual conflict resolution, no broken JSON.
pip install alterdb
Or with uv:
uv add alterdb
Requirements: Python 3.11+
Dependency conflicts? Install as an isolated CLI tool instead:
uv tool install alterdbThis keeps Alter's dependencies completely separate from your project while making the
altercommand available on yourPATH.
Live database features (
query_db,describe_table_data,explain_query): requirepsycopg2-binary. Install withpip install alterdb[db].
alter init # scan your ORM models → create schema.alter
alter canvas # open the visual ERD in your browser
Your browser opens with an interactive diagram of every table, column, and relation in your project.
pg_dump --schema-only --no-owner mydb > schema.sql
alter import schema.sql # parse DDL → merge tables into schema.alter
alter canvas # open the visual editor
Or start the canvas first and use Paste SQL in the toolbar to paste DDL directly.
alter init # creates an empty schema.alter
alter canvas # open the canvas, click "Templates" to pick a starter
Choose from saas-base, auth, cms, or ecommerce. Tables are proposed on the canvas so you can review and customize before committing anything.
Alter exposes your schema to any MCP-compatible AI assistant so it can read, modify, and query your database through natural language.
1. Initialize the schema (if you haven't already):
alter init
2. Ensure mcp>=1.2.0 is installed:
pip install 'mcp>=1.2.0'
3. Register the server in your editor:
{
"mcpServers": {
"alter": {
"command": "uv",
"args": ["run", "--directory", "/path/to/project", "alter", "mcp"]
}
}
}
| Editor | Config file |
|---|---|
| Claude Desktop | claude_desktop_config.json |
| Cursor | .cursor/mcp.json |
| Windsurf | .windsurf/mcp.json |
For Claude Code, register via the CLI:
claude mcp add alter -- uv run --directory /path/to/project alter mcp
4. Restart your editor and verify:
"What tools do you have available from alter?"
Explore and understand:
Design and modify:
Review and validate:
Import and bootstrap:
The assistant stages changes, shows you a diff, and only commits to schema.alter with your approval. Nothing touches your model files until you run alter apply.
Connect a PostgreSQL database and your AI assistant can answer questions about real data, not just schema structure.
1. Install the database extra:
pip install alterdb[db]
2. Set the DATABASE_URL environment variable:
export DATABASE_URL="postgresql://user:password@localhost:5432/mydb"
Or add it to your MCP config:
{
"mcpServers": {
"alter": {
"command": "uv",
"args": ["run", "--directory", "/path/to/project", "alter", "mcp"],
"env": {
"DATABASE_URL": "postgresql://user:password@localhost:5432/mydb"
}
}
}
}
The three data tools:
| Tool | What it does |
|---|---|
query_db | Execute a SELECT query (results as table, JSON, or CSV) |
describe_table_data | Row count, column types, relationships, sample rows |
explain_query | PostgreSQL execution plan (without running the query) |
All queries run in a read-only transaction. INSERT, UPDATE, DELETE, and DDL are blocked at the database level. Results are capped at 1,000 rows.
Example prompts:
"How many users signed up in the last 30 days?"
The assistant sees your schema, writes the query, runs it read-only, and tells you: "847 users signed up in the last 30 days."
"Which plan do most of our paying customers use?"
| plan | count |
| pro | 1,204 |
| starter | 891 |
| team | 342 |
"Tell me about the orders table before I write a query against it"
The assistant calls describe_table_data and returns row count, column types, foreign key relationships, and sample data: everything you need to understand the table before touching it.
"Why is my query slow?"
The assistant runs explain_query and walks you through the execution plan, pointing out sequential scans and suggesting indexes.
Already have a running PostgreSQL instance? Import its schema directly.
The introspect_db MCP tool reads tables, columns, constraints, indexes, and foreign key relationships from a live database and merges them into your schema. No pg_dump required.
The canvas is a browser-based interactive ERD that runs locally on your machine. It gives you a visual overview of your entire schema and lets you design tables, columns, and relations by pointing and clicking.
What you can do on the canvas:
ON DELETE rules (CASCADE, SET NULL, RESTRICT, NO ACTION, SET DEFAULT).CREATE TABLE statement and Alter parses it into a table on the canvas..alter file and updates in real time when it changes.alter canvas # open on default port
alter canvas --port 9000 # custom port
alter canvas --demo # open with a sample schema
Two commands keep schema.alter synchronized with your code.
Design on the canvas, then apply to your model files:
alter apply --preview # see exactly what will change (unified diff)
alter apply # write the changes to your model files
Or click Apply to Code directly in the canvas. It auto-commits pending changes before writing, so you never accidentally apply a stale snapshot.
What alter apply does (and doesn't do):
Field() kwargs are rebuilt in-place, preserving your original kwarg order, multi-line formatting, and inline comments.Field() line removed.Relationship() definitions, custom methods, trailing comments, and mutable defaults (default={}, default=[]) are left exactly as you wrote them.Edit your models by hand, then sync:
alter sync # re-parse your models, update schema.alter
Or click Sync from Code in the canvas toolbar. The canvas picks up the change via live reload, no restart needed.
alter diff # see what changed (text summary)
alter diff --format markdown # PR-ready changelog
From a fresh project to running migrations:
# 1. Initialise
alter init # scan models → schema.alter
# 2. Create the initial migration (with your migration tool)
alembic init alembic
alembic revision --autogenerate -m "initial schema"
alembic upgrade head
# 3. Open the canvas and design
alter canvas
# add a "payments" table, click Commit
# the Migrations tab shows the SQL that needs to run
# 4. Apply canvas changes to code
alter apply --preview # review the unified diff
alter apply # write class Payments to models.py
# 5. Run the migration
alembic revision -m "add payments table"
# paste the SQL from the canvas Migrations tab into upgrade()
alembic upgrade head
Alter generates the SQL. You run it with whatever migration tool you already use (Alembic, Django, Flyway, raw SQL, anything).
The Migrations tab in the canvas shows the pending DDL at any time. The preview_migration MCP tool returns the same SQL to AI assistants. Copy it into your migration manager of choice.
Column rename detection: Alter's diff engine is name-based and cannot distinguish a column rename from a drop + add. When it detects a
DROP COLUMNpaired with anADD COLUMNof the same type on the same table, the generated SQL includes a comment pointing out the potential rename and showing the equivalentALTER TABLE … RENAME COLUMNstatement.
alembic init alembic
Edit alembic/env.py so Alembic knows about your models:
from sqlmodel import SQLModel
import app.models # ensure all models are imported
target_metadata = SQLModel.metadata
Then create migrations as needed:
alembic revision --autogenerate -m "initial schema"
alembic upgrade head
After that, use the canvas Migrations tab or the preview_migration MCP tool to get the SQL for any change, and apply it with alembic revision + alembic upgrade head.
schema.alter: The Schema Fileschema.alter is a JSON file that captures your table definitions, column types, relations, enum types, and canvas layout positions. It's the single source of truth that your code, your canvas, and your AI all read from: human-readable, git-diffable, and versioned alongside your code.
| Type | Python | SQL |
|---|---|---|
uuid | uuid.UUID | UUID |
string | str | VARCHAR(N) / TEXT |
text | str | TEXT |
int | int | INTEGER |
bigint | int | BIGINT |
float | float | DOUBLE PRECISION |
decimal | Decimal | NUMERIC |
bool | bool | BOOLEAN |
datetime | datetime | TIMESTAMPTZ |
date | date | DATE |
time | time | TIME |
json | dict | JSONB |
json_array | list | JSONB |
bytes | bytes | BYTEA |
Plus any enum types defined in your code.
Alter understands real-world project structures out of the box:
Role is defined in app/enums.py, Alter tracks its file_path and applies changes to the right file. No duplicate enum classes.UUIDBase, TimestampedBase) are tracked as inherited and never re-injected when applying to code.alter apply writes each table to its correct file independently.alter add app/legacy/models.py # parse and merge new tables into schema.alter
alter add lib/plugins/billing.py # already-tracked tables are skipped
Safe to run multiple times.
Tables in a non-default PostgreSQL schema (with __table_args__ = {"schema": "..."}) are fully supported end-to-end:
{"schema": "billing"} dict form and tuple form ({"schema": "billing"}, UniqueConstraint(...)) are recognized.CREATE TABLE and REFERENCES use qualified schema.table names.schema_table (underscore-joined) for valid Mermaid identifiers.table.column or schema.table.column.Run alter validate to check for structural problems before applying or exporting:
alter validate
Errors (must fix):
Warnings (advisory):
select, from, table, …)Exits with code 1 if errors are found, safe to use in CI.
alter import schema.sql # SQL DDL (pg_dump, hand-written, etc.)
alter import other.alter # another schema.alter file
alter import templates/saas.alter # a built-in template
Tables already in the schema are skipped, safe to run multiple times. Format is auto-detected from the file extension.
alter export # SQL DDL to stdout
alter export --format mermaid # Mermaid ERD to stdout
alter export --format alter # raw JSON to stdout
alter export --output schema.sql # write to a file
alter export --proposed # export staged changes
The Mermaid output can be pasted directly into GitHub Markdown, Notion, or any tool that renders ```mermaid fences:
```mermaid
erDiagram
users {
uuid id PK
string email
}
posts {
uuid id PK
uuid author_id FK
}
users ||--o{ posts : "author_id"
```
Four starter templates, accessible from the canvas toolbar or the CLI:
| Template | Tables |
|---|---|
saas-base | users, organizations, memberships, sessions |
auth | users, sessions, tokens, oauth_accounts |
cms | posts, categories, tags, media |
ecommerce | products, orders, order_items, customers |
alter import templates/ecommerce.alter
A custom merge driver that resolves schema.alter conflicts structurally (by table name, not by line number). Two developers add different tables on different branches? Clean merge. No manual conflict resolution.
One-time setup (per machine):
git config --global merge.alter.name "Alter schema merge driver"
git config --global merge.alter.driver "alter merge-driver %O %A %B"
Add to your repo's .gitattributes:
*.alter merge=alter
After that, Git uses the driver automatically whenever a .alter file is involved in a merge or rebase.
How it resolves conflicts:
| Command | What it does |
|---|---|
alter init | Create schema.alter from existing ORM model files (--force to overwrite) |
alter canvas | Open the interactive ERD in your browser |
alter apply | Write schema changes to your ORM model files (--preview for dry run) |
alter sync | Update schema.alter from your ORM model files |
alter add | Add tables from a model file to the schema |
alter diff | Show pending changes (--format markdown for PR-ready output) |
alter validate | Check your schema for errors and warnings |
alter export | Export as SQL DDL, Mermaid ERD, or .alter JSON |
alter import | Import tables from a .sql or .alter file |
alter merge-driver | Git merge driver for .alter files |
alter mcp | Start the MCP server |
from sqlmodel import ...from sqlalchemy import ...MIT