session.go 23 KB

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