schema.go 15 KB

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