Prisma & PlanetScale

frookie·2023년 4월 13일
0

ExpressJS

목록 보기
2/4

전 편에서 만든 ToDoList의 데이터베이스를 생성해야 한다.
Prisma + PlanetScale의 조합으로 구성해보자
-> Prisma로 BE-DB와 상호작용 할 내용을 작성 후, 이 내용을 PlanetScale의 DB 플랫폼으로 저장

Prisma

  • 자바스크립트를 사용해서 데이터베이스와 상호작용 할 수 있는 ORM 프레임워크.
  • 데이터베이스에 특성, 쿼리문에 대한 지식이 부족해도 손 쉽게 데이터베이스를 사용할 수 있는 장점.
  • 쿼리문을 직접 작성하는 것에 비해 성능이 떨어진다는 단점.
  • ORM(Object Relation Mapping)
    객체와 데이터베이스의 관계를 매핑(연결)해주는 도구이다.
    Backend와 Database가 SQL문 대신 원활한 소통을 하게 해준다.

설치법

백엔드 파일 경로에 설치

> npm i -D prisma
> npx prisma init

확장프로그램 'prisma' 설치

스키마 작성

1. 기본 세팅

  • schema.prisma
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

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

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

=> provider를 "mysql"로 바꾸기
=> relationMode 프리즈마 추가

2. User와 Todo 데이터 작성

  • schema.prisma

//?는 필수는 아닌 값에
model User {
  id Int @id @default(autoincrement())
  account String @unique     //중복되면 안되는 것에 @unique
  name String?		//필수는 아닌 값에 ? (=Null)
  todos Todo[]3. 1:N 관계이므로 위에서는 Todo[] 배열로 정의해줘야 함
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

//User는 위의 user를 사용, 그리고 관계 정의해줘야함, 위에서도 정의해야함
model Todo {
  id Int @id @default(autoincrement())
  todo String
  isDone Boolean
  user User @relation(fields: [userId], references: [id])1. User는 모델 User를 사용
  //userId라는 필드의 값을 위 User의 id를 참조해 사용하겠다
  userId Int	▶2. userId를 숫자로 정의
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

@@index([userId])		//provider를 mysql로 바꾸면 써줘야함

=> @는 프리즈마에 세팅 돼있는 문법
=> 양쪽에서 관계 정의가 필수, User와 Todo는 1:N의 관계

PlanetScale

  • MySQL 기반의 데이터베이스 클라우드 서비스.
  • 데이터베이스 셋팅 없이 CLI 명령어로 쉽게 연결할 수 있는 특징이 있다.
  • Branch를 나누어 개발 / 운영 모드의 전환도 용이하다.

Windows 설치법

PlanetScale 홈페이지에서 Database를 만든 다음 Windows는 scoop을 통해서 PlanetScale CLI 를 설치해줘야 한다.

1. scoop 설치

  • powershell (version 5.1 or later)
> Set-ExecutionPolicy RemoteSigned -Scope CurrentUser # Optional: Needed to run a remote script the first time
> irm get.scoop.sh | iex

2. PlanetScale CLI 설치

  • powershell
> scoop bucket add pscale https://github.com/planetscale/scoop-bucket.git
> scoop install pscale mysql

버전 업그레이드
> scoop update pscale

3. DB 연결 및 접속

  • powershell
> pscale auth login		▶ 터미널과 PlanetScale을 연결
> pscale connect [DB이름]		▶생성된 DB에 접속.

접속 후 뜨는 local adress(기본: 127.0.0.1:3306) 복사 후 .env 파일에 적용

  • .env
DATABASE_URL="mysql://127.0.0.1:3306/[DB이름]"

4. 스키마 내용 PlanetScale에 반영

> npx prisma db push

schema.prisma의 내용을 planetScale의 DB로 푸쉬
5. Prisma Client 설치

> npm i @prisma/client

Prisma와 소통할 수 있도록 해준다.

6. Prisma Studio 실행

> npx prisma studio

Prisma Studio: DB Workbench (DB 상태를 확인하고 관리할 수 있는 Tool)

=> 위 과정이 모두 끝나면 총 3개의 서버가 연결돼 있어야 한다

  • npm run dev
  • npx pirsma studio
  • pscale connect [DB이름] (powershell)
profile
비전공자의 코딩, 블록체인 공부 일지

0개의 댓글