session_get.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. "reflect"
  8. "strconv"
  9. "github.com/go-xorm/core"
  10. )
  11. // Get retrieve one record from database, bean's non-empty fields
  12. // will be as conditions
  13. func (session *Session) Get(bean interface{}) (bool, error) {
  14. defer session.resetStatement()
  15. if session.IsAutoClose {
  16. defer session.Close()
  17. }
  18. beanValue := reflect.ValueOf(bean)
  19. if beanValue.Kind() != reflect.Ptr {
  20. return false, errors.New("needs a pointer")
  21. }
  22. if beanValue.Elem().Kind() == reflect.Struct {
  23. if err := session.Statement.setRefValue(beanValue.Elem()); err != nil {
  24. return false, err
  25. }
  26. }
  27. var sqlStr string
  28. var args []interface{}
  29. if session.Statement.RawSQL == "" {
  30. if len(session.Statement.TableName()) <= 0 {
  31. return false, ErrTableNotFound
  32. }
  33. session.Statement.Limit(1)
  34. sqlStr, args = session.Statement.genGetSQL(bean)
  35. } else {
  36. sqlStr = session.Statement.RawSQL
  37. args = session.Statement.RawParams
  38. }
  39. if session.canCache() && beanValue.Elem().Kind() == reflect.Struct {
  40. if cacher := session.Engine.getCacher2(session.Statement.RefTable); cacher != nil &&
  41. !session.Statement.unscoped {
  42. has, err := session.cacheGet(bean, sqlStr, args...)
  43. if err != ErrCacheFailed {
  44. return has, err
  45. }
  46. }
  47. }
  48. return session.nocacheGet(beanValue.Elem().Kind(), bean, sqlStr, args...)
  49. }
  50. func (session *Session) nocacheGet(beanKind reflect.Kind, bean interface{}, sqlStr string, args ...interface{}) (bool, error) {
  51. session.queryPreprocess(&sqlStr, args...)
  52. var rawRows *core.Rows
  53. var err error
  54. if session.IsAutoCommit {
  55. _, rawRows, err = session.innerQuery(sqlStr, args...)
  56. } else {
  57. rawRows, err = session.Tx.Query(sqlStr, args...)
  58. }
  59. if err != nil {
  60. return false, err
  61. }
  62. defer rawRows.Close()
  63. if rawRows.Next() {
  64. switch beanKind {
  65. case reflect.Struct:
  66. fields, err := rawRows.Columns()
  67. if err != nil {
  68. // WARN: Alougth rawRows return true, but get fields failed
  69. return true, err
  70. }
  71. dataStruct := rValue(bean)
  72. if err := session.Statement.setRefValue(dataStruct); err != nil {
  73. return false, err
  74. }
  75. _, err = session.row2Bean(rawRows, fields, len(fields), bean, &dataStruct, session.Statement.RefTable)
  76. case reflect.Slice:
  77. err = rawRows.ScanSlice(bean)
  78. case reflect.Map:
  79. err = rawRows.ScanMap(bean)
  80. default:
  81. err = rawRows.Scan(bean)
  82. }
  83. return true, err
  84. }
  85. return false, nil
  86. }
  87. func (session *Session) cacheGet(bean interface{}, sqlStr string, args ...interface{}) (has bool, err error) {
  88. // if has no reftable, then don't use cache currently
  89. if !session.canCache() {
  90. return false, ErrCacheFailed
  91. }
  92. for _, filter := range session.Engine.dialect.Filters() {
  93. sqlStr = filter.Do(sqlStr, session.Engine.dialect, session.Statement.RefTable)
  94. }
  95. newsql := session.Statement.convertIDSQL(sqlStr)
  96. if newsql == "" {
  97. return false, ErrCacheFailed
  98. }
  99. cacher := session.Engine.getCacher2(session.Statement.RefTable)
  100. tableName := session.Statement.TableName()
  101. session.Engine.logger.Debug("[cacheGet] find sql:", newsql, args)
  102. ids, err := core.GetCacheSql(cacher, tableName, newsql, args)
  103. table := session.Statement.RefTable
  104. if err != nil {
  105. var res = make([]string, len(table.PrimaryKeys))
  106. rows, err := session.DB().Query(newsql, args...)
  107. if err != nil {
  108. return false, err
  109. }
  110. defer rows.Close()
  111. if rows.Next() {
  112. err = rows.ScanSlice(&res)
  113. if err != nil {
  114. return false, err
  115. }
  116. } else {
  117. return false, ErrCacheFailed
  118. }
  119. var pk core.PK = make([]interface{}, len(table.PrimaryKeys))
  120. for i, col := range table.PKColumns() {
  121. if col.SQLType.IsText() {
  122. pk[i] = res[i]
  123. } else if col.SQLType.IsNumeric() {
  124. n, err := strconv.ParseInt(res[i], 10, 64)
  125. if err != nil {
  126. return false, err
  127. }
  128. pk[i] = n
  129. } else {
  130. return false, errors.New("unsupported")
  131. }
  132. }
  133. ids = []core.PK{pk}
  134. session.Engine.logger.Debug("[cacheGet] cache ids:", newsql, ids)
  135. err = core.PutCacheSql(cacher, ids, tableName, newsql, args)
  136. if err != nil {
  137. return false, err
  138. }
  139. } else {
  140. session.Engine.logger.Debug("[cacheGet] cache hit sql:", newsql)
  141. }
  142. if len(ids) > 0 {
  143. structValue := reflect.Indirect(reflect.ValueOf(bean))
  144. id := ids[0]
  145. session.Engine.logger.Debug("[cacheGet] get bean:", tableName, id)
  146. sid, err := id.ToString()
  147. if err != nil {
  148. return false, err
  149. }
  150. cacheBean := cacher.GetBean(tableName, sid)
  151. if cacheBean == nil {
  152. cacheBean = bean
  153. has, err = session.nocacheGet(reflect.Struct, cacheBean, sqlStr, args...)
  154. if err != nil || !has {
  155. return has, err
  156. }
  157. session.Engine.logger.Debug("[cacheGet] cache bean:", tableName, id, cacheBean)
  158. cacher.PutBean(tableName, sid, cacheBean)
  159. } else {
  160. session.Engine.logger.Debug("[cacheGet] cache hit bean:", tableName, id, cacheBean)
  161. has = true
  162. }
  163. structValue.Set(reflect.Indirect(reflect.ValueOf(cacheBean)))
  164. return has, nil
  165. }
  166. return false, nil
  167. }