/
client_query.go
222 lines (204 loc) · 5.22 KB
/
client_query.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
package main
import (
"errors"
"fmt"
"log"
"os"
"strconv"
"strings"
"github.com/cretz/temporal-sdk-go-advanced/temporalsqlite"
"github.com/olekukonko/tablewriter"
"github.com/urfave/cli/v2"
"go.temporal.io/sdk/client"
)
type queryConfig struct {
clientConfig
params cli.StringSlice
multi bool
}
func (q *queryConfig) flags() []cli.Flag {
return append(q.clientConfig.flags(),
&cli.StringSliceFlag{
Name: "param",
Usage: "Parameters in the form of <index|name>=<type>(<value>) (or just =null, indices start at 1)",
Destination: &q.params,
},
&cli.BoolFlag{
Name: "multi",
Usage: "Treat the query as a script with multiple statements (cannot have params)",
Destination: &q.multi,
},
)
}
var errBadParam = errors.New("all parameters must be in the form of <index|name>=<type>(<value>) (or just =null)")
func (q *queryConfig) toStmt(args cli.Args) (*temporalsqlite.Stmt, error) {
if args.Len() == 0 || args.Len() > 1 {
return nil, fmt.Errorf("must have a single query argument")
} else if q.multi && len(q.params.Value()) > 0 {
return nil, fmt.Errorf("cannot have parameters on multi statement")
}
stmt := &temporalsqlite.Stmt{Query: args.First(), Multi: q.multi}
for _, param := range q.params.Value() {
pieces := strings.SplitN(param, "=", 2)
if len(pieces) != 2 {
return nil, errBadParam
}
// Convert val type
var val interface{}
if pieces[1] != "null" {
valPieces := strings.SplitN(pieces[1], "(", 2)
if len(valPieces) != 2 || !strings.HasSuffix(valPieces[1], ")") {
return nil, errBadParam
}
valPieces[1] = strings.TrimSuffix(valPieces[1], ")")
var err error
switch valPieces[0] {
case "int":
val, err = strconv.ParseInt(valPieces[1], 10, 64)
case "float":
val, err = strconv.ParseFloat(valPieces[1], 64)
case "string":
val = valPieces[1]
case "bytes":
val = []byte(valPieces[1])
default:
return nil, fmt.Errorf("parameter type was %q, expected int, float, string or bytes", valPieces[0])
}
if err != nil {
return nil, fmt.Errorf("invalid parameter value %q: %v", valPieces[1], err)
}
}
// Use index if num, otherwise named
if i, err := strconv.Atoi(pieces[0]); err == nil {
if stmt.IndexedParams == nil {
stmt.IndexedParams = map[int]interface{}{}
}
stmt.IndexedParams[i] = val
} else {
if stmt.NamedParams == nil {
stmt.NamedParams = map[string]interface{}{}
}
stmt.NamedParams[pieces[0]] = val
}
}
return stmt, nil
}
func dialAndConnectWithStmt(
ctx *cli.Context,
config queryConfig,
) (cl client.Client, dbCl *temporalsqlite.Client, stmt *temporalsqlite.Stmt, err error) {
cl, err = config.dialClient()
defer func() {
if cl != nil && err != nil {
cl.Close()
}
}()
if err == nil {
dbCl, err = config.connect(ctx.Context, cl)
}
if err == nil {
stmt, err = config.toStmt(ctx.Args())
}
return
}
func dumpSuccesses(successes []*temporalsqlite.StmtResultSuccess) {
var dumpedFirst bool
for _, success := range successes {
if len(success.Rows) == 0 {
continue
} else if dumpedFirst {
fmt.Println()
} else {
dumpedFirst = true
}
dumpSuccess(success)
}
}
func dumpSuccess(s *temporalsqlite.StmtResultSuccess) {
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader(s.ColumnNames)
for _, row := range s.Rows {
rowStrs := make([]string, len(row))
for i, val := range row {
rowStrs[i] = fmt.Sprintf("%v", val)
}
table.Append(rowStrs)
}
table.Render()
}
func queryCmd() *cli.Command {
var config queryConfig
return &cli.Command{
Name: "query",
Usage: "send a read-only query and get a response",
Flags: config.flags(),
Action: func(ctx *cli.Context) error {
client, dbClient, stmt, err := dialAndConnectWithStmt(ctx, config)
if err != nil {
return err
}
defer client.Close()
defer dbClient.Close()
// Query and dump
res, err := dbClient.Query(ctx.Context, stmt)
if err != nil {
return err
}
dumpSuccesses(res[0].Successes)
if res[0].Error != nil {
return res[0].Error
}
log.Printf("Queries succeeded")
return nil
},
}
}
func updateCmd() *cli.Command {
var config queryConfig
return &cli.Command{
Name: "update",
Usage: "send an update that, by default, fails the entire DB if it does not succeed",
Flags: config.flags(),
Action: func(ctx *cli.Context) error {
client, dbClient, stmt, err := dialAndConnectWithStmt(ctx, config)
if err != nil {
return err
}
defer client.Close()
defer dbClient.Close()
// Update
if err := dbClient.Update(ctx.Context, stmt); err != nil {
return err
}
log.Printf("Update sent")
return nil
},
}
}
func execCmd() *cli.Command {
var config queryConfig
return &cli.Command{
Name: "exec",
Usage: "exec a query and get a response",
Flags: config.flags(),
Action: func(ctx *cli.Context) error {
client, dbClient, stmt, err := dialAndConnectWithStmt(ctx, config)
if err != nil {
return err
}
defer client.Close()
defer dbClient.Close()
// Exec and dump
res, err := dbClient.Exec(ctx.Context, stmt)
if err != nil {
return err
}
dumpSuccesses(res[0].Successes)
if res[0].Error != nil {
return res[0].Error
}
log.Printf("Executions succeeded")
return nil
},
}
}