You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.go 1.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package db
  2. import (
  3. "strings"
  4. "gorm.io/gorm"
  5. )
  6. const (
  7. maxPlaceholderCount = 65535
  8. )
  9. func BatchNamedExec[T any](ctx SQLContext, sql string, argCnt int, arr []T, callback func(result *gorm.DB) bool) error {
  10. if argCnt == 0 {
  11. result := ctx.Exec(sql, toInterfaceSlice(arr)...)
  12. if result.Error != nil {
  13. return result.Error
  14. }
  15. if callback != nil {
  16. callback(result)
  17. }
  18. return nil
  19. }
  20. batchSize := maxPlaceholderCount / argCnt
  21. for len(arr) > 0 {
  22. curBatchSize := min(batchSize, len(arr))
  23. result := ctx.Exec(sql, toInterfaceSlice(arr[:curBatchSize])...)
  24. if result.Error != nil {
  25. return result.Error
  26. }
  27. if callback != nil && !callback(result) {
  28. return nil
  29. }
  30. arr = arr[curBatchSize:]
  31. }
  32. return nil
  33. }
  34. // 将 []T 转换为 []interface{}
  35. func toInterfaceSlice[T any](arr []T) []interface{} {
  36. interfaceSlice := make([]interface{}, len(arr))
  37. for i, v := range arr {
  38. interfaceSlice[i] = v
  39. }
  40. return interfaceSlice
  41. }
  42. func min(a, b int) int {
  43. if a < b {
  44. return a
  45. }
  46. return b
  47. }
  48. func escapeLike(left, right, word string) string {
  49. var n int
  50. for i := range word {
  51. if c := word[i]; c == '%' || c == '_' || c == '\\' {
  52. n++
  53. }
  54. }
  55. // No characters to escape.
  56. if n == 0 {
  57. return left + word + right
  58. }
  59. var b strings.Builder
  60. b.Grow(len(word) + n)
  61. for _, c := range word {
  62. if c == '%' || c == '_' || c == '\\' {
  63. b.WriteByte('\\')
  64. }
  65. b.WriteRune(c)
  66. }
  67. return left + b.String() + right
  68. }

本项目旨在将云际存储公共基础设施化,使个人及企业可低门槛使用高效的云际存储服务(安装开箱即用云际存储客户端即可,无需关注其他组件的部署),同时支持用户灵活便捷定制云际存储的功能细节。