Last active
November 15, 2022 16:56
-
-
Save junkor-1011/256e05ba261c91a7872b8f00d32b8a4a to your computer and use it in GitHub Desktop.
LT資料: Prisma(ORM for TypeScript)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>about Prisma</title> | |
<meta charset="utf-8"> | |
<style> | |
@page { | |
size: 1210px 681px; | |
margin: 0; | |
} | |
@media print { | |
.remark-slide-scaler { | |
width: 100% !important; | |
height: 100% !important; | |
transform: scale(1) !important; | |
top: 0 !important; | |
left: 0 !important; | |
} | |
} | |
body { font-family: sans-serif; } | |
h1, h2, h3 { | |
font-weight: normal; | |
} | |
.remark-code, .remark-inline-code { font-family: 'Ubuntu Mono'; } | |
</style> | |
</head> | |
<body> | |
<textarea id="source"> | |
class: center, middle | |
# Title | |
--- | |
# Agenda | |
1. Introduction | |
2. Deep-dive | |
3. ... | |
--- | |
# Introduction | |
</textarea> | |
<script src="https://remarkjs.com/downloads/remark-latest.min.js"> | |
</script> | |
<script> | |
var slideshow = remark.create({ | |
sourceUrl: 'slides.md', | |
}); | |
</script> | |
</body> | |
</html> |
class: center, middle
Prisma
: TypeScriptでRDB(PostgreSQLやMySQLなど)を操作するのに汎用的に使えるORM(Object-Relational Mapping)ツール- (GitHubリポジトリ)
- DBの種類によるコードの差異を最小限にして使える
- (DynamoDBやMongoDBにも適用可能)
- (Pythonで言うとSQLAlchemyなどがあったり、他の言語でも類似ツールは存在する)
- ORM機能を使うことにより、
SQL操作をオブジェクト指向言語な感じで書くことができる
- ただし、これには**(相当)賛否両論ある**ようなので注意
- ORM機能を使わずに、素のSQLで処理を記述する感じでも使える(←DBの種類を変えてもコードの変更が少なくなるメリット)
- Getting started
- QuickStart
- ローカル上で
SQLite
を操作する簡単な例
- ローカル上で
- QuickStart
ざっくりとした使い方の流れ例:
- devDependenciesで
prisma
をインストールする - dependenciesで
@prisma/client
をインストールする prisma
用の設定ファイル: 例えばprisma/schema.prisma
を用意し、記述するprisma init
などで自動生成出来る- 接続するDBの情報や使用するテーブルのモデルの設定を出来る
- (必要に応じて)PrismaからDBマイグレーションを行うことが出来る
schema.prisma
で定義したモデルを元にテーブルを自動生成- モデルに変更があれば差分を実テーブルに適用し、変更内容を履歴用テーブル+クエリログとして管理出来る
prisma generate
コマンドでクライアントにschema.prisma
の内容を反映させる
(公式)を元に一部改変
// Data source
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
// Generator
generator client {
provider = "prisma-client-js"
}
// Data model
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
// Data source
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
- 詳細はConnection URLsなどを参照
- 使用するDBの種類を選択(上記の例ではPostgreSQL)
- なお、サポートされているDBは公式ページに記載
- 環境変数を使うことにより、DBへの接続情報(URLや認証情報)を環境ごとに切り替えられる
// Generator
generator client {
provider = "prisma-client-js"
binaryTargets = ["native", "rhel-openssl-1.0.x"]
}
- 詳細はGeneratorsや、 Generating the clientを参照
- 実行環境に応じてbundleする、といった際に調整が必要となる
- 例として、AWS Lambdaに適用する際の参考:
// Data model
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId Int?
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
- 詳細はData Modelや、 Data Modelingを参照
- (厳密ではないが)1つのmodelが1つのテーブル仕様(各カラムのデータ型や制約条件)に大体対応する(←上記の例ではPostテーブル、Userテーブル)
簡単な例:
import { PrismaClient } from '@prisma/client'
// クライアント生成
const prisma = new PrismaClient()
// クエリ実行例
const users = await prisma.user.findMany() // 全件取得
const user = await prisma.user.findUnique({
where: { // id=1のユーザーを検索
id: 1,
}
})
クエリの詳細はCRUDなどを参照のこと
- Configuring Logging
- ORMで実際に実行されるSQL文やSQL実行時エラーなどをログ出力出来る
const prisma = new PrismaClient({
log: ['query', 'info', 'warn', 'error'],
})
- datasourceの上書き
- (自分では未検証だが)PrismaClientのコンストラクタパラメータに
datasource
があり、接続情報の上書きが出来るとのこと - DBのユーザー名/パスワードは環境変数ではなく後から(SecretsManagerなどから)取得する、といった使い方ができそう
- (自分では未検証だが)PrismaClientのコンストラクタパラメータに
const prismaClient = new PrismaClient({
datasources: {
postgresql: {
url: process.env.DATABASE_URL,
},
},
});
- 詳細はRaw database access参照
- プレースホルダー付き(SQLインジェクション対策有り)で直にSQL文を組み立てて使うことが出来る
- 非ORMツール的に標準的な使い方
// example
const email = '[email protected]'
const result = await prisma.$queryRaw`SELECT * FROM User WHERE email = ${email}`
// ↑のemailはちゃんとプレースホルダー処理がなされる
class: center, middle
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment