constraints-reviewer について
データベース制約、外部キー、参照整合性を確認するレビュー用スキルです。RailsとActiveRecordの例を用いて、DB側の制約不足や孤立レコードなどを特定します。
主な機能
- 01モデル検証とDB制約の照合
- 02外部キーと削除時の連鎖を確認
- 03ポリモーフィック関連の保護を確認
- 04孤立レコードの検出
- 05合格/警告/不合格の報告
活用シーン
- 01Railsスキーマの整合性をレビュー
- 02DB側の強制制約がない検証を特定
- 03関連レコードの削除動作を確認
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ majesticlabs-dev/ majestic-marketplace --skill constraints-reviewerインストール後、Claude Code で/constraints-reviewerを入力して読み込まれたか確認します。
詳細
制約と参照整合性のレビュー
データベースの制約、外部キー、データ整合性ルールをレビューします。
データベースレベルでの強制
# PROBLEM: Model-only validation (race condition vulnerable)
validates :email, uniqueness: true
# SOLUTION: Database constraint + model validation
add_index :users, :email, unique: true
validates :email, uniqueness: true
競合状態の防止
# PROBLEM: Check-then-insert race condition
def claim_slot
return false if Slot.where(user_id: user.id).exists?
Slot.create!(user_id: user.id)
end
# SOLUTION: Database constraint with rescue
def claim_slot
Slot.create!(user_id: user.id)
rescue ActiveRecord::RecordNotUnique
false
end
不足している制約のチェックリスト
| 検証 | 必須の DB 制約 |
|---|---|
presence: true | NOT NULL |
uniqueness: true | 一意インデックス |
belongs_to | 外部キー |
enum | チェック制約 |
numericality: { in: } | チェック制約 |
外部キーのカスケード
# PROBLEM: Orphaned records on deletion
has_many :comments
# SOLUTION: Dependent handling
has_many :comments, dependent: :destroy # For callbacks
# OR database-level:
add_foreign_key :comments, :posts, on_delete: :cascade
ポリモーフィック関連付け
# PROBLEM: No referential integrity for polymorphics
belongs_to :commentable, polymorphic: true
# SOLUTION: Validate type + consider alternatives
ALLOWED_TYPES = %w[Post Article].freeze
validates :commentable_type, inclusion: { in: ALLOWED_TYPES }
# Better: separate tables instead of polymorphic
belongs_to :post, optional: true
belongs_to :article, optional: true
validates :post_id, presence: true, unless: :article_id?
孤立レコードの検出クエリ
# Find orphaned comments (missing parent)
Comment.left_joins(:post).where(posts: { id: nil })
# Find missing foreign keys
ActiveRecord::Base.connection.tables.each do |table|
columns = ActiveRecord::Base.connection.columns(table)
columns.select { |c| c.name.end_with?('_id') }.each do |col|
# Check if FK exists
end
end
レビューチェックリスト
- すべての
uniqueness検証に一意インデックスがありますか? - すべての
presence検証に NOT NULL 制約がありますか? - すべての
_idカラムに外部キーがありますか? - 削除時のカスケードルールが定義されていますか?
- ポリモーフィック型が検証されていますか?
- 孤立レコードが発生する可能性はありませんか?
出力形式
## Constraints Review: [PASS/WARN/FAIL]
### Missing Database Constraints
- [model]: [validation without DB enforcement]
### Foreign Key Issues
- [table]: [missing FK on _id column]
### Race Condition Risks
- [code location]: [check-then-insert pattern]
### Orphan Risks
- [association]: [could create orphans]
### Recommendations
1. [Prioritized fixes]
コメント
Markdown 対応