-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathschema_columns_gen.go
174 lines (147 loc) · 3.88 KB
/
schema_columns_gen.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
package gen
import (
"bytes"
"fmt"
"go/format"
"os"
"path/filepath"
"runtime"
"strings"
"text/template"
"github.com/kataras/pg"
)
// GenerateColumnsFromSchema generates Go code for the given schema.
// The generated code includes a struct for each table which contains
// struct fields for each column information.
//
// Example Code:
//
// schema := pg.NewSchema()
// schema.MustRegister("companies", Company{})
// schema.MustRegister("customers", Customer{})
//
// opts := &ExportOptions{
// RootDir: "./definition",
// }
//
// if err := GenerateColumnsFromSchema(schema, opts); err != nil {
// t.Fatal(err)
// }
//
// Usage:
// definition.Company.Name.String() // returns "name"
// definition.Customer.Email.String() // returns "email"
//
// Useful for type-safe query builders.
func GenerateColumnsFromSchema(s *pg.Schema, e ExportOptions) error {
if err := e.apply(); err != nil {
return err
}
tables := s.Tables()
if len(tables) == 0 {
return nil
}
// Create root file to store common structures and functions.
data, err := generateRoot(e.GetPackageName(""))
if err != nil {
return fmt.Errorf("generate root: %s: %w", e.GetPackageName("columns"), err)
}
filename := e.GetFileName(e.RootDir, "")
err = mkdir(filename)
if err != nil {
return fmt.Errorf("mkdir: %s: %w", e.RootDir, err)
}
err = os.WriteFile(filename, data, e.FileMode)
if err != nil {
return fmt.Errorf("write root: %s: %w", filename, err)
}
// Create each file for each table definition.
for _, td := range tables {
data, err = generateTableDefininion(e.GetPackageName(td.Name), td)
if err != nil {
return fmt.Errorf("generate table: %s: %w", td.Name, err)
}
filename := e.GetFileName(e.RootDir, td.Name)
if filename == "" {
continue
}
mkdir(filename)
err = os.WriteFile(filename, data, e.FileMode)
if err != nil {
return fmt.Errorf("write table: %s: defininion file: %s: %w", td.Name, filename, err)
}
}
return nil
}
var generateRootTmpl = template.Must(
template.New("").Parse(`
// Code generated by pg. DO NOT EDIT.
package {{.PackageName}}
// Column is a struct that represents a column in a table.
type Column struct {
Name string
}
// String returns the name of the column.
func (c Column) String() string {
return c.Name
}
`))
func generateRoot(packageName string) ([]byte, error) {
tmplData := generateTemplateData{
PackageName: packageName,
}
var buf bytes.Buffer
if err := generateRootTmpl.Execute(&buf, tmplData); err != nil {
return nil, err
}
return format.Source(buf.Bytes())
}
type generateTemplateData struct {
*pg.Table
PackageName string
}
var generateTableDefininionTmpl = template.Must(
template.New(""). // Note that we don't need to put import paths here as the only one type is the generated Column in the same package.
Parse(`
// Code generated by pg. DO NOT EDIT.
package {{.PackageName}}
// {{.StructName}} is a struct value that represents a record in the {{.Name}} table.
var {{.StructName}} = struct {
PG_TableName string
{{range .Columns}} {{.FieldName}} Column
{{end}}
}{
PG_TableName: "{{.Name}}",
{{range .Columns}} {{.FieldName}}: Column{
Name: "{{.Name}}",
},
{{end }}
}`))
func generateTableDefininion(packageName string, td *pg.Table) ([]byte, error) {
tmplData := generateTemplateData{
Table: td,
PackageName: packageName,
}
var buf bytes.Buffer
if err := generateTableDefininionTmpl.Execute(&buf, tmplData); err != nil {
return nil, err
}
return format.Source(buf.Bytes())
}
func mkdir(path string) error {
dir := filepath.Dir(path)
return os.MkdirAll(dir, 0777)
}
func getCallerPackageName() string {
pc, _, _, _ := runtime.Caller(2)
funcName := runtime.FuncForPC(pc).Name()
lastSlash := strings.LastIndexByte(funcName, '/')
if lastSlash < 0 {
lastSlash = 0
}
lastDot := strings.LastIndexByte(funcName[lastSlash:], '.')
if lastDot == -1 {
return ""
}
return funcName[:lastDot]
}