table.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package operations
  2. import (
  3. "git.sxidc.com/go-tools/utils/template"
  4. "github.com/iancoleman/strcase"
  5. "reflect"
  6. )
  7. const (
  8. tagTpl = `gorm:"column:{{ .Name }};type:{{ .Type }};comment:{{ .Comment }};
  9. {{- if .PrimaryKey -}}primaryKey;{{- end -}}
  10. {{- if .Size -}}size:{{ .Size }};{{- end -}}
  11. {{- if .Unique -}}unique;{{- end -}}
  12. {{- if .NotNull -}}not null;{{- end -}}
  13. {{- if .Index -}}index;{{- end -}}
  14. {{- if .UniqueIndex -}}uniqueIndex:{{ .UniqueIndex }};{{- end -}}
  15. {{- if .Default -}}default:{{ .Default }};{{- end -}}
  16. "`
  17. )
  18. type Table struct {
  19. TableName string
  20. Columns []TableColumn
  21. }
  22. func (spec *Table) ToDBModel() (any, error) {
  23. dbModelFields := make([]reflect.StructField, 0)
  24. for _, column := range spec.Columns {
  25. dbModelField, err := column.ToDBModelField()
  26. if err != nil {
  27. return nil, err
  28. }
  29. dbModelFields = append(dbModelFields, *dbModelField)
  30. }
  31. structType := reflect.StructOf(dbModelFields)
  32. structVar := reflect.New(structType).Elem().Addr().Interface()
  33. return structVar, nil
  34. }
  35. type TableColumn struct {
  36. Name string
  37. Type string
  38. Comment string
  39. PrimaryKey bool
  40. Size int
  41. Unique bool
  42. NotNull bool
  43. Index bool
  44. UniqueIndex string
  45. Default any
  46. }
  47. func (column *TableColumn) ToDBModelField() (*reflect.StructField, error) {
  48. tag, err := template.ParseTemplateStringToString(tagTpl, column)
  49. if err != nil {
  50. return nil, err
  51. }
  52. return &reflect.StructField{
  53. Name: strcase.ToCamel(column.Name),
  54. Type: reflect.TypeOf(""),
  55. Tag: reflect.StructTag(tag),
  56. }, nil
  57. }