forked from goadesign/gorma
/
relationalfield.go
217 lines (192 loc) · 5.51 KB
/
relationalfield.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package dsl
import (
"bytes"
"strings"
"unicode"
"github.com/goadesign/goa/design"
"github.com/goadesign/goa/dslengine"
"github.com/goadesign/goa/goagen/codegen"
"github.com/kaizenplatform/gorma"
)
// DatabaseFieldName allows for customization of the column name
// by seting the struct tags. This is necessary to create correlate
// non standard column naming conventions in gorm.
func DatabaseFieldName(name string) {
if f, ok := relationalFieldDefinition(true); ok {
f.DatabaseFieldName = name
}
}
// Field is a DSL definition for a field in a Relational Model.
// Parameter Options:
//
// // A field called "Title" with default type `String`.
// Field("Title")
//
// // Explicitly specify the type.
// Field("Title", gorma.String)
//
// // "Title" field, as `String` with other DSL included.
// Field("Title", func(){... other field level dsl ...})
//
// // All options specified: name, type and dsl.
// Field("Title", gorma.String, func(){... other field level dsl ...})
func Field(name string, args ...interface{}) {
name = codegen.Goify(name, true)
name = SanitizeFieldName(name)
fieldType, dsl := parseFieldArgs(args...)
if s, ok := relationalModelDefinition(true); ok {
if s.RelationalFields == nil {
s.RelationalFields = make(map[string]*gorma.RelationalFieldDefinition)
}
field, ok := s.RelationalFields[name]
if !ok {
field = gorma.NewRelationalFieldDefinition()
field.FieldName = name
field.DefinitionDSL = dsl
field.Parent = s
field.Datatype = fieldType
} else {
// the field was auto-added by the model parser
// so we need to update whatever we can from this new definition
field.DefinitionDSL = dsl
field.Datatype = fieldType
}
if fieldType == gorma.Timestamp {
field.Timestamp = true
field.Description = "timestamp"
}
if fieldType == gorma.NullableTimestamp {
field.Timestamp = true
field.Nullable = true
field.Description = "nullable timestamp (soft delete)"
}
field.DatabaseFieldName = SanitizeDBFieldName(name)
s.RelationalFields[name] = field
}
}
// MapsFrom establishes a mapping relationship between a source
// Type field and this model. The source type must be a UserTypeDefinition "Type"
// in goa. These are typically Payloads.
func MapsFrom(utd *design.UserTypeDefinition, field string) {
if f, ok := relationalFieldDefinition(true); ok {
md := gorma.NewMapDefinition()
md.RemoteField = field
md.RemoteType = utd
f.Mappings[utd.TypeName] = md
}
}
// MapsTo establishes a mapping relationship between a field in model and
// a MediaType in goa.
func MapsTo(mtd *design.MediaTypeDefinition, field string) {
if f, ok := relationalFieldDefinition(true); ok {
md := gorma.NewMapDefinition()
md.RemoteField = field
md.RemoteType = mtd.UserTypeDefinition
f.Mappings[mtd.UserTypeDefinition.TypeName] = md
}
}
func fixID(s string) string {
if s == "i_d" {
return "id"
}
return s
}
// Nullable sets the fields nullability
// A Nullable field will be stored as a pointer. A field that is
// not Nullable won't be stored as a pointer.
func Nullable() {
if f, ok := relationalFieldDefinition(false); ok {
f.Nullable = true
}
}
// PrimaryKey establishes a field as a Primary Key by
// seting the struct tags necessary to create the PK in gorm.
// Valid only for `Integer` datatypes currently
func PrimaryKey() {
if f, ok := relationalFieldDefinition(true); ok {
if f.Datatype != gorma.Integer && f.Datatype != gorma.UUID {
dslengine.ReportError("Integer and UUID are the only supported Primary Key field types.")
}
f.PrimaryKey = true
f.Nullable = false
f.Description = "primary key"
f.Parent.PrimaryKeys = append(f.Parent.PrimaryKeys, f)
}
}
// SanitizeFieldName is exported for testing purposes
func SanitizeFieldName(name string) string {
name = codegen.Goify(name, true)
if strings.HasSuffix(name, "Id") {
name = strings.TrimSuffix(name, "Id")
name = name + "ID"
}
return name
}
// SanitizeDBFieldName is exported for testing purposes
func SanitizeDBFieldName(name string) string {
name = goifyToCamelCase(name)
name = codegen.SnakeCase(name)
if strings.HasSuffix(name, "_i_d") {
name = strings.TrimSuffix(name, "_i_d")
name = name + "_id"
}
if name == "i_d" {
name = "id"
}
return name
}
func parseFieldArgs(args ...interface{}) (gorma.FieldType, func()) {
var (
fieldType gorma.FieldType
dslp func()
ok bool
)
parseFieldType := func(expected string, index int) {
if fieldType, ok = args[index].(gorma.FieldType); !ok {
dslengine.InvalidArgError(expected, args[index])
}
}
parseDSL := func(index int, success, failure func()) {
if dslp, ok = args[index].(func()); ok {
success()
} else {
failure()
}
}
success := func() {}
switch len(args) {
case 0:
fieldType = gorma.NotFound
case 1:
parseDSL(0, success, func() { parseFieldType("DataType or func()", 0) })
case 2:
parseFieldType("FieldType", 0)
parseDSL(1, success, func() { dslengine.InvalidArgError("DSL", args[1]) })
default:
dslengine.ReportError("too many arguments in call to Attribute")
}
return fieldType, dslp
}
// goifyToCamelCase converts the output of Goify to CamelCase, for example: "APIFoo" to "ApiFoo"
func goifyToCamelCase(val string) string {
if len(val) == 0 {
return ""
}
var b bytes.Buffer
var prev rune
for i, v := range val {
if unicode.IsUpper(v) && unicode.IsUpper(prev) {
b.WriteRune(unicode.ToLower(v))
} else {
if unicode.IsUpper(prev) {
if i != 0 {
b.Truncate(i - 1)
b.WriteRune(unicode.ToUpper(prev))
}
}
b.WriteRune(v)
}
prev = v
}
return b.String()
}