Skip to content

Instantly share code, notes, and snippets.

@kostja
Created August 27, 2019 14:06
Show Gist options
  • Save kostja/d040d2eb855a52ce05aabcce920a6834 to your computer and use it in GitHub Desktop.
Save kostja/d040d2eb855a52ce05aabcce920a6834 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"fmt"
"github.com/gocql/gocql"
"log"
"reflect"
)
// Result of execution of a CQL statement
type CQLResult struct {
status string
rows [][]string
}
func Print(result *CQLResult) {
buf := new(bytes.Buffer)
if result.status != "OK" {
fmt.Fprintf(buf, "status: %s\n", result.status)
} else if len(result.rows) != 0 {
fmt.Fprintf(buf, "%v\n", result.rows)
} else {
fmt.Fprint(buf, "OK\n")
}
fmt.Print(string(buf.Bytes()))
}
func Execute(session *gocql.Session, cql string) {
var result CQLResult
query := session.Query(cql)
err := query.Exec()
if err == nil {
result.status = "OK"
iter := query.Iter()
row, _ := iter.RowData()
for {
if !iter.Scan(row.Values...) {
break
}
strrow := make([]string, len(row.Values))
for i, v := range row.Values {
strrow[i] = fmt.Sprint(reflect.Indirect(reflect.ValueOf(v)))
}
result.rows = append(result.rows, strrow)
}
} else {
result.status = "ERROR"
}
Print(&result)
}
func main() {
cluster := gocql.NewCluster("127.0.0.1")
cluster.RetryPolicy = &gocql.SimpleRetryPolicy{NumRetries: 1}
cluster.Authenticator = gocql.PasswordAuthenticator{Username: "cassandra", Password: ""}
cluster.Keyspace = "test"
session, err := cluster.CreateSession()
if err != nil {
log.Fatal(err)
}
statements := []string{
"create table lwt (a int, listint list<int>, primary key (a))",
"insert into lwt (a) values (1)",
"update lwt set listint = listint + [5] where a = 1",
"update lwt set listint = [-1] + listint where a = 1",
"select * from lwt allow filtering",
}
for _, v := range statements {
Execute(session, v)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment