schema.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. package rest
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "reflect"
  6. "strings"
  7. "time"
  8. "git.nspix.com/golang/micro/helper/utils"
  9. lru "github.com/hashicorp/golang-lru"
  10. "gorm.io/gorm"
  11. "gorm.io/gorm/clause"
  12. "gorm.io/gorm/schema"
  13. )
  14. var (
  15. ErrInvalidModelInstance = errors.New("invalid model instance")
  16. timeKind = reflect.TypeOf(time.Time{}).Kind()
  17. timePtrKind = reflect.TypeOf(&time.Time{}).Kind()
  18. schemaCache, _ = lru.New(512)
  19. DefaultNamespace = "default"
  20. schemaDB *gorm.DB
  21. )
  22. const (
  23. ScenarioCreate = "create"
  24. ScenarioUpdate = "update"
  25. ScenarioDelete = "delete"
  26. ScenarioSearch = "search"
  27. ScenarioExport = "export"
  28. ScenarioList = "list"
  29. ScenarioView = "view"
  30. ScenarioMapping = "mapping"
  31. Basic = "basic"
  32. Advanced = "advanced"
  33. MatchExactly = "exactly" //精确匹配
  34. MatchFuzzy = "fuzzy" //模糊匹配
  35. )
  36. type (
  37. MigrateOptions struct {
  38. Callback func(schema *Schema) (err error)
  39. }
  40. MigrateOption func(o *MigrateOptions)
  41. Rule struct { //规则配置
  42. Min int `json:"min"`
  43. Max int `json:"max"`
  44. Type string `json:"type"`
  45. Unique bool `json:"unique"`
  46. Required []string `json:"required"`
  47. Regular string `json:"regular"`
  48. }
  49. FieldValue struct {
  50. Label string `json:"label"`
  51. Value interface{} `json:"value"`
  52. Color string `json:"color"`
  53. }
  54. visibleCond struct {
  55. Column string `json:"column"`
  56. Values []interface{} `json:"values"`
  57. }
  58. liveAttribute struct { //值容器
  59. Enable bool `json:"enable"`
  60. Type string `json:"type"`
  61. Url string `json:"url"`
  62. Columns []string `json:"columns"`
  63. }
  64. Properties struct { //属性配置
  65. Match string `json:"match"` //匹配模式
  66. PrimaryKey bool `json:"primary_key"` //是否为主键
  67. DefaultValue string `json:"default_value"` //默认值
  68. Readonly []string `json:"readonly"` //只读场景
  69. Disable []string `json:"disable"` //禁用场景
  70. Visible []visibleCond `json:"visible"` //可见条件
  71. Values []FieldValue `json:"values"` //值
  72. Live liveAttribute `json:"live"` //延时加载配置
  73. Icon string `json:"icon"` //显示图标
  74. Suffix string `json:"suffix"` //追加内容
  75. Tooltip string `json:"tooltip"` //字段提示信息
  76. Description string `json:"description"` //字段说明信息
  77. }
  78. Schema struct { //Schema的表
  79. Id uint64 `json:"id" gorm:"primary_key"`
  80. CreatedAt int64 `json:"created_at" gorm:"autoCreateTime"` //创建时间
  81. UpdatedAt int64 `json:"updated_at" gorm:"autoUpdateTime"` //更新时间
  82. Namespace string `json:"namespace" gorm:"column:namespace;type:char(60);index"` //域
  83. Module string `json:"module" gorm:"column:module_name;type:varchar(60);index"` //模块名称
  84. Table string `json:"table" gorm:"column:table_name;type:varchar(120);index"` //表名称
  85. Enable uint8 `json:"enable" gorm:"column:enable;type:int(1)"` //是否启用
  86. Tag string `json:"tag" gorm:"column:tag;type:varchar(60)"` //字段归类
  87. Column string `json:"column" gorm:"type:varchar(120)"` //字段名称
  88. Label string `json:"label" gorm:"type:varchar(120)"` //显示名称
  89. Type string `json:"type" gorm:"type:varchar(120)"` //字段类型
  90. Format string `json:"format" gorm:"type:varchar(120)"` //字段格式
  91. Native uint8 `json:"native" gorm:"type:int(1)"` //是否为原生字段
  92. PrimaryKey uint8 `json:"primary_key" gorm:"type:int(1)"` //是否为主键
  93. Expression string `json:"expression" gorm:"type:varchar(526)"` //计算规则
  94. Rules string `json:"rules" gorm:"type:varchar(2048)"` //字段规则
  95. Scenarios string `json:"scenarios" gorm:"type:varchar(120)"` //场景
  96. Properties string `json:"properties" gorm:"type:varchar(4096)"` //字段属性
  97. Position int `json:"position"` //字段排序位置
  98. properties *Properties
  99. }
  100. Field struct {
  101. Column string `json:"column" gorm:"type:varchar(120)"`
  102. Label string `json:"label" gorm:"type:varchar(120)"`
  103. Type string `json:"type" gorm:"type:varchar(120)"`
  104. Format string `json:"format" gorm:"type:varchar(120)"`
  105. Scenario string `json:"scenario" gorm:"type:varchar(120)"`
  106. Rules string `json:"rules" gorm:"type:varchar(2048)"`
  107. Options string `json:"options" gorm:"type:varchar(4096)"`
  108. }
  109. )
  110. func (r *Rule) String() string {
  111. buf, _ := json.Marshal(r)
  112. return string(buf)
  113. }
  114. // getProperties 获取属性
  115. func (schema *Schema) getProperties() *Properties {
  116. if schema.properties == nil {
  117. schema.properties = &Properties{}
  118. _ = json.Unmarshal([]byte(schema.Properties), schema.properties)
  119. }
  120. return schema.properties
  121. }
  122. func dataTypeOf(field *schema.Field) string {
  123. var dataType string
  124. reflectType := field.FieldType
  125. for reflectType.Kind() == reflect.Ptr {
  126. reflectType = reflectType.Elem()
  127. }
  128. dataValue := reflect.Indirect(reflect.New(reflectType))
  129. switch dataValue.Kind() {
  130. case reflect.Bool:
  131. dataType = "boolean"
  132. case reflect.Int8, reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint8, reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  133. dataType = "integer"
  134. case reflect.Float32, reflect.Float64:
  135. dataType = "double"
  136. case reflect.Struct:
  137. if _, ok := dataValue.Interface().(time.Time); ok {
  138. dataType = "string"
  139. }
  140. default:
  141. dataType = "string"
  142. }
  143. return dataType
  144. }
  145. //获取字段格式
  146. func dataFormatOf(field *schema.Field) string {
  147. var dataType string
  148. dataType = field.Tag.Get("format")
  149. if dataType != "" {
  150. return dataType
  151. }
  152. //如果有枚举值,直接设置为下拉类型
  153. enum := field.Tag.Get("enum")
  154. if enum != "" {
  155. return "dropdown"
  156. }
  157. reflectType := field.FieldType
  158. for reflectType.Kind() == reflect.Ptr {
  159. reflectType = reflectType.Elem()
  160. }
  161. //时间处理
  162. if utils.InArray(field.Name, []string{"CreatedAt", "UpdatedAt", "DeletedAt"}) {
  163. return "datetime"
  164. }
  165. dataValue := reflect.Indirect(reflect.New(reflectType))
  166. switch dataValue.Kind() {
  167. case timeKind, timePtrKind:
  168. dataType = "datetime"
  169. case reflect.Bool:
  170. dataType = "boolean"
  171. case reflect.Int8, reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint8, reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  172. dataType = "integer"
  173. case reflect.Float32, reflect.Float64:
  174. dataType = "decimal"
  175. case reflect.Struct:
  176. if _, ok := dataValue.Interface().(time.Time); ok {
  177. dataType = "datetime"
  178. }
  179. default:
  180. dataType = "string"
  181. }
  182. return dataType
  183. }
  184. func createStatement(db *gorm.DB) *gorm.Statement {
  185. return &gorm.Statement{
  186. DB: db,
  187. ConnPool: db.Statement.ConnPool,
  188. Context: db.Statement.Context,
  189. Clauses: map[string]clause.Clause{},
  190. }
  191. }
  192. // visibleSchemas 获取某个场景下面的字段
  193. func visibleSchemas(namespace, modelName, tableName, scenario string) (schemas []*Schema) {
  194. schemas, _ = getSchemas(namespace, modelName, tableName)
  195. values := make([]*Schema, 0)
  196. for _, scm := range schemas {
  197. if scm.Enable != 1 {
  198. continue
  199. }
  200. if scm.PrimaryKey == 1 {
  201. values = append(values, scm)
  202. } else {
  203. if strings.Contains(scm.Scenarios, scenario) {
  204. values = append(values, scm)
  205. }
  206. }
  207. }
  208. return values
  209. }
  210. // getSchemas 获取某个模型下面所有的字段配置
  211. func getSchemas(namespace, moduleName, tableName string) (schemas []*Schema, err error) {
  212. schemas = make([]*Schema, 0)
  213. cacheKey := namespace + ":" + tableName + "@" + moduleName
  214. if v, ok := schemaCache.Get(cacheKey); ok {
  215. return v.([]*Schema), nil
  216. }
  217. if len(namespace) == 0 {
  218. namespace = DefaultNamespace
  219. }
  220. if err = schemaDB.Where("`namespace`=? AND `module_name`=? AND `table_name`=?", namespace, moduleName, tableName).Order("position,id ASC").Find(&schemas).Error; err == nil {
  221. //修改表结构缓存
  222. if len(schemas) > 0 {
  223. schemaCache.Add(cacheKey, schemas)
  224. }
  225. }
  226. return
  227. }
  228. func getSchemasNoCache(db *gorm.DB, namespace, moduleName, tableName string) (schemas []*Schema, err error) {
  229. tx := db.Session(&gorm.Session{NewDB: true, SkipHooks: true})
  230. if len(namespace) == 0 {
  231. namespace = DefaultNamespace
  232. }
  233. err = tx.Where("`namespace`=? AND `module_name`=? AND `table_name`=?", namespace, moduleName, tableName).Order("position,id ASC").Find(&schemas).Error
  234. return
  235. }
  236. // invalidCache 删除表结构缓存
  237. func invalidCache(namespace, moduleName, tableName string) {
  238. cacheKey := namespace + ":" + tableName + "@" + moduleName
  239. schemaCache.Remove(cacheKey)
  240. }
  241. // generateFieldRule 生成数据校验规则
  242. func generateFieldRule(field *schema.Field) string {
  243. r := &Rule{
  244. Required: []string{},
  245. }
  246. if field.GORMDataType == schema.String {
  247. r.Max = field.Size
  248. }
  249. if field.GORMDataType == schema.Int || field.GORMDataType == schema.Float || field.GORMDataType == schema.Uint {
  250. r.Max = field.Scale
  251. }
  252. if field.NotNull {
  253. r.Required = []string{ScenarioCreate, ScenarioUpdate}
  254. }
  255. if field.PrimaryKey {
  256. r.Unique = true
  257. }
  258. return r.String()
  259. }
  260. // generateFieldProperties 生成数据属性
  261. func generateFieldProperties(field *schema.Field) string {
  262. attr := &Properties{
  263. Match: MatchFuzzy,
  264. PrimaryKey: field.PrimaryKey,
  265. DefaultValue: field.DefaultValue,
  266. Readonly: []string{},
  267. Disable: []string{},
  268. Visible: nil,
  269. Values: make([]FieldValue, 0),
  270. Live: liveAttribute{},
  271. Description: field.DBName,
  272. }
  273. //赋值属性
  274. props := field.Tag.Get("props")
  275. if props != "" {
  276. vs := strings.Split(props, ";")
  277. for _, str := range vs {
  278. kv := strings.SplitN(str, ":", 2)
  279. if len(kv) != 2 {
  280. continue
  281. }
  282. switch strings.ToLower(kv[0]) {
  283. case "icon":
  284. attr.Icon = kv[1]
  285. case "suffix":
  286. attr.Suffix = kv[1]
  287. case "tooltip":
  288. attr.Tooltip = kv[1]
  289. case "description":
  290. attr.Description = kv[1]
  291. case "live":
  292. //在线数据解析
  293. ss := strings.Split(kv[1], ",")
  294. for _, s := range ss {
  295. if len(s) == 0 {
  296. continue
  297. }
  298. attr.Live.Enable = true
  299. if s == "dropdown" || s == "cascader" {
  300. attr.Live.Type = s
  301. } else if s[0] == '/' || strings.HasPrefix(s, "http") {
  302. attr.Live.Url = s
  303. } else {
  304. if strings.IndexByte(s, '.') > -1 {
  305. attr.Live.Columns = strings.Split(s, ".")
  306. }
  307. }
  308. }
  309. }
  310. }
  311. }
  312. //赋值枚举值
  313. enumns := field.Tag.Get("enum")
  314. if enumns != "" {
  315. vs := strings.Split(enumns, ";")
  316. for _, str := range vs {
  317. kv := strings.SplitN(str, ":", 2)
  318. if len(kv) != 2 {
  319. continue
  320. }
  321. fv := FieldValue{Value: kv[0]}
  322. //颜色分隔符
  323. if pos := strings.IndexByte(kv[1], '#'); pos > -1 {
  324. fv.Label = kv[1][:pos]
  325. fv.Color = kv[1][pos:]
  326. } else {
  327. fv.Label = kv[1]
  328. }
  329. attr.Values = append(attr.Values, fv)
  330. }
  331. }
  332. if !field.Creatable {
  333. attr.Disable = append(attr.Disable, ScenarioCreate)
  334. }
  335. if !field.Updatable {
  336. attr.Disable = append(attr.Disable, ScenarioUpdate)
  337. }
  338. attr.Tooltip = field.Comment
  339. if buf, err := json.Marshal(attr); err == nil {
  340. return string(buf)
  341. }
  342. return ""
  343. }
  344. // generateFieldScenario 生成字段应用场景
  345. func generateFieldScenario(field *schema.Field) string {
  346. var ss []string
  347. if v, ok := field.Tag.Lookup("scenarios"); ok {
  348. v = strings.TrimSpace(v)
  349. if v != "" {
  350. ss = strings.Split(v, ";")
  351. }
  352. } else {
  353. if field.PrimaryKey {
  354. ss = []string{ScenarioList, ScenarioView, ScenarioExport}
  355. } else if field.Name == "CreatedAt" || field.Name == "UpdatedAt" {
  356. ss = []string{ScenarioList}
  357. } else if field.Name == "DeletedAt" || field.Name == "Namespace" {
  358. //不添加任何显示场景
  359. ss = []string{}
  360. } else {
  361. //高级字段只配置一些简单的场景
  362. if field.Tag.Get("tag") == Advanced {
  363. ss = []string{ScenarioCreate, ScenarioUpdate, ScenarioView, ScenarioExport}
  364. } else {
  365. ss = []string{ScenarioSearch, ScenarioList, ScenarioCreate, ScenarioUpdate, ScenarioView, ScenarioExport}
  366. }
  367. }
  368. }
  369. if buf, err := json.Marshal(ss); err == nil {
  370. return string(buf)
  371. }
  372. return ""
  373. }
  374. // migrate 合并数据表结构
  375. func migrateUp(namespace string, value interface{}, opts *MigrateOptions) (err error) {
  376. var (
  377. pos int
  378. ok bool
  379. model Model
  380. moduleName string
  381. tableName string
  382. stmt *gorm.Statement
  383. scm *Schema
  384. schemas []*Schema
  385. values []*Schema
  386. field *schema.Field
  387. columnIsExists bool
  388. columnName string
  389. columnLabel string
  390. )
  391. if schemaDB == nil {
  392. return errors.New("call initSchema first")
  393. }
  394. if len(namespace) == 0 {
  395. namespace = DefaultNamespace
  396. }
  397. stmt = createStatement(schemaDB)
  398. if value == nil {
  399. return ErrInvalidModelInstance
  400. }
  401. if model, ok = value.(Model); !ok {
  402. return ErrInvalidModelInstance
  403. }
  404. moduleName = model.ModuleName()
  405. tableName = model.TableName()
  406. if err = stmt.Parse(value); err != nil {
  407. return err
  408. }
  409. if schemas, err = getSchemas(namespace, moduleName, tableName); err != nil {
  410. schemas = make([]*Schema, 0)
  411. }
  412. totalCount := len(stmt.Schema.Fields)
  413. //遍历所有字段
  414. for _, field = range stmt.Schema.Fields {
  415. columnName = field.DBName
  416. if columnName == "-" {
  417. continue
  418. }
  419. if columnName == "" {
  420. columnName = field.Name
  421. }
  422. columnIsExists = false
  423. for _, scm = range schemas {
  424. if scm.Column == columnName {
  425. columnIsExists = true
  426. break
  427. }
  428. }
  429. if columnIsExists {
  430. continue
  431. }
  432. columnLabel = field.Tag.Get("comment")
  433. if columnLabel == "" {
  434. columnLabel = strings.Join(utils.BreakUp(field.DBName), " ")
  435. }
  436. isPrimaryKey := uint8(0)
  437. if field.PrimaryKey {
  438. isPrimaryKey = 1
  439. }
  440. pv := pos
  441. //默认把创建时间和更新时间放到最后
  442. if field.Name == "CreatedAt" || field.Name == "UpdatedAt" || field.Name == "DeletedAt" {
  443. pv = totalCount
  444. }
  445. tag := field.Tag.Get("tag")
  446. if tag == "" {
  447. tag = Basic
  448. }
  449. schemaModel := &Schema{
  450. Namespace: namespace,
  451. Module: moduleName,
  452. Table: tableName,
  453. Enable: 1,
  454. Tag: tag,
  455. Column: columnName,
  456. Label: columnLabel,
  457. Type: strings.ToLower(dataTypeOf(field)),
  458. Format: strings.ToLower(dataFormatOf(field)),
  459. Native: 1,
  460. PrimaryKey: isPrimaryKey,
  461. Rules: generateFieldRule(field),
  462. Scenarios: generateFieldScenario(field),
  463. Properties: generateFieldProperties(field),
  464. Position: pv,
  465. }
  466. if opts.Callback != nil {
  467. if err = opts.Callback(schemaModel); err == nil {
  468. values = append(values, schemaModel)
  469. pos++
  470. }
  471. } else {
  472. values = append(values, schemaModel)
  473. pos++
  474. }
  475. }
  476. if len(values) > 0 {
  477. //batch save
  478. err = schemaDB.Create(values).Error
  479. }
  480. return
  481. }
  482. func initSchema(db *gorm.DB) (err error) {
  483. schemaDB = db.Session(&gorm.Session{NewDB: true})
  484. err = schemaDB.AutoMigrate(&Schema{})
  485. return
  486. }