forked from relops/cqlc
/
generator.go
197 lines (164 loc) · 4.45 KB
/
generator.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
package generator
import (
"bytes"
"errors"
"fmt"
"github.com/gocql/gocql"
"go/format"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
)
var (
ErrInvalidOptions = errors.New("invalid options")
)
type Options struct {
Instance string `short:"i" long:"instance" description:"The Cassandra instance to connect to"`
Keyspace string `short:"k" long:"keyspace" description:"The keyspace that contains the target schema"`
Package string `short:"p" long:"package" description:"The name of the target package for the generated code"`
Output string `short:"o" long:"output" description:"The file to write the generated bindings to"`
Version func() `short:"V" long:"version" description:"Print cqlc version and exit"`
Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
Symbols bool `short:"s" long:"symbols" description:"Generate compile symbols for each column family"`
Username string `short:"u" long:"username" description:"Username for authentication"`
Password string `short:"w" long:"password" description:"Password for authentication"`
}
type Provenance struct {
Keyspace string
Version string
Timestamp time.Time
NegotiatedCQL string
ServerCQL string
ServerRelease string
HostId gocql.UUID
}
func Generate(opts *Options, version string) error {
err := validateOptions(opts)
if err != nil {
return err
}
var b bytes.Buffer
if err = generateBinding(opts, version, &b); err != nil {
return err
}
if b.Len() > 0 {
if err := os.MkdirAll(filepath.Dir(opts.Output), os.ModePerm); err != nil {
return err
}
if err := ioutil.WriteFile(opts.Output, b.Bytes(), os.ModePerm); err != nil {
return err
}
}
return nil
}
func validateOptions(opts *Options) error {
if opts.Instance == "" || opts.Keyspace == "" || opts.Package == "" || opts.Output == "" {
return ErrInvalidOptions
}
if (opts.Username == "" && opts.Password != "") || (opts.Username != "" && opts.Password == "") {
return ErrInvalidOptions
}
return nil
}
func coalesceImports(md *gocql.KeyspaceMetadata) []string {
set := make(map[string]bool)
for _, path := range importPaths(md) {
set[path] = true
}
set["github.com/relops/cqlc/cqlc"] = true
set["github.com/gocql/gocql"] = true
set["log"] = true
paths := make([]string, 0)
for path, _ := range set {
paths = append(paths, path)
}
return paths
}
func generateBinding(opts *Options, version string, w io.Writer) error {
cluster := gocql.NewCluster(opts.Instance)
if opts.Username != "" && opts.Password != "" {
cluster.Authenticator = gocql.PasswordAuthenticator{
Username: opts.Username,
Password: opts.Password,
}
}
s, err := cluster.CreateSession()
if err != nil {
return fmt.Errorf("Connect error", err)
}
defer s.Close()
var release, cqlVersion string
var hostId gocql.UUID
err = s.Query(`SELECT release_version, cql_version, host_id
FROM system.local`).Scan(&release, &cqlVersion, &hostId)
if err != nil {
return fmt.Errorf("System metadata error", err)
}
md, err := s.KeyspaceMetadata(opts.Keyspace)
if err != nil {
return err
}
provenance := Provenance{
Keyspace: opts.Keyspace,
Version: version,
Timestamp: time.Now(),
HostId: hostId,
NegotiatedCQL: cluster.CQLVersion,
ServerCQL: cqlVersion,
ServerRelease: release,
}
meta := make(map[string]interface{})
meta["Provenance"] = provenance
meta["Options"] = opts
meta["Imports"] = coalesceImports(md)
meta["Tables"] = md.Tables
var b bytes.Buffer
if err := bindingTemplate.Execute(&b, meta); err != nil {
return err
}
bfmt, err := format.Source(b.Bytes())
if err != nil {
return err
}
if _, err := w.Write(bfmt); err != nil {
return err
}
return nil
}
func importPaths(md *gocql.KeyspaceMetadata) (imports []string) {
// Ideally need to use a set
paths := make(map[string]bool)
f := func(t *gocql.TypeInfo) {
literal := literalTypes[t.Type]
if strings.Contains(literal, ".") {
paths[literal] = true
}
}
for _, table := range md.Tables {
for _, col := range table.Columns {
t := col.Type
switch t.Type {
case gocql.TypeList, gocql.TypeSet:
f(t.Elem)
case gocql.TypeMap:
f(t.Key)
f(t.Elem)
default:
f(&t)
}
}
}
for path, _ := range paths {
customPath, present := customImportPaths[path]
if present {
imports = append(imports, customPath)
} else {
parts := strings.Split(path, ".")
imports = append(imports, parts[0])
}
}
return imports
}