crud.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. r.modules = append(r.modules, newRestful(model, opts))
  98. return
  99. }
  100. //migrateSchema 合并表的结构数据
  101. func (r *CRUD) migrateSchema(ctx context.Context, namespace string, model Model) (err error) {
  102. var (
  103. pos int
  104. columnLabel string
  105. columnName string
  106. columnIsExists bool
  107. stmt *gorm.Statement
  108. schemas []*Schema
  109. schemaModels []*Schema
  110. )
  111. schemas, err = r.GetSchemas(ctx, namespace, model.ModuleName(), model.TableName())
  112. stmt = r.createStatement(r.db)
  113. if err = stmt.Parse(model); err != nil {
  114. return
  115. }
  116. if len(schemas) > 0 {
  117. pos = len(schemas)
  118. }
  119. for index, field := range stmt.Schema.Fields {
  120. columnName = field.DBName
  121. if columnName == "-" {
  122. continue
  123. }
  124. if columnName == "" {
  125. columnName = field.Name
  126. }
  127. columnIsExists = false
  128. for _, sm := range schemas {
  129. if sm.Column == columnName {
  130. columnIsExists = true
  131. break
  132. }
  133. }
  134. if columnIsExists {
  135. continue
  136. }
  137. columnLabel = field.Tag.Get("comment")
  138. if columnLabel == "" {
  139. columnLabel = generateFieldName(field.DBName)
  140. }
  141. isPrimaryKey := uint8(0)
  142. if field.PrimaryKey {
  143. isPrimaryKey = 1
  144. }
  145. schemaModel := &Schema{
  146. Namespace: namespace,
  147. ModuleName: model.ModuleName(),
  148. TableName: model.TableName(),
  149. Enable: 1,
  150. Column: columnName,
  151. Label: columnLabel,
  152. Type: strings.ToLower(dataTypeOf(field)),
  153. Format: strings.ToLower(dataFormatOf(field)),
  154. Native: 1,
  155. IsPrimaryKey: isPrimaryKey,
  156. Scenarios: generateFieldScenario(index, field),
  157. Rule: generateFieldRule(field),
  158. Attribute: generateFieldAttribute(field),
  159. Position: pos,
  160. }
  161. schemaModels = append(schemaModels, schemaModel)
  162. pos++
  163. }
  164. if len(schemaModels) > 0 {
  165. err = r.db.Create(schemaModels).Error
  166. }
  167. return
  168. }
  169. //GetSchemas 获取表的结构数据
  170. func (r *CRUD) GetSchemas(ctx context.Context, namespace, moduleName, tableName string) (schemas []*Schema, err error) {
  171. cacheKey := fmt.Sprintf("schema:%s:%s:%s", namespace, moduleName, tableName)
  172. if r.enableCache {
  173. if v, ok := cache.Get(cacheKey); ok {
  174. return v.([]*Schema), nil
  175. }
  176. }
  177. schemas = make([]*Schema, 0)
  178. if len(namespace) == 0 {
  179. namespace = DefaultNamespace
  180. }
  181. sess := r.db.Session(&gorm.Session{NewDB: true, Context: ctx})
  182. if err = sess.Where("`namespace`=? AND `module_name`=? AND `table_name`=?", namespace, moduleName, tableName).Order("position,id ASC").Find(&schemas).Error; err == nil {
  183. if r.enableCache {
  184. cache.SetEx(cacheKey, schemas, time.Minute*30)
  185. }
  186. }
  187. return
  188. }
  189. //VisibleSchemas 获取指定场景表的数据
  190. func (r *CRUD) VisibleSchemas(ctx context.Context, ns, moduleName, tableName, scene string) (result []*Schema) {
  191. var (
  192. err error
  193. schemas []*Schema
  194. )
  195. if schemas, err = r.GetSchemas(ctx, ns, moduleName, tableName); err == nil {
  196. result = make([]*Schema, 0, len(schemas))
  197. for _, s := range schemas {
  198. if s.Scenarios.Has(scene) || s.Attribute.PrimaryKey {
  199. result = append(result, s)
  200. }
  201. }
  202. }
  203. return
  204. }
  205. //New create new restful
  206. func New(dialer gorm.Dialector) (r *CRUD, err error) {
  207. r = &CRUD{
  208. delegate: &delegate{},
  209. }
  210. if r.db, err = gorm.Open(dialer); err != nil {
  211. return
  212. }
  213. r.api = &Api{crud: r}
  214. r.db.Logger = loggerpkg.New()
  215. err = r.db.AutoMigrate(&Schema{})
  216. return
  217. }