This repository has been archived by the owner on Jan 8, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathschema_builder.go
85 lines (72 loc) · 1.87 KB
/
schema_builder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package nero
import (
"github.com/stevenferrer/mira"
)
// SchemaBuilder is used for building a schema
type SchemaBuilder struct {
sc *Schema
}
// NewSchemaBuilder takes a struct value and returns a SchemaBuilder
func NewSchemaBuilder(v interface{}) *SchemaBuilder {
return &SchemaBuilder{sc: &Schema{
typeInfo: mira.NewTypeInfo(v),
fields: []*Field{},
templates: []Template{},
}}
}
// PkgName sets the package name
func (sb *SchemaBuilder) PkgName(pkgName string) *SchemaBuilder {
sb.sc.pkgName = pkgName
return sb
}
// Table sets the database table/collection name
func (sb *SchemaBuilder) Table(table string) *SchemaBuilder {
sb.sc.table = table
return sb
}
// Identity sets the identity field
func (sb *SchemaBuilder) Identity(field *Field) *SchemaBuilder {
sb.sc.identity = field
return sb
}
// Fields sets the fields
func (sb *SchemaBuilder) Fields(fields ...*Field) *SchemaBuilder {
sb.sc.fields = append(sb.sc.fields, fields...)
return sb
}
// Templates sets the templates
func (sb *SchemaBuilder) Templates(templates ...Template) *SchemaBuilder {
sb.sc.templates = append(sb.sc.templates, templates...)
return sb
}
// Build builds the schema
func (sb *SchemaBuilder) Build() *Schema {
templates := sb.sc.templates
// use default template set
if len(templates) == 0 {
templates = []Template{
NewPostgresTemplate(),
NewSQLiteTemplate(),
}
}
// get pkg imports
importMap := map[string]int{}
for _, fld := range append(sb.sc.fields, sb.sc.identity) {
if fld.typeInfo.PkgPath() != "" {
importMap[fld.typeInfo.PkgPath()] = 1
}
}
imports := []string{sb.sc.typeInfo.PkgPath()}
for imp := range importMap {
imports = append(imports, imp)
}
return &Schema{
typeInfo: sb.sc.typeInfo,
pkgName: sb.sc.pkgName,
table: sb.sc.table,
identity: sb.sc.identity,
fields: sb.sc.fields,
imports: imports,
templates: templates,
}
}