/
table.go
257 lines (223 loc) · 6.29 KB
/
table.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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package geneddl
import (
"fmt"
"os"
"strings"
"github.com/cihangir/gene/generators/common"
"github.com/cihangir/schema"
"github.com/cihangir/stringext"
)
// DefineTable creates definition for sequences
func DefineTable(settings schema.Generator, s *schema.Schema) ([]byte, error) {
common.TemplateFuncs["GenerateSQLField"] = GenerateSQLField
return common.ProcessSingle(&common.Op{
Template: TableTemplate,
PostProcessors: []common.PostProcessor{clean},
}, s, settings)
}
// TableTemplate holds the template for sequences
var TableTemplate = `{{$settings := .Settings}}-- ----------------------------
-- Table structure for {{$settings.schemaName}}.{{$settings.tableName}}
-- ----------------------------
DROP TABLE IF EXISTS "{{$settings.schemaName}}"."{{$settings.tableName}}";
CREATE TABLE "{{$settings.schemaName}}"."{{$settings.tableName}}" (
{{range $key, $value := .Properties}}
{{GenerateSQLField $settings $value}}
{{end}}
) WITH (OIDS = FALSE);-- end schema creation
GRANT {{Join $settings.grants ", "}} ON "{{$settings.schemaName}}"."{{$settings.tableName}}" TO "{{$settings.roleName}}";
`
// GenerateSQLField creates a definition line for a given coloumn
func GenerateSQLField(settings schema.Generator, s *schema.Schema) (res string) {
propertyName := s.Title
schemaName := settings.Get("schemaName").(string)
tableName := settings.Get("tableName").(string)
property := s
fieldName := stringext.ToFieldName(propertyName) // transpiled version of property
if property.Title != "" {
fieldName = stringext.ToFieldName(property.Title)
}
fieldType := "" // will hold the type for coloumn
switch strings.ToLower(property.Type.(string)) {
case "boolean":
fieldType = "BOOLEAN"
case "string":
switch property.Format {
case "date-time":
fieldType = "TIMESTAMP (6) WITH TIME ZONE"
case "UUID":
fieldType = "UUID"
default:
typeName := "TEXT"
if property.MaxLength > 0 {
// if schema defines a max length, no need to use text
typeName = fmt.Sprintf("VARCHAR (%d)", property.MaxLength)
}
fieldType = fmt.Sprintf("%s COLLATE \"default\"", typeName)
}
case "number":
fieldType = "NUMERIC"
switch property.Format {
case "int64", "uint64":
fieldType = "BIGINT"
case "integer", "int", "int32", "uint", "uint32":
fieldType = "INTEGER"
case "int8", "uint8", "int16", "uint16":
fieldType = "SMALLINT"
case "float32", "float64":
fieldType = "NUMERIC"
}
case "any":
panic("should specify type")
case "array":
panic("array not supported")
case "object", "config":
// TODO implement embedded struct table creation
res = ""
case "null":
res = ""
case "error":
res = ""
case "custom":
res = ""
default:
panic("unknown field")
}
// override if it is an enum field
if len(property.Enum) > 0 {
fieldType = fmt.Sprintf(
"%q.\"%s_%s_enum\"",
schemaName,
stringext.ToFieldName(tableName),
stringext.ToFieldName(propertyName),
)
}
res = fmt.Sprintf(
"%q %s %s %s %s,",
// first, name comes
fieldName,
// then type of the coloumn
fieldType,
// generate default value if exists
generateDefaultValue(schemaName, fieldName, tableName, property),
// generate not null statement, if required
generateNotNull(s, propertyName),
// generate validators
generateCheckStatements(tableName, fieldName, property),
)
return res
}
// generateDefaultValue generates `default` string for given coloumn
func generateDefaultValue(schemaName string, propertyName, tableName string, s *schema.Schema) string {
// if property is id, use sequence generator as default value
if propertyName == "id" {
return fmt.Sprintf("DEFAULT nextval('%s.%s_id_seq' :: regclass) ", schemaName, tableName)
}
if s.Default == nil {
return ""
}
if len(s.Enum) > 0 {
// enums should be a valud enum string
if !common.IsIn(s.Default.(string), s.Enum...) {
fmt.Printf("%s not a valid enum", s.Default)
os.Exit(1)
}
return fmt.Sprintf("DEFAULT '%s'", s.Default)
}
def := ""
switch s.Default.(type) {
case float64, float32, int16, int32, int, int64, uint16, uint32, uint, uint64, bool:
def = fmt.Sprintf("%v", s.Default)
default:
def = fmt.Sprintf("%v", s.Default)
// if default is a function call, use it
if strings.HasSuffix(def, "()") {
return fmt.Sprintf("DEFAULT %s", def)
}
// it is string, quote it
def = fmt.Sprintf("'%v'", s.Default)
}
return fmt.Sprintf("DEFAULT %s", strings.ToUpper(def))
}
// generateNotNull if field is in required values, set NOT NULL
func generateNotNull(s *schema.Schema, name string) string {
if schema.Required(name, s) {
return "NOT NULL"
}
return ""
}
// generateCheckStatements generates validators
func generateCheckStatements(tableName, fieldName string, property *schema.Schema) string {
chekcs := ""
switch strings.ToLower(property.Type.(string)) {
case "string":
if property.MinLength > 0 {
chekcs += fmt.Sprintf(
"\n\t\tCONSTRAINT \"check_%s_%s_min_length_%d\" CHECK (char_length(%q) > %d )",
tableName,
fieldName,
property.MinLength,
fieldName,
property.MinLength,
)
}
if property.Pattern != "" {
chekcs += fmt.Sprintf(
"\n\t\tCONSTRAINT \"check_%s_%s_pattern\" CHECK (%q ~ '%s')",
tableName,
fieldName,
fieldName,
property.Pattern,
)
}
// no need to check for max length, we already create coloumn with max length
case "number":
if property.MultipleOf > 0 {
chekcs += fmt.Sprintf(
"\n\t\tCONSTRAINT \"check_%s_%s_multiple_of_%d\" CHECK ((%q %% %f) = 0)",
tableName,
fieldName,
int64(property.MultipleOf), // do not use dot in check constraint
fieldName,
property.MultipleOf,
)
}
if property.Maximum > 0 {
checker := "<"
str := "lt"
if !property.ExclusiveMaximum {
checker += "="
str += "e"
}
chekcs += fmt.Sprintf(
"\n\t\tCONSTRAINT \"check_%s_%s_%s_%d\" CHECK (%q %s %f)",
tableName,
fieldName,
str,
int64(property.Maximum),
fieldName,
checker,
property.Maximum,
)
}
if property.Minimum > 0 {
checker := ">"
str := "gt"
if !property.ExclusiveMinimum {
checker += "="
str += "e"
}
chekcs += fmt.Sprintf(
"\n\t\tCONSTRAINT \"check_%s_%s_%s_%d\" CHECK (%q %s %f)",
tableName,
fieldName,
str,
int64(property.Maximum),
fieldName,
checker,
property.Maximum,
)
}
}
return chekcs
}