session_get.go 9.4 KB

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