session_get.go 5.4 KB

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