Update xorm to latest version (#1651)

* Update xorm to latest version

* Update xorm/builder
This commit is contained in:
Lauris BH 2017-05-02 03:50:33 +03:00 committed by Lunny Xiao
parent 0144817971
commit 3792867955
18 changed files with 251 additions and 141 deletions

View File

@ -22,16 +22,23 @@ func In(col string, values ...interface{}) Cond {
return condIn{col, values} return condIn{col, values}
} }
func (condIn condIn) handleBlank(w Writer) error {
if _, err := fmt.Fprintf(w, "%s IN ()", condIn.col); err != nil {
return err
}
return nil
}
func (condIn condIn) WriteTo(w Writer) error { func (condIn condIn) WriteTo(w Writer) error {
if len(condIn.vals) <= 0 { if len(condIn.vals) <= 0 {
return ErrNoInConditions return condIn.handleBlank(w)
} }
switch condIn.vals[0].(type) { switch condIn.vals[0].(type) {
case []int8: case []int8:
vals := condIn.vals[0].([]int8) vals := condIn.vals[0].([]int8)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoInConditions return condIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -43,7 +50,7 @@ func (condIn condIn) WriteTo(w Writer) error {
case []int16: case []int16:
vals := condIn.vals[0].([]int16) vals := condIn.vals[0].([]int16)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoInConditions return condIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -55,7 +62,7 @@ func (condIn condIn) WriteTo(w Writer) error {
case []int: case []int:
vals := condIn.vals[0].([]int) vals := condIn.vals[0].([]int)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoInConditions return condIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -67,7 +74,7 @@ func (condIn condIn) WriteTo(w Writer) error {
case []int32: case []int32:
vals := condIn.vals[0].([]int32) vals := condIn.vals[0].([]int32)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoInConditions return condIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -79,7 +86,7 @@ func (condIn condIn) WriteTo(w Writer) error {
case []int64: case []int64:
vals := condIn.vals[0].([]int64) vals := condIn.vals[0].([]int64)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoInConditions return condIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -91,7 +98,7 @@ func (condIn condIn) WriteTo(w Writer) error {
case []uint8: case []uint8:
vals := condIn.vals[0].([]uint8) vals := condIn.vals[0].([]uint8)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoInConditions return condIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -103,7 +110,7 @@ func (condIn condIn) WriteTo(w Writer) error {
case []uint16: case []uint16:
vals := condIn.vals[0].([]uint16) vals := condIn.vals[0].([]uint16)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoInConditions return condIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -115,7 +122,7 @@ func (condIn condIn) WriteTo(w Writer) error {
case []uint: case []uint:
vals := condIn.vals[0].([]uint) vals := condIn.vals[0].([]uint)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoInConditions return condIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -127,7 +134,7 @@ func (condIn condIn) WriteTo(w Writer) error {
case []uint32: case []uint32:
vals := condIn.vals[0].([]uint32) vals := condIn.vals[0].([]uint32)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoInConditions return condIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -139,7 +146,7 @@ func (condIn condIn) WriteTo(w Writer) error {
case []uint64: case []uint64:
vals := condIn.vals[0].([]uint64) vals := condIn.vals[0].([]uint64)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoInConditions return condIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -151,7 +158,7 @@ func (condIn condIn) WriteTo(w Writer) error {
case []string: case []string:
vals := condIn.vals[0].([]string) vals := condIn.vals[0].([]string)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoInConditions return condIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -163,7 +170,7 @@ func (condIn condIn) WriteTo(w Writer) error {
case []interface{}: case []interface{}:
vals := condIn.vals[0].([]interface{}) vals := condIn.vals[0].([]interface{})
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoInConditions return condIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -193,13 +200,12 @@ func (condIn condIn) WriteTo(w Writer) error {
return err return err
} }
default: default:
if len(condIn.vals) <= 0 {
return ErrNoInConditions
}
v := reflect.ValueOf(condIn.vals[0]) v := reflect.ValueOf(condIn.vals[0])
if v.Kind() == reflect.Slice { if v.Kind() == reflect.Slice {
l := v.Len() l := v.Len()
if l == 0 {
return condIn.handleBlank(w)
}
questionMark := strings.Repeat("?,", l) questionMark := strings.Repeat("?,", l)
if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s IN (%s)", condIn.col, questionMark[:len(questionMark)-1]); err != nil {

View File

@ -16,7 +16,12 @@ func (like Like) WriteTo(w Writer) error {
if _, err := fmt.Fprintf(w, "%s LIKE ?", like[0]); err != nil { if _, err := fmt.Fprintf(w, "%s LIKE ?", like[0]); err != nil {
return err return err
} }
w.Append("%" + like[1] + "%") // FIXME: if use other regular express, this will be failed. but for compitable, keep this
if like[1][0] == '%' || like[1][len(like[1])-1] == '%' {
w.Append(like[1])
} else {
w.Append("%" + like[1] + "%")
}
return nil return nil
} }

View File

@ -6,6 +6,7 @@ package builder
import ( import (
"fmt" "fmt"
"reflect"
"strings" "strings"
) )
@ -18,16 +19,23 @@ func NotIn(col string, values ...interface{}) Cond {
return condNotIn{col, values} return condNotIn{col, values}
} }
func (condNotIn condNotIn) handleBlank(w Writer) error {
if _, err := fmt.Fprintf(w, "%s NOT IN ()", condNotIn.col); err != nil {
return err
}
return nil
}
func (condNotIn condNotIn) WriteTo(w Writer) error { func (condNotIn condNotIn) WriteTo(w Writer) error {
if len(condNotIn.vals) <= 0 { if len(condNotIn.vals) <= 0 {
return ErrNoNotInConditions return condNotIn.handleBlank(w)
} }
switch condNotIn.vals[0].(type) { switch condNotIn.vals[0].(type) {
case []int8: case []int8:
vals := condNotIn.vals[0].([]int8) vals := condNotIn.vals[0].([]int8)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoNotInConditions return condNotIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -39,7 +47,7 @@ func (condNotIn condNotIn) WriteTo(w Writer) error {
case []int16: case []int16:
vals := condNotIn.vals[0].([]int16) vals := condNotIn.vals[0].([]int16)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoNotInConditions return condNotIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -51,7 +59,7 @@ func (condNotIn condNotIn) WriteTo(w Writer) error {
case []int: case []int:
vals := condNotIn.vals[0].([]int) vals := condNotIn.vals[0].([]int)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoNotInConditions return condNotIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -63,7 +71,7 @@ func (condNotIn condNotIn) WriteTo(w Writer) error {
case []int32: case []int32:
vals := condNotIn.vals[0].([]int32) vals := condNotIn.vals[0].([]int32)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoNotInConditions return condNotIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -75,7 +83,7 @@ func (condNotIn condNotIn) WriteTo(w Writer) error {
case []int64: case []int64:
vals := condNotIn.vals[0].([]int64) vals := condNotIn.vals[0].([]int64)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoNotInConditions return condNotIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -87,7 +95,7 @@ func (condNotIn condNotIn) WriteTo(w Writer) error {
case []uint8: case []uint8:
vals := condNotIn.vals[0].([]uint8) vals := condNotIn.vals[0].([]uint8)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoNotInConditions return condNotIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -99,7 +107,7 @@ func (condNotIn condNotIn) WriteTo(w Writer) error {
case []uint16: case []uint16:
vals := condNotIn.vals[0].([]uint16) vals := condNotIn.vals[0].([]uint16)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoNotInConditions return condNotIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -111,7 +119,7 @@ func (condNotIn condNotIn) WriteTo(w Writer) error {
case []uint: case []uint:
vals := condNotIn.vals[0].([]uint) vals := condNotIn.vals[0].([]uint)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoNotInConditions return condNotIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -123,7 +131,7 @@ func (condNotIn condNotIn) WriteTo(w Writer) error {
case []uint32: case []uint32:
vals := condNotIn.vals[0].([]uint32) vals := condNotIn.vals[0].([]uint32)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoNotInConditions return condNotIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -135,7 +143,7 @@ func (condNotIn condNotIn) WriteTo(w Writer) error {
case []uint64: case []uint64:
vals := condNotIn.vals[0].([]uint64) vals := condNotIn.vals[0].([]uint64)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoNotInConditions return condNotIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -147,7 +155,7 @@ func (condNotIn condNotIn) WriteTo(w Writer) error {
case []string: case []string:
vals := condNotIn.vals[0].([]string) vals := condNotIn.vals[0].([]string)
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoNotInConditions return condNotIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -159,7 +167,7 @@ func (condNotIn condNotIn) WriteTo(w Writer) error {
case []interface{}: case []interface{}:
vals := condNotIn.vals[0].([]interface{}) vals := condNotIn.vals[0].([]interface{})
if len(vals) <= 0 { if len(vals) <= 0 {
return ErrNoNotInConditions return condNotIn.handleBlank(w)
} }
questionMark := strings.Repeat("?,", len(vals)) questionMark := strings.Repeat("?,", len(vals))
if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil { if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil {
@ -189,11 +197,28 @@ func (condNotIn condNotIn) WriteTo(w Writer) error {
return err return err
} }
default: default:
questionMark := strings.Repeat("?,", len(condNotIn.vals)) v := reflect.ValueOf(condNotIn.vals[0])
if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil { if v.Kind() == reflect.Slice {
return err l := v.Len()
if l == 0 {
return condNotIn.handleBlank(w)
}
questionMark := strings.Repeat("?,", l)
if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil {
return err
}
for i := 0; i < l; i++ {
w.Append(v.Index(i).Interface())
}
} else {
questionMark := strings.Repeat("?,", len(condNotIn.vals))
if _, err := fmt.Fprintf(w, "%s NOT IN (%s)", condNotIn.col, questionMark[:len(questionMark)-1]); err != nil {
return err
}
w.Append(condNotIn.vals...)
} }
w.Append(condNotIn.vals...)
} }
return nil return nil
} }

View File

@ -284,3 +284,53 @@ func asKind(vv reflect.Value, tp reflect.Type) (interface{}, error) {
} }
return nil, fmt.Errorf("unsupported primary key type: %v, %v", tp, vv) return nil, fmt.Errorf("unsupported primary key type: %v, %v", tp, vv)
} }
func convertFloat(v interface{}) (float64, error) {
switch v.(type) {
case float32:
return float64(v.(float32)), nil
case float64:
return v.(float64), nil
case string:
i, err := strconv.ParseFloat(v.(string), 64)
if err != nil {
return 0, err
}
return i, nil
case []byte:
i, err := strconv.ParseFloat(string(v.([]byte)), 64)
if err != nil {
return 0, err
}
return i, nil
}
return 0, fmt.Errorf("unsupported type: %v", v)
}
func convertInt(v interface{}) (int64, error) {
switch v.(type) {
case int:
return int64(v.(int)), nil
case int8:
return int64(v.(int8)), nil
case int16:
return int64(v.(int16)), nil
case int32:
return int64(v.(int32)), nil
case int64:
return v.(int64), nil
case []byte:
i, err := strconv.ParseInt(string(v.([]byte)), 10, 64)
if err != nil {
return 0, err
}
return i, nil
case string:
i, err := strconv.ParseInt(v.(string), 10, 64)
if err != nil {
return 0, err
}
return i, nil
}
return 0, fmt.Errorf("unsupported type: %v", v)
}

View File

@ -924,6 +924,7 @@ func (engine *Engine) mapType(v reflect.Value) (*core.Table, error) {
k := strings.ToUpper(key) k := strings.ToUpper(key)
ctx.tagName = k ctx.tagName = k
ctx.params = []string{}
pStart := strings.Index(k, "(") pStart := strings.Index(k, "(")
if pStart == 0 { if pStart == 0 {
@ -935,14 +936,14 @@ func (engine *Engine) mapType(v reflect.Value) (*core.Table, error) {
} }
ctx.tagName = k[:pStart] ctx.tagName = k[:pStart]
ctx.params = strings.Split(k[pStart+1:len(k)-1], ",") ctx.params = strings.Split(key[pStart+1:len(k)-1], ",")
} }
if j > 0 { if j > 0 {
ctx.preTag = strings.ToUpper(tags[j-1]) ctx.preTag = strings.ToUpper(tags[j-1])
} }
if j < len(tags)-1 { if j < len(tags)-1 {
ctx.nextTag = strings.ToUpper(tags[j+1]) ctx.nextTag = tags[j+1]
} else { } else {
ctx.nextTag = "" ctx.nextTag = ""
} }
@ -1184,7 +1185,6 @@ func (engine *Engine) Sync(beans ...interface{}) error {
v := rValue(bean) v := rValue(bean)
tableName := engine.tbName(v) tableName := engine.tbName(v)
table, err := engine.autoMapType(v) table, err := engine.autoMapType(v)
fmt.Println(v, table, err)
if err != nil { if err != nil {
return err return err
} }
@ -1223,8 +1223,10 @@ func (engine *Engine) Sync(beans ...interface{}) error {
} }
if !isExist { if !isExist {
session := engine.NewSession() session := engine.NewSession()
session.Statement.setRefValue(v)
defer session.Close() defer session.Close()
if err := session.Statement.setRefValue(v); err != nil {
return err
}
err = session.addColumn(col.Name) err = session.addColumn(col.Name)
if err != nil { if err != nil {
return err return err
@ -1234,8 +1236,10 @@ func (engine *Engine) Sync(beans ...interface{}) error {
for name, index := range table.Indexes { for name, index := range table.Indexes {
session := engine.NewSession() session := engine.NewSession()
session.Statement.setRefValue(v)
defer session.Close() defer session.Close()
if err := session.Statement.setRefValue(v); err != nil {
return err
}
if index.Type == core.UniqueType { if index.Type == core.UniqueType {
//isExist, err := session.isIndexExist(table.Name, name, true) //isExist, err := session.isIndexExist(table.Name, name, true)
isExist, err := session.isIndexExist2(tableName, index.Cols, true) isExist, err := session.isIndexExist2(tableName, index.Cols, true)
@ -1244,8 +1248,11 @@ func (engine *Engine) Sync(beans ...interface{}) error {
} }
if !isExist { if !isExist {
session := engine.NewSession() session := engine.NewSession()
session.Statement.setRefValue(v)
defer session.Close() defer session.Close()
if err := session.Statement.setRefValue(v); err != nil {
return err
}
err = session.addUnique(tableName, name) err = session.addUnique(tableName, name)
if err != nil { if err != nil {
return err return err
@ -1258,8 +1265,11 @@ func (engine *Engine) Sync(beans ...interface{}) error {
} }
if !isExist { if !isExist {
session := engine.NewSession() session := engine.NewSession()
session.Statement.setRefValue(v)
defer session.Close() defer session.Close()
if err := session.Statement.setRefValue(v); err != nil {
return err
}
err = session.addIndex(tableName, name) err = session.addIndex(tableName, name)
if err != nil { if err != nil {
return err return err
@ -1281,18 +1291,6 @@ func (engine *Engine) Sync2(beans ...interface{}) error {
return s.Sync2(beans...) return s.Sync2(beans...)
} }
func (engine *Engine) unMap(beans ...interface{}) (e error) {
engine.mutex.Lock()
defer engine.mutex.Unlock()
for _, bean := range beans {
t := rType(bean)
if _, ok := engine.Tables[t]; ok {
delete(engine.Tables, t)
}
}
return
}
// Drop all mapped table // Drop all mapped table
func (engine *Engine) dropAll() error { func (engine *Engine) dropAll() error {
session := engine.NewSession() session := engine.NewSession()

View File

@ -452,7 +452,7 @@ func row2mapStr(rows *core.Rows, fields []string) (resultsMap map[string]string,
return result, nil return result, nil
} }
func txQuery2(tx *core.Tx, sqlStr string, params ...interface{}) (resultsSlice []map[string]string, err error) { func txQuery2(tx *core.Tx, sqlStr string, params ...interface{}) ([]map[string]string, error) {
rows, err := tx.Query(sqlStr, params...) rows, err := tx.Query(sqlStr, params...)
if err != nil { if err != nil {
return nil, err return nil, err
@ -462,13 +462,8 @@ func txQuery2(tx *core.Tx, sqlStr string, params ...interface{}) (resultsSlice [
return rows2Strings(rows) return rows2Strings(rows)
} }
func query2(db *core.DB, sqlStr string, params ...interface{}) (resultsSlice []map[string]string, err error) { func query2(db *core.DB, sqlStr string, params ...interface{}) ([]map[string]string, error) {
s, err := db.Prepare(sqlStr) rows, err := db.Query(sqlStr, params...)
if err != nil {
return nil, err
}
defer s.Close()
rows, err := s.Query(params...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -602,7 +597,6 @@ func indexName(tableName, idxName string) string {
} }
func getFlagForColumn(m map[string]bool, col *core.Column) (val bool, has bool) { func getFlagForColumn(m map[string]bool, col *core.Column) (val bool, has bool) {
if len(m) == 0 { if len(m) == 0 {
return false, false return false, false
} }

View File

@ -34,7 +34,10 @@ func newRows(session *Session, bean interface{}) (*Rows, error) {
var sqlStr string var sqlStr string
var args []interface{} var args []interface{}
rows.session.Statement.setRefValue(rValue(bean)) if err := rows.session.Statement.setRefValue(rValue(bean)); err != nil {
return nil, err
}
if len(session.Statement.TableName()) <= 0 { if len(session.Statement.TableName()) <= 0 {
return nil, ErrTableNotFound return nil, ErrTableNotFound
} }
@ -113,7 +116,9 @@ func (rows *Rows) Scan(bean interface{}) error {
} }
dataStruct := rValue(bean) dataStruct := rValue(bean)
rows.session.Statement.setRefValue(dataStruct) if err := rows.session.Statement.setRefValue(dataStruct); err != nil {
return err
}
_, err := rows.session.row2Bean(rows.rows, rows.fields, len(rows.fields), bean, &dataStruct, rows.session.Statement.RefTable) _, err := rows.session.row2Bean(rows.rows, rows.fields, len(rows.fields), bean, &dataStruct, rows.session.Statement.RefTable)
return err return err

View File

@ -26,7 +26,6 @@ type Session struct {
Statement Statement Statement Statement
IsAutoCommit bool IsAutoCommit bool
IsCommitedOrRollbacked bool IsCommitedOrRollbacked bool
TransType string
IsAutoClose bool IsAutoClose bool
// Automatically reset the statement after operations that execute a SQL // Automatically reset the statement after operations that execute a SQL
@ -44,7 +43,6 @@ type Session struct {
prepareStmt bool prepareStmt bool
stmtCache map[uint32]*core.Stmt //key: hash.Hash32 of (queryStr, len(queryStr)) stmtCache map[uint32]*core.Stmt //key: hash.Hash32 of (queryStr, len(queryStr))
cascadeDeep int
// !evalphobia! stored the last executed query on this session // !evalphobia! stored the last executed query on this session
//beforeSQLExec func(string, ...interface{}) //beforeSQLExec func(string, ...interface{})
@ -313,6 +311,11 @@ func (session *Session) rows2Beans(rows *core.Rows, fields []string, fieldsCount
} }
func (session *Session) row2Bean(rows *core.Rows, fields []string, fieldsCount int, bean interface{}, dataStruct *reflect.Value, table *core.Table) (core.PK, error) { func (session *Session) row2Bean(rows *core.Rows, fields []string, fieldsCount int, bean interface{}, dataStruct *reflect.Value, table *core.Table) (core.PK, error) {
// handle beforeClosures
for _, closure := range session.beforeClosures {
closure(bean)
}
scanResults := make([]interface{}, fieldsCount) scanResults := make([]interface{}, fieldsCount)
for i := 0; i < len(fields); i++ { for i := 0; i < len(fields); i++ {
var cell interface{} var cell interface{}
@ -334,6 +337,11 @@ func (session *Session) row2Bean(rows *core.Rows, fields []string, fieldsCount i
b.AfterSet(key, Cell(scanResults[ii].(*interface{}))) b.AfterSet(key, Cell(scanResults[ii].(*interface{})))
} }
} }
// handle afterClosures
for _, closure := range session.afterClosures {
closure(bean)
}
}() }()
dbTZ := session.Engine.DatabaseTZ dbTZ := session.Engine.DatabaseTZ
@ -369,9 +377,11 @@ func (session *Session) row2Bean(rows *core.Rows, fields []string, fieldsCount i
if fieldValue.CanAddr() { if fieldValue.CanAddr() {
if structConvert, ok := fieldValue.Addr().Interface().(core.Conversion); ok { if structConvert, ok := fieldValue.Addr().Interface().(core.Conversion); ok {
if data, err := value2Bytes(&rawValue); err == nil { if data, err := value2Bytes(&rawValue); err == nil {
structConvert.FromDB(data) if err := structConvert.FromDB(data); err != nil {
return nil, err
}
} else { } else {
session.Engine.logger.Error(err) return nil, err
} }
continue continue
} }
@ -384,7 +394,7 @@ func (session *Session) row2Bean(rows *core.Rows, fields []string, fieldsCount i
} }
fieldValue.Interface().(core.Conversion).FromDB(data) fieldValue.Interface().(core.Conversion).FromDB(data)
} else { } else {
session.Engine.logger.Error(err) return nil, err
} }
continue continue
} }
@ -414,14 +424,12 @@ func (session *Session) row2Bean(rows *core.Rows, fields []string, fieldsCount i
if fieldValue.CanAddr() { if fieldValue.CanAddr() {
err := json.Unmarshal(bs, fieldValue.Addr().Interface()) err := json.Unmarshal(bs, fieldValue.Addr().Interface())
if err != nil { if err != nil {
session.Engine.logger.Error(key, err)
return nil, err return nil, err
} }
} else { } else {
x := reflect.New(fieldType) x := reflect.New(fieldType)
err := json.Unmarshal(bs, x.Interface()) err := json.Unmarshal(bs, x.Interface())
if err != nil { if err != nil {
session.Engine.logger.Error(key, err)
return nil, err return nil, err
} }
fieldValue.Set(x.Elem()) fieldValue.Set(x.Elem())
@ -446,14 +454,12 @@ func (session *Session) row2Bean(rows *core.Rows, fields []string, fieldsCount i
if fieldValue.CanAddr() { if fieldValue.CanAddr() {
err := json.Unmarshal(bs, fieldValue.Addr().Interface()) err := json.Unmarshal(bs, fieldValue.Addr().Interface())
if err != nil { if err != nil {
session.Engine.logger.Error(err)
return nil, err return nil, err
} }
} else { } else {
x := reflect.New(fieldType) x := reflect.New(fieldType)
err := json.Unmarshal(bs, x.Interface()) err := json.Unmarshal(bs, x.Interface())
if err != nil { if err != nil {
session.Engine.logger.Error(err)
return nil, err return nil, err
} }
fieldValue.Set(x.Elem()) fieldValue.Set(x.Elem())
@ -470,14 +476,19 @@ func (session *Session) row2Bean(rows *core.Rows, fields []string, fieldsCount i
x := reflect.New(fieldType) x := reflect.New(fieldType)
err := json.Unmarshal(vv.Bytes(), x.Interface()) err := json.Unmarshal(vv.Bytes(), x.Interface())
if err != nil { if err != nil {
session.Engine.logger.Error(err)
return nil, err return nil, err
} }
fieldValue.Set(x.Elem()) fieldValue.Set(x.Elem())
} else { } else {
for i := 0; i < fieldValue.Len(); i++ { if fieldValue.Len() > 0 {
if i < vv.Len() { for i := 0; i < fieldValue.Len(); i++ {
fieldValue.Index(i).Set(vv.Index(i)) if i < vv.Len() {
fieldValue.Index(i).Set(vv.Index(i))
}
}
} else {
for i := 0; i < vv.Len(); i++ {
fieldValue.Set(reflect.Append(*fieldValue, vv.Index(i)))
} }
} }
} }
@ -540,16 +551,11 @@ func (session *Session) row2Bean(rows *core.Rows, fields []string, fieldsCount i
// !nashtsai! convert to engine location // !nashtsai! convert to engine location
t = t.In(tz) t = t.In(tz)
fieldValue.Set(reflect.ValueOf(t).Convert(fieldType)) fieldValue.Set(reflect.ValueOf(t).Convert(fieldType))
// t = fieldValue.Interface().(time.Time)
// z, _ = t.Zone()
// session.Engine.LogDebug("fieldValue key[%v]: %v | zone: %v | location: %+v\n", key, t, z, *t.Location())
} else if rawValueType == core.IntType || rawValueType == core.Int64Type || } else if rawValueType == core.IntType || rawValueType == core.Int64Type ||
rawValueType == core.Int32Type { rawValueType == core.Int32Type {
hasAssigned = true hasAssigned = true
t := time.Unix(vv.Int(), 0).In(tz) t := time.Unix(vv.Int(), 0).In(tz)
//vv = reflect.ValueOf(t)
fieldValue.Set(reflect.ValueOf(t).Convert(fieldType)) fieldValue.Set(reflect.ValueOf(t).Convert(fieldType))
} else { } else {
if d, ok := vv.Interface().([]uint8); ok { if d, ok := vv.Interface().([]uint8); ok {
@ -588,7 +594,6 @@ func (session *Session) row2Bean(rows *core.Rows, fields []string, fieldsCount i
if len([]byte(vv.String())) > 0 { if len([]byte(vv.String())) > 0 {
err := json.Unmarshal([]byte(vv.String()), x.Interface()) err := json.Unmarshal([]byte(vv.String()), x.Interface())
if err != nil { if err != nil {
session.Engine.logger.Error(err)
return nil, err return nil, err
} }
fieldValue.Set(x.Elem()) fieldValue.Set(x.Elem())
@ -599,7 +604,6 @@ func (session *Session) row2Bean(rows *core.Rows, fields []string, fieldsCount i
if len(vv.Bytes()) > 0 { if len(vv.Bytes()) > 0 {
err := json.Unmarshal(vv.Bytes(), x.Interface()) err := json.Unmarshal(vv.Bytes(), x.Interface())
if err != nil { if err != nil {
session.Engine.logger.Error(err)
return nil, err return nil, err
} }
fieldValue.Set(x.Elem()) fieldValue.Set(x.Elem())
@ -633,8 +637,6 @@ func (session *Session) row2Bean(rows *core.Rows, fields []string, fieldsCount i
return nil, err return nil, err
} }
if has { if has {
//v := structInter.Elem().Interface()
//fieldValue.Set(reflect.ValueOf(v))
fieldValue.Set(structInter.Elem()) fieldValue.Set(structInter.Elem())
} else { } else {
return nil, errors.New("cascade obj is not exist") return nil, errors.New("cascade obj is not exist")
@ -643,7 +645,6 @@ func (session *Session) row2Bean(rows *core.Rows, fields []string, fieldsCount i
} }
case reflect.Ptr: case reflect.Ptr:
// !nashtsai! TODO merge duplicated codes above // !nashtsai! TODO merge duplicated codes above
//typeStr := fieldType.String()
switch fieldType { switch fieldType {
// following types case matching ptr's native type, therefore assign ptr directly // following types case matching ptr's native type, therefore assign ptr directly
case core.PtrStringType: case core.PtrStringType:
@ -741,10 +742,9 @@ func (session *Session) row2Bean(rows *core.Rows, fields []string, fieldsCount i
if len([]byte(vv.String())) > 0 { if len([]byte(vv.String())) > 0 {
err := json.Unmarshal([]byte(vv.String()), &x) err := json.Unmarshal([]byte(vv.String()), &x)
if err != nil { if err != nil {
session.Engine.logger.Error(err) return nil, err
} else {
fieldValue.Set(reflect.ValueOf(&x))
} }
fieldValue.Set(reflect.ValueOf(&x))
} }
hasAssigned = true hasAssigned = true
case core.Complex128Type: case core.Complex128Type:
@ -752,24 +752,23 @@ func (session *Session) row2Bean(rows *core.Rows, fields []string, fieldsCount i
if len([]byte(vv.String())) > 0 { if len([]byte(vv.String())) > 0 {
err := json.Unmarshal([]byte(vv.String()), &x) err := json.Unmarshal([]byte(vv.String()), &x)
if err != nil { if err != nil {
session.Engine.logger.Error(err) return nil, err
} else {
fieldValue.Set(reflect.ValueOf(&x))
} }
fieldValue.Set(reflect.ValueOf(&x))
} }
hasAssigned = true hasAssigned = true
} // switch fieldType } // switch fieldType
// default:
// session.Engine.LogError("unsupported type in Scan: ", reflect.TypeOf(v).String())
} // switch fieldType.Kind() } // switch fieldType.Kind()
// !nashtsai! for value can't be assigned directly fallback to convert to []byte then back to value // !nashtsai! for value can't be assigned directly fallback to convert to []byte then back to value
if !hasAssigned { if !hasAssigned {
data, err := value2Bytes(&rawValue) data, err := value2Bytes(&rawValue)
if err == nil { if err != nil {
session.bytes2Value(col, fieldValue, data) return nil, err
} else { }
session.Engine.logger.Error(err.Error())
if err = session.bytes2Value(col, fieldValue, data); err != nil {
return nil, err
} }
} }
} }

View File

@ -83,7 +83,9 @@ func (session *Session) Delete(bean interface{}) (int64, error) {
defer session.Close() defer session.Close()
} }
session.Statement.setRefValue(rValue(bean)) if err := session.Statement.setRefValue(rValue(bean)); err != nil {
return 0, err
}
var table = session.Statement.RefTable var table = session.Statement.RefTable
// handle before delete processors // handle before delete processors

View File

@ -41,13 +41,17 @@ func (session *Session) Find(rowsSlicePtr interface{}, condiBean ...interface{})
if sliceElementType.Kind() == reflect.Ptr { if sliceElementType.Kind() == reflect.Ptr {
if sliceElementType.Elem().Kind() == reflect.Struct { if sliceElementType.Elem().Kind() == reflect.Struct {
pv := reflect.New(sliceElementType.Elem()) pv := reflect.New(sliceElementType.Elem())
session.Statement.setRefValue(pv.Elem()) if err := session.Statement.setRefValue(pv.Elem()); err != nil {
return err
}
} else { } else {
tp = tpNonStruct tp = tpNonStruct
} }
} else if sliceElementType.Kind() == reflect.Struct { } else if sliceElementType.Kind() == reflect.Struct {
pv := reflect.New(sliceElementType) pv := reflect.New(sliceElementType)
session.Statement.setRefValue(pv.Elem()) if err := session.Statement.setRefValue(pv.Elem()); err != nil {
return err
}
} else { } else {
tp = tpNonStruct tp = tpNonStruct
} }

View File

@ -26,7 +26,9 @@ func (session *Session) Get(bean interface{}) (bool, error) {
} }
if beanValue.Elem().Kind() == reflect.Struct { if beanValue.Elem().Kind() == reflect.Struct {
session.Statement.setRefValue(beanValue.Elem()) if err := session.Statement.setRefValue(beanValue.Elem()); err != nil {
return false, err
}
} }
var sqlStr string var sqlStr string
@ -81,7 +83,9 @@ func (session *Session) nocacheGet(beanKind reflect.Kind, bean interface{}, sqlS
return true, err return true, err
} }
dataStruct := rValue(bean) dataStruct := rValue(bean)
session.Statement.setRefValue(dataStruct) if err := session.Statement.setRefValue(dataStruct); err != nil {
return false, err
}
_, err = session.row2Bean(rawRows, fields, len(fields), bean, &dataStruct, session.Statement.RefTable) _, err = session.row2Bean(rawRows, fields, len(fields), bean, &dataStruct, session.Statement.RefTable)
case reflect.Slice: case reflect.Slice:
err = rawRows.ScanSlice(bean) err = rawRows.ScanSlice(bean)

View File

@ -67,7 +67,9 @@ func (session *Session) innerInsertMulti(rowsSlicePtr interface{}) (int64, error
return 0, errors.New("could not insert a empty slice") return 0, errors.New("could not insert a empty slice")
} }
session.Statement.setRefValue(sliceValue.Index(0)) if err := session.Statement.setRefValue(sliceValue.Index(0)); err != nil {
return 0, err
}
if len(session.Statement.TableName()) <= 0 { if len(session.Statement.TableName()) <= 0 {
return 0, ErrTableNotFound return 0, ErrTableNotFound
@ -217,19 +219,19 @@ func (session *Session) innerInsertMulti(rowsSlicePtr interface{}) (int64, error
temp := fmt.Sprintf(") INTO %s (%v%v%v) VALUES (", temp := fmt.Sprintf(") INTO %s (%v%v%v) VALUES (",
session.Engine.Quote(session.Statement.TableName()), session.Engine.Quote(session.Statement.TableName()),
session.Engine.QuoteStr(), session.Engine.QuoteStr(),
strings.Join(colNames, session.Engine.QuoteStr() + ", " + session.Engine.QuoteStr()), strings.Join(colNames, session.Engine.QuoteStr()+", "+session.Engine.QuoteStr()),
session.Engine.QuoteStr()) session.Engine.QuoteStr())
statement = fmt.Sprintf(sql, statement = fmt.Sprintf(sql,
session.Engine.Quote(session.Statement.TableName()), session.Engine.Quote(session.Statement.TableName()),
session.Engine.QuoteStr(), session.Engine.QuoteStr(),
strings.Join(colNames, session.Engine.QuoteStr() + ", " + session.Engine.QuoteStr()), strings.Join(colNames, session.Engine.QuoteStr()+", "+session.Engine.QuoteStr()),
session.Engine.QuoteStr(), session.Engine.QuoteStr(),
strings.Join(colMultiPlaces, temp)) strings.Join(colMultiPlaces, temp))
} else { } else {
statement = fmt.Sprintf(sql, statement = fmt.Sprintf(sql,
session.Engine.Quote(session.Statement.TableName()), session.Engine.Quote(session.Statement.TableName()),
session.Engine.QuoteStr(), session.Engine.QuoteStr(),
strings.Join(colNames, session.Engine.QuoteStr() + ", " + session.Engine.QuoteStr()), strings.Join(colNames, session.Engine.QuoteStr()+", "+session.Engine.QuoteStr()),
session.Engine.QuoteStr(), session.Engine.QuoteStr(),
strings.Join(colMultiPlaces, "),(")) strings.Join(colMultiPlaces, "),("))
} }
@ -297,7 +299,9 @@ func (session *Session) InsertMulti(rowsSlicePtr interface{}) (int64, error) {
} }
func (session *Session) innerInsert(bean interface{}) (int64, error) { func (session *Session) innerInsert(bean interface{}) (int64, error) {
session.Statement.setRefValue(rValue(bean)) if err := session.Statement.setRefValue(rValue(bean)); err != nil {
return 0, err
}
if len(session.Statement.TableName()) <= 0 { if len(session.Statement.TableName()) <= 0 {
return 0, ErrTableNotFound return 0, ErrTableNotFound
} }
@ -325,8 +329,8 @@ func (session *Session) innerInsert(bean interface{}) (int64, error) {
// remove the expr columns // remove the expr columns
for i, colName := range colNames { for i, colName := range colNames {
if colName == v.colName { if colName == v.colName {
colNames = append(colNames[:i], colNames[i + 1:]...) colNames = append(colNames[:i], colNames[i+1:]...)
args = append(args[:i], args[i + 1:]...) args = append(args[:i], args[i+1:]...)
} }
} }
@ -335,11 +339,11 @@ func (session *Session) innerInsert(bean interface{}) (int64, error) {
exprColVals = append(exprColVals, v.expr) exprColVals = append(exprColVals, v.expr)
} }
colPlaces := strings.Repeat("?, ", len(colNames) - len(exprColumns)) colPlaces := strings.Repeat("?, ", len(colNames)-len(exprColumns))
if len(exprColVals) > 0 { if len(exprColVals) > 0 {
colPlaces = colPlaces + strings.Join(exprColVals, ", ") colPlaces = colPlaces + strings.Join(exprColVals, ", ")
} else { } else {
colPlaces = colPlaces[0 : len(colPlaces) - 2] colPlaces = colPlaces[0 : len(colPlaces)-2]
} }
sqlStr := fmt.Sprintf("INSERT INTO %s (%v%v%v) VALUES (%v)", sqlStr := fmt.Sprintf("INSERT INTO %s (%v%v%v) VALUES (%v)",

View File

@ -10,7 +10,7 @@ import (
"github.com/go-xorm/core" "github.com/go-xorm/core"
) )
func (session *Session) query(sqlStr string, paramStr ...interface{}) (resultsSlice []map[string][]byte, err error) { func (session *Session) query(sqlStr string, paramStr ...interface{}) ([]map[string][]byte, error) {
session.queryPreprocess(&sqlStr, paramStr...) session.queryPreprocess(&sqlStr, paramStr...)
if session.IsAutoCommit { if session.IsAutoCommit {
@ -19,7 +19,7 @@ func (session *Session) query(sqlStr string, paramStr ...interface{}) (resultsSl
return session.txQuery(session.Tx, sqlStr, paramStr...) return session.txQuery(session.Tx, sqlStr, paramStr...)
} }
func (session *Session) txQuery(tx *core.Tx, sqlStr string, params ...interface{}) (resultsSlice []map[string][]byte, err error) { func (session *Session) txQuery(tx *core.Tx, sqlStr string, params ...interface{}) ([]map[string][]byte, error) {
rows, err := tx.Query(sqlStr, params...) rows, err := tx.Query(sqlStr, params...)
if err != nil { if err != nil {
return nil, err return nil, err
@ -71,7 +71,7 @@ func (session *Session) innerQuery2(sqlStr string, params ...interface{}) ([]map
} }
// Query runs a raw sql and return records as []map[string][]byte // Query runs a raw sql and return records as []map[string][]byte
func (session *Session) Query(sqlStr string, paramStr ...interface{}) (resultsSlice []map[string][]byte, err error) { func (session *Session) Query(sqlStr string, paramStr ...interface{}) ([]map[string][]byte, error) {
defer session.resetStatement() defer session.resetStatement()
if session.IsAutoClose { if session.IsAutoClose {
defer session.Close() defer session.Close()
@ -86,19 +86,13 @@ func (session *Session) QueryString(sqlStr string, args ...interface{}) ([]map[s
if session.IsAutoClose { if session.IsAutoClose {
defer session.Close() defer session.Close()
} }
return session.query2(sqlStr, args...)
}
// ============================= session.queryPreprocess(&sqlStr, args...)
// for string
// =============================
func (session *Session) query2(sqlStr string, paramStr ...interface{}) (resultsSlice []map[string]string, err error) {
session.queryPreprocess(&sqlStr, paramStr...)
if session.IsAutoCommit { if session.IsAutoCommit {
return query2(session.DB(), sqlStr, paramStr...) return query2(session.DB(), sqlStr, args...)
} }
return txQuery2(session.Tx, sqlStr, paramStr...) return txQuery2(session.Tx, sqlStr, args...)
} }
// Execute sql // Execute sql

View File

@ -27,7 +27,9 @@ func (session *Session) Ping() error {
// CreateTable create a table according a bean // CreateTable create a table according a bean
func (session *Session) CreateTable(bean interface{}) error { func (session *Session) CreateTable(bean interface{}) error {
v := rValue(bean) v := rValue(bean)
session.Statement.setRefValue(v) if err := session.Statement.setRefValue(v); err != nil {
return err
}
defer session.resetStatement() defer session.resetStatement()
if session.IsAutoClose { if session.IsAutoClose {
@ -40,7 +42,9 @@ func (session *Session) CreateTable(bean interface{}) error {
// CreateIndexes create indexes // CreateIndexes create indexes
func (session *Session) CreateIndexes(bean interface{}) error { func (session *Session) CreateIndexes(bean interface{}) error {
v := rValue(bean) v := rValue(bean)
session.Statement.setRefValue(v) if err := session.Statement.setRefValue(v); err != nil {
return err
}
defer session.resetStatement() defer session.resetStatement()
if session.IsAutoClose { if session.IsAutoClose {
@ -60,7 +64,9 @@ func (session *Session) CreateIndexes(bean interface{}) error {
// CreateUniques create uniques // CreateUniques create uniques
func (session *Session) CreateUniques(bean interface{}) error { func (session *Session) CreateUniques(bean interface{}) error {
v := rValue(bean) v := rValue(bean)
session.Statement.setRefValue(v) if err := session.Statement.setRefValue(v); err != nil {
return err
}
defer session.resetStatement() defer session.resetStatement()
if session.IsAutoClose { if session.IsAutoClose {
@ -104,7 +110,9 @@ func (session *Session) createAll() error {
// DropIndexes drop indexes // DropIndexes drop indexes
func (session *Session) DropIndexes(bean interface{}) error { func (session *Session) DropIndexes(bean interface{}) error {
v := rValue(bean) v := rValue(bean)
session.Statement.setRefValue(v) if err := session.Statement.setRefValue(v); err != nil {
return err
}
defer session.resetStatement() defer session.resetStatement()
if session.IsAutoClose { if session.IsAutoClose {

View File

@ -169,7 +169,9 @@ func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int6
var isMap = t.Kind() == reflect.Map var isMap = t.Kind() == reflect.Map
var isStruct = t.Kind() == reflect.Struct var isStruct = t.Kind() == reflect.Struct
if isStruct { if isStruct {
session.Statement.setRefValue(v) if err := session.Statement.setRefValue(v); err != nil {
return 0, err
}
if len(session.Statement.TableName()) <= 0 { if len(session.Statement.TableName()) <= 0 {
return 0, ErrTableNotFound return 0, ErrTableNotFound

View File

@ -1188,12 +1188,16 @@ func (statement *Statement) genSumSQL(bean interface{}, columns ...string) (stri
var sumStrs = make([]string, 0, len(columns)) var sumStrs = make([]string, 0, len(columns))
for _, colName := range columns { for _, colName := range columns {
sumStrs = append(sumStrs, fmt.Sprintf("COALESCE(sum(%s),0)", statement.Engine.Quote(colName))) if !strings.Contains(colName, " ") && !strings.Contains(colName, "(") {
colName = statement.Engine.Quote(colName)
}
sumStrs = append(sumStrs, fmt.Sprintf("COALESCE(sum(%s),0)", colName))
} }
sumSelect := strings.Join(sumStrs, ", ")
condSQL, condArgs, _ := statement.genConds(bean) condSQL, condArgs, _ := statement.genConds(bean)
return statement.genSelectSQL(strings.Join(sumStrs, ", "), condSQL), append(statement.joinArgs, condArgs...) return statement.genSelectSQL(sumSelect, condSQL), append(statement.joinArgs, condArgs...)
} }
func (statement *Statement) genSelectSQL(columnStr, condSQL string) (a string) { func (statement *Statement) genSelectSQL(columnStr, condSQL string) (a string) {
@ -1214,8 +1218,14 @@ func (statement *Statement) genSelectSQL(columnStr, condSQL string) (a string) {
fmt.Fprintf(&buf, " WHERE %v", condSQL) fmt.Fprintf(&buf, " WHERE %v", condSQL)
} }
var whereStr = buf.String() var whereStr = buf.String()
var fromStr = " FROM "
if dialect.DBType() == core.MSSQL && strings.Contains(statement.TableName(), "..") {
fromStr += statement.TableName()
} else {
fromStr += quote(statement.TableName())
}
var fromStr = " FROM " + quote(statement.TableName())
if statement.TableAlias != "" { if statement.TableAlias != "" {
if dialect.DBType() == core.ORACLE { if dialect.DBType() == core.ORACLE {
fromStr += " " + quote(statement.TableAlias) fromStr += " " + quote(statement.TableAlias)

View File

@ -17,7 +17,7 @@ import (
const ( const (
// Version show the xorm's version // Version show the xorm's version
Version string = "0.6.2.0401" Version string = "0.6.2.0412"
) )
func regDrvsNDialects() bool { func regDrvsNDialects() bool {

12
vendor/vendor.json vendored
View File

@ -438,10 +438,10 @@
"revisionTime": "2016-11-01T11:13:14Z" "revisionTime": "2016-11-01T11:13:14Z"
}, },
{ {
"checksumSHA1": "Fh6Svimt+QyXHbaVxgSV7qwUHL8=", "checksumSHA1": "HHB+Jna1wv0cXLxtCyOnQqFwvn4=",
"path": "github.com/go-xorm/builder", "path": "github.com/go-xorm/builder",
"revision": "9c357861b643b7dd1023551fdf116b8d42030146", "revision": "c6e604e9c7b7461715091e14ad0c242ec44c26e4",
"revisionTime": "2017-02-16T03:03:40Z" "revisionTime": "2017-02-24T04:30:50Z"
}, },
{ {
"checksumSHA1": "vt2CGANHLNXPAZ01ve3UlsgQ0uU=", "checksumSHA1": "vt2CGANHLNXPAZ01ve3UlsgQ0uU=",
@ -456,10 +456,10 @@
"revisionTime": "2016-08-11T02:11:45Z" "revisionTime": "2016-08-11T02:11:45Z"
}, },
{ {
"checksumSHA1": "/vlyLLStrbfErk/rR3SPuBGQeqk=", "checksumSHA1": "Ka4hFMvc75Fb57ZNLALyYSM7CCE=",
"path": "github.com/go-xorm/xorm", "path": "github.com/go-xorm/xorm",
"revision": "a5cb21c44305815170d0d72563e47d585e8dcabf", "revision": "d52a762fba17a2ed265463c1c7b608c14836eaaf",
"revisionTime": "2017-04-05T10:17:41Z" "revisionTime": "2017-04-20T16:02:48Z"
}, },
{ {
"checksumSHA1": "1ft/4j5MFa7C9dPI9whL03HSUzk=", "checksumSHA1": "1ft/4j5MFa7C9dPI9whL03HSUzk=",