db

package
v0.0.0-...-c3ec36b Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2022 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	DatabaseNotInitialize = errors.New("数据库连接尚未初始化")
	DatabaseConnectFail   = errors.New("数据库连接失败")
	SQLError              = errors.New("数据库操作异常")
	SQLEmptyChange        = errors.New("数据无变化")
)
View Source
var ErrorNotOpen = errors.New("数据库连接失败")

一个简便的数据库操作封装

View Source
var ErrorPing = errors.New("数据库网络异常")

Functions

func Bool

func Bool(reply interface{}) (bool, error)

Bool is a helper that converts a command reply to a boolean. If err is not equal to nil, then Bool returns false, err. Otherwise Bool converts the reply to boolean as follows:

Reply type      ExecResult
integer         value != 0, nil
bulk string     strconv.ParseBool(reply)
nil             false, ErrNil
other           false, error

Deprecated: use conv package function

func BoolDefault

func BoolDefault(reply interface{}, def ...bool) bool

BoolDefault is a helper that converts a command reply to a boolean. If err is not equal to nil, then Bool returns default value Deprecated: use conv package function

func Bytes

func Bytes(reply interface{}) ([]byte, error)

Bytes is a helper that converts a command reply to a slice of bytes. If err is not equal to nil, then Bytes returns nil, err. Otherwise Bytes converts the reply to a slice of bytes as follows:

Reply type      ExecResult
bulk string     reply, nil
simple string   []byte(reply), nil
nil             nil, ErrNil
other           nil, error

Deprecated: use conv package function

func BytesDefault

func BytesDefault(reply interface{}, def ...[]byte) []byte

BytesDefault is a helper that converts a command reply to a slice of bytes. If err is not equal to nil, then Bytes returns default value Deprecated: use conv package function

func DecodePytesStruceValueToMap

func DecodePytesStruceValueToMap(s *st.Struct) map[string]interface{}

DecodeToMap converts a pb.Struct to a map from strings to Go types. DecodeToMap panics if s is invalid.

func ExecResultToBytes

func ExecResultToBytes(v ExecResult) []byte

func Float64

func Float64(reply interface{}) (float64, error)

Float64 is a helper that converts a command reply to 64 bit float. If err is not equal to nil, then Float64 returns 0, err. Otherwise, Float64 converts the reply to an int as follows:

Reply type    ExecResult
bulk string   parsed reply, nil
nil           0, ErrNil
other         0, error

Deprecated: use conv package function

func Float64Default

func Float64Default(reply interface{}, def ...float64) float64

Float64Default is a helper that converts a command reply to 64 bit float. If err is not equal to nil, then return default value Deprecated: use conv package function

func Int

func Int(reply interface{}) (int, error)

Int is a helper that converts a command reply to an integer. If err is not equal to nil, then Int returns 0, err. Otherwise, Int converts the reply to an int as follows:

Reply type    ExecResult
integer       int(reply), nil
bulk string   parsed reply, nil
nil           0, ErrNil
other         0, error

Deprecated: use conv package function

func Int64

func Int64(reply interface{}) (int64, error)

Int64 is a helper that converts a command reply to 64 bit integer. If err is not equal to nil, then Int returns 0, err. Otherwise, Int64 converts the reply to an int64 as follows:

Reply type    ExecResult
integer       reply, nil
bulk string   parsed reply, nil
nil           0, ErrNil
other         0, error

Deprecated: use conv package function

func Int64Default

func Int64Default(reply interface{}, def ...int64) int64

Int64Default is a helper that converts 64 bit integer. If err is not equal to nil, then return default value Deprecated: use conv package function

func Int64Map

func Int64Map(result interface{}) (map[string]int64, error)

Int64Map is a helper that converts an array of strings (alternating key, value) into a map[string]int64. The HGETALL commands return replies in this format. Requires an even number of values in result. Deprecated: use conv package function

func IntDefault

func IntDefault(reply interface{}, def ...int) int

IntDefault is a helper that converts interface to an integer. If err is not equal to nil, then return default value Deprecated: use conv package function

func IntMap

func IntMap(result interface{}) (map[string]int, error)

IntMap is a helper that converts an array of strings (alternating key, value) into a map[string]int. The HGETALL commands return replies in this format. Requires an even number of values in result. Deprecated: use conv package function

func InterfaceToProtoAny

func InterfaceToProtoAny(v interface{}) (*any.Any, error)

func InterfaceToProtoAnyDefault

func InterfaceToProtoAnyDefault(v interface{}) *any.Any

func InterfaceToPytesStruceValue

func InterfaceToPytesStruceValue(v interface{}) *st.Value

ToValue converts an interface{} to a ptypes.Value

func ProtoAnyToInterface

func ProtoAnyToInterface(v *any.Any) interface{}

func QueryResultToBytes

func QueryResultToBytes(q QueryResult) []byte

查询结果序列化成字节数组

func String

func String(reply interface{}) (string, error)

String is a helper that converts a command reply to a string. If err is not equal to nil, then String returns "", err. Otherwise String converts the reply to a string as follows:

Reply type      ExecResult
bulk string     string(reply), nil
simple string   reply, nil
nil             "",  ErrNil
other           "",  error

Deprecated: use conv package function

func StringDefault

func StringDefault(reply interface{}, def ...string) string

StringDefault is a helper that converts a command reply to a string. If err is not equal to nil, then String returns default value Deprecated: use conv package function

func StringMap

func StringMap(result interface{}) (map[string]string, error)

StringMap is a helper that converts an array of strings (alternating key, value) into a map[string]string. The HGETALL and CONFIG GET commands return replies in this format. Requires an even number of values in result. Deprecated: use conv package function

func Strings

func Strings(reply interface{}) ([]string, error)

Strings is a helper that converts an array command reply to a []string. If err is not equal to nil, then Strings returns nil, err. Nil array items are converted to "" in the output slice. Strings returns an error if an array item is not a bulk string or nil. Deprecated: use conv package function

func Uint64

func Uint64(reply interface{}) (uint64, error)

Uint64 is a helper that converts a command reply to 64 bit integer. If err is not equal to nil, then Int returns 0, err. Otherwise, Int64 converts the reply to an int64 as follows:

Reply type    ExecResult
integer       reply, nil
bulk string   parsed reply, nil
nil           0, ErrNil
other         0, error

Deprecated: use conv package function

func Uint64Default

func Uint64Default(reply interface{}, def ...uint64) uint64

Uint64Default is a helper that converts to 64 bit integer. If err is not equal to nil, then return default value Deprecated: use conv package function

Types

type Conn

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

Conn 操作对象

func (*Conn) Close

func (c *Conn) Close()

Close 关闭数据库连接

func (*Conn) Count

func (c *Conn) Count(sql string, args ...interface{}) (int64, error)

Count SQL语句条数统计 @param sql string SQL @param args... interface{} SQL参数

func (*Conn) DataBaseName

func (c *Conn) DataBaseName() string

数据库名称

func (*Conn) Exec

func (c *Conn) Exec(sql string, args ...interface{}) ExecResult

Exec 执行一条SQL @param sql string SQL @param args... interface{} SQL参数

func (*Conn) GetDb

func (c *Conn) GetDb() (*sql.DB, error)

GetDb 获取数据库对象

func (*Conn) ParseSQL

func (c *Conn) ParseSQL(sql string, args map[string]interface{}) (string, []interface{}, error)

ParseSQL 解析SQL @param sql string SQL @param args map[string]interface{} 参数映射

func (*Conn) Prepare

func (c *Conn) Prepare(query string) (*sql.Stmt, error)

func (*Conn) QueryRow

func (c *Conn) QueryRow(sql string, args ...interface{}) QueryResult

Row 查询单条语句,返回结果 @param sql string SQL @param args... interface{} SQL参数

func (*Conn) QueryRows

func (c *Conn) QueryRows(sql string, args ...interface{}) QueryResult

RowsCallbackResult 查询多条数据,结果以回调函数处理

@param sql string SQL

@param callback func(*sql.Rows) 回调函数指针

@param args... interface{} SQL参数

func (*Conn) QueryWithPage

func (c *Conn) QueryWithPage(sql string, page *PageObj, args ...interface{}) QueryResult

RowsPage 分页查询

func (*Conn) SetDataBaseName

func (c *Conn) SetDataBaseName(dbname string)

设置数据库名称

func (*Conn) SetMaxOpenConns

func (c *Conn) SetMaxOpenConns(n int)

设置最大连接数

func (*Conn) SetSQLDB

func (c *Conn) SetSQLDB(dbSQL *sql.DB)

设置数据库链接

func (*Conn) Table

func (c *Conn) Table(tbname string) string

格式化表名称,不做处理直接返回

func (*Conn) Transaction

func (c *Conn) Transaction(t TransactionFunc, option ...*TxOption) error

Transaction 事务处理 @param t TransactionFunc 事务处理函数

type ConnTx

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

ConnTx 事务操作

func (*ConnTx) Count

func (m *ConnTx) Count(sql string, args ...interface{}) (int64, error)

Count SQL语句条数统计 @param sql string SQL @param args... interface{} SQL参数

func (*ConnTx) DataBaseName

func (m *ConnTx) DataBaseName() string

数据库名称

func (*ConnTx) Exec

func (m *ConnTx) Exec(sql string, args ...interface{}) ExecResult

Exec 执行一条SQL @param sql string SQL @param args... interface{} SQL参数

func (*ConnTx) GetTx

func (m *ConnTx) GetTx() *sql.Tx

GetTx 获取事务对象

func (*ConnTx) Prepare

func (m *ConnTx) Prepare(query string) (*sql.Stmt, error)

func (*ConnTx) QueryRow

func (m *ConnTx) QueryRow(sql string, args ...interface{}) QueryResult

QueryResult 查询单条语句,返回结果 @param sql string SQL @param args... interface{} SQL参数

func (*ConnTx) QueryRows

func (m *ConnTx) QueryRows(sql string, args ...interface{}) QueryResult

Rows 查询多条数据,结果以[]map[string]interface{}方式返回

返回结果,使用本package中的类型函数进行数据解析 eg:

result := Rows(...)
for _,mp := range result {
	Int(mp["colum"])
	String(mp["colum"])
	.......
}

@param sql string SQL

@param args... interface{} SQL参数

func (*ConnTx) QueryWithPage

func (m *ConnTx) QueryWithPage(sql string, page *PageObj, args ...interface{}) QueryResult

RowsPage 分页查询

func (*ConnTx) SetMaxOpenConns

func (m *ConnTx) SetMaxOpenConns(n int)

设置最大连接数

func (*ConnTx) Table

func (m *ConnTx) Table(tbname string) string

格式化表名称,不做处理直接返回

func (*ConnTx) Transaction

func (m *ConnTx) Transaction(t TransactionFunc, option ...*TxOption) error

Transaction 事务处理 param t TransactionFunc 事务处理函数

type ExecResult

type ExecResult interface {
	sql.Result
	// 出错时回调参数方法
	Error(func(error)) ExecResult
	// 错误保存到日志
	ErrorToLog(log *logrus.Entry, msg ...string) ExecResult
	//是否出错
	HasError(reportZeroChange ...bool) error
}

func BytesToExecResult

func BytesToExecResult(v []byte) ExecResult

func ErrExecResult

func ErrExecResult(err error, sql string, args []interface{}) ExecResult

查询错误结果

func NewExecResult

func NewExecResult(rs sql.Result) ExecResult

获取一个操作结果对象

type ExecResultMsg

type ExecResultMsg struct {
	LastInsertId         int64    `protobuf:"varint,1,opt,name=lastInsertId,proto3" json:"lastInsertId,omitempty"`
	RowsAffected         int64    `protobuf:"varint,2,opt,name=rowsAffected,proto3" json:"rowsAffected,omitempty"`
	ErrCode              int64    `protobuf:"varint,3,opt,name=errCode,proto3" json:"errCode,omitempty"`
	ErrMsg               string   `protobuf:"bytes,4,opt,name=errMsg,proto3" json:"errMsg,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (*ExecResultMsg) Descriptor

func (*ExecResultMsg) Descriptor() ([]byte, []int)

func (*ExecResultMsg) GetErrCode

func (m *ExecResultMsg) GetErrCode() int64

func (*ExecResultMsg) GetErrMsg

func (m *ExecResultMsg) GetErrMsg() string

func (*ExecResultMsg) GetLastInsertId

func (m *ExecResultMsg) GetLastInsertId() int64

func (*ExecResultMsg) GetRowsAffected

func (m *ExecResultMsg) GetRowsAffected() int64

func (*ExecResultMsg) ProtoMessage

func (*ExecResultMsg) ProtoMessage()

func (*ExecResultMsg) Reset

func (m *ExecResultMsg) Reset()

func (*ExecResultMsg) String

func (m *ExecResultMsg) String() string

func (*ExecResultMsg) XXX_DiscardUnknown

func (m *ExecResultMsg) XXX_DiscardUnknown()

func (*ExecResultMsg) XXX_Marshal

func (m *ExecResultMsg) XXX_Marshal(b []byte, deterministic bool) ([]byte, error)

func (*ExecResultMsg) XXX_Merge

func (m *ExecResultMsg) XXX_Merge(src proto.Message)

func (*ExecResultMsg) XXX_Size

func (m *ExecResultMsg) XXX_Size() int

func (*ExecResultMsg) XXX_Unmarshal

func (m *ExecResultMsg) XXX_Unmarshal(b []byte) error

type IDGenerator

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

SnowFlakeID算法ID生成器

func NewIDGenerator

func NewIDGenerator(workID int64) *IDGenerator

实例化毫秒15位一个ID生成器

func (*IDGenerator) NextId

func (sfg *IDGenerator) NextId() (int64, error)

生成下一个ID

func (*IDGenerator) NextString

func (sfg *IDGenerator) NextString() string

func (*IDGenerator) SetStartTimestamp

func (sfg *IDGenerator) SetStartTimestamp(startTimestamp int64)

type PageObj

type PageObj struct {
	Page     int   `json:"page"`
	Rows     int   `json:"rows"`
	Total    int64 `json:"total"`
	PageSize int   `json:"allpage"`
}

PageObj 分页数据

func (*PageObj) MarshalJSON

func (mj *PageObj) MarshalJSON() ([]byte, error)

func (*PageObj) MarshalJSONBuf

func (mj *PageObj) MarshalJSONBuf(buf fflib.EncodingBuffer) error

func (*PageObj) SetTotal

func (p *PageObj) SetTotal(total int64)

setTotal 设置分页

func (*PageObj) UnmarshalJSON

func (uj *PageObj) UnmarshalJSON(input []byte) error

func (*PageObj) UnmarshalJSONFFLexer

func (uj *PageObj) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error

type Query

type Query interface {
	//Rows 查询多条数据,结果以[]map[string]interface{}方式返回
	//返回结果,使用本package中的类型函数进行数据解析
	//eg:
	//		result := QueryRow(...)
	//		result.Error(func(error.Error){
	//			这里处理错误
	// 		}).Rows(func(map[string]interface{}) bool {
	//			return true //返回true,继续循环读取下一条
	// 		})
	//param sql string SQL
	//param args... interface{} SQL参数
	QueryRows(sql string, args ...interface{}) QueryResult
	//Rows 查询多条数据,结果以[]map[string]interface{}方式返回
	//返回结果,使用本package中的类型函数进行数据解析
	//eg:
	//		result := QueryRow(...)
	//		result.Error(func(error.Error){
	//			这里处理错误
	// 		}).Rows(func(map[string]interface{}) bool {
	//			return true //返回true,继续循环读取下一条
	// 		})
	//param sql string SQL
	//param args... interface{} SQL参数
	QueryRow(sql string, args ...interface{}) QueryResult
	//Exec 执行一条SQL
	//param sql string SQL
	//param args... interface{} SQL参数
	Exec(sql string, args ...interface{}) ExecResult
	//Count SQL语句条数统计
	//param sql string SQL
	//param args... interface{} SQL参数
	Count(sql string, args ...interface{}) (int64, error)
	//RowsPage 分页查询SQL
	//返回结果,使用本package中的类型函数进行数据解析
	//eg:
	//		result := QueryRow(...)
	//		result.Error(func(error.Error){
	//			这里处理错误
	// 		}).Rows(func(map[string]interface{}) bool {
	//			return true //返回true,继续循环读取下一条
	// 		})
	//param sql string SQL
	//param page *PageObj 分页数据
	//param args... interface{} SQL参数
	QueryWithPage(sql string, page *PageObj, args ...interface{}) QueryResult
	//Prepare 预处理
	Prepare(query string) (*sql.Stmt, error)
	//格式化表名称
	Table(tbname string) string
	//数据库名称
	DataBaseName() string
	// 设置最大连接数
	SetMaxOpenConns(n int)
	//Transaction 事务处理
	//param t TransactionFunc 事务处理函数
	//param new bool 是否创建新事物,默认false,如果设置true不管事务是否存在都会创建新事物
	Transaction(t TransactionFunc, option ...*TxOption) error
}

查询操作集合

type QueryResult

type QueryResult interface {
	//逐条获取结果
	//如果参数func返回true,并且还有下一条结果则再次调用func返回下一条
	ForEach(func(map[string]interface{}) bool) QueryResult
	//出错时回调参数方法
	Error(func(error)) QueryResult
	// 错误保存到日志
	ErrorToLog(log *logrus.Entry, msg ...string) QueryResult
	//是否出错
	HasError() error
	//是否为空
	IsEmpty() bool
	//结果空是回调参数方法
	Empty(func()) QueryResult
	//获取字段列表
	Columns() []string
	//获取所有数据
	Rows() [][]interface{}
	//读取某行的指定字段值.
	//columnName表示字段名称,index表示第几行默认第一行,如果结果不存在返回nil
	Get(columnName string, index ...int) interface{}
	//读取某行的所有数据.
	//index代表第几行默认第一行,返回的map中key是数据字段名称,value是值
	GetMap(index ...int) map[string]interface{}
	//获取结果长度
	Length() int
	// 获取记录游标
	Iterator() RowIterator
}

查询结果返回接口

func BytesToQueryResult

func BytesToQueryResult(data []byte) QueryResult

字节数组序列化成查询结果

func ErrQueryResult

func ErrQueryResult(err error, sql string, args []interface{}) QueryResult

返回一个查询错误

func NewQueryResult

func NewQueryResult(rows *sql.Rows, sql string, args []interface{}) QueryResult

读取查询结果

type QueryResultData

type QueryResultData struct {
	Data                 []*any.Any `protobuf:"bytes,1,rep,name=data,proto3" json:"data,omitempty"`
	XXX_NoUnkeyedLiteral struct{}   `json:"-"`
	XXX_unrecognized     []byte     `json:"-"`
	XXX_sizecache        int32      `json:"-"`
}

func (*QueryResultData) Descriptor

func (*QueryResultData) Descriptor() ([]byte, []int)

func (*QueryResultData) GetData

func (m *QueryResultData) GetData() []*any.Any

func (*QueryResultData) ProtoMessage

func (*QueryResultData) ProtoMessage()

func (*QueryResultData) Reset

func (m *QueryResultData) Reset()

func (*QueryResultData) String

func (m *QueryResultData) String() string

func (*QueryResultData) XXX_DiscardUnknown

func (m *QueryResultData) XXX_DiscardUnknown()

func (*QueryResultData) XXX_Marshal

func (m *QueryResultData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error)

func (*QueryResultData) XXX_Merge

func (m *QueryResultData) XXX_Merge(src proto.Message)

func (*QueryResultData) XXX_Size

func (m *QueryResultData) XXX_Size() int

func (*QueryResultData) XXX_Unmarshal

func (m *QueryResultData) XXX_Unmarshal(b []byte) error

type QueryResultMsg

type QueryResultMsg struct {
	Columns              []string           `protobuf:"bytes,1,rep,name=columns,proto3" json:"columns,omitempty"`
	Datalength           int64              `protobuf:"varint,2,opt,name=datalength,proto3" json:"datalength,omitempty"`
	ErrCode              int64              `protobuf:"varint,3,opt,name=errCode,proto3" json:"errCode,omitempty"`
	ErrMsg               string             `protobuf:"bytes,4,opt,name=errMsg,proto3" json:"errMsg,omitempty"`
	Data                 []*QueryResultData `protobuf:"bytes,5,rep,name=data,proto3" json:"data,omitempty"`
	XXX_NoUnkeyedLiteral struct{}           `json:"-"`
	XXX_unrecognized     []byte             `json:"-"`
	XXX_sizecache        int32              `json:"-"`
}

查询返回结果

func (*QueryResultMsg) Descriptor

func (*QueryResultMsg) Descriptor() ([]byte, []int)

func (*QueryResultMsg) GetColumns

func (m *QueryResultMsg) GetColumns() []string

func (*QueryResultMsg) GetData

func (m *QueryResultMsg) GetData() []*QueryResultData

func (*QueryResultMsg) GetDatalength

func (m *QueryResultMsg) GetDatalength() int64

func (*QueryResultMsg) GetErrCode

func (m *QueryResultMsg) GetErrCode() int64

func (*QueryResultMsg) GetErrMsg

func (m *QueryResultMsg) GetErrMsg() string

func (*QueryResultMsg) ProtoMessage

func (*QueryResultMsg) ProtoMessage()

func (*QueryResultMsg) Reset

func (m *QueryResultMsg) Reset()

func (*QueryResultMsg) String

func (m *QueryResultMsg) String() string

func (*QueryResultMsg) XXX_DiscardUnknown

func (m *QueryResultMsg) XXX_DiscardUnknown()

func (*QueryResultMsg) XXX_Marshal

func (m *QueryResultMsg) XXX_Marshal(b []byte, deterministic bool) ([]byte, error)

func (*QueryResultMsg) XXX_Merge

func (m *QueryResultMsg) XXX_Merge(src proto.Message)

func (*QueryResultMsg) XXX_Size

func (m *QueryResultMsg) XXX_Size() int

func (*QueryResultMsg) XXX_Unmarshal

func (m *QueryResultMsg) XXX_Unmarshal(b []byte) error

type RowIterator

type RowIterator interface {
	// 是否有下一条记录
	HasNext() bool
	// 重置游标到首位
	Reset()
	// 获取下一条数据
	Next() (map[string]interface{}, error)
}

行读取游标

type SQL

type SQL interface {
	Query
	//ParseSQL 解析SQL
	//param sql string SQL
	//param args map[string]interface{} 参数映射
	ParseSQL(sql string, args map[string]interface{}) (string, []interface{}, error)
	//GetDb 获取数据库对象
	GetDb() (*sql.DB, error)
	//Close 关闭数据库
	Close()
}

数据库操作接口

type TransactionFunc

type TransactionFunc func(tx TxSQL) error

TransactionFunc 事务回调函数

type TxOption

type TxOption struct {
	New    bool           //新事务
	Option *sql.TxOptions //事务参数
}

事务参数

type TxSQL

type TxSQL interface {
	Query
	//GetTx 获取事务对象
	GetTx() *sql.Tx
}

事物数据操作接口

Directories

Path Synopsis
package gosql mssql工具包..引用"github.com/denisenkom/go-mssqldb"
package gosql mssql工具包..引用"github.com/denisenkom/go-mssqldb"
package gosql mysql工具包..引用"github.com/go-sql-driver/mysql"
package gosql mysql工具包..引用"github.com/go-sql-driver/mysql"

Jump to

Keyboard shortcuts

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