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
/
generate.go
220 lines (200 loc) · 5.94 KB
/
generate.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package gocassa
import (
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/gocql/gocql"
)
// CREATE TABLE users (
// user_name varchar PRIMARY KEY,
// password varchar,
// gender varchar,
// session_token varchar,
// state varchar,
// birth_year bigint
// );
//
// CREATE TABLE emp (
// empID int,
// deptID int,
// first_name varchar,
// last_name varchar,
// PRIMARY KEY (empID, deptID)
// );
//
func createTableIfNotExist(keySpace, cf string, partitionKeys, colKeys []string, fields []string, values []interface{}, order []ClusteringOrderColumn, compoundKey, compact bool, compressor string) (Statement, error) {
return createTableStmt("CREATE TABLE IF NOT EXISTS", keySpace, cf, partitionKeys, colKeys, fields, values, order, compoundKey, compact, compressor)
}
func createTable(keySpace, cf string, partitionKeys, colKeys []string, fields []string, values []interface{}, order []ClusteringOrderColumn, compoundKey, compact bool, compressor string) (Statement, error) {
return createTableStmt("CREATE TABLE", keySpace, cf, partitionKeys, colKeys, fields, values, order, compoundKey, compact, compressor)
}
func createTableStmt(createStmt, keySpace, cf string, partitionKeys, colKeys []string, fields []string, values []interface{}, order []ClusteringOrderColumn, compoundKey, compact bool, compressor string) (Statement, error) {
firstLine := fmt.Sprintf("%s %v.%v (", createStmt, keySpace, cf)
fieldLines := []string{}
for i, _ := range fields {
typeStr, err := stringTypeOf(values[i])
if err != nil {
return nil, err
}
l := " " + strings.ToLower(fields[i]) + " " + typeStr
fieldLines = append(fieldLines, l)
}
//key generation
str := ""
if len(colKeys) > 0 { //key (or composite key) + clustering columns
str = " PRIMARY KEY ((%v), %v)"
} else if compoundKey { //compound key just one set of parenthesis
str = " PRIMARY KEY (%v %v)"
} else { //otherwise is a composite key without colKeys
str = " PRIMARY KEY ((%v %v))"
}
fieldLines = append(fieldLines, fmt.Sprintf(str, j(partitionKeys), j(colKeys)))
lines := []string{
firstLine,
strings.Join(fieldLines, ",\n"),
")",
}
if len(order) > 0 {
orderStrs := make([]string, len(order))
for i, o := range order {
orderStrs[i] = fmt.Sprintf("%v %v", strings.ToLower(o.Column), o.Direction.String())
}
orderLine := fmt.Sprintf("WITH CLUSTERING ORDER BY (%v)", strings.Join(orderStrs, ", "))
lines = append(lines, orderLine)
}
if compact {
compactLineStart := "WITH"
if len(order) > 0 {
compactLineStart = "AND"
}
compactLine := fmt.Sprintf("%v COMPACT STORAGE", compactLineStart)
lines = append(lines, compactLine)
}
if len(compressor) > 0 {
compressionLineStart := "WITH"
if len(order) > 0 || compact {
compressionLineStart = "AND"
}
compressionLine := fmt.Sprintf("%v compression = {'sstable_compression': '%v'}", compressionLineStart, compressor)
lines = append(lines, compressionLine)
}
lines = append(lines, ";")
qry := strings.Join(lines, "\n")
return cqlStatement{query: qry}, nil
}
func j(s []string) string {
s1 := []string{}
for _, v := range s {
s1 = append(s1, strings.ToLower(v))
}
return strings.Join(s1, ", ")
}
type CQLTyper interface {
CQLType() gocql.Type
}
func cassaType(i interface{}) gocql.Type {
switch i.(type) {
case int, int32:
return gocql.TypeInt
case int64:
return gocql.TypeBigInt
case int8, int16, uint, uint8, uint16, uint32, uint64:
return gocql.TypeVarint
case string:
return gocql.TypeVarchar
case float32:
return gocql.TypeFloat
case float64:
return gocql.TypeDouble
case bool:
return gocql.TypeBoolean
case time.Time:
return gocql.TypeTimestamp
case gocql.UUID:
return gocql.TypeUUID
case []byte:
return gocql.TypeBlob
case Counter:
return gocql.TypeCounter
}
// Fallback to using reflection if type not recognised
typ := reflect.TypeOf(i)
switch typ.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32:
return gocql.TypeInt
case reflect.Int64:
return gocql.TypeBigInt
case reflect.String:
return gocql.TypeVarchar
case reflect.Float32:
return gocql.TypeFloat
case reflect.Float64:
return gocql.TypeDouble
case reflect.Bool:
return gocql.TypeBoolean
}
// Check if the field implements the CQLTyper interface
if v, ok := i.(CQLTyper); ok {
return v.CQLType()
}
return gocql.TypeCustom
}
func stringTypeOf(i interface{}) (string, error) {
_, isByteSlice := i.([]byte)
if !isByteSlice {
// Check if we found a higher kinded type
switch reflect.ValueOf(i).Kind() {
case reflect.Slice:
elemVal := reflect.Indirect(reflect.New(reflect.TypeOf(i).Elem())).Interface()
ct := cassaType(elemVal)
if ct == gocql.TypeCustom {
return "", fmt.Errorf("Unsupported type %T", i)
}
return fmt.Sprintf("list<%v>", ct), nil
case reflect.Map:
keyVal := reflect.Indirect(reflect.New(reflect.TypeOf(i).Key())).Interface()
elemVal := reflect.Indirect(reflect.New(reflect.TypeOf(i).Elem())).Interface()
keyCt := cassaType(keyVal)
elemCt := cassaType(elemVal)
if keyCt == gocql.TypeCustom || elemCt == gocql.TypeCustom {
return "", fmt.Errorf("Unsupported map key or value type %T", i)
}
return fmt.Sprintf("map<%v, %v>", keyCt, elemCt), nil
}
}
ct := cassaType(i)
if ct == gocql.TypeCustom {
return "", fmt.Errorf("Unsupported type %T", i)
}
return cassaTypeToString(ct)
}
func cassaTypeToString(t gocql.Type) (string, error) {
switch t {
case gocql.TypeInt:
return "int", nil
case gocql.TypeBigInt:
return "bigint", nil
case gocql.TypeVarint:
return "varint", nil
case gocql.TypeVarchar:
return "varchar", nil
case gocql.TypeFloat:
return "float", nil
case gocql.TypeDouble:
return "double", nil
case gocql.TypeBoolean:
return "boolean", nil
case gocql.TypeTimestamp:
return "timestamp", nil
case gocql.TypeUUID:
return "uuid", nil
case gocql.TypeBlob:
return "blob", nil
case gocql.TypeCounter:
return "counter", nil
default:
return "", errors.New("unkown cassandra type")
}
}