package
0.0.0-20240919033358-cce434e5d354
Repository: https://github.com/codfrm/cago.git
Documentation: pkg.go.dev

# README

数据库

底层使用gorm库进行封装,支持多种数据库、支持单库与多库模式。

配置

# 单库模式, key设置为db
db:
    driver: mysql
    dsn: root:password@tcp(127.0.0.1:3306)/db?charset=utf8mb4&collation=utf8mb4_unicode_ci&parseTime=True&loc=Local&multiStatements=true
    prefix: prefix_

# 多库模式, key设置为dbs,请注意需要注册对应的数据库驱动
dbs:
    default: # 默认链接, 必须设置
      driver: mysql
      dsn: root:password@tcp(127.0.0.1:3306)/db?charset=utf8mb4&collation=utf8mb4_unicode_ci&parseTime=True&loc=Local&multiStatements=true
      prefix: prefix_
    clickhouse: # clickhouse
      driver: clickhouse
      dsn: clickhouse://127.0.0.1:9009/default?read_timeout=10s

使用

db.Default().Model(&User{}).Where("id = ?", 1).First(&user)
db.Ctx(ctx).Model(&User{}).Where("id = ?", 1).First(&user)

// 多库
db.With("clickhouse").Model(&User{}).Where("id = ?", 1).First(&user)
db.CtxWith(ctx, "clickhouse").Model(&User{}).Where("id = ?", 1).First(&user)

事务

推荐使用context去传递事务的数据库实例

db.Default().Transaction(func(tx *gorm.DB) error {
	ctx:=db.ContextWithDB(context.Background(),tx)
	// 业务方法
    return SomeMethod(ctx)
})

func SomeMethod(ctx context.Context) error {
	db.Ctx(ctx).Model(&User{}).Where("id = ?", 1).First(&user)
    return nil
}

驱动

默认支持mysql,其它驱动需要使用db.RegisterDriver进行注册。可以参考clickhouse的实现。

import (
_ "github.com/codfrm/cago/database/db/clickhouse"
)

# Packages

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Functions

Ctx 从 context 中获取数据库实例,如果不存在则返回默认数据库.
CtxWith 从 context 中获取数据库实例,如果不存在则返回指定数据库.
Database gorm数据库封装,支持多数据库,如果你配置了 trace 的话会自动开启链路追踪 默认注册和使用 mysql 驱动,如果你需要其他驱动,可以使用 RegisterDriver 注册 或者导入对应的数据库驱动,例如: import _ "clickhouse".
Default 默认数据库.
NewLogger create new logger 自定义了gorm的日志输出,会屏蔽掉一些gorm的ErrRecordNotFound错误 将日志输出重定向到了cago的日志库.
RecordNotFound 判断是否是记录不存在的错误.
RegisterDriver 注册数据库驱动 默认会注册mysql t 数据库驱动名 f 数据库驱动函数 传入配置返回 gorm.Dialector.
Use 根据 key 参数指定数据库.
WithContext 根据 key 参数指定数据库,并将数据库实例存入 context 如果你想修改后续的数据库实例,你可以使用 db.WithContext ctx:=db.WithContext(ctx, "db2") SomeMethod(ctx).
WithContextDB 将数据库实例存入 context 如果你有事务的需求,你可以使用 db.WithContextDB,然后使用带Ctx的方法来获取数据库实例,这样会自动传递数据库实例 db.Default().Transaction(func(tx *gorm.DB) error { return SomeMethod(db.WithContextDB(ctx, tx)) }).

# Constants

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Structs

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Type aliases

Driver 数据库驱动.
No description provided by the author
No description provided by the author