티스토리 뷰

Database

Prisma란 ? JS와 TS로 DB 데이터 관리하기(PlanetScale)

YG - 96년생 , 강아지 있음, 개발자 희망 2022. 5. 18. 15:53

# Prisma
1. Node.js and Typescript ORM(Object Relational Mapping)
=> JS or TS 와 데이터베이스 사이에 다리를 놓아줌 (기본적으로 번역기의 역할을 한다고 생각하면 됨)

2. Prisma를 사용하기 위해서는 먼저 Prisma에게 DB가 어떻게 생겼는지, 데이터의 모양을 설명해줘야 함 => schema.prisma

3. Prisma가 이런 타입에 관한 정보를 알고 있으면 client를 생성해줄 수 있음. client를 이용하면 TS로 DB와 직접 상호작용 가능, 자동완성 제공.

4. Prisma Studio : Visual Database Browser, DB를 위한 관리자 패널같은 것.

 

 

https://www.prisma.io/

 

Prisma - Next-generation Node.js and TypeScript ORM for Databases

Prisma is a Node.js and TypeScript ORM that can be used to build GraphQL servers, REST APIs, microservices & more.

www.prisma.io

 

 

js, ts 로 다양한 db를 이용가능하다.

 

 

설치법

 

npm install prisma -D

 

 

vs코드 확장 프로그램 깔기

 

 

 

npx prisma init

 

이 명령은 schema.prisma라는 파일과 프로젝트 루트에 .env 파일을 포함하는 prisma라는 새 디렉토리를 생성했습니다. schema.prisma는 데이터베이스 연결과 Prisma Client 생성기가 있는 Prisma 스키마를 포함합니다. .env는 환경 변수를 정의하기 위한 dotenv 파일입니다. (데이터베이스 연결에 사용됨)

 

 

 

https://www.prisma.io/docs/getting-started/setup-prisma/start-from-scratch/relational-databases-typescript-mysql

 

Start from scratch with relational databases (15 min)

Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma to your relational database and generating a Prisma Client for database access.

www.prisma.io

 

 

npx init을 하였을 때 나오는 문구

 

문구대로 사용할 db로 바꾸어 주면 됨

 

 

사용법

 

model User{
  id Int @id @default(autoincrement())
  phone Int? @unique
  email String? @unique
  name String
  avatar String?
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

 

 

다음과 같이 사용할 API에 필요한 정보를 어떤 타입인지 , 필수로 있어야하는지 등 여러 정보를 담아서 이용할 수 있다.

 

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

 

Prisma schema (Reference)

The Prisma schema is the main configuration file when using Prisma. It is typically called schema.prisma and contains your database connection and data model.

www.prisma.io

 

 

 

또한 prisma와 함께 이용할 때 더 파워가 큰 프로그램이 있는데 바로 PlanetScale 이다

 

PlanetScale
MySQL과 호환되는 Serverless 데이터베이스 플랫폼
https://planetscale.com/

Vitess
Vitess는 MySQL을 스케일링하기 위한 데이터베이스 클러스터링 시스템
인터넷에서 가장 큰 사이트를 호스팅하는 강력한 오픈 소스 기술입니다.
https://vitess.io/

Vitess를 사용하는 이유
1. 수평 스케일
2. 고가용성 (Vitess의 기본 복제본 구성은 예기치 않은 이벤트가 발생할 때 기본에서 복제본으로 원활한 장애 조치를 허용합니다.)
3. MySQL 호환
4. 쿠버네티스 네이티브
5. 구체화된 뷰
6. 온라인 스키마 마이그레이션

 

Vitess

 

vitess.io

 

PlanetScale

The database for developers

planetscale.com

 

 

 

 

그래서 PlanetScale을 이용하려면 회원가입이 필요하고 회원가입이 끝났다면 어드민 패널이 나오게 되는데 사이트 말고도 Cli를 굉장히 잘 만들어 놓았기 때문에 Cli 설치를 권장한다고 합니다

 

홈페이지 어드민 패널

 

 

각 OS에 따라 설치방법이 다릅니다. 저의 경우는 WSL2 를 하고있고 Ubuntu를 통해 Linux 환경에서 개발을 하고 있습니다.

 

 

https://docs.planetscale.com/concepts/planetscale-environment-setup

 

PlanetScale environment set up - Documentation - PlanetScale

Use the PlanetScale CLI to create development branches, make non-blocking schema changes, and open deploy requests directly from your terminal.

docs.planetscale.com

 

 

 

따라서 저는 여기에 있는 파일중 

 

https://github.com/planetscale/cli/releases/tag/v0.94.0

 

Release v0.94.0 · planetscale/cli

Changelog 941c025 32bit ARM builds for Linux and Windows da1addd Add ARMv7 Linux builds a0c297c auth: don't recommend service tokens cec0321 build(deps): bump github.com/spf13/viper from 1.10.1 to...

github.com

 

amd 입니다 비슷한 여러개가 있어서 주의하셔야 합니다.

를 다운받았고 wsl2 환경으로 파일을 옮겨서

 

 

 

 

 

sudo dpkg -i 버전

압축해제 성공한 모습
명령어 pscale을 했을 때 이렇게 나온다면 설치 성공입니다.

 

 

이용하려면 이제 로그인을 해야합니다

 

pscale auth login

 

 

위에서 나온 문자랑 열린 페이지에서의 문자가 같은지 체크해주시면 됩니다.

 

 

 

이제 데이터베이스를 만들것인데

 

pscale region list

 

이 명령어를 해준다면 planetScale에서 이용가능한 지역들의 리스트가 나오게 됩니다. 현재 한국에서 가까운 건  싱가폴이나 도쿄이므로 전 도쿄를 선택하겠습니다.

 

 

지역을 정했다면 만드는 방법은

 

pscale database create <-만들 데이터베이스 이름-> --region <-지역->

 

이렇게 적어주시면 됩니다.

 

홈페이지에서도 생성된 것을 확인할 수 있습니다.

 

 

 

이제 생성된 데이터베이스를 Prisma와 연결해야하는데 여기서 planetScale의 장점이 나옵니다. 

 

원래 컴퓨터와 서버를 사용할 때 .env 파일에 여러 암호들을 저장해두고 보안을 유지하는데 planetScale은 자체적으로 tunnel을 열어 보안을 유지하고 cli에서 명령어를 사용한다면 언제든 컴퓨터와 서버를 연결 할 수 있습니다.

 

 

pscale connect <-데이터베이스 이름->

 

여기서 받은 127.0.0.1... 의 주소를 복사해줍니다

-* 그리고 연결되었으니 저 터미널창은 닫으시면 안되고 축소를 하고 다른 터미널에서 개발을 진행해야 합니다. *- 

 

prisma와 연결된 .env 파일을 열고 주소를 수정해주시면 됩니다.

 

DATABASE_URL="mysql://<-connect를 통해 받은 주소->/<-데이터베이스 이름->"

 

 

 

이제 사용하기에 앞서 prisma 설정을 더 해주어야 하는데요

 

planetscale이 vitress 방식이기 때문에  mysql과 달리 이용하려는 정보가 진짜 존재하는지 확인하지 않는다고 하는데 이를 prisma가 대신 확인해줄 수 있는 옵션이 있습니다.

 

먼저 client 쪽에

 

  previewFeatures =["referentialIntegrity"]

를 추가하고

 

db 쪽에

 

  referentialIntegrity = "prisma"

를 추가한다면 만약 존재하지 않는 유저의 정보를 데이터베이스에서 이용하려고 한다면 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"
  previewFeatures =["referentialIntegrity"]
}

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

model User{
  id Int @id @default(autoincrement())
  phone Int? @unique
  email String? @unique
  name String
  avatar String?
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

https://www.prisma.io/docs/concepts/components/prisma-schema/relations/referential-integrity

 

Referential integrity (참조 무결성)

(어떤 다른 모델을 참조하는 경우 해당 모델이 반드시 존재해야 함)
참조 무결성은 모든 참조가 유효함을 나타내는 데이터 세트의 속성입니다. 참조 무결성을 위해서는 한 레코드가 다른 레코드를 참조하는 경우 반드시 해당 참조하는 레코드가 존재해야 한다. 예를 들어 Post 모델이 user필드를 정의하는 경우 User(모델)도 반드시 존재해야 합니다. 참조 무결성은 참조를 손상시키는 변경을 방지하는 제약 조건과 레코드를 업데이트하거나 삭제할 때 실행되는 참조 작업을 정의함으로써 적용됩니다.

 

 

 

Referential integrity

Referential integrity lets you define how the consistency of relations is handled.

www.prisma.io

 

 

이제 prisma 설정이 끝났다면 스키마를 db에 푸쉬할수 있습니다

 

npx prisma db push

 

 

홈페이지에서도 볼 수 있는 모습

 

 

또한 이러한 데이터베이스를 prisma studio를 통해 관리할 수도 있습니다

 

Prisma Studio
npx prisma studio

npx prisma studio

 

 

그리고 prisma client를 설치해야 잘 사용할 수 있습니다.

 

 

Prisma Client

TypeScript 및 Node.js용 직관적인 데이터베이스 클라이언트
Prisma Client는 생각하는 방식으로 구성하고 앱에 맞춤화된 유형으로 Prisma 스키마에서 자동 생성되는 쿼리 빌더입니다.

 

npm install @prisma/client



https://www.prisma.io/docs/concepts/components/prisma-client

 

Prisma Client (Reference)

Prisma Client is an auto-generated, type-safe query builder generated from the tables in your database.

www.prisma.io

 

 

prisma client를 사용하면 자동으로 스키마에서 타입스크립트가 사용할 수 있게끔 자동완성도 해주고 타입도 검사해줍니다.

 

user 자동완성이 나오는 모습

 

 

import { PrismaClient } from "@prisma/client";

const client = new PrismaClient();

 

 

이제 이렇게 설정한 prisma를 데이터 생성하기 위해서는 next.js에서 api 폴더를 만들고 제공해준 백앤드를 이용하면 됩니다.

 

 

 

 

파일이름.ts

import { PrismaClient } from "@prisma/client";

export default new PrismaClient();

 

 

 

 

 

pages/api/파일이름.tsx

import { NextApiRequest, NextApiResponse } from "next";
import client from "../../libs/client";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  await client.user.create({
    data: {
      email: "hi",
      name: "hi",
    },
  });
  res.json({
    ok: true,
  });
}

 

API Routes

API route는 Next.js로 API를 빌드하기 위한 솔루션을 제공합니다. pages/api 폴더 내의 모든 파일은 /api/*에 매핑되며 API endpoint로 처리됩니다. server-side 전용 번들이며 client-side 번들 크기를 늘리지 않습니다.
req: http.IncomingMessage의 인스턴스와 pre-built된 일부 미들웨어
res: http.ServerResponse의 인스턴스와 일부 helper함수

예를 들어 다음 API 경로 pages/api/user.js는 상태 코드가 200인 json 응답을 반환합니다.

export default function handler(req, res) {
res.status(200).json({ name: 'John Doe' })
}


https://nextjs.org/docs/api-routes/introduction

 

API Routes: Introduction | Next.js

Next.js supports API Routes, which allow you to build your API without leaving your Next.js app. Learn how it works here.

nextjs.org

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함