データベーススキーマの変更
データベーススキーマの変更
sqlcは、必要なコードを生成するためにCREATE TABLE
およびALTER TABLE
文を解析します。
CREATE TABLE authors (
id SERIAL PRIMARY KEY,
birth_year int NOT NULL
);
ALTER TABLE authors ADD COLUMN bio text NOT NULL;
ALTER TABLE authors DROP COLUMN birth_year;
ALTER TABLE authors RENAME TO writers;
package db
type Writer struct {
ID int
Bio string
}
SQLマイグレーションの処理
sqlcはデータベースマイグレーションを実行してくれませんが、アップマイグレーションとダウンマイグレーションを区別することができます。sqlcはSQLファイルを解析する際にダウンマイグレーションを無視します。
sqlcは以下のツールからのマイグレーション解析をサポートしています:
- atlas
- dbmate
- golang-migrate
- goose
- sql-migrate
- tern
マイグレーション解析を有効にするには、スキーマファイルの代わりにマイグレーションディレクトリを指定します:
version: "2"
sql:
- engine: "postgresql"
queries: "query.sql"
schema: "db/migrations"
gen:
go:
package: "tutorial"
out: "tutorial"
atlas
-- Create "post" table
CREATE TABLE "public"."post" ("id" integer NOT NULL, "title" text NULL, "body" text NULL, PRIMARY KEY ("id"));
package db
type Post struct {
ID int
Title sql.NullString
Body sql.NullString
}
dbmate
-- migrate:up
CREATE TABLE foo (bar INT NOT NULL);
-- migrate:down
DROP TABLE foo;
package db
type Foo struct {
Bar int32
}
golang-migrate
警告: golang-migrateはマイグレーションファイル名を数値的に解釈します。しかし、sqlcはマイグレーションファイルを辞書順で解析します。sqlcにマイグレーションファイルを列挙させる場合は、予期しない動作を避けるために、数値順序が辞書順序と一致するようにしてください。これは、マイグレーションファイル名に十分なゼロを先頭に付けることで実現できます。
これは意図したとおりに動作しません:
1_initial.up.sql
...
9_foo.up.sql
# このマイグレーションファイルは9_fooの前に解析される
10_bar.up.sql
これは意図したとおりに動作します:
001_initial.up.sql
...
009_foo.up.sql
010_bar.up.sql
20060102.up.sql
内:
CREATE TABLE post (
id int NOT NULL,
title text,
body text,
PRIMARY KEY(id)
);
20060102.down.sql
内:
DROP TABLE post;
package db
type Post struct {
ID int
Title sql.NullString
Body sql.NullString
}
goose
警告: sqlcはマイグレーションファイルを辞書順で解析します。Gooseでマイグレーションに数値ファイル名を使用し、sqlcにマイグレーションファイルを列挙させる場合、予期しない動作を避けるために、数値順序が辞書順序と一致するようにしてください。これは、マイグレーションファイル名に十分なゼロを先頭に付けることで実現できます。
これは意図したとおりに動作しません:
1_initial.sql
...
9_foo.sql
# このマイグレーションファイルは9_fooの前に解析される
10_bar.sql
これは意図したとおりに動作します:
001_initial.sql
...
009_foo.sql
010_bar.sql
-- +goose Up
CREATE TABLE post (
id int NOT NULL,
title text,
body text,
PRIMARY KEY(id)
);
-- +goose Down
DROP TABLE post;
package db
type Post struct {
ID int
Title sql.NullString
Body sql.NullString
}
sql-migrate
-- +migrate Up
-- SQL in section 'Up' is executed when this migration is applied
CREATE TABLE people (id int);
-- +migrate Down
-- SQL section 'Down' is executed when this migration is rolled back
DROP TABLE people;
package db
type People struct {
ID int32
}
tern
CREATE TABLE comment (id int NOT NULL, text text NOT NULL);
---- create above / drop below ----
DROP TABLE comment;
package db
type Comment struct {
ID int32
Text string
}
原文:https://docs.sqlc.dev/en/latest/howto/ddl.html