session_find.go 14 KB

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