ORMを試してみました
こんにちは。レスキューナウでシステムエンジニアをしている室伏です。
弊社では、近年バックエンドの開発で、Go言語が採用されて、
今回はGoとDB(MySql)の連携のためのORMについて、試してみました。
ORMとは?
オブジェクト関係マッピング(英: Object-relational mapping、O/RM、ORM)とは、
データベースとオブジェクト指向プログラミング言語の間の非互換なデータを変換するプログラミング技法である。
オブジェクト関連マッピングとも呼ぶ。実際には、オブジェクト指向言語から使える「仮想」オブジェクトデータベースを構築する手法である。
オブジェクト関係マッピングを行うソフトウェアパッケージは商用のものもフリーなものもあるが、場合によっては独自に開発することもある。
「オブジェクト関係マッピング」『フリー百科事典 ウィキペディア
日本語版』。2021年11月12日 (金) 07:34 UTC、
URL:オブジェクト関係マッピング - Wikipedia
簡単にいうと、SQLを直接書くことなく、オブジェクトのメソッドでDB操作ができる、という感じです。
Goで使用可能なORMはいくつかあるのですが、今回はGORM、XORM、SQL Boilerについて簡単なサンプルを実装してみました。(APIが呼ばれ、Responseを返すサンプルとなります)
※成果物から抜粋したコードなので直接は使用できません。
環境情報
Go 1.17
Mysql 5.6
ORM
gorm gorm.io/gorm v1.23.8
xorm xorm.io/xorm v1.3.1
sqlBoiler github.com/volatiletech/sqlboiler/v4 v4.11.0
テーブル情報
CREATE TABLE `country` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(1024) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(1024) DEFAULT NULL,
`age` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8
GORM
インストール
go get -u gorm.io/driver/mysql
go get -u gorm.io/gorm
CRUD実装サンプル
type Gorm struct {
Gorm *gorm.DB
}
type Country struct {
Id string `sql:"size:1024" json:"id"`
Name string `sql:"size:1024" json:"name"`
}
type User struct {
Id string
Name string
Age string
}
// 初期化
func (g *Gorm) InitGorm() {
user := "dbuser"
pw := "dbpassward"
db_name := "testdb"
var path string = fmt.Sprintf("%s:%s@tcp(xx.xx.xx.xx:3306)/%s?charset=utf8&parseTime=true", user, pw, db_name)
diact := mysql.Open(path)
var err error
if g.Db, err = gorm.Open(diact); err != nil {
log.Fatalf("Got error when connect database, the error is '%v'", err)
}
fmt.Println("db connected!!")
}
// 取得(countryテーブルから1件取得)
func (g *Gorm) GetCountry(w rest.ResponseWriter, r *rest.Request) {
id := r.PathParam("id")
country := Country{}
if g.Gorm.Table("country").Find(&country, id).Error != nil {
rest.NotFound(w, r)
return
}
w.WriteJson(&country)
}
// 取得(countryテーブルから全件取得)
func (g *Gorm) GetAllCountries(w rest.ResponseWriter, r *rest.Request) {
country := []Country{}
g.Gorm.Table("country").Find(&country)
w.WriteJson(country)
}
// 登録
func (g *Gorm) PostCountry(w rest.ResponseWriter, r *rest.Request) {
country := Country{}
err := r.DecodeJsonPayload(&country)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
}
err = g.Gorm.Table("country").Save(&country).Error
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteJson(&country)
}
// 更新
func (g *Gorm) PutCountry(w rest.ResponseWriter, r *rest.Request) {
id := r.PathParam("id")
country := Country{}
if g.Db.Table("country").First(&country, id).Error != nil {
rest.NotFound(w, r)
return
}
updated := domain.Country{}
if err := r.DecodeJsonPayload(&updated); err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
country.Name = updated.Name
if err := g.Gorm.Table("country").Save(&country).Error; err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteJson(&country)
}
// 削除
func (g *Gorm) DeleteCountry(w rest.ResponseWriter, r *rest.Request) {
id := r.PathParam("id")
country := Country{}
if g.Db.Table("country").First(&country, id).Error != nil {
rest.NotFound(w, r)
return
}
if err := g.Gorm.Table("country").Delete(&country).Error; err != nil {
rest.Error(w, err.Error(), http.StatusInsufficientStorage)
return
}
w.WriteHeader(http.StatusOK)
}
// 生SQLの実施
func (g *Gorm) GetCountrySQL(w rest.ResponseWriter, r *rest.Request) {
result := []User{}
sql := "SELECT Id, Name, Age FROM User"
rows, err := g.Db.Raw(sql).Rows()
defer rows.Close()
for rows.Next() {
//result = append(result, i.DB.ScanRows(rows, &User{}))
s := User{}
g.Db.ScanRows(rows, &s)
result = append(result, s)
}
if err != nil {
log.Fatal(err)
}
w.WriteJson(result)
}
XORM
インストール
go get xorm.io/xorm
CRUD実装サンプル
type Xorm struct {
engine *xorm.Engine
}
type Country struct {
Name string `sql:"size:1024" json:"name"`
}
type User struct {
Id string
Name string
Age string
}
// 初期化
func (x *Xorm) InitDBXorm() {
var err error
// MySQLとの接続。
x.engine, _ = xorm.NewEngine("mysql", "dbuser:dbpassword@tcp(xx.xx.xx.xx:3306)/testdb?charset=utf8mb4&parseTime=true")
if err != nil {
log.Fatalf("Got error when connect database, the error is '%v'", err)
}
x.engine.ShowSQL(true)
}
// 1件取得
func (x *Xorm) GetAllCountries(w rest.ResponseWriter, r *rest.Request) {
countries := []Country{}
err := x.engine.Find(&countries)
if err != nil {
log.Fatal(err)
}
w.WriteJson(countries)
}
// 全件取得
func (x *Xorm) GetCountry(w rest.ResponseWriter, r *rest.Request) {
id := r.PathParam("id")
country := Country{}
result, err := x.engine.Where("id = ?", id).Get(&country)
if err != nil {
log.Fatal(err)
}
if !result {
log.Fatal("Not Found")
}
w.WriteJson(&country)
}
// 登録
func (x *Xorm) PostCountry(w rest.ResponseWriter, r *rest.Request) {
country := Country{}
err := r.DecodeJsonPayload(&country)
_, err = x.engine.Insert(country)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
}
w.WriteJson(&country)
}
// 更新
func (x *Xorm) PutCountry(w rest.ResponseWriter, r *rest.Request) {
id := r.PathParam("id")
updated := Country{}
if err := r.DecodeJsonPayload(&updated); err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
result, err := x.engine.Where("id =?", id).Update(&updated)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
}
w.WriteJson(result)
}
// 削除
func (x *Xorm) DeleteCountry(w rest.ResponseWriter, r *rest.Request) {
id := r.PathParam("id")
_, err := x.engine.ID(id).Delete(&Country{})
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
}
w.WriteHeader(http.StatusOK)
}
// 生SQLの実施
func (x *Xorm) GetCountrySQL(w rest.ResponseWriter, r *rest.Request) {
user := []User{}
sql := "SELECT Id, Name, Age FROM User"
err := x.engine.SQL(sql).Find(&user)
if err != nil {
log.Fatal(err)
}
w.WriteJson(summary)
}
SQLBoiler
インストール
# slqboilerのインストール
go install github.com/volatiletech/sqlboiler/v4@latest
# driverのインストール(今回はMySQL)
go install github.com/volatiletech/sqlboiler/v4/drivers/sqlboiler-mysql@latest
go get github.com/volatiletech/null/v8
DBから構造体を抽出
# sqlboiler.toml(下記のコマンドを実行する場所に、tomlファイルを用意)
[mysql]
dbname="testdb"
host="xx.xx.xx.xx"
port=3306
user="dbuser"
pass="dbpassword"
sslmode="false"
# whitelist=["NOTICE","USER_MST","country"]
# コマンド
sqlboiler mysql
CRUD実装サンプル
type User struct {
Id string
Name string
Age string
}
type SqlBoiler struct {
Handler *sql.DB
}
// 1件取得
func (s *SqlBoiler) GetCountry(w rest.ResponseWriter, r *rest.Request) {
ctx := context.Background()
id := r.PathParam("id")
countries, err := models.Countries(qm.Where("id=?", id)).All(ctx, s.Handler)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
}
w.WriteJson(&countries)
}
// 全件取得
func (s *SqlBoiler) GetAllCountries(w rest.ResponseWriter, r *rest.Request) {
ctx := context.Background()
countries, err := models.Countries().All(ctx, s.Handler)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
}
w.WriteJson(&countries)
}
// 登録
func (s *SqlBoiler) PostCountry(w rest.ResponseWriter, r *rest.Request) {
ctx := context.Background()
country := models.Country{}
err := r.DecodeJsonPayload(&country)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
}
err = country.Insert(ctx, s.Handler, boil.Infer())
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteJson(&country)
}
// 更新
func (s *SqlBoiler) PutCountry(w rest.ResponseWriter, r *rest.Request) {
ctx := context.Background()
country := models.Country{}
err := r.DecodeJsonPayload(&country)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
}
_, err = country.Update(ctx, s.Handler, boil.Infer())
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteJson(&country)
}
// 削除
func (s *SqlBoiler) DeleteCountry(w rest.ResponseWriter, r *rest.Request) {
id := r.PathParam("id")
ctx := context.Background()
pid, _ := strconv.ParseInt(id, 10, 64)
country := models.Country{ID: pid}
if _, err := country.Delete(ctx, s.Handler); err != nil {
rest.Error(w, err.Error(), http.StatusInsufficientStorage)
return
}
w.WriteHeader(http.StatusOK)
}
// 生SQLの実施
func (s *SqlBoiler) GetCounttryCond(w rest.ResponseWriter, r *rest.Request) {
var u []*User
ctx := context.Background()
sql := "SELECT Id, Name, Age FROM User
err := queries.Raw(sql).Bind(ctx, s.Handler, &u)
if err != nil {
rest.Error(w, err.Error(), http.StatusInsufficientStorage)
return
}
w.WriteJson(&su)
}
sqlBoilerでDBから生成した構造体
// Code generated by SQLBoiler 4.11.0 (https://github.com/volatiletech/sqlboiler). DO NOT EDIT.
// This file is meant to be re-generated in place and/or deleted at any time.
package models
import (
"context"
"database/sql"
"fmt"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/friendsofgo/errors"
"github.com/volatiletech/null/v8"
"github.com/volatiletech/sqlboiler/v4/boil"
"github.com/volatiletech/sqlboiler/v4/queries"
"github.com/volatiletech/sqlboiler/v4/queries/qm"
"github.com/volatiletech/sqlboiler/v4/queries/qmhelper"
"github.com/volatiletech/strmangle"
)
// Country is an object representing the database table.
type Country struct {
ID int64 `boil:"id" json:"id" toml:"id" yaml:"id"`
Name null.String `boil:"name" json:"name,omitempty" toml:"name" yaml:"name,omitempty"`
CreatedAt null.Time `boil:"created_at" json:"created_at,omitempty" toml:"created_at" yaml:"created_at,omitempty"`
R *countryR `boil:"-" json:"-" toml:"-" yaml:"-"`
L countryL `boil:"-" json:"-" toml:"-" yaml:"-"`
}
var CountryColumns = struct {
ID string
Name string
CreatedAt string
}{
ID: "id",
Name: "name",
CreatedAt: "created_at",
}
var CountryTableColumns = struct {
ID string
Name string
CreatedAt string
}{
ID: "country.id",
Name: "country.name",
CreatedAt: "country.created_at",
}
// Generated where
type whereHelperint64 struct{ field string }
func (w whereHelperint64) EQ(x int64) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.EQ, x) }
func (w whereHelperint64) NEQ(x int64) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.NEQ, x) }
func (w whereHelperint64) LT(x int64) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LT, x) }
func (w whereHelperint64) LTE(x int64) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.LTE, x) }
func (w whereHelperint64) GT(x int64) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GT, x) }
func (w whereHelperint64) GTE(x int64) qm.QueryMod { return qmhelper.Where(w.field, qmhelper.GTE, x) }
func (w whereHelperint64) IN(slice []int64) qm.QueryMod {
values := make([]interface{}, 0, len(slice))
for _, value := range slice {
values = append(values, value)
}
return qm.WhereIn(fmt.Sprintf("%s IN ?", w.field), values...)
}
func (w whereHelperint64) NIN(slice []int64) qm.QueryMod {
values := make([]interface{}, 0, len(slice))
for _, value := range slice {
values = append(values, value)
}
return qm.WhereNotIn(fmt.Sprintf("%s NOT IN ?", w.field), values...)
}
var CountryWhere = struct {
ID whereHelperint64
Name whereHelpernull_String
CreatedAt whereHelpernull_Time
}{
ID: whereHelperint64{field: "`country`.`id`"},
Name: whereHelpernull_String{field: "`country`.`name`"},
CreatedAt: whereHelpernull_Time{field: "`country`.`created_at`"},
}
// CountryRels is where relationship names are stored.
var CountryRels = struct {
}{}
// countryR is where relationships are stored.
type countryR struct {
}
// NewStruct creates a new relationship struct
func (*countryR) NewStruct() *countryR {
return &countryR{}
}
// countryL is where Load methods for each relationship are stored.
type countryL struct{}
var (
countryAllColumns = []string{"id", "name", "created_at"}
countryColumnsWithoutDefault = []string{"name", "created_at"}
countryColumnsWithDefault = []string{"id"}
countryPrimaryKeyColumns = []string{"id"}
countryGeneratedColumns = []string{}
)
type (
// CountrySlice is an alias for a slice of pointers to Country.
// This should almost always be used instead of []Country.
CountrySlice []*Country
// CountryHook is the signature for custom Country hook methods
CountryHook func(context.Context, boil.ContextExecutor, *Country) error
countryQuery struct {
*queries.Query
}
)
// Cache for insert, update and upsert
var (
countryType = reflect.TypeOf(&Country{})
countryMapping = queries.MakeStructMapping(countryType)
countryPrimaryKeyMapping, _ = queries.BindMapping(countryType, countryMapping, countryPrimaryKeyColumns)
countryInsertCacheMut sync.RWMutex
countryInsertCache = make(map[string]insertCache)
countryUpdateCacheMut sync.RWMutex
countryUpdateCache = make(map[string]updateCache)
countryUpsertCacheMut sync.RWMutex
countryUpsertCache = make(map[string]insertCache)
)
var (
// Force time package dependency for automated UpdatedAt/CreatedAt.
_ = time.Second
// Force qmhelper dependency for where clause generation (which doesn't
// always happen)
_ = qmhelper.Where
)
var countryAfterSelectHooks []CountryHook
var countryBeforeInsertHooks []CountryHook
var countryAfterInsertHooks []CountryHook
var countryBeforeUpdateHooks []CountryHook
var countryAfterUpdateHooks []CountryHook
var countryBeforeDeleteHooks []CountryHook
var countryAfterDeleteHooks []CountryHook
var countryBeforeUpsertHooks []CountryHook
var countryAfterUpsertHooks []CountryHook
// doAfterSelectHooks executes all "after Select" hooks.
func (o *Country) doAfterSelectHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range countryAfterSelectHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doBeforeInsertHooks executes all "before insert" hooks.
func (o *Country) doBeforeInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range countryBeforeInsertHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doAfterInsertHooks executes all "after Insert" hooks.
func (o *Country) doAfterInsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range countryAfterInsertHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doBeforeUpdateHooks executes all "before Update" hooks.
func (o *Country) doBeforeUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range countryBeforeUpdateHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doAfterUpdateHooks executes all "after Update" hooks.
func (o *Country) doAfterUpdateHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range countryAfterUpdateHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doBeforeDeleteHooks executes all "before Delete" hooks.
func (o *Country) doBeforeDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range countryBeforeDeleteHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doAfterDeleteHooks executes all "after Delete" hooks.
func (o *Country) doAfterDeleteHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range countryAfterDeleteHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doBeforeUpsertHooks executes all "before Upsert" hooks.
func (o *Country) doBeforeUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range countryBeforeUpsertHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// doAfterUpsertHooks executes all "after Upsert" hooks.
func (o *Country) doAfterUpsertHooks(ctx context.Context, exec boil.ContextExecutor) (err error) {
if boil.HooksAreSkipped(ctx) {
return nil
}
for _, hook := range countryAfterUpsertHooks {
if err := hook(ctx, exec, o); err != nil {
return err
}
}
return nil
}
// AddCountryHook registers your hook function for all future operations.
func AddCountryHook(hookPoint boil.HookPoint, countryHook CountryHook) {
switch hookPoint {
case boil.AfterSelectHook:
countryAfterSelectHooks = append(countryAfterSelectHooks, countryHook)
case boil.BeforeInsertHook:
countryBeforeInsertHooks = append(countryBeforeInsertHooks, countryHook)
case boil.AfterInsertHook:
countryAfterInsertHooks = append(countryAfterInsertHooks, countryHook)
case boil.BeforeUpdateHook:
countryBeforeUpdateHooks = append(countryBeforeUpdateHooks, countryHook)
case boil.AfterUpdateHook:
countryAfterUpdateHooks = append(countryAfterUpdateHooks, countryHook)
case boil.BeforeDeleteHook:
countryBeforeDeleteHooks = append(countryBeforeDeleteHooks, countryHook)
case boil.AfterDeleteHook:
countryAfterDeleteHooks = append(countryAfterDeleteHooks, countryHook)
case boil.BeforeUpsertHook:
countryBeforeUpsertHooks = append(countryBeforeUpsertHooks, countryHook)
case boil.AfterUpsertHook:
countryAfterUpsertHooks = append(countryAfterUpsertHooks, countryHook)
}
}
// One returns a single country record from the query.
func (q countryQuery) One(ctx context.Context, exec boil.ContextExecutor) (*Country, error) {
o := &Country{}
queries.SetLimit(q.Query, 1)
err := q.Bind(ctx, exec, o)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, sql.ErrNoRows
}
return nil, errors.Wrap(err, "models: failed to execute a one query for country")
}
if err := o.doAfterSelectHooks(ctx, exec); err != nil {
return o, err
}
return o, nil
}
// All returns all Country records from the query.
func (q countryQuery) All(ctx context.Context, exec boil.ContextExecutor) (CountrySlice, error) {
var o []*Country
err := q.Bind(ctx, exec, &o)
if err != nil {
return nil, errors.Wrap(err, "models: failed to assign all query results to Country slice")
}
if len(countryAfterSelectHooks) != 0 {
for _, obj := range o {
if err := obj.doAfterSelectHooks(ctx, exec); err != nil {
return o, err
}
}
}
return o, nil
}
// Count returns the count of all Country records in the query.
func (q countryQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
var count int64
queries.SetSelect(q.Query, nil)
queries.SetCount(q.Query)
err := q.Query.QueryRowContext(ctx, exec).Scan(&count)
if err != nil {
return 0, errors.Wrap(err, "models: failed to count country rows")
}
return count, nil
}
// Exists checks if the row exists in the table.
func (q countryQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {
var count int64
queries.SetSelect(q.Query, nil)
queries.SetCount(q.Query)
queries.SetLimit(q.Query, 1)
err := q.Query.QueryRowContext(ctx, exec).Scan(&count)
if err != nil {
return false, errors.Wrap(err, "models: failed to check if country exists")
}
return count > 0, nil
}
// Countries retrieves all the records using an executor.
func Countries(mods ...qm.QueryMod) countryQuery {
mods = append(mods, qm.From("`country`"))
q := NewQuery(mods...)
if len(queries.GetSelect(q)) == 0 {
queries.SetSelect(q, []string{"`country`.*"})
}
return countryQuery{q}
}
// FindCountry retrieves a single record by ID with an executor.
// If selectCols is empty Find will return all columns.
func FindCountry(ctx context.Context, exec boil.ContextExecutor, iD int64, selectCols ...string) (*Country, error) {
countryObj := &Country{}
sel := "*"
if len(selectCols) > 0 {
sel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), ",")
}
query := fmt.Sprintf(
"select %s from `country` where `id`=?", sel,
)
q := queries.Raw(query, iD)
err := q.Bind(ctx, exec, countryObj)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, sql.ErrNoRows
}
return nil, errors.Wrap(err, "models: unable to select from country")
}
if err = countryObj.doAfterSelectHooks(ctx, exec); err != nil {
return countryObj, err
}
return countryObj, nil
}
// Insert a single record using an executor.
// See boil.Columns.InsertColumnSet documentation to understand column list inference for inserts.
func (o *Country) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error {
if o == nil {
return errors.New("models: no country provided for insertion")
}
var err error
if !boil.TimestampsAreSkipped(ctx) {
currTime := time.Now().In(boil.GetLocation())
if queries.MustTime(o.CreatedAt).IsZero() {
queries.SetScanner(&o.CreatedAt, currTime)
}
}
if err := o.doBeforeInsertHooks(ctx, exec); err != nil {
return err
}
nzDefaults := queries.NonZeroDefaultSet(countryColumnsWithDefault, o)
key := makeCacheKey(columns, nzDefaults)
countryInsertCacheMut.RLock()
cache, cached := countryInsertCache[key]
countryInsertCacheMut.RUnlock()
if !cached {
wl, returnColumns := columns.InsertColumnSet(
countryAllColumns,
countryColumnsWithDefault,
countryColumnsWithoutDefault,
nzDefaults,
)
cache.valueMapping, err = queries.BindMapping(countryType, countryMapping, wl)
if err != nil {
return err
}
cache.retMapping, err = queries.BindMapping(countryType, countryMapping, returnColumns)
if err != nil {
return err
}
if len(wl) != 0 {
cache.query = fmt.Sprintf("INSERT INTO `country` (`%s`) %%sVALUES (%s)%%s", strings.Join(wl, "`,`"), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1))
} else {
cache.query = "INSERT INTO `country` () VALUES ()%s%s"
}
var queryOutput, queryReturning string
if len(cache.retMapping) != 0 {
cache.retQuery = fmt.Sprintf("SELECT `%s` FROM `country` WHERE %s", strings.Join(returnColumns, "`,`"), strmangle.WhereClause("`", "`", 0, countryPrimaryKeyColumns))
}
cache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)
}
value := reflect.Indirect(reflect.ValueOf(o))
vals := queries.ValuesFromMapping(value, cache.valueMapping)
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, cache.query)
fmt.Fprintln(writer, vals)
}
result, err := exec.ExecContext(ctx, cache.query, vals...)
if err != nil {
return errors.Wrap(err, "models: unable to insert into country")
}
var lastID int64
var identifierCols []interface{}
if len(cache.retMapping) == 0 {
goto CacheNoHooks
}
lastID, err = result.LastInsertId()
if err != nil {
return ErrSyncFail
}
o.ID = int64(lastID)
if lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == countryMapping["id"] {
goto CacheNoHooks
}
identifierCols = []interface{}{
o.ID,
}
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, cache.retQuery)
fmt.Fprintln(writer, identifierCols...)
}
err = exec.QueryRowContext(ctx, cache.retQuery, identifierCols...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)
if err != nil {
return errors.Wrap(err, "models: unable to populate default values for country")
}
CacheNoHooks:
if !cached {
countryInsertCacheMut.Lock()
countryInsertCache[key] = cache
countryInsertCacheMut.Unlock()
}
return o.doAfterInsertHooks(ctx, exec)
}
// Update uses an executor to update the Country.
// See boil.Columns.UpdateColumnSet documentation to understand column list inference for updates.
// Update does not automatically update the record in case of default values. Use .Reload() to refresh the records.
func (o *Country) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) {
var err error
if err = o.doBeforeUpdateHooks(ctx, exec); err != nil {
return 0, err
}
key := makeCacheKey(columns, nil)
countryUpdateCacheMut.RLock()
cache, cached := countryUpdateCache[key]
countryUpdateCacheMut.RUnlock()
if !cached {
wl := columns.UpdateColumnSet(
countryAllColumns,
countryPrimaryKeyColumns,
)
if !columns.IsWhitelist() {
wl = strmangle.SetComplement(wl, []string{"created_at"})
}
if len(wl) == 0 {
return 0, errors.New("models: unable to update country, could not build whitelist")
}
cache.query = fmt.Sprintf("UPDATE `country` SET %s WHERE %s",
strmangle.SetParamNames("`", "`", 0, wl),
strmangle.WhereClause("`", "`", 0, countryPrimaryKeyColumns),
)
cache.valueMapping, err = queries.BindMapping(countryType, countryMapping, append(wl, countryPrimaryKeyColumns...))
if err != nil {
return 0, err
}
}
values := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, cache.query)
fmt.Fprintln(writer, values)
}
var result sql.Result
result, err = exec.ExecContext(ctx, cache.query, values...)
if err != nil {
return 0, errors.Wrap(err, "models: unable to update country row")
}
rowsAff, err := result.RowsAffected()
if err != nil {
return 0, errors.Wrap(err, "models: failed to get rows affected by update for country")
}
if !cached {
countryUpdateCacheMut.Lock()
countryUpdateCache[key] = cache
countryUpdateCacheMut.Unlock()
}
return rowsAff, o.doAfterUpdateHooks(ctx, exec)
}
// UpdateAll updates all rows with the specified column values.
func (q countryQuery) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) {
queries.SetUpdate(q.Query, cols)
result, err := q.Query.ExecContext(ctx, exec)
if err != nil {
return 0, errors.Wrap(err, "models: unable to update all for country")
}
rowsAff, err := result.RowsAffected()
if err != nil {
return 0, errors.Wrap(err, "models: unable to retrieve rows affected for country")
}
return rowsAff, nil
}
// UpdateAll updates all rows with the specified column values, using an executor.
func (o CountrySlice) UpdateAll(ctx context.Context, exec boil.ContextExecutor, cols M) (int64, error) {
ln := int64(len(o))
if ln == 0 {
return 0, nil
}
if len(cols) == 0 {
return 0, errors.New("models: update all requires at least one column argument")
}
colNames := make([]string, len(cols))
args := make([]interface{}, len(cols))
i := 0
for name, value := range cols {
colNames[i] = name
args[i] = value
i++
}
// Append all of the primary key values for each column
for _, obj := range o {
pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), countryPrimaryKeyMapping)
args = append(args, pkeyArgs...)
}
sql := fmt.Sprintf("UPDATE `country` SET %s WHERE %s",
strmangle.SetParamNames("`", "`", 0, colNames),
strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, countryPrimaryKeyColumns, len(o)))
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, sql)
fmt.Fprintln(writer, args...)
}
result, err := exec.ExecContext(ctx, sql, args...)
if err != nil {
return 0, errors.Wrap(err, "models: unable to update all in country slice")
}
rowsAff, err := result.RowsAffected()
if err != nil {
return 0, errors.Wrap(err, "models: unable to retrieve rows affected all in update all country")
}
return rowsAff, nil
}
var mySQLCountryUniqueColumns = []string{
"id",
}
// Upsert attempts an insert using an executor, and does an update or ignore on conflict.
// See boil.Columns documentation for how to properly use updateColumns and insertColumns.
func (o *Country) Upsert(ctx context.Context, exec boil.ContextExecutor, updateColumns, insertColumns boil.Columns) error {
if o == nil {
return errors.New("models: no country provided for upsert")
}
if !boil.TimestampsAreSkipped(ctx) {
currTime := time.Now().In(boil.GetLocation())
if queries.MustTime(o.CreatedAt).IsZero() {
queries.SetScanner(&o.CreatedAt, currTime)
}
}
if err := o.doBeforeUpsertHooks(ctx, exec); err != nil {
return err
}
nzDefaults := queries.NonZeroDefaultSet(countryColumnsWithDefault, o)
nzUniques := queries.NonZeroDefaultSet(mySQLCountryUniqueColumns, o)
if len(nzUniques) == 0 {
return errors.New("cannot upsert with a table that cannot conflict on a unique column")
}
// Build cache key in-line uglily - mysql vs psql problems
buf := strmangle.GetBuffer()
buf.WriteString(strconv.Itoa(updateColumns.Kind))
for _, c := range updateColumns.Cols {
buf.WriteString(c)
}
buf.WriteByte('.')
buf.WriteString(strconv.Itoa(insertColumns.Kind))
for _, c := range insertColumns.Cols {
buf.WriteString(c)
}
buf.WriteByte('.')
for _, c := range nzDefaults {
buf.WriteString(c)
}
buf.WriteByte('.')
for _, c := range nzUniques {
buf.WriteString(c)
}
key := buf.String()
strmangle.PutBuffer(buf)
countryUpsertCacheMut.RLock()
cache, cached := countryUpsertCache[key]
countryUpsertCacheMut.RUnlock()
var err error
if !cached {
insert, ret := insertColumns.InsertColumnSet(
countryAllColumns,
countryColumnsWithDefault,
countryColumnsWithoutDefault,
nzDefaults,
)
update := updateColumns.UpdateColumnSet(
countryAllColumns,
countryPrimaryKeyColumns,
)
if !updateColumns.IsNone() && len(update) == 0 {
return errors.New("models: unable to upsert country, could not build update column list")
}
ret = strmangle.SetComplement(ret, nzUniques)
cache.query = buildUpsertQueryMySQL(dialect, "`country`", update, insert)
cache.retQuery = fmt.Sprintf(
"SELECT %s FROM `country` WHERE %s",
strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, ret), ","),
strmangle.WhereClause("`", "`", 0, nzUniques),
)
cache.valueMapping, err = queries.BindMapping(countryType, countryMapping, insert)
if err != nil {
return err
}
if len(ret) != 0 {
cache.retMapping, err = queries.BindMapping(countryType, countryMapping, ret)
if err != nil {
return err
}
}
}
value := reflect.Indirect(reflect.ValueOf(o))
vals := queries.ValuesFromMapping(value, cache.valueMapping)
var returns []interface{}
if len(cache.retMapping) != 0 {
returns = queries.PtrsFromMapping(value, cache.retMapping)
}
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, cache.query)
fmt.Fprintln(writer, vals)
}
result, err := exec.ExecContext(ctx, cache.query, vals...)
if err != nil {
return errors.Wrap(err, "models: unable to upsert for country")
}
var lastID int64
var uniqueMap []uint64
var nzUniqueCols []interface{}
if len(cache.retMapping) == 0 {
goto CacheNoHooks
}
lastID, err = result.LastInsertId()
if err != nil {
return ErrSyncFail
}
o.ID = int64(lastID)
if lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == countryMapping["id"] {
goto CacheNoHooks
}
uniqueMap, err = queries.BindMapping(countryType, countryMapping, nzUniques)
if err != nil {
return errors.Wrap(err, "models: unable to retrieve unique values for country")
}
nzUniqueCols = queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), uniqueMap)
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, cache.retQuery)
fmt.Fprintln(writer, nzUniqueCols...)
}
err = exec.QueryRowContext(ctx, cache.retQuery, nzUniqueCols...).Scan(returns...)
if err != nil {
return errors.Wrap(err, "models: unable to populate default values for country")
}
CacheNoHooks:
if !cached {
countryUpsertCacheMut.Lock()
countryUpsertCache[key] = cache
countryUpsertCacheMut.Unlock()
}
return o.doAfterUpsertHooks(ctx, exec)
}
// Delete deletes a single Country record with an executor.
// Delete will match against the primary key column to find the record to delete.
func (o *Country) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
if o == nil {
return 0, errors.New("models: no Country provided for delete")
}
if err := o.doBeforeDeleteHooks(ctx, exec); err != nil {
return 0, err
}
args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), countryPrimaryKeyMapping)
sql := "DELETE FROM `country` WHERE `id`=?"
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, sql)
fmt.Fprintln(writer, args...)
}
result, err := exec.ExecContext(ctx, sql, args...)
if err != nil {
return 0, errors.Wrap(err, "models: unable to delete from country")
}
rowsAff, err := result.RowsAffected()
if err != nil {
return 0, errors.Wrap(err, "models: failed to get rows affected by delete for country")
}
if err := o.doAfterDeleteHooks(ctx, exec); err != nil {
return 0, err
}
return rowsAff, nil
}
// DeleteAll deletes all matching rows.
func (q countryQuery) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
if q.Query == nil {
return 0, errors.New("models: no countryQuery provided for delete all")
}
queries.SetDelete(q.Query)
result, err := q.Query.ExecContext(ctx, exec)
if err != nil {
return 0, errors.Wrap(err, "models: unable to delete all from country")
}
rowsAff, err := result.RowsAffected()
if err != nil {
return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for country")
}
return rowsAff, nil
}
// DeleteAll deletes all rows in the slice, using an executor.
func (o CountrySlice) DeleteAll(ctx context.Context, exec boil.ContextExecutor) (int64, error) {
if len(o) == 0 {
return 0, nil
}
if len(countryBeforeDeleteHooks) != 0 {
for _, obj := range o {
if err := obj.doBeforeDeleteHooks(ctx, exec); err != nil {
return 0, err
}
}
}
var args []interface{}
for _, obj := range o {
pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), countryPrimaryKeyMapping)
args = append(args, pkeyArgs...)
}
sql := "DELETE FROM `country` WHERE " +
strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, countryPrimaryKeyColumns, len(o))
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, sql)
fmt.Fprintln(writer, args)
}
result, err := exec.ExecContext(ctx, sql, args...)
if err != nil {
return 0, errors.Wrap(err, "models: unable to delete all from country slice")
}
rowsAff, err := result.RowsAffected()
if err != nil {
return 0, errors.Wrap(err, "models: failed to get rows affected by deleteall for country")
}
if len(countryAfterDeleteHooks) != 0 {
for _, obj := range o {
if err := obj.doAfterDeleteHooks(ctx, exec); err != nil {
return 0, err
}
}
}
return rowsAff, nil
}
// Reload refetches the object from the database
// using the primary keys with an executor.
func (o *Country) Reload(ctx context.Context, exec boil.ContextExecutor) error {
ret, err := FindCountry(ctx, exec, o.ID)
if err != nil {
return err
}
*o = *ret
return nil
}
// ReloadAll refetches every row with matching primary key column values
// and overwrites the original object slice with the newly updated slice.
func (o *CountrySlice) ReloadAll(ctx context.Context, exec boil.ContextExecutor) error {
if o == nil || len(*o) == 0 {
return nil
}
slice := CountrySlice{}
var args []interface{}
for _, obj := range *o {
pkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), countryPrimaryKeyMapping)
args = append(args, pkeyArgs...)
}
sql := "SELECT `country`.* FROM `country` WHERE " +
strmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, countryPrimaryKeyColumns, len(*o))
q := queries.Raw(sql, args...)
err := q.Bind(ctx, exec, &slice)
if err != nil {
return errors.Wrap(err, "models: unable to reload all in CountrySlice")
}
*o = slice
return nil
}
// CountryExists checks if the Country row exists.
func CountryExists(ctx context.Context, exec boil.ContextExecutor, iD int64) (bool, error) {
var exists bool
sql := "select exists(select 1 from `country` where `id`=? limit 1)"
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
fmt.Fprintln(writer, sql)
fmt.Fprintln(writer, iD)
}
row := exec.QueryRowContext(ctx, sql, iD)
err := row.Scan(&exists)
if err != nil {
return false, errors.Wrap(err, "models: unable to check if country exists")
}
return exists, nil
}
まとめ
Gorm
生SQLの実行は可能
生SQLの取得結果を、Iteratorを使用して、構造体にいれなけれなばいけない
参考になる記事などが多い
DBからコードを生成できない
オートマイグレーションあり
XORM
生SQLの実行は可能
生SQLの取得結果を、一括で構造体に入れられる
参考になる記事などが少なさそうかも
DBからコードを生成できそう
オートマイグレーションあり
SQLBoiler
生SQLの実行は可能
生SQLの取得結果を、一括で構造体に入れられる
参考になる記事などが少なさそうかも
DBからコードを生成できる
オートマイグレーションなし
実装がDBから生成したテーブル主体のクラスに依存する
どれも使いやすそうな感じだと思いました。
自分が現在担当しているプロジェクトでは、公式のドキュメントがわかりやすいgormを採用しました。
また、DBから構造体を生成するのが手間なのですが、GORM/GENというツールを使用しています。
https://github.com/go-gorm/gen
最後に
現在、レスキューナウでは、災害情報の提供、災害情報を活用した安否確認サービスなどのWebサービスの開発エンジニアを募集しています!
社員・フリーランスに関わらず、参画後に安心してご活躍できることを目指し、応募された方の特性・ご希望にマッチしたチームをご紹介します。
ちょっと話を聞いてみたい、ぜひ応募したい、など、当社にご興味を持っていただけましたら、お気軽にエントリーください!!