db

package
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: May 31, 2023 License: Apache-2.0 Imports: 24 Imported by: 0

README

db

mysql 基础库,开放有限接口,支持日志、opentracing 和 prometheus 监控。

配置

DB 配置,格式为 DB_${NAME}_DSN,内容参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name

必须设置 parseTime 选项。设置好了就可以通过 ${NAME} 获取 DB 连接池。

时区问题参考 https://www.jianshu.com/p/3f7fc9093db4

示例

import "context"
import "github.com/learninto/goutil/db"

ctx := context.Background()
c := db.Get(ctx, "default")

sql := "insert into foo(id) values(1)"
q := SQLUpdate("foo", sql)
result, err := c.ExecContext(ctx, q)

// 执行 db 事务
err := c.ExecTx(ctx, func(ctx context.Context, tx db.Conn) error {
	sql := "insert into foo(id) values(1)"
	q := SQLUpdate("foo", sql)
	result, err := c.ExecContext(ctx, q)
	if err != nil {
		return err
	}

	sql := "insert into foo(id) values(2)"
	q := SQLUpdate("foo", sql)
	result, err = tx.ExecContext(ctx, q)
	if err != nil {
		return err
	}

	return nil
})

Documentation

Overview

Package db 提供 mysql 封装

Index

Constants

View Source
const FieldLogicEgt = 201

FieldLogicEgt 过滤逻辑 201:>=

View Source
const FieldLogicElt = 301

FieldLogicElt 过滤逻辑 301: <=;

View Source
const FieldLogicEq = 100

FieldLogicEq 过滤逻辑 100:= ;

View Source
const FieldLogicGt = 200

FieldLogicGt 过滤逻辑 200:>;

View Source
const FieldLogicIn = 500

FieldLogicIn 过滤逻辑 500: in

View Source
const FieldLogicLeftLike = 1

FieldLogicLeftLike 过滤逻辑 1:左 like;

View Source
const FieldLogicLike = 0

FieldLogicLike 过滤逻辑 0:like ;

View Source
const FieldLogicLt = 300

FieldLogicLt 过滤逻辑 300 <;

View Source
const FieldLogicNeq = 400

FieldLogicNeq 过滤逻辑 400: <>;

View Source
const FieldLogicNotIn = 501

FieldLogicNotIn 过滤逻辑 500: not in

View Source
const FieldLogicRightLike = 2

FieldLogicRightLike 过滤逻辑 2:右 like;

View Source
const FieldTypeDate = 100

FieldTypeDate 日期

View Source
const FieldTypeDateTime = 101

FieldTypeDateTime 日期时间

View Source
const FieldTypeInteger = 201

FieldTypeInteger 整数

View Source
const FieldTypeListMultiple = 401

FieldTypeListMultiple 列表(可多选)

View Source
const FieldTypeListOne = 400

FieldTypeListOne 列表(只能单选)

View Source
const FieldTypePositiveInteger = 200

FieldTypePositiveInteger 正整数(包含0)

View Source
const FieldTypePositiveRealNumber = 200

FieldTypePositiveRealNumber 正实数(包含0)

View Source
const FieldTypeRealNumber = 301

FieldTypeRealNumber 实数

View Source
const FieldTypeText = 0

FieldTypeText 文本

View Source
const IsMultipleFalse = 0

IsMultipleFalse 是否多重应用条件。是指在sql中,该过滤值在多个子查询中需要用到。 0:否;100:是

View Source
const IsMultipleTrue = 100

IsMultipleTrue 是否多重应用条件。是指在sql中,该过滤值在多个子查询中需要用到。 0:否;100:是

Variables

This section is empty.

Functions

func IsDuplicateEntryErr

func IsDuplicateEntryErr(err error) bool

IsDuplicateEntryErr 判断是否为唯一键冲突错误

func IsNoRowsErr

func IsNoRowsErr(err error) bool

IsNoRowsErr 判断是否为 ErrNoRows 错误

func NotFound added in v1.2.6

func NotFound(err error) bool

NotFound returns true if err is a not found error. This error is returned by ScanOne if there were no rows.

func Reset

func Reset()

Reset 关闭所有 DB 连接 新调用 Get 方法时会使用最新 DB 配置创建连接

如果在配置中开启 HOT_LOAD_DB 开关,则每次下发配置都会重置 DB 连接!

func ScanAll added in v1.2.6

func ScanAll(dst interface{}, rows Rows) error

ScanAll iterates all rows to the end. After iterating it closes the rows, and propagates any errors that could pop up. It expects that destination should be a slice. For each row it scans data and appends it to the destination slice. ScanAll supports both types of slices: slice of structs by a pointer and slice of structs by value, for example:

type User struct {
    ID    string
    Name  string
    Email string
    Age   int
}

var usersByPtr []*User
var usersByValue []User

Both usersByPtr and usersByValue are valid destinations for ScanAll function.

Before starting, ScanAll resets the destination slice, so if it's not empty it will overwrite all existing elements.

func ScanOne added in v1.2.6

func ScanOne(dst interface{}, rows Rows) error

ScanOne iterates all rows to the end and makes sure that there was exactly one row otherwise it returns an error. Use NotFound function to check if there were no rows. After iterating ScanOne closes the rows, and propagates any errors that could pop up. It scans data from that single row into the destination.

func ScanRow added in v1.2.6

func ScanRow(dst interface{}, rows Rows) error

ScanRow creates a new RowScanner and calls RowScanner.Scan that scans current row data into the destination. It's just a helper function if you don't bother with efficiency and don't want to instantiate a new RowScanner before iterating the rows, so it could cache the reflection work between Scan calls. See RowScanner for details.

Types

type C

type C struct {
	TableName            string   `json:"-"`
	Data                 string   `json:"data"`
	OnDuplicateKeyUpdate []string `json:"on_duplicate_key_update"`
}

U 更新

func (C) BuildSQL

func (m C) BuildSQL(ctx context.Context) (sql string, err error)

type Conn

type Conn interface {
	ExecContext(ctx context.Context, query Query, args ...interface{}) (sql.Result, error)
	QueryContext(ctx context.Context, query Query, args ...interface{}) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query Query, args ...interface{}) *sql.Row
}

Conn 简单 DB 接口。用于统一非事务和事务业务逻辑

type DB

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

DB 对象,有限开放 sql.DB 功能,支持上报 metrics

func Get

func Get(ctx context.Context, name string) *DB

Get 根据配置名字创建并返回 DB 连接池对象

DB 配置名字格式为 DB_{$name}_DSN DB 配置内容格式请参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name Get 是并发安全的,可以在多协程下使用

func (*DB) ExecContext

func (db *DB) ExecContext(ctx context.Context, query Query, args ...interface{}) (sql.Result, error)

ExecContext 执行查询,无返回数据

func (*DB) ExecTx

func (db *DB) ExecTx(ctx context.Context, f TxFunc) error

ExecTx 执行一次事务,回调函数返回 err 或者 panic 或者 ctx 取消都会回滚事务。 返回的 err 为 Commit 或者 Rollback 的错误

func (*DB) QueryContext

func (db *DB) QueryContext(ctx context.Context, query Query, args ...interface{}) (*sql.Rows, error)

QueryContext 执行查询,返回多行数据

func (*DB) QueryRowContext

func (db *DB) QueryRowContext(ctx context.Context, query Query, args ...interface{}) *sql.Row

QueryRowContext 执行查询,至多返回一行数据

type F

type F struct {
	// Comment: 字段名称。 用于后端 构造sql。  如果是多重应用条件,则成为占位名称标识
	FieldName string `json:"field_name"`
	// Comment: 字段类型。 用于前端 不同输入控件,以及限制输入的内容。 0:文本;100: 日期  101:日期时间;200:正整数(包含0);201:整数;300:正实数(包含0);301:实数; 400:列表(只能单选);401:列表(可多选)
	FieldType int64 `json:"field_type"`
	// Comment: 过滤逻辑。 用于前端:显示查询条件逻辑; 用于后端 构造sql。 0:like ;1:左 like;2:右 like;100:= ;200:>; 201:>=  300 <;301: <=; 400: <>;500: in
	FieldLogic int64 `json:"field_logic"`
	// Comment: 是否多重应用条件。是指在sql中,该过滤值在多个子查询中需要用到。 0:否;100:是
	// Default: 0
	IsMultiple int64 `json:"is_multiple"`
	// Comment:值
	Value string `json:"value"`
}

F 筛选条件

type Q

type Q struct {
	Sql            string `json:"sql"`
	Filters        []F    `json:"filters"`
	ReplaceOrderBy string `json:"replace_order_by"`
	ReplaceGroupBy string `json:"replace_group_by"`
	CurrentPage    int64  `json:"current_page"`
	PageSize       int64  `json:"page_size"`
}

Q 查询

func (Q) BuildFilter added in v1.2.7

func (m Q) BuildFilter(ctx context.Context, filters []F, sql string) (string, error)

BuildFilter 获取追加的筛选条件

func (Q) BuildSql

func (m Q) BuildSql(ctx context.Context) (sql string, err error)

BuildSql 构建SQL

type Query

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

Query sql 查询对象

func SQLDelete

func SQLDelete(table string, sql string) Query

SQLDelete 构造 delete 查询

func SQLInsert

func SQLInsert(table string, sql string) Query

SQLInsert 构造 insert 查询

func SQLSelect

func SQLSelect(table string, sql string) Query

SQLSelect 构造 select 查询

func SQLUpdate

func SQLUpdate(table string, sql string) Query

SQLUpdate 构造 update 查询

type Row

type Row interface {
	Scan(dest ...interface{}) error
}

type RowScanner added in v1.2.6

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

RowScanner embraces Rows and exposes the Scan method that allows scanning data from the current row into the destination. The first time the Scan method is called it parses the destination type via reflection and caches all required information for further scans. Due to this caching mechanism, it's not allowed to call Scan for destinations of different types, the behavior is unknown in that case. RowScanner doesn't proceed to the next row nor close them, it should be done by the client code.

The main benefit of using this type directly is that you can instantiate a RowScanner and manually iterate over the rows and control how data is scanned from each row. This can be beneficial if the result set is large and you don't want to allocate a slice for all rows at once as it would be done in ScanAll.

ScanOne and ScanAll both use RowScanner type internally.

func NewRowScanner added in v1.2.6

func NewRowScanner(rows Rows) *RowScanner

NewRowScanner returns a new instance of the RowScanner.

func (*RowScanner) Scan added in v1.2.6

func (rs *RowScanner) Scan(dst interface{}) error

Scan scans data from the current row into the destination. On the first call it caches expensive reflection work and uses it the future calls. See RowScanner for details.

type Rows added in v1.2.6

type Rows interface {
	Close() error
	Err() error
	Next() bool
	Columns() ([]string, error)
	Scan(dest ...interface{}) error
}

Rows is an abstract database rows that dbscan can iterate over and get the data from. This interface is used to decouple from any particular database library.

type Tx

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

Tx 事务对象简单封装

func (*Tx) ExecContext

func (tx *Tx) ExecContext(ctx context.Context, query Query, args ...interface{}) (sql.Result, error)

ExecContext 执行写查询 不鼓励在事务中使用读查询,所以只提供 ExecContext 方法 框架会根据返回错误自动提交或者回滚,所以不提供相应方法

func (*Tx) QueryContext

func (tx *Tx) QueryContext(ctx context.Context, query Query, args ...interface{}) (*sql.Rows, error)

QueryContext 在事务中查询多行数据

func (*Tx) QueryRowContext

func (tx *Tx) QueryRowContext(ctx context.Context, query Query, args ...interface{}) *sql.Row

QueryRowContext 在事务中查询单行数据

type TxFunc

type TxFunc func(ctx context.Context, tx Conn) error

TxFunc 事务函数,返回 err 会回滚未提交事务,否则自动提交事务

type U

type U struct {
	Filters []F    `json:"filters"`
	Data    string `json:"data"`
	SQL     string `json:"sql"` //
}

U 更新

func (U) BuildSQL

func (m U) BuildSQL(ctx context.Context) (sql string, err error)

BuildSQL 构建SQL

Jump to

Keyboard shortcuts

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