Skip to content

go zero gorm extension / Integrated processing of db model and Redis cache

License

Notifications You must be signed in to change notification settings

xiao-linxin/x-gorm-zero

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

gorm-zero

go zero gorm extension

If you use go zero, and you want to use Gorm. You can use this library.

Usage

  • add the dependent
go get github.com/SpectatorNan/gorm-zero
  • replace template/model in your project with gorm-zero/template/{goctl version}/model
  • generate
goctl model mysql -src={patterns} -dir={dir} -cache --home ./template

Mysql

Config

import (
    "github.com/SpectatorNan/gorm-zero/gormc/config/mysql"
)
type Config struct {
    Mysql mysql.Mysql
    ...
}

Initialization

import (
"github.com/SpectatorNan/gorm-zero/gormc/config/mysql"
)
func NewServiceContext(c config.Config) *ServiceContext {
    db, err := mysql.Connect(c.Mysql)
    if err != nil {
        log.Fatal(err)
    }
    ...
}

PgSql

Config

import (
"github.com/SpectatorNan/gorm-zero/gormc/config/pg"
)
type Config struct {
    PgSql pg.PgSql
    ...
}

Initialization

import (
"github.com/SpectatorNan/gorm-zero/gormc/config/pg"
)
func NewServiceContext(c config.Config) *ServiceContext {
    db, err := pg.Connect(c.PgSql)
    if err != nil {
        log.Fatal(err)
    }
    ...
}

Useage

Query With Cache And Custom Expire Duration

    gormzeroUsersIdKey := fmt.Sprintf("%s%v", cacheGormzeroUsersIdExpirePrefix, id)
    var resp Users
    err := m.QueryWithExpireCtx(ctx, &resp, gormzeroUsersIdKey, expire, func(conn *gorm.DB, v interface{}) error {
        return conn.Model(&Users{}).Where("`id` = ?", id).First(&resp).Error
    })
    switch err {
        case nil:
            return &resp, nil
        case gormc.ErrNotFound:
            return nil, ErrNotFound
        default:
            return nil, err
    }

Query With Cache And Default Expire Duration

    gormzeroUsersIdKey := fmt.Sprintf("%s%v", cacheGormzeroUsersIdPrefix, id)
    var resp Users
    err := m.QueryCtx(ctx, &resp, gormzeroUsersIdKey, func(conn *gorm.DB, v interface{}) error {
        return conn.Model(&Users{}).Where("`id` = ?", id).First(&resp).Error
    })
    switch err {
        case nil:
            return &resp, nil
        case gormc.ErrNotFound:
            return nil, ErrNotFound
        default:
            return nil, err
    }

Usage Example

About

go zero gorm extension / Integrated processing of db model and Redis cache

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Go 100.0%