daoongorm

package module
v0.0.0-...-c902e56 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 29, 2022 License: MIT Imports: 17 Imported by: 3

README

dao-on-gorm

轻量级的基于gorm 的针对单条数据操作curd封装,操作方便, 同时基于主键对数据做了自动缓存cache,大大降低数据库压力, 事务和非事务操作模式基本一致

使用体验

  1. examples/config_demo.yaml 下配置自己的redis 和 mysql连接信息
  2. 在你的mysql库中导入sql: examples/sql.md
  3. go test -v ./... 即可运行项目的单测,就可以看到数据操作的日志信息
[5.619ms] [rows:1] INSERT INTO `cclehui_test_b` (`version`,`weight`,`age`,`extra`,`created_at_new`,`updated_at_new`) VALUES (10,1.900000,'1989-03-18 10:24:32','字符串数据:bbbbbbbbbbbbbbb','2022-01-29 18:02:10.639','2022-01-29 18:02:10.639')
非ID为主键key的表, create 测试成功, ID:15, : map[age:1989-03-18 10:24:32 column_id:15 created_at_new:2022-01-29 18:02:10 extra:字符串数据:bbbbbbbbbbbbbbb updated_at_new:2022-01-29 18:02:10 version:10 weight:1.9]

[0.492ms] [rows:1] SELECT * FROM `cclehui_test_b` WHERE `column_id` = 15 LIMIT 1

[3.759ms] [rows:1] UPDATE `cclehui_test_b` SET `age`='1989-03-18 18:24:32',`created_at_new`='2022-01-29 18:02:11',`extra`='字符串数据:bbbbbbbbbbbbbbb',`updated_at_new`='2022-01-29 18:02:11.647',`version`=10,`weight`=1.900000 WHERE `column_id` = 15
非ID为主键key的表, 自定义created_at,upadted_at字段名 测试成功

[3.133ms] [rows:1] DELETE FROM `cclehui_test_b` WHERE `cclehui_test_b`.`column_id` = 15

examples 目录下是完成的集成例子, 其中 examples/dao_test.go 包含了curd 和事务操作的详细例子

集成方法

  1. dao-on-gorm 本身是基于gorm的,实现上基于CacheInterfaceDBClientInterface 两个interface{}, 所以接入的时候咱们需要实现这两个api才能提供真正的cache 和db操作功能
  2. DBClientInterface 也提供了一种默认的实现 DBClient , 也可以直接使用
  3. CacheInterface 需要咱们实现, 实现方式可以参考 examples/cache_util_demo.go

具体详细建议读一下 examples/dao_test.go 即可明白

基本使用

// 定义表结构
type CclehuiTestADao struct {
	ID        int       `gorm:"column:id;primaryKey" structs:"id" json:"id"`
	Version   int64     `gorm:"column:version" structs:"version" json:"version"`
	Weight    float64   `gorm:"column:weight;column_default:1.9" structs:"weight" json:"weight"`
	Age       time.Time `gorm:"column:age" structs:"age" json:"age"`
	Extra     string    `gorm:"column:extra" structs:"extra" json:"extra"`
	CreatedAt time.Time `gorm:"column:created_at" structs:"created_at" json:"created_at"`
	UpdatedAt time.Time `gorm:"column:updated_at" structs:"updated_at" json:"updated_at"`

	daoBase *daoongorm.DaoBase
}

// 创建新记录
testDao, err := NewCclehuiTestADao(ctx, &CclehuiTestADao{}, false)
testDao.Version = 10
testDao.Age, _ = time.Parse("2006-01-02 15:04:05", "1989-03-18 10:24:32")
testDao.Extra = "字符串数据:11111aa"
err = testDao.GetDaoBase().Save(ctx)

// 从从库查询数据(一行搞定)
testDao, err := NewCclehuiTestADao(ctx, &CclehuiTestADao{ID:1}, true)

// 更新数据
testDao, err := NewCclehuiTestADao(ctx, &CclehuiTestADao{ID:1}, false)
testDao.Version = 21
err = testDao.GetDaoBase().Save(ctx)

// 删除数据
err = testDao.GetDaoBase().Delete(ctx)

特性说明

option.go 中包含了NewDao中可设置的选项

  1. 是否开启缓存
  2. 是否在记录不存在时也强制缓存
  3. 设置created_at,updated_at 字段名 (默认是created_at,updated_at 可以修改),该字段的值会自动填充

设置全局默认的缓存组件SetGlobalCacheUtil

Documentation

Index

Constants

View Source
const (
	LevelDebug = "DEBUG"
	LevelInfo  = "INFO"
	LevelWarn  = "WARN"
	LevelError = "ERROR"
)
View Source
const (
	TypeNameTime = "Time"
)

Variables

View Source
var (
	DaoCacheExpire int    = 86400 * 7  // dao缓存超时时间
	DaoCachePrefix string = "daocache" // dao缓存key前缀

	FieldNameCreatedAt = "CreatedAt"
	FieldNameUpdatedAt = "UpdatedAt"
)

全局属性变量 可以配置成自己需要的值

Functions

func DaoStructToMap

func DaoStructToMap(data interface{}) map[string]interface{}

dao结构体转 map

func GetModelFullNameAndValue

func GetModelFullNameAndValue(m interface{}) (string, reflect.Value)

func ReflectValueToStr

func ReflectValueToStr(kind reflect.Kind, v reflect.Value) string

func RegisterModel

func RegisterModel(m Model)

注册dao模型 此方法需要在dao文件的init()方法中调用

func SetGlobalCacheUtil

func SetGlobalCacheUtil(cacheUtil CacheInterface)

设置全局缓存操作util

func SetLogger

func SetLogger(newLogger Logger)

Types

type CacheInterface

type CacheInterface interface {
	Set(ctx context.Context, key string, value interface{}, ttl int) (err error)
	Get(ctx context.Context, key string, value interface{}) (hit bool, err error)
	Del(ctx context.Context, key string) (err error)
}

type DBClient

type DBClient struct {
	*gorm.DB // 读写连接
	// contains filtered or unexported fields
}

func NewDBClient

func NewDBClient(c *DBClientConfig) (*DBClient, error)

连接数据库, 获取新链接

func (*DBClient) DataSource

func (db *DBClient) DataSource(ctx context.Context, isReadOnly bool) *gorm.DB

DataSource 设定数据源

func (*DBClient) GetDBClientConfig

func (db *DBClient) GetDBClientConfig() *DBClientConfig

func (*DBClient) ReadOnly

func (db *DBClient) ReadOnly() *gorm.DB

ReadOnly 获取只读连接

func (*DBClient) ReadOnlyTable

func (db *DBClient) ReadOnlyTable(ctx context.Context, name string) *gorm.DB

ReadOnlyTable 设定只读表名

func (*DBClient) Table

func (db *DBClient) Table(ctx context.Context, name string) *gorm.DB

Table 设定表名

func (*DBClient) Transaction

func (db *DBClient) Transaction(ctx context.Context, tansFunc TransactionFunction) (err error)

type DBClientConfig

type DBClientConfig struct {
	// 主dsn配置
	DSN *DSNConfig `yaml:"dsn"`
	// 只读dsn配置
	ReadDSN []*DSNConfig `yaml:"readDSN"`
	// 最大可用数量
	Active int `yaml:"active"`
	// 最大闲置数量
	Idle int `yaml:"idle"`
	// 闲置超时时间
	IdleTimeout ctime.Duration `yaml:"idleTimeout"`
	// 查询超时时间
	QueryTimeout ctime.Duration `yaml:"queryTimeout"`
	// 执行超时时间
	ExecTimeout ctime.Duration `yaml:"execTimeout"`
	// 事务超时时间
	TranTimeout ctime.Duration `yaml:"tranTimeout"`
}

type DBClientInterface

type DBClientInterface interface {
	Table(ctx context.Context, name string) *gorm.DB         // 读写连接
	ReadOnlyTable(ctx context.Context, name string) *gorm.DB // 只读连接
}

type DBIDInt

type DBIDInt struct {
	ID int `gorm:"column:id" structs:"id" json:"id"`
}

type DBIDInt64

type DBIDInt64 struct {
	ID int64 `gorm:"column:id" structs:"id" json:"id"`
}

type DBUpdateAt

type DBUpdateAt struct {
	UpdatedAt time.Time `gorm:"column:updated_at" structs:"updated_at" json:"updated_at"`
}

type DSNConfig

type DSNConfig struct {
	UserName string          `yaml:"userName"`
	Password string          `yaml:"password"`
	Endpoint *EndpointConfig `yaml:"endpoint"`
	DBName   string          `yaml:"dbName"`
	Options  []string        `yaml:"options"`
}

DSN配置

type DaoBase

type DaoBase struct {
	// contains filtered or unexported fields
}

func NewDaoBase

func NewDaoBase(ctx context.Context, model Model, readOnly bool, options ...Option) (*DaoBase, error)

func NewDaoBaseNoLoad

func NewDaoBaseNoLoad(model Model) (*DaoBase, error)

不加载数据的 获取model的daobase 目的为了获取对应的daobase 方法拿到底层的模型函数

func NewDaoBaseWithTX

func NewDaoBaseWithTX(ctx context.Context, model Model, tx DBClientInterface, options ...Option) (*DaoBase, error)

支持事务

func (*DaoBase) Create

func (daoBase *DaoBase) Create(ctx context.Context) error

func (*DaoBase) DBClient

func (daoBase *DaoBase) DBClient() DBClientInterface

func (*DaoBase) Delete

func (daoBase *DaoBase) Delete(ctx context.Context) error

func (*DaoBase) GetDefaultMapView

func (daoBase *DaoBase) GetDefaultMapView() map[string]interface{}

dao默认转map结构

func (*DaoBase) GetOldData

func (daoBase *DaoBase) GetOldData() map[string]interface{}

func (*DaoBase) GetUniqKey

func (daoBase *DaoBase) GetUniqKey() string

func (*DaoBase) IsLoadFromDB

func (daoBase *DaoBase) IsLoadFromDB() bool

func (*DaoBase) IsNewRow

func (daoBase *DaoBase) IsNewRow() bool

func (*DaoBase) Load

func (daoBase *DaoBase) Load(ctx context.Context) error

func (*DaoBase) PKFieldsStr

func (daoBase *DaoBase) PKFieldsStr() string

主键转字符串

func (*DaoBase) Save

func (daoBase *DaoBase) Save(ctx context.Context) error

自动识别创建还是更新

func (*DaoBase) TableName

func (daoBase *DaoBase) TableName() string

func (*DaoBase) Update

func (daoBase *DaoBase) Update(ctx context.Context) error

type DefaultLogger

type DefaultLogger struct{}

func (*DefaultLogger) Errorf

func (l *DefaultLogger) Errorf(ctx context.Context, format string, args ...interface{})

func (*DefaultLogger) Infof

func (l *DefaultLogger) Infof(ctx context.Context, format string, args ...interface{})

type EndpointConfig

type EndpointConfig struct {
	Address string `yaml:"address"`
	Port    int    `yaml:"port"`
}

type Field

type Field struct {
	Name        string
	StructField *reflect.StructField
	Tag         *FieldTag
	Kind        reflect.Kind
	ColumnName  string
}

func (*Field) IsPrimaryKey

func (f *Field) IsPrimaryKey() bool

type FieldTag

type FieldTag struct {
	ColumnName        string
	Val               string
	IsPK              bool
	Ignore            bool
	ColumnDefault     string
	HaveColumnDefault bool // 是否有设置默认值
}

func NewFieldTag

func NewFieldTag(tag string) *FieldTag

type LogData

type LogData struct {
	Level   string
	Content string
}

type Logger

type Logger interface {
	Errorf(ctx context.Context, format string, args ...interface{})
	Infof(ctx context.Context, format string, args ...interface{})
}

type Model

type Model interface {
	TableName() string
	DBName() string
	DBClient() DBClientInterface
	GetDaoBase() *DaoBase
	SetDaoBase(myDaoBase *DaoBase)
}

模型

type ModelDef

type ModelDef struct {
	ModelType reflect.Type
	FullName  string
	PKFields  map[string]*Field
	Fields    map[string]*Field
	// contains filtered or unexported fields
}

模型定义

func NewModelDef

func NewModelDef(m interface{}) *ModelDef

type NopCacheUtil

type NopCacheUtil struct{}

func (*NopCacheUtil) Del

func (ncu *NopCacheUtil) Del(ctx context.Context, key string) (err error)

func (*NopCacheUtil) Get

func (ncu *NopCacheUtil) Get(ctx context.Context, key string, value interface{}) (hit bool, err error)

func (*NopCacheUtil) Set

func (ncu *NopCacheUtil) Set(ctx context.Context,
	key string, value interface{}, ttl int) (err error)

type Option

type Option interface {
	Apply(*DaoBase)
}

func OptionNewForceCache

func OptionNewForceCache(newForceCache bool) Option

记录不存在是否也缓存

func OptionSetCacheExpireTS

func OptionSetCacheExpireTS(expireTS int) Option

func OptionSetCacheUtil

func OptionSetCacheUtil(cacheUtil CacheInterface) Option

设置缓存组件

func OptionSetFieldNameCreatedAt

func OptionSetFieldNameCreatedAt(fieldName string) Option

func OptionSetFieldNameUpdatedAt

func OptionSetFieldNameUpdatedAt(fieldName string) Option

func OptionSetUseCache

func OptionSetUseCache(useCache bool) Option

type OptionFunc

type OptionFunc func(daoBase *DaoBase)

func (OptionFunc) Apply

func (of OptionFunc) Apply(daoBase *DaoBase)

type TransactionFunction

type TransactionFunction func(ctx context.Context, tx *DBClient) error

事务函数

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL