prisma QuickStart
QuickStart
リンク
インストール
$ yarn init -y
$ yarn add @prisma/cli typescript ts-node @types/node --dev
$ cat << EOF > tsconfig.json
{
"compilerOptions": {
"sourceMap": true,
"outDir": "dist",
"strict": true,
"lib": ["esnext"],
"esModuleInterop": true
}
}
EOF
// 確認
$ yarn run prisma
$ yarn run prisma init
ファイルの用意
- schema.prisma
- schema.sql
- .env
// prisma/schema.prisma
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
// prisma/.env
DATABASE_URL="mysql://root@localhost:3306/my_prisma"
(Option) テーブルの用意
// schema.sql
CREATE TABLE User (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
name VARCHAR(255),
email VARCHAR(255) UNIQUE NOT NULL
);
CREATE TABLE Post (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
title VARCHAR(255) NOT NULL,
createdAt TIMESTAMP NOT NULL DEFAULT now(),
content TEXT,
published BOOLEAN NOT NULL DEFAULT false,
authorId INTEGER NOT NULL,
FOREIGN KEY (authorId) REFERENCES User(id)
);
CREATE TABLE Profile (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
bio TEXT,
userId INTEGER UNIQUE NOT NULL,
FOREIGN KEY (userId) REFERENCES User(id)
);
mysql -uroot my_prisma < schema.sql
DBからモデルの生成
$ yarn run prisma introspect
-> prisma/schema.prisma がDB情報をもとに更新される
// prisma introspect で更新された prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
model Post {
authorId Int
content String?
createdAt DateTime @default(now())
id Int @default(autoincrement()) @id
published Boolean @default(false)
title String
User User @relation(fields: [authorId], references: [id])
@@index([authorId], name: "authorId")
}
model Profile {
bio String?
id Int @default(autoincrement()) @id
userId Int @unique
User User @relation(fields: [userId], references: [id])
}
model User {
email String @unique
id Int @default(autoincrement()) @id
name String?
Post Post[]
Profile Profile?
}
クライアント
セットアップ
$ yarn add @prisma/client
-> node_modules/@prisma/client が導入される
$ yarn run prisma generate
-> node_modules/@prisma/client を prisma/schema.prisma に沿って更新する
index.ts の例
// index.ts
import { PrismaClient } from "@prisma/client"
const prisma = new PrismaClient()
async function main() {
const allUsers = await prisma.user.findMany()
console.log(allUsers)
}
main()
.catch(e => {
throw e
})
.finally(async () => {
await prisma.disconnect()
})
$ yarn run ts-node index.ts
> []
async function main() {
await prisma.user.create({
data: {
name: "Alice",
email: "alice@prisma.io",
posts: {
create: { title: "Hello World" },
},
profile: {
create: { bio: "I like turtles" }
}
}
})
const allUsers = await prisma.user.findMany({
include: {
posts: true,
profile: true
},
})
console.dir(allUsers, { depth: null })
}
$ yarn run ts-node index.ts
> [
{
email: 'alice@prisma.io',
id: 1,
name: 'Alice',
posts: [
{
authorId: 1,
content: null,
createdAt: 2020-05-07T13:56:47.000Z,
id: 1,
published: false,
title: 'Hello World'
}
],
profile: { bio: 'I like turtles', id: 1, userId: 1 }
}
]
async function main() {
const post = await prisma.post.update({
where: { id: 1 },
data: { published: true },
})
console.log(post)
}
$ yarn run ts-node index.ts
> {
authorId: 1,
content: null,
createdAt: 2020-05-07T13:56:47.000Z,
id: 1,
published: true,
title: 'Hello World'
}
その他
モデルの更新方法
- DB・テーブルを更新
- スキーマファイルの更新
$ yarn run prisma introspect
- clientを更新
$ yarn run prisma generate
(Option) schema から databaseの更新 (prisma migrate)
$ yarn run prisma migrate save --name init --experimental
-> prisma/migrations が作られる
$ yarn run prisma migrate up --experimental
-> migrationが実行される