db

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2021 License: MIT Imports: 20 Imported by: 0

README

如何判断缺少参数?参数不存在的化,我要忽略该段SQL,而不需要报错要怎么处理?

    query = ctx.NewQuery(context.TODO()).
    For("deposit").
    Select("account_number", "card_number", "card_name", "deposit_amount").
    Where("id={id} and status=0")
//query.Var("id", "1")

	d := struct {
		AccountNumber string
		CardNumber    string
		CardName      string
		DepositAmount float64
	}{}

	if err := query.Find(&d); err != nil {
		if errors.Is(err, parser.ErrParameterMissing) {
			//TODO: 因为没有给query添加id参数值,所以执行后会报错
		}
    }

但是当做查询接口的时候,使用者并不会存入全部参数,那我们应该如何处理?使用以下的写法,将避免执行时抛出错误

    query = ctx.NewQuery(context.TODO()).
    For("deposit").
    Select("account_number", "card_number", "card_name", "deposit_amount").
    Where("id={id} and status={status}","id","status")//使用第二个参数varNames, 当query当Vars里没有id或者status的话,这段Where不会被包含在最后执行的SQL里。从而避免抛出ErrParameterMissing



	d := struct {
		AccountNumber string
		CardNumber    string
		CardName      string
		DepositAmount float64
	}{}

	if err := query.Find(&d); err != nil {
		if errors.Is(err, parser.ErrParameterMissing) {
			//TODO: 不会抛出ErrParameterMissing, 因为Where已经被跳过了
		}
    }

Documentation

Index

Constants

View Source
const PagingIndex = "_pi"

PagingIndex 分頁頁碼默認變數名稱

View Source
const PagingSize = "_ps"

PagingSize 分頁大小默認變數名稱

Variables

View Source
var (
	//InstanceID ID生成器实例ID,用于分散式生成时候保持ID唯一,可以使用以下代码做环境设定
	// func init(){
	//	db.InstanceID = types.Atoi(conf.Value("server","id","1"),1)
	//}
	InstanceID int64
	//Shardings 表ID生器成集合,用于保存各个表ID生成器的当前状态
	Shardings = make(map[string]map[string]*shardingId.IdGenerator)
)
View Source
var (
	// export variables
	ErrDefaultDatabaseMissing = errors.New("Default database is missing in config file")
	ErrInvalidTransaction     = errors.New("Invalid Transaction operation")
	ErrInvalidObject          = errors.New("Invalid Object")
	ErrTooManySelectedColumns = errors.New("Too Many selected columns")
	ErrClockMovedBackwards    = errors.New("Clock Moved Backwards")
	ErrInvalidCommand         = errors.New("Invalid Command")
)
View Source
var ErrBadData = errors.New("db: Bad data for column")

ErrBadData 不符合mysql約束的無效數據 1062 : Duplicate entry for PRIMARY/UNIQUE INDEX 1048 : Symbol: ER_BAD_NULL_ERROR; SQLSTATE: 23000 Message: Column '%s' cannot be null 1406 : Symbol: ER_DATA_TOO_LONG; SQLSTATE: 22001 Message: Data too long for column '%s' at row %ld

View Source
var ErrKeyExits = errors.New("db: Duplicate entry for key")

ErrKeyExits https://dev.mysql.com/doc/refman/8.0/en/server-error-reference.html#error_er_dup_entry

View Source
var NameMapper = strings.ToLower

Functions

func Deref

func Deref(t reflect.Type) reflect.Type

Deref is Indirect for reflect.Types

func FieldByIndexes

func FieldByIndexes(v reflect.Value, indexes []int) reflect.Value

FieldByIndexes returns a value for the field given by the struct traversal for the given value.

func FieldByIndexesReadOnly

func FieldByIndexesReadOnly(v reflect.Value, indexes []int) reflect.Value

FieldByIndexesReadOnly returns a value for a particular struct traversal, but is not concerned with allocating nil pointers because the value is going to be used for reading and not setting.

func IsErr

func IsErr(err, target error) bool

IsErr 判斷是不是指定mysql錯誤

func RoundVar

func RoundVar(value interface{}) interface{}

RoundVar 修复变量精度

func ScanAll

func ScanAll(ctx context.Context, rows rowsi, dest interface{}, structOnly bool) error

func StructScan

func StructScan(ctx context.Context, rows rowsi, dest interface{}) error

func ToStruct

func ToStruct(ctx context.Context, rows *sql.Rows, to interface{}) error

ToStruct set fields with sql result

Types

type CommandError

type CommandError struct {
	Command string
	Err     error
}

func NewCommandError

func NewCommandError(command string, err error) CommandError

type Commands

type Commands struct {
	Querys
	// contains filtered or unexported fields
}

Commands a database command session

func (*Commands) Delete

func (c *Commands) Delete() *Commands

Delete the specific rows

func (*Commands) Exec

func (c *Commands) Exec() (sql.Result, error)

func (*Commands) For

func (c *Commands) For(tableName string) *Commands

For assign specific table and business for this command

func (*Commands) Insert

func (c *Commands) Insert(col string, value interface{}) *Commands

Insert data into DB

func (*Commands) NewID

func (c *Commands) NewID(tag string) (int64, error)

func (*Commands) OR

func (q *Commands) OR(cmd string, vars ...string) *Commands
EX : query.OR("id ={id} ", "id")

use vars to check the var existed in the var map

func (*Commands) RawSQL

func (c *Commands) RawSQL(raw string) *Commands

RawSQL update command text with raw sql

func (*Commands) Update

func (c *Commands) Update(col string, value interface{}) *Commands

Update assign column and value for set expression

func (*Commands) Updates

func (c *Commands) Updates(args map[string]interface{}) *Commands

Updates assign args with key-value for set expresiion

func (*Commands) Var

func (q *Commands) Var(name string, value interface{}) *Commands

func (*Commands) Vars

func (q *Commands) Vars(vars map[string]interface{}) *Commands

Vars assign variables with key-value format to the command

func (*Commands) Where

func (q *Commands) Where(cmd string, vars ...string) *Commands

Where assign

type ConnnetionString

type ConnnetionString string

func (*ConnnetionString) String

func (cs *ConnnetionString) String() string

type Context

type Context struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func (*Context) Begin

func (c *Context) Begin() error

Begin 启动事务,但是因为需要SQL来判断是要在哪一个库上启动事务,所以这里先做标志,等到第一个Command执行的时候,再执行tx的初始化

func (*Context) Commit

func (c *Context) Commit() error

func (*Context) NewCommand

func (c *Context) NewCommand(ctx context.Context) *Commands

NewCommand create a new

func (*Context) NewQuery

func (c *Context) NewQuery(ctx context.Context) *Querys

NewQuery create a new

func (*Context) PrepareContext

func (c *Context) PrepareContext(ctx context.Context, commndText string, vars map[string]interface{}, tableName string) (*sql.Stmt, string, []interface{}, error)

PrepareContext 生成mysql的Statment, 并返回解析后的SQL和变数列表

func (*Context) Rollback

func (c *Context) Rollback() error

func (*Context) TryOpenDb

func (c *Context) TryOpenDb(conn string, maxLifetime time.Duration, maxConns, minConns int) (*sql.DB, error)

TryOpenDb 尝试打开db连接, 建议sql.DB的示例,如果已经打开, 则使用已打开的sql.DB实例,每个库一个sql.DB

type Database

type Database struct {
	sync.Mutex
	// contains filtered or unexported fields
}

Database 数据库操作实例,包含ID生成状态,共享的db连线实例,设定文档

func NewDatabase

func NewDatabase(ctx context.Context, opts ...Option) *Database

NewDatabase 创建数据库操作实例 d := db.NewContext(ctx, db.WithConfig(config))

func (*Database) Close

func (d *Database) Close() error

func (*Database) NewID

func (d *Database) NewID(ctx context.Context, tableName, tag string) (int64, error)

func (*Database) NewSubID

func (d *Database) NewSubID(ctx context.Context, tableName, tag string, parendID int64) (int64, error)

func (*Database) Open

func (d *Database) Open(ctx context.Context) *Context

Open 创建一个数据库操作上下文对象

type FieldInfo

type FieldInfo struct {
	Index    []int
	Path     string
	Field    reflect.StructField
	Zero     reflect.Value
	Name     string
	Options  map[string]string
	Embedded bool
	Children []*FieldInfo
	Parent   *FieldInfo
}

A FieldInfo is metadata for a struct field.

type Filter

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

Filter 過濾器,自動類型轉換,自動索引優先

func NewFilter

func NewFilter(values map[string]string) *Filter

NewFilter 創建過濾器

func (*Filter) Map

func (f *Filter) Map(converter func(s string) interface{}, fields ...string) *Filter

Map 註冊型別轉換

func (*Filter) ToTake

func (f *Filter) ToTake() (int, int)

ToTake 提取分頁欄位

func (*Filter) ToVars

func (f *Filter) ToVars() map[string]interface{}

ToVars 型別轉換

type Mapper

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

Mapper is a general purpose mapper of names to struct fields. A Mapper behaves like most marshallers in the standard library, obeying a field tag for name mapping but also providing a basic transform function.

func NewMapper

func NewMapper(tagName string) *Mapper

NewMapper returns a new mapper using the tagName as its struct field tag. If tagName is the empty string, it is ignored.

func NewMapperFunc

func NewMapperFunc(tagName string, f func(string) string) *Mapper

NewMapperFunc returns a new mapper which optionally obeys a field tag and a struct field name mapper func given by f. Tags will take precedence, but for any other field, the mapped name will be f(field.Name)

func NewMapperTagFunc

func NewMapperTagFunc(tagName string, mapFunc, tagMapFunc func(string) string) *Mapper

NewMapperTagFunc returns a new mapper which contains a mapper for field names AND a mapper for tag values. This is useful for tags like json which can have values like "name,omitempty".

func (*Mapper) FieldByName

func (m *Mapper) FieldByName(v reflect.Value, name string) reflect.Value

FieldByName returns a field by its mapped name as a reflect.Value. Panics if v's Kind is not Struct or v is not Indirectable to a struct Kind. Returns zero Value if the name is not found.

func (*Mapper) FieldMap

func (m *Mapper) FieldMap(v reflect.Value) map[string]reflect.Value

FieldMap returns the mapper's mapping of field names to reflect values. Panics if v's Kind is not Struct, or v is not Indirectable to a struct kind.

func (*Mapper) FieldsByName

func (m *Mapper) FieldsByName(v reflect.Value, names []string) []reflect.Value

FieldsByName returns a slice of values corresponding to the slice of names for the value. Panics if v's Kind is not Struct or v is not Indirectable to a struct Kind. Returns zero Value for each name not found.

func (*Mapper) TraversalsByName

func (m *Mapper) TraversalsByName(t reflect.Type, names []string) [][]int

TraversalsByName returns a slice of int slices which represent the struct traversals for each mapped name. Panics if t is not a struct or Indirectable to a struct. Returns empty int slice for each name not found.

func (*Mapper) TraversalsByNameFunc

func (m *Mapper) TraversalsByNameFunc(t reflect.Type, names []string, fn func(int, []int) error) error

TraversalsByNameFunc traverses the mapped names and calls fn with the index of each name and the struct traversal represented by that name. Panics if t is not a struct or Indirectable to a struct. Returns the first error returned by fn or nil.

func (*Mapper) TypeMap

func (m *Mapper) TypeMap(t reflect.Type) *StructMap

TypeMap returns a mapping of field strings to int slices representing the traversal down the struct to reach the field.

type NamedStmt

type NamedStmt struct {
	Params      []string
	QueryString string
	Stmt        *sql.Stmt
}

type Option

type Option func(d *Database)

Option 变数设定

func WithConfig

func WithConfig(c model.Config) Option

WithConfig 指定设定档

type Querys

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

Query a datbase query session

func (*Querys) Count

func (q *Querys) Count() (int, error)

Count 计算返回结果

func (*Querys) Find

func (q *Querys) Find(objects interface{}) error

Find 把查询回的数据填入指定的对象,必须使用引用对象,否则会返回ErrInvalidObject异常

func (*Querys) First

func (q *Querys) First(obj interface{}) error

First 获取排序第一的记录,填入指定的对象

func (*Querys) For

func (q *Querys) For(tableName string) *Querys

--------------------------------

func (*Querys) ForModel

func (q *Querys) ForModel(obj interface{}) (*Querys, error)

func (*Querys) GroupBy

func (q *Querys) GroupBy(columns ...string) *Querys

func (*Querys) Limit

func (s *Querys) Limit(limit int) *Querys

--------------------------------

func (*Querys) NewID

func (q *Querys) NewID(tag string) (int64, error)

func (*Querys) Offset

func (s *Querys) Offset(offset int) *Querys

func (*Querys) OrderBy

func (q *Querys) OrderBy(columns ...string) *Querys

func (*Querys) OrderByDescending

func (q *Querys) OrderByDescending(columns ...string) *Querys

func (*Querys) Query

func (q *Querys) Query(scan func(rows *sql.Rows) error) error

Query 提供底层的操作接口,暴露sql的操作对象代替ORM工作

func (*Querys) QueryRow

func (q *Querys) QueryRow(scan func(row *sql.Row) error) error

QueryRow 提供底层的QueryRow操作,暴露底层sql操作对象代替ORM工作

func (*Querys) RawSQL

func (q *Querys) RawSQL(raw string) *Querys

func (*Querys) Select

func (q *Querys) Select(columns ...string) *Querys

--------------------------------- func (q *Querys) Select(columns ...Column) *Querys {

func (*Querys) SelectModel

func (q *Querys) SelectModel(object interface{}) *Querys

func (*Querys) String

func (s *Querys) String() string

func (*Querys) Take

func (q *Querys) Take(pageIndex, pageSize int) *Querys

Take 設定分頁頁碼和每頁大小

func (*Querys) Var

func (q *Querys) Var(name string, value interface{}) *Querys

Var 添加变量

func (*Querys) VarIN

func (q *Querys) VarIN(name string, values ...interface{}) *Querys

VarIN 添加IN对应的变量,值为数组

func (*Querys) Vars

func (q *Querys) Vars(vars map[string]interface{}) *Querys

Vars 批量添加变量, 同名覆盖

func (*Querys) Where

func (q *Querys) Where(cmd string, varNames ...string) *Querys
EX : query.Where("id = {id}", "id")

use vars to check the var existed in the var map

func (*Querys) WhereIN

func (q *Querys) WhereIN(cmd string, varNames ...string) *Querys
EX : query.WhereIN("id in {id}", "id")

該欄位不能是參與分片的欄位 varNames 指定关联变量名称,如果有任一关联变量名称没有赋值,则这段cmd会被忽略,不参与最终SQL

func (*Querys) WhereOR

func (q *Querys) WhereOR(cmd string, vars ...string) *Querys
EX : query.WhereOR("id ={id} ", "id")

use vars to check the var existed in the var map

func (*Querys) WhereOrIN

func (q *Querys) WhereOrIN(cmd string, varNames ...string) *Querys
EX : query.WhereOrIN("id in {id}", "id")

該欄位不能是參與分片的欄位

type Row

type Row struct {
	Mapper *Mapper
	// contains filtered or unexported fields
}

func (*Row) ColumnTypes

func (r *Row) ColumnTypes() ([]*sql.ColumnType, error)

ColumnTypes returns the underlying sql.Rows.ColumnTypes(), or the deferred error

func (*Row) Columns

func (r *Row) Columns() ([]string, error)

Columns returns the underlying sql.Rows.Columns(), or the deferred error usually returned by Row.Scan()

func (*Row) Err

func (r *Row) Err() error

Err returns the error encountered while scanning.

func (*Row) Scan

func (r *Row) Scan(dest ...interface{}) error

func (*Row) StructScan

func (r *Row) StructScan(ctx context.Context, dest interface{}) error

StructScan a single Row into dest.

type Rows

type Rows struct {
	*sql.Rows

	Mapper *Mapper
	// contains filtered or unexported fields
}

func (*Rows) StructScan

func (r *Rows) StructScan(ctx context.Context, dest interface{}) error
type Search struct {
	Unscoped bool
	// contains filtered or unexported fields
}

func (*Search) IN

func (s *Search) IN(query interface{}, values ...interface{}) *Search

func (*Search) Limit

func (s *Search) Limit(limit interface{}) *Search

func (*Search) OR

func (s *Search) OR(query interface{}, values ...interface{}) *Search

func (*Search) Offset

func (s *Search) Offset(offset interface{}) *Search

func (*Search) OrderBy

func (s *Search) OrderBy(values ...interface{}) *Search

func (*Search) OrderByDescending

func (s *Search) OrderByDescending(values ...interface{}) *Search

func (*Search) Where

func (s *Search) Where(query interface{}, values ...interface{}) *Search

type StructMap

type StructMap struct {
	Tree  *FieldInfo
	Index []*FieldInfo
	Paths map[string]*FieldInfo
	Names map[string]*FieldInfo
}

A StructMap is an index of field metadata for a struct.

func (StructMap) GetByPath

func (f StructMap) GetByPath(path string) *FieldInfo

GetByPath returns a *FieldInfo for a given string path.

func (StructMap) GetByTraversal

func (f StructMap) GetByTraversal(index []int) *FieldInfo

GetByTraversal returns a *FieldInfo for a given integer path. It is analogous to reflect.FieldByIndex, but using the cached traversal rather than re-executing the reflect machinery each time.

type Tx

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

func (*Tx) Commit

func (t *Tx) Commit() error

func (*Tx) Rollback

func (t *Tx) Rollback() error

type ValiadtionCallback

type ValiadtionCallback interface {
	Validate(func() bool) bool
}

type Validation

type Validation interface {
	IsValidate() bool
}

Directories

Path Synopsis
cli command

Jump to

Keyboard shortcuts

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