sqlxx

package module
v1.3.4 Latest Latest
Warning

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

Go to latest
Published: May 6, 2024 License: MIT Imports: 18 Imported by: 0

README

sqlx template & database factory extension

Features

  • sql template
  • database factory

更新版本

GOPROXY=https://goproxy.cn go list -m github.com/gnodux/sqlxx
GOPROXY=https://proxy.golang.org go list -m github.com/gnodux/sqlxx

usage

Documentation

Index

Constants

View Source
const (

	// TagDS 数据源
	TagDS = "ds"
	// TagSQL sql模版(或inline sql)
	TagSQL = "sql"

	// TagTx 事务级别
	TagTx = "tx"

	// TagReadonly 事务是否只读
	TagReadonly = "readonly"

	// TxDefault 默认事务级别
	TxDefault = "Default"

	// TxReadUncommitted 事务级别:ReadUncommitted
	TxReadUncommitted = "ReadUncommitted"

	// TxReadCommitted 事务级别:ReadCommitted
	TxReadCommitted = "ReadCommitted"

	// TxWriteCommitted 事务级别:WriteCommitted
	TxWriteCommitted = "WriteCommitted"

	// TxRepeatableRead 事务级别:RepeatableRead
	TxRepeatableRead = "RepeatableRead"

	// TxSnapshot 事务级别:Snapshot
	TxSnapshot = "Snapshot"

	// TxSerializable 事务级别:Serializable
	TxSerializable = "Serializable"

	// TxLinearizable 事务级别:Linearizable
	TxLinearizable = "Linearizable"
)

Variables

View Source
var (
	ErrNilDriver = errors.New("driver is nil")
	ErrNilDB     = errors.New("DB is nil")
)
View Source
var (
	DefaultDriver = dialect.MySQL
	MySQL         = dialect.MySQL
	SQLServer     = dialect.SQLServer
	Drivers       = map[string]*dialect.Driver{
		"mysql": MySQL,
		"mssql": SQLServer,
	}
)
View Source
var (
	DefaultName = "Default"
	//StdFactory default connection manager
	StdFactory = NewFactory(DefaultName)
	//Get a db from
	Get = StdFactory.Get
	//MustGet a db,if db not exists,raise a panic
	MustGet = StdFactory.MustGet
	//Set a db
	Set = StdFactory.Set
	//SetConstructor set a db with constructors func
	SetConstructor = StdFactory.SetConstructor
	//CreateAndSet initialize a db
	CreateAndSet = StdFactory.CreateAndSet

	OpenDB = StdFactory.Open

	//SetTemplateFS set sql template from filesystem
	SetTemplateFS = StdFactory.SetTemplateFS

	//ClearTemplateFS clear sql template from filesystem
	ClearTemplateFS = StdFactory.ClearTemplateFS

	//Shutdown manager and close all db
	Shutdown = StdFactory.Shutdown
)
View Source
var (
	ManagerType       = reflect.TypeOf((*Factory)(nil))
	DBType            = reflect.TypeOf((*DB)(nil))
	ExecFuncType      = reflect.TypeOf(ExecFunc(nil))
	NamedExecFuncType = reflect.TypeOf(NamedExecFunc(nil))
	TxFuncType        = reflect.TypeOf(TxFunc(nil))
)
View Source
var (
	NameFunc = utils.LowerCase
)

Functions

func Boost

func Boost(dest interface{}, ds string) error

Boost 对mapper的Field进行wrap处理、绑定数据源、绑定sql模版、绑定事务级别、绑定是否只读等 dest: mapper对象 ds: 数据源

func BoostMapper

func BoostMapper(dest interface{}, factory *Factory, ds string) error

BoostMapper 对mapper的Field进行wrap处理、绑定数据源、绑定sql模版、绑定事务级别、绑定是否只读等

change: 2023-7-12 修改绑定策略,从延迟绑定修改到boost时绑定,动态打开数据库的需求不高,且模版延迟绑定和获取数据库需要使用到锁,对性能有一定影响

func EvalAfterHook

func EvalAfterHook(entity any) error

func EvalAfterHooks

func EvalAfterHooks[T any](entities ...T) error

func EvalBeforeHook

func EvalBeforeHook(entity any) error

EvalBeforeHook eval before hook 如果entity是nil,那么不会调用任何hook 如果entity是struct 而非指针,那么在调用EvalBeforeHook之前,需要先将entity转换为指针

func EvalBeforeHooks

func EvalBeforeHooks[T any](entities ...T) error

func GetWith

func GetWith(p reflect.Type, db *DB, templateList []string, args []any) (any, error)

func MakeFuncMap

func MakeFuncMap(driver *dialect.Driver) template.FuncMap

func NamedGetWith

func NamedGetWith(p reflect.Type, db *DB, templateList []string, arg any) (any, error)

func NamedSelectWith

func NamedSelectWith(p reflect.Type, db *DB, templateList []string, arg any) (any, error)

func NewMapper

func NewMapper[T any](dataSource string) (*T, error)

NewMapper 创建一个mapper dataSource: 数据源

func NewMapperWith

func NewMapperWith[T any](factory *Factory, dataSource string) (*T, error)

NewMapperWith 创建一个mapper factory: 数据库管理器 dataSource: 数据源

func SelectWith

func SelectWith(p reflect.Type, db *DB, templateList []string, args []any) (any, error)

func SetLogger

func SetLogger(l Logger)

Types

type AfterDelete

type AfterDelete interface {
	AfterDelete() error
}

type AfterInsert

type AfterInsert interface {
	AfterInsert() error
}

type AfterUpdate

type AfterUpdate interface {
	AfterUpdate() error
}

type BaseMapper

type BaseMapper[T any] struct {
	*DB

	CreateTx        TxFunc `sql:"builtin/create.sql" readonly:"false" tx:"Default"`
	UpdateTx        TxFunc `sql:"builtin/update_by_id_tenant_id.sql" readonly:"false" tx:"Default"`
	UpdateByIdTx    TxFunc `sql:"builtin/update_by_id.sql" readonly:"false" tx:"Default"`
	PartialUpdateTx TxFunc `sql:"builtin/partial_update_by_id_tenant_id.sql" readonly:"false" tx:"Default"`
	DeleteTx        TxFunc `sql:"builtin/delete_by_id.sql" readonly:"false" tx:"Default"`
	EraseTx         TxFunc `sql:"builtin/erase_by_id.sql" readonly:"false" tx:"Default"`
	// contains filtered or unexported fields
}

BaseMapper 基础的ORM功能 1. 默认的CRUD操作 2. 表达式查询 3. 模板查询 4. 事务操作

func (*BaseMapper[T]) AutoPartialUpdate

func (b *BaseMapper[T]) AutoPartialUpdate(useTenantId bool, entities ...T) error

AutoPartialUpdate 更新指定列.(不会自动添加租户ID作为更新条件)

useTenantId 是否使用租户ID作为更新条件

func (*BaseMapper[T]) Column

func (b *BaseMapper[T]) Column(name string) *Column

Column 获取列元数据

func (*BaseMapper[T]) CountBy

func (b *BaseMapper[T]) CountBy(where map[string]any, fns ...expr.FilterFn) (total int64, err error)

func (*BaseMapper[T]) CountByExample

func (b *BaseMapper[T]) CountByExample(entity T, filters ...expr.FilterFn) (total int64, err error)

func (*BaseMapper[T]) Create

func (b *BaseMapper[T]) Create(entities ...T) error

func (*BaseMapper[T]) DeleteBy

func (b *BaseMapper[T]) DeleteBy(builders ...expr.DeleteExprFn) (rowAffected int64, err error)

func (*BaseMapper[T]) DeleteByExample

func (b *BaseMapper[T]) DeleteByExample(example T, builders ...expr.DeleteExprFn) (effect int64, err error)

func (*BaseMapper[T]) DeleteById

func (b *BaseMapper[T]) DeleteById(tenantId any, ids ...any) error

DeleteById 根据租户ID和ID删除记录

删除使用的SQL模版是builtin/delete_by_id.sql

func (*BaseMapper[T]) EraseById

func (b *BaseMapper[T]) EraseById(tenantId any, ids ...any) error

EraseById 根据租户ID和ID擦除记录

擦除使用的SQL模版是builtin/erase_by_id.sql,该操作将完整删除记录

func (*BaseMapper[T]) Insert

func (b *BaseMapper[T]) Insert(entities ...T) error

Insert 插入数据,如果有主键,会自动填充主键

和Create不一样的是,Insert会忽略空值,仅插入有值的字段

func (*BaseMapper[T]) InsertExpr

func (b *BaseMapper[T]) InsertExpr(builders ...expr.InsertFilterFn) error

func (*BaseMapper[T]) ListById

func (b *BaseMapper[T]) ListById(tenantId any, ids ...any) (entities []T, err error)

ListById 通过ID列表查询

func (*BaseMapper[T]) Meta

func (b *BaseMapper[T]) Meta() *Entity

Meta 获取实体元数据

func (*BaseMapper[T]) PartialUpdate

func (b *BaseMapper[T]) PartialUpdate(useTenantId bool, specifiedField []string, entities ...T) error

PartialUpdate 更新指定列.(如果包含租户ID,则会自动添加租户ID作为更新条件)

useTenantId 是否使用租户ID作为更新条件

specifiedField 指定需要更新的列,如果为空则自动从实体中获取"非空"列进行更新(指定更新列名时,使用字段名而不是列名)

entities 实体列表

func (*BaseMapper[T]) Select

func (b *BaseMapper[T]) Select(builders ...expr.FilterFn) (result []T, total int64, err error)

Select 使用SelectExprBuilder构建查询 默认限制100条,如果需要更多,请使用builder中的Limit方法

func (*BaseMapper[T]) SelectByExample

func (b *BaseMapper[T]) SelectByExample(entity T, builders ...expr.FilterFn) ([]T, int64, error)

func (*BaseMapper[T]) Update

func (b *BaseMapper[T]) Update(useTenantId bool, entities ...T) error

Update 更新所有列.(如果包含租户ID,则会自动添加租户ID作为更新条件)

useTenantId 是否使用租户ID作为更新条件

如果需要更新部分列,请使用PartialUpdate

func (*BaseMapper[T]) UpdateBy

func (b *BaseMapper[T]) UpdateBy(builders ...expr.FilterFn) (effect int64, err error)

func (*BaseMapper[T]) UpdateByExample

func (b *BaseMapper[T]) UpdateByExample(newValue T, example T, builders ...expr.FilterFn) (effect int64, err error)

type BeforeDelete

type BeforeDelete interface {
	BeforeDelete() error
}

type BeforeInsert

type BeforeInsert interface {
	BeforeInsert() error
}

type BeforeUpdate

type BeforeUpdate interface {
	BeforeUpdate() error
}

type DB

type DB struct {
	*sqlx.DB
	// contains filtered or unexported fields
}

DB 数据库连接 对sqlx.DB的封装,提供更多的功能: 1. 通过模板文件生成SQL语句并执行,每个连接实例都可以拥有自己的模版系统 2. 通过expr包提供的表达式语法生成SQL语句并执行

func Open

func Open(driverName, datasource string) (*DB, error)

func OpenWith

func OpenWith(f *Factory, driver *dialect.Driver, datasource string) (*DB, error)

func (*DB) Batch

func (d *DB) Batch(ctx context.Context, opts *sql.TxOptions, fn func(tx *Tx) error) (err error)

func (*DB) Batchxx

func (d *DB) Batchxx(ctx context.Context, opts *sql.TxOptions, tpl string, fn func(tx *Tx) error) (err error)

func (*DB) ExecExpr

func (d *DB) ExecExpr(exp expr.Expr) (sql.Result, error)

ExecExpr 使用表达式进行执行

func (*DB) Execxx

func (d *DB) Execxx(sqlOrTpl string, args ...interface{}) (sql.Result, error)

func (*DB) GetExpr

func (d *DB) GetExpr(dest interface{}, exp expr.Expr, filters ...expr.FilterFn) error

func (*DB) NamedExecxx

func (d *DB) NamedExecxx(sqlOrTpl string, arg interface{}) (sql.Result, error)

func (*DB) NamedGet

func (d *DB) NamedGet(dest interface{}, query string, arg interface{}) error

func (*DB) NamedQueryxx

func (d *DB) NamedQueryxx(sqlOrTpl string, arg interface{}) (*sqlx.Rows, error)

func (*DB) NamedSelect

func (d *DB) NamedSelect(dest interface{}, sql string, arg any) (err error)

func (*DB) NamedSelectxx

func (d *DB) NamedSelectxx(dest interface{}, sqlOrTpl string, args interface{}) (err error)

func (*DB) ParseSQL

func (d *DB) ParseSQL(sqlOrTpl string, args any) (query string, err error)

ParseSQL parse sql from template 2023-7-12: 由于template的Parse方法会将{{}}中的内容当作变量,所以不再使用template.Parse方法,由BoostMapper中预先解析,减小运行时性能消耗和锁定

func (*DB) ParseTemplate

func (d *DB) ParseTemplate(name string, tpl string) (*template.Template, error)

func (*DB) ParseTemplateFS

func (d *DB) ParseTemplateFS(f fs.FS, patterns ...string) error

ParseTemplateFS parse template from filesystem。 为了保留目录结构,没有直接使用template的ParseFS(template中的ParseFS方法不会保留路径名称)

func (*DB) PrepareNamedxx

func (d *DB) PrepareNamedxx(tplName string, args any) (*sqlx.NamedStmt, error)

func (*DB) Preparexx

func (d *DB) Preparexx(sqlOrTpl string, args any) (*sqlx.Stmt, error)

func (*DB) RunPrepareNamed

func (d *DB) RunPrepareNamed(sqlOrTpl string, arg any, fn func(*sqlx.NamedStmt) error) (err error)

RunPrepareNamed run prepared statement with named args arg 如果是模版,是模版渲染参数,如果是动态SQL,则不需要(根据传入名称是否以.sql结尾判断)

func (*DB) RunPrepared

func (d *DB) RunPrepared(sqlOrTpl string, arg any, fn func(*sqlx.Stmt) error) (err error)

func (*DB) SelectExpr

func (d *DB) SelectExpr(dest interface{}, exp expr.Expr) error

SelectExpr 使用表达式进行查询

func (*DB) Selectxx

func (d *DB) Selectxx(dest interface{}, sqlOrTpl string, args ...any) error

func (*DB) SetManager

func (d *DB) SetManager(m *Factory)

func (*DB) SetTemplate

func (d *DB) SetTemplate(tpl *template.Template)

func (*DB) Template

func (d *DB) Template() *template.Template

type DBConstructor

type DBConstructor func() (*DB, error)

type ExecFunc

type ExecFunc func(args ...any) (sql.Result, error)

ExecFunc Exec 函数类型, 用于执行无返回值的SQL

func NewExecFuncWith

func NewExecFuncWith(db *DB, tpl string) ExecFunc

NewExecFuncWith 创建一个 ExecFunc db:*DB 数据库 tpl: SQL模版或者inline SQL

type Factory

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

func NewFactory

func NewFactory(name string) *Factory

func NewFactoryWithDriver

func NewFactoryWithDriver(name string, driver *dialect.Driver) *Factory

func (*Factory) BoostMapper

func (m *Factory) BoostMapper(dest any, dataSource string) error

func (*Factory) ClearTemplateFS

func (m *Factory) ClearTemplateFS()

func (*Factory) CreateAndSet

func (m *Factory) CreateAndSet(name string, fn DBConstructor) (*DB, error)

CreateAndSet 创建新的数据库连接并放入管理器中

func (*Factory) Get

func (m *Factory) Get(name string) (*DB, error)

func (*Factory) MustGet

func (m *Factory) MustGet(name string) *DB

MustGet 获取一个数据库连接,如果不存在则panic

func (*Factory) Open

func (m *Factory) Open(name, driverName, dsn string) (*DB, error)

Open 打开一个数据库连接

func (*Factory) Set

func (m *Factory) Set(name string, db *DB)

Set a database

func (*Factory) SetConstructor

func (m *Factory) SetConstructor(name string, loadFunc DBConstructor)

SetConstructor set a database constructor(Lazy create DB)

func (*Factory) SetTemplateFS

func (m *Factory) SetTemplateFS(f fs.FS, patterns ...string)

func (*Factory) Shutdown

func (m *Factory) Shutdown() error

func (*Factory) String

func (m *Factory) String() string

type GetFunc

type GetFunc[T any] func(args ...any) (T, error)

GetFunc Get 函数类型, 用于查询单条记录

type Logger

type Logger interface {
	Trace(...any)
	Tracef(string, ...any)
	Debug(...any)
	Debugf(string, ...any)
	Info(...any)
	Infof(string, ...any)

	Warn(...any)
	Warnf(string, ...any)
	Error(...any)
	Errorf(string, ...any)
}

type NamedExecFunc

type NamedExecFunc func(arg any) (sql.Result, error)

NamedExecFunc NamedExec 函数类型, 用于执行无返回值的SQL,使用命名参数

func NewNamedExecFuncWith

func NewNamedExecFuncWith(db *DB, tpl string) NamedExecFunc

NewNamedExecFuncWith 创建一个 NamedExecFunc db:*DB 数据库管理器 tpl: SQL模版或者inline SQL

type NamedGetFunc

type NamedGetFunc[T any] func(arg any) (T, error)

NamedGetFunc NamedGet 函数类型, 用于查询单条记录,使用命名参数

func NewNamedGetFuncWith

func NewNamedGetFuncWith[T any](m *Factory, db, tpl string) NamedGetFunc[T]

NewNamedGetFuncWith 创建一个 NamedGetFunc m: Factory 数据库管理器 db: 数据库名称 tpl: SQL模版或者inline SQL

type NamedSelectFunc

type NamedSelectFunc[T any] func(arg any) ([]T, error)

NamedSelectFunc NamedSelect 函数类型, 用于查询多条记录,使用命名参数

func NewNamedSelectFunc

func NewNamedSelectFunc[T any](db, tpl string) NamedSelectFunc[T]

NewNamedSelectFunc 创建一个 NamedSelectFunc db: 数据库名称 tpl: SQL模版或者inline SQL

func NewNamedSelectFuncWith

func NewNamedSelectFuncWith[T any](manager *Factory, db, tpl string) NamedSelectFunc[T]

NewNamedSelectFuncWith 创建一个 NamedSelectFunc manager: Factory 数据库管理器 db: 数据库名称 tpl: SQL模版或者inline SQL

type SelectFunc

type SelectFunc[T any] func(args ...any) ([]T, error)

SelectFunc Select 函数类型,使用位置参数

func NewSelectFunc

func NewSelectFunc[T any](db, tpl string) SelectFunc[T]

NewSelectFunc 创建一个 SelectFunc db: 数据库名称(使用默认的数据库管理器 StdFactory) tpl: SQL模版或者inline SQL

func NewSelectFuncWith

func NewSelectFuncWith[T any](m *Factory, db, tpl string) SelectFunc[T]

NewSelectFuncWith 创建一个 SelectFunc m: Factory 数据库管理器 db: 数据库名称 tpl: SQL模版或者inline SQL

type TplFS

type TplFS struct {
	FS       fs.FS
	Patterns []string
}

type Tx

type Tx struct {
	*sqlx.Tx
	// contains filtered or unexported fields
}

Tx transaction wrapper

func NewTxWith

func NewTxWith(tx *sqlx.Tx, d *DB, tpl string) *Tx

func (*Tx) ExecCurrent

func (t *Tx) ExecCurrent(args ...interface{}) (sql.Result, error)

ExecCurrent use current tpl to exec

func (*Tx) ExecExpr

func (t *Tx) ExecExpr(exp expr.Expr) (sql.Result, error)

ExecExpr 使用表达式进行执行

func (*Tx) Execxx

func (t *Tx) Execxx(sqlOrTpl string, args ...interface{}) (sql.Result, error)

func (*Tx) GetExpr

func (t *Tx) GetExpr(dest interface{}, exp expr.Expr) error

func (*Tx) Getxx

func (t *Tx) Getxx(dest any, tpl string, args ...any) error

func (*Tx) NamedExecCurrent

func (t *Tx) NamedExecCurrent(arg interface{}) (sql.Result, error)

NamedExecCurrent use current tpl to exec named statement

func (*Tx) NamedExecxx

func (t *Tx) NamedExecxx(sqlOrTpl string, arg interface{}) (sql.Result, error)

NamedExecxx use tpl to query named statement

func (*Tx) NamedGet

func (t *Tx) NamedGet(dest interface{}, query string, arg interface{}) error

func (*Tx) NamedSelect

func (t *Tx) NamedSelect(dest interface{}, sql string, arg any) (err error)

func (*Tx) Parse

func (t *Tx) Parse(tplName string, args any) (string, error)

func (*Tx) ParseAndPrepare

func (t *Tx) ParseAndPrepare(sqlOrTpl string, arg any) (*sqlx.Stmt, error)

func (*Tx) ParseAndPrepareNamed

func (t *Tx) ParseAndPrepareNamed(tplName string, arg any) (*sqlx.NamedStmt, error)

ParseAndPrepareNamed use tplName to parse and prepare named statement

func (*Tx) PrepareNamed

func (t *Tx) PrepareNamed(query string) (*sqlx.NamedStmt, error)

func (*Tx) Preparex

func (t *Tx) Preparex(query string) (*sqlx.Stmt, error)

func (*Tx) RunCurrentPrepareNamed

func (t *Tx) RunCurrentPrepareNamed(arg any, fn func(*sqlx.NamedStmt) error) (err error)

RunCurrentPrepareNamed use current tpl to prepare named statement

func (*Tx) RunCurrentPrepared

func (t *Tx) RunCurrentPrepared(arg any, fn func(*sqlx.Stmt) error) (err error)

func (*Tx) RunPrepareNamedxx

func (t *Tx) RunPrepareNamedxx(sqlOrTpl string, arg any, fn func(*sqlx.NamedStmt) error) (err error)

RunPrepareNamedxx use tplName to prepare named statement

func (*Tx) RunPreparedxx

func (t *Tx) RunPreparedxx(sqlOrTpl string, arg any, fn func(*sqlx.Stmt) error) (err error)

func (*Tx) SelectExpr

func (t *Tx) SelectExpr(dest interface{}, exp expr.Expr) error

SelectExpr 使用表达式进行查询

func (*Tx) Tpl

func (t *Tx) Tpl() string

type TxFunc

type TxFunc func(func(*Tx) error) error

TxFunc Tx 函数类型, 用于执行事务

func NewTxFuncWith

func NewTxFuncWith(db *DB, tpl string, opts *sql.TxOptions) TxFunc

NewTxFuncWith 创建一个 TxFunc db: 数据库名称 tpl: SQL模版或者inline SQL

Directories

Path Synopsis
Package expr package 用于生成sql语句
Package expr package 用于生成sql语句

Jump to

Keyboard shortcuts

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