You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
506 lines
13 KiB
506 lines
13 KiB
8 years ago
|
// Copyright 2016 The Xorm Authors. All rights reserved.
|
||
|
// Use of this source code is governed by a BSD-style
|
||
|
// license that can be found in the LICENSE file.
|
||
|
|
||
|
package xorm
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
"reflect"
|
||
|
"strings"
|
||
|
|
||
6 years ago
|
"xorm.io/builder"
|
||
|
"xorm.io/core"
|
||
8 years ago
|
)
|
||
|
|
||
|
const (
|
||
|
tpStruct = iota
|
||
|
tpNonStruct
|
||
|
)
|
||
|
|
||
|
// Find retrieve records from table, condiBeans's non-empty fields
|
||
|
// are conditions. beans could be []Struct, []*Struct, map[int64]Struct
|
||
|
// map[int64]*Struct
|
||
|
func (session *Session) Find(rowsSlicePtr interface{}, condiBean ...interface{}) error {
|
||
7 years ago
|
if session.isAutoClose {
|
||
8 years ago
|
defer session.Close()
|
||
|
}
|
||
7 years ago
|
return session.find(rowsSlicePtr, condiBean...)
|
||
|
}
|
||
8 years ago
|
|
||
6 years ago
|
// FindAndCount find the results and also return the counts
|
||
|
func (session *Session) FindAndCount(rowsSlicePtr interface{}, condiBean ...interface{}) (int64, error) {
|
||
|
if session.isAutoClose {
|
||
|
defer session.Close()
|
||
|
}
|
||
|
|
||
|
session.autoResetStatement = false
|
||
|
err := session.find(rowsSlicePtr, condiBean...)
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
|
||
|
sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
|
||
|
if sliceValue.Kind() != reflect.Slice && sliceValue.Kind() != reflect.Map {
|
||
|
return 0, errors.New("needs a pointer to a slice or a map")
|
||
|
}
|
||
|
|
||
|
sliceElementType := sliceValue.Type().Elem()
|
||
|
if sliceElementType.Kind() == reflect.Ptr {
|
||
|
sliceElementType = sliceElementType.Elem()
|
||
|
}
|
||
|
session.autoResetStatement = true
|
||
|
|
||
|
if session.statement.selectStr != "" {
|
||
|
session.statement.selectStr = ""
|
||
|
}
|
||
|
if session.statement.OrderStr != "" {
|
||
|
session.statement.OrderStr = ""
|
||
|
}
|
||
|
|
||
|
return session.Count(reflect.New(sliceElementType).Interface())
|
||
|
}
|
||
|
|
||
7 years ago
|
func (session *Session) find(rowsSlicePtr interface{}, condiBean ...interface{}) error {
|
||
5 years ago
|
defer session.resetStatement()
|
||
|
|
||
6 years ago
|
if session.statement.lastError != nil {
|
||
|
return session.statement.lastError
|
||
|
}
|
||
|
|
||
8 years ago
|
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")
|
||
|
}
|
||
|
|
||
|
sliceElementType := sliceValue.Type().Elem()
|
||
|
|
||
|
var tp = tpStruct
|
||
7 years ago
|
if session.statement.RefTable == nil {
|
||
8 years ago
|
if sliceElementType.Kind() == reflect.Ptr {
|
||
|
if sliceElementType.Elem().Kind() == reflect.Struct {
|
||
|
pv := reflect.New(sliceElementType.Elem())
|
||
6 years ago
|
if err := session.statement.setRefValue(pv); err != nil {
|
||
8 years ago
|
return err
|
||
|
}
|
||
8 years ago
|
} else {
|
||
|
tp = tpNonStruct
|
||
|
}
|
||
|
} else if sliceElementType.Kind() == reflect.Struct {
|
||
|
pv := reflect.New(sliceElementType)
|
||
6 years ago
|
if err := session.statement.setRefValue(pv); err != nil {
|
||
8 years ago
|
return err
|
||
|
}
|
||
8 years ago
|
} else {
|
||
|
tp = tpNonStruct
|
||
|
}
|
||
|
}
|
||
|
|
||
7 years ago
|
var table = session.statement.RefTable
|
||
8 years ago
|
|
||
7 years ago
|
var addedTableName = (len(session.statement.JoinStr) > 0)
|
||
8 years ago
|
var autoCond builder.Cond
|
||
|
if tp == tpStruct {
|
||
7 years ago
|
if !session.statement.noAutoCondition && len(condiBean) > 0 {
|
||
8 years ago
|
var err error
|
||
7 years ago
|
autoCond, err = session.statement.buildConds(table, condiBean[0], true, true, false, true, addedTableName)
|
||
8 years ago
|
if err != nil {
|
||
7 years ago
|
return err
|
||
8 years ago
|
}
|
||
|
} else {
|
||
|
// !oinume! Add "<col> IS NULL" to WHERE whatever condiBean is given.
|
||
5 years ago
|
// See https://gitea.com/xorm/xorm/issues/179
|
||
7 years ago
|
if col := table.DeletedColumn(); col != nil && !session.statement.unscoped { // tag "deleted" is enabled
|
||
|
var colName = session.engine.Quote(col.Name)
|
||
8 years ago
|
if addedTableName {
|
||
7 years ago
|
var nm = session.statement.TableName()
|
||
|
if len(session.statement.TableAlias) > 0 {
|
||
|
nm = session.statement.TableAlias
|
||
8 years ago
|
}
|
||
7 years ago
|
colName = session.engine.Quote(nm) + "." + colName
|
||
8 years ago
|
}
|
||
7 years ago
|
|
||
|
autoCond = session.engine.CondDeleted(colName)
|
||
8 years ago
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
var sqlStr string
|
||
|
var args []interface{}
|
||
7 years ago
|
var err error
|
||
|
if session.statement.RawSQL == "" {
|
||
|
if len(session.statement.TableName()) <= 0 {
|
||
8 years ago
|
return ErrTableNotFound
|
||
|
}
|
||
|
|
||
7 years ago
|
var columnStr = session.statement.ColumnStr
|
||
|
if len(session.statement.selectStr) > 0 {
|
||
|
columnStr = session.statement.selectStr
|
||
8 years ago
|
} else {
|
||
7 years ago
|
if session.statement.JoinStr == "" {
|
||
8 years ago
|
if columnStr == "" {
|
||
7 years ago
|
if session.statement.GroupByStr != "" {
|
||
6 years ago
|
columnStr = session.engine.quoteColumns(session.statement.GroupByStr)
|
||
8 years ago
|
} else {
|
||
7 years ago
|
columnStr = session.statement.genColumnStr()
|
||
8 years ago
|
}
|
||
|
}
|
||
|
} else {
|
||
|
if columnStr == "" {
|
||
7 years ago
|
if session.statement.GroupByStr != "" {
|
||
6 years ago
|
columnStr = session.engine.quoteColumns(session.statement.GroupByStr)
|
||
8 years ago
|
} else {
|
||
|
columnStr = "*"
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
if columnStr == "" {
|
||
|
columnStr = "*"
|
||
|
}
|
||
|
}
|
||
|
|
||
7 years ago
|
session.statement.cond = session.statement.cond.And(autoCond)
|
||
|
condSQL, condArgs, err := builder.ToSQL(session.statement.cond)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
8 years ago
|
|
||
7 years ago
|
args = append(session.statement.joinArgs, condArgs...)
|
||
6 years ago
|
sqlStr, err = session.statement.genSelectSQL(columnStr, condSQL, true, true)
|
||
7 years ago
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
8 years ago
|
// for mssql and use limit
|
||
|
qs := strings.Count(sqlStr, "?")
|
||
|
if len(args)*2 == qs {
|
||
|
args = append(args, args...)
|
||
|
}
|
||
|
} else {
|
||
7 years ago
|
sqlStr = session.statement.RawSQL
|
||
|
args = session.statement.RawParams
|
||
8 years ago
|
}
|
||
|
|
||
|
if session.canCache() {
|
||
6 years ago
|
if cacher := session.engine.getCacher(session.statement.TableName()); cacher != nil &&
|
||
7 years ago
|
!session.statement.IsDistinct &&
|
||
|
!session.statement.unscoped {
|
||
8 years ago
|
err = session.cacheFind(sliceElementType, sqlStr, rowsSlicePtr, args...)
|
||
|
if err != ErrCacheFailed {
|
||
|
return err
|
||
|
}
|
||
|
err = nil // !nashtsai! reset err to nil for ErrCacheFailed
|
||
7 years ago
|
session.engine.logger.Warn("Cache Find Failed")
|
||
8 years ago
|
}
|
||
|
}
|
||
|
|
||
8 years ago
|
return session.noCacheFind(table, sliceValue, sqlStr, args...)
|
||
8 years ago
|
}
|
||
|
|
||
8 years ago
|
func (session *Session) noCacheFind(table *core.Table, containerValue reflect.Value, sqlStr string, args ...interface{}) error {
|
||
7 years ago
|
rows, err := session.queryRows(sqlStr, args...)
|
||
8 years ago
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
7 years ago
|
defer rows.Close()
|
||
8 years ago
|
|
||
7 years ago
|
fields, err := rows.Columns()
|
||
8 years ago
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
8 years ago
|
var newElemFunc func(fields []string) reflect.Value
|
||
8 years ago
|
elemType := containerValue.Type().Elem()
|
||
8 years ago
|
var isPointer bool
|
||
8 years ago
|
if elemType.Kind() == reflect.Ptr {
|
||
8 years ago
|
isPointer = true
|
||
|
elemType = elemType.Elem()
|
||
|
}
|
||
|
if elemType.Kind() == reflect.Ptr {
|
||
|
return errors.New("pointer to pointer is not supported")
|
||
|
}
|
||
|
|
||
|
newElemFunc = func(fields []string) reflect.Value {
|
||
|
switch elemType.Kind() {
|
||
|
case reflect.Slice:
|
||
|
slice := reflect.MakeSlice(elemType, len(fields), len(fields))
|
||
|
x := reflect.New(slice.Type())
|
||
|
x.Elem().Set(slice)
|
||
|
return x
|
||
|
case reflect.Map:
|
||
|
mp := reflect.MakeMap(elemType)
|
||
|
x := reflect.New(mp.Type())
|
||
|
x.Elem().Set(mp)
|
||
|
return x
|
||
8 years ago
|
}
|
||
8 years ago
|
return reflect.New(elemType)
|
||
8 years ago
|
}
|
||
|
|
||
8 years ago
|
var containerValueSetFunc func(*reflect.Value, core.PK) error
|
||
8 years ago
|
|
||
8 years ago
|
if containerValue.Kind() == reflect.Slice {
|
||
8 years ago
|
containerValueSetFunc = func(newValue *reflect.Value, pk core.PK) error {
|
||
|
if isPointer {
|
||
|
containerValue.Set(reflect.Append(containerValue, newValue.Elem().Addr()))
|
||
|
} else {
|
||
|
containerValue.Set(reflect.Append(containerValue, newValue.Elem()))
|
||
8 years ago
|
}
|
||
8 years ago
|
return nil
|
||
8 years ago
|
}
|
||
|
} else {
|
||
|
keyType := containerValue.Type().Key()
|
||
|
if len(table.PrimaryKeys) == 0 {
|
||
|
return errors.New("don't support multiple primary key's map has non-slice key type")
|
||
|
}
|
||
|
if len(table.PrimaryKeys) > 1 && keyType.Kind() != reflect.Slice {
|
||
|
return errors.New("don't support multiple primary key's map has non-slice key type")
|
||
|
}
|
||
|
|
||
8 years ago
|
containerValueSetFunc = func(newValue *reflect.Value, pk core.PK) error {
|
||
|
keyValue := reflect.New(keyType)
|
||
|
err := convertPKToValue(table, keyValue.Interface(), pk)
|
||
|
if err != nil {
|
||
|
return err
|
||
8 years ago
|
}
|
||
8 years ago
|
if isPointer {
|
||
|
containerValue.SetMapIndex(keyValue.Elem(), newValue.Elem().Addr())
|
||
|
} else {
|
||
|
containerValue.SetMapIndex(keyValue.Elem(), newValue.Elem())
|
||
8 years ago
|
}
|
||
8 years ago
|
return nil
|
||
8 years ago
|
}
|
||
|
}
|
||
|
|
||
8 years ago
|
if elemType.Kind() == reflect.Struct {
|
||
|
var newValue = newElemFunc(fields)
|
||
|
dataStruct := rValue(newValue.Interface())
|
||
7 years ago
|
tb, err := session.engine.autoMapType(dataStruct)
|
||
8 years ago
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
7 years ago
|
err = session.rows2Beans(rows, fields, tb, newElemFunc, containerValueSetFunc)
|
||
|
rows.Close()
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
return session.executeProcessors()
|
||
8 years ago
|
}
|
||
|
|
||
7 years ago
|
for rows.Next() {
|
||
8 years ago
|
var newValue = newElemFunc(fields)
|
||
8 years ago
|
bean := newValue.Interface()
|
||
|
|
||
8 years ago
|
switch elemType.Kind() {
|
||
|
case reflect.Slice:
|
||
7 years ago
|
err = rows.ScanSlice(bean)
|
||
8 years ago
|
case reflect.Map:
|
||
7 years ago
|
err = rows.ScanMap(bean)
|
||
8 years ago
|
default:
|
||
7 years ago
|
err = rows.Scan(bean)
|
||
8 years ago
|
}
|
||
|
|
||
|
if err != nil {
|
||
8 years ago
|
return err
|
||
|
}
|
||
|
|
||
8 years ago
|
if err := containerValueSetFunc(&newValue, nil); err != nil {
|
||
|
return err
|
||
|
}
|
||
8 years ago
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
8 years ago
|
func convertPKToValue(table *core.Table, dst interface{}, pk core.PK) error {
|
||
|
cols := table.PKColumns()
|
||
|
if len(cols) == 1 {
|
||
|
return convertAssign(dst, pk[0])
|
||
|
}
|
||
|
|
||
|
dst = pk
|
||
|
return nil
|
||
|
}
|
||
|
|
||
8 years ago
|
func (session *Session) cacheFind(t reflect.Type, sqlStr string, rowsSlicePtr interface{}, args ...interface{}) (err error) {
|
||
|
if !session.canCache() ||
|
||
|
indexNoCase(sqlStr, "having") != -1 ||
|
||
|
indexNoCase(sqlStr, "group by") != -1 {
|
||
|
return ErrCacheFailed
|
||
|
}
|
||
|
|
||
6 years ago
|
tableName := session.statement.TableName()
|
||
|
cacher := session.engine.getCacher(tableName)
|
||
|
if cacher == nil {
|
||
|
return nil
|
||
|
}
|
||
|
|
||
7 years ago
|
for _, filter := range session.engine.dialect.Filters() {
|
||
|
sqlStr = filter.Do(sqlStr, session.engine.dialect, session.statement.RefTable)
|
||
8 years ago
|
}
|
||
|
|
||
7 years ago
|
newsql := session.statement.convertIDSQL(sqlStr)
|
||
8 years ago
|
if newsql == "" {
|
||
|
return ErrCacheFailed
|
||
|
}
|
||
|
|
||
7 years ago
|
table := session.statement.RefTable
|
||
8 years ago
|
ids, err := core.GetCacheSql(cacher, tableName, newsql, args)
|
||
|
if err != nil {
|
||
7 years ago
|
rows, err := session.queryRows(newsql, args...)
|
||
8 years ago
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
defer rows.Close()
|
||
|
|
||
|
var i int
|
||
|
ids = make([]core.PK, 0)
|
||
|
for rows.Next() {
|
||
|
i++
|
||
|
if i > 500 {
|
||
7 years ago
|
session.engine.logger.Debug("[cacheFind] ids length > 500, no cache")
|
||
8 years ago
|
return ErrCacheFailed
|
||
|
}
|
||
|
var res = make([]string, len(table.PrimaryKeys))
|
||
|
err = rows.ScanSlice(&res)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
var pk core.PK = make([]interface{}, len(table.PrimaryKeys))
|
||
|
for i, col := range table.PKColumns() {
|
||
7 years ago
|
pk[i], err = session.engine.idTypeAssertion(col, res[i])
|
||
|
if err != nil {
|
||
|
return err
|
||
8 years ago
|
}
|
||
|
}
|
||
|
|
||
|
ids = append(ids, pk)
|
||
|
}
|
||
|
|
||
7 years ago
|
session.engine.logger.Debug("[cacheFind] cache sql:", ids, tableName, sqlStr, newsql, args)
|
||
8 years ago
|
err = core.PutCacheSql(cacher, ids, tableName, newsql, args)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
} else {
|
||
7 years ago
|
session.engine.logger.Debug("[cacheFind] cache hit sql:", tableName, sqlStr, newsql, args)
|
||
8 years ago
|
}
|
||
|
|
||
|
sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
|
||
|
|
||
|
ididxes := make(map[string]int)
|
||
|
var ides []core.PK
|
||
|
var temps = make([]interface{}, len(ids))
|
||
|
|
||
|
for idx, id := range ids {
|
||
|
sid, err := id.ToString()
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
bean := cacher.GetBean(tableName, sid)
|
||
7 years ago
|
if bean == nil || reflect.ValueOf(bean).Elem().Type() != t {
|
||
8 years ago
|
ides = append(ides, id)
|
||
|
ididxes[sid] = idx
|
||
|
} else {
|
||
7 years ago
|
session.engine.logger.Debug("[cacheFind] cache hit bean:", tableName, id, bean)
|
||
8 years ago
|
|
||
7 years ago
|
pk := session.engine.IdOf(bean)
|
||
8 years ago
|
xid, err := pk.ToString()
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
if sid != xid {
|
||
7 years ago
|
session.engine.logger.Error("[cacheFind] error cache", xid, sid, bean)
|
||
8 years ago
|
return ErrCacheFailed
|
||
|
}
|
||
|
temps[idx] = bean
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if len(ides) > 0 {
|
||
|
slices := reflect.New(reflect.SliceOf(t))
|
||
|
beans := slices.Interface()
|
||
|
|
||
|
if len(table.PrimaryKeys) == 1 {
|
||
|
ff := make([]interface{}, 0, len(ides))
|
||
|
for _, ie := range ides {
|
||
|
ff = append(ff, ie[0])
|
||
|
}
|
||
|
|
||
7 years ago
|
session.In("`"+table.PrimaryKeys[0]+"`", ff...)
|
||
8 years ago
|
} else {
|
||
|
for _, ie := range ides {
|
||
|
cond := builder.NewCond()
|
||
|
for i, name := range table.PrimaryKeys {
|
||
|
cond = cond.And(builder.Eq{"`" + name + "`": ie[i]})
|
||
|
}
|
||
7 years ago
|
session.Or(cond)
|
||
8 years ago
|
}
|
||
|
}
|
||
|
|
||
7 years ago
|
err = session.NoCache().Table(tableName).find(beans)
|
||
8 years ago
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
vs := reflect.Indirect(reflect.ValueOf(beans))
|
||
|
for i := 0; i < vs.Len(); i++ {
|
||
|
rv := vs.Index(i)
|
||
|
if rv.Kind() != reflect.Ptr {
|
||
|
rv = rv.Addr()
|
||
|
}
|
||
7 years ago
|
id, err := session.engine.idOfV(rv)
|
||
8 years ago
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
8 years ago
|
sid, err := id.ToString()
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
bean := rv.Interface()
|
||
|
temps[ididxes[sid]] = bean
|
||
7 years ago
|
session.engine.logger.Debug("[cacheFind] cache bean:", tableName, id, bean, temps)
|
||
8 years ago
|
cacher.PutBean(tableName, sid, bean)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
for j := 0; j < len(temps); j++ {
|
||
|
bean := temps[j]
|
||
|
if bean == nil {
|
||
7 years ago
|
session.engine.logger.Warn("[cacheFind] cache no hit:", tableName, ids[j], temps)
|
||
8 years ago
|
// return errors.New("cache error") // !nashtsai! no need to return error, but continue instead
|
||
|
continue
|
||
|
}
|
||
|
if sliceValue.Kind() == reflect.Slice {
|
||
|
if t.Kind() == reflect.Ptr {
|
||
|
sliceValue.Set(reflect.Append(sliceValue, reflect.ValueOf(bean)))
|
||
|
} else {
|
||
|
sliceValue.Set(reflect.Append(sliceValue, reflect.Indirect(reflect.ValueOf(bean))))
|
||
|
}
|
||
|
} else if sliceValue.Kind() == reflect.Map {
|
||
|
var key = ids[j]
|
||
|
keyType := sliceValue.Type().Key()
|
||
|
var ikey interface{}
|
||
|
if len(key) == 1 {
|
||
|
ikey, err = str2PK(fmt.Sprintf("%v", key[0]), keyType)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
} else {
|
||
|
if keyType.Kind() != reflect.Slice {
|
||
|
return errors.New("table have multiple primary keys, key is not core.PK or slice")
|
||
|
}
|
||
|
ikey = key
|
||
|
}
|
||
|
|
||
|
if t.Kind() == reflect.Ptr {
|
||
|
sliceValue.SetMapIndex(reflect.ValueOf(ikey), reflect.ValueOf(bean))
|
||
|
} else {
|
||
|
sliceValue.SetMapIndex(reflect.ValueOf(ikey), reflect.Indirect(reflect.ValueOf(bean)))
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|