forked from ether/ueberDB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cassandra_db.js
273 lines (247 loc) · 10 KB
/
cassandra_db.js
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Helenus = require('helenus');
/**
* Cassandra DB constructor.
*
* @param {Object} settings The required settings object to create a Cassandra pool.
* @param {String[]} settings.hosts An array of '<ip>:<port>' strings that are running the Cassandra database.
* @param {String} settings.keyspace The keyspace that should be used, it's assumed that the keyspace already exists.
* @param {String} settings.cfName The prefix for the column families that should be used to store data. The column families will be created if they don't exist.
* @param {String} [settings.user] A username that should be used to authenticate with Cassandra (optional.)
* @param {String} [settings.pass] A password that should be used to authenticate with Cassandra (optional.)
* @param {Number} [settings.timeout] The time (defined in ms) when a query has been considered to time-out (Optional, default 3000.)
* @param {Number} [settings.replication] The replication factor to use. (Optional, default 1.)
* @param {String} [settings.strategyClass] The strategyClass to use (Optional, default 'SimpleStrategy'.)
*/
exports.database = function(settings) {
var self = this;
if (!settings.hosts || settings.hosts.length === 0) {
throw new Error('The Cassandra hosts should be defined.');
}
if (!settings.keyspace) {
throw new Error('The Cassandra keyspace should be defined.');
}
if (!settings.cfName) {
throw new Error('The Cassandra column family should be defined.');
}
self.settings = {};
self.settings.hosts = settings.hosts;
self.settings.keyspace = settings.keyspace;
self.settings.cfName = settings.cfName;
if (settings.user) {
self.settings.user = settings.user;
}
if (settings.pass) {
self.settings.pass = settings.pass;
}
self.settings.timeout = parseInt(settings.timeout, 10) || 3000;
self.settings.replication = parseInt(settings.replication, 10) || 1;
self.settings.strategyClass = settings.strategyClass || 'SimpleStrategy';
self.settings.cqlVersion = '2.0.0';
};
/**
* Initializes the Cassandra pool, connects to cassandra and creates the CF if it didn't exist already.
*
* @param {Function} callback Standard callback method.
* @param {Error} callback.err An error object (if any.)
*/
exports.database.prototype.init = function(callback) {
var self = this;
// Create pool
self.pool = new Helenus.ConnectionPool(self.settings);
self.pool.on('error', function(err) {
// We can't use the callback method here, as this is a generic error handler.
console.error(err);
});
// Connect to it.
self.pool.connect(function(err) {
if (err) {
return callback(err);
}
// Get a description of the keyspace so we can determine whether or not the CF exist.
self.pool.getConnection()._client.describe_keyspace(self.settings.keyspace, function(err, definition) {
if (err && err.name) {
// If the keyspace doesn't exist, it will throw here.
return callback(err);
}
// Iterate over all the column families and check if the desired one exists.
var exists = false;
for (var i = 0; i < definition.cf_defs.length;i++) {
if (definition.cf_defs[i].name === self.settings.cfName) {
exists = true;
break;
}
}
if (exists) {
// The CF exists, we're done here.
callback(null);
} else {
// Create the CF
var cql = 'CREATE COLUMNFAMILY ? (key text PRIMARY KEY, data text);';
self.pool.cql(cql, [ self.settings.cfName ], callback);
}
});
});
};
/**
* Gets a value from Cassandra.
*
* @param {String} key The key for which the value should be retrieved.
* @param {Function} callback Standard callback method.
* @param {Error} callback.err An error object (if any.)
* @param {String} callback.value The value for the given key (if any.)
*/
exports.database.prototype.get = function (key, callback) {
var self = this;
var cql = 'SELECT ? FROM ? WHERE ? = ?';
self.pool.cql(cql, [ 'data', self.settings.cfName, 'key', key ], function (err, rows) {
if (err) {
return callback(err);
}
if (rows.length === 0 || rows[0].count === 0 || !rows[0].get('data')) {
return callback(null, null);
}
callback(null, rows[0].get('data').value);
});
};
/**
* Cassandra has no native `findKeys` method. This function implements a naive filter by retrieving *all* the keys and filtering those.
* This should obviously be used with the utmost care and is probably not something you want to run in production.
*
* @param {String} key The filter for keys that should match.
* @param {String} [notKey] The filter for keys that shouldn't match.
* @param {Function} callback Standard callback method
* @param {Error} callback.err Error object in case something goes wrong.
* @param {String[]} callback.keys An array of keys that match the specified filters.
*/
exports.database.prototype.findKeys = function (key, notKey, callback) {
var self = this;
if (!notKey) {
// Get all the keys.
var cql = 'SELECT ? FROM ?';
self.pool.cql(cql, [ 'key', self.settings.cfName ], function (err, rows) {
if (err) {
return callback(err);
}
var keys = [];
rows.forEach(function(row) {
keys.push(row.get('key').value);
});
callback(null, keys);
});
} else if (notKey === '*:*:*') {
// restrict key to format 'text:*'
var matches = /^([^:]+):\*$/.exec(key);
if (matches) {
// Get the 'text' bit out of the key and get all those keys from a special column.
// We can retrieve them from this column as we're duplicating them on .set/.remove
var cql = 'SELECT * from ? WHERE ? = ?';
self.pool.cql(cql, [ self.settings.cfName, 'key', 'ueberdb:keys:' + matches[1] ], function (err, rows) {
if (err) {
return callback(err);
}
// If the key could not be found, the column count will still be one as the `key` column always returns.
if (rows.length === 0 || rows[0].count <= 1 || !rows[0].get('data')) {
return callback(null, []);
}
var keys = [];
rows[0].forEach(function(name, value) {
keys.push(name);
});
callback(null, keys);
});
} else {
callback(new customError('Cassandra db only supports key patterns like pad:* when notKey is set to *:*:*', 'apierror'), null);
}
} else {
callback(new customError('Cassandra db currently only supports *:*:* as notKey', 'apierror'), null);
}
};
/**
* Sets a value for a key.
*
* @param {String} key The key to set.
* @param {String} value The value associated to this key.
* @param {Function} callback Standard callback method.
* @param {Error} callback.err Error object in case something goes wrong.
*/
exports.database.prototype.set = function (key, value, callback) {
this.doBulk([{'type': 'set', 'key': key, 'value': value}], callback);
};
/**
* Removes a key and it's value from the column family.
*
* @param {String} key The key to remove.
* @param {Function} callback Standard callback method.
* @param {Error} callback.err Error object in case something goes wrong.
*/
exports.database.prototype.remove = function (key, callback) {
this.doBulk([{'type': 'remove', 'key': key}], callback);
};
/**
* Performs multiple operations in one action. Note that these are *NOT* atomic and any order is not guaranteed.
*
* @param {Object[]} bulk The set of operations that should be performed.
* @param {Function} callback Standard callback method.
* @param {Error} callback.err Error object in case something goes wrong.
*/
exports.database.prototype.doBulk = function (bulk, callback) {
var self = this;
var query = 'BEGIN BATCH USING CONSISTENCY ONE \n';
var parameters = [];
bulk.forEach(function(operation) {
var matches = /^([^:]+):([^:]+)$/.exec(operation.key);
if (operation.type === 'set') {
query += 'UPDATE ? SET ? = ? WHERE ? = ?; \n';
parameters.push(self.settings.cfName);
parameters.push('data');
parameters.push(operation.value);
parameters.push('key');
parameters.push(operation.key);
if (matches) {
query += 'UPDATE ? SET ? = 1 WHERE ? = ?; \n';
parameters.push(self.settings.cfName);
parameters.push(matches[0]);
parameters.push('key');
parameters.push('ueberdb:keys:' + matches[1]);
}
} else if (operation.type === 'remove') {
query += 'DELETE FROM ? WHERE ? = ?; \n';
parameters.push(self.settings.cfName);
parameters.push('key');
parameters.push(operation.key);
if (matches) {
query += 'DELETE ? FROM ? WHERE ? = ?; \n';
parameters.push(matches[0]);
parameters.push(self.settings.cfName);
parameters.push('key');
parameters.push('ueberdb:keys:' + matches[1]);
}
}
});
query += 'APPLY BATCH;';
self.pool.cql(query, parameters, callback);
};
/**
* Closes the Cassandra connection.
*
* @param {Function} callback Standard callback method.
* @param {Error} callback.err Error object in case something goes wrong.
*/
exports.database.prototype.close = function(callback) {
var self = this;
self.pool.on('close', callback);
self.pool.close();
};