Prisma 4 사용해보기

00_8_3·2022년 7월 11일
1

Migration To Prisma

목록 보기
1/11

Prisma 4

오카방을 보면 프리즈마가 좋다고들 해서 사용 해보려 한다.

프리즈마가 소개하는 왜 프리즈마 사용 이유

Prisma's main goal is to make application developers more productive when working with databases. Considering the tradeoff between productivity and control again, this is how Prisma fits in:

사용방법

디펜던시 설치

$ npm i @prisma/client
$ npm i -D prisma

schema.prisma 작성


generator client {
  provider = "prisma-client-js"
  // binaryTargets  = ["windows"]
  // output   = "native" // 생략시 default로 node_modules/.prisma/client에 타입이 생성된다.
  // output = "../src/generated/client" // 특정 path 지정하여 타입 생성 가능. // PrismaClient 호출 위치도 수정해주어야 한다.
}

datasource db {
  provider = "mysql"
  url      = env("DATABASE_UR")  // root 폴더나 prisma 폴더 내에 `.env` DATABASE_UR을 적자.
}

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

  @@map("user")
  // posts Post[]
}

db push

$ npx prisma generate // 아래 명령어를 사용 시 자동으로  generate 된다고 한다.
$ npx prisma db push

prisma 스키마가 변경되면 generate를 수동으로 다시 실행해주어야 한다.

Note that the installation of this package invokes the prisma generate command which reads your Prisma schema and generates the Prisma Client code. The code will be located in node_modules/.prisma/client, which is exported by node_modules/@prisma/client/index.d.ts.
After you change your data model, you'll need to manually re-generate Prisma Client to ensure the code inside node_modules/.prisma/client get updated:

db pull

DB에 생성된 스키마를 통해 마이그레이션

$ npx prisma db pull

prisma.shcema에 자동으로 스키마 정의해줌.

prisma client 생성

export const prisma = new PrismaClient(
            //{log: ['query', 'info', 'warn', 'error']} // 로그 옵션
        )
  • 로그 옵션
    로그 옵션 사용 시
    아래와 같은 쿼리 로그를 확인 할 수 있다.

    DB에 들어가는 데이터들은 ?로 치환됨

Query: SELECT prisma.profiles.id, prisma.profiles.name, prisma.profiles.address, prisma.profiles.birthday, prisma.profiles.user_id FROM prisma.profiles WHERE prisma.profiles.user_id IN (?)

e.g 생성 및 조회

import { PrismaClient } from '@prisma/client'
...
const result = await prisma.user.create({
            data: {
                email: "test@gmail.com",
                name: "dohan"
            }
        })

        res.json({result});

...

const result = await prisma.user.findUnique({
            where: {id: 1},
        })

        console.log("result :", result);

중간 느낌

sequelize, typeorm을 모두 사용해본 유저로써
prisma는 더욱 직관 적이고 타입스크립트 유저에게 친화적이라 느껴진다.

  • db스키마로부터 직접적인 스키마 생성,
  • 타 orm으로부터의 마이그레이션,
  • db 스키마 변경에 따른 마이그레이션
    모두 지원됨

    타 orm 마이그레이션이 지원되기는 하지만 100퍼센트 정확하게 되는 것은 아니니
    생성된 스키마 파일을 검토하고 수정하길 권장합니다.

출처

https://www.prisma.io/docs/concepts/components/prisma-schema/generators

0개의 댓글