gosql

package module
v2.0.0-...-2764cd3 Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2021 License: MIT Imports: 16 Imported by: 0

README

gosql

基于jmoiron/sqlx 修改

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (

	// Insert database automatically updates fields
	AUTO_CREATE_TIME_FIELDS = []string{
		"create_time",
		"create_at",
		"created_at",
		"update_time",
		"update_at",
		"updated_at",
	}
	// Update database automatically updates fields
	AUTO_UPDATE_TIME_FIELDS = []string{
		"update_time",
		"update_at",
		"updated_at",
	}
)
View Source
var FatalExit = true

If database fatal exit

Functions

func Connect

func Connect(configs map[string]*Config) (err error)

Connect database

func Exec

func Exec(query string, args ...interface{}) (sql.Result, error)

Exec default database

func Expr

func Expr(expression string, args ...interface{}) *expr

Expr generate raw SQL expression, for example:

gosql.Table("user").Update(map[string]interface{}{"price", gorm.Expr("price * ? + ?", 2, 100)})

func Get

func Get(dest interface{}, query string, args ...interface{}) error

Get default database

func IsZero

func IsZero(val reflect.Value) bool

IsZero assert value is zero value

func JsonObject

func JsonObject(value interface{}) (json.RawMessage, error)

func List

func List() map[string]*sqlx.DB

List gets the list of database engines

func NamedExec

func NamedExec(query string, args interface{}) (sql.Result, error)

Exec default database

func QueryRowx

func QueryRowx(query string, args ...interface{}) *sqlx.Row

QueryRowx default database

func Queryx

func Queryx(query string, args ...interface{}) (*sqlx.Rows, error)

Queryx default database

func RegisterDialect

func RegisterDialect(name string, dialect Dialect)

RegisterDialect register new dialect

func RelationAll

func RelationAll(wrapper *ModelWrapper, db *DB, data interface{}) error

RelationAll is gets the associated relational data for multiple pieces of data

func RelationOne

func RelationOne(wrapper *ModelWrapper, db *DB, data interface{}) error

RelationOne is get the associated relational data for a single piece of data

func Select

func Select(dest interface{}, query string, args ...interface{}) error

Select default database

func SetDefaultLink(db string)

SetDefaultLink set default link name

func SetLogger

func SetLogger(l Logger)

func SetLogging

func SetLogging(logging bool)

SetLogging set default logger

func Sqlx

func Sqlx(name ...string) *sqlx.DB

DB gets the specified database engine, or the default DB if no name is specified.

func Tx

func Tx(fn func(tx *DB) error) error

Tx default database the transaction

func Txx

func Txx(ctx context.Context, fn func(ctx context.Context, tx *DB) error) error

Txx default database the transaction with context

func ValueFilter

func ValueFilter(fields map[string]reflect.Value, zv []string) map[string]interface{}

summer modify 20211209

Types

type Builder

type Builder struct {
	SQLBuilder
	// contains filtered or unexported fields
}

func Model

func Model(model interface{}) *Builder

Model construct SQL from Struct

func WithContext

func WithContext(ctx context.Context) *Builder

Model construct SQL from Struct with context

func (*Builder) All

func (b *Builder) All() (err error)

All get data rows from to Struct

func (*Builder) Count

func (b *Builder) Count(zeroValues ...string) (num int64, err error)

gosql.Model(&User{}).Where("status = 0").Count()

func (*Builder) Create

func (b *Builder) Create() (lastInsertId int64, err error)

Create data from to Struct

func (*Builder) Delete

func (b *Builder) Delete(zeroValues ...string) (affected int64, err error)

gosql.Model(&User{Id:1}).Delete()

func (*Builder) ForceIndex

func (b *Builder) ForceIndex(i string) *Builder

ForceIndex

func (*Builder) Get

func (b *Builder) Get(zeroValues ...string) (err error)

All get data row from to Struct

func (*Builder) Hint

func (b *Builder) Hint(hint string) *Builder

Hint is set TDDL "/*+TDDL:slave()*/"

func (*Builder) Limit

func (b *Builder) Limit(i int) *Builder

Limit

func (*Builder) Model

func (b *Builder) Model(model interface{}) *Builder

Model construct SQL from Struct with context

func (*Builder) Offset

func (b *Builder) Offset(i int) *Builder

Offset

func (*Builder) OrderBy

func (b *Builder) OrderBy(str string) *Builder

OrderBy for example "id desc"

func (*Builder) Relation

func (b *Builder) Relation(fieldName string, fn BuilderChainFunc) *Builder

Relation association table builder handle

func (*Builder) Select

func (b *Builder) Select(fields string) *Builder

Select filter column

func (*Builder) ShowSQL

func (b *Builder) ShowSQL() *Builder

ShowSQL output single sql

func (*Builder) Update

func (b *Builder) Update(zeroValues ...string) (affected int64, err error)

gosql.Model(&User{Id:1,Status:0}).Update("status")

func (*Builder) Where

func (b *Builder) Where(str string, args ...interface{}) *Builder

Where for example Where("id = ? and name = ?",1,"test")

type BuilderChainFunc

type BuilderChainFunc func(b *Builder)

type Config

type Config struct {
	Enable       bool   `yml:"enable" toml:"enable" json:"enable"`
	Driver       string `yml:"driver" toml:"driver" json:"driver"`
	Dsn          string `yml:"dsn" toml:"dsn" json:"dsn"`
	MaxOpenConns int    `yml:"max_open_conns" toml:"max_open_conns" json:"max_open_conns"`
	MaxIdleConns int    `yml:"max_idle_conns" toml:"max_idle_conns" json:"max_idle_conns"`
	MaxLifetime  int    `yml:"max_lefttime" toml:"max_lefttime" json:"max_lefttime"`
	ShowSql      bool   `yml:"show_sql" toml:"show_sql" json:"show_sql"`
}

Config is database connection configuration

type DB

type DB struct {
	RelationMap map[string]BuilderChainFunc
	// contains filtered or unexported fields
}

func Begin

func Begin() (*DB, error)

Beginx begins a transaction for default database and returns an *gosql.DB instead of an *sql.Tx.

func Open

func Open(driver, dbSource string) (*DB, error)

Open open gosql.DB with sqlx

func OpenWithDB

func OpenWithDB(driver string, db *sql.DB) *DB

OpenWithDB open gosql.DB with sql.DB

func Relation

func Relation(name string, fn BuilderChainFunc) *DB

Relation association table builder handle

func ShowSql

func ShowSql() *DB

ShowSql single show sql log

func Use

func Use(db string) *DB

Use is change database

func (*DB) Begin

func (w *DB) Begin() (*DB, error)

Beginx begins a transaction and returns an *gosql.DB instead of an *sql.Tx.

func (*DB) Commit

func (w *DB) Commit() error

Commit commits the transaction.

func (*DB) DriverName

func (w *DB) DriverName() string

DriverName wrapper sqlx.DriverName

func (*DB) Exec

func (w *DB) Exec(query string, args ...interface{}) (result sql.Result, err error)

Exec wrapper sqlx.Exec

func (*DB) Get

func (w *DB) Get(dest interface{}, query string, args ...interface{}) (err error)

Get wrapper sqlx.Get

func (*DB) Model

func (w *DB) Model(m interface{}) *Builder

Model database handler from to struct for example: gosql.Use("db2").Model(&users{})

func (*DB) NamedExec

func (w *DB) NamedExec(query string, args interface{}) (result sql.Result, err error)

NamedExec wrapper sqlx.Exec

func (*DB) Preparex

func (w *DB) Preparex(query string) (*sqlx.Stmt, error)

Preparex wrapper sqlx.Preparex

func (*DB) QueryRowx

func (w *DB) QueryRowx(query string, args ...interface{}) (rows *sqlx.Row)

QueryRowx wrapper sqlx.QueryRowx

func (*DB) Queryx

func (w *DB) Queryx(query string, args ...interface{}) (rows *sqlx.Rows, err error)

Queryx wrapper sqlx.Queryx

func (*DB) Rebind

func (w *DB) Rebind(query string) string

Rebind wrapper sqlx.Rebind

func (*DB) Relation

func (w *DB) Relation(name string, fn BuilderChainFunc) *DB

Relation association table builder handle

func (*DB) Rollback

func (w *DB) Rollback() error

Rollback aborts the transaction.

func (*DB) Select

func (w *DB) Select(dest interface{}, query string, args ...interface{}) (err error)

Select wrapper sqlx.Select

func (*DB) ShowSql

func (w *DB) ShowSql() *DB

func (*DB) Table

func (w *DB) Table(t string) *Mapper

Table database handler from to table name for example: gosql.Use("db2").Table("users")

func (*DB) Tx

func (w *DB) Tx(fn func(w *DB) error) (err error)

Tx the transaction

func (*DB) Txx

func (w *DB) Txx(ctx context.Context, fn func(ctx context.Context, tx *DB) error) (err error)

Txx the transaction with context

func (*DB) WithContext

func (w *DB) WithContext(ctx context.Context) *Builder

Model database handler from to struct with context for example: gosql.Use("db2").WithContext(ctx).Model(&users{})

type Dialect

type Dialect interface {
	// GetName get dialect's name
	GetName() string

	// Quote quotes field name to avoid SQL parsing exceptions by using a reserved word as a field name
	Quote(key string) string

	// Placeholder is where value holder default "?"
	Placeholder() string
}

Dialect interface contains behaviors that differ across SQL database

func GetDialect

func GetDialect(name string) (dialect Dialect, ok bool)

GetDialect gets the dialect for the specified dialect name

type Hook

type Hook struct {
	Errs []error
	// contains filtered or unexported fields
}

func NewHook

func NewHook(ctx context.Context, db *DB) *Hook

func (*Hook) Err

func (h *Hook) Err(err error)

Err add error

func (*Hook) Error

func (h *Hook) Error() error

Error format happened errors

func (*Hook) HasError

func (h *Hook) HasError() bool

HasError has errors

type IModel

type IModel interface {
	TableName() string
	PK() string
}

Model interface

type ISqlx

type ISqlx interface {
	Queryx(query string, args ...interface{}) (*sqlx.Rows, error)
	QueryRowx(query string, args ...interface{}) *sqlx.Row
	Get(dest interface{}, query string, args ...interface{}) error
	Select(dest interface{}, query string, args ...interface{}) error
	Exec(query string, args ...interface{}) (sql.Result, error)
	NamedExec(query string, arg interface{}) (sql.Result, error)
	Preparex(query string) (*sqlx.Stmt, error)
	Rebind(query string) string
	DriverName() string
}

type JSONText

type JSONText json.RawMessage

JSONText is a json.RawMessage, which is a []byte underneath. Value() validates the json format in the source, and returns an error if the json is not valid. Scan does no validation. JSONText additionally implements `Unmarshal`, which unmarshals the json within to an interface{}

func (JSONText) MarshalBinary

func (j JSONText) MarshalBinary() ([]byte, error)

func (JSONText) MarshalJSON

func (j JSONText) MarshalJSON() ([]byte, error)

MarshalJSON returns the *j as the JSON encoding of j.

func (*JSONText) Scan

func (j *JSONText) Scan(src interface{}) error

Scan stores the src in *j. No validation is done.

func (JSONText) String

func (j JSONText) String() string

String supports pretty printing for JSONText types.

func (*JSONText) Unmarshal

func (j *JSONText) Unmarshal(v interface{}) error

Unmarshal unmarshal's the json in j to v, as in json.Unmarshal.

func (*JSONText) UnmarshalBinary

func (j *JSONText) UnmarshalBinary(data []byte) error

func (*JSONText) UnmarshalJSON

func (j *JSONText) UnmarshalJSON(data []byte) error

UnmarshalJSON sets *j to a copy of data

func (JSONText) Value

func (j JSONText) Value() (driver.Value, error)

Value returns j as a value. This does a validating unmarshal into another RawMessage. If j is invalid json, it returns an error.

type Logger

type Logger interface {
	Printf(format string, v ...interface{})
}

Logger represents a logging collector. You can pass a logging collector to gosql.SetLogger(myCollector) to make it collect QueryStatus messages after executing a query.

type Mapper

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

func Table

func Table(t string) *Mapper

Table select table name

func (*Mapper) Count

func (m *Mapper) Count() (num int64, err error)

Count data from to map[string]interface

func (*Mapper) Create

func (m *Mapper) Create(data map[string]interface{}) (lastInsertId int64, err error)

Create data from to map[string]interface

func (*Mapper) Delete

func (m *Mapper) Delete() (affected int64, err error)

Delete data from to map[string]interface

func (*Mapper) ShowSQL

func (m *Mapper) ShowSQL() *Mapper

func (*Mapper) Update

func (m *Mapper) Update(data map[string]interface{}) (affected int64, err error)

Update data from to map[string]interface

func (*Mapper) Where

func (m *Mapper) Where(str string, args ...interface{}) *Mapper

Where

type ModelWrapper

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

func NewModelWrapper

func NewModelWrapper(dbList map[string]*DB, model interface{}) *ModelWrapper

func (*ModelWrapper) GetRelationDB

func (m *ModelWrapper) GetRelationDB(connect string) *DB

func (*ModelWrapper) UnWrap

func (m *ModelWrapper) UnWrap() interface{}

type ModelWrapperFactory

type ModelWrapperFactory func(m interface{}) *ModelWrapper

type QueryStatus

type QueryStatus struct {
	Query string
	Args  interface{}

	Start time.Time
	End   time.Time

	Err error
}

QueryStatus represents the status of a query after being executed.

func (*QueryStatus) String

func (q *QueryStatus) String() string

String returns a formatted log message.

type ReflectMapper

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

func NewReflectMapper

func NewReflectMapper(tagName string) *ReflectMapper

func (*ReflectMapper) FieldByName

func (r *ReflectMapper) 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 (*ReflectMapper) FieldMap

func (r *ReflectMapper) 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.

type SQLBuilder

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

func (*SQLBuilder) Where

func (s *SQLBuilder) Where(str string, args ...interface{})

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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