2
1

More than 3 years have passed since last update.

Prismaの基本操作(MySQLのマイグレーション編)

Last updated at Posted at 2021-07-05

本記事の内容

TypeScriptやGo言語をサポートしているPrismaの説明をします。
本記事はマイグレーション編となります。CRUD処理はCRUD処理編をお読みください。

アジェンダ

  1. Prismaとは
  2. Prismaのインストール
  3. PrismaのMigration

1. Prismaとは

Prismaとは

Prismaは、PostgreSQL、MySQL、SQLite用のORM。TypeScript、Go言語をサポート。
主要サービスは3つですが、本記事ではPrisma Migrationの説明を記載します。

○主要なサービス
①Prisma Client:DBクライアント。
スクリーンショット 2021-07-05 16.03.19.png
②Prisma Migration:TBL作成時のマイグレーションツール
スクリーンショット 2021-07-05 16.04.42.png
③Prisma Studio:TBL状態を確認するツールスクリーンショット 2021-07-05 16.04.46.png

2. Prismaのインストール

Prismaのインストール

Prismaはnpmサポートを受けているので、npmやyarnコマンドでインストール可能です。
下記コマンドでインストールしましょう。
~/develop/study/prisma $ yarn init
yarn init v1.22.5
warning ../../../package.json: No license field
question name (prisma): 
question version (1.0.0): 
question description: 
question entry point (index.js): 
question repository url: 
question author: 
question license (MIT): 
question private: 
success Saved package.json
✨  Done in 6.47s.

~/develop/study/prisma $ yarn add prisma 
yarn add v1.22.5
warning ../../../package.json: No license field
info No lockfile found.
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 🔨  Building fresh packages...
success Saved lockfile.
success Saved 2 new dependencies.
info Direct dependencies
└─ prisma@2.26.0
info All dependencies
├─ @prisma/engines@2.26.0-23.9b816b3aa13cc270074f172f30d6eda8a8ce867d
└─ prisma@2.26.0
✨  Done in 4.42s.

インストール後はprismaの必要モジュールをインストールするため、下記コマンドを実行する。

~/develop/study/prisma $ yarn prisma init
yarn run v1.22.5
warning ../../../package.json: No license field
$ /Users/kawamurakouji/develop/study/prisma/node_modules/.bin/prisma init

✔ Your Prisma schema was created at prisma/schema.prisma
  You can now open it in your favorite editor.

Next steps:
1. Set the DATABASE_URL in the .env file to point to your existing database. If your database has no tables yet, read https://pris.ly/d/getting-started
2. Set the provider of the datasource block in schema.prisma to match your database: postgresql, mysql, sqlserver or sqlite.
3. Run yarn prisma db pull to turn your database schema into a Prisma data model.
4. Run yarn prisma generate to install Prisma Client. You can then start querying your database.

More information in our documentation:
https://pris.ly/d/getting-started

✨  Done in 1.65s.

prismaのディレクトリが作成され、schema.prismaが作成されていれば、準備OKです。

~/develop/study/prisma $ tree -I node_modules 
.
├── package.json
├── prisma
│   └── schema.prisma
└── yarn.lock

3. Prismaのマイグレーション

3-1. schema.prismaの修正

TBL作成やDBへのアクセス情報はschema.prismaで管理されています。そのため、schema.prismaを修正していきましょう。

prismaディレクトリのschema.prismaを開いてください。デフォルトでは以下のようなファイルになっています。
スクリーンショット 2021-07-05 16.44.09.png

それを以下のように変更してください。これでUserTBLを作成できます。

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
}

3-2. .envの設定

schema.prismaではDBアカウントやPWをurlで保存しています。 urlは環境変数として登録する必要があるため、登録用の.envを編集しましょう。 .envは既にできており、配置場所は下記の通りです。
~/develop/study/prisma $ ls -la
total 24
drwxr-xr-x  7 kawamurakouji  staff   224  7  5 16:36 .
drwxr-xr-x  7 kawamurakouji  staff   224  7  5 16:15 ..
-rw-r--r--  1 kawamurakouji  staff   477  7  5 16:36 .env
drwxr-xr-x  7 kawamurakouji  staff   224  7  5 16:34 node_modules
-rw-r--r--  1 kawamurakouji  staff   169  7  5 16:34 package.json
drwxr-xr-x  3 kawamurakouji  staff    96  7  5 16:36 prisma
-rw-r--r--  1 kawamurakouji  staff  1637  7  5 16:34 yarn.lock

デフォルトでは下記のようになっています。
スクリーンショット 2021-07-05 17.00.29.png

.envを下記のように変更してください。({ユーザ名}、{パスワード}、{スキーマ名}は環境に応じて変更してください。)

~/develop/study/prisma $ cat .env
# Environment variables declared in this file are automatically made available to Prisma.
# See the documentation for more detail: https://pris.ly/d/prisma-schema#using-environment-variables

# Prisma supports the native connection string format for PostgreSQL, MySQL and SQLite.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings

DATABASE_URL="mysql://{ユーザ名}:{パスワード}@localhost:3306/{スキーマ名}"

3-3. TBL作成

ではTBLを作成していきましょう。事前にMySQLをインストールし、スキーマまで作成ください。
下記コマンドでTBLを作成しましょう。
スクリーンショット 2021-07-05 17.11.18.png

作成されたので、TBLが作られた事を確認します。
スクリーンショット 2021-07-05 17.15.18.png
スクリーンショット 2021-07-05 17.16.29.png

2
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
2
1