How to use Golang PostgreSQL? | 2023's Ultimate Guide | Hevo

PostgreSQL 설치 및 실행

brew install postgresql
postgres -V

psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory
	Is the server running locally and accepting connections on that socket?

brew services list
Name          Status User File
postgresql@14 none    
    
brew services start postgresql@14
==> Successfully started `postgresql@14` (label: homebrew.mxcl.postgresql@14)

brew services list               
Name          Status  User   File
postgresql@14 started hyenee ~/Library/LaunchAgents/[email protected]

데이터베이스 생성 및 확인

psql -d postgres
psql (14.9 (Homebrew))
Type "help" for help.

CREATE DATABASE mumo;

postgres=# \\l
                          List of databases
   Name    | Owner  | Encoding | Collate | Ctype | Access privileges 
-----------+--------+----------+---------+-------+-------------------
 mumo      | hyenee | UTF8     | C       | C     | 
 postgres  | hyenee | UTF8     | C       | C     | 
 template0 | hyenee | UTF8     | C       | C     | =c/hyenee        +
           |        |          |         |       | hyenee=CTc/hyenee
 template1 | hyenee | UTF8     | C       | C     | =c/hyenee        +
           |        |          |         |       | hyenee=CTc/hyenee

데이터베이스 계정 생성 및 권한 부여

CREATE USER postgre_local WITH PASSWORD '1234';
GRANT ALL PRIVILEGES ON DATABASE mumo TO postgre_local;

\\l
                              List of databases
    Name    | Owner  | Encoding | Collate | Ctype |    Access privileges     
------------+--------+----------+---------+-------+--------------------------
 mumo       | hyenee | UTF8     | C       | C     | =Tc/hyenee              +
            |        |          |         |       | hyenee=CTc/hyenee       +
            |        |          |         |       | postgre_local=CTc/hyenee
 postgres   | hyenee | UTF8     | C       | C     | 
 profilehub | hyenee | UTF8     | C       | C     | =Tc/hyenee              +
            |        |          |         |       | hyenee=CTc/hyenee       +
            |        |          |         |       | postgre_local=CTc/hyenee
 template0  | hyenee | UTF8     | C       | C     | =c/hyenee               +
            |        |          |         |       | hyenee=CTc/hyenee
 template1  | hyenee | UTF8     | C       | C     | =c/hyenee               +
            |        |          |         |       | hyenee=CTc/hyenee
(5 rows)

DBeaver 설치

Golang 의 ORM

Go 언어에도 다양한 ORM 프레임워크가 존재한다. GORM, XORM, GORM, Storm 그 중 Go 언어 생태계에서 가장 인기 있는 ORM 라이브러리인 GORM을 사용하기 했다.

Golang에 PostgreSQL 연동

go get -u gorm.io/gorm
go get -u gorm.io/driver/postgres