session_find.go 12 KB

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