Simple and Powerful ORM for Go, support mysql,postgres,tidb,sqlite3,mssql,oracle https://xorm.io
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

889 lines
25KB

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