crud.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. package rest
  2. import (
  3. "context"
  4. "fmt"
  5. "git.nspix.com/golang/rest/v3/cache"
  6. loggerpkg "git.nspix.com/golang/rest/v3/logger"
  7. "gorm.io/gorm"
  8. "gorm.io/gorm/clause"
  9. "gorm.io/gorm/logger"
  10. "strings"
  11. "time"
  12. )
  13. const (
  14. DefaultNamespace = "default"
  15. NamespaceVariable = "namespace"
  16. UserVariable = "@uid"
  17. DepartmentVariable = "@department"
  18. NamespaceField = "namespace"
  19. CreatedByField = "CreatedBy"
  20. CreatedDeptField = "CreatedDept"
  21. UpdatedByField = "UpdatedBy"
  22. UpdatedDeptField = "UpdatedDept"
  23. )
  24. const (
  25. TypeModule = "module"
  26. TypeTable = "table"
  27. )
  28. type (
  29. CRUD struct {
  30. api *Api
  31. db *gorm.DB
  32. modules []*Restful
  33. delegate *delegate
  34. enableCache bool
  35. }
  36. treeValue struct {
  37. Label string `json:"label"`
  38. Value string `json:"value"`
  39. Type string `json:"type"`
  40. Children []*treeValue `json:"children,omitempty"`
  41. }
  42. )
  43. func (t *treeValue) Append(v *treeValue) {
  44. if t.Children == nil {
  45. t.Children = make([]*treeValue, 0)
  46. }
  47. t.Children = append(t.Children, v)
  48. }
  49. //createStatement 创建一个声明
  50. func (r *CRUD) createStatement(db *gorm.DB) *gorm.Statement {
  51. return &gorm.Statement{
  52. DB: db,
  53. ConnPool: db.Statement.ConnPool,
  54. Context: db.Statement.Context,
  55. Clauses: map[string]clause.Clause{},
  56. }
  57. }
  58. //DisableCache 禁用缓存
  59. func (r *CRUD) DisableCache() *CRUD {
  60. r.enableCache = false
  61. return r
  62. }
  63. //WithCache 启用缓存
  64. func (r *CRUD) WithCache() *CRUD {
  65. r.enableCache = true
  66. return r
  67. }
  68. //WithDebug 开启调试
  69. func (r *CRUD) WithDebug() *CRUD {
  70. r.db.Logger = r.db.Logger.LogMode(logger.Info)
  71. return r
  72. }
  73. //RegisterDelegate 注册一个旁观者
  74. func (r *CRUD) RegisterDelegate(d Delegate) {
  75. r.delegate.Register(d)
  76. }
  77. //Attach 注册一个模型
  78. func (r *CRUD) Attach(ctx context.Context, model Model, cbs ...Option) (err error) {
  79. var (
  80. opts *Options
  81. )
  82. opts = newOptions()
  83. for _, cb := range cbs {
  84. cb(opts)
  85. }
  86. if opts.DB == nil {
  87. opts.DB = r.db
  88. }
  89. if err = r.db.AutoMigrate(model); err != nil {
  90. return
  91. }
  92. if err = r.migrateSchema(ctx, DefaultNamespace, model); err != nil {
  93. return
  94. }
  95. opts.Delegate = r.delegate
  96. opts.LookupFunc = r.VisibleSchemas
  97. rt := newRestful(model, opts)
  98. r.modules = append(r.modules, rt)
  99. if r.api != nil {
  100. r.api.Attach(rt)
  101. }
  102. return
  103. }
  104. //migrateSchema 合并表的结构数据
  105. func (r *CRUD) migrateSchema(ctx context.Context, namespace string, model Model) (err error) {
  106. var (
  107. pos int
  108. columnLabel string
  109. columnName string
  110. columnIsExists bool
  111. stmt *gorm.Statement
  112. schemas []*Schema
  113. schemaModels []*Schema
  114. )
  115. schemas, err = r.GetSchemas(ctx, namespace, model.ModuleName(), model.TableName())
  116. stmt = r.createStatement(r.db)
  117. if err = stmt.Parse(model); err != nil {
  118. return
  119. }
  120. if len(schemas) > 0 {
  121. pos = len(schemas)
  122. }
  123. for index, field := range stmt.Schema.Fields {
  124. columnName = field.DBName
  125. if columnName == "-" {
  126. continue
  127. }
  128. if columnName == "" {
  129. columnName = field.Name
  130. }
  131. columnIsExists = false
  132. for _, sm := range schemas {
  133. if sm.Column == columnName {
  134. columnIsExists = true
  135. break
  136. }
  137. }
  138. if columnIsExists {
  139. continue
  140. }
  141. columnLabel = field.Tag.Get("comment")
  142. if columnLabel == "" {
  143. columnLabel = generateFieldName(field.DBName)
  144. }
  145. isPrimaryKey := uint8(0)
  146. if field.PrimaryKey {
  147. isPrimaryKey = 1
  148. }
  149. schemaModel := &Schema{
  150. Namespace: namespace,
  151. ModuleName: model.ModuleName(),
  152. TableName: model.TableName(),
  153. Enable: 1,
  154. Column: columnName,
  155. Label: columnLabel,
  156. Type: strings.ToLower(dataTypeOf(field)),
  157. Format: strings.ToLower(dataFormatOf(field)),
  158. Native: 1,
  159. IsPrimaryKey: isPrimaryKey,
  160. Scenarios: generateFieldScenario(index, field),
  161. Rule: generateFieldRule(field),
  162. Attribute: generateFieldAttribute(field),
  163. Position: pos,
  164. }
  165. schemaModels = append(schemaModels, schemaModel)
  166. pos++
  167. }
  168. if len(schemaModels) > 0 {
  169. err = r.db.Create(schemaModels).Error
  170. }
  171. return
  172. }
  173. //GetSchemas 获取表的结构数据
  174. func (r *CRUD) GetSchemas(ctx context.Context, namespace, moduleName, tableName string) (schemas []*Schema, err error) {
  175. cacheKey := fmt.Sprintf("schema:%s:%s:%s", namespace, moduleName, tableName)
  176. if r.enableCache {
  177. if v, ok := cache.Get(cacheKey); ok {
  178. return v.([]*Schema), nil
  179. }
  180. }
  181. schemas = make([]*Schema, 0)
  182. if len(namespace) == 0 {
  183. namespace = DefaultNamespace
  184. }
  185. sess := r.db.Session(&gorm.Session{NewDB: true, Context: ctx})
  186. if err = sess.Where("`namespace`=? AND `module_name`=? AND `table_name`=?", namespace, moduleName, tableName).Order("position,id ASC").Find(&schemas).Error; err == nil {
  187. if r.enableCache {
  188. cache.SetEx(cacheKey, schemas, time.Minute*30)
  189. }
  190. }
  191. return
  192. }
  193. //VisibleSchemas 获取指定场景表的数据
  194. func (r *CRUD) VisibleSchemas(ctx context.Context, ns, moduleName, tableName, scene string) (result []*Schema) {
  195. var (
  196. err error
  197. schemas []*Schema
  198. )
  199. if schemas, err = r.GetSchemas(ctx, ns, moduleName, tableName); err == nil {
  200. result = make([]*Schema, 0, len(schemas))
  201. for _, s := range schemas {
  202. if s.Scenarios.Has(scene) || s.Attribute.PrimaryKey {
  203. result = append(result, s)
  204. }
  205. }
  206. }
  207. return
  208. }
  209. //New create new restful
  210. func New(dialer gorm.Dialector) (r *CRUD, err error) {
  211. r = &CRUD{
  212. delegate: &delegate{},
  213. enableCache: true,
  214. }
  215. if r.db, err = gorm.Open(dialer); err != nil {
  216. return
  217. }
  218. r.api = &Api{crud: r}
  219. r.db.Logger = loggerpkg.New()
  220. err = r.db.AutoMigrate(&Schema{})
  221. return
  222. }