This repository has been archived by the owner on Sep 9, 2024. It is now read-only.
forked from gocassa/gocassa
-
Notifications
You must be signed in to change notification settings - Fork 13
/
gocql_backend.go
92 lines (78 loc) · 2.27 KB
/
gocql_backend.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
package gocassa
import (
"github.com/gocql/gocql"
)
type goCQLBackend struct {
session *gocql.Session
}
func (cb goCQLBackend) Query(stmt Statement, scanner Scanner) error {
return cb.QueryWithOptions(Options{}, stmt, scanner)
}
func (cb goCQLBackend) QueryWithOptions(opts Options, stmt Statement, scanner Scanner) error {
qu := cb.session.Query(stmt.Query(), stmt.Values()...)
if opts.Consistency != nil {
qu = qu.Consistency(*opts.Consistency)
}
if opts.Context != nil {
qu = qu.WithContext(opts.Context)
}
iter := qu.Iter()
if _, err := scanner.ScanIter(iter.Scanner()); err != nil {
return err
}
return iter.Close()
}
func (cb goCQLBackend) Execute(stmt Statement) error {
return cb.ExecuteWithOptions(Options{}, stmt)
}
func (cb goCQLBackend) ExecuteWithOptions(opts Options, stmt Statement) error {
qu := cb.session.Query(stmt.Query(), stmt.Values()...)
if opts.Consistency != nil {
qu = qu.Consistency(*opts.Consistency)
}
if opts.Context != nil {
qu = qu.WithContext(opts.Context)
}
return qu.Exec()
}
func (cb goCQLBackend) ExecuteAtomically(stmts []Statement) error {
return cb.ExecuteAtomicallyWithOptions(Options{}, stmts)
}
func (cb goCQLBackend) ExecuteAtomicallyWithOptions(opts Options, stmts []Statement) error {
if len(stmts) == 0 {
return nil
}
batch := cb.session.NewBatch(gocql.LoggedBatch)
for i := range stmts {
stmt := stmts[i]
batch.Query(stmt.Query(), stmt.Values()...)
}
if opts.Consistency != nil {
batch.Cons = *opts.Consistency
}
if opts.Context != nil {
batch = batch.WithContext(opts.Context)
}
return cb.session.ExecuteBatch(batch)
}
// GoCQLSessionToQueryExecutor enables you to supply your own gocql session with your custom options
// Then you can use NewConnection to mint your own thing
// See #90 for more details
func GoCQLSessionToQueryExecutor(sess *gocql.Session) QueryExecutor {
return goCQLBackend{
session: sess,
}
}
func newGoCQLBackend(nodeIps []string, username, password string) (QueryExecutor, error) {
cluster := gocql.NewCluster(nodeIps...)
cluster.Consistency = gocql.One
cluster.Authenticator = gocql.PasswordAuthenticator{
Username: username,
Password: password,
}
sess, err := cluster.CreateSession()
if err != nil {
return nil, err
}
return GoCQLSessionToQueryExecutor(sess), nil
}