/
sql.go
88 lines (72 loc) · 1.64 KB
/
sql.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
package main
import (
"fmt"
"os"
"github.com/canonical/microcluster/microcluster"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
)
type cmdSQL struct {
common *CmdControl
}
func (c *cmdSQL) Command() *cobra.Command {
cmd := &cobra.Command{
Use: "sql <query>",
Short: "Execute a SQL query against the daemon",
RunE: c.Run,
}
return cmd
}
func (c *cmdSQL) Run(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
err := cmd.Help()
if err != nil {
return fmt.Errorf("Unable to load help: %w", err)
}
if len(args) == 0 {
return nil
}
}
m, err := microcluster.App(microcluster.Args{StateDir: c.common.FlagStateDir, Verbose: c.common.FlagLogVerbose, Debug: c.common.FlagLogDebug})
if err != nil {
return err
}
query := args[0]
dump, batch, err := m.SQL(cmd.Context(), query)
if err != nil {
return err
}
if dump != "" {
fmt.Print(dump)
return nil
}
for i, result := range batch.Results {
if len(batch.Results) > 1 {
fmt.Printf("=> Query %d:\n\n", i)
}
if result.Type == "select" {
sqlPrintSelectResult(result.Columns, result.Rows)
} else {
fmt.Printf("Rows affected: %d\n", result.RowsAffected)
}
if len(batch.Results) > 1 {
fmt.Printf("\n")
}
}
return nil
}
func sqlPrintSelectResult(columns []string, rows [][]any) {
table := tablewriter.NewWriter(os.Stdout)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetAutoWrapText(false)
table.SetAutoFormatHeaders(false)
table.SetHeader(columns)
for _, row := range rows {
data := []string{}
for _, col := range row {
data = append(data, fmt.Sprintf("%v", col))
}
table.Append(data)
}
table.Render()
}