This repository has been archived by the owner on Apr 19, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathgen_schema.go
116 lines (92 loc) · 2.24 KB
/
gen_schema.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
package main
import (
"fmt"
"io"
"strings"
"bitbucket.org/pkg/inflect"
"github.com/drone/sqlgen/schema"
)
// writeSchema writes SQL statements to CREATE, INSERT,
// UPDATE and DELETE values from Table t.
func writeSchema(w io.Writer, d schema.Dialect, t *schema.Table) {
writeConst(w,
d.Table(t),
"create", inflect.Singularize(t.Name), "stmt",
)
writeConst(w,
d.Insert(t),
"insert", inflect.Singularize(t.Name), "stmt",
)
writeConst(w,
d.Select(t, nil),
"select", inflect.Singularize(t.Name), "stmt",
)
writeConst(w,
d.SelectRange(t, nil),
"select", inflect.Singularize(t.Name), "range", "stmt",
)
writeConst(w,
d.SelectCount(t, nil),
"select", inflect.Singularize(t.Name), "count", "stmt",
)
if len(t.Primary) != 0 {
writeConst(w,
d.Select(t, t.Primary),
"select", inflect.Singularize(t.Name), "pkey", "stmt",
)
writeConst(w,
d.Update(t, t.Primary),
"update", inflect.Singularize(t.Name), "pkey", "stmt",
)
writeConst(w,
d.Delete(t, t.Primary),
"delete", inflect.Singularize(t.Name), "pkey", "stmt",
)
}
for _, ix := range t.Index {
writeConst(w,
d.Index(t, ix),
"create", ix.Name, "stmt",
)
writeConst(w,
d.Select(t, ix.Fields),
"select", ix.Name, "stmt",
)
if !ix.Unique {
writeConst(w,
d.SelectRange(t, ix.Fields),
"select", ix.Name, "range", "stmt",
)
writeConst(w,
d.SelectCount(t, ix.Fields),
"select", ix.Name, "count", "stmt",
)
} else {
writeConst(w,
d.Update(t, ix.Fields),
"update", ix.Name, "stmt",
)
writeConst(w,
d.Delete(t, ix.Fields),
"delete", ix.Name, "stmt",
)
}
}
}
// WritePackage writes the Go package header to
// writer w with the given package name.
func writePackage(w io.Writer, name string) {
fmt.Fprintf(w, sPackage, name)
}
// writeConst is a helper function that writes the
// body string to a Go const variable.
func writeConst(w io.Writer, body string, label ...string) {
// create a snake case variable name from
// the specified labels. Then convert the
// variable name to a quoted, camel case string.
name := strings.Join(label, "_")
name = inflect.Typeify(name)
// quote the body using multi-line quotes
body = fmt.Sprintf(sQuote, body)
fmt.Fprintf(w, sConst, name, body)
}