Simple and Powerful ORM for Go, support mysql,postgres,tidb,sqlite3,mssql,oracle https://xorm.io
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

530 lines
16 KiB

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