db_utils.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. for i := 0; i < sliceValue.Len(); i++ {
  46. v := sliceValue.Index(i)
  47. elemValue := v.Interface()
  48. objects = append(objects, elemValue)
  49. }
  50. } else {
  51. objects = append(objects, bean)
  52. }
  53. }
  54. total := len(objects)
  55. var err error
  56. if total <= size {
  57. _, err = trans.Insert(&objects)
  58. return err
  59. }
  60. for i := 0; i < total; i += size {
  61. end := i + size
  62. if end > total {
  63. end = total
  64. }
  65. arr := objects[i:end]
  66. _, err = trans.Insert(&arr)
  67. if nil != err {
  68. return err
  69. }
  70. }
  71. return err
  72. }