THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Browse Source

refactor query functions (#689)

* refactor query functions

* remove unused function

* remove unnecessary resetStatement and some improvements

* rename all Id to ID
tags/v0.6.4
Lunny Xiao GitHub 2 years ago
parent
commit
bb639f6700
32 changed files with 272 additions and 413 deletions
  1. +1
    -1
      doc.go
  2. +0
    -30
      engine.go
  3. +5
    -5
      examples/cache.go
  4. +1
    -1
      examples/cachegoroutine.go
  5. +1
    -1
      examples/derive.go
  6. +1
    -1
      examples/goroutine.go
  7. +1
    -1
      examples/maxconnect.go
  8. +1
    -1
      examples/singlemapping.go
  9. +12
    -12
      processors_test.go
  10. +5
    -36
      rows.go
  11. +1
    -11
      session.go
  12. +1
    -1
      session_cols_test.go
  13. +1
    -1
      session_cond_test.go
  14. +2
    -6
      session_convert.go
  15. +1
    -2
      session_delete.go
  16. +9
    -9
      session_delete_test.go
  17. +3
    -13
      session_exist.go
  18. +15
    -24
      session_find.go
  19. +15
    -21
      session_get.go
  20. +2
    -5
      session_insert.go
  21. +4
    -0
      session_iterate.go
  22. +22
    -22
      session_pk_test.go
  23. +108
    -108
      session_raw.go
  24. +3
    -22
      session_schema.go
  25. +3
    -23
      session_stats.go
  26. +2
    -4
      session_update.go
  27. +36
    -36
      session_update_test.go
  28. +3
    -3
      tag_extends_test.go
  29. +3
    -3
      tag_test.go
  30. +3
    -3
      tag_version_test.go
  31. +5
    -5
      types_null_test.go
  32. +2
    -2
      types_test.go

+ 1
- 1
doc.go View File

@@ -90,7 +90,7 @@ another is Rows

5. Update one or more records

affected, err := engine.Id(...).Update(&user)
affected, err := engine.ID(...).Update(&user)
// UPDATE user SET ...

6. Delete one or more records, Delete MUST has condition


+ 0
- 30
engine.go View File

@@ -273,36 +273,6 @@ func (engine *Engine) logSQL(sqlStr string, sqlArgs ...interface{}) {
}
}

func (engine *Engine) logSQLQueryTime(sqlStr string, args []interface{}, executionBlock func() (*core.Stmt, *core.Rows, error)) (*core.Stmt, *core.Rows, error) {
if engine.showSQL && engine.showExecTime {
b4ExecTime := time.Now()
stmt, res, err := executionBlock()
execDuration := time.Since(b4ExecTime)
if len(args) > 0 {
engine.logger.Infof("[SQL] %s %v - took: %v", sqlStr, args, execDuration)
} else {
engine.logger.Infof("[SQL] %s - took: %v", sqlStr, execDuration)
}
return stmt, res, err
}
return executionBlock()
}

func (engine *Engine) logSQLExecutionTime(sqlStr string, args []interface{}, executionBlock func() (sql.Result, error)) (sql.Result, error) {
if engine.showSQL && engine.showExecTime {
b4ExecTime := time.Now()
res, err := executionBlock()
execDuration := time.Since(b4ExecTime)
if len(args) > 0 {
engine.logger.Infof("[sql] %s [args] %v - took: %v", sqlStr, args, execDuration)
} else {
engine.logger.Infof("[sql] %s - took: %v", sqlStr, execDuration)
}
return res, err
}
return executionBlock()
}

// Sql provides raw sql input parameter. When you have a complex SQL statement
// and cannot use Where, Id, In and etc. Methods to describe, you can use SQL.
//


+ 5
- 5
examples/cache.go View File

@@ -67,7 +67,7 @@ func main() {
fmt.Println("users3:", users3)

user4 := new(User)
has, err := Orm.Id(1).Get(user4)
has, err := Orm.ID(1).Get(user4)
if err != nil {
fmt.Println(err)
return
@@ -76,7 +76,7 @@ func main() {
fmt.Println("user4:", has, user4)

user4.Name = "xiaolunwen"
_, err = Orm.Id(1).Update(user4)
_, err = Orm.ID(1).Update(user4)
if err != nil {
fmt.Println(err)
return
@@ -84,14 +84,14 @@ func main() {
fmt.Println("user4:", user4)

user5 := new(User)
has, err = Orm.Id(1).Get(user5)
has, err = Orm.ID(1).Get(user5)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("user5:", has, user5)

_, err = Orm.Id(1).Delete(new(User))
_, err = Orm.ID(1).Delete(new(User))
if err != nil {
fmt.Println(err)
return
@@ -99,7 +99,7 @@ func main() {

for {
user6 := new(User)
has, err = Orm.Id(1).Get(user6)
has, err = Orm.ID(1).Get(user6)
if err != nil {
fmt.Println(err)
return


+ 1
- 1
examples/cachegoroutine.go View File

@@ -55,7 +55,7 @@ func test(engine *xorm.Engine) {
} else if x+j < 16 {
_, err = engine.Insert(&User{Name: "xlw"})
} else if x+j < 32 {
//_, err = engine.Id(1).Delete(u)
//_, err = engine.ID(1).Delete(u)
_, err = engine.Delete(u)
}
if err != nil {


+ 1
- 1
examples/derive.go View File

@@ -51,7 +51,7 @@ func main() {
}

info := LoginInfo{}
_, err = orm.Id(1).Get(&info)
_, err = orm.ID(1).Get(&info)
if err != nil {
fmt.Println(err)
return


+ 1
- 1
examples/goroutine.go View File

@@ -59,7 +59,7 @@ func test(engine *xorm.Engine) {
} else if x+j < 16 {
_, err = engine.Insert(&User{Name: "xlw"})
} else if x+j < 32 {
_, err = engine.Id(1).Delete(u)
_, err = engine.ID(1).Delete(u)
}
if err != nil {
fmt.Println(err)


+ 1
- 1
examples/maxconnect.go View File

@@ -62,7 +62,7 @@ func test(engine *xorm.Engine) {
} else if x+j < 16 {
_, err = engine.Insert(&User{Name: "xlw"})
} else if x+j < 32 {
_, err = engine.Id(1).Delete(u)
_, err = engine.ID(1).Delete(u)
}
if err != nil {
fmt.Println(err)


+ 1
- 1
examples/singlemapping.go View File

@@ -48,7 +48,7 @@ func main() {
}

info := LoginInfo{}
_, err = orm.Id(1).Get(&info)
_, err = orm.ID(1).Get(&info)
if err != nil {
fmt.Println(err)
return


+ 12
- 12
processors_test.go View File

@@ -173,7 +173,7 @@ func TestProcessors(t *testing.T) {
}

p2 := &ProcessorsStruct{}
_, err = testEngine.Id(p.Id).Get(p2)
_, err = testEngine.ID(p.Id).Get(p2)
if err != nil {
t.Error(err)
panic(err)
@@ -308,7 +308,7 @@ func TestProcessors(t *testing.T) {
}

p2 = &ProcessorsStruct{}
_, err = testEngine.Id(p.Id).Get(p2)
_, err = testEngine.ID(p.Id).Get(p2)
if err != nil {
t.Error(err)
panic(err)
@@ -402,7 +402,7 @@ func TestProcessors(t *testing.T) {

for _, elem := range pslice {
p = &ProcessorsStruct{}
_, err = testEngine.Id(elem.Id).Get(p)
_, err = testEngine.ID(elem.Id).Get(p)
if err != nil {
t.Error(err)
panic(err)
@@ -508,7 +508,7 @@ func TestProcessorsTx(t *testing.T) {
}
session.Close()
p2 := &ProcessorsStruct{}
_, err = testEngine.Id(p.Id).Get(p2)
_, err = testEngine.ID(p.Id).Get(p2)
if err != nil {
t.Error(err)
panic(err)
@@ -569,7 +569,7 @@ func TestProcessorsTx(t *testing.T) {
}
session.Close()
p2 = &ProcessorsStruct{}
_, err = testEngine.Id(p.Id).Get(p2)
_, err = testEngine.ID(p.Id).Get(p2)
if err != nil {
t.Error(err)
panic(err)
@@ -616,7 +616,7 @@ func TestProcessorsTx(t *testing.T) {

p = p2 // reset

_, err = session.Id(insertedId).Before(b4UpdateFunc).After(afterUpdateFunc).Update(p)
_, err = session.ID(insertedId).Before(b4UpdateFunc).After(afterUpdateFunc).Update(p)
if err != nil {
t.Error(err)
panic(err)
@@ -656,7 +656,7 @@ func TestProcessorsTx(t *testing.T) {
session.Close()

p2 = &ProcessorsStruct{}
_, err = testEngine.Id(insertedId).Get(p2)
_, err = testEngine.ID(insertedId).Get(p2)
if err != nil {
t.Error(err)
panic(err)
@@ -729,7 +729,7 @@ func TestProcessorsTx(t *testing.T) {

p = &ProcessorsStruct{}

_, err = session.Id(insertedId).Before(b4UpdateFunc).After(afterUpdateFunc).Update(p)
_, err = session.ID(insertedId).Before(b4UpdateFunc).After(afterUpdateFunc).Update(p)
if err != nil {
t.Error(err)
panic(err)
@@ -767,7 +767,7 @@ func TestProcessorsTx(t *testing.T) {
}
session.Close()
p2 = &ProcessorsStruct{}
_, err = testEngine.Id(insertedId).Get(p2)
_, err = testEngine.ID(insertedId).Get(p2)
if err != nil {
t.Error(err)
panic(err)
@@ -813,7 +813,7 @@ func TestProcessorsTx(t *testing.T) {

p = &ProcessorsStruct{} // reset

_, err = session.Id(insertedId).Before(b4DeleteFunc).After(afterDeleteFunc).Delete(p)
_, err = session.ID(insertedId).Before(b4DeleteFunc).After(afterDeleteFunc).Delete(p)
if err != nil {
t.Error(err)
panic(err)
@@ -852,7 +852,7 @@ func TestProcessorsTx(t *testing.T) {
session.Close()

p2 = &ProcessorsStruct{}
_, err = testEngine.Id(insertedId).Get(p2)
_, err = testEngine.ID(insertedId).Get(p2)
if err != nil {
t.Error(err)
panic(err)
@@ -882,7 +882,7 @@ func TestProcessorsTx(t *testing.T) {

p = &ProcessorsStruct{}

_, err = session.Id(insertedId).Before(b4DeleteFunc).After(afterDeleteFunc).Delete(p)
_, err = session.ID(insertedId).Before(b4DeleteFunc).After(afterDeleteFunc).Delete(p)
if err != nil {
t.Error(err)
panic(err)


+ 5
- 36
rows.go View File

@@ -17,7 +17,6 @@ type Rows struct {
NoTypeCheck bool

session *Session
stmt *core.Stmt
rows *core.Rows
fields []string
beanType reflect.Type
@@ -29,8 +28,6 @@ func newRows(session *Session, bean interface{}) (*Rows, error) {
rows.session = session
rows.beanType = reflect.Indirect(reflect.ValueOf(bean)).Type()

defer rows.session.resetStatement()

var sqlStr string
var args []interface{}
var err error
@@ -53,32 +50,11 @@ func newRows(session *Session, bean interface{}) (*Rows, error) {
args = rows.session.statement.RawParams
}

for _, filter := range rows.session.engine.dialect.Filters() {
sqlStr = filter.Do(sqlStr, session.engine.dialect, rows.session.statement.RefTable)
}

rows.session.saveLastSQL(sqlStr, args...)
if rows.session.prepareStmt {
rows.stmt, err = rows.session.DB().Prepare(sqlStr)
if err != nil {
rows.lastError = err
rows.Close()
return nil, err
}

rows.rows, err = rows.stmt.Query(args...)
if err != nil {
rows.lastError = err
rows.Close()
return nil, err
}
} else {
rows.rows, err = rows.session.DB().Query(sqlStr, args...)
if err != nil {
rows.lastError = err
rows.Close()
return nil, err
}
rows.rows, err = rows.session.queryRows(sqlStr, args...)
if err != nil {
rows.lastError = err
rows.Close()
return nil, err
}

rows.fields, err = rows.rows.Columns()
@@ -142,17 +118,10 @@ func (rows *Rows) Close() error {
if rows.rows != nil {
rows.lastError = rows.rows.Close()
if rows.lastError != nil {
defer rows.stmt.Close()
return rows.lastError
}
}
if rows.stmt != nil {
rows.lastError = rows.stmt.Close()
}
} else {
if rows.stmt != nil {
defer rows.stmt.Close()
}
if rows.rows != nil {
defer rows.rows.Close()
}


+ 1
- 11
session.go View File

@@ -631,9 +631,7 @@ func (session *Session) slice2Bean(scanResults []interface{}, fields []string, f
// however, also need to consider adding a 'lazy' attribute to xorm tag which allow hasOne
// property to be fetched lazily
structInter := reflect.New(fieldValue.Type())
newsession := session.engine.NewSession()
defer newsession.Close()
has, err := newsession.ID(pk).NoCascade().Get(structInter.Interface())
has, err := session.ID(pk).NoCascade().get(structInter.Interface())
if err != nil {
return nil, err
}
@@ -777,14 +775,6 @@ func (session *Session) slice2Bean(scanResults []interface{}, fields []string, f
return pk, nil
}

func (session *Session) queryPreprocess(sqlStr *string, paramStr ...interface{}) {
for _, filter := range session.engine.dialect.Filters() {
*sqlStr = filter.Do(*sqlStr, session.engine.dialect, session.statement.RefTable)
}

session.saveLastSQL(*sqlStr, paramStr...)
}

// saveLastSQL stores executed query information
func (session *Session) saveLastSQL(sql string, args ...interface{}) {
session.lastSQL = sql


+ 1
- 1
session_cols_test.go View File

@@ -31,7 +31,7 @@ func TestSetExpr(t *testing.T) {
if testEngine.dialect.DBType() == core.MSSQL {
not = "~"
}
cnt, err = testEngine.SetExpr("show", not+" `show`").Id(1).Update(new(User))
cnt, err = testEngine.SetExpr("show", not+" `show`").ID(1).Update(new(User))
assert.NoError(t, err)
assert.EqualValues(t, 1, cnt)
}


+ 1
- 1
session_cond_test.go View File

@@ -227,7 +227,7 @@ func TestIn(t *testing.T) {
}

user := new(Userinfo)
has, err := testEngine.Id(ids[0]).Get(user)
has, err := testEngine.ID(ids[0]).Get(user)
if err != nil {
t.Error(err)
panic(err)


+ 2
- 6
session_convert.go View File

@@ -227,9 +227,7 @@ func (session *Session) bytes2Value(col *core.Column, fieldValue *reflect.Value,
// however, also need to consider adding a 'lazy' attribute to xorm tag which allow hasOne
// property to be fetched lazily
structInter := reflect.New(fieldValue.Type())
newsession := session.engine.NewSession()
defer newsession.Close()
has, err := newsession.Id(pk).NoCascade().Get(structInter.Interface())
has, err := session.ID(pk).NoCascade().get(structInter.Interface())
if err != nil {
return err
}
@@ -510,9 +508,7 @@ func (session *Session) bytes2Value(col *core.Column, fieldValue *reflect.Value,
// !nashtsai! TODO for hasOne relationship, it's preferred to use join query for eager fetch
// however, also need to consider adding a 'lazy' attribute to xorm tag which allow hasOne
// property to be fetched lazily
newsession := session.engine.NewSession()
defer newsession.Close()
has, err := newsession.Id(pk).NoCascade().Get(structInter.Interface())
has, err := session.ID(pk).NoCascade().get(structInter.Interface())
if err != nil {
return err
}


+ 1
- 2
session_delete.go View File

@@ -31,7 +31,7 @@ func (session *Session) cacheDelete(sqlStr string, args ...interface{}) error {
tableName := session.statement.TableName()
ids, err := core.GetCacheSql(cacher, tableName, newsql, args)
if err != nil {
resultsSlice, err := session.query(newsql, args...)
resultsSlice, err := session.queryBytes(newsql, args...)
if err != nil {
return err
}
@@ -78,7 +78,6 @@ func (session *Session) cacheDelete(sqlStr string, args ...interface{}) error {

// Delete records, bean's non-empty fields are conditions
func (session *Session) Delete(bean interface{}) (int64, error) {
defer session.resetStatement()
if session.isAutoClose {
defer session.Close()
}


+ 9
- 9
session_delete_test.go View File

@@ -32,7 +32,7 @@ func TestDelete(t *testing.T) {

user.Uid = 0
user.IsMan = true
has, err := testEngine.Id(1).Get(&user)
has, err := testEngine.ID(1).Get(&user)
assert.NoError(t, err)
assert.False(t, has)

@@ -46,7 +46,7 @@ func TestDelete(t *testing.T) {

user.Uid = 0
user.IsMan = true
has, err = testEngine.Id(2).Get(&user)
has, err = testEngine.ID(2).Get(&user)
assert.NoError(t, err)
assert.False(t, has)
}
@@ -82,16 +82,16 @@ func TestDeleted(t *testing.T) {

// Test normal Get()
record1 := &Deleted{}
has, err := testEngine.Id(1).Get(record1)
has, err := testEngine.ID(1).Get(record1)
assert.NoError(t, err)
assert.True(t, has)

// Test Delete() with deleted
affected, err := testEngine.Id(1).Delete(&Deleted{})
affected, err := testEngine.ID(1).Delete(&Deleted{})
assert.NoError(t, err)
assert.EqualValues(t, 1, affected)

has, err = testEngine.Id(1).Get(&Deleted{})
has, err = testEngine.ID(1).Get(&Deleted{})
assert.NoError(t, err)
assert.False(t, has)

@@ -101,17 +101,17 @@ func TestDeleted(t *testing.T) {
assert.EqualValues(t, 2, len(records2))

// Test no rows affected after Delete() again.
affected, err = testEngine.Id(1).Delete(&Deleted{})
affected, err = testEngine.ID(1).Delete(&Deleted{})
assert.NoError(t, err)
assert.EqualValues(t, 0, affected)

// Deleted.DeletedAt must not be updated.
affected, err = testEngine.Id(2).Update(&Deleted{Name: "2", DeletedAt: time.Now()})
affected, err = testEngine.ID(2).Update(&Deleted{Name: "2", DeletedAt: time.Now()})
assert.NoError(t, err)
assert.EqualValues(t, 1, affected)

record2 := &Deleted{}
has, err = testEngine.Id(2).Get(record2)
has, err = testEngine.ID(2).Get(record2)
assert.NoError(t, err)
assert.True(t, record2.DeletedAt.IsZero())

@@ -122,7 +122,7 @@ func TestDeleted(t *testing.T) {
assert.EqualValues(t, 3, len(unscopedRecords1))

// Delete() must really delete a record with Unscoped()
affected, err = testEngine.Unscoped().Id(1).Delete(&Deleted{})
affected, err = testEngine.Unscoped().ID(1).Delete(&Deleted{})
assert.NoError(t, err)
assert.EqualValues(t, 1, affected)



+ 3
- 13
session_exist.go View File

@@ -10,12 +10,10 @@ import (
"reflect"

"github.com/go-xorm/builder"
"github.com/go-xorm/core"
)

// Exist returns true if the record exist otherwise return false
func (session *Session) Exist(bean ...interface{}) (bool, error) {
defer session.resetStatement()
if session.isAutoClose {
defer session.Close()
}
@@ -69,19 +67,11 @@ func (session *Session) Exist(bean ...interface{}) (bool, error) {
args = session.statement.RawParams
}

session.queryPreprocess(&sqlStr, args...)

var rawRows *core.Rows
if session.isAutoCommit {
_, rawRows, err = session.innerQuery(sqlStr, args...)
} else {
rawRows, err = session.tx.Query(sqlStr, args...)
}
rows, err := session.queryRows(sqlStr, args...)
if err != nil {
return false, err
}
defer rows.Close()

defer rawRows.Close()

return rawRows.Next(), nil
return rows.Next(), nil
}

+ 15
- 24
session_find.go View File

@@ -23,11 +23,13 @@ const (
// are conditions. beans could be []Struct, []*Struct, map[int64]Struct
// map[int64]*Struct
func (session *Session) Find(rowsSlicePtr interface{}, condiBean ...interface{}) error {
defer session.resetStatement()
if session.isAutoClose {
defer session.Close()
}
return session.find(rowsSlicePtr, condiBean...)
}

func (session *Session) find(rowsSlicePtr interface{}, condiBean ...interface{}) error {
sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
if sliceValue.Kind() != reflect.Slice && sliceValue.Kind() != reflect.Map {
return errors.New("needs a pointer to a slice or a map")
@@ -157,21 +159,13 @@ func (session *Session) Find(rowsSlicePtr interface{}, condiBean ...interface{})
}

func (session *Session) noCacheFind(table *core.Table, containerValue reflect.Value, sqlStr string, args ...interface{}) error {
var rawRows *core.Rows
var err error

session.queryPreprocess(&sqlStr, args...)
if session.isAutoCommit {
_, rawRows, err = session.innerQuery(sqlStr, args...)
} else {
rawRows, err = session.tx.Query(sqlStr, args...)
}
rows, err := session.queryRows(sqlStr, args...)
if err != nil {
return err
}
defer rawRows.Close()
defer rows.Close()

fields, err := rawRows.Columns()
fields, err := rows.Columns()
if err != nil {
return err
}
@@ -245,20 +239,20 @@ func (session *Session) noCacheFind(table *core.Table, containerValue reflect.Va
if err != nil {
return err
}
return session.rows2Beans(rawRows, fields, len(fields), tb, newElemFunc, containerValueSetFunc)
return session.rows2Beans(rows, fields, len(fields), tb, newElemFunc, containerValueSetFunc)
}

for rawRows.Next() {
for rows.Next() {
var newValue = newElemFunc(fields)
bean := newValue.Interface()

switch elemType.Kind() {
case reflect.Slice:
err = rawRows.ScanSlice(bean)
err = rows.ScanSlice(bean)
case reflect.Map:
err = rawRows.ScanMap(bean)
err = rows.ScanMap(bean)
default:
err = rawRows.Scan(bean)
err = rows.Scan(bean)
}

if err != nil {
@@ -304,7 +298,7 @@ func (session *Session) cacheFind(t reflect.Type, sqlStr string, rowsSlicePtr in
cacher := session.engine.getCacher2(table)
ids, err := core.GetCacheSql(cacher, tableName, newsql, args)
if err != nil {
rows, err := session.DB().Query(newsql, args...)
rows, err := session.NoCache().queryRows(newsql, args...)
if err != nil {
return err
}
@@ -376,9 +370,6 @@ func (session *Session) cacheFind(t reflect.Type, sqlStr string, rowsSlicePtr in
}

if len(ides) > 0 {
newSession := session.engine.NewSession()
defer newSession.Close()

slices := reflect.New(reflect.SliceOf(t))
beans := slices.Interface()

@@ -388,18 +379,18 @@ func (session *Session) cacheFind(t reflect.Type, sqlStr string, rowsSlicePtr in
ff = append(ff, ie[0])
}

newSession.In("`"+table.PrimaryKeys[0]+"`", ff...)
session.In("`"+table.PrimaryKeys[0]+"`", ff...)
} else {
for _, ie := range ides {
cond := builder.NewCond()
for i, name := range table.PrimaryKeys {
cond = cond.And(builder.Eq{"`" + name + "`": ie[i]})
}
newSession.Or(cond)
session.Or(cond)
}
}

err = newSession.NoCache().Find(beans)
err = session.NoCache().find(beans)
if err != nil {
return err
}


+ 15
- 21
session_get.go View File

@@ -15,11 +15,13 @@ import (
// Get retrieve one record from database, bean's non-empty fields
// will be as conditions
func (session *Session) Get(bean interface{}) (bool, error) {
defer session.resetStatement()
if session.isAutoClose {
defer session.Close()
}
return session.get(bean)
}

func (session *Session) get(bean interface{}) (bool, error) {
beanValue := reflect.ValueOf(bean)
if beanValue.Kind() != reflect.Ptr {
return false, errors.New("needs a pointer to a value")
@@ -65,30 +67,21 @@ func (session *Session) Get(bean interface{}) (bool, error) {
}

func (session *Session) nocacheGet(beanKind reflect.Kind, bean interface{}, sqlStr string, args ...interface{}) (bool, error) {
session.queryPreprocess(&sqlStr, args...)

var rawRows *core.Rows
var err error
if session.isAutoCommit {
_, rawRows, err = session.innerQuery(sqlStr, args...)
} else {
rawRows, err = session.tx.Query(sqlStr, args...)
}
rows, err := session.queryRows(sqlStr, args...)
if err != nil {
return false, err
}
defer rows.Close()

defer rawRows.Close()

if !rawRows.Next() {
if !rows.Next() {
return false, nil
}

switch beanKind {
case reflect.Struct:
fields, err := rawRows.Columns()
fields, err := rows.Columns()
if err != nil {
// WARN: Alougth rawRows return true, but get fields failed
// WARN: Alougth rows return true, but get fields failed
return true, err
}
dataStruct := rValue(bean)
@@ -96,19 +89,20 @@ func (session *Session) nocacheGet(beanKind reflect.Kind, bean interface{}, sqlS
return false, err
}

scanResults, err := session.row2Slice(rawRows, fields, len(fields), bean)
scanResults, err := session.row2Slice(rows, fields, len(fields), bean)
if err != nil {
return false, err
}
rawRows.Close()
// close it before covert data
rows.Close()

_, err = session.slice2Bean(scanResults, fields, len(fields), bean, &dataStruct, session.statement.RefTable)
case reflect.Slice:
err = rawRows.ScanSlice(bean)
err = rows.ScanSlice(bean)
case reflect.Map:
err = rawRows.ScanMap(bean)
err = rows.ScanMap(bean)
default:
err = rawRows.Scan(bean)
err = rows.Scan(bean)
}

return true, err
@@ -135,7 +129,7 @@ func (session *Session) cacheGet(bean interface{}, sqlStr string, args ...interf
table := session.statement.RefTable
if err != nil {
var res = make([]string, len(table.PrimaryKeys))
rows, err := session.DB().Query(newsql, args...)
rows, err := session.NoCache().queryRows(newsql, args...)
if err != nil {
return false, err
}


+ 2
- 5
session_insert.go View File

@@ -22,7 +22,6 @@ func (session *Session) Insert(beans ...interface{}) (int64, error) {
if session.isAutoClose {
defer session.Close()
}
defer session.resetStatement()

for _, bean := range beans {
sliceValue := reflect.Indirect(reflect.ValueOf(bean))
@@ -280,7 +279,6 @@ func (session *Session) innerInsertMulti(rowsSlicePtr interface{}) (int64, error

// InsertMulti insert multiple records
func (session *Session) InsertMulti(rowsSlicePtr interface{}) (int64, error) {
defer session.resetStatement()
if session.isAutoClose {
defer session.Close()
}
@@ -395,7 +393,7 @@ func (session *Session) innerInsert(bean interface{}) (int64, error) {
// for postgres, many of them didn't implement lastInsertId, so we should
// implemented it ourself.
if session.engine.dialect.DBType() == core.ORACLE && len(table.AutoIncrement) > 0 {
res, err := session.query("select seq_atable.currval from dual", args...)
res, err := session.queryBytes("select seq_atable.currval from dual", args...)
if err != nil {
return 0, err
}
@@ -440,7 +438,7 @@ func (session *Session) innerInsert(bean interface{}) (int64, error) {
} else if session.engine.dialect.DBType() == core.POSTGRES && len(table.AutoIncrement) > 0 {
//assert table.AutoIncrement != ""
sqlStr = sqlStr + " RETURNING " + session.engine.Quote(table.AutoIncrement)
res, err := session.query(sqlStr, args...)
res, err := session.queryBytes(sqlStr, args...)

if err != nil {
return 0, err
@@ -532,7 +530,6 @@ func (session *Session) innerInsert(bean interface{}) (int64, error) {
// The in parameter bean must a struct or a point to struct. The return
// parameter is inserted and error
func (session *Session) InsertOne(bean interface{}) (int64, error) {
defer session.resetStatement()
if session.isAutoClose {
defer session.Close()
}


+ 4
- 0
session_iterate.go View File

@@ -19,6 +19,10 @@ func (session *Session) Rows(bean interface{}) (*Rows, error) {
// are conditions. beans could be []Struct, []*Struct, map[int64]Struct
// map[int64]*Struct
func (session *Session) Iterate(bean interface{}, fun IterFunc) error {
if session.isAutoClose {
defer session.Close()
}

rows, err := session.Rows(bean)
if err != nil {
return err


+ 22
- 22
session_pk_test.go View File

@@ -127,7 +127,7 @@ func TestIntId(t *testing.T) {
panic(err)
}

cnt, err = testEngine.Id(bean.Id).Delete(&IntId{})
cnt, err = testEngine.ID(bean.Id).Delete(&IntId{})
if err != nil {
t.Error(err)
panic(err)
@@ -202,7 +202,7 @@ func TestInt16Id(t *testing.T) {
panic(err)
}

cnt, err = testEngine.Id(bean.Id).Delete(&Int16Id{})
cnt, err = testEngine.ID(bean.Id).Delete(&Int16Id{})
if err != nil {
t.Error(err)
panic(err)
@@ -277,7 +277,7 @@ func TestInt32Id(t *testing.T) {
panic(err)
}

cnt, err = testEngine.Id(bean.Id).Delete(&Int32Id{})
cnt, err = testEngine.ID(bean.Id).Delete(&Int32Id{})
if err != nil {
t.Error(err)
panic(err)
@@ -366,7 +366,7 @@ func TestUintId(t *testing.T) {
panic(err)
}

cnt, err = testEngine.Id(bean.Id).Delete(&UintId{})
cnt, err = testEngine.ID(bean.Id).Delete(&UintId{})
if err != nil {
t.Error(err)
panic(err)
@@ -441,7 +441,7 @@ func TestUint16Id(t *testing.T) {
panic(err)
}

cnt, err = testEngine.Id(bean.Id).Delete(&Uint16Id{})
cnt, err = testEngine.ID(bean.Id).Delete(&Uint16Id{})
if err != nil {
t.Error(err)
panic(err)
@@ -516,7 +516,7 @@ func TestUint32Id(t *testing.T) {
panic(err)
}

cnt, err = testEngine.Id(bean.Id).Delete(&Uint32Id{})
cnt, err = testEngine.ID(bean.Id).Delete(&Uint32Id{})
if err != nil {
t.Error(err)
panic(err)
@@ -604,7 +604,7 @@ func TestUint64Id(t *testing.T) {
panic(errors.New("should be equal"))
}

cnt, err = testEngine.Id(bean.Id).Delete(&Uint64Id{})
cnt, err = testEngine.ID(bean.Id).Delete(&Uint64Id{})
if err != nil {
t.Error(err)
panic(err)
@@ -679,7 +679,7 @@ func TestStringPK(t *testing.T) {
panic(err)
}

cnt, err = testEngine.Id(bean.Id).Delete(&StringPK{})
cnt, err = testEngine.ID(bean.Id).Delete(&StringPK{})
if err != nil {
t.Error(err)
panic(err)
@@ -725,7 +725,7 @@ func TestCompositeKey(t *testing.T) {
}

var compositeKeyVal CompositeKey
has, err := testEngine.Id(core.PK{11, 22}).Get(&compositeKeyVal)
has, err := testEngine.ID(core.PK{11, 22}).Get(&compositeKeyVal)
if err != nil {
t.Error(err)
} else if !has {
@@ -734,7 +734,7 @@ func TestCompositeKey(t *testing.T) {

var compositeKeyVal2 CompositeKey
// test passing PK ptr, this test seem failed withCache
has, err = testEngine.Id(&core.PK{11, 22}).Get(&compositeKeyVal2)
has, err = testEngine.ID(&core.PK{11, 22}).Get(&compositeKeyVal2)
if err != nil {
t.Error(err)
} else if !has {
@@ -781,14 +781,14 @@ func TestCompositeKey(t *testing.T) {
}

compositeKeyVal = CompositeKey{UpdateStr: "test1"}
cnt, err = testEngine.Id(core.PK{11, 22}).Update(&compositeKeyVal)
cnt, err = testEngine.ID(core.PK{11, 22}).Update(&compositeKeyVal)
if err != nil {
t.Error(err)
} else if cnt != 1 {
t.Error(errors.New("can't update CompositeKey{11, 22}"))
}

cnt, err = testEngine.Id(core.PK{11, 22}).Delete(&CompositeKey{})
cnt, err = testEngine.ID(core.PK{11, 22}).Delete(&CompositeKey{})
if err != nil {
t.Error(err)
} else if cnt != 1 {
@@ -832,7 +832,7 @@ func TestCompositeKey2(t *testing.T) {
}

var user User
has, err := testEngine.Id(core.PK{"11", 22}).Get(&user)
has, err := testEngine.ID(core.PK{"11", 22}).Get(&user)
if err != nil {
t.Error(err)
} else if !has {
@@ -840,7 +840,7 @@ func TestCompositeKey2(t *testing.T) {
}

// test passing PK ptr, this test seem failed withCache
has, err = testEngine.Id(&core.PK{"11", 22}).Get(&user)
has, err = testEngine.ID(&core.PK{"11", 22}).Get(&user)
if err != nil {
t.Error(err)
} else if !has {
@@ -848,14 +848,14 @@ func TestCompositeKey2(t *testing.T) {
}

user = User{NickName: "test1"}
cnt, err = testEngine.Id(core.PK{"11", 22}).Update(&user)
cnt, err = testEngine.ID(core.PK{"11", 22}).Update(&user)
if err != nil {
t.Error(err)
} else if cnt != 1 {
t.Error(errors.New("can't update User{11, 22}"))
}

cnt, err = testEngine.Id(core.PK{"11", 22}).Delete(&User{})
cnt, err = testEngine.ID(core.PK{"11", 22}).Delete(&User{})
if err != nil {
t.Error(err)
} else if cnt != 1 {
@@ -900,7 +900,7 @@ func TestCompositeKey3(t *testing.T) {
}

var user UserPK2
has, err := testEngine.Id(core.PK{"11", 22}).Get(&user)
has, err := testEngine.ID(core.PK{"11", 22}).Get(&user)
if err != nil {
t.Error(err)
} else if !has {
@@ -908,7 +908,7 @@ func TestCompositeKey3(t *testing.T) {
}

// test passing PK ptr, this test seem failed withCache
has, err = testEngine.Id(&core.PK{"11", 22}).Get(&user)
has, err = testEngine.ID(&core.PK{"11", 22}).Get(&user)
if err != nil {
t.Error(err)
} else if !has {
@@ -916,14 +916,14 @@ func TestCompositeKey3(t *testing.T) {
}

user = UserPK2{NickName: "test1"}
cnt, err = testEngine.Id(core.PK{"11", 22}).Update(&user)
cnt, err = testEngine.ID(core.PK{"11", 22}).Update(&user)
if err != nil {
t.Error(err)
} else if cnt != 1 {
t.Error(errors.New("can't update User{11, 22}"))
}

cnt, err = testEngine.Id(core.PK{"11", 22}).Delete(&UserPK2{})
cnt, err = testEngine.ID(core.PK{"11", 22}).Delete(&UserPK2{})
if err != nil {
t.Error(err)
} else if cnt != 1 {
@@ -1007,7 +1007,7 @@ func TestMyIntId(t *testing.T) {
panic(errors.New("should be equal"))
}

cnt, err = testEngine.Id(bean.ID).Delete(&MyIntPK{})
cnt, err = testEngine.ID(bean.ID).Delete(&MyIntPK{})
if err != nil {
t.Error(err)
panic(err)
@@ -1095,7 +1095,7 @@ func TestMyStringId(t *testing.T) {
panic(errors.New("should be equal"))
}

cnt, err = testEngine.Id(bean.ID).Delete(&MyStringPK{})
cnt, err = testEngine.ID(bean.ID).Delete(&MyStringPK{})
if err != nil {
t.Error(err)
panic(err)


+ 108
- 108
session_raw.go View File

@@ -14,55 +14,6 @@ import (
"github.com/go-xorm/core"
)

func (session *Session) query(sqlStr string, paramStr ...interface{}) ([]map[string][]byte, error) {
session.queryPreprocess(&sqlStr, paramStr...)

if session.isAutoCommit {
return session.innerQuery2(sqlStr, paramStr...)
}
return session.txQuery(session.tx, sqlStr, paramStr...)
}

func (session *Session) txQuery(tx *core.Tx, sqlStr string, params ...interface{}) ([]map[string][]byte, error) {
rows, err := tx.Query(sqlStr, params...)
if err != nil {
return nil, err
}
defer rows.Close()

return rows2maps(rows)
}

func (session *Session) innerQuery(sqlStr string, params ...interface{}) (*core.Stmt, *core.Rows, error) {
var callback func() (*core.Stmt, *core.Rows, error)
if session.prepareStmt {
callback = func() (*core.Stmt, *core.Rows, error) {
stmt, err := session.doPrepare(sqlStr)
if err != nil {
return nil, nil, err
}
rows, err := stmt.Query(params...)
if err != nil {
return nil, nil, err
}
return stmt, rows, nil
}
} else {
callback = func() (*core.Stmt, *core.Rows, error) {
rows, err := session.DB().Query(sqlStr, params...)
if err != nil {
return nil, nil, err
}
return nil, rows, err
}
}
stmt, rows, err := session.engine.logSQLQueryTime(sqlStr, params, callback)
if err != nil {
return nil, nil, err
}
return stmt, rows, nil
}

func rows2maps(rows *core.Rows) (resultsSlice []map[string][]byte, err error) {
fields, err := rows.Columns()
if err != nil {
@@ -117,27 +68,6 @@ func row2map(rows *core.Rows, fields []string) (resultsMap map[string][]byte, er
return result, nil
}

func (session *Session) innerQuery2(sqlStr string, params ...interface{}) ([]map[string][]byte, error) {
_, rows, err := session.innerQuery(sqlStr, params...)
if rows != nil {
defer rows.Close()
}
if err != nil {
return nil, err
}
return rows2maps(rows)
}

// Query runs a raw sql and return records as []map[string][]byte
func (session *Session) Query(sqlStr string, paramStr ...interface{}) ([]map[string][]byte, error) {
defer session.resetStatement()
if session.isAutoClose {
defer session.Close()
}

return session.query(sqlStr, paramStr...)
}

func rows2Strings(rows *core.Rows) (resultsSlice []map[string]string, err error) {
fields, err := rows.Columns()
if err != nil {
@@ -234,42 +164,136 @@ func row2mapStr(rows *core.Rows, fields []string) (resultsMap map[string]string,
return result, nil
}

func txQuery2(tx *core.Tx, sqlStr string, params ...interface{}) ([]map[string]string, error) {
rows, err := tx.Query(sqlStr, params...)
func (session *Session) queryPreprocess(sqlStr *string, paramStr ...interface{}) {
for _, filter := range session.engine.dialect.Filters() {
*sqlStr = filter.Do(*sqlStr, session.engine.dialect, session.statement.RefTable)
}

session.lastSQL = *sqlStr
session.lastSQLArgs = paramStr
}

func (session *Session) queryRows(sqlStr string, args ...interface{}) (*core.Rows, error) {
defer session.resetStatement()

session.queryPreprocess(&sqlStr, args...)

if session.engine.showSQL {
if session.engine.showExecTime {
b4ExecTime := time.Now()
defer func() {
execDuration := time.Since(b4ExecTime)
if len(args) > 0 {
session.engine.logger.Infof("[SQL] %s %#v - took: %v", sqlStr, args, execDuration)
} else {
session.engine.logger.Infof("[SQL] %s - took: %v", sqlStr, execDuration)
}
}()
} else {
if len(args) > 0 {
session.engine.logger.Infof("[SQL] %v %#v", sqlStr, args)
} else {
session.engine.logger.Infof("[SQL] %v", sqlStr)
}
}
}

if session.isAutoCommit {
if session.prepareStmt {
// don't clear stmt since session will cache them
stmt, err := session.doPrepare(sqlStr)
if err != nil {
return nil, err
}

rows, err := stmt.Query(args...)
if err != nil {
return nil, err
}
return rows, nil
}

rows, err := session.DB().Query(sqlStr, args...)
if err != nil {
return nil, err
}
return rows, nil
}

rows, err := session.tx.Query(sqlStr, args...)
if err != nil {
return nil, err
}
defer rows.Close()
return rows, nil
}

return rows2Strings(rows)
func (session *Session) queryRow(sqlStr string, args ...interface{}) *core.Row {
return core.NewRow(session.queryRows(sqlStr, args...))
}

func query2(db *core.DB, sqlStr string, params ...interface{}) ([]map[string]string, error) {
rows, err := db.Query(sqlStr, params...)
func (session *Session) queryBytes(sqlStr string, args ...interface{}) ([]map[string][]byte, error) {
rows, err := session.queryRows(sqlStr, args...)
if err != nil {
return nil, err
}
defer rows.Close()
return rows2Strings(rows)

return rows2maps(rows)
}

// Query runs a raw sql and return records as []map[string][]byte
func (session *Session) Query(sqlStr string, args ...interface{}) ([]map[string][]byte, error) {
if session.isAutoClose {
defer session.Close()
}

return session.queryBytes(sqlStr, args...)
}

// QueryString runs a raw sql and return records as []map[string]string
func (session *Session) QueryString(sqlStr string, args ...interface{}) ([]map[string]string, error) {
defer session.resetStatement()
if session.isAutoClose {
defer session.Close()
}

rows, err := session.queryRows(sqlStr, args...)
if err != nil {
return nil, err
}
defer rows.Close()

return rows2Strings(rows)
}

func (session *Session) exec(sqlStr string, args ...interface{}) (sql.Result, error) {
defer session.resetStatement()

session.queryPreprocess(&sqlStr, args...)

if session.isAutoCommit {
return query2(session.DB(), sqlStr, args...)
if session.engine.showSQL {
if session.engine.showExecTime {
b4ExecTime := time.Now()
defer func() {
execDuration := time.Since(b4ExecTime)
if len(args) > 0 {
session.engine.logger.Infof("[SQL] %s %#v - took: %v", sqlStr, args, execDuration)
} else {
session.engine.logger.Infof("[SQL] %s - took: %v", sqlStr, execDuration)
}
}()
} else {
if len(args) > 0 {
session.engine.logger.Infof("[SQL] %v %#v", sqlStr, args)
} else {
session.engine.logger.Infof("[SQL] %v", sqlStr)
}
}
}

if !session.isAutoCommit {
return session.tx.Exec(sqlStr, args...)
}
return txQuery2(session.tx, sqlStr, args...)
}

// Execute sql
func (session *Session) innerExec(sqlStr string, args ...interface{}) (sql.Result, error) {
if session.prepareStmt {
stmt, err := session.doPrepare(sqlStr)
if err != nil {
@@ -286,32 +310,8 @@ func (session *Session) innerExec(sqlStr string, args ...interface{}) (sql.Resul
return session.DB().Exec(sqlStr, args...)
}

func (session *Session) exec(sqlStr string, args ...interface{}) (sql.Result, error) {
for _, filter := range session.engine.dialect.Filters() {
// TODO: for table name, it's no need to RefTable
sqlStr = filter.Do(sqlStr, session.engine.dialect, session.statement.RefTable)
}

session.saveLastSQL(sqlStr, args...)

return session.engine.logSQLExecutionTime(sqlStr, args, func() (sql.Result, error) {
if session.isAutoCommit {
// FIXME: oci8 can not auto commit (github.com/mattn/go-oci8)
if session.engine.dialect.DBType() == core.ORACLE {
session.Begin()
r, err := session.tx.Exec(sqlStr, args...)
session.Commit()
return r, err
}
return session.innerExec(sqlStr, args...)
}
return session.tx.Exec(sqlStr, args...)
})
}

// Exec raw sql
func (session *Session) Exec(sqlStr string, args ...interface{}) (sql.Result, error) {
defer session.resetStatement()
if session.isAutoClose {
defer session.Close()
}


+ 3
- 22
session_schema.go View File

@@ -16,7 +16,6 @@ import (

// Ping test if database is ok
func (session *Session) Ping() error {
defer session.resetStatement()
if session.isAutoClose {
defer session.Close()
}
@@ -35,7 +34,6 @@ func (session *Session) CreateTable(bean interface{}) error {
}

func (session *Session) createTable(bean interface{}) error {
defer session.resetStatement()
v := rValue(bean)
if err := session.statement.setRefValue(v); err != nil {
return err
@@ -56,7 +54,6 @@ func (session *Session) CreateIndexes(bean interface{}) error {
}

func (session *Session) createIndexes(bean interface{}) error {
defer session.resetStatement()
v := rValue(bean)
if err := session.statement.setRefValue(v); err != nil {
return err
@@ -81,7 +78,6 @@ func (session *Session) CreateUniques(bean interface{}) error {
}

func (session *Session) createUniques(bean interface{}) error {
defer session.resetStatement()
v := rValue(bean)
if err := session.statement.setRefValue(v); err != nil {
return err
@@ -107,7 +103,6 @@ func (session *Session) DropIndexes(bean interface{}) error {
}

func (session *Session) dropIndexes(bean interface{}) error {
defer session.resetStatement()
v := rValue(bean)
if err := session.statement.setRefValue(v); err != nil {
return err
@@ -133,7 +128,6 @@ func (session *Session) DropTable(beanOrTableName interface{}) error {
}

func (session *Session) dropTable(beanOrTableName interface{}) error {
defer session.resetStatement()
tableName, err := session.engine.tableName(beanOrTableName)
if err != nil {
return err
@@ -142,7 +136,7 @@ func (session *Session) dropTable(beanOrTableName interface{}) error {
var needDrop = true
if !session.engine.dialect.SupportDropIfExists() {
sqlStr, args := session.engine.dialect.TableCheckSql(tableName)
results, err := session.query(sqlStr, args...)
results, err := session.queryBytes(sqlStr, args...)
if err != nil {
return err
}
@@ -172,9 +166,8 @@ func (session *Session) IsTableExist(beanOrTableName interface{}) (bool, error)
}

func (session *Session) isTableExist(tableName string) (bool, error) {
defer session.resetStatement()
sqlStr, args := session.engine.dialect.TableCheckSql(tableName)
results, err := session.query(sqlStr, args...)
results, err := session.queryBytes(sqlStr, args...)
return len(results) > 0, err
}

@@ -196,12 +189,9 @@ func (session *Session) IsTableEmpty(bean interface{}) (bool, error) {
}

func (session *Session) isTableEmpty(tableName string) (bool, error) {
defer session.resetStatement()

var total int64
sqlStr := fmt.Sprintf("select count(*) from %s", session.engine.Quote(tableName))
err := session.DB().QueryRow(sqlStr).Scan(&total)
session.saveLastSQL(sqlStr)
err := session.queryRow(sqlStr).Scan(&total)
if err != nil {
if err == sql.ErrNoRows {
err = nil
@@ -214,8 +204,6 @@ func (session *Session) isTableEmpty(tableName string) (bool, error) {

// find if index is exist according cols
func (session *Session) isIndexExist2(tableName string, cols []string, unique bool) (bool, error) {
defer session.resetStatement()

indexes, err := session.engine.dialect.GetIndexes(tableName)
if err != nil {
return false, err
@@ -233,8 +221,6 @@ func (session *Session) isIndexExist2(tableName string, cols []string, unique bo
}

func (session *Session) addColumn(colName string) error {
defer session.resetStatement()

col := session.statement.RefTable.GetColumn(colName)
sql, args := session.statement.genAddColumnStr(col)
_, err := session.exec(sql, args...)
@@ -242,18 +228,13 @@ func (session *Session) addColumn(colName string) error {
}

func (session *Session) addIndex(tableName, idxName string) error {
defer session.resetStatement()

index := session.statement.RefTable.Indexes[idxName]
sqlStr := session.engine.dialect.CreateIndexSql(tableName, index)

_, err := session.exec(sqlStr)
return err
}

func (session *Session) addUnique(tableName, uqeName string) error {
defer session.resetStatement()

index := session.statement.RefTable.Indexes[uqeName]
sqlStr := session.engine.dialect.CreateIndexSql(tableName, index)
_, err := session.exec(sqlStr)


+ 3
- 23
session_stats.go View File

@@ -13,7 +13,6 @@ import (
// Count counts the records. bean's non-empty fields
// are conditions.
func (session *Session) Count(bean ...interface{}) (int64, error) {
defer session.resetStatement()
if session.isAutoClose {
defer session.Close()
}
@@ -31,15 +30,8 @@ func (session *Session) Count(bean ...interface{}) (int64, error) {
args = session.statement.RawParams
}

session.queryPreprocess(&sqlStr, args...)

var total int64
if session.isAutoCommit {
err = session.DB().QueryRow(sqlStr, args...).Scan(&total)
} else {
err = session.tx.QueryRow(sqlStr, args...).Scan(&total)
}

err = session.queryRow(sqlStr, args...).Scan(&total)
if err == sql.ErrNoRows || err == nil {
return total, nil
}
@@ -49,7 +41,6 @@ func (session *Session) Count(bean ...interface{}) (int64, error) {

// sum call sum some column. bean's non-empty fields are conditions.
func (session *Session) sum(res interface{}, bean interface{}, columnNames ...string) error {
defer session.resetStatement()
if session.isAutoClose {
defer session.Close()
}
@@ -73,22 +64,11 @@ func (session *Session) sum(res interface{}, bean interface{}, columnNames ...st
args = session.statement.RawParams
}

session.queryPreprocess(&sqlStr, args...)

if isSlice {
if session.isAutoCommit {
err = session.DB().QueryRow(sqlStr, args...).ScanSlice(res)
} else {
err = session.tx.QueryRow(sqlStr, args...).ScanSlice(res)
}
err = session.queryRow(sqlStr, args...).ScanSlice(res)
} else {
if session.isAutoCommit {
err = session.DB().QueryRow(sqlStr, args...).Scan(res)
} else {
err = session.tx.QueryRow(sqlStr, args...).Scan(res)
}
err = session.queryRow(sqlStr, args...).Scan(res)
}

if err == sql.ErrNoRows || err == nil {
return nil
}


+ 2
- 4
session_update.go View File

@@ -45,7 +45,7 @@ func (session *Session) cacheUpdate(sqlStr string, args ...interface{}) error {
session.engine.logger.Debug("[cacheUpdate] get cache sql", newsql, args[nStart:])
ids, err := core.GetCacheSql(cacher, tableName, newsql, args[nStart:])
if err != nil {
rows, err := session.DB().Query(newsql, args[nStart:]...)
rows, err := session.NoCache().queryRows(newsql, args[nStart:]...)
if err != nil {
return err
}
@@ -144,7 +144,6 @@ func (session *Session) cacheUpdate(sqlStr string, args ...interface{}) error {
// You should call UseBool if you have bool to use.
// 2.float32 & float64 may be not inexact as conditions
func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int64, error) {
defer session.resetStatement()
if session.isAutoClose {
defer session.Close()
}
@@ -249,8 +248,7 @@ func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int6
}
}

st := session.statement
defer session.resetStatement()
st := &session.statement

var sqlStr string
var condArgs []interface{}


+ 36
- 36
session_update_test.go View File

@@ -298,7 +298,7 @@ func TestUpdate1(t *testing.T) {

// update by id
user := Userinfo{Username: "xxx", Height: 1.2}
cnt, err := testEngine.Id(ori.Uid).Update(&user)
cnt, err := testEngine.ID(ori.Uid).Update(&user)
if err != nil {
t.Error(err)
panic(err)
@@ -311,7 +311,7 @@ func TestUpdate1(t *testing.T) {
}

condi := Condi{"username": "zzz", "departname": ""}
cnt, err = testEngine.Table(&user).Id(ori.Uid).Update(&condi)
cnt, err = testEngine.Table(&user).ID(ori.Uid).Update(&condi)
if err != nil {
t.Error(err)
panic(err)
@@ -351,7 +351,7 @@ func TestUpdate1(t *testing.T) {
}
userID := user.Uid

has, err := testEngine.Id(userID).
has, err := testEngine.ID(userID).
And("username = ?", user.Username).
And("height = ?", user.Height).
And("departname = ?", "").
@@ -369,7 +369,7 @@ func TestUpdate1(t *testing.T) {
}

updatedUser := &Userinfo{Username: "null data"}
cnt, err = testEngine.Id(userID).
cnt, err = testEngine.ID(userID).
Nullable("height", "departname", "is_man", "created").
Update(updatedUser)
if err != nil {
@@ -382,7 +382,7 @@ func TestUpdate1(t *testing.T) {
panic(err)
}

has, err = testEngine.Id(userID).
has, err = testEngine.ID(userID).
And("username = ?", updatedUser.Username).
And("height IS NULL").
And("departname IS NULL").
@@ -400,7 +400,7 @@ func TestUpdate1(t *testing.T) {
panic(err)
}

cnt, err = testEngine.Id(userID).Delete(&Userinfo{})
cnt, err = testEngine.ID(userID).Delete(&Userinfo{})
if err != nil {
t.Error(err)
panic(err)
@@ -445,7 +445,7 @@ func TestUpdate1(t *testing.T) {
panic(err)
}

cnt, err = testEngine.Id(a.Id).Update(&Article{Name: "6"})
cnt, err = testEngine.ID(a.Id).Update(&Article{Name: "6"})
if err != nil {
t.Error(err)
panic(err)
@@ -474,14 +474,14 @@ func TestUpdate1(t *testing.T) {
}

col2 := &UpdateAllCols{col1.Id, true, "", nil}
_, err = testEngine.Id(col2.Id).AllCols().Update(col2)
_, err = testEngine.ID(col2.Id).AllCols().Update(col2)
if err != nil {
t.Error(err)
panic(err)
}

col3 := &UpdateAllCols{}
has, err = testEngine.Id(col2.Id).Get(col3)
has, err = testEngine.ID(col2.Id).Get(col3)
if err != nil {
t.Error(err)
panic(err)
@@ -519,14 +519,14 @@ func TestUpdate1(t *testing.T) {
col2 := &UpdateMustCols{col1.Id, true, ""}
boolStr := testEngine.ColumnMapper.Obj2Table("Bool")
stringStr := testEngine.ColumnMapper.Obj2Table("String")
_, err = testEngine.Id(col2.Id).MustCols(boolStr, stringStr).Update(col2)
_, err = testEngine.ID(col2.Id).MustCols(boolStr, stringStr).Update(col2)
if err != nil {
t.Error(err)
panic(err)
}

col3 := &UpdateMustCols{}
has, err := testEngine.Id(col2.Id).Get(col3)
has, err := testEngine.ID(col2.Id).Get(col3)
if err != nil {
t.Error(err)
panic(err)
@@ -561,27 +561,27 @@ func TestUpdateIncrDecr(t *testing.T) {

colName := testEngine.ColumnMapper.Obj2Table("Cnt")

cnt, err := testEngine.Id(col1.Id).Incr(colName).Update(col1)
cnt, err := testEngine.ID(col1.Id).Incr(colName).Update(col1)
assert.NoError(t, err)
assert.EqualValues(t, 1, cnt)

newCol := new(UpdateIncr)
has, err := testEngine.Id(col1.Id).Get(newCol)
has, err := testEngine.ID(col1.Id).Get(newCol)
assert.NoError(t, err)
assert.True(t, has)
assert.EqualValues(t, 1, newCol.Cnt)

cnt, err = testEngine.Id(col1.Id).Decr(colName).Update(col1)
cnt, err = testEngine.ID(col1.Id).Decr(colName).Update(col1)
assert.NoError(t, err)
assert.EqualValues(t, 1, cnt)

newCol = new(UpdateIncr)
has, err = testEngine.Id(col1.Id).Get(newCol)
has, err = testEngine.ID(col1.Id).Get(newCol)
assert.NoError(t, err)
assert.True(t, has)
assert.EqualValues(t, 0, newCol.Cnt)

cnt, err = testEngine.Id(col1.Id).Cols(colName).Incr(colName).Update(col1)
cnt, err = testEngine.ID(col1.Id).Cols(colName).Incr(colName).Update(col1)
assert.NoError(t, err)
assert.EqualValues(t, 1, cnt)
}
@@ -626,12 +626,12 @@ func TestUpdateUpdated(t *testing.T) {
}

ci := &UpdatedUpdate{}
_, err = testEngine.Id(1).Update(ci)
_, err = testEngine.ID(1).Update(ci)
if err != nil {
t.Fatal(err)
}

has, err := testEngine.Id(1).Get(di)
has, err := testEngine.ID(1).Get(di)
if err != nil {
t.Fatal(err)
}
@@ -654,11 +654,11 @@ func TestUpdateUpdated(t *testing.T) {
t.Fatal(err)
}
ci2 := &UpdatedUpdate2{}
_, err = testEngine.Id(1).Update(ci2)
_, err = testEngine.ID(1).Update(ci2)
if err != nil {
t.Fatal(err)
}
has, err = testEngine.Id(1).Get(di2)
has, err = testEngine.ID(1).Get(di2)
if err != nil {
t.Fatal(err)
}
@@ -681,12 +681,12 @@ func TestUpdateUpdated(t *testing.T) {
t.Fatal(err)
}
ci3 := &UpdatedUpdate3{}
_, err = testEngine.Id(1).Update(ci3)
_, err = testEngine.ID(1).Update(ci3)
if err != nil {
t.Fatal(err)
}

has, err = testEngine.Id(1).Get(di3)
has, err = testEngine.ID(1).Get(di3)
if err != nil {
t.Fatal(err)
}
@@ -710,12 +710,12 @@ func TestUpdateUpdated(t *testing.T) {
}

ci4 := &UpdatedUpdate4{}
_, err = testEngine.Id(1).Update(ci4)
_, err = testEngine.ID(1).Update(ci4)
if err != nil {
t.Fatal(err)
}

has, err = testEngine.Id(1).Get(di4)
has, err = testEngine.ID(1).Get(di4)
if err != nil {
t.Fatal(err)
}
@@ -738,12 +738,12 @@ func TestUpdateUpdated(t *testing.T) {
t.Fatal(err)
}
ci5 := &UpdatedUpdate5{}
_, err = testEngine.Id(1).Update(ci5)
_, err = testEngine.ID(1).Update(ci5)
if err != nil {
t.Fatal(err)
}

has, err = testEngine.Id(1).Get(di5)
has, err = testEngine.ID(1).Get(di5)
if err != nil {
t.Fatal(err)
}
@@ -796,7 +796,7 @@ func TestUpdateSameMapper(t *testing.T) {
}
// update by id
user := Userinfo{Username: "xxx", Height: 1.2}
cnt, err := testEngine.Id(ori.Uid).Update(&user)
cnt, err := testEngine.ID(ori.Uid).Update(&user)
if err != nil {
t.Error(err)
panic(err)
@@ -809,7 +809,7 @@ func TestUpdateSameMapper(t *testing.T) {
}

condi := Condi{"Username": "zzz", "Departname": ""}
cnt, err = testEngine.Table(&user).Id(ori.Uid).Update(&condi)
cnt, err = testEngine.Table(&user).ID(ori.Uid).Update(&condi)
if err != nil {
t.Error(err)
panic(err)
@@ -874,7 +874,7 @@ func TestUpdateSameMapper(t *testing.T) {
panic(err)
}

cnt, err = testEngine.Id(a.Id).Update(&Article{Name: "6"})
cnt, err = testEngine.ID(a.Id).Update(&Article{Name: "6"})
if err != nil {
t.Error(err)
panic(err)
@@ -901,14 +901,14 @@ func TestUpdateSameMapper(t *testing.T) {
}

col2 := &UpdateAllCols{col1.Id, true, "", nil}
_, err = testEngine.Id(col2.Id).AllCols().Update(col2)
_, err = testEngine.ID(col2.Id).AllCols().Update(col2)
if err != nil {
t.Error(err)
panic(err)
}

col3 := &UpdateAllCols{}
has, err = testEngine.Id(col2.Id).Get(col3)
has, err = testEngine.ID(col2.Id).Get(col3)
if err != nil {
t.Error(err)
panic(err)
@@ -945,14 +945,14 @@ func TestUpdateSameMapper(t *testing.T) {
col2 := &UpdateMustCols{col1.Id, true, ""}
boolStr := testEngine.ColumnMapper.Obj2Table("Bool")
stringStr := testEngine.ColumnMapper.Obj2Table("String")
_, err = testEngine.Id(col2.Id).MustCols(boolStr, stringStr).Update(col2)
_, err = testEngine.ID(col2.Id).MustCols(boolStr, stringStr).Update(col2)
if err != nil {
t.Error(err)
panic(err)
}

col3 := &UpdateMustCols{}
has, err := testEngine.Id(col2.Id).Get(col3)
has, err := testEngine.ID(col2.Id).Get(col3)
if err != nil {
t.Error(err)
panic(err)
@@ -988,7 +988,7 @@ func TestUpdateSameMapper(t *testing.T) {
panic(err)
}

cnt, err := testEngine.Id(col1.Id).Incr("`Cnt`").Update(col1)
cnt, err := testEngine.ID(col1.Id).Incr("`Cnt`").Update(col1)
if err != nil {
t.Error(err)
panic(err)
@@ -1000,7 +1000,7 @@ func TestUpdateSameMapper(t *testing.T) {
}

newCol := new(UpdateIncr)
has, err := testEngine.Id(col1.Id).Get(newCol)
has, err := testEngine.ID(col1.Id).Get(newCol)
if err != nil {
t.Error(err)
panic(err)
@@ -1119,7 +1119,7 @@ func TestNoUpdate(t *testing.T) {
})
assert.NoError(t, err)

_, err = testEngine.Id(1).Update(&NoUpdate{})
_, err = testEngine.ID(1).Update(&NoUpdate{})
assert.Error(t, err)
assert.EqualValues(t, "No content found to be updated", err.Error())
}


+ 3
- 3
tag_extends_test.go View File

@@ -86,7 +86,7 @@ func TestExtends(t *testing.T) {
}

tu3 := &tempUser2{tempUser{0, "extends update"}, ""}
_, err = testEngine.Id(tu2.TempUser.Id).Update(tu3)
_, err = testEngine.ID(tu2.TempUser.Id).Update(tu3)
if err != nil {
t.Error(err)
panic(err)
@@ -124,7 +124,7 @@ func TestExtends(t *testing.T) {
}

tu10 := &tempUser4{tempUser2{tempUser{0, "extends update"}, ""}}
_, err = testEngine.Id(tu9.TempUser2.TempUser.Id).Update(tu10)
_, err = testEngine.ID(tu9.TempUser2.TempUser.Id).Update(tu10)
if err != nil {
t.Error(err)
panic(err)
@@ -168,7 +168,7 @@ func TestExtends(t *testing.T) {
}

tu6 := &tempUser3{&tempUser{0, "extends update"}, ""}
_, err = testEngine.Id(tu5.Temp.Id).Update(tu6)
_, err = testEngine.ID(tu5.Temp.Id).Update(tu6)
if err != nil {
t.Error(err)
panic(err)


+ 3
- 3
tag_test.go View File

@@ -51,7 +51,7 @@ func TestCreatedAndUpdated(t *testing.T) {
}

u.Name = "xxx"
cnt, err = testEngine.Id(u.Id).Update(u)
cnt, err = testEngine.ID(u.Id).Update(u)
if err != nil {
t.Error(err)
panic(err)
@@ -130,13 +130,13 @@ func TestCreatedUpdated(t *testing.T) {
assert.NoError(t, err)

c2 := new(CreatedUpdated)
has, err := testEngine.Id(c.Id).Get(c2)
has, err := testEngine.ID(c.Id).Get(c2)
assert.NoError(t, err)

assert.True(t, has)

c2.Value -= 1
_, err = testEngine.Id(c2.Id).Update(c2)
_, err = testEngine.ID(c2.Id).Update(c2)
assert.NoError(t, err)
}



+ 3
- 3
tag_version_test.go View File

@@ -49,7 +49,7 @@ func TestVersion1(t *testing.T) {
}

newVer := new(VersionS)
has, err := testEngine.Id(ver.Id).Get(newVer)
has, err := testEngine.ID(ver.Id).Get(newVer)
if err != nil {
t.Error(err)
panic(err)
@@ -67,7 +67,7 @@ func TestVersion1(t *testing.T) {
}

newVer.Name = "-------"
_, err = testEngine.Id(ver.Id).Update(newVer)
_, err = testEngine.ID(ver.Id).Update(newVer)
if err != nil {
t.Error(err)
panic(err)
@@ -78,7 +78,7 @@ func TestVersion1(t *testing.T) {
}

newVer = new(VersionS)
has, err = testEngine.Id(ver.Id).Get(newVer)
has, err = testEngine.ID(ver.Id).Get(newVer)
if err != nil {
t.Error(err)
panic(err)


+ 5
- 5
types_null_test.go View File

@@ -176,7 +176,7 @@ func TestNullStructUpdate(t *testing.T) {
item.Age = sql.NullInt64{23, true}
item.Height = sql.NullFloat64{0, false} // update to NULL

affected, err := testEngine.Id(2).Cols("age", "height", "is_man").Update(item)
affected, err := testEngine.ID(2).Cols("age", "height", "is_man").Update(item)
if err != nil {
t.Error(err)
panic(err)
@@ -224,7 +224,7 @@ func TestNullStructUpdate(t *testing.T) {
// IsMan: sql.NullBool{true, true},
}

_, err := testEngine.AllCols().Id(6).Update(item)
_, err := testEngine.AllCols().ID(6).Update(item)
if err != nil {
t.Error(err)
panic(err)
@@ -268,7 +268,7 @@ func TestNullStructFind(t *testing.T) {

if true {
item := new(NullType)
has, err := testEngine.Id(1).Get(item)
has, err := testEngine.ID(1).Get(item)
if err != nil {
t.Error(err)
panic(err)
@@ -305,7 +305,7 @@ func TestNullStructFind(t *testing.T) {
if true {
item := make([]NullType, 0)

err := testEngine.Id(2).Find(&item)
err := testEngine.ID(2).Find(&item)
if err != nil {
t.Error(err)
panic(err)
@@ -390,7 +390,7 @@ func TestNullStructDelete(t *testing.T) {