-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathkeyspace.go
109 lines (88 loc) · 2.13 KB
/
keyspace.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package gocqltable
import (
"encoding/json"
"fmt"
"strings"
"github.com/gocql/gocql"
)
var (
defaultSession *gocql.Session
)
func SetDefaultSession(s *gocql.Session) {
defaultSession = s
}
type KeyspaceInterface interface {
Name() string
Session() *gocql.Session
}
type Keyspace struct {
name string
session *gocql.Session
}
func NewKeyspace(name string) Keyspace {
return Keyspace{
name: name,
session: defaultSession,
}
}
func (ks Keyspace) Create(replication map[string]interface{}, durableWrites bool) error {
if ks.session == nil {
ks.session = defaultSession
}
replicationBytes, err := json.Marshal(replication)
if err != nil {
return err
}
replicationMap := strings.Replace(string(replicationBytes), `"`, `'`, -1)
durableWritesString := "false"
if durableWrites {
durableWritesString = "true"
}
return ks.session.Query(fmt.Sprintf(`CREATE KEYSPACE %q WITH REPLICATION = %s AND DURABLE_WRITES = %s`, ks.Name(), replicationMap, durableWritesString)).Exec()
}
func (ks Keyspace) Drop() error {
if ks.session == nil {
ks.session = defaultSession
}
return ks.session.Query(fmt.Sprintf(`DROP KEYSPACE %q`, ks.Name())).Exec()
}
func (ks Keyspace) Tables() ([]string, error) {
if ks.session == nil {
ks.session = defaultSession
}
var name string
var resultSet []string
iterator := ks.session.Query(`SELECT columnfamily_name FROM system.schema_columnfamilies WHERE keyspace_name = ?;`, ks.Name()).Iter()
for iterator.Scan(&name) {
resultSet = append(resultSet, name)
}
if err := iterator.Close(); err != nil {
return nil, err
}
return resultSet, nil
}
func (ks Keyspace) NewTable(name string, rowKeys, rangeKeys []string, row interface{}) Table {
if ks.session == nil {
ks.session = defaultSession
}
return Table{
name: name,
rowKeys: rowKeys,
rangeKeys: rangeKeys,
row: row,
keyspace: ks,
session: ks.session,
}
}
func (ks Keyspace) Name() string {
return ks.name
}
func (ks Keyspace) Session() *gocql.Session {
if ks.session == nil {
ks.session = defaultSession
}
return ks.session
}
func (ks *Keyspace) SetSession(session *gocql.Session) {
ks.session = session
}