🐶

Prisma Migrate or Pushでデフォルトのデータ型以外を使用する

2021/01/03に公開

TL;DR

  • Prisma(v2.13.0)でデフォルトのデータ型以外を使用して Migrate or Push する場合は、DB で直接データ型を変更してから prisma introspectprisma generate を使用する。

  • [追記] v2.15.0より Prisma Migrate で native database types をサポートしました 🎉🎉🎉

概要

Prisma で Migration しようとした際に、Prisma のデータ型周りで少し勉強になったので共有しておきます。

本題

Prisma にはデフォルトで String や Int etc.のデータ型が実装されています。また、これらのデータ型は native database の特定のデータ型とマッピングします。
例えば、Prisma を使用して MySQL を Migrate する場合、String 型は VARCHAR(191)にマッピングされます。(なぜ"191"なのかはこの記事をお読み下さい。)

では、VARCHAR(191)以上の文字列を格納したい場合はどうするのか。
この場合、単純に VARCHAR(255)や TEXT 型を使用することで解決できると思います。そして、Prisma には native database のデータ型を使用する方法が存在しています。
例えば、MySQL の VARCHAR(255)を使用する場合、以下の様にnativeTypes@db.VarChar(255)(Extended native types)を追加します。

generator dbml {
  provider = "prisma-dbml-generator"
  previewFeatures = [nativeTypes]
}

~~~

longString String @db.VarChar(255)

これで VARCHAR(255)が使用できるようになりま…せん!
この状態で prisma migrate or prisma db push を使用すると以下の様なエラーが出力されます。

Response "Some of the requested Preview features are not yet allowed in migration engine. Please remove them from your data model before using migrations. (blocked: `nativeTypes`)"

公式ドキュメントにも記載されている様に、現状(v2.13.0) Prisma Migrate or Push は native database type attributes をサポートしていません。

[追記] 現在(v2.15.0)は可能です。

Prisma Migrate not yet supported
Prisma Migrate does not yet support native database type attributes. If you try to prisma migrate or prisma db push, you will see the following error:
Response "Some of the requested Preview features are not yet allowed in migration engine. Please remove them from your data model before using migrations. (blocked: nativeTypes)"
db push not yet supported
db push uses the Migration Engine, which does not support native database type attributes yet.Ï

解決方法

デフォルトのデータ型以外を使用して Prisma Migrate or Push を使用したい場合は、一旦デフォルトのデータ型で prisma migrate or prisma db push をし、DB で直接データ型を変更してから、prisma introspectprisma generate を実行して既存のデータベースを introspect する必要があります。
(introspect は既存のデータベース内のテーブル、カラム、インデックス、制約を Prisma モデルにマッピングします)

Here's an overview of its main functions:
Map tables in the database to Prisma models
Map columns in the database to the fields of Prisma models
Map indexes in the database to indexes in the Prisma schema
Map database constraints to attributes or type modifiers in the Prisma schema

前述の例だと、

  • 一旦デフォルトのデータ型を使用
longString String
  • prisma migrate or prisma db push を実行

  • MySQL にログインしてデータ型を変更

mysql> alter table [テーブル名] change longString longString varchar(255);
  • prisma introspectprisma generate を実行

これで Prisma を使用して native database のデータ型(VARCHAR(255))を使用することが可能になりました。

まとめ

Prisma は比較的新しいツールで、今回紹介した部分も Preview 版です。
その為、migrate や push コマンドを使う場合は --preview-feature というオプションが必要になります。
まだまだお試し期間という印象がある Prisma ですが、今回の記事が皆さんの Prisma ライフのお役に立っていれば幸いです 🐶

Discussion