sqlx

package
v0.0.0-...-817968b Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2021 License: Apache-2.0 Imports: 15 Imported by: 0

README

sqlx(WIP)

简介

sqlx主要用于扩展标准sql,统一不同平台下差异,区别于gorm等orm库,这里只会提供简单单表CRUD。

支持的特性有:

  • 参数绑定:
    • mysql: 使用?
    • postgres: 使用$1, $2
    • oracle: 使用:arg1, :arg2
    • sqlserver: 使用 @p1, @p2
  • IN数组参数绑定:
  • 查询结果绑定struct,map,slice

使用方法


其他

Documentation

Index

Constants

View Source
const (
	OrderAsc  = 0 // 默认升序
	OrderDesc = 1
)

Variables

View Source
var (
	ErrNotPointer      = errors.New("not a pointer")
	ErrNotSlicePointer = errors.New("not slice pointer")
	ErrTooManyColumns  = errors.New("too many columns")
)

Functions

func Drivers

func Drivers() []string

Drivers returns a sorted list of the names of the registered drivers.

func In

func In(query string, args ...interface{}) (string, []interface{}, error)

In expands slice values in args, returning the modified query string and a new arg list that can be executed by a database. The `query` should use the `?` bindVar. The return value uses the `?` bindVar.

func Rebind

func Rebind(bindType BindVarType, query string) string

Rebind a query from the default bindtype (QUESTION) to the target bindtype.

func Register

func Register(name string, driver Driver)

Register makes a database driver available by the provided name. If Register is called twice with the same name or if driver is nil, it panics.

func RegisterDialect

func RegisterDialect(dia Dialect)

RegisterDialect 注册Dialect

func RegisterModel

func RegisterModel(m interface{}) error

RegisterModel 注册model

Types

type BindVarType

type BindVarType uint8

Bindvar types supported by Rebind, BindMap and BindStruct.

const (
	BindVarUnknown  BindVarType = iota //
	BindVarQuestion                    // such as mysql, use ?
	BindVarDollar                      // such as postgres, $1 $2
	BindVarNamed                       // such as oracle, :named, :arg1,:arg2
	BindVarAt                          // such as sqlserver, @p1, @p2
)

type Column

type Column struct {
	Name          string // 字段名
	Type          string // 类型
	Default       string // 默认值, 不需要双引号
	NotNull       bool   // 是否非空
	AutoIncrement bool   // 是否自增
	PrimaryKey    bool   // 是否是主键
	Size          int    // 类型大小
}

Column 列信息,用于CreateTable

type Conn

type Conn interface {
	CreateDB(ctx context.Context, name string) error
	DropDB(ctx context.Context, name string) error
	Database(ctx context.Context, name string) (DB, error)
	// ListDatabases(ctx context.Context) ([]string, error)
	Ping(ctx context.Context) error
}

Conn 代表客户端连接

func Open

func Open(driverName, dataSourceName string, opts ...*OpenOptions) (Conn, error)

Open opens a database specified by its database driver name and a driver-specific data source name, usually consisting of at least a database name and connection information.

Most users will open a database via a driver-specific connection helper function that returns a *DB. No database drivers are included in the Go standard library. See https://golang.org/s/sqldrivers for a list of third-party drivers.

Open may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call Ping.

The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.

type Cursor

type Cursor interface {
	// Next 返回是否还有记录
	Next() bool
	// Decode 解析单条数据到out中,out可以是struct指针,可以是map或数组指针
	Decode(out interface{}) error
	// All 解析所有数据到out中,out为slice指针
	All(out interface{}) error
	// Close .
	Close() error
	// Error .
	Error() error
}

Cursor 多条查询结果

type D

type D []E

D is an ordered representation of a BSON document. This type should be used when the order of the elements matters, such as MongoDB command documents. If the order of the elements does not matter, an M should be used instead.

Example usage:

bson.D{{"foo", "bar"}, {"hello", "world"}, {"pi", 3.14159}}

func (D) Map

func (d D) Map() M

Map creates a map from the elements of the D.

type DB

type DB interface {
	Name() string

	Close() error

	Indexes(ctx context.Context, table string) ([]*Index, error)
	CreateIndex(ctx context.Context, table string, index *Index) error
	DropIndex(ctx context.Context, table string, name string) error

	CreateTable(ctx context.Context, table string, columns []*Column) error
	DropTable(ctx context.Context, table string, opts ...*DropTableOptions) error

	Begin(ctx context.Context, opts *TxOptions) (Tx, error)

	// CRUD接口,Options仅支持1个
	Insert(ctx context.Context, table string, datas []interface{}, opts ...*InsertOptions) (Result, error)
	InsertOne(ctx context.Context, table string, data interface{}, opts ...*InsertOptions) (Result, error)
	Update(ctx context.Context, table string, filter interface{}, data interface{}, opts ...*UpdateOptions) (Result, error)
	UpdateOne(ctx context.Context, table string, filter interface{}, data interface{}, opts ...*UpdateOptions) (Result, error)
	// Delete 若filter为nil则删除所有数据,但不删除table
	Delete(ctx context.Context, table string, filter interface{}, opts ...*DeleteOptions) (Result, error)
	DeleteOne(ctx context.Context, table string, filter interface{}, opts ...*DeleteOptions) (Result, error)
	Find(ctx context.Context, table string, filter interface{}, opts ...*FindOptions) Cursor
	FindOne(ctx context.Context, table string, filter interface{}, opts ...*FindOptions) SingleResult

	// 原生sql
	Query(ctx context.Context, query string, args ...interface{}) Cursor
	Exec(ctx context.Context, query string, args ...interface{}) (Result, error)
}

DB db相关接口,filter使用interface{},可以是bson.M或者Filter

type DeleteOptions

type DeleteOptions struct {
}

type Dialect

type Dialect interface {
	// Name 唯一名
	Name() string
	// Drivers 返回已知的Driver名
	Drivers() []string
	// 返回bind variables类型
	BindVar() BindVarType
	//
	Indexes(ctx context.Context, db Executor, table string) ([]*Index, error)
	CreateIndex(ctx context.Context, db Executor, table string, index *Index) error
	DropIndex(ctx context.Context, db Executor, table string, name string) error

	CreateTable(ctx context.Context, db Executor, table string, columns []*Column) error
	DropTable(ctx context.Context, db Executor, table string, opts ...*DropTableOptions) error

	// crud
	Insert(ctx context.Context, db Executor, bindType BindVarType, table string, datas []interface{}, opts *InsertOptions) (Result, error)
	InsertOne(ctx context.Context, db Executor, bindType BindVarType, table string, data interface{}, opts *InsertOptions) (Result, error)
	Update(ctx context.Context, db Executor, bindType BindVarType, table string, filter interface{}, data interface{}, opts *UpdateOptions) (Result, error)
	UpdateOne(ctx context.Context, db Executor, bindType BindVarType, table string, filter interface{}, data interface{}, opts *UpdateOptions) (Result, error)
	Delete(ctx context.Context, db Executor, bindType BindVarType, table string, filter interface{}, opts *DeleteOptions) (Result, error)
	DeleteOne(ctx context.Context, db Executor, bindType BindVarType, table string, filter interface{}, opts *DeleteOptions) (Result, error)
	Find(ctx context.Context, db Executor, bindType BindVarType, table string, filter interface{}, opts *FindOptions) Cursor
	FindOne(ctx context.Context, db Executor, bindType BindVarType, table string, filter interface{}, opts *FindOptions) SingleResult

	// raw sql
	Query(ctx context.Context, db Executor, query string, args ...interface{}) Cursor
	Exec(ctx context.Context, db Executor, query string, args ...interface{}) (Result, error)
}

Dialect 用于实现不同sql之间差异,需要无状态 [SQL Drivers](https://github.com/golang/go/wiki/SQLDrivers) [Go database/sql tutorial](http://go-database-sql.org/index.html)

type Driver

type Driver interface {
	Open(dataSourceName string, opts *OpenOptions) (Conn, error)
}

Driver .

type DropTableOptions

type DropTableOptions struct {
}

type E

type E struct {
	Key   string
	Value interface{}
}

E represents a BSON element for a D. It is usually used inside a D.

type Executor

type Executor interface {
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
}

Executor 标准sql接口

type Field

type Field struct {
	Name  string // 字段名
	Alias string // 别名
}

type FieldType

type FieldType int
const (
	FTChar FieldType = iota
	FTInt8
	FTInt16
	FTInt32
	FTInt64
	FTUint8
	FTUint16
)

支持的数据类型

type Filter

type Filter interface {
	Query() string
	Args() []interface{}
}

Filter .

func NewFilter

func NewFilter(query string, args ...interface{}) Filter

NewFilter 创建Filter

type FindOptions

type FindOptions struct {
	ReadPref ReadPreference //
	Fields   []Field        // 查询字段,若为空则查询全部
	Sort     []Order        // 排序
	Offset   int
	Limit    int
}

type Hook

type Hook interface {
}

type Index

type Index struct {
	Name       string     // 索引名,若为空则使用Keys拼接
	Keys       []IndexKey // 索引key
	Background bool       // 是否后台异步创建索引
	Unique     bool       // 是否唯一索引
	Sparse     bool       // 稀疏索引,see mongno: https://mongoing.com/docs/core/index-sparse.html
}

Index 索引信息

type IndexKey

type IndexKey struct {
	Name  string
	Order OrderType
}

type InsertOptions

type InsertOptions struct {
}

type M

type M map[string]interface{}

M is an unordered representation of a BSON document. This type should be used when the order of the elements does not matter. This type is handled as a regular map[string]interface{} when encoding and decoding. Elements will be serialized in an undefined, random order. If the order of the elements matters, a D should be used instead.

Example usage:

bson.M{"foo": "bar", "hello": "world", "pi": 3.14159}.

type OpenOptions

type OpenOptions struct {
	ReadDSN         string        // 只读DataSourceName
	MaxIdleConns    int           //
	MaxOpenConns    int           //
	ConnMaxIdleTime time.Duration //
	ConnMaxLifetime time.Duration //
	Dialect         string        //
}

type Order

type Order struct {
	Field string
	Order OrderType
}

type OrderType

type OrderType int

func (OrderType) String

func (o OrderType) String() string

type ReadPreference

type ReadPreference uint8

ReadPreference see: https://docs.mongodb.com/manual/core/read-preference/

const (

	// ReadPrefPrimary indicates that only a primary is
	// considered for reading. This is the default
	// mode.
	ReadPrefPrimary ReadPreference
	// ReadPrefPrimaryPreferred indicates that if a primary
	// is available, use it; otherwise, eligible
	// secondaries will be considered.
	ReadPrefPrimaryPreferred
	// ReadPrefSecondary indicates that only secondaries
	// should be considered.
	ReadPrefSecondary
	// ReadPrefSecondaryPreferred indicates that only secondaries
	// should be considered when one is available. If none
	// are available, then a primary will be considered.
	ReadPrefSecondaryPreferred
	// ReadPrefNearest indicates that all primaries and secondaries
	// will be considered.
	ReadPrefNearest
)

type Result

type Result interface {
	InsertIDs() []interface{}
	RowsAffected() int64
}

type Scanner

type Scanner interface {
	Next() bool
	Value() interface{}
	Error() error
}

Scanner 区别于Find,Find用于单次查询,而Scanner用于分页遍历全部符合条件的数据并逐条处理

func NewScanner

func NewScanner(ctx context.Context, out interface{}, db DB, table string, filter interface{}, limit int, opts *FindOptions) (Scanner, error)

NewScanner .

type SingleResult

type SingleResult interface {
	Decode(out interface{}) error
	Error() error
}

SingleResult represents a single document returned from an operation. If the operation resulted in an error, all SingleResult methods will return that error. If the operation did not return any documents, all SingleResult methods will return ErrNoDocuments.

type Tx

type Tx interface {
	Commit() error
	Rollback() error

	// 通用CRUD
	Insert(ctx context.Context, table string, datas []interface{}, opts ...*InsertOptions) (Result, error)
	InsertOne(ctx context.Context, table string, data interface{}, opts ...*InsertOptions) (Result, error)
	Update(ctx context.Context, table string, filter interface{}, data interface{}, opts ...*UpdateOptions) (Result, error)
	UpdateOne(ctx context.Context, table string, filter interface{}, data interface{}, opts ...*UpdateOptions) (Result, error)
	Delete(ctx context.Context, table string, filter interface{}, opts ...*DeleteOptions) (Result, error)
	DeleteOne(ctx context.Context, table string, filter interface{}, opts ...*DeleteOptions) (Result, error)
	Find(ctx context.Context, table string, filter interface{}, opts ...*FindOptions) Cursor
	FindOne(ctx context.Context, table string, filter interface{}, opts ...*FindOptions) SingleResult

	// 原生sql
	Query(ctx context.Context, query string, args ...interface{}) Cursor
	Exec(ctx context.Context, query string, args ...interface{}) (Result, error)
}

Tx 事务

type TxOptions

type TxOptions = sql.TxOptions

type UpdateOptions

type UpdateOptions struct {
	IgnoreZero bool // 是否忽略空值
}

Jump to

Keyboard shortcuts

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