sqlmer

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2021 License: MIT Imports: 12 Imported by: 0

README

sqlmer

Go

功能简介

数据库访问库,目前支持MySql和Sql Server。

  • SQL语句提供了统一的 命名参数索引参数 语法,可直观的使用 map 作为SQL语句参数,并以 map 或 slice 方式返回;
  • 提供了面向map的 参数结果集 交互接口,事务和非事务访问均可通过相同接口完成;
  • 扩展了原生 sql.Rows/sql.Row,使其支持 MapScan 以及 SliceScan;

API文档

https://pkg.go.dev/github.com/bunnier/sqlmer

Tips: 主交互接口为DbClient

简单样例

func main() {
	// 获取DbClient,这里使用SqlServer做示范,MySql也提供了一致的API和相应的参数解析逻辑。
	dbClient, err := data.NewMsSqlDbClient(
		"server=127.0.0.1:1433; database=test; user id=dev;password=qwer1234;",
		data.WithConnTimeout(time.Second*15), // 连接超时。
		data.WithExecTimeout(time.Second*15), // 读写超时(执行语句时候,如果没有指定超时时间,默认用这个)。
	)
	if err != nil {
		fmt.Println(err)
		return
	}

	// 创建测试表。
	_, err = dbClient.Execute(`
CREATE TABLE MainDemo(
	Id INT PRIMARY KEY IDENTITY(1,1) NOT NULL,
	Name VARCHAR(10) NOT NULL,
	Age INT NOT NULL
)`)
	if err != nil {
		log.Fatal(err)
		return
	}

	// 有超时时间的查询。
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*1)
	defer cancel()
	_, err = dbClient.ExecuteContext(ctx, "WAITFOR DELAY '00:00:02'")
	if err != nil {
		fmt.Println("timeout: " + err.Error()) // 预期内的超时~
	}

	// 索引方式插入数据,@p1...@pn,分别对应第1-n个参数。
	_, err = dbClient.Execute("INSERT INTO MainDemo(Name, Age) VALUES(@p1, @p2)", "rui", 1)
	if err != nil {
		log.Fatal(err)
		return
	}
	_, err = dbClient.Execute("INSERT INTO MainDemo(Name, Age) VALUES(@p1, @p2)", "bao", 2)
	if err != nil {
		log.Fatal(err)
		return
	}

	// 命名参数查询数据,命名参数采用map,key为sql语句@之后的参数名,value为值。
	data, err := dbClient.Get("SELECT * FROM MainDemo WHERE Name=@name", map[string]interface{}{"name": "rui"})
	if err != nil {
		log.Fatal(err)
		return
	}
	fmt.Println(data) // map方式返回,需要结构的,需要自己转换。

	// 获取第一行第一列。
	name, err := dbClient.Scalar("SELECT Name FROM MainDemo WHERE Name=@p1", "rui")
	if err != nil {
		log.Fatal(err)
		return
	}
	
	// 返回interface{},类型可以自己转换。已经统一了Sql Server和MySql返回的类型(注意:Decimal使用string返回)。
	fmt.Println(name.(string)) 

	// 获取增强后的sql.Rows(支持SliceScan、MapScan)。
	sliceRows, err := dbClient.Rows("SELECT Name, GETDATE() FROM MainDemo WHERE Name IN (@p1, @p2)", "rui", "bao")
	if err != nil {
		log.Fatal(err)
		return
	}
	for sliceRows.Next() {
		sliceRow, err := sliceRows.SliceScan() // SliceScan用[]interface{}方式返回。
		if err != nil {
			log.Fatal(err)
			return
		}
		fmt.Println(sliceRow...)
	}

	if sliceRows.Err() != nil {
		log.Fatal(err)
		return
	}

	// 删除测试表。
	_, err = dbClient.Execute("DROP TABLE MainDemo")
	if err != nil {
		log.Fatal(err)
		return
	}
}

测试用例

运行测试用例需要:

  1. 配置test_conf.yml文件,目前必须 SqlServer/MySql 均配置上才能完整运行测试用例;
  2. 调用go run ./internal/testcmd/main.go -a PREPARE -c test_conf.yml来准备环境;
  3. 测试结束后可以通过go run ./internal/testcmd/main.go -a CLEAN -c test_conf.yml销毁测试表;

如果你和我一样使用VSCode作为开发工具,可在配置好test_conf.yml之后,直接使用.vscode中编写好的Task来准备环境。

Documentation

Index

Constants

View Source
const (
	SqlServeDriver = "sqlserver" // SqlServer 驱动名称。
	MySqlDriver    = "mysql"     // MsSql 驱动名称。
)

Variables

View Source
var ErrConnect = errors.New("sqlmer: connect")

ErrConnect 是数据库连接相关错误。

View Source
var ErrSql = errors.New("sqlmer: sql")

ErrSql 是SQL语句相关错误。

View Source
var ErrTran = errors.New("sqlmer: transaction")

ErrTran 是数据库事务相关错误。

Functions

This section is empty.

Types

type BindSqlArgsFunc

type BindSqlArgsFunc func(string, ...interface{}) (string, []interface{}, error)

BindSqlArgsFunc 定义用于预处理 sql 语句与参数的函数。

type DbClient

type DbClient interface {
	// CreateTransaction 用于开始一个事务。
	CreateTransaction() (TransactionKeeper, error)

	// ConnectionString 用于获取当前实例所使用的数据库连接字符串。
	ConnectionString() string

	// Scalar 用于获取查询的第一行第一列的值。
	Scalar(sqlText string, args ...interface{}) (interface{}, error)

	// ScalarContext 用于获取查询的第一行第一列的值。
	ScalarContext(context context.Context, sqlText string, args ...interface{}) (interface{}, error)

	// Execute 用于执行非查询SQL语句,并返回所影响的行数。
	Execute(sqlText string, args ...interface{}) (int64, error)

	// ExecuteContext 用于执行非查询SQL语句,并返回所影响的行数。
	ExecuteContext(context context.Context, sqlText string, args ...interface{}) (int64, error)

	// SizedExecute 用于执行非查询SQL语句,并断言所影响的行数。若影响的函数不正确,抛出异常。
	SizedExecute(expectedSize int64, sqlText string, args ...interface{}) error

	// SizedExecuteContext 用于执行非查询SQL语句,并断言所影响的行数。若影响的函数不正确,抛出异常。
	SizedExecuteContext(context context.Context, expectedSize int64, sqlText string, args ...interface{}) error

	// Exists 用于判断给定的查询的结果是否至少包含1行。
	Exists(sqlText string, args ...interface{}) (bool, error)

	// ExistsContext 用于判断给定的查询的结果是否至少包含1行。
	ExistsContext(context context.Context, sqlText string, args ...interface{}) (bool, error)

	// Get 用于获取查询结果的第一行记录。
	Get(sqlText string, args ...interface{}) (map[string]interface{}, error)

	// GetContext 用于获取查询结果的第一行记录。
	GetContext(context context.Context, sqlText string, args ...interface{}) (map[string]interface{}, error)

	// SliceGet 用于获取查询结果得行序列。
	SliceGet(sqlText string, args ...interface{}) ([]map[string]interface{}, error)

	// SliceGetContext 用于获取查询结果得行序列。
	SliceGetContext(context context.Context, sqlText string, args ...interface{}) ([]map[string]interface{}, error)

	// Rows 用于获取查询结果得行序列。
	Rows(sqlText string, args ...interface{}) (*sqlen.EnhanceRows, error)

	// RowsContext 用于获取查询结果得行序列。
	RowsContext(context context.Context, sqlText string, args ...interface{}) (*sqlen.EnhanceRows, error)
}

DbClient 定义了数据库访问客户端。

type DbClientConfig

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

func NewDbClientConfig

func NewDbClientConfig(driver string, connectionString string, options ...DbClientOption) *DbClientConfig

NewDbClientConfig 创建一个数据库连接配置。

type DbClientOption

type DbClientOption func(config *DbClientConfig)

DbClientOption 是 DbClientConfig 的可选配置。

func WithBindArgsFunc

func WithBindArgsFunc(argsFunc BindSqlArgsFunc) DbClientOption

WithBindArgsFunc 用于为 DbClientConfig 设置处理参数的函数。

func WithConnTimeout

func WithConnTimeout(timeout time.Duration) DbClientOption

WithConnTimeout 用于为 DbClientConfig 设置获取数据库连接的超时时间。

func WithExecTimeout

func WithExecTimeout(timeout time.Duration) DbClientOption

WithExecTimeout 用于为 DbClientConfig 设置默认的执行超时时间。

type MsSqlDbClient

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

MsSqlDbClient 是针对 SqlServer 的 DbClient 实现。

func NewMsSqlDbClient

func NewMsSqlDbClient(connectionString string, options ...DbClientOption) (*MsSqlDbClient, error)

NewMsSqlDbClient 用于创建一个 MsSqlDbClient。

func (*MsSqlDbClient) ConnectionString

func (client *MsSqlDbClient) ConnectionString() string

ConnectionString 用于获取当前实例所使用的数据库连接字符串。

func (*MsSqlDbClient) CreateTransaction

func (client *MsSqlDbClient) CreateTransaction() (TransactionKeeper, error)

CreateTransaction 用于开始一个事务。

func (*MsSqlDbClient) Execute

func (client *MsSqlDbClient) Execute(sqlText string, args ...interface{}) (int64, error)

Execute 用于执行非查询SQL语句,并返回所影响的行数。

func (*MsSqlDbClient) ExecuteContext

func (client *MsSqlDbClient) ExecuteContext(ctx context.Context, sqlText string, args ...interface{}) (int64, error)

ExecuteContext 用于执行非查询 sql 语句,并返回所影响的行数。

func (*MsSqlDbClient) Exists

func (client *MsSqlDbClient) Exists(sqlText string, args ...interface{}) (bool, error)

Exists 用于判断给定的查询的结果是否至少包含1行。

func (*MsSqlDbClient) ExistsContext

func (client *MsSqlDbClient) ExistsContext(ctx context.Context, sqlText string, args ...interface{}) (bool, error)

ExistsContext 用于判断给定的查询的结果是否至少包含1行。

func (*MsSqlDbClient) Get

func (client *MsSqlDbClient) Get(sqlText string, args ...interface{}) (map[string]interface{}, error)

Get 用于获取查询结果的第一行记录。

func (*MsSqlDbClient) GetContext

func (client *MsSqlDbClient) GetContext(ctx context.Context, sqlText string, args ...interface{}) (map[string]interface{}, error)

GetContext 用于获取查询结果的第一行记录。

func (*MsSqlDbClient) Rows

func (client *MsSqlDbClient) Rows(sqlText string, args ...interface{}) (*sqlen.EnhanceRows, error)

Rows 用于获取读取数据的游标 sql.Rows。

func (*MsSqlDbClient) RowsContext

func (client *MsSqlDbClient) RowsContext(ctx context.Context, sqlText string, args ...interface{}) (*sqlen.EnhanceRows, error)

RowsContext 用于获取读取数据的游标 sql.Rows。

func (*MsSqlDbClient) Scalar

func (client *MsSqlDbClient) Scalar(sqlText string, args ...interface{}) (interface{}, error)

Scalar 用于获取查询的第一行第一列的值。

func (*MsSqlDbClient) ScalarContext

func (client *MsSqlDbClient) ScalarContext(ctx context.Context, sqlText string, args ...interface{}) (interface{}, error)

ScalarContext 用于获取查询的第一行第一列的值。

func (*MsSqlDbClient) SizedExecute

func (client *MsSqlDbClient) SizedExecute(expectedSize int64, sqlText string, args ...interface{}) error

SizedExecute 用于执行非查询 sql 语句,并断言所影响的行数。若影响的函数不正确,抛出异常。

func (*MsSqlDbClient) SizedExecuteContext

func (client *MsSqlDbClient) SizedExecuteContext(ctx context.Context, expectedSize int64, sqlText string, args ...interface{}) error

SizedExecuteContext 用于执行非查询 sql 语句,并断言所影响的行数。若影响的函数不正确,抛出异常。

func (*MsSqlDbClient) SliceGet

func (client *MsSqlDbClient) SliceGet(sqlText string, args ...interface{}) ([]map[string]interface{}, error)

SliceGet 用于获取查询结果得行序列。

func (*MsSqlDbClient) SliceGetContext

func (client *MsSqlDbClient) SliceGetContext(ctx context.Context, sqlText string, args ...interface{}) ([]map[string]interface{}, error)

SliceGetContext 用于获取查询结果得行序列。

type MySqlDbClient

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

MySqlDbClient 是针对 MySql 的 DbClient 实现。

func NewMySqlDbClient

func NewMySqlDbClient(connectionString string, options ...DbClientOption) (*MySqlDbClient, error)

NewMySqlDbClient 用于创建一个 MySqlDbClient。

func (*MySqlDbClient) ConnectionString

func (client *MySqlDbClient) ConnectionString() string

ConnectionString 用于获取当前实例所使用的数据库连接字符串。

func (*MySqlDbClient) CreateTransaction

func (client *MySqlDbClient) CreateTransaction() (TransactionKeeper, error)

CreateTransaction 用于开始一个事务。

func (*MySqlDbClient) Execute

func (client *MySqlDbClient) Execute(sqlText string, args ...interface{}) (int64, error)

Execute 用于执行非查询SQL语句,并返回所影响的行数。

func (*MySqlDbClient) ExecuteContext

func (client *MySqlDbClient) ExecuteContext(ctx context.Context, sqlText string, args ...interface{}) (int64, error)

ExecuteContext 用于执行非查询 sql 语句,并返回所影响的行数。

func (*MySqlDbClient) Exists

func (client *MySqlDbClient) Exists(sqlText string, args ...interface{}) (bool, error)

Exists 用于判断给定的查询的结果是否至少包含1行。

func (*MySqlDbClient) ExistsContext

func (client *MySqlDbClient) ExistsContext(ctx context.Context, sqlText string, args ...interface{}) (bool, error)

ExistsContext 用于判断给定的查询的结果是否至少包含1行。

func (*MySqlDbClient) Get

func (client *MySqlDbClient) Get(sqlText string, args ...interface{}) (map[string]interface{}, error)

Get 用于获取查询结果的第一行记录。

func (*MySqlDbClient) GetContext

func (client *MySqlDbClient) GetContext(ctx context.Context, sqlText string, args ...interface{}) (map[string]interface{}, error)

GetContext 用于获取查询结果的第一行记录。

func (*MySqlDbClient) Rows

func (client *MySqlDbClient) Rows(sqlText string, args ...interface{}) (*sqlen.EnhanceRows, error)

Rows 用于获取读取数据的游标 sql.Rows。

func (*MySqlDbClient) RowsContext

func (client *MySqlDbClient) RowsContext(ctx context.Context, sqlText string, args ...interface{}) (*sqlen.EnhanceRows, error)

RowsContext 用于获取读取数据的游标 sql.Rows。

func (*MySqlDbClient) Scalar

func (client *MySqlDbClient) Scalar(sqlText string, args ...interface{}) (interface{}, error)

Scalar 用于获取查询的第一行第一列的值。

func (*MySqlDbClient) ScalarContext

func (client *MySqlDbClient) ScalarContext(ctx context.Context, sqlText string, args ...interface{}) (interface{}, error)

ScalarContext 用于获取查询的第一行第一列的值。

func (*MySqlDbClient) SizedExecute

func (client *MySqlDbClient) SizedExecute(expectedSize int64, sqlText string, args ...interface{}) error

SizedExecute 用于执行非查询 sql 语句,并断言所影响的行数。若影响的函数不正确,抛出异常。

func (*MySqlDbClient) SizedExecuteContext

func (client *MySqlDbClient) SizedExecuteContext(ctx context.Context, expectedSize int64, sqlText string, args ...interface{}) error

SizedExecuteContext 用于执行非查询 sql 语句,并断言所影响的行数。若影响的函数不正确,抛出异常。

func (*MySqlDbClient) SliceGet

func (client *MySqlDbClient) SliceGet(sqlText string, args ...interface{}) ([]map[string]interface{}, error)

SliceGet 用于获取查询结果得行序列。

func (*MySqlDbClient) SliceGetContext

func (client *MySqlDbClient) SliceGetContext(ctx context.Context, sqlText string, args ...interface{}) ([]map[string]interface{}, error)

SliceGetContext 用于获取查询结果得行序列。

type TransactionKeeper

type TransactionKeeper interface {
	// DbClient 实现了数据库访问客户端的功能。
	DbClient

	// Commit 用于提交事务。
	Commit() error

	// Rollback 用于回滚事务。
	Rollback() error

	// Close 用于优雅关闭事务,创建事务后应defer执行本方法。
	Close() error
}

TransactionKeeper 是一个定义数据库事务容器。

Directories

Path Synopsis
internal
testcmd command

Jump to

Keyboard shortcuts

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