웹개발일지

[ 1-1 ] Postgres db 스키마 생성하기 본문

데이터베이스

[ 1-1 ] Postgres db 스키마 생성하기

hee_log 2023. 1. 6. 20:16
728x90

 이 글은 유데미 강좌를 듣고 학습한 내용입니다. 

Backend Master Class [Golang + Postgres + Kubernetes + gRPC]

 

Backend Master Class [Golang + Postgres + Kubernetes + gRPC]

Learn everything about backend web development: Golang, Postgres, Redis, Gin, gRPC, Docker, Kubernetes, AWS, CI/CD

www.udemy.com

 

 첫 강좌로 포스그레 문법을 사용한 db 작성 후 스키마를 생성하는 db다이어그램이라는 툴을 사용했다. 코드를 작성해주면 아래와 같은 db 스키마가 생성된다. 

https://dbdiagram.io/home

 

dbdiagram.io - Database Relationship Diagrams Design Tool

 

dbdiagram.io

 

생성한 db 다이어그램

 개발할 때 다이어그램 그리는 툴을 항상 찾아헤맸는데 이런 툴을 알게되어서 너무 기쁘다. pdf파일부터 각종 sql 파일로 내려받아 워크벤치로 바로 열어볼 수도 있다. 팀 프로젝트를 하면 팀원들끼리 자료를 공유하기 너무 용이할 것 같다. 

 

 코드

 

Table accounts as A {
  id bigserial [pk]
  owner varchar [not null]
  balance bigint [not null]
  currency varchar [not null]
  created_at timestampz [not null, default: `now()`]
  
  Indexes {
    owner 
  }
}

// record change to balance
Table entries {
  id bigserial [pk]
  account_id bigint [ref: > A.id]
  amount bigint [not null, note: 'can be negative or ']
  created_at timestamptz [not null, default: 'now()']
  Indexes {
    account_id 
  }
  
}

Table transfers {
  id bigserial [pk]
  from_accout_id bigint [ref: > A.id]
  to_account_id bigint [ref: > A.id]
  amount bigint [not null, note: 'must be positive']
  created_at timestamptz [default: `now()`]
  
  Indexes {
    from_account_id 
    to_account_id 
    (from_account_id, to_account_id)
  }
}

Enum Currency {
  USD 
  EUR
}

 

 개발 주제는 은행 계좌를 만드는 것이다. 만들어낸 데이터는 다음과 같다. 

1. accounts: 사용자의 계정이다. 사용자 id, 이름, 잔액, 통화화폐, 생성일을 설정했다. 

2. entries: 통장 거래 내역이다. account 와 관계를 맺기 위해 account_id 를 설정한다. 

3. transfer: 송금 내역이다. from_account 에서 to_account로 보낸 금액을 amount로 나타낸다. accounts와 one-to-many 관계이다. 사용자는 하나지만 거래는 다량일 수 있기 때문에 그렇게 표현한 것이다. 

 

사용시 유의점 

 데이터 스키마를 위와같이 작성하여  export한 후 워크벤치, 테이블플러스와 같은 툴에서 파일을 불러다가 사용해야하는데, 위 툴에서 스키마를 작성할 때 오타가 있으면 스키마 테이블이 뜨지도 않고 내가 작성한 그대로의 파일을 export할 수 없으므로 유의하자.