-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.go
277 lines (253 loc) · 7.73 KB
/
main.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package genddl
import (
"flag"
"fmt"
"go/ast"
"go/types"
"log"
"os"
"path/filepath"
"sort"
"strings"
"golang.org/x/tools/go/packages"
)
type Field struct {
ColumnDef string
}
type Table struct {
Name string
Fields []Field
PrimaryKey string
}
func Run(from string) {
fromdir := filepath.Dir(from)
var schemadir, outpath, driverName, tableCollate string
tableMapOptionArgs := &tableMapOption{}
flag.StringVar(&schemadir, "schemadir", fromdir, "schema declaretion directory")
flag.StringVar(&outpath, "outpath", "", "schema target path")
flag.StringVar(&driverName, "driver", "mysql", "target driver name. support mysql, pg, sqlite3")
flag.BoolVar(&tableMapOptionArgs.innerIndexDef, "innerindex", false, "Placement of index definition. If this specified, the definition was placement inner of `create table`")
flag.BoolVar(&tableMapOptionArgs.uniqueWithName, "uniquename", false, "Provides a name for the definition of a unique index.")
flag.StringVar(&tableCollate, "tablecollate", "", "Provides a collate for the definition of tables.")
flag.BoolVar(&tableMapOptionArgs.foreignKeyWithName, "foreignkeyname", false, "Provides a name for the definition of a foreign-key.")
flag.BoolVar(&tableMapOptionArgs.outerForeignKey, "outerforeignkey", false, "Placement of foreign key definition. If this specified, the definition was placement end of DDL file.")
flag.BoolVar(&tableMapOptionArgs.outerUniqueKey, "outeruniquekey", false, "Placement of unique key definition. If this specified, the definition was placement outer of CREATE TABLE.")
flag.BoolVar(&tableMapOptionArgs.withoutDropTable, "withoutdroptable", false, "If this specified, the DDL file does not contain DROP TABLE statement.")
flag.Parse()
var dialect Dialect
switch driverName {
case "mysql":
dialect = MysqlDialect{Collate: tableCollate}
case "pg":
dialect = PostgresqlDialect{Collate: tableCollate}
// It is not supported by PostgreSQL that foreign key definition with name
tableMapOptionArgs.foreignKeyWithName = false
// It is not supported by PostgreSQL that unique index definition with name
tableMapOptionArgs.uniqueWithName = false
case "sqlite3":
dialect = Sqlite3Dialect{}
// It is not supported by SQLite that placement of index definition inner CREATE TABLE
tableMapOptionArgs.innerIndexDef = false
// It is not supported by SQLite that unique index definition with name
tableMapOptionArgs.uniqueWithName = false
// It is not supported by SQLite that foreign key definition placement outer of CREATE TABLE
tableMapOptionArgs.outerForeignKey = false
default:
log.Fatalf("undefined driver name: %s", driverName)
}
tr, err := retrieveTables(schemadir)
if err != nil {
log.Fatalf("parse and retrieve table error: %s", err)
}
file, err := os.Create(outpath)
if err != nil {
log.Fatal("invalid outpath error:", err)
}
tablesMap := map[*ast.StructType]string{}
var tableNames []string
for tableName, st := range tr.tables {
tablesMap[st] = tableName
tableNames = append(tableNames, tableName)
}
sort.Strings(tableNames)
file.WriteString("-- generated by github.com/mackee/go-genddl. DO NOT EDIT!!!\n")
endOfDDLFileIndexes := make([]indexer, 0, len(tableNames))
for _, tableName := range tableNames {
st := tr.tables[tableName]
funcs := tr.funcs[st]
tableMap, err := NewTableMap(tableName, st, funcs, tablesMap, tr.ti, tableMapOptionArgs)
if err != nil {
log.Fatalf("failed to create table map: %s", err)
}
if tableMap != nil {
file.WriteString("\n")
if err := tableMap.WriteDDL(file, dialect, tableMapOptionArgs); err != nil {
log.Fatalf("failed to write DDL: %s", err)
}
endOfDDLFileIndexes = append(endOfDDLFileIndexes, tableMap.EndOfDDLFileIndexes...)
}
}
viewNames := make([]string, 0, len(tr.views))
for viewName := range tr.views {
viewNames = append(viewNames, viewName)
}
sort.Strings(viewNames)
for _, viewName := range viewNames {
v := tr.views[viewName]
vm, err := NewViewMap(newViewMapInput{
name: viewName,
st: v,
funcs: tr.funcs[v],
ti: tr.ti,
})
if err != nil {
log.Fatalf("[ERROR] failed to create view map: %s", err)
}
if vm == nil {
log.Println("[ERROR] skip view:", viewName)
continue
}
vm.WriteDDL(file, dialect)
}
for _, index := range endOfDDLFileIndexes {
if _, err := file.WriteString(index.Index(dialect, tablesMap)); err != nil {
log.Fatalf("failed to write index: %s", err)
}
if _, err := file.WriteString(";\n"); err != nil {
log.Fatalf("failed to write index: %s", err)
}
}
}
var typeNameStructMap = map[string]*ast.StructType{}
type retrieveTablesResult struct {
tables map[string]*ast.StructType
views map[string]*ast.StructType
funcs map[*ast.StructType][]*ast.FuncDecl
ti *types.Info
}
func retrieveTables(schemadir string) (*retrieveTablesResult, error) {
path, err := filepath.Abs(schemadir)
if err != nil {
return nil, err
}
conf := &packages.Config{
Mode: packages.NeedCompiledGoFiles |
packages.NeedSyntax |
packages.NeedTypes |
packages.NeedTypesInfo,
Dir: path,
}
pkgs, err := packages.Load(conf)
if err != nil {
return nil, fmt.Errorf("retrieveTables: fail to parse from dir: dir=%s, error=%w", schemadir, err)
}
var decls []ast.Decl
var ti *types.Info
for _, pkg := range pkgs {
ti = pkg.TypesInfo
for _, file := range pkg.Syntax {
decls = append(decls, file.Decls...)
}
}
tables := map[string]*ast.StructType{}
views := map[string]*ast.StructType{}
funcs := []*ast.FuncDecl{}
funcMap := map[*ast.StructType][]*ast.FuncDecl{}
for _, decl := range decls {
if funcDecl, ok := decl.(*ast.FuncDecl); ok {
funcs = append(funcs, funcDecl)
}
if genDecl, ok := decl.(*ast.GenDecl); ok {
if genDecl.Doc == nil {
continue
}
for _, comment := range genDecl.Doc.List {
if a := trimAnnotation(comment.Text); a.annotationType != annotationTypeNone {
tableName := a.tableName
spec := genDecl.Specs[0]
ts, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
st, ok := ts.Type.(*ast.StructType)
if !ok {
continue
}
switch a.annotationType {
case annotationTypeTable:
tables[tableName] = st
case annotationTypeView:
views[tableName] = st
}
funcMap[st] = make([]*ast.FuncDecl, 0)
typeNameStructMap[ts.Name.Name] = st
break
}
}
}
}
for _, funcDecl := range funcs {
if funcDecl.Recv.NumFields() < 0 {
continue
}
if funcDecl.Recv == nil || len(funcDecl.Recv.List) == 0 {
continue
}
recv := funcDecl.Recv.List[0]
ident, ok := recv.Type.(*ast.Ident)
if !ok {
continue
}
if ident.Obj == nil || ident.Obj.Decl == nil {
continue
}
ts, ok := ident.Obj.Decl.(*ast.TypeSpec)
if !ok {
continue
}
st, ok := ts.Type.(*ast.StructType)
if !ok {
continue
}
if funcs, ok := funcMap[st]; ok {
funcMap[st] = append(funcs, funcDecl)
}
}
return &retrieveTablesResult{
tables: tables,
views: views,
funcs: funcMap,
ti: ti,
}, nil
}
type annotationType string
const (
annotationTypeNone annotationType = "none"
annotationTypeTable annotationType = "table"
annotationTypeView annotationType = "view"
)
type annotation struct {
tableName string
annotationType annotationType
}
func trimAnnotation(comment string) annotation {
prefixes := map[string]annotationType{
"//+table:": annotationTypeTable,
"// +table:": annotationTypeTable,
"//genddl:table ": annotationTypeTable,
"//genddl:view ": annotationTypeView,
}
for prefix, at := range prefixes {
if trimmed := strings.TrimPrefix(comment, prefix); trimmed != comment {
trimmed = strings.TrimSpace(trimmed)
return annotation{
tableName: trimmed,
annotationType: at,
}
}
}
return annotation{
tableName: comment,
annotationType: annotationTypeNone,
}
}