sq

package module
v1.0.0 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: 19 Imported by: 0

README

#一、sq简介:

  • sq 是对 sqlx 的简单封装。这意味着sq能直接调用sqlxAPI

  • 大部分APIdatabase/sql包下的API同名。

  • 只有Take()Select()这2个API是自定义API。 ##二、使用方法:

package main

import (
    _ "github.com/go-sql-driver/mysql" //mysql driver
    "gitee.com/gopher2011/sq"
)

func main(){
    configs := make(map[string]*sq.Config)

    configs["default"] = &sq.Config{
        Enable:  true,
        Driver:  "mysql",
        DSN:     "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=True&loc=Asia%2FShanghai",
        ShowSql: true,
    }

    //connection database
    sq.Open(configs)
    sq.QueryRowX("select * from users where id = 1")
}

###1、使用 default 数据库, 就能使用sq内置的函数CRUD数据库。

  • 直接使用SQL语句操作数据库
//Exec
sq.Exec("insert into users(name,email,created_at,updated_at) value(?,?,?,?)","test","test@gmail.com",time.Now(),time.Now())

//QueryX
rows,err := sq.QueryX("select * from users")
for rows.Next() {
    user := &Users{}
    err = rows.StructScan(user)
}
rows.Close()

//QueryRowX
user := &Users{}
err := sq.QueryRowX("select * from users where id = ?",1).StructScan(user)

//Take
user := &Users{}
err := sq.Take(user,"select * from users where id = ?",1)

//Select
users := make([]*Users)
err := sq.Select(&users,"select * from users")

//Change database
db := sq.Use("test")
db.QueryX("select * from tests")

也可以设置默认的数据库连接名,例如: 以下操作设置默认数据库为log

sq.SetDefaultLink("log")
sq.Open(configs)

gosql.Get etc., will use the configuration with the connection name log

###2、使用结构体操作数据库。

  • 使用ModelStructAPI操作数据库。
type Users struct {
	Id        int       `db:"id"`
	Name      string    `db:"name"`
	Email     string    `db:"email"`
	Status    int       `db:"status"`
	CreatedAt time.Time `db:"created_at"`
	UpdatedAt time.Time `db:"updated_at"`
}

func (u *Users) TableName() string {
	return "users"
}

func (u *Users) PK() string {
	return "id"
}

//Take
user := &Users{}
sq.Model(user).Where("id=?",1).Take()

//Select
user := make([]*Users,0)
sq.Model(&user).Select()

//Insert and auto set CreatedAt
sq.Model(&User{Name:"test",Email:"test@gmail.com"}).Insert()

//Update
sq.Model(&User{Name:"test2",Email:"test@gmail.com"}).Where("id=?",1).Update()
//If you need to update the zero value, you can do so
sq.Model(&User{Status:0}).Where("id=?",1).Update("status")

//Delete
sq.Model(&User{}).Where("id=?",1).Delete()

使用结构体构造where条件

//Take where id = 1 and name = "test1"
user := &Users{Id:1,Name:"test1"}
sq.Model(&user).Take()

//Update default use primary key as the condition
sq.Model(&User{Id:1,Name:"test2"}).Update()
//Use custom conditions
//Builder => UPDATE users SET `id`=?,`name`=?,`updated_at`=? WHERE (status = ?)
sq.Model(&User{Id:1,Name:"test2"}).Where("status = ?",1).Update()

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

But the zero value is filtered by default, you can specify fields that are not filtered. For example

user := &Users{Id:1,Status:0}
sq.Model(&user).Take("status")

You can use the genstruct tool to quickly generate database structs

Transaction

The Tx function has a callback function, if an error is returned, the transaction rollback

sq.Tx(func(tx *sq.DB) error {
    for id := 1; id < 10; id++ {
        user := &Users{
            Id:    id,
            Name:  "test" + strconv.Itoa(id),
            Email: "test" + strconv.Itoa(id) + "@test.com",
        }
		
		//v2 support, do some database operations in the transaction (use 'tx' from this point, not 'gosql')
        tx.Model(user).Insert()

        if id == 8 {
            return errors.New("interrupt the transaction")
        }
    }

    //query with transaction
    var num int
    err := tx.QueryRowX("select count(*) from user_id = 1").Scan(&num)

    if err != nil {
        return err
    }

    return nil
})

If you need to invoke context, you can use gosql.Txx

Now support gosql.Begin() or gosql.Use("other").Begin() for example:

tx, err := sq.Begin()
if err != nil {
    return err
}

for id := 1; id < 10; id++ {
    _, err := tx.Exec("INSERT INTO users(id,name,status,created_at,updated_at) VALUES(?,?,?,?,?)", id, "test"+strconv.Itoa(id), 1, time.Now(), time.Now())
    if err != nil {
        return tx.Rollback()
    }
}

return tx.Commit()

Automatic time

If your fields contain the following field names, they will be updated automatically

AUTO_CREATE_TIME_FIELDS = []string{
    "create_time",
    "create_at",
    "created_at",
    "update_time",
    "update_at",
    "updated_at",
}
AUTO_UPDATE_TIME_FIELDS = []string{
    "update_time",
    "update_at",
    "updated_at",
}

Using Map

Create Update Delete Count support map[string]interface,For example:

//Insert
sq.Table("users").Insert(map[string]interface{}{
    "id":         1,
    "name":       "test",
    "email":      "test@test.com",
    "created_at": "2018-07-11 11:58:21",
    "updated_at": "2018-07-11 11:58:21",
})

//Update
sq.Table("users").Where("id = ?", 1).Update(map[string]interface{}{
    "name":  "fifsky",
    "email": "fifsky@test.com",
})

//Delete
sq.Table("users").Where("id = ?", 1).Delete()

//Count
sq.Table("users").Where("id = ?", 1).Count()

//Change database
sq.Use("db2").Table("users").Where("id = ?", 1).Count()

//Transaction `tx`
tx.Table("users").Where("id = ?", 1}).Count()

sql.Null*

Now Model support sql.Null* field's, Note, however, that if sql.Null* is also filtered by zero values,For example

type Users struct {
	Id          int            `db:"id"`
	Name        string         `db:"name"`
	Email       string         `db:"email"`
	Status      int            `db:"status"`
	SuccessTime sql.NullString `db:"success_time" json:"success_time"`
	CreatedAt   time.Time      `db:"created_at" json:"created_at"`
	UpdatedAt   time.Time      `db:"updated_at" json:"updated_at"`
}

user := &Users{
    Id: 1,
    SuccessTime: sql.NullString{
        String: "2018-09-03 00:00:00",
        Valid:  false,
    }
}

err := sq.Model(user).Take()

Builder SQL:

Query: SELECT * FROM users WHERE (id=?);
Args:  []interface {}{1}
Time:  0.00082s

If sql.NullString of Valid attribute is false, SQL builder will ignore this zero value

sq.Expr

Reference GORM Expr, Resolve update field self-update problem

sq.Table("users").Update(map[string]interface{}{
    "id":2,
    "count":gosql.Expr("count+?",1)
})
//Builder SQL
//UPDATE `users` SET `count`=count + ?,`id`=?; [1 2]

"In" Queries

Because database/sql does not inspect your query and it passes your arguments directly to the driver, it makes dealing with queries with IN clauses difficult:

SELECT * FROM users WHERE level IN (?);

sqlx.In is encapsulated In gosql and can be queried using the following schema

var levels = []int{4, 6, 7}
rows, err := sq.QueryX("SELECT * FROM users WHERE level IN (?);", levels)

//or

user := make([]*Users, 0)
err := gosql.Select(&user, "select * from users where id in(?)",[]int{1,2,3})

Relation

gosql used the golang structure to express the relationships between tables,You only need to use the relation Tag to specify the associated field, see example

⚠️ Since version v2, the relation query across library connections needs to be specified using connection tag

type MomentList struct {
	models.Moments
	User   *models.Users    `json:"user" db:"-" relation:"user_id,id"`         //one-to-one
	Photos []*models.Photos `json:"photos" db:"-" relation:"id,moment_id" connection:"db2"`     //one-to-many
}

Get single result

moment := &MomentList{}
err := sq.Model(moment).Where("status = 1 and id = ?",14).Take()
//output User and Photos and you get the result

SQL:

2018/12/06 13:27:54
	Query: SELECT * FROM `moments` WHERE (status = 1 and id = ?);
	Args:  []interface {}{14}
	Time:  0.00300s

2018/12/06 13:27:54
	Query: SELECT * FROM `moment_users` WHERE (id=?);
	Args:  []interface {}{5}
	Time:  0.00081s

2018/12/06 13:27:54
	Query: SELECT * FROM `photos` WHERE (moment_id=?);
	Args:  []interface {}{14}
	Time:  0.00093s

Get list result, many-to-many

var moments = make([]*MomentList, 0)
err := sq.Model(&moments).Where("status = 1").Limit(10).Select()
//You get the total result  for *UserMoment slice

SQL:

2018/12/06 13:50:59
	Query: SELECT * FROM `moments` WHERE (status = 1) LIMIT 10;
	Time:  0.00319s

2018/12/06 13:50:59
	Query: SELECT * FROM `moment_users` WHERE (id in(?));
	Args:  []interface {}{[]interface {}{5}}
	Time:  0.00094s

2018/12/06 13:50:59
	Query: SELECT * FROM `photos` WHERE (moment_id in(?, ?, ?, ?, ?, ?, ?, ?, ?, ?));
	Args:  []interface {}{[]interface {}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}
	Time:  0.00087s

Relation Where:

moment := &MomentList{}
err := sq.Relation("User" , func(b *sq.ModelStruct) {
    //this is builder instance,
    b.Where("gender = 0")
}).Take(moment , "select * from moments")

Hooks

Hooks are functions that are called before or after creation/querying/updating/deletion.

If you have defiend specified methods for a model, it will be called automatically when creating, updating, querying, deleting, and if any callback returns an error, gosql will stop future operations and rollback current transaction.

// begin transaction
BeforeChange
BeforeCreate
// update timestamp `CreatedAt`, `UpdatedAt`
// save
AfterCreate
AfterChange
// commit or rollback transaction

Example:

func (u *Users) BeforeCreate() (err error) {
  if u.IsValid() {
    err = errors.New("can't save invalid data")
  }
  return
}

func (u *Users) AfterCreate(tx *gosql.DB) (err error) {
  if u.Id == 1 {
    u.Email = "after@test.com"
    tx.Model(u).Update()
  }
  return
}

BeforeChange and AfterChange only used in create/update/delete

All Hooks:

BeforeChange
AfterChange
BeforeCreate
AfterCreate
BeforeUpdate
AfterUpdate
BeforeDelete
AfterDelete
BeforeFind
AfterFind

Hook func type supports multiple ways:

func (u *Users) BeforeCreate()
func (u *Users) BeforeCreate() (err error)
func (u *Users) BeforeCreate(tx *gosql.DB)
func (u *Users) BeforeCreate(tx *gosql.DB) (err error)

Thanks

sqlx https://github.com/jmoiron/sqlx

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	AutoCreateTimeFields = []string{
		"create_time",
		"create_at",
		"created_at",
		"update_time",
		"update_at",
		"updated_at",
	}

	AutoUpdateTimeFields = []string{
		"update_time",
		"update_at",
		"updated_at",
	}
)
View Source
var (
	FatalExit = true //如果该值为true,则当前数据库退出。

)

Functions

func Connect

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

Connect 连接数据库。

注意: 不要再显性的调用Ping()了,该函数默认已经 Ping()了。

func Exec

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

Exec default database

func Expr

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

Expr 生成原始SQL表达式,例如:

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

func GetDB

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

GetDB 获取指定的数据库引擎;如果未指定名称,则获取默认数据库。

func Import

func Import(f string) ([]sql.Result, error)

Import SQL DDL from io.Reader

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 获取数据库引擎列表。

func QueryRowX

func QueryRowX(querySql string, args ...interface{}) *sqlx.Row

QueryRow default database

func QueryX

func QueryX(querySql string, args ...interface{}) (*sqlx.Rows, error)

Query default database

func RegisterDialect

func RegisterDialect(name string, dialect Dialect)

RegisterDialect 注册一个新方言。

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(pointer interface{}, querySql string, args ...interface{}) error

Select default database

func SetDefaultLink(db string)

SetDefaultLink set default link name

func SetLogger

func SetLogger(l ILogger)

SetLogger 设置日志器。

func SetLogging

func SetLogging(print bool)

SetLogging 是否打印日志,<print>为true,则打印日志。

func Take

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

Get default database

func Tx

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

Tx default database the transaction

func TxCtx

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

TxCtx default database the transaction with context

Types

type BuildFunc

type BuildFunc func(b *Builder)

type Builder

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

Builder 模型结构体

func Ctx

func Ctx(ctx context.Context) *Builder

Model construct SQL from Struct with context

func Model

func Model(model interface{}) *Builder

Model 从结构体构造SQL

func (*Builder) Cols

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

Cols filter column

func (*Builder) Count

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

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

func (*Builder) Delete

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

Delete 删除一条记录。参数<zeroValues>即使是0值,也会被强制执行。

例如: sq.Model(&User{Id:1}).Delete()。

func (*Builder) ForceIndex

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

ForceIndex

func (*Builder) Hint

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

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

func (*Builder) Insert

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

Insert 插入一条记录。

例如: sq.Model(&User{Id:1}).Insert()

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 BuildFunc) *Builder

Relation 关联表构建器句柄

func (*Builder) Select

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

Select 查询多条记录。

func (*Builder) ShowSQL

func (b *Builder) ShowSQL() *Builder

ShowSQL 输出单条SQL

func (*Builder) Take

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

Take 查询一条记录。参数<zeroValues>即使是0值,也会被强制执行。

例如: user := &Users{Id:1,Status:0}
     sq.Model(&user).Take("status")

func (*Builder) Update

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

Update 更新一条记录。参数<zeroValues>即使是0值,也会被强制执行。

例如: sq.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 Config

type Config struct {
	Driver       string `toml:"driver" json:"driver"`
	DSN          string `toml:"dsn" json:"dsn"`
	MaxOpenConns int    `toml:"max_open_conns" json:"max_open_conns"`
	MaxIdleConns int    `toml:"max_idle_conns" json:"max_idle_conns"`
	MaxLifetime  int    `toml:"max_lefttime" json:"max_lefttime"`
	Enable       bool   `toml:"enable" json:"enable"`
	ShowSql      bool   `toml:"show_sql" json:"show_sql"` // 是否显示SQL语句,ture:显示,false:不显示。
}

Config 是数据库连接配置。

type DB

type DB struct {
	RelationMap map[string]BuildFunc // // 用来构造一个 Builder 对象的map容器。
	// contains filtered or unexported fields
}

func Begin

func Begin() (*DB, error)

Begin 开始默认数据库的事务,并返回 *sq.DB而不是 *sql.Tx。

func NewDB

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

NewDB 通过*sql.DB,返回一个 *sq.DB 对象。

func Open

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

Open 打开一个数据库连接。返回一个 *sq.DB。

注意: 不要再显性的调用Ping()了,该函数默认已经 Ping()了。

func Relation

func Relation(name string, fn BuildFunc) *DB

Relation association table builder handle

func ShowSql

func ShowSql() *DB

ShowSql single show sql log

func Use

func Use(db string) *DB

Use 变更数据库。

func (*DB) Begin

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

Begin 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) Ctx

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

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

func (*DB) DriverName

func (w *DB) DriverName() string

DriverName wrapper sqlx.DriverName

func (*DB) Exec

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

Exec 执行: 增、删、改操作。

参数 <sqlStr> 是具体的SQL语句;参数 <args> 是SQL语句需要的参数。

func (*DB) ExecN

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

ExecN wrapper *sqlx.ExecN

func (*DB) Import

func (w *DB) Import(fileName string) ([]sql.Result, error)

Import sql文件中的SQL DDL

func (*DB) Model

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

Model database handler from to struct

for example:
sq.Use("db2").Model(&users{})

func (*DB) PrepareX

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

func (*DB) QueryRowX

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

QueryRowX 查询一条记录。

参数 <querySql> 是具体的SQL语句;参数 <args> 是SQL语句需要的参数。
注意: 返回的是 *sqlx.Row 而不是 *sql.Row

func (*DB) QueryX

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

QueryX 查询多条记录。

参数 <querySql> 是具体的SQL语句;参数 <args> 是SQL语句需要的参数。
注意: 返回的是 *sqlx.Rows 而不是 *sql.Rows

func (*DB) Rebind

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

Rebind wrapper sqlx.Rebind

func (*DB) Relation

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

Relation 关联表构建器句柄。

func (*DB) Rollback

func (w *DB) Rollback() error

Rollback aborts the transaction.

func (*DB) Select

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

Select 快捷方式,查询多条记录,并将查询结果扫描进 <pointer>。

参数 <querySql> 是具体的SQL语句;参数 <args> 是SQL语句需要的参数。

func (*DB) Table

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

Table database handler from to table name

for example:
sq.Use("db2").Table("users")

func (*DB) Take

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

Take 快捷方式,查询一条记录,并将查询结果扫描进 <pointer>。

参数 <querySql> 是具体的SQL语句;参数 <args> 是SQL语句需要的参数。

func (*DB) Tx

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

Tx the transaction

func (*DB) TxCtx

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

TxCtx the transaction with context

type Dialect

type Dialect interface {
	GetName() string         // GetName 放回当前正在使用的方言(例如:mysql,mssql...)
	Quote(key string) string // Quote 通过使用保留字作为字段名来对字段名加引号,以避免SQL解析异常
}

Dialect 处理不同SQL数据库的方言。

func GetDialect

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

GetDialect 获取指定方言名称的方言。

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 ILogger

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

ILogger 表示一个日志收集器. 您可以将日志收集器传递给 sq.SetLogger(myCollector),以使其在执行查询后收集QueryStatus消息。

type IModel

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

Model interface

type ISql

type ISql interface {
	// Query 参数<querySql>是查询类的SQL语句,<args>是SQL语句的参数。
	QueryX(querySql string, args ...interface{}) (*sqlx.Rows, error)
	// QueryRow 参数<querySql>是查询类的SQL语句,<args>是SQL语句的参数。
	QueryRowX(querySql string, args ...interface{}) *sqlx.Row
	// 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
	// Exec 增、删、改操作的接口。
	//  参数<querySql>是查询类的SQL语句,<args>是SQL语句的参数。
	Exec(querySql string, args ...interface{}) (sql.Result, error)
	PrepareX(query string) (*sqlx.Stmt, error)
	// Rebind 绑定 querySql 语句。
	Rebind(querySql string) string
	//
	ExecN(query string, arg interface{}) (sql.Result, error)
	// DriverName 获取当前处于连接状态的 *sql.DB 的驱动名称。
	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 Mapper

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

func Table

func Table(tableName string) *Mapper

Table 选择表名

func (*Mapper) Count

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

Count

func (*Mapper) Delete

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

Delete 物理删除一条记录。

func (*Mapper) Insert

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

Insert 插入一条记录。

func (*Mapper) ShowSQL

func (m *Mapper) ShowSQL() *Mapper

ShowSQL 显示SQL语句

func (*Mapper) Update

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

Update 更新一条记录。

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 表示查询执行后的状态。

func (*QueryStatus) String

func (q *QueryStatus) String() string

String 返回格式化的日志消息。

type ReflectMapper

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

ReflectMapper 数据库字段与结构体属性的反射映射器。

func NewReflectMapper

func NewReflectMapper(tagName string) *ReflectMapper

NewReflectMapper 输入<tagName>返回一个 反射映射器对象。

func (*ReflectMapper) FieldByName

func (r *ReflectMapper) FieldByName(v reflect.Value, name string) reflect.Value

FieldByName 通过其映射名称返回字段,即 reflect.Value。

如果v的Kind不是Struct或v不可间接访问结构体,则会 panic。
如果找不到名称,则返回零值。

func (*ReflectMapper) FieldMap

func (r *ReflectMapper) FieldMap(v reflect.Value) map[string]reflect.Value

FieldMap 返回映射器对字段名称的映射以反映值。

如果 v不是结构体指针,或者不是结果体,则会panic。

type SqlBuilder

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

SQL语句构造器

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