メインコンテンツにスキップ

データベースのベースライン設定

ベースライン設定は、次のデータベースの移行履歴を初期化するプロセスです。

  • ✔ Prisma Migrateを使い始める前に存在していた
  • ✔ 維持する必要があるデータ(本番環境など)が含まれており、データベースをリセットできない

ベースライン設定は、Prisma Migrateに、1つ以上の移行がすでに適用されていると想定するように指示します。これにより、生成された移行が、すでに存在するテーブルとフィールドを作成しようとしたときに失敗するのを防ぎます。

:開発データベースをリセットおよびシードすることは許容されると想定しています。

ベースライン設定は、既存のデータベースを持つプロジェクトにPrisma Migrateを追加するの一部です。

警告

このガイドはMongoDBには適用されません
migrate deployの代わりに、db pushMongoDBに使用されます。

ベースライン設定が必要な理由

既存のプロジェクトにPrisma Migrateを追加すると、最初の移行には、Prisma Migrateを使い始める前のデータベースの状態を再作成するために必要なすべてのSQLが含まれています。

The image shows a database labelled 'Existing database', and a list of existing database features next to it - 24 tables, 13 relationships, 92 fields, 3 indexes. An arrow labelled 'represented by' connects the database features list to a box that represents a migration. The existing databases's features are represented by a single migration.

ヒント

最初の移行を編集して、ストアドプロシージャやトリガーなど、Prismaスキーマでは表現できないスキーマ要素を含めることができます。

開発環境を作成およびリセットするには、この最初の移行が必要です。

The image shows a migration history with three migrations. Each migration is represented by a file icon and a name, and all migrations are surrounded by a box labelled 'migration history'. The first migration has an additional label: "State of database before Prisma Migrate", and the two remaining migrations are labelled "Generated as part of the Prisma Migrate workflow". An arrow labelled "prisma migrate dev" connects the migration history box to a database labelled "new development database", signifying that all three migrations are applied to the development database - none are skipped.

ただし、prisma migrate deployを使用して移行をすでに存在し、リセットできないデータベース(本番環境など)にデプロイする場合、最初の移行を含めたくありません

ターゲットデータベースには、最初の移行によって作成されたテーブルと列がすでに含まれており、これらの要素を再度作成しようとすると、エラーが発生する可能性が非常に高くなります。

A migration history represented by three migration files (file icon and name), surrounded by a a box labelled 'migration history'. The first migration is marked 'do not apply', and the second two migrations are marked 'apply'. An arrow labelled with the command 'prisma migrate deploy' points from the migration history to a database labelled 'production'.

ベースライン設定は、Prisma Migrateに最初の移行がすでに適用されていると見なすように指示することで、この問題を解決します。

データベースのベースライン設定

ベースライン移行を作成するには

  1. prisma/migrationsフォルダーがある場合は、このフォルダーを削除、移動、名前変更、またはアーカイブします。

  2. 次のコマンドを実行して、任意の名前のmigrationsディレクトリを内部に作成します。この例では、移行名に0_initを使用します。

    mkdir -p prisma/migrations/0_init
    情報

    0_は、Prisma Migrateが移行を辞書式順序で適用するため重要です。現在のタイムスタンプなど、別の値を使用できます。

  3. prisma migrate diffを使用して移行を生成し、ファイルに保存します

    npx prisma migrate diff \
    --from-empty \
    --to-schema-datamodel prisma/schema.prisma \
    --script > prisma/migrations/0_init/migration.sql
  4. 無視する必要がある移行ごとにprisma migrate resolveコマンドを実行します

    npx prisma migrate resolve --applied 0_init

このコマンドは、ターゲット移行を_prisma_migrationsテーブルに追加し、適用済みとしてマークします。新しい移行を適用するためにprisma migrate deployを実行すると、Prisma Migrateは

  1. ベースライン移行を含む、'適用済み'としてマークされたすべての移行をスキップします
  2. ベースライン移行に来る新しい移行を適用します