table.go 1.6 KB

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