0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

goのmigrateで複数クエリを1ファイルにまとめてマイグレーションしたい

Last updated at Posted at 2020-07-15

ちょっとハマったのでメモ。

事象

migrateでこのsqlを1ファイルで流したかった。

20200715034115_create_samples.up.sql
BEGIN;

CREATE TABLE `samples` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `boo_id` bigint(20) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`, `created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `samples` PARTITION BY RANGE COLUMNS(`created_at`) (
  PARTITION p2020 VALUES LESS THAN ('2020-01-01 00:00:00'),
  PARTITION p2021 VALUES LESS THAN ('2021-01-01 00:00:00'),
  PARTITION p2022 VALUES LESS THAN ('2022-01-01 00:00:00'),
  PARTITION p2023 VALUES LESS THAN ('2023-01-01 00:00:00'),
  PARTITION p2024 VALUES LESS THAN ('2024-01-01 00:00:00')
);

create index samples_index on `samples` (`boo_id`);

COMMIT;

構文的には問題ないはずなのだが、なぜか Error 1064: You have an error in your SQL syntax; のエラーが出る。

対処

dsnに multiStatements=true をつける。こんなイメージ。
このオプションをつけていれば一つのsqlファイルで複数のクエリをサポートしてくれるようになる。

user := os.Getenv("DB_USERNAME")
pass := os.Getenv("DB_PASSWORD")
host := os.Getenv("DB_HOST")
port := os.Getenv("DB_PORT")
dbName := os.Getenv("DB_DATABASE")

dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true&multiStatements=true", user, pass, host, port, dbName)

このプルリクがmultiStatementsの対応をした時のやつ。
migrateの話というより、go-sql-driver/mysqlの話だった。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?