forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.go
210 lines (185 loc) · 5.07 KB
/
model.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
package generate
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/gobuffalo/makr"
"github.com/pkg/errors"
"github.com/markbates/going/defaults"
"github.com/markbates/inflect"
"github.com/markbates/pop"
"github.com/spf13/cobra"
)
var skipMigration bool
func init() {
ModelCmd.Flags().BoolVarP(&skipMigration, "skip-migration", "s", false, "Skip creating a new fizz migration for this model.")
}
var nrx = regexp.MustCompile(`^nulls\.(.+)`)
type names struct {
Original string
Table string
Proper string
File string
Plural string
Char string
}
func newName(name string) names {
return names{
Original: name,
File: name,
Table: inflect.Tableize(name),
Proper: inflect.ForeignKeyToAttribute(name),
Plural: inflect.Pluralize(inflect.Camelize(name)),
Char: strings.ToLower(string([]byte(name)[0])),
}
}
type attribute struct {
Names names
OriginalType string
GoType string
Nullable bool
}
func (a attribute) String() string {
return fmt.Sprintf("\t%s %s `json:\"%s\" db:\"%s\"`", a.Names.Proper, a.GoType, a.Names.Original, a.Names.Original)
}
type model struct {
Package string
Imports []string
Names names
Attributes []attribute
ValidatableAttributes []attribute
}
func (m model) Generate() error {
g := makr.New()
ctx := makr.Data{}
ctx["model"] = m
ctx["plural_model_name"] = m.Names.Plural
ctx["model_name"] = m.Names.Proper
ctx["package_name"] = m.Package
ctx["char"] = m.Names.Char
fname := filepath.Join(m.Package, m.Names.File+".go")
g.Add(makr.NewFile(fname, modelTemplate))
tfname := filepath.Join(m.Package, m.Names.File+"_test.go")
g.Add(makr.NewFile(tfname, modelTestTemplate))
g.Add(makr.NewCommand(makr.GoFmt()))
return g.Run(".", ctx)
}
func (m model) Fizz() string {
s := []string{fmt.Sprintf("create_table(\"%s\", func(t) {", m.Names.Table)}
for _, a := range m.Attributes {
switch a.Names.Original {
case "created_at", "updated_at":
case "id":
s = append(s, fmt.Sprintf("\tt.Column(\"id\", \"%s\", {\"primary\": true})", fizzColType(a.OriginalType)))
default:
x := fmt.Sprintf("\tt.Column(\"%s\", \"%s\", {})", a.Names.Original, fizzColType(a.OriginalType))
if a.Nullable {
x = strings.Replace(x, "{}", `{"null": true}`, -1)
}
s = append(s, x)
}
}
s = append(s, "})")
return strings.Join(s, "\n")
}
func newModel(name string) model {
id := newName("id")
id.Proper = "ID"
return model{
Package: "models",
Imports: []string{"time", "encoding/json", "github.com/markbates/pop", "github.com/markbates/validate", "github.com/satori/go.uuid"},
Names: newName(name),
Attributes: []attribute{
{Names: id, OriginalType: "uuid.UUID", GoType: "uuid.UUID"},
{Names: newName("created_at"), OriginalType: "time.Time", GoType: "time.Time"},
{Names: newName("updated_at"), OriginalType: "time.Time", GoType: "time.Time"},
},
ValidatableAttributes: []attribute{},
}
}
var ModelCmd = &cobra.Command{
Use: "model [name]",
Aliases: []string{"m"},
Short: "Generates a model for your database",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return errors.New("You must supply a name for your model!")
}
model := newModel(args[0])
hasNulls := false
for _, def := range args[1:] {
col := strings.Split(def, ":")
if len(col) == 1 {
col = append(col, "string")
}
nullable := nrx.MatchString(col[1])
if !hasNulls && nullable {
hasNulls = true
model.Imports = append(model.Imports, "github.com/markbates/pop/nulls")
}
a := attribute{
Names: newName(col[0]),
OriginalType: col[1],
GoType: colType(col[1]),
Nullable: nullable,
}
model.Attributes = append(model.Attributes, a)
if !a.Nullable {
if a.GoType == "string" || a.GoType == "time.Time" || a.GoType == "int" {
if a.GoType == "time.Time" {
a.GoType = "Time"
}
model.ValidatableAttributes = append(model.ValidatableAttributes, a)
}
}
}
err := os.MkdirAll(model.Package, 0766)
if err != nil {
return errors.Wrapf(err, "couldn't create folder %s", model.Package)
}
err = model.Generate()
if err != nil {
return err
}
if !skipMigration {
cflag := cmd.Flag("path")
migrationPath := defaults.String(cflag.Value.String(), "./migrations")
err = pop.MigrationCreate(migrationPath, fmt.Sprintf("create_%s", model.Names.Table), "fizz", []byte(model.Fizz()), []byte(fmt.Sprintf("drop_table(\"%s\")", model.Names.Table)))
if err != nil {
return err
}
}
return nil
},
}
func colType(s string) string {
switch s {
case "text":
return "string"
case "time", "timestamp":
return "time.Time"
case "nulls.Text":
return "nulls.String"
case "uuid":
return "uuid.UUID"
default:
return s
}
}
func fizzColType(s string) string {
if nrx.MatchString(s) {
return fizzColType(strings.Replace(s, "nulls.", "", -1))
}
switch strings.ToLower(s) {
case "int":
return "integer"
case "time":
return "timestamp"
case "uuid.uuid", "uuid":
return "uuid"
default:
return strings.ToLower(s)
}
}