a_baseStore.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. package dao
  2. import (
  3. "context"
  4. "fmt"
  5. "reflect"
  6. "time"
  7. "gogs.baozhida.cn/Cold_Logistic_libs/pkg/contrib/errors"
  8. "gorm.io/gorm"
  9. "Cold_Logistic/internal/pkg/common/global"
  10. "Cold_Logistic/internal/server/infra/models"
  11. )
  12. type DbBaseStore interface {
  13. Create(ctx context.Context, value models.BaseEntity) error
  14. Save(ctx context.Context, value models.BaseEntity, omit ...string) error
  15. UpdateById(ctx context.Context, value models.BaseEntity, selected ...string) error
  16. FirstById(ctx context.Context, dest models.BaseEntity, id int) error
  17. GetById(ctx context.Context, dest models.BaseEntity, id int) error
  18. GetByIds(ctx context.Context, dest, ids interface{}) error
  19. DeleteByIds(ctx context.Context, ids interface{}) error
  20. GetIntValueMapByIds(ctx context.Context, ids []int, fieldName string) (map[int]int, error)
  21. GetStringValueMapByIds(ctx context.Context, ids []int, fieldName string) (map[int]string, error)
  22. }
  23. var _ DbBaseStore = &dbBase{}
  24. type dbBase struct {
  25. store *DataStore
  26. baseEntity models.BaseEntity
  27. }
  28. func (ds *dbBase) Create(ctx context.Context, m models.BaseEntity) error {
  29. db := ds.store.optionDB(ctx)
  30. v := reflect.ValueOf(m).Elem()
  31. if v.CanAddr() {
  32. accountId := global.GetTokenInfoFromContext(ctx).AccountId
  33. if field := v.FieldByName("CreatedTime"); field.IsValid() {
  34. field.Set(reflect.ValueOf(models.MyTime{Time: time.Now()}))
  35. }
  36. if field := v.FieldByName("Deleted"); field.IsValid() {
  37. field.SetInt(models.DeleteNo)
  38. }
  39. if field := v.FieldByName("CreatedBy"); field.IsValid() && accountId != 0 {
  40. field.Set(reflect.ValueOf(accountId))
  41. }
  42. }
  43. return db.Table(m.TableName()).Create(m).Error
  44. }
  45. func (ds *dbBase) Save(ctx context.Context, m models.BaseEntity, omit ...string) error {
  46. db := ds.store.optionDB(ctx)
  47. v := reflect.ValueOf(m).Elem()
  48. if v.CanAddr() {
  49. accountId := global.GetTokenInfoFromContext(ctx).AccountId
  50. if field := v.FieldByName("Id"); field.IsValid() && field.IsZero() {
  51. if field := v.FieldByName("CreatedTime"); field.IsValid() {
  52. field.Set(reflect.ValueOf(models.MyTime{Time: time.Now()}))
  53. }
  54. if field := v.FieldByName("CreatedBy"); field.IsValid() && accountId != 0 {
  55. field.Set(reflect.ValueOf(accountId))
  56. }
  57. if field := v.FieldByName("Deleted"); field.IsValid() {
  58. field.SetInt(models.DeleteNo)
  59. }
  60. } else {
  61. if field := v.FieldByName("UpdatedTime"); field.IsValid() {
  62. field.Set(reflect.ValueOf(models.MyTime{Time: time.Now()}))
  63. }
  64. if field := v.FieldByName("UpdatedBy"); field.IsValid() && accountId != 0 {
  65. field.Set(reflect.ValueOf(accountId))
  66. }
  67. }
  68. }
  69. return db.Table(m.TableName()).Omit(omit...).Save(m).Error
  70. }
  71. func (ds *dbBase) UpdateById(ctx context.Context, m models.BaseEntity, selected ...string) error {
  72. db := ds.store.optionDB(ctx)
  73. v := reflect.ValueOf(m).Elem()
  74. if v.CanAddr() {
  75. accountId := global.GetTokenInfoFromContext(ctx).AccountId
  76. if field := v.FieldByName("UpdatedTime"); field.IsValid() {
  77. field.Set(reflect.ValueOf(models.MyTime{Time: time.Now()}))
  78. if len(selected) > 0 {
  79. selected = append(selected, "UpdatedTime")
  80. }
  81. }
  82. if field := v.FieldByName("UpdatedBy"); field.IsValid() && accountId != 0 {
  83. field.Set(reflect.ValueOf(accountId))
  84. if len(selected) > 0 {
  85. selected = append(selected, "UpdatedBy")
  86. }
  87. }
  88. }
  89. return db.Table(m.TableName()).Select(selected).Updates(m).Error
  90. }
  91. func (ds *dbBase) FirstById(ctx context.Context, dest models.BaseEntity, id int) error {
  92. return ds.firstByOptions(ctx, dest, ds.store.withByID(id), ds.store.withByNotDeleted())
  93. }
  94. func (ds *dbBase) GetById(ctx context.Context, dest models.BaseEntity, id int) error {
  95. return ds.findByOptions(ctx, dest, ds.store.withByID(id), ds.store.withByNotDeleted())
  96. }
  97. func (ds *dbBase) GetByIds(ctx context.Context, dest, ids interface{}) error {
  98. db := ds.store.optionDB(ctx)
  99. err := db.Table(ds.baseEntity.TableName()).Where("deleted = ?", models.DeleteNo).
  100. Where("id in (?)", ids).
  101. Find(dest).Error
  102. return err
  103. }
  104. func (ds *dbBase) DeleteByIds(ctx context.Context, ids interface{}) error {
  105. destVal := reflect.ValueOf(ds.baseEntity)
  106. if destVal.Kind() == reflect.Ptr {
  107. destVal = destVal.Elem()
  108. }
  109. v := reflect.New(destVal.Type())
  110. v = v.Elem()
  111. if field := v.FieldByName("DeletedTime"); field.IsValid() {
  112. field.Set(reflect.ValueOf(models.MyTime{Time: time.Now()}))
  113. }
  114. if field := v.FieldByName("DeletedBy"); field.IsValid() {
  115. field.Set(reflect.ValueOf(global.GetTokenInfoFromContext(ctx).AccountId))
  116. }
  117. if field := v.FieldByName("Deleted"); field.IsValid() {
  118. field.Set(reflect.ValueOf(models.DeleteYes))
  119. }
  120. db := ds.store.optionDB(ctx)
  121. err := db.Table(ds.baseEntity.TableName()).
  122. Where("deleted = ?", models.DeleteNo).
  123. Where("id IN (?)", ids).
  124. Updates(v.Interface()).Error
  125. return err
  126. }
  127. func (ds *dbBase) GetIntValueMapByIds(ctx context.Context, ids []int, fieldName string) (map[int]int, error) {
  128. res := make(map[int]int, len(ids))
  129. if len(ids) == 0 {
  130. return res, nil
  131. }
  132. slicePtr := ds.makeSlice(len(ids))
  133. err := ds.findByOptions(ctx, slicePtr.Interface(),
  134. ds.store.withByNotDeleted(),
  135. ds.store.withByColumnInVal("id", ids),
  136. ds.store.withBySelects("id", fieldName))
  137. if err != nil {
  138. return nil, err
  139. }
  140. sliceVal := slicePtr.Elem()
  141. for i := 0; i < sliceVal.Len(); i++ {
  142. elem := sliceVal.Index(i)
  143. if fieldValue := elem.FieldByName(fieldName); fieldValue.IsValid() {
  144. res[elem.FieldByName("Id").Interface().(int)] = fieldValue.Interface().(int)
  145. } else {
  146. return nil, errors.New(fmt.Sprintf("fieldName %s not found", fieldName))
  147. }
  148. }
  149. return res, nil
  150. }
  151. func (ds *dbBase) GetStringValueMapByIds(ctx context.Context, ids []int, fieldName string) (map[int]string, error) {
  152. res := make(map[int]string, len(ids))
  153. if len(ids) == 0 {
  154. return res, nil
  155. }
  156. slicePtr := ds.makeSlice(len(ids))
  157. err := ds.findByOptions(ctx, slicePtr.Interface(),
  158. ds.store.withByNotDeleted(),
  159. ds.store.withByColumnInVal("id", ids),
  160. ds.store.withBySelects("id", fieldName))
  161. if err != nil {
  162. return nil, err
  163. }
  164. sliceVal := slicePtr.Elem()
  165. for i := 0; i < sliceVal.Len(); i++ {
  166. elem := sliceVal.Index(i)
  167. if fieldValue := elem.FieldByName(fieldName); fieldValue.IsValid() {
  168. res[elem.FieldByName("Id").Interface().(int)] = fieldValue.Interface().(string)
  169. } else {
  170. return nil, errors.New(fmt.Sprintf("fieldName %s not found", fieldName))
  171. }
  172. }
  173. return res, nil
  174. }
  175. func (ds *dbBase) makeSlice(cap int) reflect.Value {
  176. elemType := reflect.TypeOf(ds.baseEntity)
  177. if elemType.Kind() == reflect.Ptr {
  178. elemType = elemType.Elem()
  179. }
  180. slice := reflect.MakeSlice(reflect.SliceOf(elemType), 0, cap)
  181. results := reflect.New(slice.Type())
  182. results.Elem().Set(slice)
  183. return results
  184. }
  185. func (ds *dbBase) firstByOptions(ctx context.Context, m models.BaseEntity, opts ...dbOption) error {
  186. db := ds.store.optionDB(ctx, opts...)
  187. err := db.Table(m.TableName()).First(m).Error
  188. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  189. return errors.WithStackOnce(err)
  190. }
  191. return err
  192. }
  193. func (ds *dbBase) findByOptions(ctx context.Context, dest interface{}, opts ...dbOption) error {
  194. db := ds.store.optionDB(ctx, opts...)
  195. err := db.Table(ds.baseEntity.TableName()).Find(dest).Error
  196. return err
  197. }