session.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. // Copyright 2015 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. "context"
  7. "database/sql"
  8. "errors"
  9. "fmt"
  10. "hash/crc32"
  11. "reflect"
  12. "strings"
  13. "time"
  14. "xorm.io/core"
  15. )
  16. type sessionType int
  17. const (
  18. engineSession sessionType = iota
  19. groupSession
  20. )
  21. // Session keep a pointer to sql.DB and provides all execution of all
  22. // kind of database operations.
  23. type Session struct {
  24. db *core.DB
  25. engine *Engine
  26. tx *core.Tx
  27. statement Statement
  28. isAutoCommit bool
  29. isCommitedOrRollbacked bool
  30. isAutoClose bool
  31. // Automatically reset the statement after operations that execute a SQL
  32. // query such as Count(), Find(), Get(), ...
  33. autoResetStatement bool
  34. // !nashtsai! storing these beans due to yet committed tx
  35. afterInsertBeans map[interface{}]*[]func(interface{})
  36. afterUpdateBeans map[interface{}]*[]func(interface{})
  37. afterDeleteBeans map[interface{}]*[]func(interface{})
  38. // --
  39. beforeClosures []func(interface{})
  40. afterClosures []func(interface{})
  41. afterProcessors []executedProcessor
  42. prepareStmt bool
  43. stmtCache map[uint32]*core.Stmt //key: hash.Hash32 of (queryStr, len(queryStr))
  44. // !evalphobia! stored the last executed query on this session
  45. //beforeSQLExec func(string, ...interface{})
  46. lastSQL string
  47. lastSQLArgs []interface{}
  48. ctx context.Context
  49. sessionType sessionType
  50. }
  51. // Clone copy all the session's content and return a new session
  52. func (session *Session) Clone() *Session {
  53. var sess = *session
  54. return &sess
  55. }
  56. // Init reset the session as the init status.
  57. func (session *Session) Init() {
  58. session.statement.Init()
  59. session.statement.Engine = session.engine
  60. session.isAutoCommit = true
  61. session.isCommitedOrRollbacked = false
  62. session.isAutoClose = false
  63. session.autoResetStatement = true
  64. session.prepareStmt = false
  65. // !nashtsai! is lazy init better?
  66. session.afterInsertBeans = make(map[interface{}]*[]func(interface{}), 0)
  67. session.afterUpdateBeans = make(map[interface{}]*[]func(interface{}), 0)
  68. session.afterDeleteBeans = make(map[interface{}]*[]func(interface{}), 0)
  69. session.beforeClosures = make([]func(interface{}), 0)
  70. session.afterClosures = make([]func(interface{}), 0)
  71. session.stmtCache = make(map[uint32]*core.Stmt)
  72. session.afterProcessors = make([]executedProcessor, 0)
  73. session.lastSQL = ""
  74. session.lastSQLArgs = []interface{}{}
  75. session.ctx = session.engine.defaultContext
  76. }
  77. // Close release the connection from pool
  78. func (session *Session) Close() {
  79. for _, v := range session.stmtCache {
  80. v.Close()
  81. }
  82. if session.db != nil {
  83. // When Close be called, if session is a transaction and do not call
  84. // Commit or Rollback, then call Rollback.
  85. if session.tx != nil && !session.isCommitedOrRollbacked {
  86. session.Rollback()
  87. }
  88. session.tx = nil
  89. session.stmtCache = nil
  90. session.db = nil
  91. }
  92. }
  93. // ContextCache enable context cache or not
  94. func (session *Session) ContextCache(context ContextCache) *Session {
  95. session.statement.context = context
  96. return session
  97. }
  98. // IsClosed returns if session is closed
  99. func (session *Session) IsClosed() bool {
  100. return session.db == nil
  101. }
  102. func (session *Session) resetStatement() {
  103. if session.autoResetStatement {
  104. session.statement.Init()
  105. }
  106. }
  107. // Prepare set a flag to session that should be prepare statement before execute query
  108. func (session *Session) Prepare() *Session {
  109. session.prepareStmt = true
  110. return session
  111. }
  112. // Before Apply before Processor, affected bean is passed to closure arg
  113. func (session *Session) Before(closures func(interface{})) *Session {
  114. if closures != nil {
  115. session.beforeClosures = append(session.beforeClosures, closures)
  116. }
  117. return session
  118. }
  119. // After Apply after Processor, affected bean is passed to closure arg
  120. func (session *Session) After(closures func(interface{})) *Session {
  121. if closures != nil {
  122. session.afterClosures = append(session.afterClosures, closures)
  123. }
  124. return session
  125. }
  126. // Table can input a string or pointer to struct for special a table to operate.
  127. func (session *Session) Table(tableNameOrBean interface{}) *Session {
  128. session.statement.Table(tableNameOrBean)
  129. return session
  130. }
  131. // Alias set the table alias
  132. func (session *Session) Alias(alias string) *Session {
  133. session.statement.Alias(alias)
  134. return session
  135. }
  136. // NoCascade indicate that no cascade load child object
  137. func (session *Session) NoCascade() *Session {
  138. session.statement.UseCascade = false
  139. return session
  140. }
  141. // ForUpdate Set Read/Write locking for UPDATE
  142. func (session *Session) ForUpdate() *Session {
  143. session.statement.IsForUpdate = true
  144. return session
  145. }
  146. // NoAutoCondition disable generate SQL condition from beans
  147. func (session *Session) NoAutoCondition(no ...bool) *Session {
  148. session.statement.NoAutoCondition(no...)
  149. return session
  150. }
  151. // Limit provide limit and offset query condition
  152. func (session *Session) Limit(limit int, start ...int) *Session {
  153. session.statement.Limit(limit, start...)
  154. return session
  155. }
  156. // OrderBy provide order by query condition, the input parameter is the content
  157. // after order by on a sql statement.
  158. func (session *Session) OrderBy(order string) *Session {
  159. session.statement.OrderBy(order)
  160. return session
  161. }
  162. // Desc provide desc order by query condition, the input parameters are columns.
  163. func (session *Session) Desc(colNames ...string) *Session {
  164. session.statement.Desc(colNames...)
  165. return session
  166. }
  167. // Asc provide asc order by query condition, the input parameters are columns.
  168. func (session *Session) Asc(colNames ...string) *Session {
  169. session.statement.Asc(colNames...)
  170. return session
  171. }
  172. // StoreEngine is only avialble mysql dialect currently
  173. func (session *Session) StoreEngine(storeEngine string) *Session {
  174. session.statement.StoreEngine = storeEngine
  175. return session
  176. }
  177. // Charset is only avialble mysql dialect currently
  178. func (session *Session) Charset(charset string) *Session {
  179. session.statement.Charset = charset
  180. return session
  181. }
  182. // Cascade indicates if loading sub Struct
  183. func (session *Session) Cascade(trueOrFalse ...bool) *Session {
  184. if len(trueOrFalse) >= 1 {
  185. session.statement.UseCascade = trueOrFalse[0]
  186. }
  187. return session
  188. }
  189. // NoCache ask this session do not retrieve data from cache system and
  190. // get data from database directly.
  191. func (session *Session) NoCache() *Session {
  192. session.statement.UseCache = false
  193. return session
  194. }
  195. // Join join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
  196. func (session *Session) Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *Session {
  197. session.statement.Join(joinOperator, tablename, condition, args...)
  198. return session
  199. }
  200. // GroupBy Generate Group By statement
  201. func (session *Session) GroupBy(keys string) *Session {
  202. session.statement.GroupBy(keys)
  203. return session
  204. }
  205. // Having Generate Having statement
  206. func (session *Session) Having(conditions string) *Session {
  207. session.statement.Having(conditions)
  208. return session
  209. }
  210. // DB db return the wrapper of sql.DB
  211. func (session *Session) DB() *core.DB {
  212. if session.db == nil {
  213. session.db = session.engine.db
  214. session.stmtCache = make(map[uint32]*core.Stmt, 0)
  215. }
  216. return session.db
  217. }
  218. func cleanupProcessorsClosures(slices *[]func(interface{})) {
  219. if len(*slices) > 0 {
  220. *slices = make([]func(interface{}), 0)
  221. }
  222. }
  223. func (session *Session) canCache() bool {
  224. if session.statement.RefTable == nil ||
  225. session.statement.JoinStr != "" ||
  226. session.statement.RawSQL != "" ||
  227. !session.statement.UseCache ||
  228. session.statement.IsForUpdate ||
  229. session.tx != nil ||
  230. len(session.statement.selectStr) > 0 {
  231. return false
  232. }
  233. return true
  234. }
  235. func (session *Session) doPrepare(db *core.DB, sqlStr string) (stmt *core.Stmt, err error) {
  236. crc := crc32.ChecksumIEEE([]byte(sqlStr))
  237. // TODO try hash(sqlStr+len(sqlStr))
  238. var has bool
  239. stmt, has = session.stmtCache[crc]
  240. if !has {
  241. stmt, err = db.PrepareContext(session.ctx, sqlStr)
  242. if err != nil {
  243. return nil, err
  244. }
  245. session.stmtCache[crc] = stmt
  246. }
  247. return
  248. }
  249. func (session *Session) getField(dataStruct *reflect.Value, key string, table *core.Table, idx int) (*reflect.Value, error) {
  250. var col *core.Column
  251. if col = table.GetColumnIdx(key, idx); col == nil {
  252. return nil, ErrFieldIsNotExist{key, table.Name}
  253. }
  254. fieldValue, err := col.ValueOfV(dataStruct)
  255. if err != nil {
  256. return nil, err
  257. }
  258. if !fieldValue.IsValid() || !fieldValue.CanSet() {
  259. return nil, ErrFieldIsNotValid{key, table.Name}
  260. }
  261. return fieldValue, nil
  262. }
  263. // Cell cell is a result of one column field
  264. type Cell *interface{}
  265. func (session *Session) rows2Beans(rows *core.Rows, fields []string,
  266. table *core.Table, newElemFunc func([]string) reflect.Value,
  267. sliceValueSetFunc func(*reflect.Value, core.PK) error) error {
  268. for rows.Next() {
  269. var newValue = newElemFunc(fields)
  270. bean := newValue.Interface()
  271. dataStruct := newValue.Elem()
  272. // handle beforeClosures
  273. scanResults, err := session.row2Slice(rows, fields, bean)
  274. if err != nil {
  275. return err
  276. }
  277. pk, err := session.slice2Bean(scanResults, fields, bean, &dataStruct, table)
  278. if err != nil {
  279. return err
  280. }
  281. session.afterProcessors = append(session.afterProcessors, executedProcessor{
  282. fun: func(*Session, interface{}) error {
  283. return sliceValueSetFunc(&newValue, pk)
  284. },
  285. session: session,
  286. bean: bean,
  287. })
  288. }
  289. return nil
  290. }
  291. func (session *Session) row2Slice(rows *core.Rows, fields []string, bean interface{}) ([]interface{}, error) {
  292. for _, closure := range session.beforeClosures {
  293. closure(bean)
  294. }
  295. scanResults := make([]interface{}, len(fields))
  296. for i := 0; i < len(fields); i++ {
  297. var cell interface{}
  298. scanResults[i] = &cell
  299. }
  300. if err := rows.Scan(scanResults...); err != nil {
  301. return nil, err
  302. }
  303. if b, hasBeforeSet := bean.(BeforeSetProcessor); hasBeforeSet {
  304. for ii, key := range fields {
  305. b.BeforeSet(key, Cell(scanResults[ii].(*interface{})))
  306. }
  307. }
  308. return scanResults, nil
  309. }
  310. func (session *Session) slice2Bean(scanResults []interface{}, fields []string, bean interface{}, dataStruct *reflect.Value, table *core.Table) (core.PK, error) {
  311. defer func() {
  312. if b, hasAfterSet := bean.(AfterSetProcessor); hasAfterSet {
  313. for ii, key := range fields {
  314. b.AfterSet(key, Cell(scanResults[ii].(*interface{})))
  315. }
  316. }
  317. }()
  318. // handle afterClosures
  319. for _, closure := range session.afterClosures {
  320. session.afterProcessors = append(session.afterProcessors, executedProcessor{
  321. fun: func(sess *Session, bean interface{}) error {
  322. closure(bean)
  323. return nil
  324. },
  325. session: session,
  326. bean: bean,
  327. })
  328. }
  329. if a, has := bean.(AfterLoadProcessor); has {
  330. session.afterProcessors = append(session.afterProcessors, executedProcessor{
  331. fun: func(sess *Session, bean interface{}) error {
  332. a.AfterLoad()
  333. return nil
  334. },
  335. session: session,
  336. bean: bean,
  337. })
  338. }
  339. if a, has := bean.(AfterLoadSessionProcessor); has {
  340. session.afterProcessors = append(session.afterProcessors, executedProcessor{
  341. fun: func(sess *Session, bean interface{}) error {
  342. a.AfterLoad(sess)
  343. return nil
  344. },
  345. session: session,
  346. bean: bean,
  347. })
  348. }
  349. var tempMap = make(map[string]int)
  350. var pk core.PK
  351. for ii, key := range fields {
  352. var idx int
  353. var ok bool
  354. var lKey = strings.ToLower(key)
  355. if idx, ok = tempMap[lKey]; !ok {
  356. idx = 0
  357. } else {
  358. idx = idx + 1
  359. }
  360. tempMap[lKey] = idx
  361. fieldValue, err := session.getField(dataStruct, key, table, idx)
  362. if err != nil {
  363. if !strings.Contains(err.Error(), "is not valid") {
  364. session.engine.logger.Warn(err)
  365. }
  366. continue
  367. }
  368. if fieldValue == nil {
  369. continue
  370. }
  371. rawValue := reflect.Indirect(reflect.ValueOf(scanResults[ii]))
  372. // if row is null then ignore
  373. if rawValue.Interface() == nil {
  374. continue
  375. }
  376. if fieldValue.CanAddr() {
  377. if structConvert, ok := fieldValue.Addr().Interface().(core.Conversion); ok {
  378. if data, err := value2Bytes(&rawValue); err == nil {
  379. if err := structConvert.FromDB(data); err != nil {
  380. return nil, err
  381. }
  382. } else {
  383. return nil, err
  384. }
  385. continue
  386. }
  387. }
  388. if _, ok := fieldValue.Interface().(core.Conversion); ok {
  389. if data, err := value2Bytes(&rawValue); err == nil {
  390. if fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil() {
  391. fieldValue.Set(reflect.New(fieldValue.Type().Elem()))
  392. }
  393. fieldValue.Interface().(core.Conversion).FromDB(data)
  394. } else {
  395. return nil, err
  396. }
  397. continue
  398. }
  399. rawValueType := reflect.TypeOf(rawValue.Interface())
  400. vv := reflect.ValueOf(rawValue.Interface())
  401. col := table.GetColumnIdx(key, idx)
  402. if col.IsPrimaryKey {
  403. pk = append(pk, rawValue.Interface())
  404. }
  405. fieldType := fieldValue.Type()
  406. hasAssigned := false
  407. if col.SQLType.IsJson() {
  408. var bs []byte
  409. if rawValueType.Kind() == reflect.String {
  410. bs = []byte(vv.String())
  411. } else if rawValueType.ConvertibleTo(core.BytesType) {
  412. bs = vv.Bytes()
  413. } else {
  414. return nil, fmt.Errorf("unsupported database data type: %s %v", key, rawValueType.Kind())
  415. }
  416. hasAssigned = true
  417. if len(bs) > 0 {
  418. if fieldType.Kind() == reflect.String {
  419. fieldValue.SetString(string(bs))
  420. continue
  421. }
  422. if fieldValue.CanAddr() {
  423. err := DefaultJSONHandler.Unmarshal(bs, fieldValue.Addr().Interface())
  424. if err != nil {
  425. return nil, err
  426. }
  427. } else {
  428. x := reflect.New(fieldType)
  429. err := DefaultJSONHandler.Unmarshal(bs, x.Interface())
  430. if err != nil {
  431. return nil, err
  432. }
  433. fieldValue.Set(x.Elem())
  434. }
  435. }
  436. continue
  437. }
  438. switch fieldType.Kind() {
  439. case reflect.Complex64, reflect.Complex128:
  440. // TODO: reimplement this
  441. var bs []byte
  442. if rawValueType.Kind() == reflect.String {
  443. bs = []byte(vv.String())
  444. } else if rawValueType.ConvertibleTo(core.BytesType) {
  445. bs = vv.Bytes()
  446. }
  447. hasAssigned = true
  448. if len(bs) > 0 {
  449. if fieldValue.CanAddr() {
  450. err := DefaultJSONHandler.Unmarshal(bs, fieldValue.Addr().Interface())
  451. if err != nil {
  452. return nil, err
  453. }
  454. } else {
  455. x := reflect.New(fieldType)
  456. err := DefaultJSONHandler.Unmarshal(bs, x.Interface())
  457. if err != nil {
  458. return nil, err
  459. }
  460. fieldValue.Set(x.Elem())
  461. }
  462. }
  463. case reflect.Slice, reflect.Array:
  464. switch rawValueType.Kind() {
  465. case reflect.Slice, reflect.Array:
  466. switch rawValueType.Elem().Kind() {
  467. case reflect.Uint8:
  468. if fieldType.Elem().Kind() == reflect.Uint8 {
  469. hasAssigned = true
  470. if col.SQLType.IsText() {
  471. x := reflect.New(fieldType)
  472. err := DefaultJSONHandler.Unmarshal(vv.Bytes(), x.Interface())
  473. if err != nil {
  474. return nil, err
  475. }
  476. fieldValue.Set(x.Elem())
  477. } else {
  478. if fieldValue.Len() > 0 {
  479. for i := 0; i < fieldValue.Len(); i++ {
  480. if i < vv.Len() {
  481. fieldValue.Index(i).Set(vv.Index(i))
  482. }
  483. }
  484. } else {
  485. for i := 0; i < vv.Len(); i++ {
  486. fieldValue.Set(reflect.Append(*fieldValue, vv.Index(i)))
  487. }
  488. }
  489. }
  490. }
  491. }
  492. }
  493. case reflect.String:
  494. if rawValueType.Kind() == reflect.String {
  495. hasAssigned = true
  496. fieldValue.SetString(vv.String())
  497. }
  498. case reflect.Bool:
  499. if rawValueType.Kind() == reflect.Bool {
  500. hasAssigned = true
  501. fieldValue.SetBool(vv.Bool())
  502. }
  503. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  504. switch rawValueType.Kind() {
  505. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  506. hasAssigned = true
  507. fieldValue.SetInt(vv.Int())
  508. }
  509. case reflect.Float32, reflect.Float64:
  510. switch rawValueType.Kind() {
  511. case reflect.Float32, reflect.Float64:
  512. hasAssigned = true
  513. fieldValue.SetFloat(vv.Float())
  514. }
  515. case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
  516. switch rawValueType.Kind() {
  517. case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
  518. hasAssigned = true
  519. fieldValue.SetUint(vv.Uint())
  520. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  521. hasAssigned = true
  522. fieldValue.SetUint(uint64(vv.Int()))
  523. }
  524. case reflect.Struct:
  525. if fieldType.ConvertibleTo(core.TimeType) {
  526. dbTZ := session.engine.DatabaseTZ
  527. if col.TimeZone != nil {
  528. dbTZ = col.TimeZone
  529. }
  530. if rawValueType == core.TimeType {
  531. hasAssigned = true
  532. t := vv.Convert(core.TimeType).Interface().(time.Time)
  533. z, _ := t.Zone()
  534. // set new location if database don't save timezone or give an incorrect timezone
  535. if len(z) == 0 || t.Year() == 0 || t.Location().String() != dbTZ.String() { // !nashtsai! HACK tmp work around for lib/pq doesn't properly time with location
  536. session.engine.logger.Debugf("empty zone key[%v] : %v | zone: %v | location: %+v\n", key, t, z, *t.Location())
  537. t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(),
  538. t.Minute(), t.Second(), t.Nanosecond(), dbTZ)
  539. }
  540. t = t.In(session.engine.TZLocation)
  541. fieldValue.Set(reflect.ValueOf(t).Convert(fieldType))
  542. } else if rawValueType == core.IntType || rawValueType == core.Int64Type ||
  543. rawValueType == core.Int32Type {
  544. hasAssigned = true
  545. t := time.Unix(vv.Int(), 0).In(session.engine.TZLocation)
  546. fieldValue.Set(reflect.ValueOf(t).Convert(fieldType))
  547. } else {
  548. if d, ok := vv.Interface().([]uint8); ok {
  549. hasAssigned = true
  550. t, err := session.byte2Time(col, d)
  551. if err != nil {
  552. session.engine.logger.Error("byte2Time error:", err.Error())
  553. hasAssigned = false
  554. } else {
  555. fieldValue.Set(reflect.ValueOf(t).Convert(fieldType))
  556. }
  557. } else if d, ok := vv.Interface().(string); ok {
  558. hasAssigned = true
  559. t, err := session.str2Time(col, d)
  560. if err != nil {
  561. session.engine.logger.Error("byte2Time error:", err.Error())
  562. hasAssigned = false
  563. } else {
  564. fieldValue.Set(reflect.ValueOf(t).Convert(fieldType))
  565. }
  566. } else {
  567. return nil, fmt.Errorf("rawValueType is %v, value is %v", rawValueType, vv.Interface())
  568. }
  569. }
  570. } else if nulVal, ok := fieldValue.Addr().Interface().(sql.Scanner); ok {
  571. // !<winxxp>! 增加支持sql.Scanner接口的结构,如sql.NullString
  572. hasAssigned = true
  573. if err := nulVal.Scan(vv.Interface()); err != nil {
  574. session.engine.logger.Error("sql.Sanner error:", err.Error())
  575. hasAssigned = false
  576. }
  577. } else if col.SQLType.IsJson() {
  578. if rawValueType.Kind() == reflect.String {
  579. hasAssigned = true
  580. x := reflect.New(fieldType)
  581. if len([]byte(vv.String())) > 0 {
  582. err := DefaultJSONHandler.Unmarshal([]byte(vv.String()), x.Interface())
  583. if err != nil {
  584. return nil, err
  585. }
  586. fieldValue.Set(x.Elem())
  587. }
  588. } else if rawValueType.Kind() == reflect.Slice {
  589. hasAssigned = true
  590. x := reflect.New(fieldType)
  591. if len(vv.Bytes()) > 0 {
  592. err := DefaultJSONHandler.Unmarshal(vv.Bytes(), x.Interface())
  593. if err != nil {
  594. return nil, err
  595. }
  596. fieldValue.Set(x.Elem())
  597. }
  598. }
  599. } else if session.statement.UseCascade {
  600. table, err := session.engine.autoMapType(*fieldValue)
  601. if err != nil {
  602. return nil, err
  603. }
  604. hasAssigned = true
  605. if len(table.PrimaryKeys) != 1 {
  606. return nil, errors.New("unsupported non or composited primary key cascade")
  607. }
  608. var pk = make(core.PK, len(table.PrimaryKeys))
  609. pk[0], err = asKind(vv, rawValueType)
  610. if err != nil {
  611. return nil, err
  612. }
  613. if !isPKZero(pk) {
  614. // !nashtsai! TODO for hasOne relationship, it's preferred to use join query for eager fetch
  615. // however, also need to consider adding a 'lazy' attribute to xorm tag which allow hasOne
  616. // property to be fetched lazily
  617. structInter := reflect.New(fieldValue.Type())
  618. has, err := session.ID(pk).NoCascade().get(structInter.Interface())
  619. if err != nil {
  620. return nil, err
  621. }
  622. if has {
  623. fieldValue.Set(structInter.Elem())
  624. } else {
  625. return nil, errors.New("cascade obj is not exist")
  626. }
  627. }
  628. }
  629. case reflect.Ptr:
  630. // !nashtsai! TODO merge duplicated codes above
  631. switch fieldType {
  632. // following types case matching ptr's native type, therefore assign ptr directly
  633. case core.PtrStringType:
  634. if rawValueType.Kind() == reflect.String {
  635. x := vv.String()
  636. hasAssigned = true
  637. fieldValue.Set(reflect.ValueOf(&x))
  638. }
  639. case core.PtrBoolType:
  640. if rawValueType.Kind() == reflect.Bool {
  641. x := vv.Bool()
  642. hasAssigned = true
  643. fieldValue.Set(reflect.ValueOf(&x))
  644. }
  645. case core.PtrTimeType:
  646. if rawValueType == core.PtrTimeType {
  647. hasAssigned = true
  648. var x = rawValue.Interface().(time.Time)
  649. fieldValue.Set(reflect.ValueOf(&x))
  650. }
  651. case core.PtrFloat64Type:
  652. if rawValueType.Kind() == reflect.Float64 {
  653. x := vv.Float()
  654. hasAssigned = true
  655. fieldValue.Set(reflect.ValueOf(&x))
  656. }
  657. case core.PtrUint64Type:
  658. if rawValueType.Kind() == reflect.Int64 {
  659. var x = uint64(vv.Int())
  660. hasAssigned = true
  661. fieldValue.Set(reflect.ValueOf(&x))
  662. }
  663. case core.PtrInt64Type:
  664. if rawValueType.Kind() == reflect.Int64 {
  665. x := vv.Int()
  666. hasAssigned = true
  667. fieldValue.Set(reflect.ValueOf(&x))
  668. }
  669. case core.PtrFloat32Type:
  670. if rawValueType.Kind() == reflect.Float64 {
  671. var x = float32(vv.Float())
  672. hasAssigned = true
  673. fieldValue.Set(reflect.ValueOf(&x))
  674. }
  675. case core.PtrIntType:
  676. if rawValueType.Kind() == reflect.Int64 {
  677. var x = int(vv.Int())
  678. hasAssigned = true
  679. fieldValue.Set(reflect.ValueOf(&x))
  680. }
  681. case core.PtrInt32Type:
  682. if rawValueType.Kind() == reflect.Int64 {
  683. var x = int32(vv.Int())
  684. hasAssigned = true
  685. fieldValue.Set(reflect.ValueOf(&x))
  686. }
  687. case core.PtrInt8Type:
  688. if rawValueType.Kind() == reflect.Int64 {
  689. var x = int8(vv.Int())
  690. hasAssigned = true
  691. fieldValue.Set(reflect.ValueOf(&x))
  692. }
  693. case core.PtrInt16Type:
  694. if rawValueType.Kind() == reflect.Int64 {
  695. var x = int16(vv.Int())
  696. hasAssigned = true
  697. fieldValue.Set(reflect.ValueOf(&x))
  698. }
  699. case core.PtrUintType:
  700. if rawValueType.Kind() == reflect.Int64 {
  701. var x = uint(vv.Int())
  702. hasAssigned = true
  703. fieldValue.Set(reflect.ValueOf(&x))
  704. }
  705. case core.PtrUint32Type:
  706. if rawValueType.Kind() == reflect.Int64 {
  707. var x = uint32(vv.Int())
  708. hasAssigned = true
  709. fieldValue.Set(reflect.ValueOf(&x))
  710. }
  711. case core.Uint8Type:
  712. if rawValueType.Kind() == reflect.Int64 {
  713. var x = uint8(vv.Int())
  714. hasAssigned = true
  715. fieldValue.Set(reflect.ValueOf(&x))
  716. }
  717. case core.Uint16Type:
  718. if rawValueType.Kind() == reflect.Int64 {
  719. var x = uint16(vv.Int())
  720. hasAssigned = true
  721. fieldValue.Set(reflect.ValueOf(&x))
  722. }
  723. case core.Complex64Type:
  724. var x complex64
  725. if len([]byte(vv.String())) > 0 {
  726. err := DefaultJSONHandler.Unmarshal([]byte(vv.String()), &x)
  727. if err != nil {
  728. return nil, err
  729. }
  730. fieldValue.Set(reflect.ValueOf(&x))
  731. }
  732. hasAssigned = true
  733. case core.Complex128Type:
  734. var x complex128
  735. if len([]byte(vv.String())) > 0 {
  736. err := DefaultJSONHandler.Unmarshal([]byte(vv.String()), &x)
  737. if err != nil {
  738. return nil, err
  739. }
  740. fieldValue.Set(reflect.ValueOf(&x))
  741. }
  742. hasAssigned = true
  743. } // switch fieldType
  744. } // switch fieldType.Kind()
  745. // !nashtsai! for value can't be assigned directly fallback to convert to []byte then back to value
  746. if !hasAssigned {
  747. data, err := value2Bytes(&rawValue)
  748. if err != nil {
  749. return nil, err
  750. }
  751. if err = session.bytes2Value(col, fieldValue, data); err != nil {
  752. return nil, err
  753. }
  754. }
  755. }
  756. return pk, nil
  757. }
  758. // saveLastSQL stores executed query information
  759. func (session *Session) saveLastSQL(sql string, args ...interface{}) {
  760. session.lastSQL = sql
  761. session.lastSQLArgs = args
  762. session.engine.logSQL(sql, args...)
  763. }
  764. // LastSQL returns last query information
  765. func (session *Session) LastSQL() (string, []interface{}) {
  766. return session.lastSQL, session.lastSQLArgs
  767. }
  768. // Unscoped always disable struct tag "deleted"
  769. func (session *Session) Unscoped() *Session {
  770. session.statement.Unscoped()
  771. return session
  772. }
  773. func (session *Session) incrVersionFieldValue(fieldValue *reflect.Value) {
  774. switch fieldValue.Kind() {
  775. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  776. fieldValue.SetInt(fieldValue.Int() + 1)
  777. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  778. fieldValue.SetUint(fieldValue.Uint() + 1)
  779. }
  780. }