Repository navigation
Expand file tree
/
Copy pathcli.go
More file actions
561 lines (474 loc) · 12.3 KB
/
Copy pathcli.go
File metadata and controls
561 lines (474 loc) · 12.3 KB
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
package cli
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"github.com/scriptease/database-cli/internal/client"
"github.com/scriptease/database-cli/internal/protocol"
)
const topHelp = `database-cli <subcommand> [flags] [args]
Subcommands:
ping Check if the daemon is running
list List open connection aliases
open Open a new JDBC connection
close Close an open connection
query Run a SELECT query
exec Run an INSERT/UPDATE/DELETE statement
schema List tables in the database
describe Describe columns of a table
begin Begin a transaction
commit Commit a transaction
rollback Roll back a transaction
batch Execute multiple operations from stdin (NDJSON)
Global flags:
--help Show this help
Run 'database-cli <subcommand> --help' for subcommand-specific usage.
`
var boolFlags = map[string]struct{}{
"help": {},
"json": {},
"password-stdin": {},
"read-only": {},
}
type parsedArgs struct {
flags map[string]string
positionals []string
}
func Run(args []string) error {
if len(args) == 0 || isHelp(args[0]) {
printTopHelp()
return nil
}
socketPath, err := protocol.SocketPath()
if err != nil {
return err
}
httpClient := client.New(socketPath)
switch args[0] {
case "ping":
return runPing(httpClient, args[1:])
case "list":
return runList(httpClient, args[1:])
case "open":
return runOpen(httpClient, args[1:])
case "close":
return runAliasCommand(httpClient, args[1:], protocol.PathClose, "close")
case "query":
return runQuery(httpClient, args[1:])
case "exec":
return runExec(httpClient, args[1:])
case "schema":
return runAliasCommand(httpClient, args[1:], protocol.PathSchema, "schema")
case "describe":
return runDescribe(httpClient, args[1:])
case "begin":
return runAliasCommand(httpClient, args[1:], protocol.PathBegin, "begin")
case "commit":
return runAliasCommand(httpClient, args[1:], protocol.PathCommit, "commit")
case "rollback":
return runAliasCommand(httpClient, args[1:], protocol.PathRollback, "rollback")
case "batch":
return runBatch(httpClient, args[1:])
default:
return fmt.Errorf("unknown subcommand: %s", args[0])
}
}
func runPing(httpClient *client.Client, args []string) error {
if containsHelp(args) {
printHelp("ping")
return nil
}
body, err := httpClient.Get(protocol.PathPing)
if err != nil {
return err
}
writeStdout(body)
return nil
}
func runList(httpClient *client.Client, args []string) error {
if containsHelp(args) {
printHelp("list")
return nil
}
body, err := httpClient.Get(protocol.PathList)
if err != nil {
return err
}
writeStdout(body)
return nil
}
func runOpen(httpClient *client.Client, args []string) error {
if containsHelp(args) {
printHelp("open")
return nil
}
parsed := parse(args, 0)
req := protocol.OpenRequest{
Alias: parsed.flags["alias"],
JDBCURL: parsed.flags["jdbc-url"],
User: parsed.flags["user"],
PasswordKeychain: parsed.flags["password-keychain"],
ReadOnly: hasFlag(parsed.flags, "read-only"),
}
if req.Alias == "" {
return fmt.Errorf("--alias required")
}
if req.JDBCURL == "" {
return fmt.Errorf("--jdbc-url required")
}
if hasFlag(parsed.flags, "password-stdin") {
password, err := readPasswordStdin()
if err != nil {
return err
}
req.Password = password
}
body, err := httpClient.PostJSON(protocol.PathOpen, req)
if err != nil {
return err
}
writeStdout(body)
return nil
}
func runAliasCommand(httpClient *client.Client, args []string, path string, help string) error {
if containsHelp(args) {
printHelp(help)
return nil
}
parsed := parse(args, 0)
alias := parsed.flags["alias"]
if alias == "" {
return fmt.Errorf("--alias required")
}
body, err := httpClient.PostJSON(path, protocol.AliasRequest{Alias: alias})
if err != nil {
return err
}
writeStdout(body)
return nil
}
func runQuery(httpClient *client.Client, args []string) error {
if containsHelp(args) {
printHelp("query")
return nil
}
parsed := parse(args, 0)
alias := parsed.flags["alias"]
if alias == "" {
return fmt.Errorf("--alias required")
}
sqlText, err := sqlArgument(parsed.flags, parsed.positionals)
if err != nil {
return err
}
body, err := httpClient.PostJSON(protocol.PathQuery, protocol.SQLRequest{
Alias: alias,
SQL: sqlText,
JSON: hasFlag(parsed.flags, "json"),
})
if err != nil {
return err
}
writeStdout(body)
return nil
}
func runExec(httpClient *client.Client, args []string) error {
if containsHelp(args) {
printHelp("exec")
return nil
}
parsed := parse(args, 0)
alias := parsed.flags["alias"]
if alias == "" {
return fmt.Errorf("--alias required")
}
sqlText, err := sqlArgument(parsed.flags, parsed.positionals)
if err != nil {
return err
}
body, err := httpClient.PostJSON(protocol.PathExec, protocol.SQLRequest{
Alias: alias,
SQL: sqlText,
})
if err != nil {
return err
}
writeStdout(body)
return nil
}
func runDescribe(httpClient *client.Client, args []string) error {
if containsHelp(args) {
printHelp("describe")
return nil
}
parsed := parse(args, 0)
req := protocol.DescribeRequest{
Alias: parsed.flags["alias"],
Table: parsed.flags["table"],
}
if req.Alias == "" {
return fmt.Errorf("--alias required")
}
if req.Table == "" {
return fmt.Errorf("--table required")
}
body, err := httpClient.PostJSON(protocol.PathDescribe, req)
if err != nil {
return err
}
writeStdout(body)
return nil
}
func runBatch(httpClient *client.Client, args []string) error {
if containsHelp(args) {
printHelp("batch")
return nil
}
parsed := parse(args, 0)
defaultAlias := parsed.flags["alias"]
body, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
if defaultAlias != "" {
body, err = injectDefaultAlias(body, defaultAlias)
if err != nil {
return err
}
}
response, err := httpClient.PostText(protocol.PathBatch, "application/x-ndjson", body)
if err != nil {
return err
}
writeStdout(response)
return nil
}
func parse(args []string, start int) parsedArgs {
flags := make(map[string]string)
positionals := make([]string, 0)
for i := start; i < len(args); i++ {
arg := args[i]
if strings.HasPrefix(arg, "--") {
key := strings.TrimPrefix(arg, "--")
_, isBool := boolFlags[key]
if isBool || i+1 >= len(args) || strings.HasPrefix(args[i+1], "--") {
flags[key] = ""
continue
}
flags[key] = args[i+1]
i++
continue
}
positionals = append(positionals, arg)
}
return parsedArgs{
flags: flags,
positionals: positionals,
}
}
func sqlArgument(flags map[string]string, positionals []string) (string, error) {
if len(positionals) > 0 {
return strings.Join(positionals, " "), nil
}
if sqlText := flags["sql"]; strings.TrimSpace(sqlText) != "" {
return sqlText, nil
}
return "", fmt.Errorf("SQL argument required")
}
func hasFlag(flags map[string]string, key string) bool {
_, ok := flags[key]
return ok
}
func printTopHelp() {
_, _ = io.WriteString(os.Stdout, topHelp)
}
func printHelp(cmd string) {
text := helpText(cmd)
_, _ = io.WriteString(os.Stdout, text)
if !strings.HasSuffix(text, "\n") {
_, _ = io.WriteString(os.Stdout, "\n")
}
}
func helpText(cmd string) string {
switch cmd {
case "ping":
return `ping Check if the daemon is running.
Usage:
database-cli ping
`
case "list":
return `list List all open connection aliases.
Usage:
database-cli list
`
case "open":
return `open Open a new JDBC connection and register it under an alias.
Usage:
database-cli open --alias <name> --jdbc-url <url> [auth flags]
Flags:
--alias <name> Alias to register this connection under (required)
--jdbc-url <url> JDBC URL, e.g. jdbc:mysql://localhost:3306/mydb (required)
--user <user> Database username
--password-stdin Read password from stdin
--password-keychain <ref> Look up password from macOS Keychain (service/account)
--read-only Block write operations (exec, begin, commit, rollback) on this alias
`
case "close":
return `close Close an open connection.
Usage:
database-cli close --alias <name>
Flags:
--alias <name> Connection alias to close (required)
`
case "query":
return `query Run a SELECT query and print results.
Usage:
database-cli query --alias <name> [--json] '<SQL>'
Flags:
--alias <name> Connection alias (required)
--json Output results as JSON array instead of TSV
Example:
database-cli query --alias mydb 'SELECT * FROM users LIMIT 10'
database-cli query --alias mydb --json 'SELECT id, name FROM users'
`
case "exec":
return `exec Run a write SQL statement (INSERT, UPDATE, DELETE, DDL).
Usage:
database-cli exec --alias <name> '<SQL>'
Flags:
--alias <name> Connection alias (required)
Output:
{"rowsAffected": <n>}
Note: blocked if the alias was opened with --read-only.
`
case "schema":
return `schema List all tables in the database.
Usage:
database-cli schema --alias <name>
Flags:
--alias <name> Connection alias (required)
`
case "describe":
return `describe Show column definitions for a table.
Usage:
database-cli describe --alias <name> --table <table>
Flags:
--alias <name> Connection alias (required)
--table <table> Table name (required)
Output:
JSON array of {name, type, size, nullable} objects.
`
case "begin":
return `begin Begin a transaction on the connection.
Usage:
database-cli begin --alias <name>
Flags:
--alias <name> Connection alias (required)
Note: blocked if the alias was opened with --read-only.
`
case "commit":
return `commit Commit the current transaction.
Usage:
database-cli commit --alias <name>
Flags:
--alias <name> Connection alias (required)
Note: blocked if the alias was opened with --read-only.
`
case "rollback":
return `rollback Roll back the current transaction.
Usage:
database-cli rollback --alias <name>
Flags:
--alias <name> Connection alias (required)
Note: blocked if the alias was opened with --read-only.
`
case "batch":
return `batch Execute multiple operations from stdin in NDJSON format.
Usage:
echo '<ndjson>' | database-cli batch [--alias <default-alias>]
Flags:
--alias <name> Default alias injected into ops that omit it (optional)
Each stdin line is a JSON object with an "op" field:
{"op":"query","alias":"mydb","sql":"SELECT 1","json":false}
{"op":"exec","alias":"mydb","sql":"INSERT INTO t VALUES (1)"}
{"op":"begin","alias":"mydb"}
{"op":"commit","alias":"mydb"}
{"op":"rollback","alias":"mydb"}
Output is one NDJSON result line per input line.
Note: blocked if the alias was opened with --read-only.
`
default:
return fmt.Sprintf("No help available for %q.\n", cmd)
}
}
func injectDefaultAlias(body []byte, alias string) ([]byte, error) {
scanner := bufio.NewScanner(bytes.NewReader(body))
scanner.Buffer(make([]byte, 0, 1024), 10*1024*1024)
var out bytes.Buffer
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
updated, err := injectAlias(line, alias)
if err != nil {
return nil, err
}
out.WriteString(updated)
out.WriteByte('\n')
}
if err := scanner.Err(); err != nil {
return nil, err
}
return out.Bytes(), nil
}
func injectAlias(line string, alias string) (string, error) {
var obj map[string]json.RawMessage
if err := json.Unmarshal([]byte(line), &obj); err != nil {
return line, nil
}
if _, ok := obj["alias"]; ok {
return line, nil
}
value, err := json.Marshal(alias)
if err != nil {
return "", err
}
obj["alias"] = value
updated, err := json.Marshal(obj)
if err != nil {
return "", err
}
return string(updated), nil
}
func readPasswordStdin() (string, error) {
body, err := io.ReadAll(os.Stdin)
if err != nil {
return "", err
}
return strings.TrimRight(string(body), "\r\n"), nil
}
func containsHelp(args []string) bool {
for _, arg := range args {
if isHelp(arg) {
return true
}
}
return false
}
func isHelp(arg string) bool {
return arg == "--help" || arg == "-h"
}
func writeStdout(body []byte) {
if len(body) == 0 {
return
}
_, _ = os.Stdout.Write(body)
if body[len(body)-1] != '\n' {
_, _ = os.Stdout.Write([]byte("\n"))
}
}