db_utils.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package utils
  2. import (
  3. "errors"
  4. "github.com/go-xorm/xorm"
  5. "reflect"
  6. )
  7. // 分页插入数据库
  8. func Insert(db *xorm.Engine, beans ...interface{}) error {
  9. return InsertWithSize(db, 500, beans...)
  10. }
  11. func InsertWithSize(db *xorm.Engine, size int, beans ...interface{}) error {
  12. if nil == db {
  13. return errors.New(`db can not be nil`)
  14. }
  15. if nil == beans || len(beans) == 0 {
  16. return nil
  17. }
  18. trans := db.NewSession()
  19. defer trans.Close()
  20. _ = trans.Begin()
  21. err := TransInsertWithSize(trans, size, beans...)
  22. if nil != err {
  23. _ = trans.Rollback()
  24. return err
  25. }
  26. return trans.Commit()
  27. }
  28. func TransInsert(trans *xorm.Session, beans ...interface{}) error {
  29. return TransInsertWithSize(trans, 500, beans...)
  30. }
  31. func TransInsertWithSize(trans *xorm.Session, size int, beans ...interface{}) error {
  32. if nil == trans {
  33. return errors.New(`trans can not be nil`)
  34. }
  35. if nil == beans || len(beans) == 0 {
  36. return nil
  37. }
  38. if size < 100 {
  39. size = 500
  40. }
  41. var objects []interface{}
  42. for _, bean := range beans {
  43. sliceValue := reflect.Indirect(reflect.ValueOf(bean))
  44. if sliceValue.Kind() == reflect.Slice {
  45. sLen := sliceValue.Len()
  46. if sLen == 0 {
  47. continue
  48. }
  49. if sLen <= size {
  50. objects = append(objects, bean)
  51. continue
  52. }
  53. idx := 0
  54. arrMap := make(map[int][]interface{})
  55. for i := 0; i < sliceValue.Len(); i++ {
  56. if i%size == 0 {
  57. idx++
  58. }
  59. v := sliceValue.Index(i)
  60. if v.Kind() == reflect.Ptr {
  61. v = v.Elem()
  62. }
  63. elemValue := v.Interface()
  64. if nil == arrMap[idx] {
  65. arrMap[idx] = []interface{}{elemValue}
  66. } else {
  67. arrMap[idx] = append(arrMap[idx], elemValue)
  68. }
  69. }
  70. for i := 1; i <= idx; i++ {
  71. arr := arrMap[i]
  72. objects = append(objects, &arr)
  73. }
  74. } else {
  75. objects = append(objects, bean)
  76. }
  77. }
  78. _, err := trans.Insert(objects...)
  79. if nil != err {
  80. return err
  81. }
  82. return nil
  83. }