session_convert.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. // Copyright 2017 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. "database/sql/driver"
  8. "errors"
  9. "fmt"
  10. "reflect"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "xorm.io/core"
  15. )
  16. func (session *Session) str2Time(col *core.Column, data string) (outTime time.Time, outErr error) {
  17. sdata := strings.TrimSpace(data)
  18. var x time.Time
  19. var err error
  20. var parseLoc = session.engine.DatabaseTZ
  21. if col.TimeZone != nil {
  22. parseLoc = col.TimeZone
  23. }
  24. if sdata == zeroTime0 || sdata == zeroTime1 {
  25. } else if !strings.ContainsAny(sdata, "- :") { // !nashtsai! has only found that mymysql driver is using this for time type column
  26. // time stamp
  27. sd, err := strconv.ParseInt(sdata, 10, 64)
  28. if err == nil {
  29. x = time.Unix(sd, 0)
  30. //session.engine.logger.Debugf("time(0) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
  31. } else {
  32. //session.engine.logger.Debugf("time(0) err key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
  33. }
  34. } else if len(sdata) > 19 && strings.Contains(sdata, "-") {
  35. x, err = time.ParseInLocation(time.RFC3339Nano, sdata, parseLoc)
  36. session.engine.logger.Debugf("time(1) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
  37. if err != nil {
  38. x, err = time.ParseInLocation("2006-01-02 15:04:05.999999999", sdata, parseLoc)
  39. //session.engine.logger.Debugf("time(2) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
  40. }
  41. if err != nil {
  42. x, err = time.ParseInLocation("2006-01-02 15:04:05.9999999 Z07:00", sdata, parseLoc)
  43. //session.engine.logger.Debugf("time(3) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
  44. }
  45. } else if len(sdata) == 19 && strings.Contains(sdata, "-") {
  46. x, err = time.ParseInLocation("2006-01-02 15:04:05", sdata, parseLoc)
  47. //session.engine.logger.Debugf("time(4) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
  48. } else if len(sdata) == 10 && sdata[4] == '-' && sdata[7] == '-' {
  49. x, err = time.ParseInLocation("2006-01-02", sdata, parseLoc)
  50. //session.engine.logger.Debugf("time(5) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
  51. } else if col.SQLType.Name == core.Time {
  52. if strings.Contains(sdata, " ") {
  53. ssd := strings.Split(sdata, " ")
  54. sdata = ssd[1]
  55. }
  56. sdata = strings.TrimSpace(sdata)
  57. if session.engine.dialect.DBType() == core.MYSQL && len(sdata) > 8 {
  58. sdata = sdata[len(sdata)-8:]
  59. }
  60. st := fmt.Sprintf("2006-01-02 %v", sdata)
  61. x, err = time.ParseInLocation("2006-01-02 15:04:05", st, parseLoc)
  62. //session.engine.logger.Debugf("time(6) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
  63. } else {
  64. outErr = fmt.Errorf("unsupported time format %v", sdata)
  65. return
  66. }
  67. if err != nil {
  68. outErr = fmt.Errorf("unsupported time format %v: %v", sdata, err)
  69. return
  70. }
  71. outTime = x.In(session.engine.TZLocation)
  72. return
  73. }
  74. func (session *Session) byte2Time(col *core.Column, data []byte) (outTime time.Time, outErr error) {
  75. return session.str2Time(col, string(data))
  76. }
  77. // convert a db data([]byte) to a field value
  78. func (session *Session) bytes2Value(col *core.Column, fieldValue *reflect.Value, data []byte) error {
  79. if structConvert, ok := fieldValue.Addr().Interface().(core.Conversion); ok {
  80. return structConvert.FromDB(data)
  81. }
  82. if structConvert, ok := fieldValue.Interface().(core.Conversion); ok {
  83. return structConvert.FromDB(data)
  84. }
  85. var v interface{}
  86. key := col.Name
  87. fieldType := fieldValue.Type()
  88. switch fieldType.Kind() {
  89. case reflect.Complex64, reflect.Complex128:
  90. x := reflect.New(fieldType)
  91. if len(data) > 0 {
  92. err := DefaultJSONHandler.Unmarshal(data, x.Interface())
  93. if err != nil {
  94. session.engine.logger.Error(err)
  95. return err
  96. }
  97. fieldValue.Set(x.Elem())
  98. }
  99. case reflect.Slice, reflect.Array, reflect.Map:
  100. v = data
  101. t := fieldType.Elem()
  102. k := t.Kind()
  103. if col.SQLType.IsText() {
  104. x := reflect.New(fieldType)
  105. if len(data) > 0 {
  106. err := DefaultJSONHandler.Unmarshal(data, x.Interface())
  107. if err != nil {
  108. session.engine.logger.Error(err)
  109. return err
  110. }
  111. fieldValue.Set(x.Elem())
  112. }
  113. } else if col.SQLType.IsBlob() {
  114. if k == reflect.Uint8 {
  115. fieldValue.Set(reflect.ValueOf(v))
  116. } else {
  117. x := reflect.New(fieldType)
  118. if len(data) > 0 {
  119. err := DefaultJSONHandler.Unmarshal(data, x.Interface())
  120. if err != nil {
  121. session.engine.logger.Error(err)
  122. return err
  123. }
  124. fieldValue.Set(x.Elem())
  125. }
  126. }
  127. } else {
  128. return ErrUnSupportedType
  129. }
  130. case reflect.String:
  131. fieldValue.SetString(string(data))
  132. case reflect.Bool:
  133. v, err := asBool(data)
  134. if err != nil {
  135. return fmt.Errorf("arg %v as bool: %s", key, err.Error())
  136. }
  137. fieldValue.Set(reflect.ValueOf(v))
  138. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  139. sdata := string(data)
  140. var x int64
  141. var err error
  142. // for mysql, when use bit, it returned \x01
  143. if col.SQLType.Name == core.Bit &&
  144. session.engine.dialect.DBType() == core.MYSQL { // !nashtsai! TODO dialect needs to provide conversion interface API
  145. if len(data) == 1 {
  146. x = int64(data[0])
  147. } else {
  148. x = 0
  149. }
  150. } else if strings.HasPrefix(sdata, "0x") {
  151. x, err = strconv.ParseInt(sdata, 16, 64)
  152. } else if strings.HasPrefix(sdata, "0") {
  153. x, err = strconv.ParseInt(sdata, 8, 64)
  154. } else if strings.EqualFold(sdata, "true") {
  155. x = 1
  156. } else if strings.EqualFold(sdata, "false") {
  157. x = 0
  158. } else {
  159. x, err = strconv.ParseInt(sdata, 10, 64)
  160. }
  161. if err != nil {
  162. return fmt.Errorf("arg %v as int: %s", key, err.Error())
  163. }
  164. fieldValue.SetInt(x)
  165. case reflect.Float32, reflect.Float64:
  166. x, err := strconv.ParseFloat(string(data), 64)
  167. if err != nil {
  168. return fmt.Errorf("arg %v as float64: %s", key, err.Error())
  169. }
  170. fieldValue.SetFloat(x)
  171. case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
  172. x, err := strconv.ParseUint(string(data), 10, 64)
  173. if err != nil {
  174. return fmt.Errorf("arg %v as int: %s", key, err.Error())
  175. }
  176. fieldValue.SetUint(x)
  177. //Currently only support Time type
  178. case reflect.Struct:
  179. // !<winxxp>! 增加支持sql.Scanner接口的结构,如sql.NullString
  180. if nulVal, ok := fieldValue.Addr().Interface().(sql.Scanner); ok {
  181. if err := nulVal.Scan(data); err != nil {
  182. return fmt.Errorf("sql.Scan(%v) failed: %s ", data, err.Error())
  183. }
  184. } else {
  185. if fieldType.ConvertibleTo(core.TimeType) {
  186. x, err := session.byte2Time(col, data)
  187. if err != nil {
  188. return err
  189. }
  190. v = x
  191. fieldValue.Set(reflect.ValueOf(v).Convert(fieldType))
  192. } else if session.statement.UseCascade {
  193. table, err := session.engine.autoMapType(*fieldValue)
  194. if err != nil {
  195. return err
  196. }
  197. // TODO: current only support 1 primary key
  198. if len(table.PrimaryKeys) > 1 {
  199. return errors.New("unsupported composited primary key cascade")
  200. }
  201. var pk = make(core.PK, len(table.PrimaryKeys))
  202. rawValueType := table.ColumnType(table.PKColumns()[0].FieldName)
  203. pk[0], err = str2PK(string(data), rawValueType)
  204. if err != nil {
  205. return err
  206. }
  207. if !isPKZero(pk) {
  208. // !nashtsai! TODO for hasOne relationship, it's preferred to use join query for eager fetch
  209. // however, also need to consider adding a 'lazy' attribute to xorm tag which allow hasOne
  210. // property to be fetched lazily
  211. structInter := reflect.New(fieldValue.Type())
  212. has, err := session.ID(pk).NoCascade().get(structInter.Interface())
  213. if err != nil {
  214. return err
  215. }
  216. if has {
  217. v = structInter.Elem().Interface()
  218. fieldValue.Set(reflect.ValueOf(v))
  219. } else {
  220. return errors.New("cascade obj is not exist")
  221. }
  222. }
  223. }
  224. }
  225. case reflect.Ptr:
  226. // !nashtsai! TODO merge duplicated codes above
  227. //typeStr := fieldType.String()
  228. switch fieldType.Elem().Kind() {
  229. // case "*string":
  230. case core.StringType.Kind():
  231. x := string(data)
  232. fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
  233. // case "*bool":
  234. case core.BoolType.Kind():
  235. d := string(data)
  236. v, err := strconv.ParseBool(d)
  237. if err != nil {
  238. return fmt.Errorf("arg %v as bool: %s", key, err.Error())
  239. }
  240. fieldValue.Set(reflect.ValueOf(&v).Convert(fieldType))
  241. // case "*complex64":
  242. case core.Complex64Type.Kind():
  243. var x complex64
  244. if len(data) > 0 {
  245. err := DefaultJSONHandler.Unmarshal(data, &x)
  246. if err != nil {
  247. session.engine.logger.Error(err)
  248. return err
  249. }
  250. fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
  251. }
  252. // case "*complex128":
  253. case core.Complex128Type.Kind():
  254. var x complex128
  255. if len(data) > 0 {
  256. err := DefaultJSONHandler.Unmarshal(data, &x)
  257. if err != nil {
  258. session.engine.logger.Error(err)
  259. return err
  260. }
  261. fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
  262. }
  263. // case "*float64":
  264. case core.Float64Type.Kind():
  265. x, err := strconv.ParseFloat(string(data), 64)
  266. if err != nil {
  267. return fmt.Errorf("arg %v as float64: %s", key, err.Error())
  268. }
  269. fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
  270. // case "*float32":
  271. case core.Float32Type.Kind():
  272. var x float32
  273. x1, err := strconv.ParseFloat(string(data), 32)
  274. if err != nil {
  275. return fmt.Errorf("arg %v as float32: %s", key, err.Error())
  276. }
  277. x = float32(x1)
  278. fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
  279. // case "*uint64":
  280. case core.Uint64Type.Kind():
  281. var x uint64
  282. x, err := strconv.ParseUint(string(data), 10, 64)
  283. if err != nil {
  284. return fmt.Errorf("arg %v as int: %s", key, err.Error())
  285. }
  286. fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
  287. // case "*uint":
  288. case core.UintType.Kind():
  289. var x uint
  290. x1, err := strconv.ParseUint(string(data), 10, 64)
  291. if err != nil {
  292. return fmt.Errorf("arg %v as int: %s", key, err.Error())
  293. }
  294. x = uint(x1)
  295. fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
  296. // case "*uint32":
  297. case core.Uint32Type.Kind():
  298. var x uint32
  299. x1, err := strconv.ParseUint(string(data), 10, 64)
  300. if err != nil {
  301. return fmt.Errorf("arg %v as int: %s", key, err.Error())
  302. }
  303. x = uint32(x1)
  304. fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
  305. // case "*uint8":
  306. case core.Uint8Type.Kind():
  307. var x uint8
  308. x1, err := strconv.ParseUint(string(data), 10, 64)
  309. if err != nil {
  310. return fmt.Errorf("arg %v as int: %s", key, err.Error())
  311. }
  312. x = uint8(x1)
  313. fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
  314. // case "*uint16":
  315. case core.Uint16Type.Kind():
  316. var x uint16
  317. x1, err := strconv.ParseUint(string(data), 10, 64)
  318. if err != nil {
  319. return fmt.Errorf("arg %v as int: %s", key, err.Error())
  320. }
  321. x = uint16(x1)
  322. fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
  323. // case "*int64":
  324. case core.Int64Type.Kind():
  325. sdata := string(data)
  326. var x int64
  327. var err error
  328. // for mysql, when use bit, it returned \x01
  329. if col.SQLType.Name == core.Bit &&
  330. strings.Contains(session.engine.DriverName(), "mysql") {
  331. if len(data) == 1 {
  332. x = int64(data[0])
  333. } else {
  334. x = 0
  335. }
  336. } else if strings.HasPrefix(sdata, "0x") {
  337. x, err = strconv.ParseInt(sdata, 16, 64)
  338. } else if strings.HasPrefix(sdata, "0") {
  339. x, err = strconv.ParseInt(sdata, 8, 64)
  340. } else {
  341. x, err = strconv.ParseInt(sdata, 10, 64)
  342. }
  343. if err != nil {
  344. return fmt.Errorf("arg %v as int: %s", key, err.Error())
  345. }
  346. fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
  347. // case "*int":
  348. case core.IntType.Kind():
  349. sdata := string(data)
  350. var x int
  351. var x1 int64
  352. var err error
  353. // for mysql, when use bit, it returned \x01
  354. if col.SQLType.Name == core.Bit &&
  355. strings.Contains(session.engine.DriverName(), "mysql") {
  356. if len(data) == 1 {
  357. x = int(data[0])
  358. } else {
  359. x = 0
  360. }
  361. } else if strings.HasPrefix(sdata, "0x") {
  362. x1, err = strconv.ParseInt(sdata, 16, 64)
  363. x = int(x1)
  364. } else if strings.HasPrefix(sdata, "0") {
  365. x1, err = strconv.ParseInt(sdata, 8, 64)
  366. x = int(x1)
  367. } else {
  368. x1, err = strconv.ParseInt(sdata, 10, 64)
  369. x = int(x1)
  370. }
  371. if err != nil {
  372. return fmt.Errorf("arg %v as int: %s", key, err.Error())
  373. }
  374. fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
  375. // case "*int32":
  376. case core.Int32Type.Kind():
  377. sdata := string(data)
  378. var x int32
  379. var x1 int64
  380. var err error
  381. // for mysql, when use bit, it returned \x01
  382. if col.SQLType.Name == core.Bit &&
  383. session.engine.dialect.DBType() == core.MYSQL {
  384. if len(data) == 1 {
  385. x = int32(data[0])
  386. } else {
  387. x = 0
  388. }
  389. } else if strings.HasPrefix(sdata, "0x") {
  390. x1, err = strconv.ParseInt(sdata, 16, 64)
  391. x = int32(x1)
  392. } else if strings.HasPrefix(sdata, "0") {
  393. x1, err = strconv.ParseInt(sdata, 8, 64)
  394. x = int32(x1)
  395. } else {
  396. x1, err = strconv.ParseInt(sdata, 10, 64)
  397. x = int32(x1)
  398. }
  399. if err != nil {
  400. return fmt.Errorf("arg %v as int: %s", key, err.Error())
  401. }
  402. fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
  403. // case "*int8":
  404. case core.Int8Type.Kind():
  405. sdata := string(data)
  406. var x int8
  407. var x1 int64
  408. var err error
  409. // for mysql, when use bit, it returned \x01
  410. if col.SQLType.Name == core.Bit &&
  411. strings.Contains(session.engine.DriverName(), "mysql") {
  412. if len(data) == 1 {
  413. x = int8(data[0])
  414. } else {
  415. x = 0
  416. }
  417. } else if strings.HasPrefix(sdata, "0x") {
  418. x1, err = strconv.ParseInt(sdata, 16, 64)
  419. x = int8(x1)
  420. } else if strings.HasPrefix(sdata, "0") {
  421. x1, err = strconv.ParseInt(sdata, 8, 64)
  422. x = int8(x1)
  423. } else {
  424. x1, err = strconv.ParseInt(sdata, 10, 64)
  425. x = int8(x1)
  426. }
  427. if err != nil {
  428. return fmt.Errorf("arg %v as int: %s", key, err.Error())
  429. }
  430. fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
  431. // case "*int16":
  432. case core.Int16Type.Kind():
  433. sdata := string(data)
  434. var x int16
  435. var x1 int64
  436. var err error
  437. // for mysql, when use bit, it returned \x01
  438. if col.SQLType.Name == core.Bit &&
  439. strings.Contains(session.engine.DriverName(), "mysql") {
  440. if len(data) == 1 {
  441. x = int16(data[0])
  442. } else {
  443. x = 0
  444. }
  445. } else if strings.HasPrefix(sdata, "0x") {
  446. x1, err = strconv.ParseInt(sdata, 16, 64)
  447. x = int16(x1)
  448. } else if strings.HasPrefix(sdata, "0") {
  449. x1, err = strconv.ParseInt(sdata, 8, 64)
  450. x = int16(x1)
  451. } else {
  452. x1, err = strconv.ParseInt(sdata, 10, 64)
  453. x = int16(x1)
  454. }
  455. if err != nil {
  456. return fmt.Errorf("arg %v as int: %s", key, err.Error())
  457. }
  458. fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
  459. // case "*SomeStruct":
  460. case reflect.Struct:
  461. switch fieldType {
  462. // case "*.time.Time":
  463. case core.PtrTimeType:
  464. x, err := session.byte2Time(col, data)
  465. if err != nil {
  466. return err
  467. }
  468. v = x
  469. fieldValue.Set(reflect.ValueOf(&x))
  470. default:
  471. if session.statement.UseCascade {
  472. structInter := reflect.New(fieldType.Elem())
  473. table, err := session.engine.autoMapType(structInter.Elem())
  474. if err != nil {
  475. return err
  476. }
  477. if len(table.PrimaryKeys) > 1 {
  478. return errors.New("unsupported composited primary key cascade")
  479. }
  480. var pk = make(core.PK, len(table.PrimaryKeys))
  481. rawValueType := table.ColumnType(table.PKColumns()[0].FieldName)
  482. pk[0], err = str2PK(string(data), rawValueType)
  483. if err != nil {
  484. return err
  485. }
  486. if !isPKZero(pk) {
  487. // !nashtsai! TODO for hasOne relationship, it's preferred to use join query for eager fetch
  488. // however, also need to consider adding a 'lazy' attribute to xorm tag which allow hasOne
  489. // property to be fetched lazily
  490. has, err := session.ID(pk).NoCascade().get(structInter.Interface())
  491. if err != nil {
  492. return err
  493. }
  494. if has {
  495. v = structInter.Interface()
  496. fieldValue.Set(reflect.ValueOf(v))
  497. } else {
  498. return errors.New("cascade obj is not exist")
  499. }
  500. }
  501. } else {
  502. return fmt.Errorf("unsupported struct type in Scan: %s", fieldValue.Type().String())
  503. }
  504. }
  505. default:
  506. return fmt.Errorf("unsupported type in Scan: %s", fieldValue.Type().String())
  507. }
  508. default:
  509. return fmt.Errorf("unsupported type in Scan: %s", fieldValue.Type().String())
  510. }
  511. return nil
  512. }
  513. // convert a field value of a struct to interface for put into db
  514. func (session *Session) value2Interface(col *core.Column, fieldValue reflect.Value) (interface{}, error) {
  515. if fieldValue.CanAddr() {
  516. if fieldConvert, ok := fieldValue.Addr().Interface().(core.Conversion); ok {
  517. data, err := fieldConvert.ToDB()
  518. if err != nil {
  519. return 0, err
  520. }
  521. if col.SQLType.IsBlob() {
  522. return data, nil
  523. }
  524. return string(data), nil
  525. }
  526. }
  527. if fieldConvert, ok := fieldValue.Interface().(core.Conversion); ok {
  528. data, err := fieldConvert.ToDB()
  529. if err != nil {
  530. return 0, err
  531. }
  532. if col.SQLType.IsBlob() {
  533. return data, nil
  534. }
  535. return string(data), nil
  536. }
  537. fieldType := fieldValue.Type()
  538. k := fieldType.Kind()
  539. if k == reflect.Ptr {
  540. if fieldValue.IsNil() {
  541. return nil, nil
  542. } else if !fieldValue.IsValid() {
  543. session.engine.logger.Warn("the field[", col.FieldName, "] is invalid")
  544. return nil, nil
  545. } else {
  546. // !nashtsai! deference pointer type to instance type
  547. fieldValue = fieldValue.Elem()
  548. fieldType = fieldValue.Type()
  549. k = fieldType.Kind()
  550. }
  551. }
  552. switch k {
  553. case reflect.Bool:
  554. return fieldValue.Bool(), nil
  555. case reflect.String:
  556. return fieldValue.String(), nil
  557. case reflect.Struct:
  558. if fieldType.ConvertibleTo(core.TimeType) {
  559. t := fieldValue.Convert(core.TimeType).Interface().(time.Time)
  560. tf := session.engine.formatColTime(col, t)
  561. return tf, nil
  562. }
  563. if !col.SQLType.IsJson() {
  564. // !<winxxp>! 增加支持driver.Valuer接口的结构,如sql.NullString
  565. if v, ok := fieldValue.Interface().(driver.Valuer); ok {
  566. return v.Value()
  567. }
  568. fieldTable, err := session.engine.autoMapType(fieldValue)
  569. if err != nil {
  570. return nil, err
  571. }
  572. if len(fieldTable.PrimaryKeys) == 1 {
  573. pkField := reflect.Indirect(fieldValue).FieldByName(fieldTable.PKColumns()[0].FieldName)
  574. return pkField.Interface(), nil
  575. }
  576. return 0, fmt.Errorf("no primary key for col %v", col.Name)
  577. }
  578. if col.SQLType.IsText() {
  579. bytes, err := DefaultJSONHandler.Marshal(fieldValue.Interface())
  580. if err != nil {
  581. session.engine.logger.Error(err)
  582. return 0, err
  583. }
  584. return string(bytes), nil
  585. } else if col.SQLType.IsBlob() {
  586. bytes, err := DefaultJSONHandler.Marshal(fieldValue.Interface())
  587. if err != nil {
  588. session.engine.logger.Error(err)
  589. return 0, err
  590. }
  591. return bytes, nil
  592. }
  593. return nil, fmt.Errorf("Unsupported type %v", fieldValue.Type())
  594. case reflect.Complex64, reflect.Complex128:
  595. bytes, err := DefaultJSONHandler.Marshal(fieldValue.Interface())
  596. if err != nil {
  597. session.engine.logger.Error(err)
  598. return 0, err
  599. }
  600. return string(bytes), nil
  601. case reflect.Array, reflect.Slice, reflect.Map:
  602. if !fieldValue.IsValid() {
  603. return fieldValue.Interface(), nil
  604. }
  605. if col.SQLType.IsText() {
  606. bytes, err := DefaultJSONHandler.Marshal(fieldValue.Interface())
  607. if err != nil {
  608. session.engine.logger.Error(err)
  609. return 0, err
  610. }
  611. return string(bytes), nil
  612. } else if col.SQLType.IsBlob() {
  613. var bytes []byte
  614. var err error
  615. if (k == reflect.Slice) &&
  616. (fieldValue.Type().Elem().Kind() == reflect.Uint8) {
  617. bytes = fieldValue.Bytes()
  618. } else {
  619. bytes, err = DefaultJSONHandler.Marshal(fieldValue.Interface())
  620. if err != nil {
  621. session.engine.logger.Error(err)
  622. return 0, err
  623. }
  624. }
  625. return bytes, nil
  626. }
  627. return nil, ErrUnSupportedType
  628. case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
  629. return int64(fieldValue.Uint()), nil
  630. default:
  631. return fieldValue.Interface(), nil
  632. }
  633. }