helpers.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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. "errors"
  7. "fmt"
  8. "reflect"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/go-xorm/core"
  14. )
  15. // str2PK convert string value to primary key value according to tp
  16. func str2PKValue(s string, tp reflect.Type) (reflect.Value, error) {
  17. var err error
  18. var result interface{}
  19. var defReturn = reflect.Zero(tp)
  20. switch tp.Kind() {
  21. case reflect.Int:
  22. result, err = strconv.Atoi(s)
  23. if err != nil {
  24. return defReturn, fmt.Errorf("convert %s as int: %s", s, err.Error())
  25. }
  26. case reflect.Int8:
  27. x, err := strconv.Atoi(s)
  28. if err != nil {
  29. return defReturn, fmt.Errorf("convert %s as int8: %s", s, err.Error())
  30. }
  31. result = int8(x)
  32. case reflect.Int16:
  33. x, err := strconv.Atoi(s)
  34. if err != nil {
  35. return defReturn, fmt.Errorf("convert %s as int16: %s", s, err.Error())
  36. }
  37. result = int16(x)
  38. case reflect.Int32:
  39. x, err := strconv.Atoi(s)
  40. if err != nil {
  41. return defReturn, fmt.Errorf("convert %s as int32: %s", s, err.Error())
  42. }
  43. result = int32(x)
  44. case reflect.Int64:
  45. result, err = strconv.ParseInt(s, 10, 64)
  46. if err != nil {
  47. return defReturn, fmt.Errorf("convert %s as int64: %s", s, err.Error())
  48. }
  49. case reflect.Uint:
  50. x, err := strconv.ParseUint(s, 10, 64)
  51. if err != nil {
  52. return defReturn, fmt.Errorf("convert %s as uint: %s", s, err.Error())
  53. }
  54. result = uint(x)
  55. case reflect.Uint8:
  56. x, err := strconv.ParseUint(s, 10, 64)
  57. if err != nil {
  58. return defReturn, fmt.Errorf("convert %s as uint8: %s", s, err.Error())
  59. }
  60. result = uint8(x)
  61. case reflect.Uint16:
  62. x, err := strconv.ParseUint(s, 10, 64)
  63. if err != nil {
  64. return defReturn, fmt.Errorf("convert %s as uint16: %s", s, err.Error())
  65. }
  66. result = uint16(x)
  67. case reflect.Uint32:
  68. x, err := strconv.ParseUint(s, 10, 64)
  69. if err != nil {
  70. return defReturn, fmt.Errorf("convert %s as uint32: %s", s, err.Error())
  71. }
  72. result = uint32(x)
  73. case reflect.Uint64:
  74. result, err = strconv.ParseUint(s, 10, 64)
  75. if err != nil {
  76. return defReturn, fmt.Errorf("convert %s as uint64: %s", s, err.Error())
  77. }
  78. case reflect.String:
  79. result = s
  80. default:
  81. return defReturn, errors.New("unsupported convert type")
  82. }
  83. return reflect.ValueOf(result).Convert(tp), nil
  84. }
  85. func str2PK(s string, tp reflect.Type) (interface{}, error) {
  86. v, err := str2PKValue(s, tp)
  87. if err != nil {
  88. return nil, err
  89. }
  90. return v.Interface(), nil
  91. }
  92. func splitTag(tag string) (tags []string) {
  93. tag = strings.TrimSpace(tag)
  94. var hasQuote = false
  95. var lastIdx = 0
  96. for i, t := range tag {
  97. if t == '\'' {
  98. hasQuote = !hasQuote
  99. } else if t == ' ' {
  100. if lastIdx < i && !hasQuote {
  101. tags = append(tags, strings.TrimSpace(tag[lastIdx:i]))
  102. lastIdx = i + 1
  103. }
  104. }
  105. }
  106. if lastIdx < len(tag) {
  107. tags = append(tags, strings.TrimSpace(tag[lastIdx:]))
  108. }
  109. return
  110. }
  111. type zeroable interface {
  112. IsZero() bool
  113. }
  114. func isZero(k interface{}) bool {
  115. switch k.(type) {
  116. case int:
  117. return k.(int) == 0
  118. case int8:
  119. return k.(int8) == 0
  120. case int16:
  121. return k.(int16) == 0
  122. case int32:
  123. return k.(int32) == 0
  124. case int64:
  125. return k.(int64) == 0
  126. case uint:
  127. return k.(uint) == 0
  128. case uint8:
  129. return k.(uint8) == 0
  130. case uint16:
  131. return k.(uint16) == 0
  132. case uint32:
  133. return k.(uint32) == 0
  134. case uint64:
  135. return k.(uint64) == 0
  136. case float32:
  137. return k.(float32) == 0
  138. case float64:
  139. return k.(float64) == 0
  140. case bool:
  141. return k.(bool) == false
  142. case string:
  143. return k.(string) == ""
  144. case zeroable:
  145. return k.(zeroable).IsZero()
  146. }
  147. return false
  148. }
  149. func isStructZero(v reflect.Value) bool {
  150. if !v.IsValid() {
  151. return true
  152. }
  153. for i := 0; i < v.NumField(); i++ {
  154. field := v.Field(i)
  155. switch field.Kind() {
  156. case reflect.Ptr:
  157. field = field.Elem()
  158. fallthrough
  159. case reflect.Struct:
  160. if !isStructZero(field) {
  161. return false
  162. }
  163. default:
  164. if field.CanInterface() && !isZero(field.Interface()) {
  165. return false
  166. }
  167. }
  168. }
  169. return true
  170. }
  171. func isArrayValueZero(v reflect.Value) bool {
  172. if !v.IsValid() || v.Len() == 0 {
  173. return true
  174. }
  175. for i := 0; i < v.Len(); i++ {
  176. if !isZero(v.Index(i).Interface()) {
  177. return false
  178. }
  179. }
  180. return true
  181. }
  182. func int64ToIntValue(id int64, tp reflect.Type) reflect.Value {
  183. var v interface{}
  184. switch tp.Kind() {
  185. case reflect.Int16:
  186. v = int16(id)
  187. case reflect.Int32:
  188. v = int32(id)
  189. case reflect.Int:
  190. v = int(id)
  191. case reflect.Int64:
  192. v = id
  193. case reflect.Uint16:
  194. v = uint16(id)
  195. case reflect.Uint32:
  196. v = uint32(id)
  197. case reflect.Uint64:
  198. v = uint64(id)
  199. case reflect.Uint:
  200. v = uint(id)
  201. }
  202. return reflect.ValueOf(v).Convert(tp)
  203. }
  204. func int64ToInt(id int64, tp reflect.Type) interface{} {
  205. return int64ToIntValue(id, tp).Interface()
  206. }
  207. func isPKZero(pk core.PK) bool {
  208. for _, k := range pk {
  209. if isZero(k) {
  210. return true
  211. }
  212. }
  213. return false
  214. }
  215. func indexNoCase(s, sep string) int {
  216. return strings.Index(strings.ToLower(s), strings.ToLower(sep))
  217. }
  218. func splitNoCase(s, sep string) []string {
  219. idx := indexNoCase(s, sep)
  220. if idx < 0 {
  221. return []string{s}
  222. }
  223. return strings.Split(s, s[idx:idx+len(sep)])
  224. }
  225. func splitNNoCase(s, sep string, n int) []string {
  226. idx := indexNoCase(s, sep)
  227. if idx < 0 {
  228. return []string{s}
  229. }
  230. return strings.SplitN(s, s[idx:idx+len(sep)], n)
  231. }
  232. func makeArray(elem string, count int) []string {
  233. res := make([]string, count)
  234. for i := 0; i < count; i++ {
  235. res[i] = elem
  236. }
  237. return res
  238. }
  239. func rValue(bean interface{}) reflect.Value {
  240. return reflect.Indirect(reflect.ValueOf(bean))
  241. }
  242. func rType(bean interface{}) reflect.Type {
  243. sliceValue := reflect.Indirect(reflect.ValueOf(bean))
  244. //return reflect.TypeOf(sliceValue.Interface())
  245. return sliceValue.Type()
  246. }
  247. func structName(v reflect.Type) string {
  248. for v.Kind() == reflect.Ptr {
  249. v = v.Elem()
  250. }
  251. return v.Name()
  252. }
  253. func col2NewCols(columns ...string) []string {
  254. newColumns := make([]string, 0, len(columns))
  255. for _, col := range columns {
  256. col = strings.Replace(col, "`", "", -1)
  257. col = strings.Replace(col, `"`, "", -1)
  258. ccols := strings.Split(col, ",")
  259. for _, c := range ccols {
  260. newColumns = append(newColumns, strings.TrimSpace(c))
  261. }
  262. }
  263. return newColumns
  264. }
  265. func sliceEq(left, right []string) bool {
  266. if len(left) != len(right) {
  267. return false
  268. }
  269. sort.Sort(sort.StringSlice(left))
  270. sort.Sort(sort.StringSlice(right))
  271. for i := 0; i < len(left); i++ {
  272. if left[i] != right[i] {
  273. return false
  274. }
  275. }
  276. return true
  277. }
  278. func reflect2value(rawValue *reflect.Value) (str string, err error) {
  279. aa := reflect.TypeOf((*rawValue).Interface())
  280. vv := reflect.ValueOf((*rawValue).Interface())
  281. switch aa.Kind() {
  282. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  283. str = strconv.FormatInt(vv.Int(), 10)
  284. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  285. str = strconv.FormatUint(vv.Uint(), 10)
  286. case reflect.Float32, reflect.Float64:
  287. str = strconv.FormatFloat(vv.Float(), 'f', -1, 64)
  288. case reflect.String:
  289. str = vv.String()
  290. case reflect.Array, reflect.Slice:
  291. switch aa.Elem().Kind() {
  292. case reflect.Uint8:
  293. data := rawValue.Interface().([]byte)
  294. str = string(data)
  295. default:
  296. err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
  297. }
  298. // time type
  299. case reflect.Struct:
  300. if aa.ConvertibleTo(core.TimeType) {
  301. str = vv.Convert(core.TimeType).Interface().(time.Time).Format(time.RFC3339Nano)
  302. } else {
  303. err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
  304. }
  305. case reflect.Bool:
  306. str = strconv.FormatBool(vv.Bool())
  307. case reflect.Complex128, reflect.Complex64:
  308. str = fmt.Sprintf("%v", vv.Complex())
  309. /* TODO: unsupported types below
  310. case reflect.Map:
  311. case reflect.Ptr:
  312. case reflect.Uintptr:
  313. case reflect.UnsafePointer:
  314. case reflect.Chan, reflect.Func, reflect.Interface:
  315. */
  316. default:
  317. err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
  318. }
  319. return
  320. }
  321. func value2Bytes(rawValue *reflect.Value) (data []byte, err error) {
  322. var str string
  323. str, err = reflect2value(rawValue)
  324. if err != nil {
  325. return
  326. }
  327. data = []byte(str)
  328. return
  329. }
  330. func value2String(rawValue *reflect.Value) (data string, err error) {
  331. data, err = reflect2value(rawValue)
  332. if err != nil {
  333. return
  334. }
  335. return
  336. }
  337. func rows2Strings(rows *core.Rows) (resultsSlice []map[string]string, err error) {
  338. fields, err := rows.Columns()
  339. if err != nil {
  340. return nil, err
  341. }
  342. for rows.Next() {
  343. result, err := row2mapStr(rows, fields)
  344. if err != nil {
  345. return nil, err
  346. }
  347. resultsSlice = append(resultsSlice, result)
  348. }
  349. return resultsSlice, nil
  350. }
  351. func rows2maps(rows *core.Rows) (resultsSlice []map[string][]byte, err error) {
  352. fields, err := rows.Columns()
  353. if err != nil {
  354. return nil, err
  355. }
  356. for rows.Next() {
  357. result, err := row2map(rows, fields)
  358. if err != nil {
  359. return nil, err
  360. }
  361. resultsSlice = append(resultsSlice, result)
  362. }
  363. return resultsSlice, nil
  364. }
  365. func row2map(rows *core.Rows, fields []string) (resultsMap map[string][]byte, err error) {
  366. result := make(map[string][]byte)
  367. scanResultContainers := make([]interface{}, len(fields))
  368. for i := 0; i < len(fields); i++ {
  369. var scanResultContainer interface{}
  370. scanResultContainers[i] = &scanResultContainer
  371. }
  372. if err := rows.Scan(scanResultContainers...); err != nil {
  373. return nil, err
  374. }
  375. for ii, key := range fields {
  376. rawValue := reflect.Indirect(reflect.ValueOf(scanResultContainers[ii]))
  377. //if row is null then ignore
  378. if rawValue.Interface() == nil {
  379. //fmt.Println("ignore ...", key, rawValue)
  380. continue
  381. }
  382. if data, err := value2Bytes(&rawValue); err == nil {
  383. result[key] = data
  384. } else {
  385. return nil, err // !nashtsai! REVIEW, should return err or just error log?
  386. }
  387. }
  388. return result, nil
  389. }
  390. func row2mapStr(rows *core.Rows, fields []string) (resultsMap map[string]string, err error) {
  391. result := make(map[string]string)
  392. scanResultContainers := make([]interface{}, len(fields))
  393. for i := 0; i < len(fields); i++ {
  394. var scanResultContainer interface{}
  395. scanResultContainers[i] = &scanResultContainer
  396. }
  397. if err := rows.Scan(scanResultContainers...); err != nil {
  398. return nil, err
  399. }
  400. for ii, key := range fields {
  401. rawValue := reflect.Indirect(reflect.ValueOf(scanResultContainers[ii]))
  402. //if row is null then ignore
  403. if rawValue.Interface() == nil {
  404. //fmt.Println("ignore ...", key, rawValue)
  405. continue
  406. }
  407. if data, err := value2String(&rawValue); err == nil {
  408. result[key] = data
  409. } else {
  410. return nil, err // !nashtsai! REVIEW, should return err or just error log?
  411. }
  412. }
  413. return result, nil
  414. }
  415. func txQuery2(tx *core.Tx, sqlStr string, params ...interface{}) ([]map[string]string, error) {
  416. rows, err := tx.Query(sqlStr, params...)
  417. if err != nil {
  418. return nil, err
  419. }
  420. defer rows.Close()
  421. return rows2Strings(rows)
  422. }
  423. func query2(db *core.DB, sqlStr string, params ...interface{}) ([]map[string]string, error) {
  424. rows, err := db.Query(sqlStr, params...)
  425. if err != nil {
  426. return nil, err
  427. }
  428. defer rows.Close()
  429. return rows2Strings(rows)
  430. }
  431. func setColumnInt(bean interface{}, col *core.Column, t int64) {
  432. v, err := col.ValueOf(bean)
  433. if err != nil {
  434. return
  435. }
  436. if v.CanSet() {
  437. switch v.Type().Kind() {
  438. case reflect.Int, reflect.Int64, reflect.Int32:
  439. v.SetInt(t)
  440. case reflect.Uint, reflect.Uint64, reflect.Uint32:
  441. v.SetUint(uint64(t))
  442. }
  443. }
  444. }
  445. func setColumnTime(bean interface{}, col *core.Column, t time.Time) {
  446. v, err := col.ValueOf(bean)
  447. if err != nil {
  448. return
  449. }
  450. if v.CanSet() {
  451. switch v.Type().Kind() {
  452. case reflect.Struct:
  453. v.Set(reflect.ValueOf(t).Convert(v.Type()))
  454. case reflect.Int, reflect.Int64, reflect.Int32:
  455. v.SetInt(t.Unix())
  456. case reflect.Uint, reflect.Uint64, reflect.Uint32:
  457. v.SetUint(uint64(t.Unix()))
  458. }
  459. }
  460. }
  461. func genCols(table *core.Table, session *Session, bean interface{}, useCol bool, includeQuote bool) ([]string, []interface{}, error) {
  462. colNames := make([]string, 0, len(table.ColumnsSeq()))
  463. args := make([]interface{}, 0, len(table.ColumnsSeq()))
  464. for _, col := range table.Columns() {
  465. if useCol && !col.IsVersion && !col.IsCreated && !col.IsUpdated {
  466. if _, ok := getFlagForColumn(session.Statement.columnMap, col); !ok {
  467. continue
  468. }
  469. }
  470. if col.MapType == core.ONLYFROMDB {
  471. continue
  472. }
  473. fieldValuePtr, err := col.ValueOf(bean)
  474. if err != nil {
  475. return nil, nil, err
  476. }
  477. fieldValue := *fieldValuePtr
  478. if col.IsAutoIncrement {
  479. switch fieldValue.Type().Kind() {
  480. case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int, reflect.Int64:
  481. if fieldValue.Int() == 0 {
  482. continue
  483. }
  484. case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint, reflect.Uint64:
  485. if fieldValue.Uint() == 0 {
  486. continue
  487. }
  488. case reflect.String:
  489. if len(fieldValue.String()) == 0 {
  490. continue
  491. }
  492. }
  493. }
  494. if col.IsDeleted {
  495. continue
  496. }
  497. if session.Statement.ColumnStr != "" {
  498. if _, ok := getFlagForColumn(session.Statement.columnMap, col); !ok {
  499. continue
  500. }
  501. }
  502. if session.Statement.OmitStr != "" {
  503. if _, ok := getFlagForColumn(session.Statement.columnMap, col); ok {
  504. continue
  505. }
  506. }
  507. // !evalphobia! set fieldValue as nil when column is nullable and zero-value
  508. if _, ok := getFlagForColumn(session.Statement.nullableMap, col); ok {
  509. if col.Nullable && isZero(fieldValue.Interface()) {
  510. var nilValue *int
  511. fieldValue = reflect.ValueOf(nilValue)
  512. }
  513. }
  514. if (col.IsCreated || col.IsUpdated) && session.Statement.UseAutoTime /*&& isZero(fieldValue.Interface())*/ {
  515. // if time is non-empty, then set to auto time
  516. val, t := session.Engine.NowTime2(col.SQLType.Name)
  517. args = append(args, val)
  518. var colName = col.Name
  519. session.afterClosures = append(session.afterClosures, func(bean interface{}) {
  520. col := table.GetColumn(colName)
  521. setColumnTime(bean, col, t)
  522. })
  523. } else if col.IsVersion && session.Statement.checkVersion {
  524. args = append(args, 1)
  525. } else {
  526. arg, err := session.value2Interface(col, fieldValue)
  527. if err != nil {
  528. return colNames, args, err
  529. }
  530. args = append(args, arg)
  531. }
  532. if includeQuote {
  533. colNames = append(colNames, session.Engine.Quote(col.Name)+" = ?")
  534. } else {
  535. colNames = append(colNames, col.Name)
  536. }
  537. }
  538. return colNames, args, nil
  539. }
  540. func indexName(tableName, idxName string) string {
  541. return fmt.Sprintf("IDX_%v_%v", tableName, idxName)
  542. }
  543. func getFlagForColumn(m map[string]bool, col *core.Column) (val bool, has bool) {
  544. if len(m) == 0 {
  545. return false, false
  546. }
  547. n := len(col.Name)
  548. for mk := range m {
  549. if len(mk) != n {
  550. continue
  551. }
  552. if strings.EqualFold(mk, col.Name) {
  553. return m[mk], true
  554. }
  555. }
  556. return false, false
  557. }