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.

462 lines
12 KiB

  1. // Copyright 2016 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package xorm
  5. import (
  6. "errors"
  7. "fmt"
  8. "reflect"
  9. "strings"
  10. "github.com/go-xorm/builder"
  11. "github.com/go-xorm/core"
  12. )
  13. const (
  14. tpStruct = iota
  15. tpNonStruct
  16. )
  17. // Find retrieve records from table, condiBeans's non-empty fields
  18. // are conditions. beans could be []Struct, []*Struct, map[int64]Struct
  19. // map[int64]*Struct
  20. func (session *Session) Find(rowsSlicePtr interface{}, condiBean ...interface{}) error {
  21. if session.isAutoClose {
  22. defer session.Close()
  23. }
  24. return session.find(rowsSlicePtr, condiBean...)
  25. }
  26. func (session *Session) find(rowsSlicePtr interface{}, condiBean ...interface{}) error {
  27. sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
  28. if sliceValue.Kind() != reflect.Slice && sliceValue.Kind() != reflect.Map {
  29. return errors.New("needs a pointer to a slice or a map")
  30. }
  31. sliceElementType := sliceValue.Type().Elem()
  32. var tp = tpStruct
  33. if session.statement.RefTable == nil {
  34. if sliceElementType.Kind() == reflect.Ptr {
  35. if sliceElementType.Elem().Kind() == reflect.Struct {
  36. pv := reflect.New(sliceElementType.Elem())
  37. if err := session.statement.setRefValue(pv.Elem()); err != nil {
  38. return err
  39. }
  40. } else {
  41. tp = tpNonStruct
  42. }
  43. } else if sliceElementType.Kind() == reflect.Struct {
  44. pv := reflect.New(sliceElementType)
  45. if err := session.statement.setRefValue(pv.Elem()); err != nil {
  46. return err
  47. }
  48. } else {
  49. tp = tpNonStruct
  50. }
  51. }
  52. var table = session.statement.RefTable
  53. var addedTableName = (len(session.statement.JoinStr) > 0)
  54. var autoCond builder.Cond
  55. if tp == tpStruct {
  56. if !session.statement.noAutoCondition && len(condiBean) > 0 {
  57. var err error
  58. autoCond, err = session.statement.buildConds(table, condiBean[0], true, true, false, true, addedTableName)
  59. if err != nil {
  60. return err
  61. }
  62. } else {
  63. // !oinume! Add "<col> IS NULL" to WHERE whatever condiBean is given.
  64. // See https://github.com/go-xorm/xorm/issues/179
  65. if col := table.DeletedColumn(); col != nil && !session.statement.unscoped { // tag "deleted" is enabled
  66. var colName = session.engine.Quote(col.Name)
  67. if addedTableName {
  68. var nm = session.statement.TableName()
  69. if len(session.statement.TableAlias) > 0 {
  70. nm = session.statement.TableAlias
  71. }
  72. colName = session.engine.Quote(nm) + "." + colName
  73. }
  74. autoCond = session.engine.CondDeleted(colName)
  75. }
  76. }
  77. }
  78. var sqlStr string
  79. var args []interface{}
  80. var err error
  81. if session.statement.RawSQL == "" {
  82. if len(session.statement.TableName()) <= 0 {
  83. return ErrTableNotFound
  84. }
  85. var columnStr = session.statement.ColumnStr
  86. if len(session.statement.selectStr) > 0 {
  87. columnStr = session.statement.selectStr
  88. } else {
  89. if session.statement.JoinStr == "" {
  90. if columnStr == "" {
  91. if session.statement.GroupByStr != "" {
  92. columnStr = session.statement.Engine.Quote(strings.Replace(session.statement.GroupByStr, ",", session.engine.Quote(","), -1))
  93. } else {
  94. columnStr = session.statement.genColumnStr()
  95. }
  96. }
  97. } else {
  98. if columnStr == "" {
  99. if session.statement.GroupByStr != "" {
  100. columnStr = session.statement.Engine.Quote(strings.Replace(session.statement.GroupByStr, ",", session.engine.Quote(","), -1))
  101. } else {
  102. columnStr = "*"
  103. }
  104. }
  105. }
  106. if columnStr == "" {
  107. columnStr = "*"
  108. }
  109. }
  110. session.statement.cond = session.statement.cond.And(autoCond)
  111. condSQL, condArgs, err := builder.ToSQL(session.statement.cond)
  112. if err != nil {
  113. return err
  114. }
  115. args = append(session.statement.joinArgs, condArgs...)
  116. sqlStr, err = session.statement.genSelectSQL(columnStr, condSQL)
  117. if err != nil {
  118. return err
  119. }
  120. // for mssql and use limit
  121. qs := strings.Count(sqlStr, "?")
  122. if len(args)*2 == qs {
  123. args = append(args, args...)
  124. }
  125. } else {
  126. sqlStr = session.statement.RawSQL
  127. args = session.statement.RawParams
  128. }
  129. if session.canCache() {
  130. if cacher := session.engine.getCacher2(table); cacher != nil &&
  131. !session.statement.IsDistinct &&
  132. !session.statement.unscoped {
  133. err = session.cacheFind(sliceElementType, sqlStr, rowsSlicePtr, args...)
  134. if err != ErrCacheFailed {
  135. return err
  136. }
  137. err = nil // !nashtsai! reset err to nil for ErrCacheFailed
  138. session.engine.logger.Warn("Cache Find Failed")
  139. }
  140. }
  141. return session.noCacheFind(table, sliceValue, sqlStr, args...)
  142. }
  143. func (session *Session) noCacheFind(table *core.Table, containerValue reflect.Value, sqlStr string, args ...interface{}) error {
  144. rows, err := session.queryRows(sqlStr, args...)
  145. if err != nil {
  146. return err
  147. }
  148. defer rows.Close()
  149. fields, err := rows.Columns()
  150. if err != nil {
  151. return err
  152. }
  153. var newElemFunc func(fields []string) reflect.Value
  154. elemType := containerValue.Type().Elem()
  155. var isPointer bool
  156. if elemType.Kind() == reflect.Ptr {
  157. isPointer = true
  158. elemType = elemType.Elem()
  159. }
  160. if elemType.Kind() == reflect.Ptr {
  161. return errors.New("pointer to pointer is not supported")
  162. }
  163. newElemFunc = func(fields []string) reflect.Value {
  164. switch elemType.Kind() {
  165. case reflect.Slice:
  166. slice := reflect.MakeSlice(elemType, len(fields), len(fields))
  167. x := reflect.New(slice.Type())
  168. x.Elem().Set(slice)
  169. return x
  170. case reflect.Map:
  171. mp := reflect.MakeMap(elemType)
  172. x := reflect.New(mp.Type())
  173. x.Elem().Set(mp)
  174. return x
  175. }
  176. return reflect.New(elemType)
  177. }
  178. var containerValueSetFunc func(*reflect.Value, core.PK) error
  179. if containerValue.Kind() == reflect.Slice {
  180. containerValueSetFunc = func(newValue *reflect.Value, pk core.PK) error {
  181. if isPointer {
  182. containerValue.Set(reflect.Append(containerValue, newValue.Elem().Addr()))
  183. } else {
  184. containerValue.Set(reflect.Append(containerValue, newValue.Elem()))
  185. }
  186. return nil
  187. }
  188. } else {
  189. keyType := containerValue.Type().Key()
  190. if len(table.PrimaryKeys) == 0 {
  191. return errors.New("don't support multiple primary key's map has non-slice key type")
  192. }
  193. if len(table.PrimaryKeys) > 1 && keyType.Kind() != reflect.Slice {
  194. return errors.New("don't support multiple primary key's map has non-slice key type")
  195. }
  196. containerValueSetFunc = func(newValue *reflect.Value, pk core.PK) error {
  197. keyValue := reflect.New(keyType)
  198. err := convertPKToValue(table, keyValue.Interface(), pk)
  199. if err != nil {
  200. return err
  201. }
  202. if isPointer {
  203. containerValue.SetMapIndex(keyValue.Elem(), newValue.Elem().Addr())
  204. } else {
  205. containerValue.SetMapIndex(keyValue.Elem(), newValue.Elem())
  206. }
  207. return nil
  208. }
  209. }
  210. if elemType.Kind() == reflect.Struct {
  211. var newValue = newElemFunc(fields)
  212. dataStruct := rValue(newValue.Interface())
  213. tb, err := session.engine.autoMapType(dataStruct)
  214. if err != nil {
  215. return err
  216. }
  217. err = session.rows2Beans(rows, fields, tb, newElemFunc, containerValueSetFunc)
  218. rows.Close()
  219. if err != nil {
  220. return err
  221. }
  222. return session.executeProcessors()
  223. }
  224. for rows.Next() {
  225. var newValue = newElemFunc(fields)
  226. bean := newValue.Interface()
  227. switch elemType.Kind() {
  228. case reflect.Slice:
  229. err = rows.ScanSlice(bean)
  230. case reflect.Map:
  231. err = rows.ScanMap(bean)
  232. default:
  233. err = rows.Scan(bean)
  234. }
  235. if err != nil {
  236. return err
  237. }
  238. if err := containerValueSetFunc(&newValue, nil); err != nil {
  239. return err
  240. }
  241. }
  242. return nil
  243. }
  244. func convertPKToValue(table *core.Table, dst interface{}, pk core.PK) error {
  245. cols := table.PKColumns()
  246. if len(cols) == 1 {
  247. return convertAssign(dst, pk[0])
  248. }
  249. dst = pk
  250. return nil
  251. }
  252. func (session *Session) cacheFind(t reflect.Type, sqlStr string, rowsSlicePtr interface{}, args ...interface{}) (err error) {
  253. if !session.canCache() ||
  254. indexNoCase(sqlStr, "having") != -1 ||
  255. indexNoCase(sqlStr, "group by") != -1 {
  256. return ErrCacheFailed
  257. }
  258. for _, filter := range session.engine.dialect.Filters() {
  259. sqlStr = filter.Do(sqlStr, session.engine.dialect, session.statement.RefTable)
  260. }
  261. newsql := session.statement.convertIDSQL(sqlStr)
  262. if newsql == "" {
  263. return ErrCacheFailed
  264. }
  265. tableName := session.statement.TableName()
  266. table := session.statement.RefTable
  267. cacher := session.engine.getCacher2(table)
  268. ids, err := core.GetCacheSql(cacher, tableName, newsql, args)
  269. if err != nil {
  270. rows, err := session.queryRows(newsql, args...)
  271. if err != nil {
  272. return err
  273. }
  274. defer rows.Close()
  275. var i int
  276. ids = make([]core.PK, 0)
  277. for rows.Next() {
  278. i++
  279. if i > 500 {
  280. session.engine.logger.Debug("[cacheFind] ids length > 500, no cache")
  281. return ErrCacheFailed
  282. }
  283. var res = make([]string, len(table.PrimaryKeys))
  284. err = rows.ScanSlice(&res)
  285. if err != nil {
  286. return err
  287. }
  288. var pk core.PK = make([]interface{}, len(table.PrimaryKeys))
  289. for i, col := range table.PKColumns() {
  290. pk[i], err = session.engine.idTypeAssertion(col, res[i])
  291. if err != nil {
  292. return err
  293. }
  294. }
  295. ids = append(ids, pk)
  296. }
  297. session.engine.logger.Debug("[cacheFind] cache sql:", ids, tableName, sqlStr, newsql, args)
  298. err = core.PutCacheSql(cacher, ids, tableName, newsql, args)
  299. if err != nil {
  300. return err
  301. }
  302. } else {
  303. session.engine.logger.Debug("[cacheFind] cache hit sql:", tableName, sqlStr, newsql, args)
  304. }
  305. sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
  306. ididxes := make(map[string]int)
  307. var ides []core.PK
  308. var temps = make([]interface{}, len(ids))
  309. for idx, id := range ids {
  310. sid, err := id.ToString()
  311. if err != nil {
  312. return err
  313. }
  314. bean := cacher.GetBean(tableName, sid)
  315. if bean == nil || reflect.ValueOf(bean).Elem().Type() != t {
  316. ides = append(ides, id)
  317. ididxes[sid] = idx
  318. } else {
  319. session.engine.logger.Debug("[cacheFind] cache hit bean:", tableName, id, bean)
  320. pk := session.engine.IdOf(bean)
  321. xid, err := pk.ToString()
  322. if err != nil {
  323. return err
  324. }
  325. if sid != xid {
  326. session.engine.logger.Error("[cacheFind] error cache", xid, sid, bean)
  327. return ErrCacheFailed
  328. }
  329. temps[idx] = bean
  330. }
  331. }
  332. if len(ides) > 0 {
  333. slices := reflect.New(reflect.SliceOf(t))
  334. beans := slices.Interface()
  335. if len(table.PrimaryKeys) == 1 {
  336. ff := make([]interface{}, 0, len(ides))
  337. for _, ie := range ides {
  338. ff = append(ff, ie[0])
  339. }
  340. session.In("`"+table.PrimaryKeys[0]+"`", ff...)
  341. } else {
  342. for _, ie := range ides {
  343. cond := builder.NewCond()
  344. for i, name := range table.PrimaryKeys {
  345. cond = cond.And(builder.Eq{"`" + name + "`": ie[i]})
  346. }
  347. session.Or(cond)
  348. }
  349. }
  350. err = session.NoCache().Table(tableName).find(beans)
  351. if err != nil {
  352. return err
  353. }
  354. vs := reflect.Indirect(reflect.ValueOf(beans))
  355. for i := 0; i < vs.Len(); i++ {
  356. rv := vs.Index(i)
  357. if rv.Kind() != reflect.Ptr {
  358. rv = rv.Addr()
  359. }
  360. id, err := session.engine.idOfV(rv)
  361. if err != nil {
  362. return err
  363. }
  364. sid, err := id.ToString()
  365. if err != nil {
  366. return err
  367. }
  368. bean := rv.Interface()
  369. temps[ididxes[sid]] = bean
  370. session.engine.logger.Debug("[cacheFind] cache bean:", tableName, id, bean, temps)
  371. cacher.PutBean(tableName, sid, bean)
  372. }
  373. }
  374. for j := 0; j < len(temps); j++ {
  375. bean := temps[j]
  376. if bean == nil {
  377. session.engine.logger.Warn("[cacheFind] cache no hit:", tableName, ids[j], temps)
  378. // return errors.New("cache error") // !nashtsai! no need to return error, but continue instead
  379. continue
  380. }
  381. if sliceValue.Kind() == reflect.Slice {
  382. if t.Kind() == reflect.Ptr {
  383. sliceValue.Set(reflect.Append(sliceValue, reflect.ValueOf(bean)))
  384. } else {
  385. sliceValue.Set(reflect.Append(sliceValue, reflect.Indirect(reflect.ValueOf(bean))))
  386. }
  387. } else if sliceValue.Kind() == reflect.Map {
  388. var key = ids[j]
  389. keyType := sliceValue.Type().Key()
  390. var ikey interface{}
  391. if len(key) == 1 {
  392. ikey, err = str2PK(fmt.Sprintf("%v", key[0]), keyType)
  393. if err != nil {
  394. return err
  395. }
  396. } else {
  397. if keyType.Kind() != reflect.Slice {
  398. return errors.New("table have multiple primary keys, key is not core.PK or slice")
  399. }
  400. ikey = key
  401. }
  402. if t.Kind() == reflect.Ptr {
  403. sliceValue.SetMapIndex(reflect.ValueOf(ikey), reflect.ValueOf(bean))
  404. } else {
  405. sliceValue.SetMapIndex(reflect.ValueOf(ikey), reflect.Indirect(reflect.ValueOf(bean)))
  406. }
  407. }
  408. }
  409. return nil
  410. }