본문 바로가기
DevOps/Deployment

golang sqlboiler

by cusmaker 2023. 6. 2.
반응형

https://thedevelopercafe.com/articles/sql-in-go-with-sqlboiler-ac8efc4c5cb8

예제 레포 https://github.com/gurleensethi/go-sql-boiler-example

 

SQL in Go with SQLBoiler

SQLBoiler is package that introspects your database schema and generates a static ORM client. In this article I am going to give you a taste of SQLBoiler.

thedevelopercafe.com

Installing SQLBoiler CLI tool #

go install github.com/volatiletech/sqlboiler/v4@latest
go install github.com/volatiletech/sqlboiler/v4/drivers/sqlboiler-psql@latest

 

 

Project Setup 

Setting up database 

도커 이미지 가져와서 구동 및 접속후 스키마 생성 

docker pull postgres

docker run -d -p 5432:5432 --name pgsql -e POSTGRES_PASSWORD=1234 postgres

docker exec -it pgsql bash

 

$ psql -U postgres

# CREATE DATABASE mytestdb;

CREATE TABLE author(
  id serial primary key,
  email varchar not null,
  name varchar not null
);

CREATE TABLE article(
  id serial primary key,
  title varchar not null,
  body text,
  created_at timestamp default now(),
  author_id int not null,
  constraint fk_author_id foreign key(author_id) references author(id)
);

Setting up go project 

go get github.com/lib/pq
go get github.com/volatiletech/sqlboiler/v4
go get github.com/volatiletech/null/v8

기본코드 작성

package main

import (
	"database/sql"

	_ "github.com/lib/pq"
	"github.com/volatiletech/sqlboiler/v4/boil"
)

func main() {
	db := connectDB()

	boil.SetDB(db)
}

func connectDB() *sql.DB {
	db, err := sql.Open("postgres", "postgres://postgres:postgres@localhost:2345/postgres?sslmode=disable")
	if err != nil {
		log.Fatal(err)
	}
	return db
}
main.go

 

# Directory in which the generated static code is to be kept.
output = "db/models" 

# Each time new code is generated, completely wipe out the old one.
wipe = true

# The `go` package name used in the generated code.
pkgname = "dbmodels"

# Adds global variant of the generated functions, more on this later.
add-global-variants = true

# Generates code for enum types as well.
add-enum-types = true

# This is the postgres config, which should be self explanatory.
[psql]
dbname = "postgres"
host = "localhost"
port = 5432
user = "postgres"
pass = "1234"
sslmode = "disable"
sqlboiler.toml

 

'DevOps > Deployment' 카테고리의 다른 글

쉘스크립트 팁  (0) 2022.08.22
[Nginx + Tomcat] 무중단 배포 구현하기 2  (0) 2018.04.19
[Nginx + Tomcat] 무중단 배포 구현하기  (0) 2018.03.20