db

package
v0.0.0-...-83d2edf Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2025 License: MIT Imports: 15 Imported by: 0

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/cago-frame/cago/database/db/clickhouse"
)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Ctx

func Ctx(ctx context.Context) *gorm.DB

Ctx 从 context 中获取数据库实例,如果不存在则返回默认数据库

func CtxWith

func CtxWith(ctx context.Context, key string) *gorm.DB

CtxWith 从 context 中获取数据库实例,如果不存在则返回指定数据库

func Default

func Default() *gorm.DB

Default 默认数据库

func RecordNotFound

func RecordNotFound(err error) bool

RecordNotFound 判断是否是记录不存在的错误

func RegisterDriver

func RegisterDriver(t Driver, f func(*Config) gorm.Dialector)

RegisterDriver 注册数据库驱动 默认会注册mysql t 数据库驱动名 f 数据库驱动函数 传入配置返回 gorm.Dialector

func Use

func Use(key string) *gorm.DB

Use 根据 key 参数指定数据库

func WithContext

func WithContext(ctx context.Context, key string) context.Context

WithContext 根据 key 参数指定数据库,并将数据库实例存入 context 如果你想修改后续的数据库实例,你可以使用 db.WithContext ctx:=db.WithContext(ctx, "db2") SomeMethod(ctx)

func WithContextDB

func WithContextDB(ctx context.Context, db *gorm.DB) context.Context

WithContextDB 将数据库实例存入 context 如果你有事务的需求,你可以使用 db.WithContextDB,然后使用带Ctx的方法来获取数据库实例,这样会自动传递数据库实例

db.Default().Transaction(func(tx *gorm.DB) error {
  return SomeMethod(db.WithContextDB(ctx, tx))
})

Types

type Config

type Config struct {
	Driver Driver `yaml:"driver"`
	Dsn    string `yaml:"dsn"`
	Prefix string `yaml:"prefix"`
	// 开启 gorm 的 debug 模式
	Debug bool `yaml:"debug"`
	// 读写分离,以后再说吧
	//WriterDsn []string `yaml:"writerDsn,omitempty"` // 写入数据源
	//ReaderDsn []string `yaml:"readerDsn,omitempty"` // 读取数据源
	// gorm配置
	PrepareStmt bool `yaml:"prepareStmt,omitempty"` // 是否开启预编译
}

type DB

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

func Database

func Database() *DB

Database gorm数据库封装,支持多数据库,如果你配置了 trace 的话会自动开启链路追踪 默认注册和使用 mysql 驱动,如果你需要其他驱动,可以使用 RegisterDriver 注册 或者导入对应的数据库驱动,例如: import _ "clickhouse"

func (*DB) CloseHandle

func (d *DB) CloseHandle()

func (*DB) SetDefault

func (d *DB) SetDefault(db *gorm.DB)

SetDefault 设置默认数据库

func (*DB) Start

func (d *DB) Start(ctx context.Context, config *configs.Config) error

type Driver

type Driver string

Driver 数据库驱动

const (
	MySQL      Driver = "mysql"
	Clickhouse Driver = "clickhouse"
	SQLite     Driver = "sqlite"
	Postgres   Driver = "postgres"
)

type GroupConfig

type GroupConfig map[string]*Config

type Logger

type Logger struct {
	logger.Config
	// contains filtered or unexported fields
}

func NewLogger

func NewLogger(driver Driver, config logger.Config) *Logger

NewLogger create new logger 自定义了gorm的日志输出,会屏蔽掉一些gorm的ErrRecordNotFound错误 将日志输出重定向到了cago的日志库

func (*Logger) Error

func (l *Logger) Error(ctx context.Context, msg string, args ...interface{})

func (*Logger) Info

func (l *Logger) Info(ctx context.Context, msg string, args ...interface{})

func (*Logger) LogMode

func (l *Logger) LogMode(level logger.LogLevel) logger.Interface

func (*Logger) ParamsFilter

func (l *Logger) ParamsFilter(ctx context.Context, sql string, params ...interface{}) (string, []interface{})

ParamsFilter Trace print sql message

func (*Logger) Trace

func (l *Logger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error)

func (*Logger) Warn

func (l *Logger) Warn(ctx context.Context, msg string, args ...interface{})

type Option

type Option func(*Options)

type Options

type Options struct {
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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