session.go 23 KB

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