session.go 23 KB

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