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.
 
 
 
 
 

892 line
25 KiB

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