THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

357 lines
8.4KB

  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. "fmt"
  9. "reflect"
  10. "strconv"
  11. "xorm.io/core"
  12. )
  13. // Get retrieve one record from database, bean's non-empty fields
  14. // will be as conditions
  15. func (session *Session) Get(bean interface{}) (bool, error) {
  16. if session.isAutoClose {
  17. defer session.Close()
  18. }
  19. return session.get(bean)
  20. }
  21. func (session *Session) get(bean interface{}) (bool, error) {
  22. defer session.resetStatement()
  23. if session.statement.lastError != nil {
  24. return false, session.statement.lastError
  25. }
  26. beanValue := reflect.ValueOf(bean)
  27. if beanValue.Kind() != reflect.Ptr {
  28. return false, errors.New("needs a pointer to a value")
  29. } else if beanValue.Elem().Kind() == reflect.Ptr {
  30. return false, errors.New("a pointer to a pointer is not allowed")
  31. }
  32. if beanValue.Elem().Kind() == reflect.Struct {
  33. if err := session.statement.setRefBean(bean); err != nil {
  34. return false, err
  35. }
  36. }
  37. var sqlStr string
  38. var args []interface{}
  39. var err error
  40. if session.statement.RawSQL == "" {
  41. if len(session.statement.TableName()) <= 0 {
  42. return false, ErrTableNotFound
  43. }
  44. session.statement.Limit(1)
  45. sqlStr, args, err = session.statement.genGetSQL(bean)
  46. if err != nil {
  47. return false, err
  48. }
  49. } else {
  50. sqlStr = session.statement.RawSQL
  51. args = session.statement.RawParams
  52. }
  53. table := session.statement.RefTable
  54. if session.canCache() && beanValue.Elem().Kind() == reflect.Struct {
  55. if cacher := session.engine.getCacher(session.statement.TableName()); cacher != nil &&
  56. !session.statement.unscoped {
  57. has, err := session.cacheGet(bean, sqlStr, args...)
  58. if err != ErrCacheFailed {
  59. return has, err
  60. }
  61. }
  62. }
  63. context := session.statement.context
  64. if context != nil {
  65. res := context.Get(fmt.Sprintf("%v-%v", sqlStr, args))
  66. if res != nil {
  67. session.engine.logger.Debug("hit context cache", sqlStr)
  68. structValue := reflect.Indirect(reflect.ValueOf(bean))
  69. structValue.Set(reflect.Indirect(reflect.ValueOf(res)))
  70. session.lastSQL = ""
  71. session.lastSQLArgs = nil
  72. return true, nil
  73. }
  74. }
  75. has, err := session.nocacheGet(beanValue.Elem().Kind(), table, bean, sqlStr, args...)
  76. if err != nil || !has {
  77. return has, err
  78. }
  79. if context != nil {
  80. context.Put(fmt.Sprintf("%v-%v", sqlStr, args), bean)
  81. }
  82. return true, nil
  83. }
  84. func (session *Session) nocacheGet(beanKind reflect.Kind, table *core.Table, bean interface{}, sqlStr string, args ...interface{}) (bool, error) {
  85. rows, err := session.queryRows(sqlStr, args...)
  86. if err != nil {
  87. return false, err
  88. }
  89. defer rows.Close()
  90. if !rows.Next() {
  91. if rows.Err() != nil {
  92. return false, rows.Err()
  93. }
  94. return false, nil
  95. }
  96. switch bean.(type) {
  97. case sql.NullInt64, sql.NullBool, sql.NullFloat64, sql.NullString:
  98. return true, rows.Scan(&bean)
  99. case *sql.NullInt64, *sql.NullBool, *sql.NullFloat64, *sql.NullString:
  100. return true, rows.Scan(bean)
  101. case *string:
  102. var res sql.NullString
  103. if err := rows.Scan(&res); err != nil {
  104. return true, err
  105. }
  106. if res.Valid {
  107. *(bean.(*string)) = res.String
  108. }
  109. return true, nil
  110. case *int:
  111. var res sql.NullInt64
  112. if err := rows.Scan(&res); err != nil {
  113. return true, err
  114. }
  115. if res.Valid {
  116. *(bean.(*int)) = int(res.Int64)
  117. }
  118. return true, nil
  119. case *int8:
  120. var res sql.NullInt64
  121. if err := rows.Scan(&res); err != nil {
  122. return true, err
  123. }
  124. if res.Valid {
  125. *(bean.(*int8)) = int8(res.Int64)
  126. }
  127. return true, nil
  128. case *int16:
  129. var res sql.NullInt64
  130. if err := rows.Scan(&res); err != nil {
  131. return true, err
  132. }
  133. if res.Valid {
  134. *(bean.(*int16)) = int16(res.Int64)
  135. }
  136. return true, nil
  137. case *int32:
  138. var res sql.NullInt64
  139. if err := rows.Scan(&res); err != nil {
  140. return true, err
  141. }
  142. if res.Valid {
  143. *(bean.(*int32)) = int32(res.Int64)
  144. }
  145. return true, nil
  146. case *int64:
  147. var res sql.NullInt64
  148. if err := rows.Scan(&res); err != nil {
  149. return true, err
  150. }
  151. if res.Valid {
  152. *(bean.(*int64)) = int64(res.Int64)
  153. }
  154. return true, nil
  155. case *uint:
  156. var res sql.NullInt64
  157. if err := rows.Scan(&res); err != nil {
  158. return true, err
  159. }
  160. if res.Valid {
  161. *(bean.(*uint)) = uint(res.Int64)
  162. }
  163. return true, nil
  164. case *uint8:
  165. var res sql.NullInt64
  166. if err := rows.Scan(&res); err != nil {
  167. return true, err
  168. }
  169. if res.Valid {
  170. *(bean.(*uint8)) = uint8(res.Int64)
  171. }
  172. return true, nil
  173. case *uint16:
  174. var res sql.NullInt64
  175. if err := rows.Scan(&res); err != nil {
  176. return true, err
  177. }
  178. if res.Valid {
  179. *(bean.(*uint16)) = uint16(res.Int64)
  180. }
  181. return true, nil
  182. case *uint32:
  183. var res sql.NullInt64
  184. if err := rows.Scan(&res); err != nil {
  185. return true, err
  186. }
  187. if res.Valid {
  188. *(bean.(*uint32)) = uint32(res.Int64)
  189. }
  190. return true, nil
  191. case *uint64:
  192. var res sql.NullInt64
  193. if err := rows.Scan(&res); err != nil {
  194. return true, err
  195. }
  196. if res.Valid {
  197. *(bean.(*uint64)) = uint64(res.Int64)
  198. }
  199. return true, nil
  200. case *bool:
  201. var res sql.NullBool
  202. if err := rows.Scan(&res); err != nil {
  203. return true, err
  204. }
  205. if res.Valid {
  206. *(bean.(*bool)) = res.Bool
  207. }
  208. return true, nil
  209. }
  210. switch beanKind {
  211. case reflect.Struct:
  212. fields, err := rows.Columns()
  213. if err != nil {
  214. // WARN: Alougth rows return true, but get fields failed
  215. return true, err
  216. }
  217. scanResults, err := session.row2Slice(rows, fields, bean)
  218. if err != nil {
  219. return false, err
  220. }
  221. // close it before covert data
  222. rows.Close()
  223. dataStruct := rValue(bean)
  224. _, err = session.slice2Bean(scanResults, fields, bean, &dataStruct, table)
  225. if err != nil {
  226. return true, err
  227. }
  228. return true, session.executeProcessors()
  229. case reflect.Slice:
  230. err = rows.ScanSlice(bean)
  231. case reflect.Map:
  232. err = rows.ScanMap(bean)
  233. case reflect.String, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
  234. reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  235. err = rows.Scan(bean)
  236. default:
  237. err = rows.Scan(bean)
  238. }
  239. return true, err
  240. }
  241. func (session *Session) cacheGet(bean interface{}, sqlStr string, args ...interface{}) (has bool, err error) {
  242. // if has no reftable, then don't use cache currently
  243. if !session.canCache() {
  244. return false, ErrCacheFailed
  245. }
  246. for _, filter := range session.engine.dialect.Filters() {
  247. sqlStr = filter.Do(sqlStr, session.engine.dialect, session.statement.RefTable)
  248. }
  249. newsql := session.statement.convertIDSQL(sqlStr)
  250. if newsql == "" {
  251. return false, ErrCacheFailed
  252. }
  253. tableName := session.statement.TableName()
  254. cacher := session.engine.getCacher(tableName)
  255. session.engine.logger.Debug("[cacheGet] find sql:", newsql, args)
  256. table := session.statement.RefTable
  257. ids, err := core.GetCacheSql(cacher, tableName, newsql, args)
  258. if err != nil {
  259. var res = make([]string, len(table.PrimaryKeys))
  260. rows, err := session.NoCache().queryRows(newsql, args...)
  261. if err != nil {
  262. return false, err
  263. }
  264. defer rows.Close()
  265. if rows.Next() {
  266. err = rows.ScanSlice(&res)
  267. if err != nil {
  268. return false, err
  269. }
  270. } else {
  271. return false, ErrCacheFailed
  272. }
  273. var pk core.PK = make([]interface{}, len(table.PrimaryKeys))
  274. for i, col := range table.PKColumns() {
  275. if col.SQLType.IsText() {
  276. pk[i] = res[i]
  277. } else if col.SQLType.IsNumeric() {
  278. n, err := strconv.ParseInt(res[i], 10, 64)
  279. if err != nil {
  280. return false, err
  281. }
  282. pk[i] = n
  283. } else {
  284. return false, errors.New("unsupported")
  285. }
  286. }
  287. ids = []core.PK{pk}
  288. session.engine.logger.Debug("[cacheGet] cache ids:", newsql, ids)
  289. err = core.PutCacheSql(cacher, ids, tableName, newsql, args)
  290. if err != nil {
  291. return false, err
  292. }
  293. } else {
  294. session.engine.logger.Debug("[cacheGet] cache hit sql:", newsql, ids)
  295. }
  296. if len(ids) > 0 {
  297. structValue := reflect.Indirect(reflect.ValueOf(bean))
  298. id := ids[0]
  299. session.engine.logger.Debug("[cacheGet] get bean:", tableName, id)
  300. sid, err := id.ToString()
  301. if err != nil {
  302. return false, err
  303. }
  304. cacheBean := cacher.GetBean(tableName, sid)
  305. if cacheBean == nil {
  306. cacheBean = bean
  307. has, err = session.nocacheGet(reflect.Struct, table, cacheBean, sqlStr, args...)
  308. if err != nil || !has {
  309. return has, err
  310. }
  311. session.engine.logger.Debug("[cacheGet] cache bean:", tableName, id, cacheBean)
  312. cacher.PutBean(tableName, sid, cacheBean)
  313. } else {
  314. session.engine.logger.Debug("[cacheGet] cache hit bean:", tableName, id, cacheBean)
  315. has = true
  316. }
  317. structValue.Set(reflect.Indirect(reflect.ValueOf(cacheBean)))
  318. return has, nil
  319. }
  320. return false, nil
  321. }