crud.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. func (r *CRUD) DB() *gorm.DB {
  59. return r.db
  60. }
  61. //DisableCache 禁用缓存
  62. func (r *CRUD) DisableCache() *CRUD {
  63. r.enableCache = false
  64. return r
  65. }
  66. //WithCache 启用缓存
  67. func (r *CRUD) WithCache() *CRUD {
  68. r.enableCache = true
  69. return r
  70. }
  71. //WithDebug 开启调试
  72. func (r *CRUD) WithDebug() *CRUD {
  73. r.db.Logger = r.db.Logger.LogMode(logger.Info)
  74. return r
  75. }
  76. //RegisterDelegate 注册一个旁观者
  77. func (r *CRUD) RegisterDelegate(d Delegate) {
  78. r.delegate.Register(d)
  79. }
  80. //Attach 注册一个模型
  81. func (r *CRUD) Attach(ctx context.Context, model Model, cbs ...Option) (err error) {
  82. var (
  83. opts *Options
  84. )
  85. opts = newOptions()
  86. for _, cb := range cbs {
  87. cb(opts)
  88. }
  89. if opts.DB == nil {
  90. opts.DB = r.db
  91. }
  92. if err = r.db.AutoMigrate(model); err != nil {
  93. return
  94. }
  95. //不启用schema
  96. if opts.Schema {
  97. if err = r.migrateSchema(ctx, DefaultNamespace, model); err != nil {
  98. return
  99. }
  100. }
  101. opts.Delegate = r.delegate
  102. opts.LookupFunc = r.VisibleSchemas
  103. rt := newRestful(model, opts)
  104. r.modules = append(r.modules, rt)
  105. if r.api != nil {
  106. r.api.Attach(rt)
  107. }
  108. return
  109. }
  110. //migrateSchema 合并表的结构数据
  111. func (r *CRUD) migrateSchema(ctx context.Context, namespace string, model Model) (err error) {
  112. var (
  113. pos int
  114. columnLabel string
  115. columnName string
  116. columnIsExists bool
  117. stmt *gorm.Statement
  118. schemas []*Schema
  119. schemaModels []*Schema
  120. )
  121. schemas, err = r.GetSchemas(ctx, namespace, model.ModuleName(), model.TableName())
  122. stmt = r.createStatement(r.db)
  123. if err = stmt.Parse(model); err != nil {
  124. return
  125. }
  126. if len(schemas) > 0 {
  127. pos = len(schemas)
  128. }
  129. for index, field := range stmt.Schema.Fields {
  130. columnName = field.DBName
  131. if columnName == "-" {
  132. continue
  133. }
  134. if columnName == "" {
  135. columnName = field.Name
  136. }
  137. columnIsExists = false
  138. for _, sm := range schemas {
  139. if sm.Column == columnName {
  140. columnIsExists = true
  141. break
  142. }
  143. }
  144. if columnIsExists {
  145. continue
  146. }
  147. columnLabel = field.Tag.Get("comment")
  148. if columnLabel == "" {
  149. columnLabel = generateFieldName(field.DBName)
  150. }
  151. isPrimaryKey := uint8(0)
  152. if field.PrimaryKey {
  153. isPrimaryKey = 1
  154. }
  155. schemaModel := &Schema{
  156. Namespace: namespace,
  157. ModuleName: model.ModuleName(),
  158. TableName: model.TableName(),
  159. Enable: 1,
  160. Column: columnName,
  161. Label: columnLabel,
  162. Type: strings.ToLower(dataTypeOf(field)),
  163. Format: strings.ToLower(dataFormatOf(field)),
  164. Native: 1,
  165. IsPrimaryKey: isPrimaryKey,
  166. Scenarios: generateFieldScenario(index, field),
  167. Rule: generateFieldRule(field),
  168. Attribute: generateFieldAttribute(field),
  169. Position: pos,
  170. }
  171. schemaModels = append(schemaModels, schemaModel)
  172. pos++
  173. }
  174. if len(schemaModels) > 0 {
  175. err = r.db.Create(schemaModels).Error
  176. }
  177. return
  178. }
  179. //GetSchemas 获取表的结构数据
  180. func (r *CRUD) GetSchemas(ctx context.Context, namespace, moduleName, tableName string) (schemas []*Schema, err error) {
  181. cacheKey := fmt.Sprintf("schema:%s:%s:%s", namespace, moduleName, tableName)
  182. if r.enableCache {
  183. if v, ok := cache.Get(cacheKey); ok {
  184. return v.([]*Schema), nil
  185. }
  186. }
  187. schemas = make([]*Schema, 0)
  188. if len(namespace) == 0 {
  189. namespace = DefaultNamespace
  190. }
  191. sess := r.db.Session(&gorm.Session{NewDB: true, Context: ctx})
  192. if err = sess.Where("`namespace`=? AND `module_name`=? AND `table_name`=?", namespace, moduleName, tableName).Order("position,id ASC").Find(&schemas).Error; err == nil {
  193. if r.enableCache {
  194. cache.SetEx(cacheKey, schemas, time.Minute*30)
  195. }
  196. }
  197. return
  198. }
  199. //VisibleSchemas 获取指定场景表的数据
  200. func (r *CRUD) VisibleSchemas(ctx context.Context, ns, moduleName, tableName, scene string) (result []*Schema) {
  201. var (
  202. err error
  203. schemas []*Schema
  204. )
  205. if schemas, err = r.GetSchemas(ctx, ns, moduleName, tableName); err == nil {
  206. result = make([]*Schema, 0, len(schemas))
  207. for _, s := range schemas {
  208. if s.Scenarios.Has(scene) || s.Attribute.PrimaryKey {
  209. result = append(result, s)
  210. }
  211. }
  212. }
  213. return
  214. }
  215. //New create new restful
  216. func New(dialer gorm.Dialector) (r *CRUD, err error) {
  217. r = &CRUD{
  218. delegate: &delegate{},
  219. enableCache: true,
  220. }
  221. if r.db, err = gorm.Open(dialer); err != nil {
  222. return
  223. }
  224. r.api = &Api{crud: r}
  225. r.db.Logger = loggerpkg.New()
  226. err = r.db.AutoMigrate(&Schema{})
  227. return
  228. }