sqx

package
v0.0.0-...-45da7de Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2024 License: MIT Imports: 35 Imported by: 1

README

sqx

helper to generate sql on various conditions.

go get github.com/bingoohuang/gg/pkg/sqx/...

type Cond struct {
	Name string `cond:"name like ?" modifier:"%v%"` // like的示例
	Addr string `cond:"addr = ?"`
	Code int    `cond:"code > ?" zero:"-1"` // Code == -1时,忽略本字段的条件
	Nooo string `cond:"-"`                  // 忽略本字段作为条件
}

ret, err := sqx.CreateSQL(`select code, name, addr, email from person order by code`, Cond{
	Name: "天问一号",
	Addr: "火星基地",
	Code: -1,
})
fmt.Println(fmt.Sprintf("%+v", ret), err)
// &{Query:select code, name, addr, email from person where name like ? and addr = ? order by code Vars:[%天问一号% 火星基地]}

ret, err = sqx.CreateSQL(`select code, name, addr, email from person order by code`, Cond{
	Name: "嫦娥",
	Addr: "广寒宫",
	Code: 100,
})
fmt.Println(fmt.Sprintf("%+v", ret), err)
// &{Query:select code, name, addr, email from person where name like ? and addr = ? and code > ? order by code Vars:[%嫦娥% 广寒宫 100]}

ret.Append("limit ?, ?", 1, 10) // 手动附加语句
fmt.Println(fmt.Sprintf("%+v", ret), err)
// &{Query:select code, name, addr, email from person where name like ? and addr = ? and code > ? order by code limit ?, ? Vars:[%嫦娥% 广寒宫 100 1 10]}

create counting sql:

ret, err := sqx.SQL{
	Query: `select a, b, c from t where a = ? and b = ? order by a limit ?, ?`,
	Vars:  []interface{}{"地球", "亚洲", 0, 100},
}.CreateCount()
fmt.Println(fmt.Sprintf("%+v", ret), err) 
// &{Query:select count(*) from t where a = ? and b = ? Vars:[地球 亚洲]}

do update or query to database:

// 创建数据库连接池
db, _ := sql.Open("sqlite3", ":memory:")

sqx.NewSQL("create table person(id varchar(100), age int)").Update(db)
sqx.NewSQL("insert into person(id, age) values(?, ?)", "嫦娥", 1000).Update(db)
sqx.NewSQL("insert into person(id, age) values(?, ?)", "悟空", 500).Update(db)

m, _ := sqx.NewSQL("select id, age from person where id=?", "嫦娥").QueryAsMap(db)
fmt.Println(m) // // map[age:1000 id:嫦娥]

r, _ := sqx.NewSQL("select id, age from person where id=?", "嫦娥").QueryAsRow(db)
fmt.Println(r) // // [嫦娥 1000]

type Person struct {
	ID string
	Ag int `col:"AGE"`
}

var ps []Person
sqx.NewSQL("select id, age from person where id=?", "嫦娥").QueryAsBeans(db, &ps)
fmt.Printf("%+v\n", ps) // [{ID:嫦娥 Ag:1000}]

var p Person
sqx.NewSQL("select id, age from person where id=?", "嫦娥").QueryAsBeans(db, &p)
fmt.Printf("%+v\n", p) // {ID:嫦娥 Ag:1000}

age, _ := sqx.NewSQL("select age from person where id=?", "嫦娥").QueryAsNumber(db)
fmt.Println(age) // 1000

id, _ := sqx.NewSQL("select id from person where id=?", "嫦娥").QueryAsString(db)
fmt.Println(id) // 嫦娥

Documentation

Index

Constants

View Source
const (
	// ByNone means no bind params.
	ByNone bindBy = iota
	// ByAuto means auto seq for bind params.
	ByAuto
	// BySeq means specific seq for bind params.
	BySeq
	// ByName means named bind params.
	ByName
)

Variables

View Source
var (
	LimitType = reflect.TypeOf((*Limit)(nil)).Elem()
	CountType = reflect.TypeOf((*Count)(nil)).Elem()
)
View Source
var (
	TypeInt64   = reflect.TypeOf(int64(0))
	TypeUint64  = reflect.TypeOf(uint64(0))
	TypeFloat64 = reflect.TypeOf(float64(0))
)
View Source
var CustomDriverValueConverters = map[reflect.Type]CustomDriverValueConverter{}
View Source
var DB *sql.DB

DB is the global sql.DB for convenience.

View Source
var ErrConditionKind = errors.New("condition kind should be struct or its pointer")

ErrConditionKind tells that the condition kind should be struct or its pointer

View Source
var ErrNotSelect = errors.New("not a select query statement")

ErrNotSelect shows an error that the query is not a select statement.

View Source
var ErrNotSupported = errors.New("sqx: Unsupported result type")

Functions

func CompatibleMySQLDs

func CompatibleMySQLDs(s string) string

CompatibleMySQLDs make mysql datasource be compatible with raw, mysql or gossh host format.

func ConvertSQLLines

func ConvertSQLLines(lines []string) []string

ConvertSQLLines converts the inline comments to line comments and merge to uncomment lines together.

func CreateDao

func CreateDao(dao interface{}, createDaoOpts ...CreateDaoOpter) error

CreateDao fulfils the dao (should be pointer).

func DetectDriverName

func DetectDriverName(driverName, dataSourceName string) string

DetectDriverName detects the driver name for database source name.

func DriverName

func DriverName(d driver.Driver) string

DriverName returns the driver name for the current db.

func GetQueryRows

func GetQueryRows(dest interface{}) int

func ImplSQLScanner

func ImplSQLScanner(t reflect.Type) bool

ImplSQLScanner tells t whether it implements sql.Scanner interface.

func IsIPv6

func IsIPv6(str string) bool

IsIPv6 tests if the str is an IPv6 format.

func IsQuerySQL

func IsQuerySQL(query string) (string, bool)

IsQuerySQL tests a sql is a query or not.

func LogSqlResult

func LogSqlResult(lastResult sql.Result)

func LogSqlResultDesc

func LogSqlResultDesc(desc string, lastResult sql.Result)

func ParseDotTag

func ParseDotTag(line, prefix, mainTag string) (map[string]string, string)

ParseDotTag parses the tag like name:value age:34 adult to map returns the map and main tag's value.

func RegisterDriverName

func RegisterDriverName(d driver.Driver, driverName string)

RegisterDriverName register the driver name for the current db.

func ScanMapRow

func ScanMapRow(rows *sql.Rows, columns []string) (map[string]string, error)

func ScanRowValues

func ScanRowValues(rows *sql.Rows) ([]interface{}, error)

func ScanSliceRow

func ScanSliceRow(rows *sql.Rows, columns []string) ([]string, error)

func ScanStringRow

func ScanStringRow(rows *sql.Rows, columns []string) ([]string, error)

func SplitSqls

func SplitSqls(sqls string, separate rune) []string

SplitSqls splits sqls by separate.

func TrimSQL

func TrimSQL(s, delimiter string) string

TrimSQL trims the delimiter from the string s.

func Vars

func Vars(keys ...interface{}) []interface{}

func VarsStr

func VarsStr(keys ...string) []interface{}

func WithVars

func WithVars(vars ...interface{}) []interface{}

WithVars replace vars.

Types

type BeginTx

type BeginTx interface {
	BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
}

type Col1Scanner

type Col1Scanner struct {
	Data    []string
	MaxRows int
}

func (*Col1Scanner) ScanRow

func (s *Col1Scanner) ScanRow(columns []string, rows *sql.Rows, _ int) (bool, error)

type ContextKey

type ContextKey int
const (
	AdaptedKey ContextKey = iota + 1
)

type Count

type Count int64

type CreateDaoOpt

type CreateDaoOpt struct {
	Error              *error
	Ctx                context.Context
	QueryMaxRows       int `default:"-1"`
	RowScanInterceptor RowScanInterceptor
	DotSQL             func(name string) (SQLPart, error)
	Logger             DaoLogger
	ErrSetter          func(err error)
	DBGetter           DBGetter
}

CreateDaoOpt defines the options for CreateDao.

type CreateDaoOptFn

type CreateDaoOptFn func(*CreateDaoOpt)

CreateDaoOptFn defines the func prototype to option applying.

func (CreateDaoOptFn) ApplyCreateOpt

func (c CreateDaoOptFn) ApplyCreateOpt(opt *CreateDaoOpt)

ApplyCreateOpt applies the option.

type CreateDaoOpter

type CreateDaoOpter interface {
	ApplyCreateOpt(*CreateDaoOpt)
}

CreateDaoOpter defines the option pattern interface for CreateDaoOpt.

func WithCtx

func WithCtx(ctx context.Context) CreateDaoOpter

WithCtx specifies the context.Context to sdb execution processes.

func WithDB

func WithDB(db *sql.DB) CreateDaoOpter

WithDB imports a db.

func WithError

func WithError(err *error) CreateDaoOpter

WithError specifies the err pointer to receive error.

func WithLimit

func WithLimit(maxRows int) CreateDaoOpter

WithLimit specifies the max rows to be fetched when execute query.

func WithRowScanInterceptor

func WithRowScanInterceptor(interceptor RowScanInterceptor) CreateDaoOpter

WithRowScanInterceptor specifies the RowScanInterceptor after a row fetched.

func WithSQLFile

func WithSQLFile(sqlFile string) CreateDaoOpter

WithSQLFile imports SQL queries from the file.

func WithSQLStr

func WithSQLStr(s string) CreateDaoOpter

WithSQLStr imports SQL queries from the string.

type CustomDriverValueConvertFn

type CustomDriverValueConvertFn func(value interface{}) (interface{}, error)

func (CustomDriverValueConvertFn) Convert

func (fn CustomDriverValueConvertFn) Convert(value interface{}) (interface{}, error)

type CustomDriverValueConverter

type CustomDriverValueConverter interface {
	Convert(value interface{}) (interface{}, error)
}

type DBGetter

type DBGetter interface{ GetDB() *sql.DB }

DBGetter is the interface to get a sql.DBGetter.

type DBRaw

type DBRaw struct {
	SqxDB
	DBType sqlparser.DBType
}

func (DBRaw) GetDBType

func (t DBRaw) GetDBType() sqlparser.DBType

type DBTypeAware

type DBTypeAware interface {
	GetDBType() sqlparser.DBType
}

type DaoLog

type DaoLog struct{}

DaoLog implements the interface for dao logging with standard log.

func (*DaoLog) LogError

func (d *DaoLog) LogError(err error)

LogError logs the error.

func (*DaoLog) LogStart

func (d *DaoLog) LogStart(id, sql string, vars interface{})

LogStart logs the sql before the sql execution.

type DaoLogger

type DaoLogger interface {
	// LogError logs the error
	LogError(err error)
	// LogStart logs the sql before the sql execution
	LogStart(id, sql string, vars interface{})
}

DaoLogger is the interface for dao logging.

type Dot

type Dot struct {
	Query string
	Vars  []interface{}

	CountQuery string
	CuntVars   []interface{}
}

type DotItem

type DotItem struct {
	Content []string
	Name    string
	Attrs   map[string]string
}

DotItem tells the item details.

func (DotItem) DynamicSQL

func (d DotItem) DynamicSQL() (SQLPart, error)

DynamicSQL returns the dynamic SQL.

func (DotItem) RawSQL

func (d DotItem) RawSQL() string

RawSQL returns the raw SQL.

type DotSQL

type DotSQL struct {
	Dots map[string]DotItem
}

DotSQL is the set of SQL statements.

func DotSQLLoad

func DotSQLLoad(r io.Reader) (*DotSQL, error)

DotSQLLoad imports sql queries from any io.Reader.

func DotSQLLoadFile

func DotSQLLoadFile(sqlFile string) (*DotSQL, error)

DotSQLLoadFile imports SQL queries from the file.

func DotSQLLoadString

func DotSQLLoadString(s string) (*DotSQL, error)

DotSQLLoadString imports SQL queries from the string.

func (DotSQL) Raw

func (d DotSQL) Raw(name string) (SQLPart, error)

Raw returns the query, everything after the --name tag.

type DotScanner

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

DotScanner scans the SQL statements from .sql files.

func (*DotScanner) Run

func (s *DotScanner) Run(io *bufio.Scanner) map[string]DotItem

Run runs the scanner.

type ExecFn

type ExecFn func(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

func (ExecFn) Exec

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

func (ExecFn) ExecContext

func (f ExecFn) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

type ExecOption

type ExecOption struct {
	MaxRows     int
	NullReplace string
	BlobReplace string
}

type Executable

type Executable interface {
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
}

type FieldPart

type FieldPart struct {
	PartSQL        string
	BindVal        []interface{}
	PartSQLPlTimes int
	JoinedSep      bool
}

func (FieldPart) VarMarks

func (p FieldPart) VarMarks() []string

func (FieldPart) Vars

func (p FieldPart) Vars() []interface{}

type FieldParts

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

func (*FieldParts) AddFieldSqlPart

func (p *FieldParts) AddFieldSqlPart(part string, varVal []interface{}, joinedSep bool)

type IfCondition

type IfCondition struct {
	Expr         string
	CompiledExpr *vm.Program
	Part         SQLPart
}

IfCondition defines a single condition that makes up a conditions-set for IfPart/SwitchPart.

type IfPart

type IfPart struct {
	Conditions []IfCondition
	Else       SQLPart
}

IfPart is the part that has the format of if ... else if ... else ... end.

func MakeIfPart

func MakeIfPart() *IfPart

MakeIfPart makes a new IfPart.

func (*IfPart) AddCondition

func (p *IfPart) AddCondition(conditionExpr string, part SQLPart)

AddCondition adds a condition to the IfPart.

func (*IfPart) AddElse

func (p *IfPart) AddElse(part SQLPart)

AddElse adds an else part to the IfPart.

func (*IfPart) Compile

func (p *IfPart) Compile() (err error)

Compile compiles the condition int advance.

func (*IfPart) Eval

func (p *IfPart) Eval(env map[string]interface{}) (string, error)

Eval evaluates the SQL part to a real SQL.

func (*IfPart) Raw

func (p *IfPart) Raw() string

Raw returns the raw content.

type IfSQLPartParser

type IfSQLPartParser struct {
	Condition string
	Else      string
}

IfSQLPartParser defines the Parser of IfPart.

func MakeIfSQLPartParser

func MakeIfSQLPartParser(condition string) *IfSQLPartParser

MakeIfSQLPartParser makes a IfSQLPartParser.

func (*IfSQLPartParser) Parse

func (p *IfSQLPartParser) Parse(lines []string) (partLines int, part SQLPart, err error)

Parse parses the lines to SQLPart.

type Limit

type Limit struct {
	Offset int64
	Length int64
}

type LiteralPart

type LiteralPart struct {
	Literal string
}

LiteralPart define literal SQL part that no eval required.

func (*LiteralPart) Compile

func (p *LiteralPart) Compile() error

Compile compiles the condition int advance.

func (*LiteralPart) Eval

func (p *LiteralPart) Eval(map[string]interface{}) (string, error)

Eval evaluates the SQL part to a real SQL.

func (*LiteralPart) Raw

func (p *LiteralPart) Raw() string

Raw returns the raw content.

type MapScanner

type MapScanner struct {
	Data    []map[string]string
	MaxRows int
}

func (*MapScanner) Data0

func (s *MapScanner) Data0() map[string]string

func (*MapScanner) ScanRow

func (s *MapScanner) ScanRow(columns []string, rows *sql.Rows, _ int) (bool, error)

type MultiPart

type MultiPart struct {
	Parts []SQLPart
}

MultiPart is the multi SQLParts.

func MakeLiteralMultiPart

func MakeLiteralMultiPart(l string) *MultiPart

MakeLiteralMultiPart makes a MultiPart.

func MakeMultiPart

func MakeMultiPart() *MultiPart

MakeMultiPart makes MultiPart.

func (*MultiPart) AddPart

func (p *MultiPart) AddPart(part SQLPart)

AddPart adds a part to the current MultiPart.

func (*MultiPart) Compile

func (p *MultiPart) Compile() error

Compile compiles the condition int advance.

func (*MultiPart) Eval

func (p *MultiPart) Eval(env map[string]interface{}) (string, error)

Eval evaluates the SQL part to a real SQL.

func (*MultiPart) Raw

func (p *MultiPart) Raw() string

Raw returns the raw content.

type NullAny

type NullAny struct {
	Type reflect.Type
	Val  reflect.Value
}

NullAny represents any that may be null. NullAny implements the Scanner interface so it can be used as a scan destination.

func ScanRow

func ScanRow(columnSize int, r *sql.Rows) ([]NullAny, error)

func (*NullAny) Get

func (n *NullAny) Get() interface{}

func (*NullAny) GetVal

func (n *NullAny) GetVal() reflect.Value

func (*NullAny) Scan

func (n *NullAny) Scan(value interface{}) error

Scan assigns a value from a database driver.

The src value will be of one of the following types:

int64
float64
bool
[]byte
string
time.Time
nil - for NULL values

An error should be returned if the value cannot be stored without loss of information.

Reference types such as []byte are only valid until the next call to Scan and should not be retained. Their underlying memory is owned by the driver. If retention is necessary, copy their values before the next call to Scan.

func (*NullAny) String

func (n *NullAny) String() string

func (*NullAny) Valid

func (n *NullAny) Valid() bool

type PostProcessingSQLPart

type PostProcessingSQLPart struct {
	Part  SQLPart
	Attrs map[string]string
}

PostProcessingSQLPart defines the SQLPart for post-processing like delimiter trimming.

func (*PostProcessingSQLPart) Compile

func (p *PostProcessingSQLPart) Compile() error

Compile compiles the condition int advance.

func (*PostProcessingSQLPart) Eval

func (p *PostProcessingSQLPart) Eval(env map[string]interface{}) (string, error)

Eval evaluated the dynamic sql with env.

func (*PostProcessingSQLPart) Raw

func (p *PostProcessingSQLPart) Raw() string

Raw returns the raw content.

type QueryArgs

type QueryArgs struct {
	Desc    string
	Dest    interface{}
	Query   string
	Args    []interface{}
	Limit   int
	Options []sqlparser.ConvertOption
	Ctx     context.Context
}

func (*QueryArgs) DoExec

func (a *QueryArgs) DoExec(db SqxDB) (int64, error)

func (*QueryArgs) DoExecRaw

func (a *QueryArgs) DoExecRaw(db SqxDB) (sql.Result, error)

func (*QueryArgs) DoQuery

func (a *QueryArgs) DoQuery(db SqxDB) error

type QueryFn

type QueryFn func(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

func (QueryFn) Query

func (f QueryFn) Query(query string, args ...interface{}) (*sql.Rows, error)

func (QueryFn) QueryContext

func (f QueryFn) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

type QueryOption

type QueryOption struct {
	MaxRows          int
	TagNames         []string
	Scanner          RowScanner
	LowerColumnNames bool

	ConvertOptionOptions []sqlparser.ConvertOption
}

QueryOption defines the query options.

type QueryOptionFn

type QueryOptionFn func(o *QueryOption)

QueryOptionFn define the prototype function to set QueryOption.

func WithLowerColumnNames

func WithLowerColumnNames(v bool) QueryOptionFn

WithLowerColumnNames set the LowerColumnNames of QueryOption.

func WithMaxRows

func WithMaxRows(maxRows int) QueryOptionFn

WithMaxRows set the max rows of QueryOption.

func WithOptions

func WithOptions(v *QueryOption) QueryOptionFn

WithOptions apply the query option directly.

func WithRowScanner

func WithRowScanner(v RowScanner) QueryOptionFn

WithRowScanner set row scanner for the query result.

func WithScanRow

func WithScanRow(v ScanRowFn) QueryOptionFn

WithScanRow set row scanner for the query result.

func WithTagNames

func WithTagNames(tagNames ...string) QueryOptionFn

WithTagNames set the tagNames for mapping struct fields to query Columns.

type QueryOptionFns

type QueryOptionFns []QueryOptionFn

QueryOptionFns is the slice of QueryOptionFn.

func (QueryOptionFns) Options

func (q QueryOptionFns) Options() *QueryOption

type Queryable

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

type Result

type Result struct {
	Error        error
	CostTime     time.Duration
	Headers      []string
	Rows         [][]string
	RowsAffected int64
	LastInsertID int64
	IsQuerySQL   bool
	FirstKey     string
}

Result defines the result structure of sql execution.

func Exec

func Exec(db SQLExec, query string, option ExecOption) Result

Exec executes a SQL.

func (Result) Return

func (r Result) Return(start time.Time, err error) Result

type RowScanInterceptor

type RowScanInterceptor interface {
	After(rowIndex int, v ...interface{}) (bool, error)
}

RowScanInterceptor defines the interceptor after a row scanning.

type RowScanInterceptorFn

type RowScanInterceptorFn func(rowIndex int, v ...interface{}) (bool, error)

RowScanInterceptorFn defines the interceptor function after a row scanning.

func (RowScanInterceptorFn) After

func (r RowScanInterceptorFn) After(rowIndex int, v ...interface{}) (bool, error)

After is revoked after a row scanning.

type RowScanner

type RowScanner interface {
	ScanRow(columns []string, rows *sql.Rows, rowIndex int) (bool, error)
}

type RowScannerInit

type RowScannerInit interface {
	InitRowScanner(columns []string)
}

type SQL

type SQL struct {
	Name    string
	Q       string
	AppendQ string
	Vars    []interface{}
	Ctx     context.Context
	NoLog   bool

	Timeout        time.Duration
	Limit          int
	ConvertOptions []sqlparser.ConvertOption
	// contains filtered or unexported fields
}

SQL is a structure for query and vars.

func CreateSQL

func CreateSQL(base string, cond interface{}) (*SQL, error)

CreateSQL creates a composite SQL on base and condition cond.

func NewSQL

func NewSQL(query string, vars ...interface{}) *SQL

NewSQL create s SQL object.

func (*SQL) And

func (s *SQL) And(cond string, args ...interface{}) *SQL

func (*SQL) AndIf

func (s *SQL) AndIf(ok bool, cond string, args ...interface{}) *SQL

func (*SQL) Append

func (s *SQL) Append(sub string, args ...interface{}) *SQL

Append appends sub statement to the query.

func (*SQL) AppendIf

func (s *SQL) AppendIf(ok bool, sub string, args ...interface{}) *SQL

func (SQL) CreateCount

func (s SQL) CreateCount() (*SQL, error)

CreateCount creates a count query sql.

func (SQL) Query

func (s SQL) Query(db SqxDB, result interface{}, optionFns ...QueryOptionFn) error

Query queries return with result.

func (SQL) QueryAsMap

func (s SQL) QueryAsMap(db SqxDB, optionFns ...QueryOptionFn) (map[string]string, error)

QueryAsMap query a single row as a map return.

func (SQL) QueryAsMaps

func (s SQL) QueryAsMaps(db SqxDB, optionFns ...QueryOptionFn) ([]map[string]string, error)

QueryAsMaps query rows as map slice.

func (SQL) QueryAsNumber

func (s SQL) QueryAsNumber(db SqxDB) (int64, error)

QueryAsNumber executes a query which only returns number like count(*) sql.

func (SQL) QueryAsRow

func (s SQL) QueryAsRow(db SqxDB, optionFns ...QueryOptionFn) ([]string, error)

QueryAsRow query a single row as a string slice return.

func (SQL) QueryAsRows

func (s SQL) QueryAsRows(db SqxDB, optionFns ...QueryOptionFn) ([][]string, error)

QueryAsRows query rows as [][]string.

func (SQL) QueryAsString

func (s SQL) QueryAsString(db SqxDB) (string, error)

QueryAsString executes a query which only returns number like count(*) sql.

func (SQL) QueryRaw

func (s SQL) QueryRaw(db SqxDB, optionFns ...QueryOptionFn) error

QueryRaw query rows for customized row scanner.

func (SQL) Update

func (s SQL) Update(db SqxDB) (int64, error)

Update executes an update/delete query and returns rows affected.

func (SQL) UpdateRaw

func (s SQL) UpdateRaw(db SqxDB) (sql.Result, error)

func (*SQL) WithConvertOptions

func (s *SQL) WithConvertOptions(convertOptions []sqlparser.ConvertOption) *SQL

WithConvertOptions set SQL conversion options.

func (*SQL) WithTimeout

func (s *SQL) WithTimeout(timeout time.Duration) *SQL

WithTimeout set sql execution timeout

func (*SQL) WithVars

func (s *SQL) WithVars(vars ...interface{}) *SQL

WithVars replace vars.

type SQLExec

type SQLExec interface {
	Exec(query string, args ...interface{}) (sql.Result, error)
	Query(query string, args ...interface{}) (*sql.Rows, error)
}

SQLExec wraps Exec method.

type SQLExecContext

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

type SQLParsed

type SQLParsed struct {
	ID      string
	SQL     SQLPart
	BindBy  bindBy
	Vars    []string
	MaxSeq  int
	IsQuery bool

	RawStmt string
	// contains filtered or unexported fields
}

SQLParsed is the structure of the parsed SQL.

func ParseSQL

func ParseSQL(name, stmt string) (*SQLParsed, error)

ParseSQL parses the sql.

type SQLPart

type SQLPart interface {
	// Compile compiles the condition int advance.
	Compile() error
	// Eval evaluates the SQL part to a real SQL.
	Eval(m map[string]interface{}) (string, error)
	// Raw returns the raw content.
	Raw() string
}

SQLPart defines the dynamic SQL part.

func MakeLiteralPart

func MakeLiteralPart(s string) SQLPart

MakeLiteralPart makes a MakeLiteralPart.

func ParseDynamicSQL

func ParseDynamicSQL(lines []string, terminators ...string) (int, SQLPart, error)

ParseDynamicSQL parses the dynamic sqls to structured SQLPart.

type SQLPartParser

type SQLPartParser interface {
	// Parse parses the lines to SQLPart.
	Parse(lines []string) (partLines int, part SQLPart, err error)
}

SQLPartParser defines the parser of SQLPart.

func CreateParser

func CreateParser(word string, l string) SQLPartParser

CreateParser creates a SQLPartParser. If no parser found, nil returned.

type ScanRowFn

type ScanRowFn func(columns []string, rows *sql.Rows, rowIndex int) (bool, error)

func (ScanRowFn) ScanRow

func (s ScanRowFn) ScanRow(columns []string, rows *sql.Rows, rowIndex int) (bool, error)

type Sqx

type Sqx struct {
	DB      SqxDB
	DBType  sqlparser.DBType
	CloseFn func() error
}

func NewSqx

func NewSqx(db *sql.DB) *Sqx

func Open

func Open(driverName, dataSourceName string) (*sql.DB, *Sqx, error)

func (*Sqx) Close

func (s *Sqx) Close() error

func (*Sqx) DoExec

func (s *Sqx) DoExec(arg *QueryArgs) (int64, error)

func (*Sqx) DoExecRaw

func (s *Sqx) DoExecRaw(arg *QueryArgs) (sql.Result, error)

func (*Sqx) DoQuery

func (s *Sqx) DoQuery(arg *QueryArgs) error

func (*Sqx) Exec

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

func (*Sqx) ExecContext

func (s *Sqx) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

func (*Sqx) Get

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

func (Sqx) GetDBType

func (s Sqx) GetDBType() sqlparser.DBType

func (*Sqx) GetDesc

func (s *Sqx) GetDesc(desc string, dest interface{}, query string, args ...interface{}) error

func (*Sqx) Query

func (s *Sqx) Query(query string, args ...interface{}) (*sql.Rows, error)

func (*Sqx) QueryContext

func (s *Sqx) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

func (*Sqx) Select

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

func (*Sqx) SelectDesc

func (s *Sqx) SelectDesc(desc string, dest interface{}, query string, args ...interface{}) error

func (*Sqx) Tx

func (s *Sqx) Tx(f func(sqx *Sqx) error) error

func (*Sqx) TxContext

func (s *Sqx) TxContext(ctx context.Context, f func(sqx *Sqx) error) error

func (*Sqx) Upsert

func (s *Sqx) Upsert(insertQuery, updateQuery string, args ...interface{}) (ur UpsertResult, err error)

type SqxDB

type SqxDB interface {
	SQLExec
	SQLExecContext
}

type StdDB

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

StdDB is the wrapper for sql.DBGetter.

func (StdDB) GetDB

func (f StdDB) GetDB() *sql.DB

GetDB returns a sql.DBGetter.

type StringRowScanner

type StringRowScanner struct {
	Data    [][]string
	MaxRows int
}

func (*StringRowScanner) Data0

func (r *StringRowScanner) Data0() []string

func (*StringRowScanner) ScanRow

func (r *StringRowScanner) ScanRow(columns []string, rows *sql.Rows, _ int) (bool, error)

type StructField

type StructField struct {
	Parent      *StructValue
	Field       reflect.Value
	Index       int
	StructField reflect.StructField
	Type        reflect.Type
	Name        string
	Tag         reflect.StructTag
	Kind        reflect.Kind
	PkgPath     string
}

StructField represents the information of a struct's field.

func (StructField) GetTag

func (f StructField) GetTag(name string) string

GetTag returns the value associated with key in the tag string. If there is no such key in the tag, Get returns the empty string.

func (StructField) GetTagOr

func (f StructField) GetTagOr(tagName string, defaultValue string) string

GetTagOr returns the tag's value of the field or defaultValue when tag is empty.

type StructValue

type StructValue struct {
	StructSelf reflect.Value
	NumField   int
	FieldTypes []reflect.StructField
}

StructValue represents the structure for a struct.

func MakeStructValue

func MakeStructValue(structSelf reflect.Value) *StructValue

MakeStructValue makes a StructValue by a struct's value.

func (*StructValue) FieldByIndex

func (s *StructValue) FieldByIndex(index int) StructField

FieldByIndex return the StructField at index.

func (*StructValue) FieldByName

func (s *StructValue) FieldByName(name string) (StructField, bool)

FieldByName returns the StructField which has the name.

func (*StructValue) FieldIndexByName

func (s *StructValue) FieldIndexByName(name string) int

FieldIndexByName return's the index of field by its name. If the field is not found, FieldIndexByName returns -1.

type UpsertResult

type UpsertResult int
const (
	UpsertError UpsertResult = iota
	UpsertInserted
	UpsertUpdated
)

func Upsert

func Upsert(executable Executable, insertQuery, updateQuery string, args ...interface{}) (ur UpsertResult, err error)

func UpsertContext

func UpsertContext(ctx context.Context, executable Executable, insertQuery, updateQuery string, args ...interface{}) (ur UpsertResult, err error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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