Documentation ¶
Overview ¶
Package gdb provides ORM features for popular relationship databases.
Example (Transaction) ¶
db.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error { // user result, err := tx.Insert("user", g.Map{ "passport": "john", "password": "12345678", "nickname": "JohnGuo", }) if err != nil { return err } // user_detail id, err := result.LastInsertId() if err != nil { return err } _, err = tx.Insert("user_detail", g.Map{ "uid": id, "site": "https://johng.cn", "true_name": "GuoQiang", }) if err != nil { return err } return nil })
Output:
Index ¶
- Constants
- func AddConfigNode(group string, node ConfigNode)
- func AddDefaultConfigGroup(nodes ConfigGroup)
- func AddDefaultConfigNode(node ConfigNode)
- func ConvertDataForTableRecord(value interface{}) map[string]interface{}
- func DataToMapDeep(value interface{}) map[string]interface{}
- func FormatSqlWithArgs(sql string, args []interface{}) string
- func GetDefaultGroup() string
- func GetInsertOperationByOption(option int) string
- func GetPrimaryKeyCondition(primary string, where ...interface{}) (newWhereCondition []interface{})
- func IsConfigured() bool
- func ListItemValues(list interface{}, key interface{}, subKey ...interface{}) (values []interface{})
- func ListItemValuesUnique(list interface{}, key string, subKey ...interface{}) []interface{}
- func Register(name string, driver Driver) error
- func SetConfig(config Config)
- func SetConfigGroup(group string, nodes ConfigGroup)
- func SetDefaultGroup(name string)
- func WithTX(ctx context.Context, tx *TX) context.Context
- type CacheOption
- type ChunkHandler
- type Config
- type ConfigGroup
- type ConfigNode
- type Core
- func (c *Core) Begin(ctx context.Context) (tx *TX, err error)
- func (c *Core) Close(ctx context.Context) (err error)
- func (c *Core) Ctx(ctx context.Context) DB
- func (c *Core) Delete(ctx context.Context, table string, condition interface{}, args ...interface{}) (result sql.Result, err error)
- func (c *Core) DoCommit(ctx context.Context, link Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error)
- func (c *Core) DoDelete(ctx context.Context, link Link, table string, condition string, ...) (result sql.Result, err error)
- func (c *Core) DoExec(ctx context.Context, link Link, sql string, args ...interface{}) (result sql.Result, err error)
- func (c *Core) DoGetAll(ctx context.Context, link Link, sql string, args ...interface{}) (result Result, err error)
- func (c *Core) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error)
- func (c *Core) DoPrepare(ctx context.Context, link Link, sql string) (*Stmt, error)
- func (c *Core) DoQuery(ctx context.Context, link Link, sql string, args ...interface{}) (result Result, err error)
- func (c *Core) DoUpdate(ctx context.Context, link Link, table string, data interface{}, ...) (result sql.Result, err error)
- func (c *Core) Exec(ctx context.Context, sql string, args ...interface{}) (result sql.Result, err error)
- func (c *Core) GetAll(ctx context.Context, sql string, args ...interface{}) (Result, error)
- func (c *Core) GetArray(ctx context.Context, sql string, args ...interface{}) ([]Value, error)
- func (c *Core) GetCache() *gcache.Cache
- func (c *Core) GetChars() (charLeft string, charRight string)
- func (c *Core) GetConfig() *ConfigNode
- func (c *Core) GetCore() *Core
- func (c *Core) GetCount(ctx context.Context, sql string, args ...interface{}) (int, error)
- func (c *Core) GetCtx() context.Context
- func (c *Core) GetCtxTimeout(timeoutType int, ctx context.Context) (context.Context, context.CancelFunc)
- func (c *Core) GetDebug() bool
- func (c *Core) GetDryRun() bool
- func (c *Core) GetGroup() string
- func (c *Core) GetLogger() *glog.Logger
- func (c *Core) GetOne(ctx context.Context, sql string, args ...interface{}) (Record, error)
- func (c *Core) GetPrefix() string
- func (c *Core) GetScan(ctx context.Context, pointer interface{}, sql string, args ...interface{}) error
- func (c *Core) GetSchema() string
- func (c *Core) GetStruct(ctx context.Context, pointer interface{}, sql string, args ...interface{}) error
- func (c *Core) GetStructs(ctx context.Context, pointer interface{}, sql string, args ...interface{}) error
- func (c *Core) GetValue(ctx context.Context, sql string, args ...interface{}) (Value, error)
- func (c *Core) HasField(table, field string, schema ...string) (bool, error)
- func (c *Core) HasTable(name string) (bool, error)
- func (c *Core) Insert(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error)
- func (c *Core) InsertAndGetId(ctx context.Context, table string, data interface{}, batch ...int) (int64, error)
- func (c *Core) InsertIgnore(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error)
- func (c *Core) MarshalJSON() ([]byte, error)
- func (c *Core) Master(schema ...string) (*sql.DB, error)
- func (c *Core) MasterLink(schema ...string) (Link, error)
- func (c *Core) Model(tableNameQueryOrStruct ...interface{}) *Model
- func (c *Core) PingMaster() error
- func (c *Core) PingSlave() error
- func (c *Core) Prepare(ctx context.Context, sql string, execOnMaster ...bool) (*Stmt, error)
- func (c *Core) Query(ctx context.Context, sql string, args ...interface{}) (result Result, err error)
- func (c *Core) QuotePrefixTableName(table string) string
- func (c *Core) QuoteString(s string) string
- func (c *Core) QuoteWord(s string) string
- func (c *Core) Raw(rawSql string, args ...interface{}) *Model
- func (c *Core) Replace(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error)
- func (c *Core) Save(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error)
- func (c *Core) Schema(schema string) *Schema
- func (c *Core) SetDebug(debug bool)
- func (c *Core) SetDryRun(enabled bool)
- func (c *Core) SetLogger(logger *glog.Logger)
- func (c *Core) SetMaxConnLifeTime(d time.Duration)
- func (c *Core) SetMaxIdleConnCount(n int)
- func (c *Core) SetMaxOpenConnCount(n int)
- func (c *Core) SetSchema(schema string)
- func (c *Core) Slave(schema ...string) (*sql.DB, error)
- func (c *Core) SlaveLink(schema ...string) (Link, error)
- func (c *Core) TableFields(table string, schema ...string) (fields map[string]*TableField, err error)
- func (c *Core) Tables(schema ...string) (tables []string, err error)
- func (c *Core) Transaction(ctx context.Context, f func(ctx context.Context, tx *TX) error) (err error)
- func (c *Core) Union(unions ...*Model) *Model
- func (c *Core) UnionAll(unions ...*Model) *Model
- func (c *Core) Update(ctx context.Context, table string, data interface{}, condition interface{}, ...) (sql.Result, error)
- func (c *Core) With(objects ...interface{}) *Model
- type Counter
- type DB
- type DoInsertOption
- type Driver
- type DriverMssql
- func (d *DriverMssql) DoCommit(ctx context.Context, link Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error)
- func (d *DriverMssql) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error)
- func (d *DriverMssql) FilteredLink() string
- func (d *DriverMssql) GetChars() (charLeft string, charRight string)
- func (d *DriverMssql) New(core *Core, node *ConfigNode) (DB, error)
- func (d *DriverMssql) Open(config *ConfigNode) (*sql.DB, error)
- func (d *DriverMssql) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*TableField, err error)
- func (d *DriverMssql) Tables(ctx context.Context, schema ...string) (tables []string, err error)
- type DriverMysql
- func (d *DriverMysql) DoCommit(ctx context.Context, link Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error)
- func (d *DriverMysql) FilteredLink() string
- func (d *DriverMysql) GetChars() (charLeft string, charRight string)
- func (d *DriverMysql) New(core *Core, node *ConfigNode) (DB, error)
- func (d *DriverMysql) Open(config *ConfigNode) (*sql.DB, error)
- func (d *DriverMysql) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*TableField, err error)
- func (d *DriverMysql) Tables(ctx context.Context, schema ...string) (tables []string, err error)
- type DriverOracle
- func (d *DriverOracle) DoCommit(ctx context.Context, link Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error)
- func (d *DriverOracle) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error)
- func (d *DriverOracle) FilteredLink() string
- func (d *DriverOracle) GetChars() (charLeft string, charRight string)
- func (d *DriverOracle) New(core *Core, node *ConfigNode) (DB, error)
- func (d *DriverOracle) Open(config *ConfigNode) (*sql.DB, error)
- func (d *DriverOracle) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*TableField, err error)
- func (d *DriverOracle) Tables(ctx context.Context, schema ...string) (tables []string, err error)
- type DriverPgsql
- func (d *DriverPgsql) DoCommit(ctx context.Context, link Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error)
- func (d *DriverPgsql) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error)
- func (d *DriverPgsql) FilteredLink() string
- func (d *DriverPgsql) GetChars() (charLeft string, charRight string)
- func (d *DriverPgsql) New(core *Core, node *ConfigNode) (DB, error)
- func (d *DriverPgsql) Open(config *ConfigNode) (*sql.DB, error)
- func (d *DriverPgsql) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*TableField, err error)
- func (d *DriverPgsql) Tables(ctx context.Context, schema ...string) (tables []string, err error)
- type DriverSqlite
- func (d *DriverSqlite) DoCommit(ctx context.Context, link Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error)
- func (d *DriverSqlite) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error)
- func (d *DriverSqlite) FilteredLink() string
- func (d *DriverSqlite) GetChars() (charLeft string, charRight string)
- func (d *DriverSqlite) New(core *Core, node *ConfigNode) (DB, error)
- func (d *DriverSqlite) Open(config *ConfigNode) (*sql.DB, error)
- func (d *DriverSqlite) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*TableField, err error)
- func (d *DriverSqlite) Tables(ctx context.Context, schema ...string) (tables []string, err error)
- type Link
- type List
- type Map
- type Model
- func (m *Model) All(where ...interface{}) (Result, error)
- func (m *Model) Args(args ...interface{}) *Model
- func (m *Model) Array(fieldsAndWhere ...interface{}) ([]Value, error)
- func (m *Model) As(as string) *Model
- func (m *Model) Avg(column string) (float64, error)
- func (m *Model) Batch(batch int) *Model
- func (m *Model) Cache(option CacheOption) *Model
- func (m *Model) Chunk(size int, handler ChunkHandler)
- func (m *Model) Clone() *Model
- func (m *Model) Count(where ...interface{}) (int, error)
- func (m *Model) CountColumn(column string) (int, error)
- func (m *Model) Ctx(ctx context.Context) *Model
- func (m *Model) DB(db DB) *Model
- func (m *Model) Data(data ...interface{}) *Model
- func (m *Model) Decrement(column string, amount interface{}) (sql.Result, error)
- func (m *Model) Delete(where ...interface{}) (result sql.Result, err error)
- func (m *Model) Distinct() *Model
- func (m *Model) FieldAvg(column string, as ...string) *Model
- func (m *Model) FieldCount(column string, as ...string) *Model
- func (m *Model) FieldMax(column string, as ...string) *Model
- func (m *Model) FieldMin(column string, as ...string) *Model
- func (m *Model) FieldSum(column string, as ...string) *Model
- func (m *Model) Fields(fieldNamesOrMapStruct ...interface{}) *Model
- func (m *Model) FieldsEx(fieldNamesOrMapStruct ...interface{}) *Model
- func (m *Model) FieldsExPrefix(prefix string, fieldNamesOrMapStruct ...interface{}) *Model
- func (m *Model) FieldsPrefix(prefix string, fieldNamesOrMapStruct ...interface{}) *Model
- func (m *Model) GetCtx() context.Context
- func (m *Model) GetFieldsExStr(fields string, prefix ...string) string
- func (m *Model) GetFieldsStr(prefix ...string) string
- func (m *Model) Group(groupBy ...string) *Model
- func (m *Model) Handler(handlers ...ModelHandler) *Model
- func (m *Model) HasField(field string) (bool, error)
- func (m *Model) Having(having interface{}, args ...interface{}) *Model
- func (m *Model) Increment(column string, amount interface{}) (sql.Result, error)
- func (m *Model) InnerJoin(table ...string) *Model
- func (m *Model) InnerJoinOnField(table, field string) *Model
- func (m *Model) Insert(data ...interface{}) (result sql.Result, err error)
- func (m *Model) InsertAndGetId(data ...interface{}) (lastInsertId int64, err error)
- func (m *Model) InsertIgnore(data ...interface{}) (result sql.Result, err error)
- func (m *Model) LeftJoin(table ...string) *Model
- func (m *Model) LeftJoinOnField(table, field string) *Model
- func (m *Model) Limit(limit ...int) *Model
- func (m *Model) LockShared() *Model
- func (m *Model) LockUpdate() *Model
- func (m *Model) Master() *Model
- func (m *Model) Max(column string) (float64, error)
- func (m *Model) Min(column string) (float64, error)
- func (m *Model) Offset(offset int) *Model
- func (m *Model) OmitEmpty() *Model
- func (m *Model) OmitEmptyData() *Model
- func (m *Model) OmitEmptyWhere() *Model
- func (m *Model) OmitNil() *Model
- func (m *Model) OmitNilData() *Model
- func (m *Model) OmitNilWhere() *Model
- func (m *Model) OnDuplicate(onDuplicate ...interface{}) *Model
- func (m *Model) OnDuplicateEx(onDuplicateEx ...interface{}) *Model
- func (m *Model) One(where ...interface{}) (Record, error)
- func (m *Model) Order(orderBy ...string) *Model
- func (m *Model) OrderAsc(column string) *Model
- func (m *Model) OrderDesc(column string) *Model
- func (m *Model) OrderRandom() *Model
- func (m *Model) Page(page, limit int) *Model
- func (m *Model) QuoteWord(s string) string
- func (m *Model) Raw(rawSql string, args ...interface{}) *Model
- func (m *Model) Replace(data ...interface{}) (result sql.Result, err error)
- func (m *Model) RightJoin(table ...string) *Model
- func (m *Model) RightJoinOnField(table, field string) *Model
- func (m *Model) Safe(safe ...bool) *Model
- func (m *Model) Save(data ...interface{}) (result sql.Result, err error)
- func (m *Model) Scan(pointer interface{}, where ...interface{}) error
- func (m *Model) ScanList(structSlicePointer interface{}, bindToAttrName string, ...) (err error)
- func (m *Model) Schema(schema string) *Model
- func (m *Model) Slave() *Model
- func (m *Model) Sum(column string) (float64, error)
- func (m *Model) TX(tx *TX) *Model
- func (m *Model) TableFields(tableStr string, schema ...string) (fields map[string]*TableField, err error)
- func (m *Model) Transaction(ctx context.Context, f func(ctx context.Context, tx *TX) error) (err error)
- func (m *Model) Union(unions ...*Model) *Model
- func (m *Model) UnionAll(unions ...*Model) *Model
- func (m *Model) Unscoped() *Model
- func (m *Model) Update(dataAndWhere ...interface{}) (result sql.Result, err error)
- func (m *Model) Value(fieldsAndWhere ...interface{}) (Value, error)
- func (m *Model) Where(where interface{}, args ...interface{}) *Model
- func (m *Model) WhereBetween(column string, min, max interface{}) *Model
- func (m *Model) WhereGT(column string, value interface{}) *Model
- func (m *Model) WhereGTE(column string, value interface{}) *Model
- func (m *Model) WhereIn(column string, in interface{}) *Model
- func (m *Model) WhereLT(column string, value interface{}) *Model
- func (m *Model) WhereLTE(column string, value interface{}) *Model
- func (m *Model) WhereLike(column string, like interface{}) *Model
- func (m *Model) WhereNot(column string, value interface{}) *Model
- func (m *Model) WhereNotBetween(column string, min, max interface{}) *Model
- func (m *Model) WhereNotIn(column string, in interface{}) *Model
- func (m *Model) WhereNotLike(column string, like interface{}) *Model
- func (m *Model) WhereNotNull(columns ...string) *Model
- func (m *Model) WhereNull(columns ...string) *Model
- func (m *Model) WhereOr(where interface{}, args ...interface{}) *Model
- func (m *Model) WhereOrBetween(column string, min, max interface{}) *Model
- func (m *Model) WhereOrGT(column string, value interface{}) *Model
- func (m *Model) WhereOrGTE(column string, value interface{}) *Model
- func (m *Model) WhereOrIn(column string, in interface{}) *Model
- func (m *Model) WhereOrLT(column string, value interface{}) *Model
- func (m *Model) WhereOrLTE(column string, value interface{}) *Model
- func (m *Model) WhereOrLike(column string, like interface{}) *Model
- func (m *Model) WhereOrNotBetween(column string, min, max interface{}) *Model
- func (m *Model) WhereOrNotIn(column string, in interface{}) *Model
- func (m *Model) WhereOrNotLike(column string, like interface{}) *Model
- func (m *Model) WhereOrNotNull(columns ...string) *Model
- func (m *Model) WhereOrNull(columns ...string) *Model
- func (m *Model) WhereOrPrefix(prefix string, where interface{}, args ...interface{}) *Model
- func (m *Model) WhereOrPrefixBetween(prefix string, column string, min, max interface{}) *Model
- func (m *Model) WhereOrPrefixGT(prefix string, column string, value interface{}) *Model
- func (m *Model) WhereOrPrefixGTE(prefix string, column string, value interface{}) *Model
- func (m *Model) WhereOrPrefixIn(prefix string, column string, in interface{}) *Model
- func (m *Model) WhereOrPrefixLT(prefix string, column string, value interface{}) *Model
- func (m *Model) WhereOrPrefixLTE(prefix string, column string, value interface{}) *Model
- func (m *Model) WhereOrPrefixLike(prefix string, column string, like interface{}) *Model
- func (m *Model) WhereOrPrefixNotBetween(prefix string, column string, min, max interface{}) *Model
- func (m *Model) WhereOrPrefixNotIn(prefix string, column string, in interface{}) *Model
- func (m *Model) WhereOrPrefixNotLike(prefix string, column string, like interface{}) *Model
- func (m *Model) WhereOrPrefixNotNull(prefix string, columns ...string) *Model
- func (m *Model) WhereOrPrefixNull(prefix string, columns ...string) *Model
- func (m *Model) WhereOrf(format string, args ...interface{}) *Model
- func (m *Model) WherePrefix(prefix string, where interface{}, args ...interface{}) *Model
- func (m *Model) WherePrefixBetween(prefix string, column string, min, max interface{}) *Model
- func (m *Model) WherePrefixGT(prefix string, column string, value interface{}) *Model
- func (m *Model) WherePrefixGTE(prefix string, column string, value interface{}) *Model
- func (m *Model) WherePrefixIn(prefix string, column string, in interface{}) *Model
- func (m *Model) WherePrefixLT(prefix string, column string, value interface{}) *Model
- func (m *Model) WherePrefixLTE(prefix string, column string, value interface{}) *Model
- func (m *Model) WherePrefixLike(prefix string, column string, like interface{}) *Model
- func (m *Model) WherePrefixNot(prefix string, column string, value interface{}) *Model
- func (m *Model) WherePrefixNotBetween(prefix string, column string, min, max interface{}) *Model
- func (m *Model) WherePrefixNotIn(prefix string, column string, in interface{}) *Model
- func (m *Model) WherePrefixNotLike(prefix string, column string, like interface{}) *Model
- func (m *Model) WherePrefixNotNull(prefix string, columns ...string) *Model
- func (m *Model) WherePrefixNull(prefix string, columns ...string) *Model
- func (m *Model) WherePri(where interface{}, args ...interface{}) *Model
- func (m *Model) Wheref(format string, args ...interface{}) *Model
- func (m *Model) With(objects ...interface{}) *Model
- func (m *Model) WithAll() *Model
- type ModelHandler
- type ModelWhereHolder
- type Raw
- type Record
- type Result
- func (r Result) Array(field ...string) []Value
- func (r Result) Chunk(size int) []Result
- func (r Result) IsEmpty() bool
- func (r Result) Json() string
- func (r Result) Len() int
- func (r Result) List() List
- func (r Result) MapKeyInt(key string) map[int]Map
- func (r Result) MapKeyStr(key string) map[string]Map
- func (r Result) MapKeyUint(key string) map[uint]Map
- func (r Result) MapKeyValue(key string) map[string]Value
- func (r Result) RecordKeyInt(key string) map[int]Record
- func (r Result) RecordKeyStr(key string) map[string]Record
- func (r Result) RecordKeyUint(key string) map[uint]Record
- func (r Result) ScanList(structSlicePointer interface{}, bindToAttrName string, ...) (err error)
- func (r Result) Size() int
- func (r Result) Structs(pointer interface{}) (err error)
- func (r Result) Xml(rootTag ...string) string
- type Schema
- type Sql
- type SqlResult
- type Stmt
- func (s *Stmt) Close() error
- func (s *Stmt) Exec(args ...interface{}) (sql.Result, error)
- func (s *Stmt) ExecContext(ctx context.Context, args ...interface{}) (sql.Result, error)
- func (s *Stmt) Query(args ...interface{}) (*sql.Rows, error)
- func (s *Stmt) QueryContext(ctx context.Context, args ...interface{}) (*sql.Rows, error)
- func (s *Stmt) QueryRow(args ...interface{}) *sql.Row
- func (s *Stmt) QueryRowContext(ctx context.Context, args ...interface{}) *sql.Row
- type TX
- func (tx *TX) Begin() error
- func (tx *TX) Commit() error
- func (tx *TX) Ctx(ctx context.Context) *TX
- func (tx *TX) Delete(table string, condition interface{}, args ...interface{}) (sql.Result, error)
- func (tx *TX) Exec(sql string, args ...interface{}) (sql.Result, error)
- func (tx *TX) GetAll(sql string, args ...interface{}) (Result, error)
- func (tx *TX) GetCount(sql string, args ...interface{}) (int, error)
- func (tx *TX) GetOne(sql string, args ...interface{}) (Record, error)
- func (tx *TX) GetScan(pointer interface{}, sql string, args ...interface{}) error
- func (tx *TX) GetStruct(obj interface{}, sql string, args ...interface{}) error
- func (tx *TX) GetStructs(objPointerSlice interface{}, sql string, args ...interface{}) error
- func (tx *TX) GetValue(sql string, args ...interface{}) (Value, error)
- func (tx *TX) Insert(table string, data interface{}, batch ...int) (sql.Result, error)
- func (tx *TX) InsertAndGetId(table string, data interface{}, batch ...int) (int64, error)
- func (tx *TX) InsertIgnore(table string, data interface{}, batch ...int) (sql.Result, error)
- func (tx *TX) IsClosed() bool
- func (tx *TX) Model(tableNameQueryOrStruct ...interface{}) *Model
- func (tx *TX) Prepare(sql string) (*Stmt, error)
- func (tx *TX) Query(sql string, args ...interface{}) (result Result, err error)
- func (tx *TX) Raw(rawSql string, args ...interface{}) *Model
- func (tx *TX) Replace(table string, data interface{}, batch ...int) (sql.Result, error)
- func (tx *TX) Rollback() error
- func (tx *TX) RollbackTo(point string) error
- func (tx *TX) Save(table string, data interface{}, batch ...int) (sql.Result, error)
- func (tx *TX) SavePoint(point string) error
- func (tx *TX) Schema(schema string) *Schema
- func (tx *TX) Transaction(ctx context.Context, f func(ctx context.Context, tx *TX) error) (err error)
- func (tx *TX) Update(table string, data interface{}, condition interface{}, args ...interface{}) (sql.Result, error)
- func (tx *TX) With(object interface{}) *Model
- type TableField
- type Value
Examples ¶
Constants ¶
const ( OrmTagForStruct = "orm" OrmTagForTable = "table" OrmTagForWith = "with" OrmTagForWithWhere = "where" OrmTagForWithOrder = "order" )
const (
DefaultGroupName = "default" // Default group name.
)
Variables ¶
This section is empty.
Functions ¶
func AddConfigNode ¶
func AddConfigNode(group string, node ConfigNode)
AddConfigNode adds one node configuration to configuration of given group.
func AddDefaultConfigGroup ¶
func AddDefaultConfigGroup(nodes ConfigGroup)
AddDefaultConfigGroup adds multiple node configurations to configuration of default group.
func AddDefaultConfigNode ¶
func AddDefaultConfigNode(node ConfigNode)
AddDefaultConfigNode adds one node configuration to configuration of default group.
func ConvertDataForTableRecord ¶
func ConvertDataForTableRecord(value interface{}) map[string]interface{}
ConvertDataForTableRecord is a very important function, which does converting for any data that will be inserted into table as a record.
The parameter `value` should be type of *map/map/*struct/struct. It supports embedded struct definition for struct.
func DataToMapDeep ¶
func DataToMapDeep(value interface{}) map[string]interface{}
DataToMapDeep converts `value` to map type recursively(if attribute struct is embedded). The parameter `value` should be type of *map/map/*struct/struct. It supports embedded struct definition for struct.
func FormatSqlWithArgs ¶
FormatSqlWithArgs binds the arguments to the sql string and returns a complete sql string, just for debugging.
func GetDefaultGroup ¶
func GetDefaultGroup() string
GetDefaultGroup returns the { name of default configuration.
func GetInsertOperationByOption ¶
GetInsertOperationByOption returns proper insert option with given parameter `option`.
func GetPrimaryKeyCondition ¶
func GetPrimaryKeyCondition(primary string, where ...interface{}) (newWhereCondition []interface{})
GetPrimaryKeyCondition returns a new where condition by primary field name. The optional parameter `where` is like follows: 123 => primary=123 []int{1, 2, 3} => primary IN(1,2,3) "john" => primary='john' []string{"john", "smith"} => primary IN('john','smith') g.Map{"id": g.Slice{1,2,3}} => id IN(1,2,3) g.Map{"id": 1, "name": "john"} => id=1 AND name='john' etc.
Note that it returns the given `where` parameter directly if the `primary` is empty or length of `where` > 1.
func IsConfigured ¶
func IsConfigured() bool
IsConfigured checks and returns whether the database configured. It returns true if any configuration exists.
func ListItemValues ¶
func ListItemValues(list interface{}, key interface{}, subKey ...interface{}) (values []interface{})
ListItemValues retrieves and returns the elements of all item struct/map with key `key`. Note that the parameter `list` should be type of slice which contains elements of map or struct, or else it returns an empty slice.
The parameter `list` supports types like: []map[string]interface{} []map[string]sub-map []struct []struct:sub-struct Note that the sub-map/sub-struct makes sense only if the optional parameter `subKey` is given. See gutil.ListItemValues.
func ListItemValuesUnique ¶
func ListItemValuesUnique(list interface{}, key string, subKey ...interface{}) []interface{}
ListItemValuesUnique retrieves and returns the unique elements of all struct/map with key `key`. Note that the parameter `list` should be type of slice which contains elements of map or struct, or else it returns an empty slice. See gutil.ListItemValuesUnique.
func Register ¶
Register registers custom database driver to gdb.
func SetConfig ¶
func SetConfig(config Config)
SetConfig sets the global configuration for package. It will overwrite the old configuration of package.
func SetConfigGroup ¶
func SetConfigGroup(group string, nodes ConfigGroup)
SetConfigGroup sets the configuration for given group.
Types ¶
type CacheOption ¶
type CacheOption struct { // Duration is the TTL for the cache. // If the parameter `Duration` < 0, which means it clear the cache with given `Name`. // If the parameter `Duration` = 0, which means it never expires. // If the parameter `Duration` > 0, which means it expires after `Duration`. Duration time.Duration // Name is an optional unique name for the cache. // The Name is used to bind a name to the cache, which means you can later control the cache // like changing the `duration` or clearing the cache with specified Name. Name string // Force caches the query result whatever the result is nil or not. // It is used to avoid Cache Penetration. Force bool }
type ChunkHandler ¶
ChunkHandler is a function that is used in function Chunk, which handles given Result and error. It returns true if it wants to continue chunking, or else it returns false to stop chunking.
type ConfigGroup ¶
type ConfigGroup []ConfigNode
ConfigGroup is a slice of configuration node for specified named group.
func GetConfig ¶
func GetConfig(group string) ConfigGroup
GetConfig retrieves and returns the configuration of given group.
type ConfigNode ¶
type ConfigNode struct { Host string `json:"host"` // Host of server, ip or domain like: 127.0.0.1, localhost Port string `json:"port"` // Port, it's commonly 3306. User string `json:"user"` // Authentication username. Pass string `json:"pass"` // Authentication password. Name string `json:"name"` // Default used database name. Type string `json:"type"` // Database type: mysql, sqlite, mssql, pgsql, oracle. Link string `json:"link"` // (Optional) Custom link information, when it is used, configuration Host/Port/User/Pass/Name are ignored. Role string `json:"role"` // (Optional, "master" in default) Node role, used for master-slave mode: master, slave. Debug bool `json:"debug"` // (Optional) Debug mode enables debug information logging and output. Prefix string `json:"prefix"` // (Optional) Table prefix. DryRun bool `json:"dryRun"` // (Optional) Dry run, which does SELECT but no INSERT/UPDATE/DELETE statements. Weight int `json:"weight"` // (Optional) Weight for load balance calculating, it's useless if there's just one node. Charset string `json:"charset"` // (Optional, "utf8mb4" in default) Custom charset when operating on database. Timezone string `json:"timezone"` // (Optional) Sets the time zone for displaying and interpreting time stamps. MaxIdleConnCount int `json:"maxIdle"` // (Optional) Max idle connection configuration for underlying connection pool. MaxOpenConnCount int `json:"maxOpen"` // (Optional) Max open connection configuration for underlying connection pool. MaxConnLifeTime time.Duration `json:"maxLifeTime"` // (Optional) Max amount of time a connection may be idle before being closed. QueryTimeout time.Duration `json:"queryTimeout"` // (Optional) Max query time for per dql. ExecTimeout time.Duration `json:"execTimeout"` // (Optional) Max exec time for dml. TranTimeout time.Duration `json:"tranTimeout"` // (Optional) Max exec time time for a transaction. PrepareTimeout time.Duration `json:"prepareTimeout"` // (Optional) Max exec time time for prepare operation. CreatedAt string `json:"createdAt"` // (Optional) The filed name of table for automatic-filled created datetime. UpdatedAt string `json:"updatedAt"` // (Optional) The filed name of table for automatic-filled updated datetime. DeletedAt string `json:"deletedAt"` // (Optional) The filed name of table for automatic-filled updated datetime. TimeMaintainDisabled bool `json:"timeMaintainDisabled"` // (Optional) Disable the automatic time maintaining feature. }
ConfigNode is configuration for one node.
func (*ConfigNode) String ¶
func (node *ConfigNode) String() string
String returns the node as string.
type Core ¶
type Core struct {
// contains filtered or unexported fields
}
Core is the base struct for database management.
func (*Core) Begin ¶
Begin starts and returns the transaction object. You should call Commit or Rollback functions of the transaction object if you no longer use the transaction. Commit or Rollback functions will also close the transaction automatically.
func (*Core) Close ¶
Close closes the database and prevents new queries from starting. Close then waits for all queries that have started processing on the server to finish.
It is rare to Close a DB, as the DB handle is meant to be long-lived and shared between many goroutines.
func (*Core) Ctx ¶
Ctx is a chaining function, which creates and returns a new DB that is a shallow copy of current DB object and with given context in it. Note that this returned DB object can be used only once, so do not assign it to a global or package variable for long using.
func (*Core) Delete ¶
func (c *Core) Delete(ctx context.Context, table string, condition interface{}, args ...interface{}) (result sql.Result, err error)
Delete does "DELETE FROM ... " statement for the table.
The parameter `condition` can be type of string/map/gmap/slice/struct/*struct, etc. It is commonly used with parameter `args`. Eg: "uid=10000", "uid", 10000 "money>? AND name like ?", 99999, "vip_%" "status IN (?)", g.Slice{1,2,3} "age IN(?,?)", 18, 50 User{ Id : 1, UserName : "john"}.
func (*Core) DoCommit ¶
func (c *Core) DoCommit(ctx context.Context, link Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error)
DoCommit is a hook function, which deals with the sql string before it's committed to underlying driver. The parameter `link` specifies the current database connection operation object. You can modify the sql string `sql` and its arguments `args` as you wish before they're committed to driver.
func (*Core) DoDelete ¶
func (c *Core) DoDelete(ctx context.Context, link Link, table string, condition string, args ...interface{}) (result sql.Result, err error)
DoDelete does "DELETE FROM ... " statement for the table. This function is usually used for custom interface definition, you do not need call it manually.
func (*Core) DoExec ¶
func (c *Core) DoExec(ctx context.Context, link Link, sql string, args ...interface{}) (result sql.Result, err error)
DoExec commits the sql string and its arguments to underlying driver through given link object and returns the execution result.
func (*Core) DoGetAll ¶
func (c *Core) DoGetAll(ctx context.Context, link Link, sql string, args ...interface{}) (result Result, err error)
DoGetAll queries and returns data records from database.
func (*Core) DoInsert ¶
func (c *Core) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error)
DoInsert inserts or updates data forF given table. This function is usually used for custom interface definition, you do not need call it manually. The parameter `data` can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
The parameter `option` values are as follows: 0: insert: just insert, if there's unique/primary key in the data, it returns error; 1: replace: if there's unique/primary key in the data, it deletes it from table and inserts a new one; 2: save: if there's unique/primary key in the data, it updates it or else inserts a new one; 3: ignore: if there's unique/primary key in the data, it ignores the inserting;
func (*Core) DoPrepare ¶
DoPrepare calls prepare function on given link object and returns the statement object.
func (*Core) DoQuery ¶
func (c *Core) DoQuery(ctx context.Context, link Link, sql string, args ...interface{}) (result Result, err error)
DoQuery commits the sql string and its arguments to underlying driver through given link object and returns the execution result.
func (*Core) DoUpdate ¶
func (c *Core) DoUpdate(ctx context.Context, link Link, table string, data interface{}, condition string, args ...interface{}) (result sql.Result, err error)
DoUpdate does "UPDATE ... " statement for the table. This function is usually used for custom interface definition, you do not need to call it manually.
func (*Core) Exec ¶
func (c *Core) Exec(ctx context.Context, sql string, args ...interface{}) (result sql.Result, err error)
Exec commits one query SQL to underlying driver and returns the execution result. It is most commonly used for data inserting and updating.
func (*Core) GetAll ¶
GetAll queries and returns data records from database.
func (*Core) GetArray ¶
GetArray queries and returns data values as slice from database. Note that if there are multiple columns in the result, it returns just one column values randomly.
func (*Core) GetCache ¶
GetCache returns the internal cache object.
func (*Core) GetChars ¶
GetChars returns the security char for current database. It does nothing in default.
func (*Core) GetConfig ¶
func (c *Core) GetConfig() *ConfigNode
GetConfig returns the current used node configuration.
func (*Core) GetCount ¶
GetCount queries and returns the count from database.
func (*Core) GetCtx ¶
GetCtx returns the context for current DB. It returns `context.Background()` is there's no context previously set.
func (*Core) GetCtxTimeout ¶
func (c *Core) GetCtxTimeout(timeoutType int, ctx context.Context) (context.Context, context.CancelFunc)
GetCtxTimeout returns the context and cancel function for specified timeout type.
func (*Core) GetGroup ¶
GetGroup returns the group string configured.
func (*Core) GetLogger ¶
GetLogger returns the (logger) of the orm.
func (*Core) GetOne ¶
GetOne queries and returns one record from database.
func (*Core) GetPrefix ¶
GetPrefix returns the table prefix string configured.
func (*Core) GetScan ¶
func (c *Core) GetScan(ctx context.Context, pointer interface{}, sql string, args ...interface{}) error
GetScan queries one or more records from database and converts them to given struct or struct array.
If parameter `pointer` is type of struct pointer, it calls GetStruct internally for the conversion. If parameter `pointer` is type of slice, it calls GetStructs internally for conversion.
func (*Core) GetStruct ¶
func (c *Core) GetStruct(ctx context.Context, pointer interface{}, sql string, args ...interface{}) error
GetStruct queries one record from database and converts it to given struct. The parameter `pointer` should be a pointer to struct.
func (*Core) GetStructs ¶
func (c *Core) GetStructs(ctx context.Context, pointer interface{}, sql string, args ...interface{}) error
GetStructs queries records from database and converts them to given struct. The parameter `pointer` should be type of struct slice: []struct/[]*struct.
func (*Core) GetValue ¶
GetValue queries and returns the field value from database. The sql should query only one field from database, or else it returns only one field of the result.
func (*Core) HasField ¶
HasField determine whether the field exists in the table.
func (*Core) HasTable ¶
HasTable determine whether the table name exists in the database.
func (*Core) Insert ¶
func (c *Core) Insert(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error)
Insert does "INSERT INTO ..." statement for the table. If there's already one unique record of the data in the table, it returns error.
The parameter `data` can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
The parameter `batch` specifies the batch operation count when given data is slice.
func (*Core) InsertAndGetId ¶
func (c *Core) InsertAndGetId(ctx context.Context, table string, data interface{}, batch ...int) (int64, error)
InsertAndGetId performs action Insert and returns the last insert id that automatically generated.
func (*Core) InsertIgnore ¶
func (c *Core) InsertIgnore(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error)
InsertIgnore does "INSERT IGNORE INTO ..." statement for the table. If there's already one unique record of the data in the table, it ignores the inserting.
The parameter `data` can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
The parameter `batch` specifies the batch operation count when given data is slice.
func (*Core) MarshalJSON ¶
MarshalJSON implements the interface MarshalJSON for json.Marshal. It just returns the pointer address.
Note that this interface implements mainly for workaround for a json infinite loop bug of Golang version < v1.14.
func (*Core) Master ¶
Master creates and returns a connection from master node if master-slave configured. It returns the default connection if master-slave not configured.
func (*Core) MasterLink ¶
MasterLink acts like function Master but with additional `schema` parameter specifying the schema for the connection. It is defined for internal usage. Also see Master.
func (*Core) Model ¶
Model creates and returns a new ORM model from given schema. The parameter `tableNameQueryOrStruct` can be more than one table names, and also alias name, like:
- Model names: db.Model("user") db.Model("user u") db.Model("user, user_detail") db.Model("user u, user_detail ud")
- Model name with alias: db.Model("user", "u")
- Model name with sub-query: db.Model("? AS a, ? AS b", subQuery1, subQuery2)
func (*Core) PingMaster ¶
PingMaster pings the master node to check authentication or keeps the connection alive.
func (*Core) PingSlave ¶
PingSlave pings the slave node to check authentication or keeps the connection alive.
func (*Core) Prepare ¶
Prepare creates a prepared statement for later queries or executions. Multiple queries or executions may be run concurrently from the returned statement. The caller must call the statement's Close method when the statement is no longer needed.
The parameter `execOnMaster` specifies whether executing the sql on master node, or else it executes the sql on slave node if master-slave configured.
func (*Core) Query ¶
func (c *Core) Query(ctx context.Context, sql string, args ...interface{}) (result Result, err error)
Query commits one query SQL to underlying driver and returns the execution result. It is most commonly used for data querying.
func (*Core) QuotePrefixTableName ¶
QuotePrefixTableName adds prefix string and quotes chars for the table. It handles table string like: "user", "user u", "user,user_detail", "user u, user_detail ut", "user as u, user_detail as ut".
Note that, this will automatically checks the table prefix whether already added, if true it does nothing to the table name, or else adds the prefix to the table name.
func (*Core) QuoteString ¶
QuoteString quotes string with quote chars. Strings like: "user", "user u", "user,user_detail", "user u, user_detail ut", "u.id asc".
The meaning of a `string` can be considered as part of a statement string including columns.
func (*Core) QuoteWord ¶
QuoteWord checks given string `s` a word, if true it quotes `s` with security chars of the database and returns the quoted string; or else it returns `s` without any change.
The meaning of a `word` can be considered as a column name.
func (*Core) Raw ¶
Raw creates and returns a model based on a raw sql not a table. Example:
db.Raw("SELECT * FROM `user` WHERE `name` = ?", "john").Scan(&result)
func (*Core) Replace ¶
func (c *Core) Replace(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error)
Replace does "REPLACE INTO ..." statement for the table. If there's already one unique record of the data in the table, it deletes the record and inserts a new one.
The parameter `data` can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
The parameter `data` can be type of map/gmap/struct/*struct/[]map/[]struct, etc. If given data is type of slice, it then does batch replacing, and the optional parameter `batch` specifies the batch operation count.
func (*Core) Save ¶
func (c *Core) Save(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error)
Save does "INSERT INTO ... ON DUPLICATE KEY UPDATE..." statement for the table. It updates the record if there's primary or unique index in the saving data, or else it inserts a new record into the table.
The parameter `data` can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
If given data is type of slice, it then does batch saving, and the optional parameter `batch` specifies the batch operation count.
func (*Core) Schema ¶
Schema creates and returns a schema.
func (*Core) SetDebug ¶
SetDebug enables/disables the debug mode.
func (*Core) SetDryRun ¶
SetDryRun enables/disables the DryRun feature.
func (*Core) SetLogger ¶
SetLogger sets the logger for orm.
func (*Core) SetMaxConnLifeTime ¶
SetMaxConnLifeTime sets the maximum amount of time a connection may be reused.
Expired connections may be closed lazily before reuse.
If d <= 0, connections are not closed due to a connection's age.
func (*Core) SetMaxIdleConnCount ¶
SetMaxIdleConnCount sets the maximum number of connections in the idle connection pool.
If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, then the new MaxIdleConns will be reduced to match the MaxOpenConns limit.
If n <= 0, no idle connections are retained.
The default max idle connections is currently 2. This may change in a future release.
func (*Core) SetMaxOpenConnCount ¶
SetMaxOpenConnCount sets the maximum number of open connections to the database.
If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than MaxIdleConns, then MaxIdleConns will be reduced to match the new MaxOpenConns limit.
If n <= 0, then there is no limit on the number of open connections. The default is 0 (unlimited).
func (*Core) SetSchema ¶
SetSchema changes the schema for this database connection object. Importantly note that when schema configuration changed for the database, it affects all operations on the database object in the future.
func (*Core) Slave ¶
Slave creates and returns a connection from slave node if master-slave configured. It returns the default connection if master-slave not configured.
func (*Core) SlaveLink ¶
SlaveLink acts like function Slave but with additional `schema` parameter specifying the schema for the connection. It is defined for internal usage. Also see Slave.
func (*Core) TableFields ¶
func (c *Core) TableFields(table string, schema ...string) (fields map[string]*TableField, err error)
TableFields retrieves and returns the fields' information of specified table of current schema.
Note that it returns a map containing the field name and its corresponding fields. As a map is unsorted, the TableField struct has a "Index" field marks its sequence in the fields.
It's using cache feature to enhance the performance, which is never expired util the process restarts.
It does nothing in default.
func (*Core) Tables ¶
Tables retrieves and returns the tables of current schema. It's mainly used in cli tool chain for automatically generating the models.
It does nothing in default.
func (*Core) Transaction ¶
func (c *Core) Transaction(ctx context.Context, f func(ctx context.Context, tx *TX) error) (err error)
Transaction wraps the transaction logic using function `f`. It rollbacks the transaction and returns the error from function `f` if it returns non-nil error. It commits the transaction and returns nil if function `f` returns nil.
Note that, you should not Commit or Rollback the transaction in function `f` as it is automatically handled by this function.
func (*Core) Union ¶
Union does "(SELECT xxx FROM xxx) UNION (SELECT xxx FROM xxx) ..." statement.
func (*Core) UnionAll ¶
UnionAll does "(SELECT xxx FROM xxx) UNION ALL (SELECT xxx FROM xxx) ..." statement.
func (*Core) Update ¶
func (c *Core) Update(ctx context.Context, table string, data interface{}, condition interface{}, args ...interface{}) (sql.Result, error)
Update does "UPDATE ... " statement for the table.
The parameter `data` can be type of string/map/gmap/struct/*struct, etc. Eg: "uid=10000", "uid", 10000, g.Map{"uid": 10000, "name":"john"}
The parameter `condition` can be type of string/map/gmap/slice/struct/*struct, etc. It is commonly used with parameter `args`. Eg: "uid=10000", "uid", 10000 "money>? AND name like ?", 99999, "vip_%" "status IN (?)", g.Slice{1,2,3} "age IN(?,?)", 18, 50 User{ Id : 1, UserName : "john"}.
type Counter ¶
Counter is the type for update count.
type DB ¶
type DB interface { // Model creates and returns a new ORM model from given schema. // The parameter `table` can be more than one table names, and also alias name, like: // 1. Model names: // Model("user") // Model("user u") // Model("user, user_detail") // Model("user u, user_detail ud") // 2. Model name with alias: Model("user", "u") // Also see Core.Model. Model(tableNameOrStruct ...interface{}) *Model // Raw creates and returns a model based on a raw sql not a table. Raw(rawSql string, args ...interface{}) *Model // Schema creates and returns a schema. // Also see Core.Schema. Schema(schema string) *Schema // With creates and returns an ORM model based on meta data of given object. // Also see Core.With. With(objects ...interface{}) *Model // Open creates a raw connection object for database with given node configuration. // Note that it is not recommended using the this function manually. // Also see DriverMysql.Open. Open(config *ConfigNode) (*sql.DB, error) // Ctx is a chaining function, which creates and returns a new DB that is a shallow copy // of current DB object and with given context in it. // Also see Core.Ctx. Ctx(ctx context.Context) DB // Close closes the database and prevents new queries from starting. // Close then waits for all queries that have started processing on the server // to finish. // // It is rare to Close a DB, as the DB handle is meant to be // long-lived and shared between many goroutines. Close(ctx context.Context) error Query(ctx context.Context, sql string, args ...interface{}) (Result, error) // See Core.Query. Exec(ctx context.Context, sql string, args ...interface{}) (sql.Result, error) // See Core.Exec. Prepare(ctx context.Context, sql string, execOnMaster ...bool) (*Stmt, error) // See Core.Prepare. Insert(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error) // See Core.Insert. InsertIgnore(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error) // See Core.InsertIgnore. InsertAndGetId(ctx context.Context, table string, data interface{}, batch ...int) (int64, error) // See Core.InsertAndGetId. Replace(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error) // See Core.Replace. Save(ctx context.Context, table string, data interface{}, batch ...int) (sql.Result, error) // See Core.Save. Update(ctx context.Context, table string, data interface{}, condition interface{}, args ...interface{}) (sql.Result, error) // See Core.Update. Delete(ctx context.Context, table string, condition interface{}, args ...interface{}) (sql.Result, error) // See Core.Delete. DoGetAll(ctx context.Context, link Link, sql string, args ...interface{}) (result Result, err error) // See Core.DoGetAll. DoInsert(ctx context.Context, link Link, table string, data List, option DoInsertOption) (result sql.Result, err error) // See Core.DoInsert. DoUpdate(ctx context.Context, link Link, table string, data interface{}, condition string, args ...interface{}) (result sql.Result, err error) // See Core.DoUpdate. DoDelete(ctx context.Context, link Link, table string, condition string, args ...interface{}) (result sql.Result, err error) // See Core.DoDelete. DoQuery(ctx context.Context, link Link, sql string, args ...interface{}) (result Result, err error) // See Core.DoQuery. DoExec(ctx context.Context, link Link, sql string, args ...interface{}) (result sql.Result, err error) // See Core.DoExec. DoCommit(ctx context.Context, link Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error) // See Core.DoCommit. DoPrepare(ctx context.Context, link Link, sql string) (*Stmt, error) // See Core.DoPrepare. GetAll(ctx context.Context, sql string, args ...interface{}) (Result, error) // See Core.GetAll. GetOne(ctx context.Context, sql string, args ...interface{}) (Record, error) // See Core.GetOne. GetValue(ctx context.Context, sql string, args ...interface{}) (Value, error) // See Core.GetValue. GetArray(ctx context.Context, sql string, args ...interface{}) ([]Value, error) // See Core.GetArray. GetCount(ctx context.Context, sql string, args ...interface{}) (int, error) // See Core.GetCount. GetScan(ctx context.Context, objPointer interface{}, sql string, args ...interface{}) error // See Core.GetScan. Union(unions ...*Model) *Model // See Core.Union. UnionAll(unions ...*Model) *Model // See Core.UnionAll. Master(schema ...string) (*sql.DB, error) // See Core.Master. Slave(schema ...string) (*sql.DB, error) // See Core.Slave. PingMaster() error // See Core.PingMaster. PingSlave() error // See Core.PingSlave. Begin(ctx context.Context) (*TX, error) // See Core.Begin. Transaction(ctx context.Context, f func(ctx context.Context, tx *TX) error) error // See Core.Transaction. GetCache() *gcache.Cache // See Core.GetCache. SetDebug(debug bool) // See Core.SetDebug. GetDebug() bool // See Core.GetDebug. SetSchema(schema string) // See Core.SetSchema. GetSchema() string // See Core.GetSchema. GetPrefix() string // See Core.GetPrefix. GetGroup() string // See Core.GetGroup. SetDryRun(enabled bool) // See Core.SetDryRun. GetDryRun() bool // See Core.GetDryRun. SetLogger(logger *glog.Logger) // See Core.SetLogger. GetLogger() *glog.Logger // See Core.GetLogger. GetConfig() *ConfigNode // See Core.GetConfig. SetMaxIdleConnCount(n int) // See Core.SetMaxIdleConnCount. SetMaxOpenConnCount(n int) // See Core.SetMaxOpenConnCount. SetMaxConnLifeTime(d time.Duration) // See Core.SetMaxConnLifeTime. GetCtx() context.Context // See Core.GetCtx. GetCore() *Core // See Core.GetCore GetChars() (charLeft string, charRight string) // See Core.GetChars. Tables(ctx context.Context, schema ...string) (tables []string, err error) // See Core.Tables. TableFields(ctx context.Context, table string, schema ...string) (map[string]*TableField, error) // See Core.TableFields. FilteredLink() string // FilteredLink is used for filtering sensitive information in `Link` configuration before output it to tracing server. }
DB defines the interfaces for ORM operations.
func Instance ¶
Instance returns an instance for DB operations. The parameter `name` specifies the configuration group name, which is DefaultGroupName in default.
type DoInsertOption ¶
type DoInsertOption struct { OnDuplicateStr string OnDuplicateMap map[string]interface{} InsertOption int // Insert operation. BatchCount int // Batch count for batch inserting. }
DoInsertOption is the input struct for function DoInsert.
type Driver ¶
type Driver interface { // New creates and returns a database object for specified database server. New(core *Core, node *ConfigNode) (DB, error) }
Driver is the interface for integrating sql drivers into package gdb.
type DriverMssql ¶
type DriverMssql struct {
*Core
}
DriverMssql is the driver for SQL server database.
func (*DriverMssql) DoCommit ¶
func (d *DriverMssql) DoCommit(ctx context.Context, link Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error)
DoCommit deals with the sql string before commits it to underlying sql driver.
func (*DriverMssql) DoInsert ¶
func (d *DriverMssql) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error)
DoInsert is not supported in mssql.
func (*DriverMssql) FilteredLink ¶
func (d *DriverMssql) FilteredLink() string
FilteredLink retrieves and returns filtered `linkInfo` that can be using for logging or tracing purpose.
func (*DriverMssql) GetChars ¶
func (d *DriverMssql) GetChars() (charLeft string, charRight string)
GetChars returns the security char for this type of database.
func (*DriverMssql) New ¶
func (d *DriverMssql) New(core *Core, node *ConfigNode) (DB, error)
New creates and returns a database object for SQL server. It implements the interface of gdb.Driver for extra database driver installation.
func (*DriverMssql) Open ¶
func (d *DriverMssql) Open(config *ConfigNode) (*sql.DB, error)
Open creates and returns an underlying sql.DB object for mssql.
func (*DriverMssql) TableFields ¶
func (d *DriverMssql) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*TableField, err error)
TableFields retrieves and returns the fields information of specified table of current schema.
Also see DriverMysql.TableFields.
type DriverMysql ¶
type DriverMysql struct {
*Core
}
DriverMysql is the driver for mysql database.
func (*DriverMysql) DoCommit ¶
func (d *DriverMysql) DoCommit(ctx context.Context, link Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error)
DoCommit handles the sql before posts it to database.
func (*DriverMysql) FilteredLink ¶
func (d *DriverMysql) FilteredLink() string
FilteredLink retrieves and returns filtered `linkInfo` that can be using for logging or tracing purpose.
func (*DriverMysql) GetChars ¶
func (d *DriverMysql) GetChars() (charLeft string, charRight string)
GetChars returns the security char for this type of database.
func (*DriverMysql) New ¶
func (d *DriverMysql) New(core *Core, node *ConfigNode) (DB, error)
New creates and returns a database object for mysql. It implements the interface of gdb.Driver for extra database driver installation.
func (*DriverMysql) Open ¶
func (d *DriverMysql) Open(config *ConfigNode) (*sql.DB, error)
Open creates and returns an underlying sql.DB object for mysql. Note that it converts time.Time argument to local timezone in default.
func (*DriverMysql) TableFields ¶
func (d *DriverMysql) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*TableField, err error)
TableFields retrieves and returns the fields information of specified table of current schema.
The parameter `link` is optional, if given nil it automatically retrieves a raw sql connection as its link to proceed necessary sql query.
Note that it returns a map containing the field name and its corresponding fields. As a map is unsorted, the TableField struct has a "Index" field marks its sequence in the fields.
It's using cache feature to enhance the performance, which is never expired util the process restarts.
type DriverOracle ¶
type DriverOracle struct {
*Core
}
DriverOracle is the driver for oracle database.
func (*DriverOracle) DoCommit ¶
func (d *DriverOracle) DoCommit(ctx context.Context, link Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error)
DoCommit deals with the sql string before commits it to underlying sql driver.
func (*DriverOracle) DoInsert ¶
func (d *DriverOracle) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error)
DoInsert inserts or updates data for given table. This function is usually used for custom interface definition, you do not need call it manually. The parameter `data` can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
The parameter `option` values are as follows: 0: insert: just insert, if there's unique/primary key in the data, it returns error; 1: replace: if there's unique/primary key in the data, it deletes it from table and inserts a new one; 2: save: if there's unique/primary key in the data, it updates it or else inserts a new one; 3: ignore: if there's unique/primary key in the data, it ignores the inserting;
func (*DriverOracle) FilteredLink ¶
func (d *DriverOracle) FilteredLink() string
FilteredLink retrieves and returns filtered `linkInfo` that can be using for logging or tracing purpose.
func (*DriverOracle) GetChars ¶
func (d *DriverOracle) GetChars() (charLeft string, charRight string)
GetChars returns the security char for this type of database.
func (*DriverOracle) New ¶
func (d *DriverOracle) New(core *Core, node *ConfigNode) (DB, error)
New creates and returns a database object for oracle. It implements the interface of gdb.Driver for extra database driver installation.
func (*DriverOracle) Open ¶
func (d *DriverOracle) Open(config *ConfigNode) (*sql.DB, error)
Open creates and returns a underlying sql.DB object for oracle.
func (*DriverOracle) TableFields ¶
func (d *DriverOracle) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*TableField, err error)
TableFields retrieves and returns the fields information of specified table of current schema.
Also see DriverMysql.TableFields.
func (*DriverOracle) Tables ¶
Tables retrieves and returns the tables of current schema. It's mainly used in cli tool chain for automatically generating the models. Note that it ignores the parameter `schema` in oracle database, as it is not necessary.
type DriverPgsql ¶
type DriverPgsql struct {
*Core
}
DriverPgsql is the driver for postgresql database.
func (*DriverPgsql) DoCommit ¶
func (d *DriverPgsql) DoCommit(ctx context.Context, link Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error)
DoCommit deals with the sql string before commits it to underlying sql driver.
func (*DriverPgsql) DoInsert ¶
func (d *DriverPgsql) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error)
DoInsert is not supported in pgsql.
func (*DriverPgsql) FilteredLink ¶
func (d *DriverPgsql) FilteredLink() string
FilteredLink retrieves and returns filtered `linkInfo` that can be using for logging or tracing purpose.
func (*DriverPgsql) GetChars ¶
func (d *DriverPgsql) GetChars() (charLeft string, charRight string)
GetChars returns the security char for this type of database.
func (*DriverPgsql) New ¶
func (d *DriverPgsql) New(core *Core, node *ConfigNode) (DB, error)
New creates and returns a database object for postgresql. It implements the interface of gdb.Driver for extra database driver installation.
func (*DriverPgsql) Open ¶
func (d *DriverPgsql) Open(config *ConfigNode) (*sql.DB, error)
Open creates and returns a underlying sql.DB object for pgsql.
func (*DriverPgsql) TableFields ¶
func (d *DriverPgsql) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*TableField, err error)
TableFields retrieves and returns the fields' information of specified table of current schema.
Also see DriverMysql.TableFields.
type DriverSqlite ¶
type DriverSqlite struct {
*Core
}
DriverSqlite is the driver for sqlite database.
func (*DriverSqlite) DoCommit ¶
func (d *DriverSqlite) DoCommit(ctx context.Context, link Link, sql string, args []interface{}) (newSql string, newArgs []interface{}, err error)
DoCommit deals with the sql string before commits it to underlying sql driver.
func (*DriverSqlite) DoInsert ¶
func (d *DriverSqlite) DoInsert(ctx context.Context, link Link, table string, list List, option DoInsertOption) (result sql.Result, err error)
DoInsert is not supported in sqlite.
func (*DriverSqlite) FilteredLink ¶
func (d *DriverSqlite) FilteredLink() string
FilteredLink retrieves and returns filtered `linkInfo` that can be using for logging or tracing purpose.
func (*DriverSqlite) GetChars ¶
func (d *DriverSqlite) GetChars() (charLeft string, charRight string)
GetChars returns the security char for this type of database.
func (*DriverSqlite) New ¶
func (d *DriverSqlite) New(core *Core, node *ConfigNode) (DB, error)
New creates and returns a database object for sqlite. It implements the interface of gdb.Driver for extra database driver installation.
func (*DriverSqlite) Open ¶
func (d *DriverSqlite) Open(config *ConfigNode) (*sql.DB, error)
Open creates and returns a underlying sql.DB object for sqlite.
func (*DriverSqlite) TableFields ¶
func (d *DriverSqlite) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*TableField, err error)
TableFields retrieves and returns the fields' information of specified table of current schema.
Also see DriverMysql.TableFields.
type Link ¶
type Link interface { Query(sql string, args ...interface{}) (*sql.Rows, error) Exec(sql string, args ...interface{}) (sql.Result, error) Prepare(sql string) (*sql.Stmt, error) QueryContext(ctx context.Context, sql string, args ...interface{}) (*sql.Rows, error) ExecContext(ctx context.Context, sql string, args ...interface{}) (sql.Result, error) PrepareContext(ctx context.Context, sql string) (*sql.Stmt, error) IsTransaction() bool }
Link is a common database function wrapper interface.
type Map ¶
type Map = map[string]interface{} // Map is alias of map[string]interface{}, which is the most common usage map type.
type Model ¶
type Model struct {
// contains filtered or unexported fields
}
Model is core struct implementing the DAO for ORM.
func (*Model) All ¶
All does "SELECT FROM ..." statement for the model. It retrieves the records from table and returns the result as slice type. It returns nil if there's no record retrieved with the given conditions from table.
The optional parameter `where` is the same as the parameter of Model.Where function, see Model.Where.
func (*Model) Args ¶
Args sets custom arguments for model operation.
func (*Model) Array ¶
Array queries and returns data values as slice from database. Note that if there are multiple columns in the result, it returns just one column values randomly.
If the optional parameter `fieldsAndWhere` is given, the fieldsAndWhere[0] is the selected fields and fieldsAndWhere[1:] is treated as where condition fields. Also see Model.Fields and Model.Where functions.
func (*Model) Avg ¶
Avg does "SELECT AVG(x) FROM ..." statement for the model.
func (*Model) Batch ¶
Batch sets the batch operation number for the model.
func (*Model) Cache ¶
func (m *Model) Cache(option CacheOption) *Model
Cache sets the cache feature for the model. It caches the result of the sql, which means if there's another same sql request, it just reads and returns the result from cache, it but not committed and executed into the database.
Note that, the cache feature is disabled if the model is performing select statement on a transaction.
func (*Model) Chunk ¶
func (m *Model) Chunk(size int, handler ChunkHandler)
Chunk iterates the query result with given `size` and `handler` function.
func (*Model) Clone ¶
Clone creates and returns a new model which is a clone of current model. Note that it uses deep-copy for the clone.
func (*Model) Count ¶
Count does "SELECT COUNT(x) FROM ..." statement for the model. The optional parameter `where` is the same as the parameter of Model.Where function, see Model.Where.
func (*Model) CountColumn ¶
CountColumn does "SELECT COUNT(x) FROM ..." statement for the model.
func (*Model) Ctx ¶
Ctx sets the context for current operation.
func (*Model) DB ¶
DB sets/changes the db object for current operation.
func (*Model) Data ¶
Data sets the operation data for the model. The parameter `data` can be type of string/map/gmap/slice/struct/*struct, etc. Note that, it uses shallow value copying for `data` if `data` is type of map/slice to avoid changing it inside function. Eg: Data("uid=10000") Data("uid", 10000) Data("uid=? AND name=?", 10000, "john") Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"}).
func (*Model) Decrement ¶
Decrement decrements a column's value by a given amount. The parameter `amount` can be type of float or integer.
func (*Model) Delete ¶
Delete does "DELETE FROM ... " statement for the model. The optional parameter `where` is the same as the parameter of Model.Where function, see Model.Where.
func (*Model) Distinct ¶
Distinct forces the query to only return distinct results.
func (*Model) FieldAvg ¶
FieldAvg formats and appends commonly used field `AVG(column)` to the select fields of model.
func (*Model) FieldCount ¶
FieldCount formats and appends commonly used field `COUNT(column)` to the select fields of model.
func (*Model) FieldMax ¶
FieldMax formats and appends commonly used field `MAX(column)` to the select fields of model.
func (*Model) FieldMin ¶
FieldMin formats and appends commonly used field `MIN(column)` to the select fields of model.
func (*Model) FieldSum ¶
FieldSum formats and appends commonly used field `SUM(column)` to the select fields of model.
func (*Model) Fields ¶
Fields appends `fieldNamesOrMapStruct` to the operation fields of the model, multiple fields joined using char ','. The parameter `fieldNamesOrMapStruct` can be type of string/map/*map/struct/*struct.
Eg: Fields("id", "name", "age") Fields([]string{"id", "name", "age"}) Fields(map[string]interface{}{"id":1, "name":"john", "age":18}) Fields(User{ Id: 1, Name: "john", Age: 18}).
func (*Model) FieldsEx ¶
FieldsEx appends `fieldNamesOrMapStruct` to the excluded operation fields of the model, multiple fields joined using char ','. Note that this function supports only single table operations. The parameter `fieldNamesOrMapStruct` can be type of string/map/*map/struct/*struct.
Also see Fields.
func (*Model) FieldsExPrefix ¶
FieldsExPrefix performs as function FieldsEx but add extra prefix for each field.
func (*Model) FieldsPrefix ¶
FieldsPrefix performs as function Fields but add extra prefix for each field.
func (*Model) GetCtx ¶
GetCtx returns the context for current Model. It returns `context.Background()` is there's no context previously set.
func (*Model) GetFieldsExStr ¶
GetFieldsExStr retrieves and returns fields which are not in parameter `fields` from the table, joined with char ','. The parameter `fields` specifies the fields that are excluded. The optional parameter `prefix` specifies the prefix for each field, eg: FieldsExStr("id", "u.").
func (*Model) GetFieldsStr ¶
GetFieldsStr retrieves and returns all fields from the table, joined with char ','. The optional parameter `prefix` specifies the prefix for each field, eg: GetFieldsStr("u.").
func (*Model) Group ¶
Group sets the "GROUP BY" statement for the model.
func (*Model) Handler ¶
func (m *Model) Handler(handlers ...ModelHandler) *Model
Handler calls each of `handlers` on current Model and returns a new Model. ModelHandler is a function that handles given Model and returns a new Model that is custom modified.
func (*Model) HasField ¶
HasField determine whether the field exists in the table.
func (*Model) Having ¶
Having sets the having statement for the model. The parameters of this function usage are as the same as function Where. See Where.
func (*Model) Increment ¶
Increment increments a column's value by a given amount. The parameter `amount` can be type of float or integer.
func (*Model) InnerJoin ¶
InnerJoin does "INNER JOIN ... ON ..." statement on the model. The parameter `table` can be joined table and its joined condition, and also with its alias name。
Eg: Model("user").InnerJoin("user_detail", "user_detail.uid=user.uid") Model("user", "u").InnerJoin("user_detail", "ud", "ud.uid=u.uid") Model("user", "u").InnerJoin("SELECT xxx FROM xxx AS a", "a.uid=u.uid").
func (*Model) InnerJoinOnField ¶
InnerJoinOnField performs as InnerJoin, but it joins both tables with the same field name.
Eg: Model("order").InnerJoinOnField("user", "user_id") Model("order").InnerJoinOnField("product", "product_id").
func (*Model) Insert ¶
Insert does "INSERT INTO ..." statement for the model. The optional parameter `data` is the same as the parameter of Model.Data function, see Model.Data.
func (*Model) InsertAndGetId ¶
InsertAndGetId performs action Insert and returns the last insert id that automatically generated.
func (*Model) InsertIgnore ¶
InsertIgnore does "INSERT IGNORE INTO ..." statement for the model. The optional parameter `data` is the same as the parameter of Model.Data function, see Model.Data.
func (*Model) LeftJoin ¶
LeftJoin does "LEFT JOIN ... ON ..." statement on the model. The parameter `table` can be joined table and its joined condition, and also with its alias name.
Eg: Model("user").LeftJoin("user_detail", "user_detail.uid=user.uid") Model("user", "u").LeftJoin("user_detail", "ud", "ud.uid=u.uid") Model("user", "u").LeftJoin("SELECT xxx FROM xxx AS a", "a.uid=u.uid").
func (*Model) LeftJoinOnField ¶
LeftJoinOnField performs as LeftJoin, but it joins both tables with the same field name.
Eg: Model("order").LeftJoinOnField("user", "user_id") Model("order").LeftJoinOnField("product", "product_id").
func (*Model) Limit ¶
Limit sets the "LIMIT" statement for the model. The parameter `limit` can be either one or two number, if passed two number is passed, it then sets "LIMIT limit[0],limit[1]" statement for the model, or else it sets "LIMIT limit[0]" statement.
func (*Model) LockShared ¶
LockShared sets the lock in share mode for current operation.
func (*Model) LockUpdate ¶
LockUpdate sets the lock for update for current operation.
func (*Model) Master ¶
Master marks the following operation on master node.
func (*Model) Max ¶
Max does "SELECT MAX(x) FROM ..." statement for the model.
func (*Model) Min ¶
Min does "SELECT MIN(x) FROM ..." statement for the model.
func (*Model) Offset ¶
Offset sets the "OFFSET" statement for the model. It only makes sense for some databases like SQLServer, PostgreSQL, etc.
func (*Model) OmitEmpty ¶
OmitEmpty sets optionOmitEmpty option for the model, which automatically filers the data and where parameters for `empty` values.
func (*Model) OmitEmptyData ¶
OmitEmptyData sets optionOmitEmptyData option for the model, which automatically filers the Data parameters for `empty` values.
func (*Model) OmitEmptyWhere ¶
OmitEmptyWhere sets optionOmitEmptyWhere option for the model, which automatically filers the Where/Having parameters for `empty` values.
Eg: Where("id", []int{}).All() -> SELECT xxx FROM xxx WHERE 0=1 Where("name", "").All() -> SELECT xxx FROM xxx WHERE `name`=” OmitEmpty().Where("id", []int{}).All() -> SELECT xxx FROM xxx OmitEmpty().("name", "").All() -> SELECT xxx FROM xxx.
func (*Model) OmitNil ¶
OmitNil sets optionOmitNil option for the model, which automatically filers the data and where parameters for `nil` values.
func (*Model) OmitNilData ¶
OmitNilData sets optionOmitNilData option for the model, which automatically filers the Data parameters for `nil` values.
func (*Model) OmitNilWhere ¶
OmitNilWhere sets optionOmitNilWhere option for the model, which automatically filers the Where/Having parameters for `nil` values.
func (*Model) OnDuplicate ¶
OnDuplicate sets the operations when columns conflicts occurs. In MySQL, this is used for "ON DUPLICATE KEY UPDATE" statement. The parameter `onDuplicate` can be type of string/Raw/*Raw/map/slice. Example: OnDuplicate("nickname, age") OnDuplicate("nickname", "age")
OnDuplicate(g.Map{ "nickname": gdb.Raw("CONCAT('name_', VALUES(`nickname`))"), })
OnDuplicate(g.Map{ "nickname": "passport", }).
func (*Model) OnDuplicateEx ¶
OnDuplicateEx sets the excluding columns for operations when columns conflicts occurs. In MySQL, this is used for "ON DUPLICATE KEY UPDATE" statement. The parameter `onDuplicateEx` can be type of string/map/slice. Example: OnDuplicateEx("passport, password") OnDuplicateEx("passport", "password")
OnDuplicateEx(g.Map{ "passport": "", "password": "", }).
func (*Model) One ¶
One retrieves one record from table and returns the result as map type. It returns nil if there's no record retrieved with the given conditions from table.
The optional parameter `where` is the same as the parameter of Model.Where function, see Model.Where.
func (*Model) Order ¶
Order sets the "ORDER BY" statement for the model.
Eg: Order("id desc") Order("id", "desc") Order("id desc,name asc").
func (*Model) OrderAsc ¶
OrderAsc sets the "ORDER BY xxx ASC" statement for the model.
func (*Model) OrderDesc ¶
OrderDesc sets the "ORDER BY xxx DESC" statement for the model.
func (*Model) OrderRandom ¶
OrderRandom sets the "ORDER BY RANDOM()" statement for the model.
func (*Model) Page ¶
Page sets the paging number for the model. The parameter `page` is started from 1 for paging. Note that, it differs that the Limit function starts from 0 for "LIMIT" statement.
func (*Model) QuoteWord ¶
QuoteWord checks given string `s` a word, if true it quotes `s` with security chars of the database and returns the quoted string; or else it returns `s` without any change.
The meaning of a `word` can be considered as a column name.
func (*Model) Raw ¶
Raw sets current model as a raw sql model. Example:
db.Raw("SELECT * FROM `user` WHERE `name` = ?", "john").Scan(&result)
See Core.Raw.
func (*Model) Replace ¶
Replace does "REPLACE INTO ..." statement for the model. The optional parameter `data` is the same as the parameter of Model.Data function, see Model.Data.
func (*Model) RightJoin ¶
RightJoin does "RIGHT JOIN ... ON ..." statement on the model. The parameter `table` can be joined table and its joined condition, and also with its alias name.
Eg: Model("user").RightJoin("user_detail", "user_detail.uid=user.uid") Model("user", "u").RightJoin("user_detail", "ud", "ud.uid=u.uid") Model("user", "u").RightJoin("SELECT xxx FROM xxx AS a", "a.uid=u.uid").
func (*Model) RightJoinOnField ¶
RightJoinOnField performs as RightJoin, but it joins both tables with the same field name.
Eg: Model("order").InnerJoinOnField("user", "user_id") Model("order").InnerJoinOnField("product", "product_id").
func (*Model) Safe ¶
Safe marks this model safe or unsafe. If safe is true, it clones and returns a new model object whenever the operation done, or else it changes the attribute of current model.
func (*Model) Save ¶
Save does "INSERT INTO ... ON DUPLICATE KEY UPDATE..." statement for the model. The optional parameter `data` is the same as the parameter of Model.Data function, see Model.Data.
It updates the record if there's primary or unique index in the saving data, or else it inserts a new record into the table.
func (*Model) Scan ¶
Scan automatically calls Struct or Structs function according to the type of parameter `pointer`. It calls function doStruct if `pointer` is type of *struct/**struct. It calls function doStructs if `pointer` is type of *[]struct/*[]*struct.
The optional parameter `where` is the same as the parameter of Model.Where function, see Model.Where.
Note that it returns sql.ErrNoRows if the given parameter `pointer` pointed to a variable that has default value and there's no record retrieved with the given conditions from table.
Example: user := new(User) err := db.Model("user").Where("id", 1).Scan(user)
user := (*User)(nil) err := db.Model("user").Where("id", 1).Scan(&user)
users := ([]User)(nil) err := db.Model("user").Scan(&users)
users := ([]*User)(nil) err := db.Model("user").Scan(&users).
func (*Model) ScanList ¶
func (m *Model) ScanList(structSlicePointer interface{}, bindToAttrName string, relationAttrNameAndFields ...string) (err error)
ScanList converts `r` to struct slice which contains other complex struct attributes. Note that the parameter `listPointer` should be type of *[]struct/*[]*struct.
See Result.ScanList.
func (*Model) Schema ¶
Schema sets the schema for current operation.
func (*Model) Slave ¶
Slave marks the following operation on slave node. Note that it makes sense only if there's any slave node configured.
func (*Model) Sum ¶
Sum does "SELECT SUM(x) FROM ..." statement for the model.
func (*Model) TX ¶
TX sets/changes the transaction for current operation.
func (*Model) TableFields ¶
func (m *Model) TableFields(tableStr string, schema ...string) (fields map[string]*TableField, err error)
TableFields retrieves and returns the fields' information of specified table of current schema.
Also see DriverMysql.TableFields.
func (*Model) Transaction ¶
func (m *Model) Transaction(ctx context.Context, f func(ctx context.Context, tx *TX) error) (err error)
Transaction wraps the transaction logic using function `f`. It rollbacks the transaction and returns the error from function `f` if it returns non-nil error. It commits the transaction and returns nil if function `f` returns nil.
Note that, you should not Commit or Rollback the transaction in function `f` as it is automatically handled by this function.
func (*Model) Union ¶
Union does "(SELECT xxx FROM xxx) UNION (SELECT xxx FROM xxx) ..." statement for the model.
func (*Model) UnionAll ¶
UnionAll does "(SELECT xxx FROM xxx) UNION ALL (SELECT xxx FROM xxx) ..." statement for the model.
func (*Model) Unscoped ¶
Unscoped disables the auto-update time feature for insert, update and delete options.
func (*Model) Update ¶
Update does "UPDATE ... " statement for the model.
If the optional parameter `dataAndWhere` is given, the dataAndWhere[0] is the updated data field, and dataAndWhere[1:] is treated as where condition fields. Also see Model.Data and Model.Where functions.
func (*Model) Value ¶
Value retrieves a specified record value from table and returns the result as interface type. It returns nil if there's no record found with the given conditions from table.
If the optional parameter `fieldsAndWhere` is given, the fieldsAndWhere[0] is the selected fields and fieldsAndWhere[1:] is treated as where condition fields. Also see Model.Fields and Model.Where functions.
func (*Model) Where ¶
Where sets the condition statement for the model. The parameter `where` can be type of string/map/gmap/slice/struct/*struct, etc. Note that, if it's called more than one times, multiple conditions will be joined into where statement using "AND". Eg: Where("uid=10000") Where("uid", 10000) Where("money>? AND name like ?", 99999, "vip_%") Where("uid", 1).Where("name", "john") Where("status IN (?)", g.Slice{1,2,3}) Where("age IN(?,?)", 18, 50) Where(User{ Id : 1, UserName : "john"}).
func (*Model) WhereBetween ¶
WhereBetween builds `column BETWEEN min AND max` statement.
func (*Model) WhereGT ¶
WhereGT builds `column > value` statement.
func (*Model) WhereGTE ¶
WhereGTE builds `column >= value` statement.
func (*Model) WhereIn ¶
WhereIn builds `column IN (in)` statement.
func (*Model) WhereLT ¶
WhereLT builds `column < value` statement.
func (*Model) WhereLTE ¶
WhereLTE builds `column <= value` statement.
func (*Model) WhereLike ¶
WhereLike builds `column LIKE like` statement.
func (*Model) WhereNot ¶
WhereNot builds `column != value` statement.
func (*Model) WhereNotBetween ¶
WhereNotBetween builds `column NOT BETWEEN min AND max` statement.
func (*Model) WhereNotIn ¶
WhereNotIn builds `column NOT IN (in)` statement.
func (*Model) WhereNotLike ¶
WhereNotLike builds `column NOT LIKE like` statement.
func (*Model) WhereNotNull ¶
WhereNotNull builds `columns[0] IS NOT NULL AND columns[1] IS NOT NULL ...` statement.
func (*Model) WhereNull ¶
WhereNull builds `columns[0] IS NULL AND columns[1] IS NULL ...` statement.
func (*Model) WhereOr ¶
WhereOr adds "OR" condition to the where statement.
func (*Model) WhereOrBetween ¶
WhereOrBetween builds `column BETWEEN min AND max` statement in `OR` conditions.
func (*Model) WhereOrGT ¶
WhereOrGT builds `column > value` statement in `OR` conditions..
func (*Model) WhereOrGTE ¶
WhereOrGTE builds `column >= value` statement in `OR` conditions..
func (*Model) WhereOrIn ¶
WhereOrIn builds `column IN (in)` statement in `OR` conditions.
func (*Model) WhereOrLT ¶
WhereOrLT builds `column < value` statement in `OR` conditions..
func (*Model) WhereOrLTE ¶
WhereOrLTE builds `column <= value` statement in `OR` conditions..
func (*Model) WhereOrLike ¶
WhereOrLike builds `column LIKE like` statement in `OR` conditions.
func (*Model) WhereOrNotBetween ¶
WhereOrNotBetween builds `column NOT BETWEEN min AND max` statement in `OR` conditions.
func (*Model) WhereOrNotIn ¶
WhereOrNotIn builds `column NOT IN (in)` statement.
func (*Model) WhereOrNotLike ¶
WhereOrNotLike builds `column NOT LIKE like` statement in `OR` conditions.
func (*Model) WhereOrNotNull ¶
WhereOrNotNull builds `columns[0] IS NOT NULL OR columns[1] IS NOT NULL ...` statement in `OR` conditions.
func (*Model) WhereOrNull ¶
WhereOrNull builds `columns[0] IS NULL OR columns[1] IS NULL ...` statement in `OR` conditions.
func (*Model) WhereOrPrefix ¶
WhereOrPrefix performs as WhereOr, but it adds prefix to each field in where statement. Eg: WhereOrPrefix("order", "status", "paid") => WHERE xxx OR (`order`.`status`='paid') WhereOrPrefix("order", struct{Status:"paid", "channel":"bank"}) => WHERE xxx OR (`order`.`status`='paid' AND `order`.`channel`='bank')
func (*Model) WhereOrPrefixBetween ¶
WhereOrPrefixBetween builds `prefix.column BETWEEN min AND max` statement in `OR` conditions.
func (*Model) WhereOrPrefixGT ¶
WhereOrPrefixGT builds `prefix.column > value` statement in `OR` conditions..
func (*Model) WhereOrPrefixGTE ¶
WhereOrPrefixGTE builds `prefix.column >= value` statement in `OR` conditions..
func (*Model) WhereOrPrefixIn ¶
WhereOrPrefixIn builds `prefix.column IN (in)` statement in `OR` conditions.
func (*Model) WhereOrPrefixLT ¶
WhereOrPrefixLT builds `prefix.column < value` statement in `OR` conditions..
func (*Model) WhereOrPrefixLTE ¶
WhereOrPrefixLTE builds `prefix.column <= value` statement in `OR` conditions..
func (*Model) WhereOrPrefixLike ¶
WhereOrPrefixLike builds `prefix.column LIKE like` statement in `OR` conditions.
func (*Model) WhereOrPrefixNotBetween ¶
WhereOrPrefixNotBetween builds `prefix.column NOT BETWEEN min AND max` statement in `OR` conditions.
func (*Model) WhereOrPrefixNotIn ¶
WhereOrPrefixNotIn builds `prefix.column NOT IN (in)` statement.
func (*Model) WhereOrPrefixNotLike ¶
WhereOrPrefixNotLike builds `prefix.column NOT LIKE like` statement in `OR` conditions.
func (*Model) WhereOrPrefixNotNull ¶
WhereOrPrefixNotNull builds `prefix.columns[0] IS NOT NULL OR prefix.columns[1] IS NOT NULL ...` statement in `OR` conditions.
func (*Model) WhereOrPrefixNull ¶
WhereOrPrefixNull builds `prefix.columns[0] IS NULL OR prefix.columns[1] IS NULL ...` statement in `OR` conditions.
func (*Model) WhereOrf ¶
WhereOrf builds `OR` condition string using fmt.Sprintf and arguments. Eg: WhereOrf(`amount<? and status=%s`, "paid", 100) => WHERE xxx OR `amount`<100 and status='paid' WhereOrf(`amount<%d and status=%s`, 100, "paid") => WHERE xxx OR `amount`<100 and status='paid'
func (*Model) WherePrefix ¶
WherePrefix performs as Where, but it adds prefix to each field in where statement. Eg: WherePrefix("order", "status", "paid") => WHERE `order`.`status`='paid' WherePrefix("order", struct{Status:"paid", "channel":"bank"}) => WHERE `order`.`status`='paid' AND `order`.`channel`='bank'
func (*Model) WherePrefixBetween ¶
WherePrefixBetween builds `prefix.column BETWEEN min AND max` statement.
func (*Model) WherePrefixGT ¶
WherePrefixGT builds `prefix.column > value` statement.
func (*Model) WherePrefixGTE ¶
WherePrefixGTE builds `prefix.column >= value` statement.
func (*Model) WherePrefixIn ¶
WherePrefixIn builds `prefix.column IN (in)` statement.
func (*Model) WherePrefixLT ¶
WherePrefixLT builds `prefix.column < value` statement.
func (*Model) WherePrefixLTE ¶
WherePrefixLTE builds `prefix.column <= value` statement.
func (*Model) WherePrefixLike ¶
WherePrefixLike builds `prefix.column LIKE like` statement.
func (*Model) WherePrefixNot ¶
WherePrefixNot builds `prefix.column != value` statement.
func (*Model) WherePrefixNotBetween ¶
WherePrefixNotBetween builds `prefix.column NOT BETWEEN min AND max` statement.
func (*Model) WherePrefixNotIn ¶
WherePrefixNotIn builds `prefix.column NOT IN (in)` statement.
func (*Model) WherePrefixNotLike ¶
WherePrefixNotLike builds `prefix.column NOT LIKE like` statement.
func (*Model) WherePrefixNotNull ¶
WherePrefixNotNull builds `prefix.columns[0] IS NOT NULL AND prefix.columns[1] IS NOT NULL ...` statement.
func (*Model) WherePrefixNull ¶
WherePrefixNull builds `prefix.columns[0] IS NULL AND prefix.columns[1] IS NULL ...` statement.
func (*Model) WherePri ¶
WherePri does the same logic as Model.Where except that if the parameter `where` is a single condition like int/string/float/slice, it treats the condition as the primary key value. That is, if primary key is "id" and given `where` parameter as "123", the WherePri function treats the condition as "id=123", but Model.Where treats the condition as string "123".
func (*Model) Wheref ¶
Wheref builds condition string using fmt.Sprintf and arguments. Note that if the number of `args` is more than the placeholder in `format`, the extra `args` will be used as the where condition arguments of the Model. Eg: Wheref(`amount<? and status=%s`, "paid", 100) => WHERE `amount`<100 and status='paid' Wheref(`amount<%d and status=%s`, 100, "paid") => WHERE `amount`<100 and status='paid'
func (*Model) With ¶
With creates and returns an ORM model based on metadata of given object. It also enables model association operations feature on given `object`. It can be called multiple times to add one or more objects to model and enable their mode association operations feature. For example, if given struct definition:
type User struct { gmeta.Meta `orm:"table:user"` Id int `json:"id"` Name string `json:"name"` UserDetail *UserDetail `orm:"with:uid=id"` UserScores []*UserScores `orm:"with:uid=id"` }
We can enable model association operations on attribute `UserDetail` and `UserScores` by:
db.With(User{}.UserDetail).With(User{}.UserDetail).Scan(xxx)
Or:
db.With(UserDetail{}).With(UserDetail{}).Scan(xxx)
Or:
db.With(UserDetail{}, UserDetail{}).Scan(xxx)
type ModelHandler ¶
ModelHandler is a function that handles given Model and returns a new Model that is custom modified.
type ModelWhereHolder ¶
type ModelWhereHolder struct { Operator int // Operator for this holder. Where interface{} // Where parameter, which can commonly be type of string/map/struct. Args []interface{} // Arguments for where parameter. Prefix string // Field prefix, eg: "user.", "order.". }
ModelWhereHolder is the holder for where condition preparing.
type Raw ¶
type Raw string // Raw is a raw sql that will not be treated as argument but as a direct sql part.
type Record ¶
func (Record) IsEmpty ¶
IsEmpty checks and returns whether `r` is empty.
func (Record) Struct ¶
Struct converts `r` to a struct. Note that the parameter `pointer` should be type of *struct/**struct.
Note that it returns sql.ErrNoRows if `r` is empty.
type Result ¶
type Result []Record // Result is the row record array.
func (Result) Array ¶
Array retrieves and returns specified column values as slice. The parameter `field` is optional is the column field is only one. The default `field` is the first field name of the first item in `Result` if parameter `field` is not given.
func (Result) Chunk ¶
Chunk splits a Result into multiple Results, the size of each array is determined by `size`. The last chunk may contain less than size elements.
func (Result) IsEmpty ¶
IsEmpty checks and returns whether `r` is empty.
func (Result) MapKeyInt ¶
MapKeyInt converts `r` to a map[int]Map of which key is specified by `key`.
func (Result) MapKeyStr ¶
MapKeyStr converts `r` to a map[string]Map of which key is specified by `key`.
func (Result) MapKeyUint ¶
MapKeyUint converts `r` to a map[uint]Map of which key is specified by `key`.
func (Result) MapKeyValue ¶
MapKeyValue converts `r` to a map[string]Value of which key is specified by `key`. Note that the item value may be type of slice.
func (Result) RecordKeyInt ¶
RecordKeyInt converts `r` to a map[int]Record of which key is specified by `key`.
func (Result) RecordKeyStr ¶
RecordKeyStr converts `r` to a map[string]Record of which key is specified by `key`.
func (Result) RecordKeyUint ¶
RecordKeyUint converts `r` to a map[uint]Record of which key is specified by `key`.
func (Result) ScanList ¶
func (r Result) ScanList(structSlicePointer interface{}, bindToAttrName string, relationAttrNameAndFields ...string) (err error)
ScanList converts `r` to struct slice which contains other complex struct attributes. Note that the parameter `structSlicePointer` should be type of *[]struct/*[]*struct.
Usage example 1: Normal attribute struct relation:
type EntityUser struct { Uid int Name string }
type EntityUserDetail struct { Uid int Address string }
type EntityUserScores struct { Id int Uid int Score int Course string }
type Entity struct { User *EntityUser UserDetail *EntityUserDetail UserScores []*EntityUserScores }
var users []*Entity ScanList(&users, "User") ScanList(&users, "User", "uid") ScanList(&users, "UserDetail", "User", "uid:Uid") ScanList(&users, "UserScores", "User", "uid:Uid") ScanList(&users, "UserScores", "User", "uid")
Usage example 2: Embedded attribute struct relation:
type EntityUser struct { Uid int Name string }
type EntityUserDetail struct { Uid int Address string }
type EntityUserScores struct { Id int Uid int Score int }
type Entity struct { EntityUser UserDetail EntityUserDetail UserScores []EntityUserScores }
var users []*Entity ScanList(&users) ScanList(&users, "UserDetail", "uid") ScanList(&users, "UserScores", "uid")
The parameters "User/UserDetail/UserScores" in the example codes specify the target attribute struct that current result will be bound to.
The "uid" in the example codes is the table field name of the result, and the "Uid" is the relational struct attribute name - not the attribute name of the bound to target. In the example codes, it's attribute name "Uid" of "User" of entity "Entity". It automatically calculates the HasOne/HasMany relationship with given `relation` parameter.
See the example or unit testing cases for clear understanding for this function.
func (Result) Structs ¶
Structs converts `r` to struct slice. Note that the parameter `pointer` should be type of *[]struct/*[]*struct.
type Schema ¶
type Schema struct {
// contains filtered or unexported fields
}
Schema is a schema object from which it can then create a Model.
type Sql ¶
type Sql struct { Sql string // SQL string(may contain reserved char '?'). Type string // SQL operation type. Args []interface{} // Arguments for this sql. Format string // Formatted sql which contains arguments in the sql. Error error // Execution result. Start int64 // Start execution timestamp in milliseconds. End int64 // End execution timestamp in milliseconds. Group string // Group is the group name of the configuration that the sql is executed from. IsTransaction bool // IsTransaction marks whether this sql is executed in transaction. RowsAffected int64 // RowsAffected marks retrieved or affected number with current sql statement. }
Sql is the sql recording struct.
type SqlResult ¶
type SqlResult struct {
// contains filtered or unexported fields
}
SqlResult is execution result for sql operations. It also supports batch operation result for rowsAffected.
func (*SqlResult) LastInsertId ¶
LastInsertId returns the integer generated by the database in response to a command. Typically this will be from an "auto increment" column when inserting a new row. Not all databases support this feature, and the syntax of such statements varies. Also See sql.Result.
func (*SqlResult) MustGetAffected ¶
MustGetAffected returns the affected rows count, if any error occurs, it panics.
func (*SqlResult) MustGetInsertId ¶
MustGetInsertId returns the last insert id, if any error occurs, it panics.
type Stmt ¶
Stmt is a prepared statement. A Stmt is safe for concurrent use by multiple goroutines.
If a Stmt is prepared on a Tx or Conn, it will be bound to a single underlying connection forever. If the Tx or Conn closes, the Stmt will become unusable and all operations will return an error. If a Stmt is prepared on a DB, it will remain usable for the lifetime of the DB. When the Stmt needs to execute on a new underlying connection, it will prepare itself on the new connection automatically.
func (*Stmt) Exec ¶
Exec executes a prepared statement with the given arguments and returns a Result summarizing the effect of the statement.
func (*Stmt) ExecContext ¶
ExecContext executes a prepared statement with the given arguments and returns a Result summarizing the effect of the statement.
func (*Stmt) Query ¶
Query executes a prepared query statement with the given arguments and returns the query results as a *Rows.
func (*Stmt) QueryContext ¶
QueryContext executes a prepared query statement with the given arguments and returns the query results as a *Rows.
func (*Stmt) QueryRow ¶
QueryRow executes a prepared query statement with the given arguments. If an error occurs during the execution of the statement, that error will be returned by a call to Scan on the returned *Row, which is always non-nil. If the query selects no rows, the *Row's Scan will return ErrNoRows. Otherwise, the *Row's Scan scans the first selected row and discards the rest.
Example usage:
var name string err := nameByUseridStmt.QueryRow(id).Scan(&name)
func (*Stmt) QueryRowContext ¶
QueryRowContext executes a prepared query statement with the given arguments. If an error occurs during the execution of the statement, that error will be returned by a call to Scan on the returned *Row, which is always non-nil. If the query selects no rows, the *Row's Scan will return ErrNoRows. Otherwise, the *Row's Scan scans the first selected row and discards the rest.
type TX ¶
type TX struct {
// contains filtered or unexported fields
}
TX is the struct for transaction management.
func TXFromCtx ¶
TXFromCtx retrieves and returns transaction object from context. It is usually used in nested transaction feature, and it returns nil if it is not set previously.
func (*TX) Commit ¶
Commit commits current transaction. Note that it releases previous saved transaction point if it's in a nested transaction procedure, or else it commits the hole transaction.
func (*TX) Ctx ¶
Ctx sets the context for current transaction.
func (*TX) Delete ¶
Delete does "DELETE FROM ... " statement for the table.
The parameter `condition` can be type of string/map/gmap/slice/struct/*struct, etc. It is commonly used with parameter `args`. Eg: "uid=10000", "uid", 10000 "money>? AND name like ?", 99999, "vip_%" "status IN (?)", g.Slice{1,2,3} "age IN(?,?)", 18, 50 User{ Id : 1, UserName : "john"}.
func (*TX) Exec ¶
Exec does none query operation on transaction. See Core.Exec.
func (*TX) GetAll ¶
GetAll queries and returns data records from database.
func (*TX) GetCount ¶
GetCount queries and returns the count from database.
func (*TX) GetOne ¶
GetOne queries and returns one record from database.
func (*TX) GetScan ¶
GetScan queries one or more records from database and converts them to given struct or struct array.
If parameter `pointer` is type of struct pointer, it calls GetStruct internally for the conversion. If parameter `pointer` is type of slice, it calls GetStructs internally for conversion.
func (*TX) GetStruct ¶
GetStruct queries one record from database and converts it to given struct. The parameter `pointer` should be a pointer to struct.
func (*TX) GetStructs ¶
GetStructs queries records from database and converts them to given struct. The parameter `pointer` should be type of struct slice: []struct/[]*struct.
func (*TX) GetValue ¶
GetValue queries and returns the field value from database. The sql should query only one field from database, or else it returns only one field of the result.
func (*TX) Insert ¶
Insert does "INSERT INTO ..." statement for the table. If there's already one unique record of the data in the table, it returns error.
The parameter `data` can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
The parameter `batch` specifies the batch operation count when given data is slice.
func (*TX) InsertAndGetId ¶
InsertAndGetId performs action Insert and returns the last insert id that automatically generated.
func (*TX) InsertIgnore ¶
InsertIgnore does "INSERT IGNORE INTO ..." statement for the table. If there's already one unique record of the data in the table, it ignores the inserting.
The parameter `data` can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
The parameter `batch` specifies the batch operation count when given data is slice.
func (*TX) IsClosed ¶
IsClosed checks and returns this transaction has already been committed or rolled back.
func (*TX) Model ¶
Model acts like Core.Model except it operates on transaction. See Core.Model.
func (*TX) Prepare ¶
Prepare creates a prepared statement for later queries or executions. Multiple queries or executions may be run concurrently from the returned statement. The caller must call the statement's Close method when the statement is no longer needed.
func (*TX) Query ¶
Query does query operation on transaction. See Core.Query.
func (*TX) Replace ¶
Replace does "REPLACE INTO ..." statement for the table. If there's already one unique record of the data in the table, it deletes the record and inserts a new one.
The parameter `data` can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
The parameter `data` can be type of map/gmap/struct/*struct/[]map/[]struct, etc. If given data is type of slice, it then does batch replacing, and the optional parameter `batch` specifies the batch operation count.
func (*TX) Rollback ¶
Rollback aborts current transaction. Note that it aborts current transaction if it's in a nested transaction procedure, or else it aborts the hole transaction.
func (*TX) RollbackTo ¶
RollbackTo performs `ROLLBACK TO SAVEPOINT xxx` SQL statement that rollbacks to specified saved transaction. The parameter `point` specifies the point name that was saved previously.
func (*TX) Save ¶
Save does "INSERT INTO ... ON DUPLICATE KEY UPDATE..." statement for the table. It updates the record if there's primary or unique index in the saving data, or else it inserts a new record into the table.
The parameter `data` can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
If given data is type of slice, it then does batch saving, and the optional parameter `batch` specifies the batch operation count.
func (*TX) SavePoint ¶
SavePoint performs `SAVEPOINT xxx` SQL statement that saves transaction at current point. The parameter `point` specifies the point name that will be saved to server.
func (*TX) Schema ¶
Schema creates and returns a initialization model from schema, from which it can then create a Model.
func (*TX) Transaction ¶
func (tx *TX) Transaction(ctx context.Context, f func(ctx context.Context, tx *TX) error) (err error)
Transaction wraps the transaction logic using function `f`. It rollbacks the transaction and returns the error from function `f` if it returns non-nil error. It commits the transaction and returns nil if function `f` returns nil.
Note that, you should not Commit or Rollback the transaction in function `f` as it is automatically handled by this function.
func (*TX) Update ¶
func (tx *TX) Update(table string, data interface{}, condition interface{}, args ...interface{}) (sql.Result, error)
Update does "UPDATE ... " statement for the table.
The parameter `data` can be type of string/map/gmap/struct/*struct, etc. Eg: "uid=10000", "uid", 10000, g.Map{"uid": 10000, "name":"john"}
The parameter `condition` can be type of string/map/gmap/slice/struct/*struct, etc. It is commonly used with parameter `args`. Eg: "uid=10000", "uid", 10000 "money>? AND name like ?", 99999, "vip_%" "status IN (?)", g.Slice{1,2,3} "age IN(?,?)", 18, 50 User{ Id : 1, UserName : "john"}.
type TableField ¶
type TableField struct { Index int // For ordering purpose as map is unordered. Name string // Field name. Type string // Field type. Null bool // Field can be null or not. Key string // The index information(empty if it's not an index). Default interface{} // Default value for the field. Extra string // Extra information. Comment string // Field comment. }
TableField is the struct for table field.
Source Files ¶
- gdb.go
- gdb_core.go
- gdb_core_config.go
- gdb_core_link.go
- gdb_core_structure.go
- gdb_core_tracing.go
- gdb_core_transaction.go
- gdb_core_underlying.go
- gdb_core_utility.go
- gdb_driver_mssql.go
- gdb_driver_mysql.go
- gdb_driver_oracle.go
- gdb_driver_pgsql.go
- gdb_driver_sqlite.go
- gdb_func.go
- gdb_model.go
- gdb_model_cache.go
- gdb_model_delete.go
- gdb_model_fields.go
- gdb_model_insert.go
- gdb_model_join.go
- gdb_model_lock.go
- gdb_model_option.go
- gdb_model_order_group.go
- gdb_model_select.go
- gdb_model_time.go
- gdb_model_transaction.go
- gdb_model_update.go
- gdb_model_utility.go
- gdb_model_where.go
- gdb_model_where_prefix.go
- gdb_model_whereor.go
- gdb_model_whereor_prefix.go
- gdb_model_with.go
- gdb_result.go
- gdb_schema.go
- gdb_statement.go
- gdb_type_record.go
- gdb_type_result.go
- gdb_type_result_scanlist.go