sqlx

package module
v1.3.3 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2021 License: Apache-2.0 Imports: 16 Imported by: 1

README

sqlx

install

go get gitee.com/gopher2011/sqlx

usage

Below is an example which shows some common use cases for sqlx. Check sqlx_test.go for more usage.

package main

import (
    "database/sql"
    "fmt"
    "log"
    
    _ "github.com/lib/pq"
    "gitee.com/gopher2011/sqlx"
)

var schema = `
CREATE TABLE person (
    first_name text,
    last_name text,
    email text
);

CREATE TABLE place (
    country text,
    city text NULL,
    telcode integer
)`

type Person struct {
    FirstName string `d:"first_name"`
    LastName  string `d:"last_name"`
    Email     string
}

type Place struct {
    Country string
    City    sql.NullString
    TelCode int
}

func main() {
    // this Pings the database trying to connect
    // use sqlx.Open() for sql.Open() semantics
    db, err := sqlx.Connect("postgres", "user=foo dbname=bar sslmode=disable")
    if err != nil {
        log.Fatalln(err)
    }

    // exec the schema or fail; multi-statement Exec behavior varies between
    // database drivers;  pq will exec them all, sqlite3 won't, ymmv
    db.ExecPanic(schema)
    
    tx := db.BeginPanic()
    tx.ExecPanic("INSERT INTO person (first_name, last_name, email) VALUES ($1, $2, $3)", "Jason", "Moiron", "jmoiron@jmoiron.net")
    tx.ExecPanic("INSERT INTO person (first_name, last_name, email) VALUES ($1, $2, $3)", "John", "Doe", "johndoeDNE@gmail.net")
    tx.ExecPanic("INSERT INTO place (country, city, telcode) VALUES ($1, $2, $3)", "United States", "New York", "1")
    tx.ExecPanic("INSERT INTO place (country, telcode) VALUES ($1, $2)", "Hong Kong", "852")
    tx.ExecPanic("INSERT INTO place (country, telcode) VALUES ($1, $2)", "Singapore", "65")
    // Named queries can use structs, so if you have an existing struct (i.e. person := &Person{}) that you have populated, you can pass it in as &person
    tx.ExecN("INSERT INTO person (first_name, last_name, email) VALUES (:first_name, :last_name, :email)", &Person{"Jane", "Citizen", "jane.citzen@example.com"})
    tx.Commit()

    // Query the database, storing results in a []Person (wrapped in []interface{})
    people := []Person{}
    db.Select(&people, "SELECT * FROM person ORDER BY first_name ASC")
    jason, john := people[0], people[1]

    fmt.Printf("%#v\n%#v", jason, john)
    // Person{FirstName:"Jason", LastName:"Moiron", Email:"jmoiron@jmoiron.net"}
    // Person{FirstName:"John", LastName:"Doe", Email:"johndoeDNE@gmail.net"}

    // You can also get a single result, a la QueryRow
    jason = Person{}
    err = db.Take(&jason, "SELECT * FROM person WHERE first_name=$1", "Jason")
    fmt.Printf("%#v\n", jason)
    // Person{FirstName:"Jason", LastName:"Moiron", Email:"jmoiron@jmoiron.net"}

    // if you have null fields and use SELECT *, you must use sql.Null* in your struct
    places := []Place{}
    err = db.Select(&places, "SELECT * FROM place ORDER BY telcode ASC")
    if err != nil {
        fmt.Println(err)
        return
    }
    usa, singsing, honkers := places[0], places[1], places[2]
    
    fmt.Printf("%#v\n%#v\n%#v\n", usa, singsing, honkers)
    // Place{Country:"United States", City:sql.NullString{String:"New York", Valid:true}, TelCode:1}
    // Place{Country:"Singapore", City:sql.NullString{String:"", Valid:false}, TelCode:65}
    // Place{Country:"Hong Kong", City:sql.NullString{String:"", Valid:false}, TelCode:852}

    // Loop through rows using only one struct
    place := Place{}
    rows, err := db.QueryX("SELECT * FROM place")
    for rows.Next() {
        err := rows.StructScan(&place)
        if err != nil {
            log.Fatalln(err)
        } 
        fmt.Printf("%#v\n", place)
    }
    // Place{Country:"United States", City:sql.NullString{String:"New York", Valid:true}, TelCode:1}
    // Place{Country:"Hong Kong", City:sql.NullString{String:"", Valid:false}, TelCode:852}
    // Place{Country:"Singapore", City:sql.NullString{String:"", Valid:false}, TelCode:65}

    // Named queries, using `:name` as the bindvar.  Automatic bindvar support
    // which takes into account the dbtype based on the driverName on sqlx.Open/Connect
    _, err = db.ExecN(`INSERT INTO person (first_name,last_name,email) VALUES (:first,:last,:email)`, 
        map[string]interface{}{
            "first": "Bin",
            "last": "Smuth",
            "email": "bensmith@allblacks.nz",
    })

    // Selects Mr. Smith from the database
    rows, err = db.QueryN(`SELECT * FROM person WHERE first_name=:fn`, map[string]interface{}{"fn": "Bin"})

    // Named queries can also use structs.  Their bind names follow the same rules
    // as the name -> db mapping, so struct fields are lowercased and the `db` tag
    // is taken into consideration.
    rows, err = db.QueryN(`SELECT * FROM person WHERE first_name=:first_name`, jason)
    
    
    // batch insert
    
    // batch insert with structs
    personStructs := []Person{
        {FirstName: "Ardie", LastName: "Savea", Email: "asavea@ab.co.nz"},
        {FirstName: "Sonny Bill", LastName: "Williams", Email: "sbw@ab.co.nz"},
        {FirstName: "Ngani", LastName: "Laumape", Email: "nlaumape@ab.co.nz"},
    }

    _, err = db.ExecN(`INSERT INTO person (first_name, last_name, email)
        VALUES (:first_name, :last_name, :email)`, personStructs)

    // batch insert with maps
    personMaps := []map[string]interface{}{
        {"first_name": "Ardie", "last_name": "Savea", "email": "asavea@ab.co.nz"},
        {"first_name": "Sonny Bill", "last_name": "Williams", "email": "sbw@ab.co.nz"},
        {"first_name": "Ngani", "last_name": "Laumape", "email": "nlaumape@ab.co.nz"},
    }

    _, err = db.ExecN(`INSERT INTO person (first_name, last_name, email)
        VALUES (:first_name, :last_name, :email)`, personMaps)
}

Documentation

Index

Constants

View Source
const (
	Unknown = iota
	Question
	Dollar
	NAMED
	AT
)

Rebind,BindMap 和 BindStruct 支持的BindVar类型。

Variables

View Source
var (
	NameMapper = strings.ToLower
)

Functions

func BindDriver

func BindDriver(driverName string, bindType int)

BindDriver sets the BindType for driverName to bindType.

func BindNamed

func BindNamed(bindType int, query string, arg interface{}) (string, []interface{}, error)

BindNamed binds a struct or a map to a query with named parameters. DEPRECATED: use sqlx.Named` instead of this, it may be removed in future.

func BindType

func BindType(driverName string) int

BindType returns the bindtype for a given database given a drivername.

func ExecNContext

func ExecNContext(ctx context.Context, e ExtContext, query string, arg interface{}) (sql.Result, error)

NamedExecContext uses BindStruct to get a query executable by the driver and then runs Exec on the result. Returns an error from the binding or the query execution itself.

func ExecPanic

func ExecPanic(e IExecute, query string, args ...interface{}) sql.Result

MustExec 如果发生错误,则使用e和panics执行查询。

任何占位符参数都将替换为提供的args。

func ExecPanicCtx

func ExecPanicCtx(ctx context.Context, e IExecuteContext, query string, args ...interface{}) sql.Result

ExecPanicCtx (原MustExecContext)execs the query using e and panics if there was an error. Any placeholder parameters are replaced with supplied args.

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 LoadFile

func LoadFile(e IExecute, path string) (*sql.Result, error)

LoadFile exec's every statement in a file (as a single call to Exec). LoadFile may return a nil *sql.Result if errors are encountered locating or reading the file at path. LoadFile reads the entire file into memory, so it is not suitable for loading large data dumps, but can be useful for initializing schemas or loading indexes.

FIXME: this does not really work with multi-statement files for mattn/go-sqlite3 or the go-mysql-driver/mysql drivers; pq seems to be an exception here. Detecting this by requiring something with DriverName() and then attempting to split the queries will be difficult to get right, and its current driver-specific behavior is deemed at least not complex in its incorrectness.

func LoadFileContext

func LoadFileContext(ctx context.Context, e IExecuteContext, path string) (*sql.Result, error)

LoadFileContext exec's every statement in a file (as a single call to Exec). LoadFileContext may return a nil *sql.Result if errors are encountered locating or reading the file at path. LoadFile reads the entire file into memory, so it is not suitable for loading large data dumps, but can be useful for initializing schemas or loading indexes.

FIXME: this does not really work with multi-statement files for mattn/go-sqlite3 or the go-mysql-driver/mysql drivers; pq seems to be an exception here. Detecting this by requiring something with DriverName() and then attempting to split the queries will be difficult to get right, and its current driver-specific behavior is deemed at least not complex in its incorrectness.

func MapScan

func MapScan(r ColScanner, dest map[string]interface{}) error

MapScan scans a single Row into the dest map[string]interface{}. Use this to get results for SQL that might not be under your control (for instance, if you're building an interface for an SQL server that executes SQL from input). Please do not use this as a primary interface! This will modify the map sent to it in place, so reuse the same map with care. Columns which occur more than once in the result will overwrite each other!

func Named

func Named(query string, arg interface{}) (string, []interface{}, error)

Named takes a query using named parameters and an argument and returns a new query with a list of args that can be executed by a database. The return value uses the `?` bindvar.

func NamedExec

func NamedExec(e Ext, query string, arg interface{}) (sql.Result, error)

NamedExec uses BindStruct to get a query executable by the driver and then runs Exec on the result. Returns an error from the binding or the query execution itself.

func Rebind

func Rebind(bindType int, query string) string

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

func Select

func Select(q IQuery, pointer interface{}, querySql string, args ...interface{}) error

Select 使用提供的查询器查询多条数据,并将结果扫描进<pointer>中。参数<pointer>必须是切片(slice)类型。

如果<pointer>中的元素是可扫描的,则结果集必须只有一列。否则,将使用StructScan。
默认sql.Rows自动关闭。<querySql>是SQL查询语句。

func SelectCtx

func SelectCtx(ctx context.Context, q IQueryContext, pointer interface{}, querySql string, args ...interface{}) error

SelectCtx (原SelectContext) 使用提供的查询器查询多条数据,并将结果扫描进<pointer>中。参数<pointer>必须是切片(slice)类型。

 1、如果<pointer>中的元素是可扫描的,则结果集必须只有一列。否则,将使用StructScan。
 2、<querySql>是查询类的SQL语句,<args>是该SQL语句需要的参数。
	3、默认sql.Rows自动关闭。任何占位符参数都将替换为提供的args。

func SliceScan

func SliceScan(r ColScanner) ([]interface{}, error)

SliceScan a row, returning a []interface{} with values similar to MapScan. This function is primarily intended for use where the number of columns is not known. Because you can pass an []interface{} directly to Scan, it's recommended that you do that as it will not have to allocate new slices per row.

func StructScan

func StructScan(rows IRow, dest interface{}) error

StructScan all rows from an sql.Rows or an sqlx.Rows into the dest slice. StructScan will scan in the entire rows result, so if you do not want to allocate structs for the entire result, use Queryx and see sqlx.Rows.StructScan. If rows is sqlx.Rows, it will use its mapper, otherwise it will use the default.

func Take

func Take(q IQuery, pointer interface{}, querySql string, args ...interface{}) error

Take (原Get) 使用提供的查询器,查询一条记录,并将结果扫描进<pointer>中。参数<pointer>可以是 struct/*struct。

如果<pointer>是可扫描的,则结果必须只有一列。否则,将使用StructScan。
如果结果集为空,将返回像row.Scan一样的sql.ErrNoRows。

func TakeCtx

func TakeCtx(ctx context.Context, q IQueryContext, pointer interface{}, query string, args ...interface{}) error

TakeCtx (原GetContext) 使用提供的查询器执行QueryRow,然后将结果行扫描到<pointer>。

1、如果<pointer>是可扫描的,则结果必须只有一列,否则,将使用StructScan。
2、如果结果集为空 将像row.Scan一样返回sql.ErrNoRows。
3、<querySql>是查询类的SQL语句,<args>是该SQL语句需要的参数。

Types

type ColScanner

type ColScanner interface {
	Columns() ([]string, error)

	Err() error
	// contains filtered or unexported methods
}

ColScanner 是MapScan和SliceScan使用的接口。

type Conn

type Conn struct {
	*sql.Conn

	Mapper *reflectx.Mapper
	// contains filtered or unexported fields
}

Conn 是对 sql.Conn 的扩展。

func (*Conn) BeginTxX

func (c *Conn) BeginTxX(ctx context.Context, opts *sql.TxOptions) (*Tx, error)

BeginTxX begins a transaction and returns an *sqlx.Tx instead of an *sql.Tx.

The provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginxContext is canceled.

func (*Conn) PrepareXCtx

func (c *Conn) PrepareXCtx(ctx context.Context, query string) (*Stmt, error)

PrepareXCtx (原PrepareXContext) returns an sqlx.Stmt instead of a sql.Stmt. The provided context is used for the preparation of the statement, not for the execution of the statement.

func (*Conn) QueryRowXCtx

func (c *Conn) QueryRowXCtx(ctx context.Context, query string, args ...interface{}) *Row

QueryRowxContext queries the database and returns an *sqlx.Row. Any placeholder parameters are replaced with supplied args.

func (*Conn) QueryXCtx

func (c *Conn) QueryXCtx(ctx context.Context, query string, args ...interface{}) (*Rows, error)

QueryxContext queries the database and returns an *sqlx.Rows. Any placeholder parameters are replaced with supplied args.

func (*Conn) Rebind

func (c *Conn) Rebind(query string) string

Rebind a query within a Conn's bindvar type.

func (*Conn) SelectCtx

func (c *Conn) SelectCtx(ctx context.Context, dest interface{}, query string, args ...interface{}) error

SelectCtx (原SelectContext) using this Conn. Any placeholder parameters are replaced with supplied args.

func (*Conn) TakeCtx

func (c *Conn) TakeCtx(ctx context.Context, dest interface{}, query string, args ...interface{}) error

TakeCtx (原GetContext) using this Conn. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

type DB

type DB struct {
	*sql.DB

	Mapper *reflectx.Mapper
	// contains filtered or unexported fields
}

DB 是 sql.DB 的包装,在打开时跟踪driverName,通常用于使用正确的 bindVars 自动绑定命名查询。

func Connect

func Connect(driverName, dataSourceName string) (*DB, error)

Connect 连接到数据库并通过 ping 进行验证,ping失败则关闭数据库连接,并返回error。

func ConnectCtx

func ConnectCtx(ctx context.Context, driverName, dataSourceName string) (*DB, error)

ConnectCtx (原ConnectContext) 传入 context.Context,连接到数据库并通过ping进行验证。

func NewDB

func NewDB(db *sql.DB, driverName string) *DB

NewDB 输入一个 *sql.DB 和 数据库驱动,返回一个 *sqlx.DB实例。

这是 sqlx.DB 的构造函数。
原始数据库的driverName是命名查询支持所必需的。

func Open

func Open(driverName, dataSourceName string) (*DB, error)

Open 与sql.Open相同,但返回 *sqlx.DB。

func (*DB) BeginPanic

func (db *DB) BeginPanic() *Tx

MustBegin starts a transaction, and panics on error. Returns an *sqlx.Tx instead of an *sql.Tx.

func (*DB) BeginPanicTx

func (db *DB) BeginPanicTx(ctx context.Context, opts *sql.TxOptions) *Tx

func (*DB) BeginTxx

func (db *DB) BeginTxx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)

BeginTxx begins a transaction and returns an *sqlx.Tx instead of an *sql.Tx.

The provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginxContext is canceled.

func (*DB) BeginX

func (db *DB) BeginX() (*Tx, error)

BeginX 开启一个事务,(区别于原生Begin) 并返回 *sqlx.Tx 而不是 *sql.Tx。

func (*DB) BindNamed

func (db *DB) BindNamed(query string, arg interface{}) (string, []interface{}, error)

BindNamed 使用数据库驱动程序的 bindvar 类型绑定查询。

func (*DB) ConnX

func (db *DB) ConnX(ctx context.Context) (*Conn, error)

ConnX returns an *sqlx.Conn instead of an *sql.Conn.

func (*DB) DriverName

func (db *DB) DriverName() string

DriverName 返回传递给该数据库的 Open() 函数的driverName。

(获取当前数据库的驱动名称)

func (*DB) ExecN

func (db *DB) ExecN(query string, arg interface{}) (sql.Result, error)

NamedExec using this DB. Any named placeholder parameters are replaced with fields from arg.

func (*DB) ExecNCtx

func (db *DB) ExecNCtx(ctx context.Context, query string, arg interface{}) (sql.Result, error)

NamedExecContext using this DB. Any named placeholder parameters are replaced with fields from arg.

func (*DB) ExecPanic

func (db *DB) ExecPanic(query string, args ...interface{}) sql.Result

MustExec (panic) runs MustExec using this database. Any placeholder parameters are replaced with supplied args.

func (*DB) ExecPanicCtx

func (db *DB) ExecPanicCtx(ctx context.Context, query string, args ...interface{}) sql.Result

MustExecContext (panic) runs MustExec using this database. Any placeholder parameters are replaced with supplied args.

func (*DB) MapperFunc

func (db *DB) MapperFunc(mf func(string) string)

MapperFunc 使用默认的 sqlx.struct 标记和提供的 mapper 函数为此数据库设置一个新的 mapper。

func (*DB) PrepareN

func (db *DB) PrepareN(query string) (*StmtN, error)

PrepareNamed 返回一个 *sqlx.NamedStmt,*StmtN 支持命名参数。

func (*DB) PrepareNCtx

func (db *DB) PrepareNCtx(ctx context.Context, query string) (*StmtN, error)

PrepareNamedContext returns an sqlx.NamedStmt

func (*DB) PrepareX

func (db *DB) PrepareX(query string) (*Stmt, error)

PrepareX 返回 *sqlx.Stmt 而不是 *sql.Stmt

func (*DB) PrepareXCtx

func (db *DB) PrepareXCtx(ctx context.Context, query string) (*Stmt, error)

func (*DB) QueryN

func (db *DB) QueryN(query string, arg interface{}) (*Rows, error)

NamedQuery using this DB. Any named placeholder parameters are replaced with fields from arg.

func (*DB) QueryNCtx

func (db *DB) QueryNCtx(ctx context.Context, query string, arg interface{}) (*Rows, error)

NamedQueryContext using this DB. Any named placeholder parameters are replaced with fields from arg.

func (*DB) QueryRowX

func (db *DB) QueryRowX(query string, args ...interface{}) *Row

QueryRowX 查询数据库并返回 *sqlx.Row。

任何占位符参数都将替换为提供的args。

func (*DB) QueryRowXCtx

func (db *DB) QueryRowXCtx(ctx context.Context, query string, args ...interface{}) *Row

QueryRowxContext queries the database and returns an *sqlx.Row. Any placeholder parameters are replaced with supplied args.

func (*DB) QueryX

func (db *DB) QueryX(query string, args ...interface{}) (*Rows, error)

QueryX 查询数据库并返回 *sqlx.Rows。

任何占位符参数都将替换为提供的args。

func (*DB) QueryXCtx

func (db *DB) QueryXCtx(ctx context.Context, query string, args ...interface{}) (*Rows, error)

QueryxContext queries the database and returns an *sqlx.Rows. Any placeholder parameters are replaced with supplied args.

func (*DB) Rebind

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

Rebind 将查询从 Question 转换为数据库驱动程序的 bindVar 类型。

func (*DB) Select

func (db *DB) Select(pointer interface{}, querySql string, args ...interface{}) error

Select 查询多条数据,并将结果扫描进<pointer>中。参数<pointer>必须是切片(slice)类型。

 <querySql>是查询SQL语句,<args>是查询SQL语句需要的参数。
	任何占位符参数都将替换为提供的args。

func (*DB) SelectCtx

func (db *DB) SelectCtx(ctx context.Context, dest interface{}, query string, args ...interface{}) error

SelectContext using this DB. Any placeholder parameters are replaced with supplied args.

func (*DB) Take

func (db *DB) Take(pointer interface{}, querySql string, args ...interface{}) error

Take 查询任意一条数据,并将结果扫描进<pointer>中。参数<pointer>可以是 struct/*struct。

 <querySql>是查询SQL语句,<args>是查询SQL语句需要的参数。
	任何占位符参数都将替换为提供的args。如果结果集为空,则返回错误。

func (*DB) TakeCtx

func (db *DB) TakeCtx(ctx context.Context, dest interface{}, query string, args ...interface{}) error

GetContext using this DB. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

func (*DB) Unsafe

func (db *DB) Unsafe() *DB

Unsafe 返回一个DB版本,当SQL结果中的列在目标结构中没有字段时,它将以静默方式成功扫描。 从此数据库创建的sqlx.Stmt和sqlx.Tx将继承其安全行为。

type Ext

type Ext interface {
	IBind
	IQuery
	IExecute
}

Ext 是一个可以绑定,查询和执行的联合接口,供 NamedQuery 和 NamedExec 使用。

type ExtContext

type ExtContext interface {
	IBind
	IQueryContext
	IExecuteContext
}

ExtContext 是一个联合接口,可以与NamedQueryContext和NamedExecContext使用的Context绑定,查询和执行。

type IBind

type IBind interface {
	DriverName() string
	Rebind(string) string
	BindNamed(string, interface{}) (string, []interface{}, error)
}

IBind 是可以绑定查询(Tx,DB)的接口。

type IExecute

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

IExecute 是 MustExec 和 LoadFile 使用的接口。

type IExecuteContext

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

IExecuteContext 是 MustExecContext 和 LoadFileContext 使用的接口

type IPrepare

type IPrepare interface {
	Prepare(query string) (*sql.Stmt, error)
}

IPrepare 是 PrepareX 使用的接口。

type IPrepareContext

type IPrepareContext interface {
	PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
}

IPrepareContext 是 PreparexContext 使用的接口。

type IQuery

type IQuery interface {
	Query(query string, args ...interface{}) (*sql.Rows, error)
	QueryX(query string, args ...interface{}) (*Rows, error)
	QueryRowX(query string, args ...interface{}) *Row
}

IQuery 查询操作的接口。// 仅由 *qStmt实现了这个接口

type IQueryContext

type IQueryContext interface {
	QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
	QueryXCtx(ctx context.Context, query string, args ...interface{}) (*Rows, error)
	QueryRowXCtx(ctx context.Context, query string, args ...interface{}) *Row
}

IQueryContext 是 GetContext 和 SelectContext 使用的接口

type IRow

type IRow interface {
	Columns() ([]string, error)
	Scan(...interface{}) error
	Err() error
	Next() bool
	Close() error
}

IRow 是 ColScanner 和 io.Closer 的联合接口。

type ISql

type ISql interface {
	// Query 参数<querySql>是查询类的SQL语句,<args>是SQL语句的参数。
	QueryX(querySql string, args ...interface{}) (*Rows, error)
	// QueryRow 参数<querySql>是查询类的SQL语句,<args>是SQL语句的参数。
	QueryRowX(querySql string, args ...interface{}) *Row
	// Exec 增、删、改操作的接口。
	//  参数<querySql>是查询类的SQL语句,<args>是SQL语句的参数。
	Exec(querySql string, args ...interface{}) (sql.Result, error)
	// Take 查询一条记录,并将结果扫描进 <pointer>
	//  参数<pointer>可以是struct/*struct。
	//  参数<querySql>是查询类的SQL语句,<args>是SQL语句的参数。
	Take(pointer interface{}, querySql string, args ...interface{}) error
	// Select 查询多条记录,并将查询结果扫描进 <pointer>
	//  参数<pointer>可以是[]struct/*[]struct。
	//  参数<querySql>是查询类的SQL语句,<args>是SQL语句的参数。
	Select(pointer interface{}, querySql string, args ...interface{}) error
	PrepareX(query string) (*Stmt, error)
	// Rebind 绑定 querySql 语句。
	Rebind(querySql string) string
	// DriverName 获取当前处于连接状态的 *sql.DB 的驱动名称。
	DriverName() string
}

ISql 为对外暴露的主要接口,该接口由 Engine 实现。

type ModelTime added in v1.3.3

type ModelTime struct {
	CreatedAt time.Time `form:"-" json:"created_at" db:"created_at" time_format:"2006-01-02 15:04:05"`
	UpdatedAt time.Time `form:"-" json:"updated_at" db:"updated_at" time_format:"2006-01-02 15:04:05"`
}

type Moments added in v1.3.3

type Moments struct {
	Id           int    `form:"id" json:"id" db:"id"`
	UserId       int    `form:"user_id" json:"user_id" db:"user_id"`
	Content      string `form:"content" json:"content" db:"content"`
	CommentTotal int    `form:"comment_total" json:"comment_total" db:"comment_total"`
	LikeTotal    int    `form:"like_total" json:"like_total" db:"like_total"`
	Status       int    `form:"status" json:"status" db:"status"`
	ModelTime
}

type Photos added in v1.3.3

type Photos struct {
	Id       int    `form:"id" json:"id" db:"id"`
	MomentId int    `form:"moment_id" json:"moment_id" db:"moment_id"`
	Url      string `form:"url" json:"url" db:"url"`
	ModelTime
}

type Row

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

Row 是对 sql.Row 的重新实现,以便获得对 StructScan 必需的基础 sql.Rows.Columns() 数据的访问。

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 返回基础的sql.Rows.Columns(),或通常由Row.Scan() 返回的延迟错误

func (*Row) Err

func (r *Row) Err() error

Err returns the error encountered while scanning.

func (*Row) Scan

func (r *Row) Scan(pointer interface{}) ([]interface{}, error)

Scan 将 Row 结果扫描进<pointer>中。<pointer>如果是结构体,则它只能是结构体的指针类型。

参数<pointer>如果为 nil,则底层直接调用 SliceScan(),将返回: []interface{},error。
参数<pointer>如果是 map[string]interface{}类型,则底层直接调用 MapScan(),将返回: nil,error。
参数<pointer>如果是 *struct,则底层直接调用 Row.scanAny(),将返回: nil,error。

type Rows

type Rows struct {
	*sql.Rows

	Mapper *reflectx.Mapper
	// contains filtered or unexported fields
}

Rows 是对 sql.Rows 的扩展

func NamedQuery

func NamedQuery(e Ext, query string, arg interface{}) (*Rows, error)

NamedQuery binds a named query and then runs Query on the result using the provided Ext (sqlx.Tx, sqlx.Db). It works with both structs and with map[string]interface{} types.

func QueryNContext

func QueryNContext(ctx context.Context, e ExtContext, query string, arg interface{}) (*Rows, error)

NamedQueryContext binds a named query and then runs Query on the result using the provided Ext (sqlx.Tx, sqlx.Db). It works with both structs and with map[string]interface{} types.

func (*Rows) ScanX added in v1.3.3

func (r *Rows) ScanX(pointer ...interface{}) ([]interface{}, error)

ScanX (原StructScan) 类似于 sql.Rows.Scan,但是是将单个Row扫描到单个Struct中。

使用此方法,并在Select() 的内存负载可能过高的情况下,手动遍历Rows。
Rows.StructScan缓存将列位置匹配到字段的反射工作,以避免每次扫描的开销。
这意味着在具有不同结构类型的同一Rows实例上运行StructScan是不安全的。

参数<pointer>如果为 nil,则底层直接调用 SliceScan(),将返回: []interface{},error。
参数<pointer>如果是 map[string]interface{}类型,则底层直接调用 MapScan(),将返回: nil,error。
参数<pointer>如果是结构体,则它只能是结构体的指针类型。

type Stmt

type Stmt struct {
	*sql.Stmt

	Mapper *reflectx.Mapper
	// contains filtered or unexported fields
}

Stmt 是 sql.Stmt 的扩展。

func PrepareX

func PrepareX(p IPrepare, query string) (*Stmt, error)

PrepareX 准备 stmt

func PrepareXCtx

func PrepareXCtx(ctx context.Context, p IPrepareContext, query string) (*Stmt, error)

PrepareXCtx (原PrepareXContext)prepares a statement. The provided context is used for the preparation of the statement, not for the execution of the statement.

func (*Stmt) ExecPanic

func (s *Stmt) ExecPanic(args ...interface{}) sql.Result

ExecPanic 原(MustExec) (panic) using this statement.

请注意,错误输出的查询部分将为空白,因为Stmt不会公开其查询。
任何占位符参数都将替换为提供的args。

func (*Stmt) ExecPanicCtx

func (s *Stmt) ExecPanicCtx(ctx context.Context, args ...interface{}) sql.Result

ExecPanicCtx (原MustExecContext)(panic) using this statement. Note that the query portion of the error output will be blank, as Stmt does not expose its query. Any placeholder parameters are replaced with supplied args.

func (*Stmt) QueryRowX

func (s *Stmt) QueryRowX(args ...interface{}) *Row

QueryRowX using this statement.

任何占位符参数都将替换为提供的args。

func (*Stmt) QueryRowXCtx

func (s *Stmt) QueryRowXCtx(ctx context.Context, args ...interface{}) *Row

QueryRowXCtx(原QueryRowXContext) using this statement. Any placeholder parameters are replaced with supplied args.

func (*Stmt) QueryX

func (s *Stmt) QueryX(args ...interface{}) (*Rows, error)

QueryX using this statement.

任何占位符参数都将替换为提供的args。

func (*Stmt) QueryXCtx

func (s *Stmt) QueryXCtx(ctx context.Context, args ...interface{}) (*Rows, error)

func (*Stmt) Select

func (s *Stmt) Select(pointer interface{}, args ...interface{}) error

Select 查询多行记录,并将结果扫描进<pointer>中,参数<pointer>可以是 struct/*struct。

任何占位符参数都将替换为提供的args。

func (*Stmt) SelectCtx

func (s *Stmt) SelectCtx(ctx context.Context, dest interface{}, args ...interface{}) error

SelectCtx (原SelectContext)using the prepared statement. Any placeholder parameters are replaced with supplied args.

func (*Stmt) Take

func (s *Stmt) Take(pointer interface{}, args ...interface{}) error

Take (原Get) 查询一条记录,并将结果扫描进<pointer>中,参数<pointer>可以是 struct/*struct。

任何占位符参数都将替换为提供的args。如果结果集为空,则返回错误。

func (*Stmt) TakeCtx

func (s *Stmt) TakeCtx(ctx context.Context, dest interface{}, args ...interface{}) error

TakeCtx (原GetContext)using the prepared statement. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

func (*Stmt) Unsafe

func (s *Stmt) Unsafe() *Stmt

Unsafe 返回一个Stmt版本,当SQL结果中的列在目标结构中没有字段时,它将以静默方式成功扫描。

type StmtN

type StmtN struct {
	Stmt        *Stmt
	Params      []string
	QueryString string
}

StmtN (原NamedStmt) 是执行命名参数查询的预加载语句。

准备如何执行 NamedQuery,但在执行时传入结构体或map。

func (*StmtN) Close

func (n *StmtN) Close() error

Close closes the named statement.

func (*StmtN) Exec

func (n *StmtN) Exec(arg interface{}) (sql.Result, error)

Exec executes a named statement using the struct passed. Any named placeholder parameters are replaced with fields from arg.

func (*StmtN) ExecCtx

func (n *StmtN) ExecCtx(ctx context.Context, arg interface{}) (sql.Result, error)

ExecContext executes a named statement using the struct passed. Any named placeholder parameters are replaced with fields from arg.

func (*StmtN) ExecPanic

func (n *StmtN) ExecPanic(arg interface{}) sql.Result

ExecPanic (原MustExec) execs a NamedStmt, panicing on error Any named placeholder parameters are replaced with fields from arg.

func (*StmtN) ExecPanicCtx

func (n *StmtN) ExecPanicCtx(ctx context.Context, arg interface{}) sql.Result

MustExecContext execs a NamedStmt, panicing on error Any named placeholder parameters are replaced with fields from arg.

func (*StmtN) Query

func (n *StmtN) Query(arg interface{}) (*sql.Rows, error)

Query executes a named statement using the struct argument, returning rows. Any named placeholder parameters are replaced with fields from arg.

func (*StmtN) QueryCtx

func (n *StmtN) QueryCtx(ctx context.Context, arg interface{}) (*sql.Rows, error)

QueryContext executes a named statement using the struct argument, returning rows. Any named placeholder parameters are replaced with fields from arg.

func (*StmtN) QueryRow

func (n *StmtN) QueryRow(arg interface{}) *Row

QueryRow executes a named statement against the database. Because sqlx cannot create a *sql.Row with an error condition pre-set for binding errors, sqlx returns a *sqlx.Row instead. Any named placeholder parameters are replaced with fields from arg.

func (*StmtN) QueryRowCtx

func (n *StmtN) QueryRowCtx(ctx context.Context, arg interface{}) *Row

QueryRowContext executes a named statement against the database. Because sqlx cannot create a *sql.Row with an error condition pre-set for binding errors, sqlx returns a *sqlx.Row instead. Any named placeholder parameters are replaced with fields from arg.

func (*StmtN) QueryRowX

func (n *StmtN) QueryRowX(arg interface{}) *Row

QueryRowX this NamedStmt. Because of limitations with QueryRow, this is an alias for QueryRow. Any named placeholder parameters are replaced with fields from arg.

func (*StmtN) QueryRowXCtx

func (n *StmtN) QueryRowXCtx(ctx context.Context, arg interface{}) *Row

QueryRowxContext this NamedStmt. Because of limitations with QueryRow, this is an alias for QueryRow. Any named placeholder parameters are replaced with fields from arg.

func (*StmtN) QueryX

func (n *StmtN) QueryX(arg interface{}) (*Rows, error)

QueryX using this NamedStmt Any named placeholder parameters are replaced with fields from arg.

func (*StmtN) QueryXCtx

func (n *StmtN) QueryXCtx(ctx context.Context, arg interface{}) (*Rows, error)

QueryxContext using this NamedStmt Any named placeholder parameters are replaced with fields from arg.

func (*StmtN) Select

func (n *StmtN) Select(pointer interface{}, arg interface{}) error

Select 查询多行记录,并将结果扫描进<pointer>中,参数<pointer>可以是 struct/*struct。

任何占位符参数都将替换为提供的args。

func (*StmtN) SelectCtx

func (n *StmtN) SelectCtx(ctx context.Context, dest interface{}, arg interface{}) error

SelectContext using this NamedStmt Any named placeholder parameters are replaced with fields from arg.

func (*StmtN) Take

func (n *StmtN) Take(pointer interface{}, arg interface{}) error

Take (原Get) 查询一条记录,并将结果扫描进<pointer>中,参数<pointer>可以是 struct/*struct。

任何占位符参数都将替换为提供的args。如果结果集为空,则返回错误。

func (*StmtN) TakeCtx

func (n *StmtN) TakeCtx(ctx context.Context, dest interface{}, arg interface{}) error

GetContext using this NamedStmt Any named placeholder parameters are replaced with fields from arg.

func (*StmtN) Unsafe

func (n *StmtN) Unsafe() *StmtN

Unsafe creates an unsafe version of the NamedStmt

type Tx

type Tx struct {
	*sql.Tx

	Mapper *reflectx.Mapper
	// contains filtered or unexported fields
}

Tx 是对 sql.Tx 的扩展。

func (*Tx) BindNamed

func (tx *Tx) BindNamed(query string, arg interface{}) (string, []interface{}, error)

BindNamed binds a query within a transaction's bindvar type.

func (*Tx) DriverName

func (tx *Tx) DriverName() string

DriverName 返回开始该事务的数据库使用的 driverName。

func (*Tx) ExecN

func (tx *Tx) ExecN(query string, arg interface{}) (sql.Result, error)

ExecN (原NamedExec) 区别于原生的 Tx.Query(),它支持命名参数执行SQL语句。

任何命名的占位符参数都将替换为arg中的字段。

func (*Tx) ExecNCtx

func (tx *Tx) ExecNCtx(ctx context.Context, query string, arg interface{}) (sql.Result, error)

NamedExecContext using this Tx. Any named placeholder parameters are replaced with fields from arg.

func (*Tx) ExecPanic

func (tx *Tx) ExecPanic(query string, args ...interface{}) sql.Result

ExecPanic (原MustExec)区别于原生的 Tx.Exec(),如果执行出错,它内部会 panic。

任何占位符参数都将替换为提供的args。

func (*Tx) ExecPanicCtx

func (tx *Tx) ExecPanicCtx(ctx context.Context, query string, args ...interface{}) sql.Result

MustExecContext runs MustExecContext within a transaction. Any placeholder parameters are replaced with supplied args.

func (*Tx) PrepareN

func (tx *Tx) PrepareN(query string) (*StmtN, error)

PrepareNamed 返回一个 *sqlx.NamedStmt

func (*Tx) PrepareNCtx

func (tx *Tx) PrepareNCtx(ctx context.Context, query string) (*StmtN, error)

PrepareNamedContext returns an sqlx.NamedStmt

func (*Tx) PrepareX

func (tx *Tx) PrepareX(query string) (*Stmt, error)

PrepareX a statement within a transaction.

func (*Tx) PrepareXCtx

func (tx *Tx) PrepareXCtx(ctx context.Context, query string) (*Stmt, error)

PreparexContext returns an sqlx.Stmt instead of a sql.Stmt.

The provided context is used for the preparation of the statement, not for the execution of the statement.

func (*Tx) QueryN

func (tx *Tx) QueryN(query string, arg interface{}) (*Rows, error)

QueryN (原NamedQuery) 区别于原生的 Tx.Query(),它支持命名参数查询多条记录。

任何命名的占位符参数都将替换为arg中的字段。

func (*Tx) QueryRowX

func (tx *Tx) QueryRowX(query string, args ...interface{}) *Row

QueryRowX 区别于 database/sql 包下的原生 Tx.QueryRow()

任何占位符参数都将替换为提供的args。

func (*Tx) QueryRowXCtx

func (tx *Tx) QueryRowXCtx(ctx context.Context, query string, args ...interface{}) *Row

QueryRowxContext within a transaction and context. Any placeholder parameters are replaced with supplied args.

func (*Tx) QueryX

func (tx *Tx) QueryX(query string, args ...interface{}) (*Rows, error)

QueryX 区别于 database/sql 包下的原生 Tx.Query()

任何占位符参数都将替换为提供的args。

func (*Tx) QueryXCtx

func (tx *Tx) QueryXCtx(ctx context.Context, query string, args ...interface{}) (*Rows, error)

QueryxContext within a transaction and context. Any placeholder parameters are replaced with supplied args.

func (*Tx) Rebind

func (tx *Tx) Rebind(query string) string

Rebind 事务的bindVar类型的查询。

func (*Tx) Select

func (tx *Tx) Select(pointer interface{}, query string, args ...interface{}) error

Select 通过事务查询多条数据,并将结果扫描进<pointer>中,参数<pointer>可以是 struct/*struct。

任何占位符参数都将替换为提供的args。

func (*Tx) SelectCtx

func (tx *Tx) SelectCtx(ctx context.Context, dest interface{}, query string, args ...interface{}) error

SelectContext within a transaction and context. Any placeholder parameters are replaced with supplied args.

func (*Tx) StmtN

func (tx *Tx) StmtN(stmt *StmtN) *StmtN

NamedStmt 返回在事务中运行的prepared语句的版本,返回一个 *sqlx.NamedStmt

func (*Tx) StmtNCtx

func (tx *Tx) StmtNCtx(ctx context.Context, stmt *StmtN) *StmtN

NamedStmtContext returns a version of the prepared statement which runs within a transaction.

func (*Tx) StmtX

func (tx *Tx) StmtX(stmt interface{}) *Stmt

StmtX 返回在事务中运行的 prepared语句的版本。提供的stmt可以是 *sql.Stmt 或 *sqlx.Stmt。

func (*Tx) StmtXCtx

func (tx *Tx) StmtXCtx(ctx context.Context, stmt interface{}) *Stmt

StmtxContext returns a version of the prepared statement which runs within a transaction. Provided stmt can be either *sql.Stmt or *sqlx.Stmt.

func (*Tx) Take

func (tx *Tx) Take(pointer interface{}, query string, args ...interface{}) error

Take 通过事务查询任意一条数据,并将结果扫描进<pointer>中,参数<pointer>可以是 struct/*struct。

任何占位符参数都将替换为提供的参数。如果结果集为空,则返回错误。

func (*Tx) TakeCtx

func (tx *Tx) TakeCtx(ctx context.Context, dest interface{}, query string, args ...interface{}) error

GetContext within a transaction and context. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

func (*Tx) Unsafe

func (tx *Tx) Unsafe() *Tx

Unsafe returns a version of Tx which will silently succeed to scan when columns in the SQL result have no fields in the destination struct.

type Users added in v1.3.3

type Users struct {
	Id          int            `form:"id" json:"id" d:"id"`
	Name        string         `form:"name" json:"name" d:"name"`
	Status      int            `form:"status" json:"status" d:"status"`
	SuccessTime sql.NullString `form:"-" json:"success_time" d:"success_time"`
	CreatedAt   time.Time      `form:"-" json:"created_at" d:"created_at" time_format:"2006-01-02 15:04:05"`
	UpdatedAt   time.Time      `form:"-" json:"updated_at" d:"updated_at" time_format:"2006-01-02 15:04:05"`
}

Directories

Path Synopsis
软件包 reflects 实现了对标准反射库的扩展,适用于实现编组和解组软件包。
软件包 reflects 实现了对标准反射库的扩展,适用于实现编组和解组软件包。

Jump to

Keyboard shortcuts

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