Token导航 LogoToken导航TokenDH.com
开发需要联网github未标认证来源可访问clear审计通过

axiom-database-migration公理数据库迁移

Agent Skill

用于辅助数据库表结构、查询语句、迁移脚本和数据维护任务。它适合让 Agent 分析 schema、编写 SQL、排查查询问题、整理索引或生成迁移建议。使用时需要明确数据库类型、连接环境和目标表,区分只读分析与写入变更;涉及删除、更新、迁移和批量导入时,应优先 dry-run、备份或事务保护,避免误操作。

总安装

4,260

周安装

174

GitHub Stars

868

下载量

1,364
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:axiom-database-migration(公理数据库迁移)
来源仓库:https://github.com/charleswiltgen/axiom
仓库路径:skills/axiom-database-migration
安装命令:
npx skills add https://github.com/charleswiltgen/axiom --skill axiom-database-migration
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/charleswiltgen/axiom --skill axiom-database-migration

简介

用于辅助数据库表结构、查询语句、迁移脚本和数据维护任务,适合让 Agent 分析 schema、编写 SQL 或生成迁移建议。

  • 适用于生产环境中的数据库模式演进,支持 SwiftData、GRDB、SQLite 等多种数据库类型。
  • 通过 GitHub 仓库安装,使用 npx skills add 命令添加指定技能,需结合原始 README 进一步确认具体用法。
  • 使用时需明确数据库类型和连接环境,区分只读分析与写入变更;涉及删除、更新或批量导入时应优先 dry-run 或事务保护。
  • axiom-database-migration 属于开发类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

Database Migration

Overview

Safe database schema evolution for production apps with user data. Core principle Migrations are immutable after shipping. Make them additive, idempotent, and thoroughly tested.

Example Prompts

These are real questions developers ask that this skill is designed to answer:

1. "I need to add a new column to store user preferences, but the app is already live with user data. How do I do this safely?"

→ The skill covers safe additive patterns for adding columns without losing existing data, including idempotency checks

2. "I'm getting 'cannot add NOT NULL column' errors when I try to migrate. What does this mean and how do I fix it?"

→ The skill explains why NOT NULL columns fail with existing rows, and shows the safe pattern (nullable first, backfill later)

3. "I need to change a column from text to integer. Can I just ALTER the column type?"

→ The skill demonstrates the safe pattern: add new column → migrate data → deprecate old (NEVER delete)

4. "I'm adding a foreign key relationship between tables. How do I add the relationship without breaking existing data?"

→ The skill covers safe foreign key patterns: add column → populate data → add index (SQLite limitations explained)

5. "Users are reporting crashes after the last update. I changed a migration but the app is already in production. What do I do?"

→ The skill explains migrations are immutable after shipping; shows how to create a new migration to fix the issue rather than modifying the old one


⛔ NEVER Do These (Data Loss Risk)

These actions DESTROY user data in production

NEVER use DROP TABLE with user data ❌ NEVER modify shipped migrations (create new one instead) ❌ NEVER recreate tables to change schema (loses data) ❌ NEVER add NOT NULL column without DEFAULT value ❌ NEVER delete columns (SQLite doesn't support DROP COLUMN safely)

If you're tempted to do any of these, STOP and use the safe patterns below.

Mandatory Rules

ALWAYS follow these

  1. Additive only Add new columns/tables, never delete
  2. Idempotent Check existence before creating (safe to run twice)
  3. Transactional Wrap entire migration in single transaction
  4. Test both paths Fresh install AND migration from previous version
  5. Nullable first Add columns as NULL, backfill later if needed
  6. Immutable Once shipped to users, migrations cannot be changed

Safe Patterns

Adding Column (Most Common)

// ✅ Safe pattern
func migration00X_AddNewColumn() throws {
    try database.write { db in
        // 1. Check if column exists (idempotency)
        let hasColumn = try db.columns(in: "tableName")
            .contains { $0.name == "newColumn" }

        if !hasColumn {
            // 2. Add as nullable (works with existing rows)
            try db.execute(sql: """
                ALTER TABLE tableName
                ADD COLUMN newColumn TEXT
            """)
        }
    }
}

Why this works

  • Nullable columns don't require DEFAULT
  • Existing rows get NULL automatically
  • No data transformation needed
  • Safe for users upgrading from old versions

Adding Column with Default Value

// ✅ Safe pattern with default
func migration00X_AddColumnWithDefault() throws {
    try database.write { db in
        let hasColumn = try db.columns(in: "tracks")
            .contains { $0.name == "playCount" }

        if !hasColumn {
            try db.execute(sql: """
                ALTER TABLE tracks
                ADD COLUMN playCount INTEGER DEFAULT 0
            """)
        }
    }
}

Changing Column Type (Advanced)

Pattern: Add new column → migrate data → deprecate old (NEVER delete)

// ✅ Safe pattern for type change
func migration00X_ChangeColumnType() throws {
    try database.write { db in
        // Step 1: Add new column with new type
        try db.execute(sql: """
            ALTER TABLE users
            ADD COLUMN age_new INTEGER
        """)

        // Step 2: Migrate existing data
        try db.execute(sql: """
            UPDATE users
            SET age_new = CAST(age_old AS INTEGER)
            WHERE age_old IS NOT NULL
        """)

        // Step 3: Application code uses age_new going forward
        // (Never delete age_old column - just stop using it)
    }
}

Adding Foreign Key Constraint

// ✅ Safe pattern for foreign keys
func migration00X_AddForeignKey() throws {
    try database.write { db in
        // Step 1: Add new column (nullable initially)
        try db.execute(sql: """
            ALTER TABLE tracks
            ADD COLUMN album_id TEXT
        """)

        // Step 2: Populate the data
        try db.execute(sql: """
            UPDATE tracks
            SET album_id = (
                SELECT id FROM albums
                WHERE albums.title = tracks.album_name
            )
        """)

        // Step 3: Add index (helps query performance)
        try db.execute(sql: """
            CREATE INDEX IF NOT EXISTS idx_tracks_album_id
            ON tracks(album_id)
        """)

        // Note: SQLite doesn't allow adding FK constraints to existing tables
        // The foreign key relationship is enforced at the application level
    }
}

Complex Schema Refactoring

Pattern: Break into multiple migrations

// Migration 1: Add new structure
func migration010_AddNewTable() throws {
    try database.write { db in
        try db.execute(sql: """
            CREATE TABLE IF NOT EXISTS new_structure (
                id TEXT PRIMARY KEY,
                data TEXT
            )
        """)
    }
}

// Migration 2: Copy data
func migration011_MigrateData() throws {
    try database.write { db in
        try db.execute(sql: """
            INSERT INTO new_structure (id, data)
            SELECT id, data FROM old_structure
        """)
    }
}

// Migration 3: Add indexes
func migration012_AddIndexes() throws {
    try database.write { db in
        try db.execute(sql: """
            CREATE INDEX IF NOT EXISTS idx_new_structure_data
            ON new_structure(data)
        """)
    }
}

// Old structure stays around (deprecated in code)

Testing Checklist

BEFORE deploying any migration

// Test 1: Migration path (CRITICAL - tests data preservation)
@Test func migrationFromV1ToV2Succeeds() async throws {
    let db = try Database(inMemory: true)

    // Simulate v1 schema
    try db.write { db in
        try db.execute(sql: "CREATE TABLE tableName (id TEXT PRIMARY KEY)")
        try db.execute(sql: "INSERT INTO tableName (id) VALUES ('test1')")
    }

    // Run v2 migration
    try db.runMigrations()

    // Verify data survived + new column exists
    try db.read { db in
        let count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM tableName")
        #expect(count == 1)  // Data preserved

        let columns = try db.columns(in: "tableName").map { $0.name }
        #expect(columns.contains("newColumn"))  // New column exists
    }
}

Test 2 Fresh install (run all migrations, verify final schema)

@Test func freshInstallCreatesCorrectSchema() async throws {
    let db = try Database(inMemory: true)

    // Run all migrations
    try db.runMigrations()

    // Verify final schema
    try db.read { db in
        let tables = try db.tables()
        #expect(tables.contains("tableName"))

        let columns = try db.columns(in: "tableName").map { $0.name }
        #expect(columns.contains("id"))
        #expect(columns.contains("newColumn"))
    }
}

Test 3 Idempotency (run migrations twice, should not throw)

@Test func migrationsAreIdempotent() async throws {
    let db = try Database(inMemory: true)

    // Run migrations twice
    try db.runMigrations()
    try db.runMigrations()  // Should not throw

    // Verify still correct
    try db.read { db in
        let count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM tableName")
        #expect(count == 0)  // No duplicate data
    }
}

Manual testing (before TestFlight)

  1. Install v(n-1) build on device → add real user data
  2. Install v(n) build (with new migration)
  3. Verify: App launches, data visible, no crashes

Decision Tree

What are you trying to do?
├─ Add new column?
│  └─ ALTER TABLE ADD COLUMN (nullable) → Done
├─ Add column with default?
│  └─ ALTER TABLE ADD COLUMN ... DEFAULT value → Done
├─ Change column type?
│  └─ Add new column → Migrate data → Deprecate old → Done
├─ Delete column?
│  └─ Mark as deprecated in code → Never delete from schema → Done
├─ Rename column?
│  └─ Add new column → Migrate data → Deprecate old → Done
├─ Add foreign key?
│  └─ Add column → Populate data → Add index → Done
└─ Complex refactor?
   └─ Break into multiple migrations → Test each step → Done

Common Errors

ErrorFix
FOREIGN KEY constraint failedCheck parent row exists, or disable FK temporarily
no such column: columnNameAdd migration to create column
cannot add NOT NULL columnUse nullable column first, backfill in separate migration
table tableName already existsAdd IF NOT EXISTS clause
duplicate column nameCheck if column exists before adding (idempotency)

Common Mistakes

Adding NOT NULL without DEFAULT

// ❌ Fails on existing data
ALTER TABLE albums ADD COLUMN rating INTEGER NOT NULL

Correct: Add as nullable first

ALTER TABLE albums ADD COLUMN rating INTEGER  // NULL allowed
// Backfill in separate migration if needed
UPDATE albums SET rating = 0 WHERE rating IS NULL

Forgetting to check for existence — Always add IF NOT EXISTS or manual check

Modifying shipped migrations — Create new migration instead

Not testing migration path — Always test upgrade from previous version

GRDB-Specific Patterns

DatabaseMigrator Setup

var migrator = DatabaseMigrator()

// Migration 1
migrator.registerMigration("v1") { db in
    try db.execute(sql: """
        CREATE TABLE IF NOT EXISTS users (
            id TEXT PRIMARY KEY,
            name TEXT NOT NULL
        )
    """)
}

// Migration 2
migrator.registerMigration("v2") { db in
    let hasColumn = try db.columns(in: "users")
        .contains { $0.name == "email" }

    if !hasColumn {
        try db.execute(sql: """
            ALTER TABLE users
            ADD COLUMN email TEXT
        """)
    }
}

// Apply migrations
try migrator.migrate(dbQueue)

Checking Migration Status

// Check which migrations have been applied
let appliedMigrations = try dbQueue.read { db in
    try migrator.appliedMigrations(db)
}
print("Applied migrations: \(appliedMigrations)")

// Check if migrations are needed
let hasBeenMigrated = try dbQueue.read { db in
    try migrator.hasBeenMigrated(db)
}

SwiftData Migrations

For SwiftData (iOS 17+), use VersionedSchema and SchemaMigrationPlan:

// Define schema versions
enum MyAppSchemaV1: VersionedSchema {
    static var versionIdentifier = Schema.Version(1, 0, 0)
    static var models: [any PersistentModel.Type] {
        [Track.self, Album.self]
    }
}

enum MyAppSchemaV2: VersionedSchema {
    static var versionIdentifier = Schema.Version(2, 0, 0)
    static var models: [any PersistentModel.Type] {
        [Track.self, Album.self, Playlist.self]  // Added Playlist
    }
}

// Define migration plan
enum MyAppMigrationPlan: SchemaMigrationPlan {
    static var schemas: [any VersionedSchema.Type] {
        [MyAppSchemaV1.self, MyAppSchemaV2.self]
    }

    static var stages: [MigrationStage] {
        [migrateV1toV2]
    }

    static let migrateV1toV2 = MigrationStage.custom(
        fromVersion: MyAppSchemaV1.self,
        toVersion: MyAppSchemaV2.self,
        willMigrate: nil,
        didMigrate: { context in
            // Custom migration logic here
        }
    )
}

Real-World Impact

Before Developer adds NOT NULL column → migration fails for 50% of users → emergency rollback → data inconsistency

After Developer adds nullable column → tests both paths → smooth deployment → backfills data in v2

Key insight Migrations can't be rolled back in production. Get them right the first time through thorough testing.

tvOS

tvOS migrations may run against a fresh database. The system deletes local storage under pressure, so your app may launch with no database at all. Migrations must handle this gracefully — they effectively become both "create" and "upgrade" operations.

Key implications:

  • Migrations must be idempotent (already a best practice, but critical here)
  • Don't assume previous data exists for backfill operations
  • Test the "fresh install" path as often as the "upgrade" path

See axiom-tvos for full tvOS storage constraints.


Last Updated: 2025-11-28 Frameworks: SQLite, GRDB, SwiftData Status: Production-ready patterns for safe schema evolution

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

30.71%
按下载量换算419

Codex

23.14%
按下载量换算316

OpenCode

19.18%
按下载量换算262

Antigravity

13.34%
按下载量换算182

Cursor

7.98%
按下载量换算109

windsurf

3.36%
按下载量换算46

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills