データベースマイグレーションを作成する際に使用。Atlas CLI使用、master/shardingのマイグレーション、SQLite構文。DB変更、テーブル追加、カラム追加、マイグレーションファイル作成時に使用。
このプロジェクトのデータベースマイグレーション実装パターンを定義します。
スキーマは db/schema/ に .hcl 形式で定義されている。db/migrations/ には master / master-mysql / view_master / view_master-mysql および sharding_1..4 / sharding_1..4-mysql など、環境別・用途別のマイグレーションがある。
db/schema/
├── master.hcl # マスタースキーマ(.hcl)
├── master-mysql/ # マスター(MySQL向け .hcl)
│ └── master.hcl
├── sharding_1/ .. sharding_4/ # シャード別 .hcl(_schema.hcl + dm_*.hcl)
└── sharding_*_mysql/ # シャード別 MySQL 向け .hcl
db/migrations/
├── master/ # マスターDB用
├── master-mysql/ # マスターDB用(MySQL)
├── view_master/ # ビュー用(マスター)
├── view_master-mysql/ # ビュー用(マスター・MySQL)
├── sharding_1/ .. sharding_4/ # シャーディングDB用
└── sharding_*_mysql/ # シャーディングDB用(MySQL)
既存マイグレーション:
db/migrations/master/ - マスターDBマイグレーションdb/migrations/sharding_1/ - シャーディングDBマイグレーション例スクリプト:
scripts/migrate.sh - マイグレーション適用スクリプトAtlas CLIで差分を生成。スキーマが .hcl の場合は --to に .hcl ファイルまたは .hcl があるディレクトリを指定する。
# マスターDB用(.hcl スキーマの場合)
atlas migrate diff {migration_name} \
--dir "file://db/migrations/master" \
--to "file://db/schema/master.hcl" \
--dev-url "sqlite://file?mode=memory"
# マスターDB用(master-mysql ディレクトリの .hcl の場合)
atlas migrate diff {migration_name} \
--dir "file://db/migrations/master-mysql" \
--to "file://db/schema/master-mysql" \
--dev-url "mysql://root:password@localhost:3306/dev"
# シャーディングDB用(.hcl スキーマの場合、4つ全てに適用)
for i in 1 2 3 4; do
atlas migrate diff {migration_name} \
--dir "file://db/migrations/sharding_$i" \
--to "file://db/schema/sharding_$i" \
--dev-url "sqlite://file?mode=memory"
done
# シャーディングDB用(MySQL の場合、4つ全てに適用)
for i in 1 2 3 4; do
atlas migrate diff {migration_name} \
--dir "file://db/migrations/sharding_${i}-mysql" \
--to "file://db/schema/sharding_${i}_mysql" \
--dev-url "mysql://root:password@localhost:3306/dev"
done
ファイル名: {YYYYMMDDHHMMSS}_{description}.sql
例: 20251226074846_initial.sql
-- Create "entities" table
CREATE TABLE `entities` (
`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT,
`name` text NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL
);
シャーディングDBでは、テーブル名にサフィックスが付きます:
-- DB1: entities_000 ~ entities_007
-- DB2: entities_008 ~ entities_015
-- DB3: entities_016 ~ entities_023
-- DB4: entities_024 ~ entities_031
CREATE TABLE `users_000` (
`id` integer NOT NULL,
`name` text NOT NULL,
`email` text NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`id`)
);
-- 同様に users_001 ~ users_007 を作成
-- Create index "idx_entities_name" to table: "entities"
CREATE INDEX `idx_entities_name` ON `entities` (`name`);
-- Add column "description" to table: "entities"
ALTER TABLE `entities` ADD COLUMN `description` text NULL;
# 全マイグレーション適用
./scripts/migrate.sh all
# マスターのみ
./scripts/migrate.sh master
# シャーディングのみ
./scripts/migrate.sh sharding
マイグレーションファイルを手動で編集した場合:
atlas migrate hash --dir "file://db/migrations/master"
atlas migrate hash --dir "file://db/migrations/sharding_1"
# ... sharding_2, 3, 4 も同様
_000 ~ _031)