gomodel

package module
Version: v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2017 License: MIT Imports: 8 Imported by: 0

README

gomodel wercker status GoDoc

gomodel provide another method to interact with database.
Instead of reflection, use bitset represent fields of CRUD, sql/stmt cache and generate model code for you, high performance.

Install

$ go get github.com/cosiner/gomodel
$ cd /path/of/gomodel/cmd/gomodel
$ go install # it will install the gomodel binary file to your $GOPATH/bin
$ gomodel -cp # copy model.tmpl to default path $HOME/.config/go/model.tmpl
              # or just put it to your model package, gomodel will search it first 
$ # if need customed template, just copy model.tmpl to your models directory

The gomodel cmd tool and SQL convertion for structures.

There is a detailed example User-Follow.

User
var (
    ErrDuplicateUserName = httperrs.Conflict.NewS("user name already exists")
    ErrNoUser            = httperrs.NotFound.NewS("user not found")
)

type User struct {
    Id   int64
    Name string
    Age  int

    Followings int
    Followers  int
}

func (u *User) Add() error {
    u.Followings = 0
    u.Followers = 0

    id, err := DB.Insert(u, userFieldsExcpId, gomodel.RES_ID)
    err = dberrs.DuplicateKeyError(err, UserNameCol, ErrDuplicateUserName)
    if err == nil {
        u.Id = id
    }

    return err
}

func DeleteUserById(id int64) error {
    c, err := DB.ArgsDelete(userInstance, USER_ID, id)

    return dberrs.NoAffects(c, err, ErrNoUser)
}

func (u *User) Update() error {
    c, err := DB.Update(u, USER_NAME|USER_AGE, USER_ID)

    return dberrs.NoAffects(c, err, ErrNoUser)
}

func (u *User) ById() error {
    err := DB.One(u, userFieldsExcpId, USER_ID)

    return dberrs.NoRows(err, ErrNoUser)
}

func UsersByAge(age, start, count int) ([]User, error) {
    users := userStore{
        Fields: userFieldsAll,
    }

    err := DB.ArgsLimit(&users, userInstance, userFieldsAll, USER_AGE, age, start, count)
    return users.Values, dberrs.NoRows(err, ErrNoUser)
}

func AllUsersByAge(age int) ([]User, error) {
    users := userStore{
        Fields: userFieldsAll,
    }

    err := DB.ArgsAll(&users, userInstance, userFieldsAll, USER_AGE, age)
    return users.Values, dberrs.NoRows(err, ErrNoUser)
}
Follow
var (
    ErrFollowed  = httperrs.Conflict.NewS("already followed")
    ErrNonFollow = httperrs.NotFound.NewS("non follow")
)

type Follow struct {
    UserId       int64 `table:"user_follow"`
    FollowUserId int64
}


//gomodel insertUserFollowSQL = [
//  INSERT INTO Follow(UserId, FollowUserId)
//      SELECT ?, ? FROM DUAL
//      WHERE EXISTS(SELECT Id FROM User WHERE Id=?)
//]
func (f *Follow) Add() error {
    return f.txDo(DB, func(tx gomodel.Tx, f *Follow) error {
        c, err := tx.UpdateById(insertUserFollowSQL, gomodel.FieldVals(f, followFieldsAll, f.FollowUserId)...)

        err = dberrs.NoAffects(c, err, ErrNoUser)
        err = dberrs.DuplicateKeyError(err, dberrs.PRIMARY_KEY, ErrFollowed)

        return f.updateFollowInfo(tx, err, 1)
    })
}

func (f *Follow) Delete() error {
    return f.txDo(DB, func(tx gomodel.Tx, f *Follow) error {
        c, err := tx.Delete(f, followFieldsAll)
        err = dberrs.NoAffects(c, err, ErrNonFollow)

        return f.updateFollowInfo(tx, err, -1)
    })
}

func (f *Follow) updateFollowInfo(tx gomodel.Tx, err error, c int) error {
    if err == nil {
        _, err = tx.ArgsIncrBy(userInstance, USER_FOLLOWINGS, USER_ID, c, f.UserId)
        if err == nil {
            _, err = tx.ArgsIncrBy(userInstance, USER_FOLLOWERS, USER_ID, c, f.FollowUserId)
        }
    }
    return err
}

LICENSE

MIT.

Documentation

Overview

Package gomodel is a library help for interact with database efficiently

Index

Constants

View Source
const (
	STMT_CLOSEABLE = true
	STMT_NOPCLOSE  = false
)
View Source
const (
	MAX_NUMFIELDS = 30
)

Variables

This section is empty.

Functions

func AllFieldsExcp added in v0.6.2

func AllFieldsExcp(allFields uint64, fields ...uint64) uint64

AllFieldsExcp create fieldset except given fields

func AllFieldsOrSome added in v0.6.3

func AllFieldsOrSome(allFields uint64, fields ...uint64) uint64

func CloseExec

func CloseExec(stmt Stmt, err error, typ ResultType, args ...interface{}) (int64, error)

Exec execute stmt with given arguments and resolve the result if error is nil

func CloseUpdate

func CloseUpdate(stmt Stmt, err error, args ...interface{}) (int64, error)

Update always returl the count of affected rows

func Exec

func Exec(stmt Stmt, err error, typ ResultType, args ...interface{}) (int64, error)

Exec execute stmt with given arguments and resolve the result if error is nil

func FieldPtrs

func FieldPtrs(model Model, fields uint64, args ...interface{}) []interface{}

FieldPtrs is similar to FieldVals, but for field pointers. FieldPtrs only used for query operations such as One, Limit, All.

func FieldVals

func FieldVals(model Model, fields uint64, args ...interface{}) []interface{}

FieldVals will extract values of fields from model, and concat with remains arguments

func Fields added in v0.6.3

func Fields(fields ...uint64) uint64

func FieldsIdentity

func FieldsIdentity(sqlType SQLType, numField, fields, whereFields uint64) uint64

FieldsIdentity create signature from fields

func NewSqlId

func NewSqlId(create func(Executor) string) (id uint64)

NewSqlId create an id for this sql creator used in methods like XXXById

func NumFields

func NumFields(n uint64) int

func NumFieldsExcp added in v0.6.2

func NumFieldsExcp(numField uint64, fields ...uint64) uint64

NumFieldsExcp create fieldset except given fields

func OnlyParamed added in v0.6.2

func OnlyParamed(n int) string

func ResolveResult

func ResolveResult(res sql.Result, err error, typ ResultType) (int64, error)

ResolveResult resolve sql result, if need id, return last insert id else return affected rows count

func SQLPrint

func SQLPrint(enable bool, printer func(formart string, v ...interface{}))

SQLPrint enable sql print for each operation

func SqlById added in v0.6.3

func SqlById(executor Executor, id uint64) string

func Update

func Update(stmt Stmt, err error, args ...interface{}) (int64, error)

Update always returl the count of affected rows

Types

type ColNum added in v0.6.2

type ColNum int

type Cols

type Cols interface {
	// Cols return colum names
	Names() []string
	// String return columns string join with ",",
	// result like "foo, bar"
	String() string

	// Paramed return columns string joind with "=?,", last "," was trimed,
	// result like "foo=?, bar=?"
	Paramed() string

	// IncrParamed: result like "foo=foo+?, bar=bar+?"
	IncrParamed() string

	// OnlyParam return columns placeholdered string,
	// each column was replaced with "?"
	// result like "?, ?, ?, ?", count of "?" is colums length
	OnlyParam() string

	// Join append suffix string to each columns then join them with the seperator
	Join(suffix, sep string) string

	// Length return columns count
	Length() int
}

type Columner

type Columner interface {
	// Columns return all column names for this Model
	Columns() []string
}

Columner is a optional interface for Model, if Model implements this interface, it's no need to parse Model info with reflection

type DB

type DB struct {
	*sql.DB

	// initial models count for select 'All', default 20
	InitialModels int
	// contains filtered or unexported fields
}

DB holds database connections, store all tables

func NewDB

func NewDB() *DB

NewDB create a new DB instance

func Open

func Open(driver Driver, dsn string, maxIdle, maxOpen int) (*DB, error)

Open create a database manager and connect to database server

func (*DB) All

func (db *DB) All(store Store, model Model, fields, whereFields uint64) error

func (*DB) ArgsAll

func (db *DB) ArgsAll(store Store, model Model, fields, whereFields uint64, args ...interface{}) error

func (*DB) ArgsCount

func (db *DB) ArgsCount(model Model, whereFields uint64, args ...interface{}) (count int64, err error)

ArgsCount return count of rows for model use custome arguments

func (*DB) ArgsDelete

func (db *DB) ArgsDelete(model Model, whereFields uint64, args ...interface{}) (int64, error)

func (*DB) ArgsExists added in v0.6.3

func (db *DB) ArgsExists(model Model, field, whereFields uint64, args ...interface{}) (exist bool, err error)

func (*DB) ArgsIncrBy

func (db *DB) ArgsIncrBy(model Model, fields, whereFields uint64, args ...interface{}) (int64, error)

func (*DB) ArgsInsert

func (db *DB) ArgsInsert(model Model, fields uint64, resType ResultType, args ...interface{}) (int64, error)

func (*DB) ArgsLimit

func (db *DB) ArgsLimit(store Store, model Model, fields, whereFields uint64, args ...interface{}) error

The last two arguments must be "start" and "count" of limition with type "int"

func (*DB) ArgsOne

func (db *DB) ArgsOne(model Model, fields, whereFields uint64, args []interface{}, ptrs ...interface{}) error

func (*DB) ArgsUpdate

func (db *DB) ArgsUpdate(model Model, fields, whereFields uint64, args ...interface{}) (int64, error)

func (*DB) Begin

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

func (*DB) Connect

func (db *DB) Connect(driver Driver, dsn string, maxIdle, maxOpen int) error

Connect to database server

func (*DB) Count

func (db *DB) Count(model Model, whereFields uint64) (count int64, err error)

Count return count of rows for model, arguments was extracted from Model

func (*DB) Delete

func (db *DB) Delete(model Model, whereFields uint64) (int64, error)

func (*DB) Driver

func (db *DB) Driver() Driver

func (*DB) Exec

func (db *DB) Exec(sql string, resTyp ResultType, args ...interface{}) (int64, error)

func (*DB) ExecById

func (db *DB) ExecById(sqlid uint64, resTyp ResultType, args ...interface{}) (int64, error)

func (*DB) ExecUpdate

func (db *DB) ExecUpdate(sql string, args ...interface{}) (int64, error)

func (*DB) Exists added in v0.6.3

func (db *DB) Exists(model Model, field, whereFields uint64) (bool, error)

func (*DB) IncrBy

func (db *DB) IncrBy(model Model, fields, whereFields uint64, counts ...int) (int64, error)

func (*DB) Insert

func (db *DB) Insert(model Model, fields uint64, resType ResultType) (int64, error)

func (*DB) Limit

func (db *DB) Limit(store Store, model Model, fields, whereFields uint64, start, count int64) error

func (*DB) One

func (db *DB) One(model Model, fields, whereFields uint64) error

One select one row from database

func (*DB) Query added in v0.6.2

func (db *DB) Query(sql string, args ...interface{}) Scanner

func (*DB) QueryById

func (db *DB) QueryById(sqlid uint64, args ...interface{}) Scanner

func (*DB) StmtById

func (db *DB) StmtById(sqlid uint64) (Stmt, error)

func (*DB) Table

func (db *DB) Table(model Model) *Table

Table return infomation of given model if table not exist, do parse and save it

func (*DB) TxDo

func (db *DB) TxDo(do func(*Tx) error) error

func (*DB) Update

func (db *DB) Update(model Model, fields, whereFields uint64) (int64, error)

func (*DB) UpdateById

func (db *DB) UpdateById(sqlid uint64, args ...interface{}) (int64, error)

func (*DB) Use added in v0.6.3

func (db *DB) Use(driver Driver, db_ *sql.DB) error

type Driver added in v0.6.0

type Driver interface {
	String() string
	DSN(host, port, username, password, dbname string, cfg map[string]string) string
	// Prepare should replace the standard placeholder '?' with driver specific placeholder,
	// for postgresql it's '$n'
	Prepare(sql string) string
	SQLLimit() string
	ParamLimit(offset, count int) (int, int)
	PrimaryKey() string
	DuplicateKey(err error) string
	ForeignKey(err error) string
}

type Executor added in v0.6.0

type Executor interface {
	Driver() Driver
	Table(model Model) *Table
	Prepare(sql string) (*sql.Stmt, error)

	Insert(model Model, fields uint64, resType ResultType) (int64, error)
	ArgsInsert(model Model, fields uint64, resType ResultType, args ...interface{}) (int64, error)

	Update(model Model, fields, whereFields uint64) (int64, error)
	ArgsUpdate(model Model, fields, whereFields uint64, args ...interface{}) (int64, error)

	Delete(model Model, whereFields uint64) (int64, error)
	ArgsDelete(model Model, whereFields uint64, args ...interface{}) (int64, error)

	One(model Model, fields, whereFields uint64) error
	ArgsOne(model Model, fields, whereFields uint64, args []interface{}, ptrs ...interface{}) error

	Limit(store Store, model Model, fields, whereFields uint64, start, count int64) error
	ArgsLimit(store Store, model Model, fields, whereFields uint64, args ...interface{}) error

	All(store Store, model Model, fields, whereFields uint64) error
	ArgsAll(store Store, model Model, fields, whereFields uint64, args ...interface{}) error

	Count(model Model, whereFields uint64) (count int64, err error)
	ArgsCount(model Model, whereFields uint64, args ...interface{}) (count int64, err error)

	IncrBy(model Model, field, whereFields uint64, counts ...int) (int64, error)
	ArgsIncrBy(model Model, field, whereFields uint64, args ...interface{}) (int64, error)

	Exists(model Model, field, whereFields uint64) (bool, error)
	ArgsExists(model Model, field, whereFields uint64, args ...interface{}) (bool, error)

	ExecUpdate(sql string, args ...interface{}) (int64, error)
	Exec(sql string, resType ResultType, args ...interface{}) (int64, error)

	ExecById(sqlid uint64, resTyp ResultType, args ...interface{}) (int64, error)
	UpdateById(sqlid uint64, args ...interface{}) (int64, error)
	QueryById(sqlid uint64, args ...interface{}) Scanner
}

type Model

type Model interface {
	// Table return database table name that the model mapped
	Table() string
	// Vals store values of fields to given slice, the slice has length,
	// just setup value by index. The value order MUST same as fields defined
	// in strcuture
	Vals(fields uint64, vals []interface{})
	// Ptrs is similar to Vals, but for field pointers
	Ptrs(fields uint64, ptrs []interface{})
}

Model represent a database model mapping to a table

type MultipleCols added in v0.6.2

type MultipleCols struct {
	Cols []string
	// contains filtered or unexported fields
}

MultipleCols used for columns more than two

func (*MultipleCols) IncrParamed added in v0.6.3

func (c *MultipleCols) IncrParamed() string

func (*MultipleCols) Join added in v0.6.2

func (c *MultipleCols) Join(suffix, sep string) string

func (*MultipleCols) Length added in v0.6.2

func (c *MultipleCols) Length() int

func (*MultipleCols) Names added in v0.6.2

func (c *MultipleCols) Names() []string

func (*MultipleCols) OnlyParam added in v0.6.2

func (c *MultipleCols) OnlyParam() string

func (*MultipleCols) Paramed added in v0.6.2

func (c *MultipleCols) Paramed() string

func (*MultipleCols) String added in v0.6.2

func (c *MultipleCols) String() string

type Nocacher

type Nocacher interface {
	Nocache() bool
}

Nocacher is a optional interface for Model, if Model implements this interface, and NoCache method return true, it will not allocate memory to store sql, stmt, columns for this Model, all sqls, stmts must be stored in DB instance.

If Nocache, the only methods to get Stmt are DB.StmtById and Tx.PrepareById, implements it only when you actually know what are you do.

type NopCloseStmt

type NopCloseStmt struct {
	*sql.Stmt
}

func (NopCloseStmt) Close

func (s NopCloseStmt) Close() error

type ResultType

type ResultType int
const (
	RES_NO   ResultType = iota // don't resolve sql.Result
	RES_ID                     // Result.LastInsertID
	RES_ROWS                   // Result.RowsAffected
)

type SQLBuilder

type SQLBuilder func(driver Driver, fields, whereFields uint64) string

SQLBuilder build sql for model using fields and where fields

type SQLPrinter

type SQLPrinter func(string, ...interface{})

func (SQLPrinter) Print

func (p SQLPrinter) Print(fromcache bool, sql string)

type SQLType

type SQLType uint64
const (
	// These are several predefined sql types
	INSERT SQLType = iota << (MAX_NUMFIELDS * 2)
	DELETE
	UPDATE
	INCRBY
	LIMIT
	ONE
	ALL
	COUNT
	EXISTS
)

type Scanner

type Scanner struct {
	Error error
	Rows  *sql.Rows
	Stmt  Stmt
}

Scanner scan database rows to data Store when Error is nil, if the Rows is empty, sql.ErrNoRows was returned, the Rows will always be be Closed

func Query

func Query(stmt Stmt, err error, args ...interface{}) Scanner

Query execute the query stmt, error stored in Scanner

func (Scanner) All

func (sc Scanner) All(s Store, initsize int) error

func (Scanner) Close added in v0.6.2

func (sc Scanner) Close()

func (Scanner) Limit

func (sc Scanner) Limit(s Store, rowCount int) error

func (Scanner) One

func (sc Scanner) One(ptrs ...interface{}) error

type SingleCol added in v0.6.2

type SingleCol string

singleCol means only one column

func (SingleCol) IncrParamed added in v0.6.3

func (c SingleCol) IncrParamed() string

func (SingleCol) Join added in v0.6.2

func (c SingleCol) Join(suffix, _ string) string

func (SingleCol) Length added in v0.6.2

func (c SingleCol) Length() int

func (SingleCol) Names added in v0.6.2

func (c SingleCol) Names() []string

func (SingleCol) OnlyParam added in v0.6.2

func (c SingleCol) OnlyParam() string

func (SingleCol) Paramed added in v0.6.2

func (c SingleCol) Paramed() string

func (SingleCol) String added in v0.6.2

func (c SingleCol) String() string

type SqlIdKeeper added in v0.6.3

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

func NewSqlIdKeeper added in v0.6.3

func NewSqlIdKeeper() *SqlIdKeeper

func (*SqlIdKeeper) Get added in v0.6.3

func (s *SqlIdKeeper) Get(key string) (string, bool)

func (*SqlIdKeeper) Set added in v0.6.3

func (s *SqlIdKeeper) Set(key, val string)

type Stmt

type Stmt interface {
	Exec(...interface{}) (sql.Result, error)
	Query(...interface{}) (*sql.Rows, error)
	QueryRow(...interface{}) *sql.Row
	Close() error
}

func WrapStmt

func WrapStmt(closeable bool, stmt *sql.Stmt, err error) (Stmt, error)

type Store

type Store interface {
	// Init will be called twice, first to allocate initial data space, second to specified
	// the final row count
	// Init initial the data store with size rows, if size is not enough,
	// Realloc will be called
	Init(size int)

	// Final indicate the last found rows
	Final(size int)

	// Ptrs should store pointers of data store at given index to the ptr parameter
	Ptrs(index int, ptrs []interface{})

	// Realloc will occurred if the initial size is not enough, only occured
	// when call the All method of Scanner.
	// The return value shold be the new size of Store.
	// If don't want to continue, just return a non-positive number.
	Realloc(currSize int) (latest int)
}

Store defines the interface to store data from databqase rows

type Table

type Table struct {
	Name      string
	NumFields uint64
	// contains filtered or unexported fields
}

Table represent information of type contains field count, table name, field names, field offsets

because count sql and limit select sql is both stored in the same cache, you should not use a empty fields for limit select, that will conflict with count sql and get the wrong sql statement.

func (*Table) Col

func (t *Table) Col(field uint64) string

Col return column name of field

func (*Table) Cols

func (t *Table) Cols(fields uint64) Cols

Cols return column names for given fields if fields is only one, return single column else return column slice

func (*Table) Prepare

func (t *Table) Prepare(exec Executor, sqlType SQLType, fields, whereFields uint64, build SQLBuilder) (Stmt, error)

func (*Table) PrepareAll

func (t *Table) PrepareAll(exec Executor, fields, whereFields uint64) (Stmt, error)

func (*Table) PrepareCount

func (t *Table) PrepareCount(exec Executor, whereFields uint64) (Stmt, error)

func (*Table) PrepareDelete

func (t *Table) PrepareDelete(exec Executor, whereFields uint64) (Stmt, error)

func (*Table) PrepareExists added in v0.6.3

func (t *Table) PrepareExists(exec Executor, field, whereFields uint64) (Stmt, error)

func (*Table) PrepareIncrBy

func (t *Table) PrepareIncrBy(exec Executor, fields, whereFields uint64) (Stmt, error)

func (*Table) PrepareInsert

func (t *Table) PrepareInsert(exec Executor, fields uint64) (Stmt, error)

func (*Table) PrepareLimit

func (t *Table) PrepareLimit(exec Executor, fields, whereFields uint64) (Stmt, error)

func (*Table) PrepareOne

func (t *Table) PrepareOne(exec Executor, fields, whereFields uint64) (Stmt, error)

func (*Table) PrepareUpdate

func (t *Table) PrepareUpdate(exec Executor, fields, whereFields uint64) (Stmt, error)

func (*Table) SQLAll

func (t *Table) SQLAll(_ Driver, fields, whereFields uint64) string

AllSQL create select sql for given fields

func (*Table) SQLCount

func (t *Table) SQLCount(_ Driver, _, whereFields uint64) string

SQLForCount create select count sql

func (*Table) SQLDelete

func (t *Table) SQLDelete(_ Driver, _, whereFields uint64) string

DeleteSQL create delete sql for given fields

func (*Table) SQLExists added in v0.6.3

func (t *Table) SQLExists(_ Driver, field, whereFields uint64) string

SQLExists create sql for checking whether model exists

func (*Table) SQLIncrBy

func (t *Table) SQLIncrBy(_ Driver, fields, whereFields uint64) string

SQLIncrBy create sql for increase/decrease field value

func (*Table) SQLInsert

func (t *Table) SQLInsert(_ Driver, fields, _ uint64) string

InsertSQL create insert sql for given fields

func (*Table) SQLLimit

func (t *Table) SQLLimit(driver Driver, fields, whereFields uint64) string

LimitSQL create select sql for given fields

func (*Table) SQLOne

func (t *Table) SQLOne(_ Driver, fields, whereFields uint64) string

LimitSQL create select sql for given fields

func (*Table) SQLUpdate

func (t *Table) SQLUpdate(_ Driver, fields, whereFields uint64) string

UpdateSQL create update sql for given fields

func (*Table) Stmt

func (t *Table) Stmt(exec Executor, sqlType SQLType, fields, whereFields uint64, build SQLBuilder) (Stmt, error)

Stmt get sql from cache container, if cache not exist, then create new

func (*Table) StmtAll

func (t *Table) StmtAll(exec Executor, fields, whereFields uint64) (Stmt, error)

func (*Table) StmtCount

func (t *Table) StmtCount(exec Executor, whereFields uint64) (Stmt, error)

func (*Table) StmtDelete

func (t *Table) StmtDelete(exec Executor, whereFields uint64) (Stmt, error)

func (*Table) StmtExists added in v0.6.3

func (t *Table) StmtExists(exec Executor, field, whereFields uint64) (Stmt, error)

func (*Table) StmtIncrBy

func (t *Table) StmtIncrBy(exec Executor, fields, whereFields uint64) (Stmt, error)

func (*Table) StmtInsert

func (t *Table) StmtInsert(exec Executor, fields uint64) (Stmt, error)

func (*Table) StmtLimit

func (t *Table) StmtLimit(exec Executor, fields, whereFields uint64) (Stmt, error)

func (*Table) StmtOne

func (t *Table) StmtOne(exec Executor, fields, whereFields uint64) (Stmt, error)

func (*Table) StmtUpdate

func (t *Table) StmtUpdate(exec Executor, fields, whereFields uint64) (Stmt, error)

func (*Table) TabCol

func (t *Table) TabCol(field uint64) string

Col return column name of field

func (*Table) TabCols

func (t *Table) TabCols(fields uint64) Cols

TabCols return column names for given fields with type's table name as prefix like table.column

func (*Table) TabWhere

func (t *Table) TabWhere(fields uint64) string

TabWhere is slimilar with Where, but prepend a table name for each column

func (*Table) Where

func (t *Table) Where(fields uint64) string

Where create where clause for given fields, the 'WHERE' word is included

type Tx

type Tx struct {
	*sql.Tx
	// contains filtered or unexported fields
}

func (*Tx) All

func (tx *Tx) All(store Store, model Model, fields, whereFields uint64) error

func (*Tx) ArgsAll

func (tx *Tx) ArgsAll(store Store, model Model, fields, whereFields uint64, args ...interface{}) error

ArgsAll select all rows, the last two argument must be "start" and "count"

func (*Tx) ArgsCount

func (tx *Tx) ArgsCount(model Model, whereFields uint64,
	args ...interface{}) (count int64, err error)

ArgsCount return count of rows for model use custome arguments

func (*Tx) ArgsDelete

func (tx *Tx) ArgsDelete(model Model, whereFields uint64, args ...interface{}) (int64, error)

func (*Tx) ArgsExists added in v0.6.3

func (tx *Tx) ArgsExists(model Model, fields, whereFields uint64, args ...interface{}) (exists bool, err error)

func (*Tx) ArgsIncrBy

func (tx *Tx) ArgsIncrBy(model Model, fields, whereFields uint64, args ...interface{}) (int64, error)

func (*Tx) ArgsInsert

func (tx *Tx) ArgsInsert(model Model, fields uint64, resType ResultType, args ...interface{}) (int64, error)

func (*Tx) ArgsLimit

func (tx *Tx) ArgsLimit(store Store, model Model, fields, whereFields uint64, args ...interface{}) error

The last two arguments must be "start" and "count" of limition with type "int"

func (*Tx) ArgsOne

func (tx *Tx) ArgsOne(model Model, fields, whereFields uint64, args []interface{}, ptrs ...interface{}) error

func (*Tx) ArgsUpdate

func (tx *Tx) ArgsUpdate(model Model, fields, whereFields uint64, args ...interface{}) (int64, error)

func (*Tx) Close added in v0.6.1

func (tx *Tx) Close() error

Done check if error is nil then commit transaction, otherwise rollback. Done should be called only once, otherwise it will panic. Done should be called in deferred function to avoid uncommitted/unrollbacked transaction caused by panic.

Example:

 func operation() (err error) {
 	tx, err := db.Begin()
 	if err != nil {
 		return err
 	}
 	defer tx.Close()

 	// do something

		tx.Success(true)
 	return // err must be a named return value, otherwise, error in deferred
 	       isSuccessfunction will be lost
 }

func (*Tx) Count

func (tx *Tx) Count(model Model, whereFields uint64) (count int64, err error)

Count return count of rows for model, arguments was extracted from Model

func (*Tx) Delete

func (tx *Tx) Delete(model Model, whereFields uint64) (int64, error)

func (*Tx) Driver

func (tx *Tx) Driver() Driver

func (*Tx) Exec

func (tx *Tx) Exec(sql string, resType ResultType, args ...interface{}) (int64, error)

func (*Tx) ExecById

func (tx *Tx) ExecById(sqlid uint64, resType ResultType, args ...interface{}) (int64, error)

ExecById execute a update operation, return rows affected

func (*Tx) ExecUpdate

func (tx *Tx) ExecUpdate(sql string, args ...interface{}) (int64, error)

func (*Tx) Exists added in v0.6.3

func (tx *Tx) Exists(model Model, fields, whereFields uint64) (exists bool, err error)

func (*Tx) IncrBy

func (tx *Tx) IncrBy(model Model, field, whereFields uint64, counts ...int) (int64, error)

func (*Tx) Insert

func (tx *Tx) Insert(model Model, fields uint64, resType ResultType) (int64, error)

func (*Tx) Limit

func (tx *Tx) Limit(store Store, model Model, fields, whereFields uint64, start, count int64) error

func (*Tx) One

func (tx *Tx) One(model Model, fields, whereFields uint64) error

One select one row from database

func (*Tx) PrepareById

func (tx *Tx) PrepareById(sqlid uint64) (Stmt, error)

func (*Tx) Query added in v0.6.2

func (tx *Tx) Query(sql string, args ...interface{}) Scanner

func (*Tx) QueryById

func (tx *Tx) QueryById(sqlid uint64, args ...interface{}) Scanner

func (*Tx) Success added in v0.6.1

func (tx *Tx) Success(success bool)

func (*Tx) Table

func (tx *Tx) Table(model Model) *Table

func (*Tx) Update

func (tx *Tx) Update(model Model, fields, whereFields uint64) (int64, error)

func (*Tx) UpdateById

func (tx *Tx) UpdateById(sqlid uint64, args ...interface{}) (int64, error)

UpdateById execute a update operation, return resolved result

Directories

Path Synopsis
cmd
Package dberrs help processing database errors
Package dberrs help processing database errors
example

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL