session.go 24 KB

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