gchapim

Ecto Migrator

開發程式設計v1.0.0
作者:gchapim更新於 2026-05-11ecto-migrator@clawhub_gchapim/ecto-migrator
程式碼生成指令碼工具#Database

據 AlphaMoat 統計,截至 2026-09,Ecto Migrator 累計下載 2,557 次、獲 1 個星標,在全部 5,078 個 AI 技能中排名第 4,053 位,在「開發程式設計」分類(577 個)中排名第 504 位。

累計安裝
156
累計下載
2557
星標
1
全站排名
#4,053
全站前 80% · 「開發程式設計」前 88%
平台累計安裝累計下載星標評論
ClawHub ↗7623621-
SkillHub ↗15625571—

各平台的計數口徑不同,統計時間不一致。

這個技能是做什麼的

可草擬表、列、索引、約束、引用關係和資料遷移。生成內容可能包含刪除表列、重新命名或級聯刪除,並可能鎖定大型生產表;應用前應審查破壞性操作、備份、上線策略和回滾行為。 執行需要適當 Elixir/Ecto 專案和 Repo/資料庫設定,起草本身不套用變更。schema 與 data 分離,適當時並行索引獨立遷移,無法推斷復原的操作明確定義 up/down。down 函數不保證恢復已刪或覆蓋資料,應結合備份驗證復原。

資料釋出於 2026-10-27

可以用來做什麼

  • 起草 schema 變更或資料庫索引遷移
  • 審閱資料遷移和可逆性

什麼時候用

  • 將生成遷移作為草案,並在生產應用前完成程式碼審查與備份計畫時

示例提示詞

以下是根據技能文件生成的示例,不代表實際執行結果。

為新增欄位起草遷移,但不生成或執行刪除操作。
列出應用生產遷移前的鎖表、回滾和備份檢查。

月度資料趨勢

累計下載2557
1672214826232026-03 · 累計下載 17382026-05 · 累計下載 19502026-06 · 累計下載 20292026-07 · 累計下載 22102026-08 · 累計下載 22852026-09 · 累計下載 255726-0326-09
星標1
0122026-03 · 星標 12026-05 · 星標 12026-06 · 星標 12026-07 · 星標 12026-08 · 星標 12026-09 · 星標 126-0326-09

2026-09 起統計方法調整:同名技能按作者分別統計,並覆蓋全部技能。圖中虛線為調整前的月份,與之後的資料不直接比較,也不計算跨越調整的增長。

月份累計下載環比星標
2026-092557—1
2026-082285+3.4%1
2026-072210+8.9%1
2026-062029+4.1%1
2026-051950—1
2026-031738—1

SKILL.md 原文

以下是作者釋出的原始檔案,按純文字顯示,本站未做修改或稽核;其中的連結不可點選,命令請核實後再執行。抓取於 2026-10-23。

8.3 KB · ClawHub v1.0.0
---
name: ecto-migrator
description: "Generate Ecto migrations from natural language or schema descriptions. Handles tables, columns, indexes, constraints, references, enums, and partitioning. Supports reversible migrations, data migrations, and multi-tenant patterns. Use when creating or modifying database schemas, adding indexes, altering tables, creating enums, or performing data migrations in an Elixir project."
---

# Ecto Migrator

## Generating Migrations

### From Natural Language
展開全部(共 308 行)

Parse the user's description and generate a migration file. Common patterns:

| User Says | Migration Action |
|-----------|-----------------|
| "Create users table with email and name" | `create table(:users)` with columns |
| "Add phone to users" | `alter table(:users), add :phone` |
| "Make email unique on users" | `create unique_index(:users, [:email])` |
| "Add tenant_id to all tables" | Multiple `alter table` with index |
| "Rename status to state on orders" | `rename table(:orders), :status, to: :state` |
| "Remove the legacy_id column from users" | `alter table(:users), remove :legacy_id` |
| "Add a check constraint on orders amount > 0" | `create constraint(:orders, ...)` |

### File Naming

```bash
mix ecto.gen.migration <name>
# Generates: priv/repo/migrations/YYYYMMDDHHMMSS_<name>.exs
```

Name conventions: `create_<table>`, `add_<column>_to_<table>`, `create_<table>_<column>_index`, `alter_<table>_add_<columns>`.

## Migration Template

```elixir
defmodule MyApp.Repo.Migrations.CreateUsers do
  use Ecto.Migration

  def change do
    create table(:users, primary_key: false) do
      add :id, :binary_id, primary_key: true
      add :email, :string, null: false
      add :name, :string, null: false
      add :role, :string, null: false, default: "member"
      add :metadata, :map, default: %{}
      add :tenant_id, :binary_id, null: false

      add :team_id, references(:teams, type: :binary_id, on_delete: :delete_all)

      timestamps(type: :utc_datetime_usec)
    end

    create unique_index(:users, [:tenant_id, :email])
    create index(:users, [:tenant_id])
    create index(:users, [:team_id])
  end
end
```

## Column Types

See [references/column-types.md](references/column-types.md) for complete type mapping and guidance.

Key decisions:
- **IDs**: Use `:binary_id` (UUID) — set `primary_key: false` on table, add `:id` manually.
- **Money**: Use `:integer` (cents) or `:decimal` — never `:float`.
- **Timestamps**: Always `timestamps(type: :utc_datetime_usec)`.
- **Enums**: Use `:string` with app-level `Ecto.Enum` — avoid Postgres enums (hard to migrate).
- **JSON**: Use `:map` (maps to `jsonb`).
- **Arrays**: Use `{:array, :string}` etc.

## Index Strategies

See [references/index-patterns.md](references/index-patterns.md) for detailed index guidance.

### When to Add Indexes

Always index:
- Foreign keys (`_id` columns)
- `tenant_id` (first column in composite indexes)
- Columns used in `WHERE` clauses
- Columns used in `ORDER BY`
- Unique constraints

### Index Types

```elixir
# Standard B-tree
create index(:users, [:tenant_id])

# Unique
create unique_index(:users, [:tenant_id, :email])

# Partial (conditional)
create index(:orders, [:status], where: "status != 'completed'", name: :orders_active_status_idx)

# GIN for JSONB
create index(:events, [:metadata], using: :gin)

# GIN for array columns
create index(:posts, [:tags], using: :gin)

# Composite
create index(:orders, [:tenant_id, :status, :inserted_at])

# Concurrent (no table lock — use in separate migration)
@disable_ddl_transaction true
@disable_migration_lock true

def change do
  create index(:users, [:email], concurrently: true)
end
```

## Constraints

```elixir
# Check constraint
create constraint(:orders, :amount_must_be_positive, check: "amount > 0")

# Exclusion constraint (requires btree_gist extension)
execute "CREATE EXTENSION IF NOT EXISTS btree_gist", ""
create constraint(:reservations, :no_overlapping_bookings,
  exclude: ~s|gist (room_id WITH =, tstzrange(starts_at, ends_at) WITH &&)|
)

# Unique constraint (same as unique_index for most purposes)
create unique_index(:accounts, [:slug])
```

## References (Foreign Keys)

```elixir
add :user_id, references(:users, type: :binary_id, on_delete: :delete_all), null: false
add :team_id, references(:teams, type: :binary_id, on_delete: :nilify_all)
add :parent_id, references(:categories, type: :binary_id, on_delete: :nothing)
```

| `on_delete` | Use When |
|-------------|----------|
| `:delete_all` | Child can't exist without parent (memberships, line items) |
| `:nilify_all` | Child should survive parent deletion (optional association) |
| `:nothing` | Handle in application code (default) |
| `:restrict` | Prevent parent deletion if children exist |

## Multi-Tenant Patterns

### Every Table Gets tenant_id

```elixir
def change do
  create table(:items, primary_key: false) do
    add :id, :binary_id, primary_key: true
    add :name, :string, null: false
    add :tenant_id, :binary_id, null: false
    timestamps(type: :utc_datetime_usec)
  end

  # Always composite index with tenant_id first
  create index(:items, [:tenant_id])
  create unique_index(:items, [:tenant_id, :name])
end
```

### Adding tenant_id to Existing Tables

```elixir
def change do
  alter table(:items) do
    add :tenant_id, :binary_id
  end

  # Backfill in a separate data migration, then:
  # alter table(:items) do
  #   modify :tenant_id, :binary_id, null: false
  # end
end
```

## Data Migrations

**Rule: Never mix schema changes and data changes in the same migration.**

### Safe Data Migration Pattern

```elixir
defmodule MyApp.Repo.Migrations.BackfillUserRoles do
  use Ecto.Migration

  # Don't use schema modules — they may change after this migration runs
  def up do
    execute """
    UPDATE users SET role = 'member' WHERE role IS NULL
    """
  end

  def down do
    # Data migrations may not be reversible
    :ok
  end
end
```

### Batched Data Migration (large tables)

```elixir
def up do
  execute """
  UPDATE users SET role = 'member'
  WHERE id IN (
    SELECT id FROM users WHERE role IS NULL LIMIT 10000
  )
  """

  # For very large tables, use a Task or Oban job instead
end
```

## Reversible vs Irreversible

### Reversible (use `change`)

These are auto-reversible:
- `create table` ↔ `drop table`
- `add column` ↔ `remove column`
- `create index` ↔ `drop index`
- `rename` ↔ `rename`

### Irreversible (use `up`/`down`)

Must define both directions:
- `modify` column type — Ecto can't infer the old type
- `execute` raw SQL
- Data backfills
- Dropping columns with data

```elixir
def up do
  alter table(:users) do
    modify :email, :citext, from: :string  # from: helps reversibility
  end
end

def down do
  alter table(:users) do
    modify :email, :string, from: :citext
  end
end
```

### Using `modify` with `from:`

Phoenix 1.7+ supports `from:` for reversible `modify`:

```elixir
def change do
  alter table(:users) do
    modify :email, :citext, null: false, from: {:string, null: true}
  end
end
```

## PostgreSQL Extensions

```elixir
def change do
  execute "CREATE EXTENSION IF NOT EXISTS citext", "DROP EXTENSION IF EXISTS citext"
  execute "CREATE EXTENSION IF NOT EXISTS pgcrypto", "DROP EXTENSION IF EXISTS pgcrypto"
  execute "CREATE EXTENSION IF NOT EXISTS pg_trgm", "DROP EXTENSION IF EXISTS pg_trgm"
end
```

## Enum Types (PostgreSQL native — use sparingly)

Prefer `Ecto.Enum` with `:string` columns. If you must use Postgres enums:

```elixir
def up do
  execute "CREATE TYPE order_status AS ENUM ('pending', 'confirmed', 'shipped', 'delivered')"

  alter table(:orders) do
    add :status, :order_status, null: false, default: "pending"
  end
end

def down do
  alter table(:orders) do
    remove :status
  end

  execute "DROP TYPE order_status"
end
```

**Warning:** Adding values to Postgres enums requires `ALTER TYPE ... ADD VALUE` which cannot run inside a transaction. Prefer `:string` + `Ecto.Enum`.

## Checklist

- [ ] Primary key: `primary_key: false` + `add :id, :binary_id, primary_key: true`
- [ ] `null: false` on required columns
- [ ] `timestamps(type: :utc_datetime_usec)`
- [ ] Foreign keys with appropriate `on_delete`
- [ ] Index on every foreign key column
- [ ] `tenant_id` indexed (composite with lookup fields)
- [ ] Unique constraints where needed
- [ ] Concurrent indexes in separate migration with `@disable_ddl_transaction true`
- [ ] Data migrations in separate files from schema migrations

「開發程式設計」分類下的熱門技能

gchapim 的其他技能

資料月份:2026-09 · 下載/星標/安裝數聚合自公開技能註冊庫(ClawHub、SkillHub),按月更新。口徑說明見資料方法。