db

package module
v3.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2022 License: BSD-3-Clause Imports: 13 Imported by: 0

README

DB

基于 xorm 构建的 DB 工具.

导入包
import (
    "github.com/fuyibing/db/v3"
)
依赖项
import (
    "github.com/fuyibing/log/v3
    "xorm.io/xorm"
)

Documentation

Overview

Package db 基于 XORM 的数据库操作工具.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Transaction

func Transaction(ctx context.Context, handlers ...TransactionHandler) error

Transaction 执行事务.

[13:40:26.000][ INFO][span-id=0.0] example begin
[13:40:26.026][ INFO][span-id=0.1] [SQL] BEGIN TRANSACTION
[13:40:26.031][ INFO][span-id=0.2] [SQL] SELECT * FROM `example` WHERE (`id` = ?) LIMIT 1, Args: [1]
[13:40:26.031][ERROR][span-id=0.3] Error 1146: Table 'schema.example' doesn't exist
[13:40:26.037][ INFO][span-id=0.4] [SQL] ROLLBACK
[13:40:26.037][ INFO][span-id=0.5] example error: Error 1146: Table 'schema.example' doesn't exist
Example
// 1. 创建上下文.
ctx := trace.New()
log.Infofc(ctx, "example begin")

// 2. 定义事务.
//
//    参数 tx1, tx2, tx3, tx4 遵循 TransactionHandler, 执行时
//    按顺序执行. 当任一返回 error 时, 跳过未执行的 handler.
err := Transaction(ctx, tx1, tx2, tx3, tx4)

// 3. 事务出错.
if err != nil {
	log.Infofc(ctx, "example error: %v", err)
	return
}

// 4. 成功完成.
log.Infofc(ctx, "example completed")
Output:

func TransactionWithSession

func TransactionWithSession(ctx context.Context, sess *xorm.Session, handlers ...TransactionHandler) (err error)

TransactionWithSession 执行事务.

[13:40:26.000][ INFO][span-id=0.0] example begin
[13:40:26.026][ INFO][span-id=0.1] [SQL] BEGIN TRANSACTION
[13:40:26.031][ INFO][span-id=0.2] [SQL] SELECT * FROM `example` WHERE (`id` = ?) LIMIT 1, Args: [1]
[13:40:26.031][ERROR][span-id=0.3] Error 1146: Table 'schema.example' doesn't exist
[13:40:26.037][ INFO][span-id=0.4] [SQL] ROLLBACK
[13:40:26.037][ INFO][span-id=0.5] example error: Error 1146: Table 'schema.example' doesn't exist
Example
// 1. 创建上下文.
ctx := trace.New()
log.Infofc(ctx, "example begin")

// 2. 获取连接
//    并在结束时释放回池.
sess := Connector.GetMasterWithContext(ctx)
defer func() { _ = sess.Close() }()

// 3. 定义事务.
//
//    参数 tx1, tx2, tx3, tx4 遵循 TransactionHandler, 执行时
//    按顺序执行. 当任一返回 error 时, 跳过未执行的 handler.
err := TransactionWithSession(ctx, sess, tx1, tx2, tx3, tx4)

// 4. 事务出错.
if err != nil {
	log.Infofc(ctx, "example error: %v", err)
	return
}

// 5. 成功完成.
log.Infofc(ctx, "example completed")
Output:

Types

type Configuration

type Configuration struct {
	// 数据源列表.
	// 包初始化时, 从 config/db.yaml 文件中解析.
	Databases map[string]*Database `yaml:"databases"`
	// contains filtered or unexported fields
}

Configuration 配置结构体.

var (
	// Config
	// 配置实例.
	Config *Configuration
)

func (*Configuration) GetDatabase

func (o *Configuration) GetDatabase(key string) *Database

GetDatabase 读取数据源.

func (*Configuration) GetDefault

func (o *Configuration) GetDefault() *Database

GetDefault 读取数据源.

func (*Configuration) SetDatabase

func (o *Configuration) SetDatabase(key string, database *Database)

SetDatabase 设置数据源.

Example
Config.SetDatabase("my", &Database{
	Dsn: []string{
		"user:pass@tcp(192.168.0.100:6379)/schema?charset=utf8",
		"user:pass@tcp(192.168.0.101:6379)/schema?charset=utf8",
		"user:pass@tcp(192.168.0.102:6379)/schema?charset=utf8",
		"user:pass@tcp(192.168.0.103:6379)/schema?charset=utf8",
	},
})
Output:

type Connection

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

Connection 连接操作.

var (
	Connector *Connection
)

func (*Connection) GetEngineGroup

func (o *Connection) GetEngineGroup(keys ...string) (engine *xorm.EngineGroup)

GetEngineGroup 读取ORM引擎.

func (*Connection) GetMaster

func (o *Connection) GetMaster(keys ...string) *xorm.Session

GetMaster 读取主库连接.

func (*Connection) GetMasterWithContext

func (o *Connection) GetMasterWithContext(ctx context.Context, keys ...string) *xorm.Session

GetMasterWithContext 读取主库连接.

func (*Connection) GetSlave

func (o *Connection) GetSlave(keys ...string) *xorm.Session

GetSlave 读取从库连接.

func (*Connection) GetSlaveWithContext

func (o *Connection) GetSlaveWithContext(ctx context.Context, keys ...string) *xorm.Session

GetSlaveWithContext 读取从库连接.

type Database

type Database struct {
	Driver        string   `yaml:"driver"`
	Dsn           []string `yaml:"dsn"`
	MaxIdle       int      `yaml:"max-idle"`
	MaxLifetime   int      `yaml:"max-lifetime"`
	MaxOpen       int      `yaml:"max-open"`
	Mapper        string   `yaml:"mapper"`
	EnableSession *bool    `yaml:"enable-session"`
	ShowSQL       *bool    `yaml:"show-sql"`
	// contains filtered or unexported fields
}

Database 数据库配置.

func (*Database) GetDataName

func (o *Database) GetDataName() string

GetDataName 返回数据库库名.

func (*Database) GetMapper

func (o *Database) GetMapper() names.Mapper

GetMapper 返回映射关系.

func (*Database) GetUsername

func (o *Database) GetUsername() string

GetUsername 返回数据库用户名.

func (*Database) Undefined

func (o *Database) Undefined() bool

Undefined 是否未定义.

type Service

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

Service 服务操作.

func (*Service) Master

func (o *Service) Master() *xorm.Session

Master 读取主库连接.

Example
bean := &example{}
service := &exampleService{}
exists, err := service.Master().Get(bean)

if err != nil {
	println("service error:", err.Error())
	return
}

if exists {
	println("service found")
} else {
	println("service not found")
}
Output:

func (*Service) Slave

func (o *Service) Slave() *xorm.Session

Slave 读取从库连接.

Example
bean := &example{}
service := &exampleService{}
service.UseConnection("my")
exists, err := service.Slave().Get(bean)

if err != nil {
	println("service error:", err.Error())
	return
}

if exists {
	println("service found")
} else {
	println("service not found")
}
Output:

func (*Service) Use

func (o *Service) Use(sessions ...*xorm.Session)

Use 绑定连接.

Example
session := Connector.GetMaster()

service := &exampleService{}
service.Use(session)
Output:

func (*Service) UseConnection

func (o *Service) UseConnection(connection string)

UseConnection 绑定连接名称.

Example
// [config.yaml]
//
// databases:
//   my:
//     driver: "mysql"
//     dsn:
//       - "user:pass@tcp(192.168.1.100:3306)/schema?charset=utf8" # master
//       - "user:pass@tcp(192.168.1.101:3306)/schema?charset=utf8" # slave1
//       - "user:pass@tcp(192.168.1.102:3306)/schema?charset=utf8" # slave2
//       - "user:pass@tcp(192.168.1.103:3306)/schema?charset=utf8" # slave3
service := &exampleService{}
service.UseConnection("my")
Output:

type TransactionHandler

type TransactionHandler func(ctx context.Context, sess *xorm.Session) error

TransactionHandler 事务回调.

参数 ctx 是日志上下文, 参数 sess 为DB连接. 当返回 error 后不再执行后续回调.

Jump to

Keyboard shortcuts

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