session_find.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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, _ := builder.ToSQL(session.Statement.cond.And(autoCond))
  113. args = append(session.Statement.joinArgs, condArgs...)
  114. sqlStr = session.Statement.genSelectSQL(columnStr, condSQL)
  115. // for mssql and use limit
  116. qs := strings.Count(sqlStr, "?")
  117. if len(args)*2 == qs {
  118. args = append(args, args...)
  119. }
  120. } else {
  121. sqlStr = session.Statement.RawSQL
  122. args = session.Statement.RawParams
  123. }
  124. var err error
  125. if session.canCache() {
  126. if cacher := session.Engine.getCacher2(table); cacher != nil &&
  127. !session.Statement.IsDistinct &&
  128. !session.Statement.unscoped {
  129. err = session.cacheFind(sliceElementType, sqlStr, rowsSlicePtr, args...)
  130. if err != ErrCacheFailed {
  131. return err
  132. }
  133. err = nil // !nashtsai! reset err to nil for ErrCacheFailed
  134. session.Engine.logger.Warn("Cache Find Failed")
  135. }
  136. }
  137. return session.noCacheFind(table, sliceValue, sqlStr, args...)
  138. }
  139. func (session *Session) noCacheFind(table *core.Table, containerValue reflect.Value, sqlStr string, args ...interface{}) error {
  140. var rawRows *core.Rows
  141. var err error
  142. session.queryPreprocess(&sqlStr, args...)
  143. if session.IsAutoCommit {
  144. _, rawRows, err = session.innerQuery(sqlStr, args...)
  145. } else {
  146. rawRows, err = session.Tx.Query(sqlStr, args...)
  147. }
  148. if err != nil {
  149. return err
  150. }
  151. defer rawRows.Close()
  152. fields, err := rawRows.Columns()
  153. if err != nil {
  154. return err
  155. }
  156. var newElemFunc func(fields []string) reflect.Value
  157. elemType := containerValue.Type().Elem()
  158. var isPointer bool
  159. if elemType.Kind() == reflect.Ptr {
  160. isPointer = true
  161. elemType = elemType.Elem()
  162. }
  163. if elemType.Kind() == reflect.Ptr {
  164. return errors.New("pointer to pointer is not supported")
  165. }
  166. newElemFunc = func(fields []string) reflect.Value {
  167. switch elemType.Kind() {
  168. case reflect.Slice:
  169. slice := reflect.MakeSlice(elemType, len(fields), len(fields))
  170. x := reflect.New(slice.Type())
  171. x.Elem().Set(slice)
  172. return x
  173. case reflect.Map:
  174. mp := reflect.MakeMap(elemType)
  175. x := reflect.New(mp.Type())
  176. x.Elem().Set(mp)
  177. return x
  178. }
  179. return reflect.New(elemType)
  180. }
  181. var containerValueSetFunc func(*reflect.Value, core.PK) error
  182. if containerValue.Kind() == reflect.Slice {
  183. containerValueSetFunc = func(newValue *reflect.Value, pk core.PK) error {
  184. if isPointer {
  185. containerValue.Set(reflect.Append(containerValue, newValue.Elem().Addr()))
  186. } else {
  187. containerValue.Set(reflect.Append(containerValue, newValue.Elem()))
  188. }
  189. return nil
  190. }
  191. } else {
  192. keyType := containerValue.Type().Key()
  193. if len(table.PrimaryKeys) == 0 {
  194. return errors.New("don't support multiple primary key's map has non-slice key type")
  195. }
  196. if len(table.PrimaryKeys) > 1 && keyType.Kind() != reflect.Slice {
  197. return errors.New("don't support multiple primary key's map has non-slice key type")
  198. }
  199. containerValueSetFunc = func(newValue *reflect.Value, pk core.PK) error {
  200. keyValue := reflect.New(keyType)
  201. err := convertPKToValue(table, keyValue.Interface(), pk)
  202. if err != nil {
  203. return err
  204. }
  205. if isPointer {
  206. containerValue.SetMapIndex(keyValue.Elem(), newValue.Elem().Addr())
  207. } else {
  208. containerValue.SetMapIndex(keyValue.Elem(), newValue.Elem())
  209. }
  210. return nil
  211. }
  212. }
  213. if elemType.Kind() == reflect.Struct {
  214. var newValue = newElemFunc(fields)
  215. dataStruct := rValue(newValue.Interface())
  216. tb, err := session.Engine.autoMapType(dataStruct)
  217. if err != nil {
  218. return err
  219. }
  220. return session.rows2Beans(rawRows, fields, len(fields), tb, newElemFunc, containerValueSetFunc)
  221. }
  222. for rawRows.Next() {
  223. var newValue = newElemFunc(fields)
  224. bean := newValue.Interface()
  225. switch elemType.Kind() {
  226. case reflect.Slice:
  227. err = rawRows.ScanSlice(bean)
  228. case reflect.Map:
  229. err = rawRows.ScanMap(bean)
  230. default:
  231. err = rawRows.Scan(bean)
  232. }
  233. if err != nil {
  234. return err
  235. }
  236. if err := containerValueSetFunc(&newValue, nil); err != nil {
  237. return err
  238. }
  239. }
  240. return nil
  241. }
  242. func convertPKToValue(table *core.Table, dst interface{}, pk core.PK) error {
  243. cols := table.PKColumns()
  244. if len(cols) == 1 {
  245. return convertAssign(dst, pk[0])
  246. }
  247. dst = pk
  248. return nil
  249. }
  250. func (session *Session) cacheFind(t reflect.Type, sqlStr string, rowsSlicePtr interface{}, args ...interface{}) (err error) {
  251. if !session.canCache() ||
  252. indexNoCase(sqlStr, "having") != -1 ||
  253. indexNoCase(sqlStr, "group by") != -1 {
  254. return ErrCacheFailed
  255. }
  256. for _, filter := range session.Engine.dialect.Filters() {
  257. sqlStr = filter.Do(sqlStr, session.Engine.dialect, session.Statement.RefTable)
  258. }
  259. newsql := session.Statement.convertIDSQL(sqlStr)
  260. if newsql == "" {
  261. return ErrCacheFailed
  262. }
  263. tableName := session.Statement.TableName()
  264. table := session.Statement.RefTable
  265. cacher := session.Engine.getCacher2(table)
  266. ids, err := core.GetCacheSql(cacher, tableName, newsql, args)
  267. if err != nil {
  268. rows, err := session.DB().Query(newsql, args...)
  269. if err != nil {
  270. return err
  271. }
  272. defer rows.Close()
  273. var i int
  274. ids = make([]core.PK, 0)
  275. for rows.Next() {
  276. i++
  277. if i > 500 {
  278. session.Engine.logger.Debug("[cacheFind] ids length > 500, no cache")
  279. return ErrCacheFailed
  280. }
  281. var res = make([]string, len(table.PrimaryKeys))
  282. err = rows.ScanSlice(&res)
  283. if err != nil {
  284. return err
  285. }
  286. var pk core.PK = make([]interface{}, len(table.PrimaryKeys))
  287. for i, col := range table.PKColumns() {
  288. if col.SQLType.IsNumeric() {
  289. n, err := strconv.ParseInt(res[i], 10, 64)
  290. if err != nil {
  291. return err
  292. }
  293. pk[i] = n
  294. } else if col.SQLType.IsText() {
  295. pk[i] = res[i]
  296. } else {
  297. return errors.New("not supported")
  298. }
  299. }
  300. ids = append(ids, pk)
  301. }
  302. session.Engine.logger.Debug("[cacheFind] cache sql:", ids, tableName, newsql, args)
  303. err = core.PutCacheSql(cacher, ids, tableName, newsql, args)
  304. if err != nil {
  305. return err
  306. }
  307. } else {
  308. session.Engine.logger.Debug("[cacheFind] cache hit sql:", newsql, args)
  309. }
  310. sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
  311. ididxes := make(map[string]int)
  312. var ides []core.PK
  313. var temps = make([]interface{}, len(ids))
  314. for idx, id := range ids {
  315. sid, err := id.ToString()
  316. if err != nil {
  317. return err
  318. }
  319. bean := cacher.GetBean(tableName, sid)
  320. if bean == nil {
  321. ides = append(ides, id)
  322. ididxes[sid] = idx
  323. } else {
  324. session.Engine.logger.Debug("[cacheFind] cache hit bean:", tableName, id, bean)
  325. pk := session.Engine.IdOf(bean)
  326. xid, err := pk.ToString()
  327. if err != nil {
  328. return err
  329. }
  330. if sid != xid {
  331. session.Engine.logger.Error("[cacheFind] error cache", xid, sid, bean)
  332. return ErrCacheFailed
  333. }
  334. temps[idx] = bean
  335. }
  336. }
  337. if len(ides) > 0 {
  338. newSession := session.Engine.NewSession()
  339. defer newSession.Close()
  340. slices := reflect.New(reflect.SliceOf(t))
  341. beans := slices.Interface()
  342. if len(table.PrimaryKeys) == 1 {
  343. ff := make([]interface{}, 0, len(ides))
  344. for _, ie := range ides {
  345. ff = append(ff, ie[0])
  346. }
  347. newSession.In("`"+table.PrimaryKeys[0]+"`", ff...)
  348. } else {
  349. for _, ie := range ides {
  350. cond := builder.NewCond()
  351. for i, name := range table.PrimaryKeys {
  352. cond = cond.And(builder.Eq{"`" + name + "`": ie[i]})
  353. }
  354. newSession.Or(cond)
  355. }
  356. }
  357. err = newSession.NoCache().Find(beans)
  358. if err != nil {
  359. return err
  360. }
  361. vs := reflect.Indirect(reflect.ValueOf(beans))
  362. for i := 0; i < vs.Len(); i++ {
  363. rv := vs.Index(i)
  364. if rv.Kind() != reflect.Ptr {
  365. rv = rv.Addr()
  366. }
  367. id, err := session.Engine.idOfV(rv)
  368. if err != nil {
  369. return err
  370. }
  371. sid, err := id.ToString()
  372. if err != nil {
  373. return err
  374. }
  375. bean := rv.Interface()
  376. temps[ididxes[sid]] = bean
  377. session.Engine.logger.Debug("[cacheFind] cache bean:", tableName, id, bean, temps)
  378. cacher.PutBean(tableName, sid, bean)
  379. }
  380. }
  381. for j := 0; j < len(temps); j++ {
  382. bean := temps[j]
  383. if bean == nil {
  384. session.Engine.logger.Warn("[cacheFind] cache no hit:", tableName, ids[j], temps)
  385. // return errors.New("cache error") // !nashtsai! no need to return error, but continue instead
  386. continue
  387. }
  388. if sliceValue.Kind() == reflect.Slice {
  389. if t.Kind() == reflect.Ptr {
  390. sliceValue.Set(reflect.Append(sliceValue, reflect.ValueOf(bean)))
  391. } else {
  392. sliceValue.Set(reflect.Append(sliceValue, reflect.Indirect(reflect.ValueOf(bean))))
  393. }
  394. } else if sliceValue.Kind() == reflect.Map {
  395. var key = ids[j]
  396. keyType := sliceValue.Type().Key()
  397. var ikey interface{}
  398. if len(key) == 1 {
  399. ikey, err = str2PK(fmt.Sprintf("%v", key[0]), keyType)
  400. if err != nil {
  401. return err
  402. }
  403. } else {
  404. if keyType.Kind() != reflect.Slice {
  405. return errors.New("table have multiple primary keys, key is not core.PK or slice")
  406. }
  407. ikey = key
  408. }
  409. if t.Kind() == reflect.Ptr {
  410. sliceValue.SetMapIndex(reflect.ValueOf(ikey), reflect.ValueOf(bean))
  411. } else {
  412. sliceValue.SetMapIndex(reflect.ValueOf(ikey), reflect.Indirect(reflect.ValueOf(bean)))
  413. }
  414. }
  415. }
  416. return nil
  417. }