forked from Incroud/cassanova
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
360 lines (301 loc) · 10.9 KB
/
index.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
var _ = require('lodash'),
colors = require('colors'),
Query = require('./lib/query'),
Model = require('./lib/model'),
Schema = require("./lib/schema"),
Table = require("./lib/table"),
EventEmitter = require('events').EventEmitter,
util = require('util'),
driver = require('cassandra-driver'),
noop = function(){};
/**
* Cassanova. An object modeler for Cassandra CQL built upon the node-cassandra-cql driver.
*/
function Cassanova(){
this.tables = {};
this.models = {};
this.schemas = {};
this.client = null;
this.options = null;
EventEmitter.call(this);
}
//Used to bubble events out of the driver.
util.inherits(Cassanova, EventEmitter);
/**
* Creates a client for models.
* @return {client} A driver client.
*/
/**
* A pass-through to the driver to connect to the pool.
* @param {Object} options Configureation options for the driver
* @return {Client} The newly created client.
*/
Cassanova.prototype.createClient = function(options){
var authProvider,
port,
host,
hosts,
len,
i;
//Lets parse the hosts code into the new driver structure.
//Let's attempt to determine the port from the hosts
if(options.hosts){
options.contactPoints = [];
hosts = options.hosts;
len = hosts.length;
for(i=0; i<len; i++){
host = hosts[i].split(":");
if(!port && host[1]){
port = host[1];
}
options.contactPoints.push(host[0]);
}
if(port && !options.port){
console.warn("DEPRECATION: ".bold.cyan, "Use the port config option, instead of host:port.".cyan);
options.protocolOptions = { port:port };
}
delete options.hosts;
}
if(options.port){
options.protocolOptions = { port:options.port };
delete options.port;
}
if(options.username && options.password){
authProvider = new driver.auth.PlainTextAuthProvider(options.username, options.password);
options.authProvider = authProvider;
delete options.username;
delete options.password;
}
if(!options || !options.contactPoints){
throw new Error("Creating a client requires hosts information when being created.");
}
if(!options || !options.protocolOptions.port){
throw new Error("Creating a client requires port information when being created.");
}
if(!options.keyspace){
cassanova.emit('log', 'warn', "keyspace has not been defined in the config.");
}
this.options = options;
Query.skipSchemaValidation = options.skipSchemaValidation || false;
this.client = new driver.Client(options);
this.client.on('log', function(level, message) {
cassanova.emit('log', level, Array.prototype.slice.call(arguments).slice(1).join(" : "));
});
this.client.on('connectionFailed', function() {
cassanova.emit('connectionFailed');
});
this.client.on('connectionAvailable', function() {
cassanova.emit('connectionAvailable');
});
return this.client;
};
/**
* A pass-through to the driver to determine the connected state.
* @return {Boolean} Whether the client is connected or not.
*/
Cassanova.prototype.isConnected = function(){
if(!this.client){
return false;
}
return this.client.connected;
};
/**
* Connects to the pool with options supported by the driver. It will not attempt to connect if it's already connected, but return a success.
* @param {Object} options Configuration for the connection.
* @param {Function} callback Called upon initialization.
*/
Cassanova.prototype.connect = function(options, callback){
if (arguments.length < 2){
callback = _.isFunction(options) ? options : noop;
options = {};
}
if(!this.client){
this.client = this.createClient(options);
}
if(this.isConnected()){
cassanova.emit('log', "info", "Client is already connected.");
callback(null, true);
return;
}
this.client.connect(callback);
};
/**
* A pass-through to the driver to shut down client.
*/
Cassanova.prototype.disconnect = function(callback){
if(!this.client){
return callback(new Error("No client to disconnect."), null);
}
if(!this.isConnected()){
return callback(null, true);
}
this.client.shutdown(callback);
};
/**
* Creates/Retrieves a schema based on object.
*/
Cassanova.prototype.Schema = function(obj){
return new Schema(obj);
};
/**
* Returns the Schema types to construct a schema.
*/
Cassanova.prototype.SchemaType = Schema.Type;
/**
* Creates a new table object from a schema. Once created, they cannot be modified.
* @param {String} name The name of the table. This must match the actual table name in Cassandra.
* @param {Schema} schema The schema of the table.
* @return {Table} Returns the newly created table.
*/
Cassanova.prototype.Table = function(name, schema){
var table_obj = this.tables[name];
if(table_obj){
if(!schema){
return table_obj;
}else if(table_obj.schema !== schema){
throw new Error("Attempting to overwrite the schema for table : " + name);
}
}
table_obj = new Table(name, schema, this.client);
this.tables[name] = table_obj;
return table_obj;
};
/**
* Creates/Retrieves a model from a name/schema. If it exists, the schemas are compared (if require). If they are different,
* an error is throw as to not overwrite a model. If the schema is the same or not defined, the model is returned.
* @param {String} name The name of the model to create or retrieve.
* @param {Schema or Object} schema Used in model creation only, defines the schema for the model.
* @return {Model} Returns the existing or newly created model.
*/
Cassanova.prototype.Model = function (name, table){
var _name = name,
_table = table,
_model = _name ? this.models[_name] : null;
if(!_name || typeof _name !== "string"){
throw new Error("Attempted to create a model with an invalid name.");
}
if(!_model){
if(!_table || !(_table instanceof Table)){
throw new Error("Attempted to retrieve a model that doesn't exist or create a model with an invalid table.");
}
_model = this.models[_name] = Model.create(_name, _table, this.client, this);
this.schemas[_table.name] = _table.schema;
}else{
if(_table !== undefined && _model.table !== _table){
throw new Error("Attempting to overwrite a model with a different table : " + _name);
}
}
return _model;
};
Cassanova.prototype.Query = function(){
return new Query();
};
Cassanova.prototype.cql = function(query, options, callback){
if (arguments.length < 3){
callback = _.isFunction(options) ? options : noop;
options = {};
}
options = (!_.isObject(options)) ? {} : options;
options.consistency = options.consistency || this.consistencies.default;
this.client.execute(query, null, options, function(err, result){
if(!err){
result = Query.utils.scrubCollectionData(result.rows);
}
callback(err, result);
});
};
Cassanova.prototype.execute = function(query, options, callback){
if (arguments.length < 3){
callback = _.isFunction(options) ? options : noop;
options = {};
}
options = (!_.isObject(options)) ? {} : options;
options.consistency = options.consistency || this.consistencies.default;
this.client.execute(query.toString(), null, options, function(err, result){
if(!err){
result = Query.utils.scrubCollectionData(result.rows);
}
callback(err, result);
});
};
Cassanova.prototype.executeAsPrepared = function(query, options, callback){
if (arguments.length < 3){
callback = _.isFunction(options) ? options : noop;
options = {};
}
options = (!_.isObject(options)) ? {} : options;
options.prepare = true;
options.consistency = options.consistency || this.consistencies.default;
this.client.execute(query.toString(), null, options, function(err, result){
if(!err){
result = Query.utils.scrubCollectionData(result.rows);
}
callback(err, result);
});
};
Cassanova.prototype.executeBatch = function(queries, options, callback){
var queryBatch = [],
len = queries.length,
query,
i;
if (arguments.length < 3){
callback = _.isFunction(options) ? options : noop;
options = {};
}
options = (!_.isObject(options)) ? {} : options;
options.consistency = (options && options.consistency) || this.consistencies.default;
for(i=0; i<len; i++){
query = queries[i];
queryBatch.push(query.toString());
}
this.client.batch(queryBatch, options, function(err, result){
if(!err){
result = Query.utils.scrubCollectionData(result.rows);
}
callback(err, result);
});
};
Cassanova.prototype.executeEachRow = function(query, options, rowCallback, endCallback){
if (arguments.length < 4){
endCallback = _.isFunction(rowCallback) ? rowCallback : noop;
rowCallback = _.isFunction(options) ? options : noop;
options = {};
}
options = (!_.isObject(options)) ? {} : options;
options.consistency = options.consistency || this.consistencies.default;
this.client.eachRow(query.toString(), null, options, rowCallback, endCallback);
};
Cassanova.prototype.executeStreamField = function(query, options, rowCallback, endCallback){
console.warn("DEPRECATION: ".bold.cyan, "executeStreamField has been deprecated. The method is no longer available in the driver. The current implementation is identical to executeEachRow.".cyan);
if (arguments.length < 4){
endCallback = _.isFunction(rowCallback) ? rowCallback : noop;
rowCallback = _.isFunction(options) ? options : noop;
options = {};
}
options = (!_.isObject(options)) ? {} : options;
options.consistency = options.consistency || this.consistencies.default;
this.client.eachRow(query.toString(), null, options, rowCallback, endCallback);
};
Cassanova.prototype.executeStream = function(query, options, callback){
var consistency;
if (arguments.length < 3){
callback = _.isFunction(options) ? options : noop;
options = {};
}
options = (!_.isObject(options)) ? {} : options;
options.consistency = options.consistency || this.consistencies.default;
return this.client.stream(query.toString(), null, options)
.on('end', function(){
if(callback){
callback(null, true);
}
})
.on('error', function(err){
if(callback){
callback(err, false);
}
});
};
Cassanova.prototype.consistencies = Query.consistencies;
Cassanova.prototype.Cassanova = Cassanova;
module.exports = cassanova = new Cassanova();