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.
 
 

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