Merge pull request #4653 from Loyalsoldier/orm-fix-lint

Fix lint and format code in client/orm dir
This commit is contained in:
Ming Deng 2021-06-06 21:43:38 +08:00 committed by GitHub
commit 060ae4b987
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
32 changed files with 108 additions and 137 deletions

View File

@ -10,6 +10,7 @@
- Chore: format code. [4615](https://github.com/beego/beego/pull/4615) - Chore: format code. [4615](https://github.com/beego/beego/pull/4615)
- Test on Go v1.15.x & v1.16.x. [4614](https://github.com/beego/beego/pull/4614) - Test on Go v1.15.x & v1.16.x. [4614](https://github.com/beego/beego/pull/4614)
- Env: non-empty GOBIN & GOPATH. [4613](https://github.com/beego/beego/pull/4613) - Env: non-empty GOBIN & GOPATH. [4613](https://github.com/beego/beego/pull/4613)
- Fix lint and format code in client/orm dir [4653](https://github.com/beego/beego/pull/4653)
- Chore: update dependencies. [4611](https://github.com/beego/beego/pull/4611) - Chore: update dependencies. [4611](https://github.com/beego/beego/pull/4611)
- Update orm_test.go/TestInsertOrUpdate with table-driven. [4609](https://github.com/beego/beego/pull/4609) - Update orm_test.go/TestInsertOrUpdate with table-driven. [4609](https://github.com/beego/beego/pull/4609)
- Add: Resp() method for web.Controller. [4588](https://github.com/beego/beego/pull/4588) - Add: Resp() method for web.Controller. [4588](https://github.com/beego/beego/pull/4588)

View File

@ -5,9 +5,7 @@ import (
) )
func TestClause(t *testing.T) { func TestClause(t *testing.T) {
var ( column := `a`
column = `a`
)
o := Clause( o := Clause(
Column(column), Column(column),
@ -108,7 +106,6 @@ func TestParseOrder(t *testing.T) {
if orders[2].GetColumn() != `user.status` { if orders[2].GetColumn() != `user.status` {
t.Error() t.Error()
} }
} }
func TestOrder_GetColumn(t *testing.T) { func TestOrder_GetColumn(t *testing.T) {

View File

@ -27,9 +27,7 @@ type commander interface {
Run() error Run() error
} }
var ( var commands = make(map[string]commander)
commands = make(map[string]commander)
)
// print help. // print help.
func printHelp(errs ...string) { func printHelp(errs ...string) {

View File

@ -126,9 +126,7 @@ func getColumnAddQuery(al *alias, fi *fieldInfo) string {
// Get string value for the attribute "DEFAULT" for the CREATE, ALTER commands // Get string value for the attribute "DEFAULT" for the CREATE, ALTER commands
func getColumnDefault(fi *fieldInfo) string { func getColumnDefault(fi *fieldInfo) string {
var ( var v, t, d string
v, t, d string
)
// Skip default attribute if field is in relations // Skip default attribute if field is in relations
if fi.rel || fi.reverse { if fi.rel || fi.reverse {

View File

@ -32,13 +32,10 @@ const (
formatDateTime = "2006-01-02 15:04:05" formatDateTime = "2006-01-02 15:04:05"
) )
var (
// ErrMissPK missing pk error // ErrMissPK missing pk error
ErrMissPK = errors.New("missed pk value") var ErrMissPK = errors.New("missed pk value")
)
var ( var operators = map[string]bool{
operators = map[string]bool{
"exact": true, "exact": true,
"iexact": true, "iexact": true,
"strictexact": true, "strictexact": true,
@ -66,7 +63,6 @@ var (
"isnull": true, "isnull": true,
// "search": true, // "search": true,
} }
)
// an instance of dbBaser interface/ // an instance of dbBaser interface/
type dbBase struct { type dbBase struct {
@ -537,7 +533,6 @@ func (d *dbBase) InsertOrUpdate(ctx context.Context, q dbQuerier, mi *modelInfo,
names := make([]string, 0, len(mi.fields.dbcols)-1) names := make([]string, 0, len(mi.fields.dbcols)-1)
Q := d.ins.TableQuote() Q := d.ins.TableQuote()
values, _, err := d.collectValues(mi, ind, mi.fields.dbcols, true, true, &names, a.TZ) values, _, err := d.collectValues(mi, ind, mi.fields.dbcols, true, true, &names, a.TZ)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -934,7 +929,6 @@ func (d *dbBase) DeleteBatch(ctx context.Context, q dbQuerier, qs *querySet, mi
// read related records. // read related records.
func (d *dbBase) ReadBatch(ctx context.Context, q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition, container interface{}, tz *time.Location, cols []string) (int64, error) { func (d *dbBase) ReadBatch(ctx context.Context, q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition, container interface{}, tz *time.Location, cols []string) (int64, error) {
val := reflect.ValueOf(container) val := reflect.ValueOf(container)
ind := reflect.Indirect(val) ind := reflect.Indirect(val)
@ -1435,12 +1429,10 @@ end:
} }
return value, nil return value, nil
} }
// set one value to struct column field. // set one value to struct column field.
func (d *dbBase) setFieldValue(fi *fieldInfo, value interface{}, field reflect.Value) (interface{}, error) { func (d *dbBase) setFieldValue(fi *fieldInfo, value interface{}, field reflect.Value) (interface{}, error) {
fieldType := fi.fieldType fieldType := fi.fieldType
isNative := !fi.isFielder isNative := !fi.isFielder
@ -1632,7 +1624,6 @@ setValue:
// query sql, read values , save to *[]ParamList. // query sql, read values , save to *[]ParamList.
func (d *dbBase) ReadValues(ctx context.Context, q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition, exprs []string, container interface{}, tz *time.Location) (int64, error) { func (d *dbBase) ReadValues(ctx context.Context, q dbQuerier, qs *querySet, mi *modelInfo, cond *Condition, exprs []string, container interface{}, tz *time.Location) (int64, error) {
var ( var (
maps []Params maps []Params
lists []ParamsList lists []ParamsList

View File

@ -112,8 +112,10 @@ type DB struct {
stmtDecoratorsLimit int stmtDecoratorsLimit int
} }
var _ dbQuerier = new(DB) var (
var _ txer = new(DB) _ dbQuerier = new(DB)
_ txer = new(DB)
)
func (d *DB) Begin() (*sql.Tx, error) { func (d *DB) Begin() (*sql.Tx, error) {
return d.DB.Begin() return d.DB.Begin()
@ -221,8 +223,10 @@ type TxDB struct {
tx *sql.Tx tx *sql.Tx
} }
var _ dbQuerier = new(TxDB) var (
var _ txEnder = new(TxDB) _ dbQuerier = new(TxDB)
_ txEnder = new(TxDB)
)
func (t *TxDB) Commit() error { func (t *TxDB) Commit() error {
return t.tx.Commit() return t.tx.Commit()
@ -240,8 +244,10 @@ func (t *TxDB) RollbackUnlessCommit() error {
return nil return nil
} }
var _ dbQuerier = new(TxDB) var (
var _ txEnder = new(TxDB) _ dbQuerier = new(TxDB)
_ txEnder = new(TxDB)
)
func (t *TxDB) Prepare(query string) (*sql.Stmt, error) { func (t *TxDB) Prepare(query string) (*sql.Stmt, error) {
return t.PrepareContext(context.Background(), query) return t.PrepareContext(context.Background(), query)
@ -365,7 +371,6 @@ func addAliasWthDB(aliasName, driverName string, db *sql.DB, params ...DBOption)
} }
func newAliasWithDb(aliasName, driverName string, db *sql.DB, params ...DBOption) (*alias, error) { func newAliasWithDb(aliasName, driverName string, db *sql.DB, params ...DBOption) (*alias, error) {
al := &alias{} al := &alias{}
al.DB = &DB{ al.DB = &DB{
RWMutex: new(sync.RWMutex), RWMutex: new(sync.RWMutex),

View File

@ -124,7 +124,6 @@ func (d *dbBaseMysql) InsertOrUpdate(ctx context.Context, q dbQuerier, mi *model
names := make([]string, 0, len(mi.fields.dbcols)-1) names := make([]string, 0, len(mi.fields.dbcols)-1)
Q := d.ins.TableQuote() Q := d.ins.TableQuote()
values, _, err := d.collectValues(mi, ind, mi.fields.dbcols, true, true, &names, a.TZ) values, _, err := d.collectValues(mi, ind, mi.fields.dbcols, true, true, &names, a.TZ)
if err != nil { if err != nil {
return 0, err return 0, err
} }

View File

@ -106,7 +106,6 @@ func (t *dbTables) loopDepth(depth int, prefix string, fi *fieldInfo, related []
// parse related fields. // parse related fields.
func (t *dbTables) parseRelated(rels []string, depth int) { func (t *dbTables) parseRelated(rels []string, depth int) {
relsNum := len(rels) relsNum := len(rels)
related := make([]string, relsNum) related := make([]string, relsNum)
copy(related, rels) copy(related, rels)

View File

@ -55,7 +55,6 @@ func getExistPk(mi *modelInfo, ind reflect.Value) (column string, value interfac
// get fields description as flatted string. // get fields description as flatted string.
func getFlatParams(fi *fieldInfo, args []interface{}, tz *time.Location) (params []interface{}) { func getFlatParams(fi *fieldInfo, args []interface{}, tz *time.Location) (params []interface{}) {
outFor: outFor:
for _, arg := range args { for _, arg := range args {
val := reflect.ValueOf(arg) val := reflect.ValueOf(arg)

View File

@ -27,8 +27,7 @@ import (
var _ Ormer = new(DoNothingOrm) var _ Ormer = new(DoNothingOrm)
type DoNothingOrm struct { type DoNothingOrm struct{}
}
func (d *DoNothingOrm) Read(md interface{}, cols ...string) error { func (d *DoNothingOrm) Read(md interface{}, cols ...string) error {
return nil return nil

View File

@ -57,7 +57,6 @@ func TestDefaultValueFilterChainBuilder_FilterChain(t *testing.T) {
_, _ = o.InsertMulti(3, []*DefaultValueTestEntity{entity}) _, _ = o.InsertMulti(3, []*DefaultValueTestEntity{entity})
assert.Equal(t, 12, entity.Age) assert.Equal(t, 12, entity.Age)
assert.Equal(t, 13, entity.AgeInOldStyle) assert.Equal(t, 13, entity.AgeInOldStyle)
} }
type defaultValueTestOrm struct { type defaultValueTestOrm struct {

View File

@ -39,11 +39,12 @@ type FilterChainBuilder struct {
RunMode string RunMode string
} }
var summaryVec prometheus.ObserverVec var (
var initSummaryVec sync.Once summaryVec prometheus.ObserverVec
initSummaryVec sync.Once
)
func (builder *FilterChainBuilder) FilterChain(next orm.Filter) orm.Filter { func (builder *FilterChainBuilder) FilterChain(next orm.Filter) orm.Filter {
initSummaryVec.Do(func() { initSummaryVec.Do(func() {
summaryVec = prometheus.NewSummaryVec(prometheus.SummaryOpts{ summaryVec = prometheus.NewSummaryVec(prometheus.SummaryOpts{
Name: "beego", Name: "beego",

View File

@ -58,5 +58,4 @@ func TestFilterChainBuilder_FilterChain1(t *testing.T) {
inv.Method = "Update" inv.Method = "Update"
builder.report(ctx, inv, time.Second) builder.report(ctx, inv, time.Second)
} }

View File

@ -28,8 +28,10 @@ const (
TxNameKey = "TxName" TxNameKey = "TxName"
) )
var _ Ormer = new(filterOrmDecorator) var (
var _ TxOrmer = new(filterOrmDecorator) _ Ormer = new(filterOrmDecorator)
_ TxOrmer = new(filterOrmDecorator)
)
type filterOrmDecorator struct { type filterOrmDecorator struct {
ormer ormer
@ -120,7 +122,6 @@ func (f *filterOrmDecorator) ReadOrCreate(md interface{}, col1 string, cols ...s
} }
func (f *filterOrmDecorator) ReadOrCreateWithCtx(ctx context.Context, md interface{}, col1 string, cols ...string) (bool, int64, error) { func (f *filterOrmDecorator) ReadOrCreateWithCtx(ctx context.Context, md interface{}, col1 string, cols ...string) (bool, int64, error) {
mi, _ := modelCache.getByMd(md) mi, _ := modelCache.getByMd(md)
inv := &Invocation{ inv := &Invocation{
Method: "ReadOrCreateWithCtx", Method: "ReadOrCreateWithCtx",
@ -143,7 +144,6 @@ func (f *filterOrmDecorator) LoadRelated(md interface{}, name string, args ...ut
} }
func (f *filterOrmDecorator) LoadRelatedWithCtx(ctx context.Context, md interface{}, name string, args ...utils.KV) (int64, error) { func (f *filterOrmDecorator) LoadRelatedWithCtx(ctx context.Context, md interface{}, name string, args ...utils.KV) (int64, error) {
mi, _ := modelCache.getByMd(md) mi, _ := modelCache.getByMd(md)
inv := &Invocation{ inv := &Invocation{
Method: "LoadRelatedWithCtx", Method: "LoadRelatedWithCtx",
@ -162,7 +162,6 @@ func (f *filterOrmDecorator) LoadRelatedWithCtx(ctx context.Context, md interfac
} }
func (f *filterOrmDecorator) QueryM2M(md interface{}, name string) QueryM2Mer { func (f *filterOrmDecorator) QueryM2M(md interface{}, name string) QueryM2Mer {
mi, _ := modelCache.getByMd(md) mi, _ := modelCache.getByMd(md)
inv := &Invocation{ inv := &Invocation{
Method: "QueryM2M", Method: "QueryM2M",

View File

@ -27,7 +27,6 @@ import (
) )
func TestFilterOrmDecorator_Read(t *testing.T) { func TestFilterOrmDecorator_Read(t *testing.T) {
register() register()
o := &filterMockOrm{} o := &filterMockOrm{}

View File

@ -116,7 +116,6 @@ func (m *Migration) UniCol(uni, name string) *Column {
// ForeignCol creates a new foreign column and returns the instance of column // ForeignCol creates a new foreign column and returns the instance of column
func (m *Migration) ForeignCol(colname, foreigncol, foreigntable string) (foreign *Foreign) { func (m *Migration) ForeignCol(colname, foreigncol, foreigntable string) (foreign *Foreign) {
foreign = &Foreign{ForeignColumn: foreigncol, ForeignTable: foreigntable} foreign = &Foreign{ForeignColumn: foreigncol, ForeignTable: foreigntable}
foreign.Name = colname foreign.Name = colname
m.AddForeign(foreign) m.AddForeign(foreign)
@ -153,7 +152,6 @@ func (c *Column) SetAuto(inc bool) *Column {
func (c *Column) SetNullable(null bool) *Column { func (c *Column) SetNullable(null bool) *Column {
if null { if null {
c.Null = "" c.Null = ""
} else { } else {
c.Null = "NOT NULL" c.Null = "NOT NULL"
} }
@ -184,7 +182,6 @@ func (c *Column) SetDataType(dataType string) *Column {
func (c *RenameColumn) SetOldNullable(null bool) *RenameColumn { func (c *RenameColumn) SetOldNullable(null bool) *RenameColumn {
if null { if null {
c.OldNull = "" c.OldNull = ""
} else { } else {
c.OldNull = "NOT NULL" c.OldNull = "NOT NULL"
} }
@ -219,7 +216,6 @@ func (c *Column) SetPrimary(m *Migration) *Column {
// AddColumnsToUnique adds the columns to Unique Struct // AddColumnsToUnique adds the columns to Unique Struct
func (unique *Unique) AddColumnsToUnique(columns ...*Column) *Unique { func (unique *Unique) AddColumnsToUnique(columns ...*Column) *Unique {
unique.Columns = append(unique.Columns, columns...) unique.Columns = append(unique.Columns, columns...)
return unique return unique
@ -227,7 +223,6 @@ func (unique *Unique) AddColumnsToUnique(columns ...*Column) *Unique {
// AddColumns adds columns to m struct // AddColumns adds columns to m struct
func (m *Migration) AddColumns(columns ...*Column) *Migration { func (m *Migration) AddColumns(columns ...*Column) *Migration {
m.Columns = append(m.Columns, columns...) m.Columns = append(m.Columns, columns...)
return m return m

View File

@ -72,9 +72,7 @@ type Migration struct {
RemoveForeigns []*Foreign RemoveForeigns []*Foreign
} }
var ( var migrationMap map[string]Migrationer
migrationMap map[string]Migrationer
)
func init() { func init() {
migrationMap = make(map[string]Migrationer) migrationMap = make(map[string]Migrationer)
@ -82,7 +80,6 @@ func init() {
// Up implement in the Inheritance struct for upgrade // Up implement in the Inheritance struct for upgrade
func (m *Migration) Up() { func (m *Migration) Up() {
switch m.ModifyType { switch m.ModifyType {
case "reverse": case "reverse":
m.ModifyType = "alter" m.ModifyType = "alter"
@ -94,7 +91,6 @@ func (m *Migration) Up() {
// Down implement in the Inheritance struct for down // Down implement in the Inheritance struct for down
func (m *Migration) Down() { func (m *Migration) Down() {
switch m.ModifyType { switch m.ModifyType {
case "alter": case "alter":
m.ModifyType = "reverse" m.ModifyType = "reverse"
@ -311,6 +307,7 @@ func isRollBack(name string) bool {
} }
return false return false
} }
func getAllMigrations() (map[string]string, error) { func getAllMigrations() (map[string]string, error) {
o := orm.NewOrm() o := orm.NewOrm()
var maps []orm.Params var maps []orm.Params

View File

@ -55,7 +55,6 @@ func (o *OrmStub) Clear() {
func (o *OrmStub) FilterChain(next orm.Filter) orm.Filter { func (o *OrmStub) FilterChain(next orm.Filter) orm.Filter {
return func(ctx context.Context, inv *orm.Invocation) []interface{} { return func(ctx context.Context, inv *orm.Invocation) []interface{} {
ms := mockFromCtx(ctx) ms := mockFromCtx(ctx)
ms = append(ms, o.ms...) ms = append(ms, o.ms...)

View File

@ -22,8 +22,7 @@ import (
// DoNothingQueryM2Mer do nothing // DoNothingQueryM2Mer do nothing
// use it to build mock orm.QueryM2Mer // use it to build mock orm.QueryM2Mer
type DoNothingQueryM2Mer struct { type DoNothingQueryM2Mer struct{}
}
func (d *DoNothingQueryM2Mer) AddWithCtx(ctx context.Context, i ...interface{}) (int64, error) { func (d *DoNothingQueryM2Mer) AddWithCtx(ctx context.Context, i ...interface{}) (int64, error) {
return 0, nil return 0, nil

View File

@ -23,8 +23,7 @@ import (
// DoNothingQuerySetter do nothing // DoNothingQuerySetter do nothing
// usually you use this to build your mock QuerySetter // usually you use this to build your mock QuerySetter
type DoNothingQuerySetter struct { type DoNothingQuerySetter struct{}
}
func (d *DoNothingQuerySetter) OrderClauses(orders ...*order_clause.Order) orm.QuerySeter { func (d *DoNothingQuerySetter) OrderClauses(orders ...*order_clause.Order) orm.QuerySeter {
return d return d

View File

@ -20,8 +20,7 @@ import (
"github.com/beego/beego/v2/client/orm" "github.com/beego/beego/v2/client/orm"
) )
type DoNothingRawSetter struct { type DoNothingRawSetter struct{}
}
func (d *DoNothingRawSetter) Exec() (sql.Result, error) { func (d *DoNothingRawSetter) Exec() (sql.Result, error) {
return nil, nil return nil, nil

View File

@ -32,9 +32,7 @@ const (
defaultStructTagDelim = ";" defaultStructTagDelim = ";"
) )
var ( var modelCache = NewModelCacheHandler()
modelCache = NewModelCacheHandler()
)
// model info collection // model info collection
type _modelCache struct { type _modelCache struct {
@ -332,7 +330,6 @@ end:
// register register models to model cache // register register models to model cache
func (mc *_modelCache) register(prefixOrSuffixStr string, prefixOrSuffix bool, models ...interface{}) (err error) { func (mc *_modelCache) register(prefixOrSuffixStr string, prefixOrSuffix bool, models ...interface{}) (err error) {
for _, model := range models { for _, model := range models {
val := reflect.ValueOf(model) val := reflect.ValueOf(model)
typ := reflect.Indirect(val).Type() typ := reflect.Indirect(val).Type()

View File

@ -387,7 +387,6 @@ checkType:
fi.timePrecision = &v fi.timePrecision = &v
} }
} }
} }
if attrs["auto_now"] { if attrs["auto_now"] {

View File

@ -193,22 +193,24 @@ type DataNull struct {
DateTimePtr *time.Time `orm:"null"` DateTimePtr *time.Time `orm:"null"`
} }
type String string type (
type Boolean bool String string
type Byte byte Boolean bool
type Rune rune Byte byte
type Int int Rune rune
type Int8 int8 Int int
type Int16 int16 Int8 int8
type Int32 int32 Int16 int16
type Int64 int64 Int32 int32
type Uint uint Int64 int64
type Uint8 uint8 Uint uint
type Uint16 uint16 Uint8 uint8
type Uint32 uint32 Uint16 uint16
type Uint64 uint64 Uint32 uint32
type Float32 float64 Uint64 uint64
type Float64 float64 Float32 float64
Float64 float64
)
type DataCustom struct { type DataCustom struct {
ID int `orm:"column(id)"` ID int `orm:"column(id)"`
@ -486,8 +488,7 @@ var (
dDbBaser dbBaser dDbBaser dbBaser
) )
var ( var helpinfo = `need driver and source!
helpinfo = `need driver and source!
Default DB Drivers. Default DB Drivers.
@ -530,7 +531,6 @@ var (
go test -v github.com/beego/beego/v2/pgk/orm go test -v github.com/beego/beego/v2/pgk/orm
` `
)
func init() { func init() {
// Debug, _ = StrTo(DBARGS.Debug).Bool() // Debug, _ = StrTo(DBARGS.Debug).Bool()
@ -542,7 +542,6 @@ func init() {
} }
err := RegisterDataBase("default", DBARGS.Driver, DBARGS.Source, MaxIdleConnections(20)) err := RegisterDataBase("default", DBARGS.Driver, DBARGS.Source, MaxIdleConnections(20))
if err != nil { if err != nil {
panic(fmt.Sprintf("can not register database: %v", err)) panic(fmt.Sprintf("can not register database: %v", err))
} }
@ -551,5 +550,4 @@ func init() {
if alias.Driver == DRMySQL { if alias.Driver == DRMySQL {
alias.Engine = "INNODB" alias.Engine = "INNODB"
} }
} }

View File

@ -101,9 +101,11 @@ type ormBase struct {
db dbQuerier db dbQuerier
} }
var _ DQL = new(ormBase) var (
var _ DML = new(ormBase) _ DQL = new(ormBase)
var _ DriverGetter = new(ormBase) _ DML = new(ormBase)
_ DriverGetter = new(ormBase)
)
// get model info and model reflect value // get model info and model reflect value
func (o *ormBase) getMiInd(md interface{}, needPtr bool) (mi *modelInfo, ind reflect.Value) { func (o *ormBase) getMiInd(md interface{}, needPtr bool) (mi *modelInfo, ind reflect.Value) {
@ -133,6 +135,7 @@ func (o *ormBase) getFieldInfo(mi *modelInfo, name string) *fieldInfo {
func (o *ormBase) Read(md interface{}, cols ...string) error { func (o *ormBase) Read(md interface{}, cols ...string) error {
return o.ReadWithCtx(context.Background(), md, cols...) return o.ReadWithCtx(context.Background(), md, cols...)
} }
func (o *ormBase) ReadWithCtx(ctx context.Context, md interface{}, cols ...string) error { func (o *ormBase) ReadWithCtx(ctx context.Context, md interface{}, cols ...string) error {
mi, ind := o.getMiInd(md, true) mi, ind := o.getMiInd(md, true)
return o.alias.DbBaser.Read(ctx, o.db, mi, ind, o.alias.TZ, cols, false) return o.alias.DbBaser.Read(ctx, o.db, mi, ind, o.alias.TZ, cols, false)
@ -142,6 +145,7 @@ func (o *ormBase) ReadWithCtx(ctx context.Context, md interface{}, cols ...strin
func (o *ormBase) ReadForUpdate(md interface{}, cols ...string) error { func (o *ormBase) ReadForUpdate(md interface{}, cols ...string) error {
return o.ReadForUpdateWithCtx(context.Background(), md, cols...) return o.ReadForUpdateWithCtx(context.Background(), md, cols...)
} }
func (o *ormBase) ReadForUpdateWithCtx(ctx context.Context, md interface{}, cols ...string) error { func (o *ormBase) ReadForUpdateWithCtx(ctx context.Context, md interface{}, cols ...string) error {
mi, ind := o.getMiInd(md, true) mi, ind := o.getMiInd(md, true)
return o.alias.DbBaser.Read(ctx, o.db, mi, ind, o.alias.TZ, cols, true) return o.alias.DbBaser.Read(ctx, o.db, mi, ind, o.alias.TZ, cols, true)
@ -151,6 +155,7 @@ func (o *ormBase) ReadForUpdateWithCtx(ctx context.Context, md interface{}, cols
func (o *ormBase) ReadOrCreate(md interface{}, col1 string, cols ...string) (bool, int64, error) { func (o *ormBase) ReadOrCreate(md interface{}, col1 string, cols ...string) (bool, int64, error) {
return o.ReadOrCreateWithCtx(context.Background(), md, col1, cols...) return o.ReadOrCreateWithCtx(context.Background(), md, col1, cols...)
} }
func (o *ormBase) ReadOrCreateWithCtx(ctx context.Context, md interface{}, col1 string, cols ...string) (bool, int64, error) { func (o *ormBase) ReadOrCreateWithCtx(ctx context.Context, md interface{}, col1 string, cols ...string) (bool, int64, error) {
cols = append([]string{col1}, cols...) cols = append([]string{col1}, cols...)
mi, ind := o.getMiInd(md, true) mi, ind := o.getMiInd(md, true)
@ -177,6 +182,7 @@ func (o *ormBase) ReadOrCreateWithCtx(ctx context.Context, md interface{}, col1
func (o *ormBase) Insert(md interface{}) (int64, error) { func (o *ormBase) Insert(md interface{}) (int64, error) {
return o.InsertWithCtx(context.Background(), md) return o.InsertWithCtx(context.Background(), md)
} }
func (o *ormBase) InsertWithCtx(ctx context.Context, md interface{}) (int64, error) { func (o *ormBase) InsertWithCtx(ctx context.Context, md interface{}) (int64, error) {
mi, ind := o.getMiInd(md, true) mi, ind := o.getMiInd(md, true)
id, err := o.alias.DbBaser.Insert(ctx, o.db, mi, ind, o.alias.TZ) id, err := o.alias.DbBaser.Insert(ctx, o.db, mi, ind, o.alias.TZ)
@ -204,6 +210,7 @@ func (o *ormBase) setPk(mi *modelInfo, ind reflect.Value, id int64) {
func (o *ormBase) InsertMulti(bulk int, mds interface{}) (int64, error) { func (o *ormBase) InsertMulti(bulk int, mds interface{}) (int64, error) {
return o.InsertMultiWithCtx(context.Background(), bulk, mds) return o.InsertMultiWithCtx(context.Background(), bulk, mds)
} }
func (o *ormBase) InsertMultiWithCtx(ctx context.Context, bulk int, mds interface{}) (int64, error) { func (o *ormBase) InsertMultiWithCtx(ctx context.Context, bulk int, mds interface{}) (int64, error) {
var cnt int64 var cnt int64
@ -242,6 +249,7 @@ func (o *ormBase) InsertMultiWithCtx(ctx context.Context, bulk int, mds interfac
func (o *ormBase) InsertOrUpdate(md interface{}, colConflictAndArgs ...string) (int64, error) { func (o *ormBase) InsertOrUpdate(md interface{}, colConflictAndArgs ...string) (int64, error) {
return o.InsertOrUpdateWithCtx(context.Background(), md, colConflictAndArgs...) return o.InsertOrUpdateWithCtx(context.Background(), md, colConflictAndArgs...)
} }
func (o *ormBase) InsertOrUpdateWithCtx(ctx context.Context, md interface{}, colConflitAndArgs ...string) (int64, error) { func (o *ormBase) InsertOrUpdateWithCtx(ctx context.Context, md interface{}, colConflitAndArgs ...string) (int64, error) {
mi, ind := o.getMiInd(md, true) mi, ind := o.getMiInd(md, true)
id, err := o.alias.DbBaser.InsertOrUpdate(ctx, o.db, mi, ind, o.alias, colConflitAndArgs...) id, err := o.alias.DbBaser.InsertOrUpdate(ctx, o.db, mi, ind, o.alias, colConflitAndArgs...)
@ -259,6 +267,7 @@ func (o *ormBase) InsertOrUpdateWithCtx(ctx context.Context, md interface{}, col
func (o *ormBase) Update(md interface{}, cols ...string) (int64, error) { func (o *ormBase) Update(md interface{}, cols ...string) (int64, error) {
return o.UpdateWithCtx(context.Background(), md, cols...) return o.UpdateWithCtx(context.Background(), md, cols...)
} }
func (o *ormBase) UpdateWithCtx(ctx context.Context, md interface{}, cols ...string) (int64, error) { func (o *ormBase) UpdateWithCtx(ctx context.Context, md interface{}, cols ...string) (int64, error) {
mi, ind := o.getMiInd(md, true) mi, ind := o.getMiInd(md, true)
return o.alias.DbBaser.Update(ctx, o.db, mi, ind, o.alias.TZ, cols) return o.alias.DbBaser.Update(ctx, o.db, mi, ind, o.alias.TZ, cols)
@ -269,6 +278,7 @@ func (o *ormBase) UpdateWithCtx(ctx context.Context, md interface{}, cols ...str
func (o *ormBase) Delete(md interface{}, cols ...string) (int64, error) { func (o *ormBase) Delete(md interface{}, cols ...string) (int64, error) {
return o.DeleteWithCtx(context.Background(), md, cols...) return o.DeleteWithCtx(context.Background(), md, cols...)
} }
func (o *ormBase) DeleteWithCtx(ctx context.Context, md interface{}, cols ...string) (int64, error) { func (o *ormBase) DeleteWithCtx(ctx context.Context, md interface{}, cols ...string) (int64, error) {
mi, ind := o.getMiInd(md, true) mi, ind := o.getMiInd(md, true)
num, err := o.alias.DbBaser.Delete(ctx, o.db, mi, ind, o.alias.TZ, cols) num, err := o.alias.DbBaser.Delete(ctx, o.db, mi, ind, o.alias.TZ, cols)
@ -313,6 +323,7 @@ func (o *ormBase) QueryM2MWithCtx(_ context.Context, md interface{}, name string
func (o *ormBase) LoadRelated(md interface{}, name string, args ...utils.KV) (int64, error) { func (o *ormBase) LoadRelated(md interface{}, name string, args ...utils.KV) (int64, error) {
return o.LoadRelatedWithCtx(context.Background(), md, name, args...) return o.LoadRelatedWithCtx(context.Background(), md, name, args...)
} }
func (o *ormBase) LoadRelatedWithCtx(ctx context.Context, md interface{}, name string, args ...utils.KV) (int64, error) { func (o *ormBase) LoadRelatedWithCtx(ctx context.Context, md interface{}, name string, args ...utils.KV) (int64, error) {
_, fi, ind, qs := o.queryRelated(md, name) _, fi, ind, qs := o.queryRelated(md, name)
@ -482,6 +493,7 @@ func (o *ormBase) QueryTableWithCtx(_ context.Context, ptrStructOrTableName inte
func (o *ormBase) Raw(query string, args ...interface{}) RawSeter { func (o *ormBase) Raw(query string, args ...interface{}) RawSeter {
return o.RawWithCtx(context.Background(), query, args...) return o.RawWithCtx(context.Background(), query, args...)
} }
func (o *ormBase) RawWithCtx(ctx context.Context, query string, args ...interface{}) RawSeter { func (o *ormBase) RawWithCtx(ctx context.Context, query string, args ...interface{}) RawSeter {
return newRawSet(o, query, args) return newRawSet(o, query, args)
} }
@ -571,7 +583,7 @@ func doTxTemplate(o TxBeginner, ctx context.Context, opts *sql.TxOptions,
} }
} }
}() }()
var taskTxOrm = _txOrm taskTxOrm := _txOrm
err = task(ctx, taskTxOrm) err = task(ctx, taskTxOrm)
panicked = false panicked = false
return err return err

View File

@ -78,7 +78,6 @@ func (c Condition) AndNot(expr string, args ...interface{}) *Condition {
// AndCond combine a condition to current condition // AndCond combine a condition to current condition
func (c *Condition) AndCond(cond *Condition) *Condition { func (c *Condition) AndCond(cond *Condition) *Condition {
if c == cond { if c == cond {
panic(fmt.Errorf("<Condition.AndCond> cannot use self as sub cond")) panic(fmt.Errorf("<Condition.AndCond> cannot use self as sub cond"))
} }

View File

@ -40,7 +40,7 @@ func NewLog(out io.Writer) *Log {
} }
func debugLogQueies(alias *alias, operaton, query string, t time.Time, err error, args ...interface{}) { func debugLogQueies(alias *alias, operaton, query string, t time.Time, err error, args ...interface{}) {
var logMap = make(map[string]interface{}) logMap := make(map[string]interface{})
sub := time.Since(t) / 1e5 sub := time.Since(t) / 1e5
elsp := float64(int(sub)) / 10.0 elsp := float64(int(sub)) / 10.0
logMap["cost_time"] = elsp logMap["cost_time"] = elsp
@ -94,6 +94,7 @@ func (d *stmtQueryLog) ExecContext(ctx context.Context, args ...interface{}) (sq
debugLogQueies(d.alias, "st.Exec", d.query, a, err, args...) debugLogQueies(d.alias, "st.Exec", d.query, a, err, args...)
return res, err return res, err
} }
func (d *stmtQueryLog) Query(args ...interface{}) (*sql.Rows, error) { func (d *stmtQueryLog) Query(args ...interface{}) (*sql.Rows, error) {
return d.QueryContext(context.Background(), args...) return d.QueryContext(context.Background(), args...)
} }
@ -133,9 +134,11 @@ type dbQueryLog struct {
txe txEnder txe txEnder
} }
var _ dbQuerier = new(dbQueryLog) var (
var _ txer = new(dbQueryLog) _ dbQuerier = new(dbQueryLog)
var _ txEnder = new(dbQueryLog) _ txer = new(dbQueryLog)
_ txEnder = new(dbQueryLog)
)
func (d *dbQueryLog) Prepare(query string) (*sql.Stmt, error) { func (d *dbQueryLog) Prepare(query string) (*sql.Stmt, error) {
return d.PrepareContext(context.Background(), query) return d.PrepareContext(context.Background(), query)

View File

@ -253,7 +253,6 @@ func (o *rawSet) loopSetRefs(refs []interface{}, sInds []reflect.Value, nIndsPtr
} }
cur++ cur++
} }
} else { } else {
value := reflect.ValueOf(refs[cur]).Elem().Interface() value := reflect.ValueOf(refs[cur]).Elem().Interface()
if isPtr && value == nil { if isPtr && value == nil {
@ -437,7 +436,6 @@ func (o *rawSet) QueryRow(containers ...interface{}) error {
sInd.Set(nInd) sInd.Set(nInd)
} }
} }
} else { } else {
return ErrNoRows return ErrNoRows
} }
@ -606,7 +604,6 @@ func (o *rawSet) QueryRows(containers ...interface{}) (int64, error) {
} }
if cnt > 0 { if cnt > 0 {
if structMode { if structMode {
sInds[0].Set(sInd) sInds[0].Set(sInd)
} else { } else {

View File

@ -842,7 +842,6 @@ The program—and web server—godoc processes Go source files to extract docume
throwFailNow(t, AssertIs(nums, num)) throwFailNow(t, AssertIs(nums, num))
} }
} }
} }
func TestCustomField(t *testing.T) { func TestCustomField(t *testing.T) {
@ -1235,7 +1234,6 @@ func TestOne(t *testing.T) {
err = qs.Filter("user_name", "nothing").One(&user) err = qs.Filter("user_name", "nothing").One(&user)
throwFail(t, AssertIs(err, ErrNoRows)) throwFail(t, AssertIs(err, ErrNoRows))
} }
func TestValues(t *testing.T) { func TestValues(t *testing.T) {
@ -2219,7 +2217,7 @@ func TestTransaction(t *testing.T) {
to, err := o.Begin() to, err := o.Begin()
throwFail(t, err) throwFail(t, err)
var names = []string{"1", "2", "3"} names := []string{"1", "2", "3"}
var tag Tag var tag Tag
tag.Name = names[0] tag.Name = names[0]
@ -2262,7 +2260,6 @@ func TestTransaction(t *testing.T) {
num, err = o.QueryTable("tag").Filter("name", "commit").Delete() num, err = o.QueryTable("tag").Filter("name", "commit").Delete()
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, int64(1), num) assert.Equal(t, int64(1), num)
} }
func TestTxOrmRollbackUnlessCommit(t *testing.T) { func TestTxOrmRollbackUnlessCommit(t *testing.T) {

View File

@ -21,7 +21,6 @@ func processingStr(str []string) string {
// Select will join the fields // Select will join the fields
func (qb *PostgresQueryBuilder) Select(fields ...string) QueryBuilder { func (qb *PostgresQueryBuilder) Select(fields ...string) QueryBuilder {
var str string var str string
n := len(fields) n := len(fields)
@ -80,7 +79,6 @@ func (qb *PostgresQueryBuilder) RightJoin(table string) QueryBuilder {
// On join with on cond // On join with on cond
func (qb *PostgresQueryBuilder) On(cond string) QueryBuilder { func (qb *PostgresQueryBuilder) On(cond string) QueryBuilder {
var str string var str string
cond = strings.Replace(cond, " ", "", -1) cond = strings.Replace(cond, " ", "", -1)
slice := strings.Split(cond, "=") slice := strings.Split(cond, "=")