1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- package operations
- import (
- "git.sxidc.com/go-tools/utils/template"
- "github.com/iancoleman/strcase"
- "github.com/pkg/errors"
- "reflect"
- )
- const (
- tagTpl = `gorm:"column:{{ .Name }};type:{{ .Type }};comment:{{ .Comment }};
- {{- if .PrimaryKey -}}primaryKey;{{- end -}}
- {{- if .Size -}}size:{{ .Size }};{{- end -}}
- {{- if .Unique -}}unique;{{- end -}}
- {{- if .NotNull -}}not null;{{- end -}}
- {{- if .Index -}}index;{{- end -}}
- {{- if .UniqueIndex -}}uniqueIndex:{{ .UniqueIndex }};{{- end -}}
- {{- if .Default -}}default:{{ .Default }};{{- end -}}
- "`
- )
- type Table struct {
- TableName string
- Columns []TableColumn
- }
- func (spec *Table) ToDBModel() (any, error) {
- dbModelFields := make([]reflect.StructField, 0)
- for _, column := range spec.Columns {
- dbModelField, err := column.ToDBModelField()
- if err != nil {
- return nil, err
- }
- dbModelFields = append(dbModelFields, *dbModelField)
- }
- structType := reflect.StructOf(dbModelFields)
- structVar := reflect.New(structType).Elem().Addr().Interface()
- return structVar, nil
- }
- type TableColumn struct {
- Name string
- Type string
- Comment string
- PrimaryKey bool
- Size int
- Unique bool
- NotNull bool
- Index bool
- UniqueIndex string
- Default any
- }
- func (column *TableColumn) ToDBModelField() (*reflect.StructField, error) {
- tag, err := template.ParseTemplateStringToString(tagTpl, column)
- if err != nil {
- return nil, errors.New(err.Error())
- }
- return &reflect.StructField{
- Name: strcase.ToCamel(column.Name),
- Type: reflect.TypeOf(""),
- Tag: reflect.StructTag(tag),
- }, nil
- }
|