forked from kristoiv/gocqltable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.go
122 lines (95 loc) · 2.27 KB
/
table.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
110
111
112
113
114
115
116
117
118
119
120
121
122
package gocqltable
import (
"fmt"
"strings"
"github.com/gocql/gocql"
r "github.com/elvtechnology/gocqltable/reflect"
)
type TableInterface interface {
Create() error
Drop() error
Query(statement string, params ...interface{}) Query
Name() string
Keyspace() Keyspace
RowKeys() []string
RangeKeys() []string
Row() interface{}
}
type Table struct {
name string
rowKeys []string
rangeKeys []string
row interface{}
keyspace Keyspace
session *gocql.Session
}
func (t Table) Create() error {
return t.create()
}
func (t Table) CreateWithProperties(props ...string) error {
return t.create(props...)
}
func (t Table) create(props ...string) error {
if t.session == nil {
t.session = defaultSession
}
rowKeys := t.RowKeys()
rangeKeys := t.RangeKeys()
pkString := "PRIMARY KEY ((" + strings.Join(rowKeys, ", ") + ")"
if len(rangeKeys) > 0 {
pkString = pkString + ", " + strings.Join(rangeKeys, ", ")
}
pkString = pkString + ")"
fields := []string{}
m, ok := r.StructToMap(t.Row())
if !ok {
panic("Unable to get map from struct during create table")
}
for key, value := range m {
key = strings.ToLower(key)
typ, err := stringTypeOf(value)
if err != nil {
return err
}
fields = append(fields, fmt.Sprintf(`%q %v`, key, typ))
}
// Add primary key value to fields list
fields = append(fields, pkString)
propertiesString := ""
if len(props) > 0 {
propertiesString = "WITH " + strings.Join(props, " AND ")
}
return t.session.Query(fmt.Sprintf(`CREATE TABLE %q.%q (%s) %s`, t.Keyspace().Name(), t.Name(), strings.Join(fields, ", "), propertiesString)).Exec()
}
func (t Table) Drop() error {
if t.session == nil {
t.session = defaultSession
}
return t.session.Query(fmt.Sprintf(`DROP TABLE %q.%q`, t.Keyspace().Name(), t.Name())).Exec()
}
func (t Table) Query(statement string, values ...interface{}) Query {
if t.session == nil {
t.session = defaultSession
}
return Query{
Statement: statement,
Values: values,
Table: t,
Session: t.session,
}
}
func (t Table) Name() string {
return t.name
}
func (t Table) Keyspace() Keyspace {
return t.keyspace
}
func (t Table) RowKeys() []string {
return t.rowKeys
}
func (t Table) RangeKeys() []string {
return t.rangeKeys
}
func (t Table) Row() interface{} {
return t.row
}