/
main.go
176 lines (161 loc) · 4.03 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
//go:build !tinygo.wasm
package sqlla
import (
"fmt"
"go/ast"
"go/types"
"os"
"path/filepath"
"reflect"
"strings"
"golang.org/x/tools/go/packages"
)
func Run(from, ext string) {
fullpath, err := filepath.Abs(from)
if err != nil {
panic(err)
}
dir := filepath.Dir(fullpath)
conf := &packages.Config{
Mode: packages.NeedCompiledGoFiles | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo,
}
pkgs, err := packages.Load(conf, dir)
if err != nil {
panic(err)
}
for _, pkg := range pkgs {
files := pkg.Syntax
for _, f := range files {
for _, decl := range f.Decls {
pos := pkg.Fset.Position(decl.Pos())
if pos.Filename != fullpath {
continue
}
genDecl, ok := decl.(*ast.GenDecl)
if !ok {
continue
}
if genDecl.Doc == nil {
continue
}
var hasAnnotation bool
var annotationComment string
for _, comment := range genDecl.Doc.List {
if trimmed := trimAnnotation(comment.Text); trimmed != comment.Text {
hasAnnotation = true
annotationComment = comment.Text
}
}
if !hasAnnotation {
continue
}
table, err := toTable(pkg.Types, annotationComment, genDecl, pkg.TypesInfo)
if err != nil {
panic(err)
}
filename := filepath.Join(dir, table.TableName+ext)
f, err := os.Create(filename)
if err != nil {
panic(err)
}
if err := WriteCode(f, table); err != nil {
panic(err)
}
}
}
}
}
var supportedNonPrimitiveTypes = map[string]struct{}{
"time.Time": {},
"mysql.NullTime": {},
"sql.NullTime": {},
"sql.NullInt64": {},
"sql.NullString": {},
"sql.NullFloat64": {},
"sql.NullBool": {},
}
var altTypeNames = map[string]string{
"[]byte": "Bytes",
"mysql.NullTime": "MysqlNullTime",
}
func toTable(tablePkg *types.Package, annotationComment string, gd *ast.GenDecl, ti *types.Info) (*Table, error) {
table := new(Table)
table.Package = tablePkg
table.PackageName = tablePkg.Name()
table.TableName = trimAnnotation(annotationComment)
spec := gd.Specs[0]
ts, ok := spec.(*ast.TypeSpec)
if !ok {
return nil, fmt.Errorf("toTable: not type spec: table=%s", table.TableName)
}
structType, ok := ts.Type.(*ast.StructType)
if !ok {
return nil, fmt.Errorf("toTable: not struct type: table=%s", table.TableName)
}
table.StructName = ts.Name.Name
if isV2Annotation(annotationComment) {
table.Name = table.StructName
} else {
table.Name = table.TableName
}
for _, field := range structType.Fields.List {
tagText := field.Tag.Value[1 : len(field.Tag.Value)-1]
tag := reflect.StructTag(tagText)
columnInfo := tag.Get("db")
columnMaps := strings.Split(columnInfo, ",")
columnName := columnMaps[0]
isPk := false
for _, cm := range columnMaps {
if cm == "primarykey" {
isPk = true
break
}
}
t := ti.TypeOf(field.Type)
var typeName, pkgName string
baseTypeName := t.String()
nt, ok := t.(*types.Named)
if ok {
pkgName = nt.Obj().Pkg().Path()
if tablePkg.Path() != pkgName {
typeName = strings.Join([]string{nt.Obj().Pkg().Name(), nt.Obj().Name()}, ".")
} else {
typeName = nt.Obj().Name()
}
baseTypeName = typeName
if _, ok := supportedNonPrimitiveTypes[typeName]; !ok {
bt := nt.Underlying()
for _, ok := bt.Underlying().(*types.Named); ok; bt = bt.Underlying() {
}
baseTypeName = bt.String()
}
} else {
typeName = t.String()
}
column := Column{
Field: field,
Name: columnName,
IsPk: isPk,
TypeName: typeName,
BaseTypeName: baseTypeName,
PkgName: pkgName,
}
if alt, ok := altTypeNames[baseTypeName]; ok {
column.AltTypeName = alt
}
table.AddColumn(column)
}
return table, nil
}
func trimAnnotation(comment string) string {
prefixes := []string{"//+table: ", "// +table: ", "//sqlla:table "}
for _, prefix := range prefixes {
if trimmed := strings.TrimPrefix(comment, prefix); trimmed != comment {
return trimmed
}
}
return comment
}
func isV2Annotation(comment string) bool {
return strings.HasPrefix(comment, "//sqlla:table ")
}