-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
82 lines (70 loc) · 1.79 KB
/
main.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
package main
import (
"flag"
"fmt"
"log"
"github.com/gocql/gocql"
"reflect"
"text/tabwriter"
"os"
)
func main() {
host := flag.String("host", "localhost", "Cassandra host (without port)")
port := flag.Int("port", 9042, "Cassandra host port")
user := flag.String("user", "", "Username - will not use authentication if blank")
pass := flag.String("pass", "", "Password - will not use authentication if blank")
keyspace := flag.String("keyspace", "", "Cassandra Keyspace - will not use keyspace of blank")
command := flag.String("command", "", "CQL command to execute")
flag.Parse()
if *command == "" {
log.Fatal("command cannot be empty")
}
cluster := gocql.NewCluster(fmt.Sprintf("%s:%d", *host, *port))
if (*user != "" && *pass != "") {
cluster.Authenticator = gocql.PasswordAuthenticator{
Username: *user,
Password: *pass,
}
}
if *keyspace != "" {
cluster.Keyspace = *keyspace
}
session, err := cluster.CreateSession()
if err != nil {
log.Fatal(err)
}
defer session.Close()
iter := session.Query(*command).Iter()
defer iter.Close()
printIter(iter)
}
// Borrowed from https://pkg.go.dev/github.com/gocql/gocql#example-package-DynamicColumns
func printIter(iter *gocql.Iter) {
w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', 0)
for i, columnInfo := range iter.Columns() {
if i > 0 {
fmt.Fprint(w, "\t| ")
}
fmt.Fprintf(w, "%s (%s)", columnInfo.Name, columnInfo.TypeInfo)
}
for {
rd, err := iter.RowData()
if err != nil {
fmt.Println(reflect.ValueOf(err).Type())
log.Fatal(err)
}
if !iter.Scan(rd.Values...) {
break
}
fmt.Fprint(w, "\n")
for i, val := range rd.Values {
if i > 0 {
fmt.Fprint(w, "\t| ")
}
fmt.Fprint(w, reflect.Indirect(reflect.ValueOf(val)).Interface())
}
}
fmt.Fprint(w, "\n")
w.Flush()
fmt.Println()
}