session_find.go 13 KB

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