A lightweight, fast, orm-like library helps interactive with database

gomodel wercker status GoDoc

gomodel provide another method to interact with database.
Instead of reflection, use bitset represent fields of CRUD, sql/stmt cache and generate model code for you, high performance.

Install

$ go get github.com/cosiner/gomodel
$ cd /path/of/gomodel/cmd/gomodel
$ go install # it will install the gomodel binary file to your $GOPATH/bin
$ gomodel -cp # copy model.tmpl to default path $HOME/.config/go/model.tmpl
              # or just put it to your model package, gomodel will search it first 
$ # if need customed template, just copy model.tmpl to your models directory

The gomodel cmd tool and SQL convertion for structures.

There is a detailed example User-Follow.

User

var (
    ErrDuplicateUserName = httperrs.Conflict.NewS("user name already exists")
    ErrNoUser            = httperrs.NotFound.NewS("user not found")
)

type User struct {
    Id   int64
    Name string
    Age  int

    Followings int
    Followers  int
}

func (u *User) Add() error {
    u.Followings = 0
    u.Followers = 0

    id, err := DB.Insert(u, userFieldsExcpId, gomodel.RES_ID)
    err = dberrs.DuplicateKeyError(err, UserNameCol, ErrDuplicateUserName)
    if err == nil {
        u.Id = id
    }

    return err
}

func DeleteUserById(id int64) error {
    c, err := DB.ArgsDelete(userInstance, USER_ID, id)

    return dberrs.NoAffects(c, err, ErrNoUser)
}

func (u *User) Update() error {
    c, err := DB.Update(u, USER_NAME|USER_AGE, USER_ID)

    return dberrs.NoAffects(c, err, ErrNoUser)
}

func (u *User) ById() error {
    err := DB.One(u, userFieldsExcpId, USER_ID)

    return dberrs.NoRows(err, ErrNoUser)
}

func UsersByAge(age, start, count int) ([]User, error) {
    users := userStore{
        Fields: userFieldsAll,
    }

    err := DB.ArgsLimit(&users, userInstance, userFieldsAll, USER_AGE, age, start, count)
    return users.Values, dberrs.NoRows(err, ErrNoUser)
}

func AllUsersByAge(age int) ([]User, error) {
    users := userStore{
        Fields: userFieldsAll,
    }

    err := DB.ArgsAll(&users, userInstance, userFieldsAll, USER_AGE, age)
    return users.Values, dberrs.NoRows(err, ErrNoUser)
}

Follow

var (
    ErrFollowed  = httperrs.Conflict.NewS("already followed")
    ErrNonFollow = httperrs.NotFound.NewS("non follow")
)

type Follow struct {
    UserId       int64 `table:"user_follow"`
    FollowUserId int64
}


//gomodel insertUserFollowSQL = [
//  INSERT INTO Follow(UserId, FollowUserId)
//      SELECT ?, ? FROM DUAL
//      WHERE EXISTS(SELECT Id FROM User WHERE Id=?)
//]
func (f *Follow) Add() error {
    return f.txDo(DB, func(tx gomodel.Tx, f *Follow) error {
        c, err := tx.UpdateById(insertUserFollowSQL, gomodel.FieldVals(f, followFieldsAll, f.FollowUserId)...)

        err = dberrs.NoAffects(c, err, ErrNoUser)
        err = dberrs.DuplicateKeyError(err, dberrs.PRIMARY_KEY, ErrFollowed)

        return f.updateFollowInfo(tx, err, 1)
    })
}

func (f *Follow) Delete() error {
    return f.txDo(DB, func(tx gomodel.Tx, f *Follow) error {
        c, err := tx.Delete(f, followFieldsAll)
        err = dberrs.NoAffects(c, err, ErrNonFollow)

        return f.updateFollowInfo(tx, err, -1)
    })
}

func (f *Follow) updateFollowInfo(tx gomodel.Tx, err error, c int) error {
    if err == nil {
        _, err = tx.ArgsIncrBy(userInstance, USER_FOLLOWINGS, USER_ID, c, f.UserId)
        if err == nil {
            _, err = tx.ArgsIncrBy(userInstance, USER_FOLLOWERS, USER_ID, c, f.FollowUserId)
        }
    }
    return err
}

LICENSE

MIT.

Similar Resources

Simple Go ORM for Google/Firebase Cloud Firestore

go-firestorm Go ORM (Object-relational mapping) for Google Cloud Firestore. Goals Easy to use Non intrusive Non exclusive Fast Features Basic CRUD ope

Dec 1, 2022

QBS stands for Query By Struct. A Go ORM.

Qbs Qbs stands for Query By Struct. A Go ORM. 中文版 README ChangeLog 2013.03.14: index name has changed to {table name}_{column name}. For existing appl

Sep 9, 2022

Simple and Powerful ORM for Go, support mysql,postgres,tidb,sqlite3,mssql,oracle, Moved to https://gitea.com/xorm/xorm

xorm HAS BEEN MOVED TO https://gitea.com/xorm/xorm . THIS REPOSITORY WILL NOT BE UPDATED ANY MORE. 中文 Xorm is a simple and powerful ORM for Go. Featur

Jan 3, 2023

A better ORM for Go, based on non-empty interfaces and code generation.

reform A better ORM for Go and database/sql. It uses non-empty interfaces, code generation (go generate), and initialization-time reflection as oppose

Dec 31, 2022

100% type-safe ORM for Go (Golang) with code generation and MySQL, PostgreSQL, Sqlite3, SQL Server support. GORM under the hood.

go-queryset 100% type-safe ORM for Go (Golang) with code generation and MySQL, PostgreSQL, Sqlite3, SQL Server support. GORM under the hood. Contents

Dec 30, 2022

A better ORM for Go, based on non-empty interfaces and code generation.

A better ORM for Go, based on non-empty interfaces and code generation.

A better ORM for Go and database/sql. It uses non-empty interfaces, code generation (go generate), and initialization-time reflection as opposed to interface{}, type system sidestepping, and runtime reflection. It will be kept simple.

Dec 29, 2022

Simple and performant ORM for sql.DB

Simple and performant ORM for sql.DB Main features are: Works with PostgreSQL, MySQL, SQLite. Selecting into a map, struct, slice of maps/structs/vars

Jan 4, 2023

golang orm

korm golang orm, 一个简单易用的orm, 支持嵌套事务 安装 go get github.com/wdaglb/korm go get github.com/go-sql-driver/mysql 支持数据库 mysql https://github.com/go-sql-driv

Oct 31, 2022

Golang ORM with focus on PostgreSQL features and performance

go-pg is in a maintenance mode and only critical issues are addressed. New development happens in Bun repo which offers similar functionality but works with PostgreSQL, MySQL, and SQLite.

Jan 8, 2023
Related tags
beedb is a go ORM,support database/sql interface,pq/mysql/sqlite

Beedb ❗ IMPORTANT: Beedb is being deprecated in favor of Beego.orm ❗ Beedb is an ORM for Go. It lets you map Go structs to tables in a database. It's

Nov 25, 2022
Database agnostic ORM for Go

If you are looking for something more lightweight and flexible, have a look at jet For questions, suggestions and general topics visit the group. Inde

Nov 28, 2022
Generate a Go ORM tailored to your database schema.
Generate a Go ORM tailored to your database schema.

SQLBoiler is a tool to generate a Go ORM tailored to your database schema. It is a "database-first" ORM as opposed to "code-first" (like gorm/gorp). T

Jan 2, 2023
Examples of using various popular database libraries and ORM in Go.

Introduction Examples of using various popular database libraries and ORM in Go. sqlx sqlc Gorm sqlboiler ent The aim is to demonstrate and compare us

Dec 12, 2021
Examples of using various popular database libraries and ORM in Go.

Introduction Examples of using various popular database libraries and ORM in Go. sqlx sqlc Gorm sqlboiler ent The aim is to demonstrate and compare us

Dec 28, 2022
ORM-ish library for Go

We've moved! gorp is now officially maintained at: https://github.com/go-gorp/gorp This fork was created when the project was moved, and is provided f

Aug 23, 2022
An orm library support nGQL for Golang

norm An ORM library support nGQL for Golang. Overview Build insert nGQL by struct / map (Support vertex, edge). Parse Nebula execute result to struct

Dec 1, 2022
The fantastic ORM library for Golang, aims to be developer friendly

GORM The fantastic ORM library for Golang, aims to be developer friendly. Overview Full-Featured ORM Associations (Has One, Has Many, Belongs To, Many

Nov 11, 2021
Mikorm - Library ORM Mikrotik API using go
Mikorm - Library ORM Mikrotik API using go

Mikrotik ORM (mikorm) Library Mikrotik API menggunakan ORM untuk mempermudah int

Jun 28, 2022
A simple wrapper around sql.DB to help with structs. Not quite an ORM.

go-modeldb A simple wrapper around sql.DB to help with structs. Not quite an ORM. Philosophy: Don't make an ORM Example: // Setup require "modeldb" db

Nov 16, 2019