-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.go
218 lines (189 loc) · 5.45 KB
/
template.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
// Copyright 2019 Job Stoit. All rights reserved.
package main
import (
"bytes"
"fmt"
"io"
"strings"
"text/template"
)
// This file contains the templates for the code generation
// These are the template for each table
// CreateQbModel creates the models template
func CreateQbModel(m Model, wr io.Writer) {
temp := template.Must(template.New(`qb-model`).
Funcs(template.FuncMap{
`title`: title,
`quote`: quote,
`join`: strings.Join,
`notnil`: notNil,
`qbtype`: qbType,
`migrate`: func() string {
buf := new(bytes.Buffer)
CreateMigration(m, buf)
return buf.String()
},
}).
Parse(queryTempl + tableTempl))
catch(temp.Execute(wr, m), `Unable to execute the Model template`)
}
// CreateMigration creates the migration template
func CreateMigration(m Model, wr io.Writer) {
temp := template.Must(template.New(`migration`).
Funcs(template.FuncMap{
`notnil`: notNil,
}).
Parse(queryTempl + migrationTempl))
catch(temp.Execute(wr, m), `Unable to execute migration template`)
}
func title(s interface{}) (t string) {
for _, part := range strings.Split(fmt.Sprint(s), `_`) {
switch part {
case `id`, `Id`, `sql`, `Sql`, `url`, `Url`:
t += strings.ToUpper(part)
default:
t += strings.Title(part)
}
}
return
}
func quote(i ...interface{}) (s string) {
s += "`"
if len(i) == 0 {
return
}
for e, it := range i {
s += fmt.Sprint(it)
if e != len(i)-1 {
s += ` `
}
}
s += "`"
return
}
func notNil(x interface{}) bool {
return x != nil
}
func qbType(x DataType) string {
switch x.Type() {
case `varchar`, `text`:
return `qb.String`
case `int`, `tinyint`, `smallint`, `bigint`:
return `qb.Int`
case `double`, `float`:
return `qb.Float`
case `date`, `datetime`:
return `qb.Date`
case `boolean`:
return `qb.Bool`
default:
return `qb.Int`
}
}
var queryTempl = `{{define "tablequery"}}CREATE TABLE IF NOT EXISTS {{print (index . 0).Table}} ({{range $n, $col := .}}{{if $n}},{{end}}
{{$col.Name -}}
{{- if notnil $col.DataType}} {{$col.DataType.Type}}{{end -}}
{{- if gt $col.Size 0}}({{$col.Size}}){{end -}}
{{- if and (not $col.Nullable) (eq $col.Default "")}} NOT NULL{{end -}}
{{- if $col.Primary}} PRIMARY KEY{{end -}}
{{- if $col.Unique}} UNIQUE{{end -}}
{{- if not (eq $col.Default "")}} DEFAULT '{{$col.Default}}'{{end -}}
{{- range $g, $c := $col.Constraints}}{{if $g}}, {{end}} ADD CONSTRAINT {{$c}}{{end -}}
{{- end}}
);{{- end}}
{{define "enumquery"}}CREATE TYPE {{print .Table}} AS ENUM ({{range $n, $val := .Values}}{{if $n}},{{end}} {{$val}}{{end}} );{{end}}`
var migrationTempl = `{{range $.Tables}}
{{- $col := .Columns $.Types -}}
{{- $enu := .Enum $.Types -}}
-- {{print .}}
{{if gt (len $col) 0 }}{{template "tablequery" $col}}
{{else if gt (len $enu.Values) 0}}{{template "enumquery" $enu}}
{{- end}}
{{end}}`
var tableTempl = `
{{range $e, $t := $.Tables -}}
{{- $cols := $t.Columns $.Types -}}
{{- $enu := $t.Enum $.Types -}}
// {{print $t}}
{{- if gt (len $cols) 0}}
var (
qb{{title $t}}Table = qb.Table{Name: {{quote $t}}}
{{range $cols}}
qb{{title $t}}F{{title .Name}} = qb.TableField{Parent: &qb{{title $t}}Table, Name: {{quote .Name}}
{{- if notnil .DataType}}, Type: {{qbtype .DataType}}{{end -}}
{{- if gt .Size 0}}, Size: {{.Size}}{{end -}}
{{- if .Nullable}}, Nullable: true{{end -}}
}{{end}}
)
// {{title $t}}Type represents the table "{{print $t}}"
type {{title $t}}Type struct {
{{- range $cols}}
{{title .Name}} qb.Field{{end}}
table *qb.Table
}
// SQL is the qb.Query implementation for migration the {{title $t}} table
func (*{{title $t}}Type) SQL(_ qb.SQLBuilder) (q string, _ []interface{}) {
q = {{quote}}{{template "tablequery" $cols}}{{- quote}}
return
}
// GetTable returns an object with info about the table
func (t *{{title $t}}Type) GetTable() *qb.Table {
return t.table
}
// Select starts a SELECT query
func (t *{{title $t}}Type) Select(f ...qb.Field) *qb.SelectBuilder {
return t.table.Select(f)
}
// Delete creates a DELETE query
func (t *{{title $t}}Type) Delete(c1 qb.Condition, c ...qb.Condition) qb.Query {
return t.table.Delete(c1, c...)
}
// Update starts a UPDATE query
func (t *{{title $t}}Type) Update() *qb.UpdateBuilder {
return t.table.Update()
}
// Insert starts a INSERT query
func (t *{{title $t}}Type) Insert(f ...qb.Field) *qb.InsertBuilder {
return t.table.Insert(f)
}
// {{title $t}} returns a new {{title $t}}Type
func {{title $t}}() *{{title $t}}Type {
table := qb{{title $t}}Table
return &{{title $t}}Type{
{{- range $cols}}
qb{{title $t}}F{{title .Name}}.Copy(&table),
{{- end}}
&table,
}
}
{{- else if notnil $enu.Table}}
// {{title $t}}Type represents the enum "{{print $t}}
type {{title $t}}Type []string
// SQL is the qb.Query implementation for migrating the {{title $t}} enum
func (*{{title $t}}Type) SQL(_ qb.SQLBuilder) (q string, _[]interface{}) {
q = {{quote}}{{template "enumquery" $enu}}{{quote}}
return
}
// {{title $t}} returns a new {{title $t}}Type
func {{title $t}}() *{{title $t}}Type {
enu := {{title $t}}Type([]string{ {{range $enu.Values}}
{{quote .}},{{end}}
})
return &enu
}
{{end}}
{{end}}
// Open creates a connection with the database and
// inserst the migration if not exists and
// returns the qbdb database
func Open(driver, connectionString string) (*qbdb.DB, error) {
db, err := sql.Open(driver, connectionString)
if err != nil {
return nil, err
}
q := {{ quote migrate }}
if _, err := db.Exec(q); err != nil {
return nil, fmt.Errorf("Migration failed: %v", err)
}
return autoqb.New(db), nil
}`