schema-alignment
Detect and report drift between database schema and code data models. Works with SQLAlchemy, Django ORM, Prisma, TypeORM, and other ORMs. Generic across any project.
下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o schema-alignment.zip https://jpskill.com/download/18044.zip && unzip -o schema-alignment.zip && rm schema-alignment.zip
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/18044.zip -OutFile "$d\schema-alignment.zip"; Expand-Archive "$d\schema-alignment.zip" -DestinationPath $d -Force; ri "$d\schema-alignment.zip"
完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。
💾 手動でダウンロードしたい(コマンドが難しい人向け)
- 1. 下の青いボタンを押して
schema-alignment.zipをダウンロード - 2. ZIPファイルをダブルクリックで解凍 →
schema-alignmentフォルダができる - 3. そのフォルダを
C:\Users\あなたの名前\.claude\skills\(Win)または~/.claude/skills/(Mac)へ移動 - 4. Claude Code を再起動
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-18
- 取得日時
- 2026-05-18
- 同梱ファイル
- 1
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
スキーマ整合性スキル
データベーススキーマとコードデータモデル間のずれを検出します。このスキルは、欠落しているカラム、型の不一致、孤立したマイグレーション、および命名の不整合を特定します。
設計原則
このスキルはフレームワークに依存しません。あらゆるORMまたはデータベースで動作します。
- SQLAlchemy (Python)
- Django ORM (Python)
- Prisma (TypeScript/JavaScript)
- TypeORM (TypeScript)
- Drizzle (TypeScript)
- Alembic migrations
- Prisma migrations
- Django migrations
変数
| 変数 | デフォルト | 説明 |
|---|---|---|
| SCHEMA_SOURCE | auto | スキーマのソース: auto, migrations, live_db, models |
| SEVERITY_THRESHOLD | medium | このレベル以上の問題を報告します |
| AUTO_FIX | false | 修正案の生成を試みます |
| INCLUDE_TYPES | true | 型の不一致の検出を含めます |
指示
必須 - 以下のワークフローの手順を順番に実行してください。
- 使用中のデータベース技術とORMを検出します
- マイグレーションまたはライブデータベースからスキーマを抽出します
- コードからデータモデルを抽出します
- 比較してずれを特定します
- 整合性レポートを生成します
危険信号 - 停止して再検討してください
もしあなたが以下をしようとしているなら:
- マイグレーションなしでデータベーススキーマを直接変更する
- スキーマを確認せずにカラムが存在すると仮定する
- 「テストでは動作する」という理由で型チェックをスキップする
- nullable/not-null の不一致を無視する
停止 -> スキーマの整合性を確認 -> 必要に応じてマイグレーションを生成 -> その後、続行
ワークフロー
1. スタックの検出
データベースとORMを特定します。
以下の指標を確認してください。
| ファイル/依存関係 | 技術 |
|-----------------|------------|
| alembic.ini, alembic/ | Alembic (SQLAlchemy) |
| prisma/schema.prisma | Prisma |
| manage.py + migrations/ | Django |
| ormconfig.json | TypeORM |
| drizzle.config.ts | Drizzle |
| supabase/migrations/ | Supabase (PostgreSQL) |
2. データベーススキーマの抽出
オプションA:マイグレーションから(推奨)
マイグレーションファイルを解析して、現在のスキーマを再構築します。
# Alembicの例
from alembic.script import ScriptDirectory
from alembic.config import Config
config = Config("alembic.ini")
scripts = ScriptDirectory.from_config(config)
# リビジョンをたどってスキーマを構築します
オプションB:ライブデータベースから
information_schema をクエリします(アクセス可能な場合)。
SELECT table_name, column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_schema = 'public';
オプションC:モデル定義から
ORMモデルファイルを直接解析します。
3. コードモデルの抽出
コードからモデル定義を解析します。
SQLAlchemy
# 以下のようなパターンを探します。
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
email = Column(String(255), nullable=False)
Prisma
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}
Pydantic/TypeScript Types
関連する型も抽出します。
- Pydantic models
- TypeScript interfaces
- BAML type definitions
4. 比較とずれの検出
比較を実行します。
| チェック | ソースA | ソースB | 問題の種類 |
|---|---|---|---|
| カラムの欠落 | DBスキーマ | ORMモデル | MISSING_IN_MODEL |
| カラムの欠落 | ORMモデル | DBスキーマ | MISSING_IN_DB |
| 型の不一致 | DB型 | コード型 | TYPE_MISMATCH |
| Nullableの不一致 | DB nullable | モデル nullable | NULLABLE_MISMATCH |
| 名前の不一致 | snake_case | camelCase | NAMING_DRIFT |
| マイグレーションの欠落 | モデルの変更 | マイグレーションファイル | MISSING_MIGRATION |
| FK制約 | DB制約 | ORMリレーションシップ | FK_MISMATCH |
5. レポートの生成
出力形式:
# スキーマ整合性レポート
**生成日時**: 2025-12-24T10:00:00Z
**データベース**: PostgreSQL (via Supabase)
**ORM**: SQLAlchemy 2.0
## サマリー
| 重大度 | カウント |
|----------|-------|
| HIGH | 2 |
| MEDIUM | 3 |
| LOW | 5 |
## 問題
### 1. MISSING_IN_MODEL (HIGH)
**テーブル**: `curation_jobs`
**カラム**: `retry_count` (INTEGER NOT NULL DEFAULT 0)
**モデル**: `src/models/curation_job.py:CurationJob`
カラムはデータベースに存在しますが、ORMモデルで定義されていません。
**修正**:
```python
retry_count: Mapped[int] = mapped_column(Integer, default=0)
2. TYPE_MISMATCH (MEDIUM)
テーブル: books
カラム: isbn (VARCHAR(13))
モデル: src/models/book.py:Book.isbn -> str
データベースは13文字に制限していますが、モデルは制限のない文字列を許可しています。
修正:
isbn: Mapped[str] = mapped_column(String(13))
3. MISSING_MIGRATION (LOW)
モデルの変更: User.preferences が追加されました (JSONB)
マイグレーション: 見つかりません
新しいカラムがモデルに追加されましたが、マイグレーションが存在しません。
修正:
alembic revision --autogenerate -m "add user preferences"
## クックブック
### SQLAlchemyの検出
- IF: SQLAlchemyモデルを解析する場合
- THEN: `./cookbook/sqlalchemy-detection.md` を読んで実行します
### Prismaの検出
- IF: Prismaスキーマを解析する場合
- THEN: `./cookbook/prisma-detection.md` を読んで実行します
### Alembicマイグレーション
- IF: マイグレーションの修正を生成する場合
- THEN: `./cookbook/alembic-migration.md` を読んで実行します
## 問題の重大度マトリックス
| 問題の種類 | デフォルトの重大度 | アップグレードする場合 |
|------------|-----------------|------------|
| MISSING_IN_MODEL | HIGH | カラムが NOT NULL の場合 |
| MISSING_IN_DB | MEDIUM | モデルがそれを参照している場合 |
| TYPE_MISMATCH | MEDIUM | データ損失を引き起こす可能性がある場合 |
| NULLABLE_MISMATCH | LOW | コードでは NOT NULL、DBでは nullable の場合 |
| NAMING_DRIFT | LOW | - |
| MISSING_MIGRATION | LOW | - |
| FK_MISMATCH | MEDIUM | ORMエラーを引き起こす場合 |
## 統合
### With /ai-dev-kit:check-schema
直接呼び出し:
```bash
# 完全なチェック
/ai-dev-kit:check-schema
# 特定のテーブルをチェック
/ai-dev-kit:check-schema --tables=users,orders
# 修正を生成
/ai-dev-kit:check-schema --auto-fix
# ファイルに出力
/ai-dev-kit:check-schema --output=alignment-report.md
With /ai-dev-kit:execute-lane
データベース関連のレーンの事前チェックとして実行します。
レーン: SL-DB (データベーススキーマ)
事前チェック:
1. ✓ Git worktree cl
(原文がここで切り詰められています) 📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
Schema Alignment Skill
Detect drift between database schemas and code data models. This skill identifies missing columns, type mismatches, orphaned migrations, and naming inconsistencies.
Design Principle
This skill is framework-generic. It works with any ORM or database:
- SQLAlchemy (Python)
- Django ORM (Python)
- Prisma (TypeScript/JavaScript)
- TypeORM (TypeScript)
- Drizzle (TypeScript)
- Alembic migrations
- Prisma migrations
- Django migrations
Variables
| Variable | Default | Description |
|---|---|---|
| SCHEMA_SOURCE | auto | Schema source: auto, migrations, live_db, models |
| SEVERITY_THRESHOLD | medium | Report issues at this level or higher |
| AUTO_FIX | false | Attempt to generate fix suggestions |
| INCLUDE_TYPES | true | Include type mismatch detection |
Instructions
MANDATORY - Follow the Workflow steps below in order.
- Detect database technology and ORM in use
- Extract schema from migrations or live database
- Extract data models from code
- Compare and identify drift
- Generate alignment report
Red Flags - STOP and Reconsider
If you're about to:
- Modify the database schema directly without a migration
- Assume a column exists without checking the schema
- Skip type checking because "it works in tests"
- Ignore nullable/not-null mismatches
STOP -> Check schema alignment -> Generate migration if needed -> Then proceed
Workflow
1. Detect Stack
Identify the database and ORM:
Check for these indicators:
| File/Dependency | Technology |
|-----------------|------------|
| alembic.ini, alembic/ | Alembic (SQLAlchemy) |
| prisma/schema.prisma | Prisma |
| manage.py + migrations/ | Django |
| ormconfig.json | TypeORM |
| drizzle.config.ts | Drizzle |
| supabase/migrations/ | Supabase (PostgreSQL) |
2. Extract Database Schema
Option A: From Migrations (Preferred)
Parse migration files to reconstruct current schema:
# Alembic example
from alembic.script import ScriptDirectory
from alembic.config import Config
config = Config("alembic.ini")
scripts = ScriptDirectory.from_config(config)
# Walk revisions to build schema
Option B: From Live Database
Query information_schema (if accessible):
SELECT table_name, column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_schema = 'public';
Option C: From Model Definitions
Parse ORM model files directly.
3. Extract Code Models
Parse model definitions from code:
SQLAlchemy
# Look for patterns like:
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
email = Column(String(255), nullable=False)
Prisma
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}
Pydantic/TypeScript Types
Also extract related types:
- Pydantic models
- TypeScript interfaces
- BAML type definitions
4. Compare and Detect Drift
Run comparisons:
| Check | Source A | Source B | Issue Type |
|---|---|---|---|
| Missing column | DB schema | ORM model | MISSING_IN_MODEL |
| Missing column | ORM model | DB schema | MISSING_IN_DB |
| Type mismatch | DB type | Code type | TYPE_MISMATCH |
| Nullable mismatch | DB nullable | Model nullable | NULLABLE_MISMATCH |
| Name mismatch | snake_case | camelCase | NAMING_DRIFT |
| Missing migration | Model change | Migration files | MISSING_MIGRATION |
| FK constraint | DB constraint | ORM relationship | FK_MISMATCH |
5. Generate Report
Output format:
# Schema Alignment Report
**Generated**: 2025-12-24T10:00:00Z
**Database**: PostgreSQL (via Supabase)
**ORM**: SQLAlchemy 2.0
## Summary
| Severity | Count |
|----------|-------|
| HIGH | 2 |
| MEDIUM | 3 |
| LOW | 5 |
## Issues
### 1. MISSING_IN_MODEL (HIGH)
**Table**: `curation_jobs`
**Column**: `retry_count` (INTEGER NOT NULL DEFAULT 0)
**Model**: `src/models/curation_job.py:CurationJob`
The column exists in the database but is not defined in the ORM model.
**Fix**:
```python
retry_count: Mapped[int] = mapped_column(Integer, default=0)
2. TYPE_MISMATCH (MEDIUM)
Table: books
Column: isbn (VARCHAR(13))
Model: src/models/book.py:Book.isbn -> str
Database constrains to 13 characters but model allows unbounded string.
Fix:
isbn: Mapped[str] = mapped_column(String(13))
3. MISSING_MIGRATION (LOW)
Model Change: User.preferences added (JSONB)
Migration: Not found
A new column was added to the model but no migration exists.
Fix:
alembic revision --autogenerate -m "add user preferences"
## Cookbook
### SQLAlchemy Detection
- IF: Parsing SQLAlchemy models
- THEN: Read and execute `./cookbook/sqlalchemy-detection.md`
### Prisma Detection
- IF: Parsing Prisma schema
- THEN: Read and execute `./cookbook/prisma-detection.md`
### Alembic Migrations
- IF: Generating migration fix
- THEN: Read and execute `./cookbook/alembic-migration.md`
## Issue Severity Matrix
| Issue Type | Default Severity | Upgrade If |
|------------|-----------------|------------|
| MISSING_IN_MODEL | HIGH | Column is NOT NULL |
| MISSING_IN_DB | MEDIUM | Model references it |
| TYPE_MISMATCH | MEDIUM | Could cause data loss |
| NULLABLE_MISMATCH | LOW | NOT NULL in code, nullable in DB |
| NAMING_DRIFT | LOW | - |
| MISSING_MIGRATION | LOW | - |
| FK_MISMATCH | MEDIUM | Causes ORM errors |
## Integration
### With /ai-dev-kit:check-schema
Direct invocation:
```bash
# Full check
/ai-dev-kit:check-schema
# Check specific tables
/ai-dev-kit:check-schema --tables=users,orders
# Generate fixes
/ai-dev-kit:check-schema --auto-fix
# Output to file
/ai-dev-kit:check-schema --output=alignment-report.md
With /ai-dev-kit:execute-lane
Runs as pre-flight check for database-related lanes:
Lane: SL-DB (Database Schema)
Pre-flight checks:
1. ✓ Git worktree clean
2. ✗ Schema alignment check failed
- 2 HIGH severity issues found
- See alignment-report.md
Action: Resolve schema issues before proceeding.
With /ai-dev-kit:plan-phase
Runs during phase planning:
Planning Phase P1...
Schema Alignment: ⚠️ 3 issues detected
- 1 missing migration
- 2 type mismatches
Recommendation: Add schema alignment task to SL-DB lane.
Output Schema
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"generated_at": {"type": "string", "format": "date-time"},
"database": {"type": "string"},
"orm": {"type": "string"},
"summary": {
"type": "object",
"properties": {
"high": {"type": "integer"},
"medium": {"type": "integer"},
"low": {"type": "integer"}
}
},
"issues": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": {"type": "string"},
"severity": {"enum": ["HIGH", "MEDIUM", "LOW"]},
"table": {"type": "string"},
"column": {"type": "string"},
"model_location": {"type": "string"},
"description": {"type": "string"},
"fix": {"type": "string"}
}
}
}
}
}
Best Practices
- Run regularly: Check schema alignment before each PR
- CI integration: Add to CI pipeline for automatic detection
- Migration hygiene: Always generate migrations for model changes
- Type consistency: Use explicit types in models matching DB constraints
- Document drift: If drift is intentional, document why