session.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  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 {
  238. var col *core.Column
  239. if col = table.GetColumnIdx(key, idx); col == nil {
  240. //session.engine.logger.Warnf("table %v has no column %v. %v", table.Name, key, table.ColumnsSeq())
  241. return nil
  242. }
  243. fieldValue, err := col.ValueOfV(dataStruct)
  244. if err != nil {
  245. session.engine.logger.Error(err)
  246. return nil
  247. }
  248. if !fieldValue.IsValid() || !fieldValue.CanSet() {
  249. session.engine.logger.Warnf("table %v's column %v is not valid or cannot set", table.Name, key)
  250. return nil
  251. }
  252. return fieldValue
  253. }
  254. // Cell cell is a result of one column field
  255. type Cell *interface{}
  256. func (session *Session) rows2Beans(rows *core.Rows, fields []string,
  257. table *core.Table, newElemFunc func([]string) reflect.Value,
  258. sliceValueSetFunc func(*reflect.Value, core.PK) error) error {
  259. for rows.Next() {
  260. var newValue = newElemFunc(fields)
  261. bean := newValue.Interface()
  262. dataStruct := newValue.Elem()
  263. // handle beforeClosures
  264. scanResults, err := session.row2Slice(rows, fields, bean)
  265. if err != nil {
  266. return err
  267. }
  268. pk, err := session.slice2Bean(scanResults, fields, bean, &dataStruct, table)
  269. if err != nil {
  270. return err
  271. }
  272. session.afterProcessors = append(session.afterProcessors, executedProcessor{
  273. fun: func(*Session, interface{}) error {
  274. return sliceValueSetFunc(&newValue, pk)
  275. },
  276. session: session,
  277. bean: bean,
  278. })
  279. }
  280. return nil
  281. }
  282. func (session *Session) row2Slice(rows *core.Rows, fields []string, bean interface{}) ([]interface{}, error) {
  283. for _, closure := range session.beforeClosures {
  284. closure(bean)
  285. }
  286. scanResults := make([]interface{}, len(fields))
  287. for i := 0; i < len(fields); i++ {
  288. var cell interface{}
  289. scanResults[i] = &cell
  290. }
  291. if err := rows.Scan(scanResults...); err != nil {
  292. return nil, err
  293. }
  294. if b, hasBeforeSet := bean.(BeforeSetProcessor); hasBeforeSet {
  295. for ii, key := range fields {
  296. b.BeforeSet(key, Cell(scanResults[ii].(*interface{})))
  297. }
  298. }
  299. return scanResults, nil
  300. }
  301. func (session *Session) slice2Bean(scanResults []interface{}, fields []string, bean interface{}, dataStruct *reflect.Value, table *core.Table) (core.PK, error) {
  302. defer func() {
  303. if b, hasAfterSet := bean.(AfterSetProcessor); hasAfterSet {
  304. for ii, key := range fields {
  305. b.AfterSet(key, Cell(scanResults[ii].(*interface{})))
  306. }
  307. }
  308. }()
  309. // handle afterClosures
  310. for _, closure := range session.afterClosures {
  311. session.afterProcessors = append(session.afterProcessors, executedProcessor{
  312. fun: func(sess *Session, bean interface{}) error {
  313. closure(bean)
  314. return nil
  315. },
  316. session: session,
  317. bean: bean,
  318. })
  319. }
  320. if a, has := bean.(AfterLoadProcessor); has {
  321. session.afterProcessors = append(session.afterProcessors, executedProcessor{
  322. fun: func(sess *Session, bean interface{}) error {
  323. a.AfterLoad()
  324. return nil
  325. },
  326. session: session,
  327. bean: bean,
  328. })
  329. }
  330. if a, has := bean.(AfterLoadSessionProcessor); has {
  331. session.afterProcessors = append(session.afterProcessors, executedProcessor{
  332. fun: func(sess *Session, bean interface{}) error {
  333. a.AfterLoad(sess)
  334. return nil
  335. },
  336. session: session,
  337. bean: bean,
  338. })
  339. }
  340. var tempMap = make(map[string]int)
  341. var pk core.PK
  342. for ii, key := range fields {
  343. var idx int
  344. var ok bool
  345. var lKey = strings.ToLower(key)
  346. if idx, ok = tempMap[lKey]; !ok {
  347. idx = 0
  348. } else {
  349. idx = idx + 1
  350. }
  351. tempMap[lKey] = idx
  352. if fieldValue := session.getField(dataStruct, key, table, idx); fieldValue != nil {
  353. rawValue := reflect.Indirect(reflect.ValueOf(scanResults[ii]))
  354. // if row is null then ignore
  355. if rawValue.Interface() == nil {
  356. continue
  357. }
  358. if fieldValue.CanAddr() {
  359. if structConvert, ok := fieldValue.Addr().Interface().(core.Conversion); ok {
  360. if data, err := value2Bytes(&rawValue); err == nil {
  361. if err := structConvert.FromDB(data); err != nil {
  362. return nil, err
  363. }
  364. } else {
  365. return nil, err
  366. }
  367. continue
  368. }
  369. }
  370. if _, ok := fieldValue.Interface().(core.Conversion); ok {
  371. if data, err := value2Bytes(&rawValue); err == nil {
  372. if fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil() {
  373. fieldValue.Set(reflect.New(fieldValue.Type().Elem()))
  374. }
  375. fieldValue.Interface().(core.Conversion).FromDB(data)
  376. } else {
  377. return nil, err
  378. }
  379. continue
  380. }
  381. rawValueType := reflect.TypeOf(rawValue.Interface())
  382. vv := reflect.ValueOf(rawValue.Interface())
  383. col := table.GetColumnIdx(key, idx)
  384. if col.IsPrimaryKey {
  385. pk = append(pk, rawValue.Interface())
  386. }
  387. fieldType := fieldValue.Type()
  388. hasAssigned := false
  389. if col.SQLType.IsJson() {
  390. var bs []byte
  391. if rawValueType.Kind() == reflect.String {
  392. bs = []byte(vv.String())
  393. } else if rawValueType.ConvertibleTo(core.BytesType) {
  394. bs = vv.Bytes()
  395. } else {
  396. return nil, fmt.Errorf("unsupported database data type: %s %v", key, rawValueType.Kind())
  397. }
  398. hasAssigned = true
  399. if len(bs) > 0 {
  400. if fieldType.Kind() == reflect.String {
  401. fieldValue.SetString(string(bs))
  402. continue
  403. }
  404. if fieldValue.CanAddr() {
  405. err := json.Unmarshal(bs, fieldValue.Addr().Interface())
  406. if err != nil {
  407. return nil, err
  408. }
  409. } else {
  410. x := reflect.New(fieldType)
  411. err := json.Unmarshal(bs, x.Interface())
  412. if err != nil {
  413. return nil, err
  414. }
  415. fieldValue.Set(x.Elem())
  416. }
  417. }
  418. continue
  419. }
  420. switch fieldType.Kind() {
  421. case reflect.Complex64, reflect.Complex128:
  422. // TODO: reimplement this
  423. var bs []byte
  424. if rawValueType.Kind() == reflect.String {
  425. bs = []byte(vv.String())
  426. } else if rawValueType.ConvertibleTo(core.BytesType) {
  427. bs = vv.Bytes()
  428. }
  429. hasAssigned = true
  430. if len(bs) > 0 {
  431. if fieldValue.CanAddr() {
  432. err := json.Unmarshal(bs, fieldValue.Addr().Interface())
  433. if err != nil {
  434. return nil, err
  435. }
  436. } else {
  437. x := reflect.New(fieldType)
  438. err := json.Unmarshal(bs, x.Interface())
  439. if err != nil {
  440. return nil, err
  441. }
  442. fieldValue.Set(x.Elem())
  443. }
  444. }
  445. case reflect.Slice, reflect.Array:
  446. switch rawValueType.Kind() {
  447. case reflect.Slice, reflect.Array:
  448. switch rawValueType.Elem().Kind() {
  449. case reflect.Uint8:
  450. if fieldType.Elem().Kind() == reflect.Uint8 {
  451. hasAssigned = true
  452. if col.SQLType.IsText() {
  453. x := reflect.New(fieldType)
  454. err := json.Unmarshal(vv.Bytes(), x.Interface())
  455. if err != nil {
  456. return nil, err
  457. }
  458. fieldValue.Set(x.Elem())
  459. } else {
  460. if fieldValue.Len() > 0 {
  461. for i := 0; i < fieldValue.Len(); i++ {
  462. if i < vv.Len() {
  463. fieldValue.Index(i).Set(vv.Index(i))
  464. }
  465. }
  466. } else {
  467. for i := 0; i < vv.Len(); i++ {
  468. fieldValue.Set(reflect.Append(*fieldValue, vv.Index(i)))
  469. }
  470. }
  471. }
  472. }
  473. }
  474. }
  475. case reflect.String:
  476. if rawValueType.Kind() == reflect.String {
  477. hasAssigned = true
  478. fieldValue.SetString(vv.String())
  479. }
  480. case reflect.Bool:
  481. if rawValueType.Kind() == reflect.Bool {
  482. hasAssigned = true
  483. fieldValue.SetBool(vv.Bool())
  484. }
  485. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  486. switch rawValueType.Kind() {
  487. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  488. hasAssigned = true
  489. fieldValue.SetInt(vv.Int())
  490. }
  491. case reflect.Float32, reflect.Float64:
  492. switch rawValueType.Kind() {
  493. case reflect.Float32, reflect.Float64:
  494. hasAssigned = true
  495. fieldValue.SetFloat(vv.Float())
  496. }
  497. case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
  498. switch rawValueType.Kind() {
  499. case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
  500. hasAssigned = true
  501. fieldValue.SetUint(vv.Uint())
  502. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  503. hasAssigned = true
  504. fieldValue.SetUint(uint64(vv.Int()))
  505. }
  506. case reflect.Struct:
  507. if fieldType.ConvertibleTo(core.TimeType) {
  508. dbTZ := session.engine.DatabaseTZ
  509. if col.TimeZone != nil {
  510. dbTZ = col.TimeZone
  511. }
  512. if rawValueType == core.TimeType {
  513. hasAssigned = true
  514. t := vv.Convert(core.TimeType).Interface().(time.Time)
  515. z, _ := t.Zone()
  516. // set new location if database don't save timezone or give an incorrect timezone
  517. 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
  518. session.engine.logger.Debugf("empty zone key[%v] : %v | zone: %v | location: %+v\n", key, t, z, *t.Location())
  519. t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(),
  520. t.Minute(), t.Second(), t.Nanosecond(), dbTZ)
  521. }
  522. t = t.In(session.engine.TZLocation)
  523. fieldValue.Set(reflect.ValueOf(t).Convert(fieldType))
  524. } else if rawValueType == core.IntType || rawValueType == core.Int64Type ||
  525. rawValueType == core.Int32Type {
  526. hasAssigned = true
  527. t := time.Unix(vv.Int(), 0).In(session.engine.TZLocation)
  528. fieldValue.Set(reflect.ValueOf(t).Convert(fieldType))
  529. } else {
  530. if d, ok := vv.Interface().([]uint8); ok {
  531. hasAssigned = true
  532. t, err := session.byte2Time(col, d)
  533. if err != nil {
  534. session.engine.logger.Error("byte2Time error:", err.Error())
  535. hasAssigned = false
  536. } else {
  537. fieldValue.Set(reflect.ValueOf(t).Convert(fieldType))
  538. }
  539. } else if d, ok := vv.Interface().(string); ok {
  540. hasAssigned = true
  541. t, err := session.str2Time(col, d)
  542. if err != nil {
  543. session.engine.logger.Error("byte2Time error:", err.Error())
  544. hasAssigned = false
  545. } else {
  546. fieldValue.Set(reflect.ValueOf(t).Convert(fieldType))
  547. }
  548. } else {
  549. return nil, fmt.Errorf("rawValueType is %v, value is %v", rawValueType, vv.Interface())
  550. }
  551. }
  552. } else if nulVal, ok := fieldValue.Addr().Interface().(sql.Scanner); ok {
  553. // !<winxxp>! 增加支持sql.Scanner接口的结构,如sql.NullString
  554. hasAssigned = true
  555. if err := nulVal.Scan(vv.Interface()); err != nil {
  556. session.engine.logger.Error("sql.Sanner error:", err.Error())
  557. hasAssigned = false
  558. }
  559. } else if col.SQLType.IsJson() {
  560. if rawValueType.Kind() == reflect.String {
  561. hasAssigned = true
  562. x := reflect.New(fieldType)
  563. if len([]byte(vv.String())) > 0 {
  564. err := json.Unmarshal([]byte(vv.String()), x.Interface())
  565. if err != nil {
  566. return nil, err
  567. }
  568. fieldValue.Set(x.Elem())
  569. }
  570. } else if rawValueType.Kind() == reflect.Slice {
  571. hasAssigned = true
  572. x := reflect.New(fieldType)
  573. if len(vv.Bytes()) > 0 {
  574. err := json.Unmarshal(vv.Bytes(), x.Interface())
  575. if err != nil {
  576. return nil, err
  577. }
  578. fieldValue.Set(x.Elem())
  579. }
  580. }
  581. } else if session.statement.UseCascade {
  582. table, err := session.engine.autoMapType(*fieldValue)
  583. if err != nil {
  584. return nil, err
  585. }
  586. hasAssigned = true
  587. if len(table.PrimaryKeys) != 1 {
  588. return nil, errors.New("unsupported non or composited primary key cascade")
  589. }
  590. var pk = make(core.PK, len(table.PrimaryKeys))
  591. pk[0], err = asKind(vv, rawValueType)
  592. if err != nil {
  593. return nil, err
  594. }
  595. if !isPKZero(pk) {
  596. // !nashtsai! TODO for hasOne relationship, it's preferred to use join query for eager fetch
  597. // however, also need to consider adding a 'lazy' attribute to xorm tag which allow hasOne
  598. // property to be fetched lazily
  599. structInter := reflect.New(fieldValue.Type())
  600. has, err := session.ID(pk).NoCascade().get(structInter.Interface())
  601. if err != nil {
  602. return nil, err
  603. }
  604. if has {
  605. fieldValue.Set(structInter.Elem())
  606. } else {
  607. return nil, errors.New("cascade obj is not exist")
  608. }
  609. }
  610. }
  611. case reflect.Ptr:
  612. // !nashtsai! TODO merge duplicated codes above
  613. switch fieldType {
  614. // following types case matching ptr's native type, therefore assign ptr directly
  615. case core.PtrStringType:
  616. if rawValueType.Kind() == reflect.String {
  617. x := vv.String()
  618. hasAssigned = true
  619. fieldValue.Set(reflect.ValueOf(&x))
  620. }
  621. case core.PtrBoolType:
  622. if rawValueType.Kind() == reflect.Bool {
  623. x := vv.Bool()
  624. hasAssigned = true
  625. fieldValue.Set(reflect.ValueOf(&x))
  626. }
  627. case core.PtrTimeType:
  628. if rawValueType == core.PtrTimeType {
  629. hasAssigned = true
  630. var x = rawValue.Interface().(time.Time)
  631. fieldValue.Set(reflect.ValueOf(&x))
  632. }
  633. case core.PtrFloat64Type:
  634. if rawValueType.Kind() == reflect.Float64 {
  635. x := vv.Float()
  636. hasAssigned = true
  637. fieldValue.Set(reflect.ValueOf(&x))
  638. }
  639. case core.PtrUint64Type:
  640. if rawValueType.Kind() == reflect.Int64 {
  641. var x = uint64(vv.Int())
  642. hasAssigned = true
  643. fieldValue.Set(reflect.ValueOf(&x))
  644. }
  645. case core.PtrInt64Type:
  646. if rawValueType.Kind() == reflect.Int64 {
  647. x := vv.Int()
  648. hasAssigned = true
  649. fieldValue.Set(reflect.ValueOf(&x))
  650. }
  651. case core.PtrFloat32Type:
  652. if rawValueType.Kind() == reflect.Float64 {
  653. var x = float32(vv.Float())
  654. hasAssigned = true
  655. fieldValue.Set(reflect.ValueOf(&x))
  656. }
  657. case core.PtrIntType:
  658. if rawValueType.Kind() == reflect.Int64 {
  659. var x = int(vv.Int())
  660. hasAssigned = true
  661. fieldValue.Set(reflect.ValueOf(&x))
  662. }
  663. case core.PtrInt32Type:
  664. if rawValueType.Kind() == reflect.Int64 {
  665. var x = int32(vv.Int())
  666. hasAssigned = true
  667. fieldValue.Set(reflect.ValueOf(&x))
  668. }
  669. case core.PtrInt8Type:
  670. if rawValueType.Kind() == reflect.Int64 {
  671. var x = int8(vv.Int())
  672. hasAssigned = true
  673. fieldValue.Set(reflect.ValueOf(&x))
  674. }
  675. case core.PtrInt16Type:
  676. if rawValueType.Kind() == reflect.Int64 {
  677. var x = int16(vv.Int())
  678. hasAssigned = true
  679. fieldValue.Set(reflect.ValueOf(&x))
  680. }
  681. case core.PtrUintType:
  682. if rawValueType.Kind() == reflect.Int64 {
  683. var x = uint(vv.Int())
  684. hasAssigned = true
  685. fieldValue.Set(reflect.ValueOf(&x))
  686. }
  687. case core.PtrUint32Type:
  688. if rawValueType.Kind() == reflect.Int64 {
  689. var x = uint32(vv.Int())
  690. hasAssigned = true
  691. fieldValue.Set(reflect.ValueOf(&x))
  692. }
  693. case core.Uint8Type:
  694. if rawValueType.Kind() == reflect.Int64 {
  695. var x = uint8(vv.Int())
  696. hasAssigned = true
  697. fieldValue.Set(reflect.ValueOf(&x))
  698. }
  699. case core.Uint16Type:
  700. if rawValueType.Kind() == reflect.Int64 {
  701. var x = uint16(vv.Int())
  702. hasAssigned = true
  703. fieldValue.Set(reflect.ValueOf(&x))
  704. }
  705. case core.Complex64Type:
  706. var x complex64
  707. if len([]byte(vv.String())) > 0 {
  708. err := json.Unmarshal([]byte(vv.String()), &x)
  709. if err != nil {
  710. return nil, err
  711. }
  712. fieldValue.Set(reflect.ValueOf(&x))
  713. }
  714. hasAssigned = true
  715. case core.Complex128Type:
  716. var x complex128
  717. if len([]byte(vv.String())) > 0 {
  718. err := json.Unmarshal([]byte(vv.String()), &x)
  719. if err != nil {
  720. return nil, err
  721. }
  722. fieldValue.Set(reflect.ValueOf(&x))
  723. }
  724. hasAssigned = true
  725. } // switch fieldType
  726. } // switch fieldType.Kind()
  727. // !nashtsai! for value can't be assigned directly fallback to convert to []byte then back to value
  728. if !hasAssigned {
  729. data, err := value2Bytes(&rawValue)
  730. if err != nil {
  731. return nil, err
  732. }
  733. if err = session.bytes2Value(col, fieldValue, data); err != nil {
  734. return nil, err
  735. }
  736. }
  737. }
  738. }
  739. return pk, nil
  740. }
  741. // saveLastSQL stores executed query information
  742. func (session *Session) saveLastSQL(sql string, args ...interface{}) {
  743. session.lastSQL = sql
  744. session.lastSQLArgs = args
  745. session.engine.logSQL(sql, args...)
  746. }
  747. // LastSQL returns last query information
  748. func (session *Session) LastSQL() (string, []interface{}) {
  749. return session.lastSQL, session.lastSQLArgs
  750. }
  751. // tbName get some table's table name
  752. func (session *Session) tbNameNoSchema(table *core.Table) string {
  753. if len(session.statement.AltTableName) > 0 {
  754. return session.statement.AltTableName
  755. }
  756. return table.Name
  757. }
  758. // Unscoped always disable struct tag "deleted"
  759. func (session *Session) Unscoped() *Session {
  760. session.statement.Unscoped()
  761. return session
  762. }