-
Notifications
You must be signed in to change notification settings - Fork 23
/
adapter.js
506 lines (452 loc) · 16.5 KB
/
adapter.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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
"use strict";
/**
* Module Dependencies
*/
var ensureNewline = process.env.NODE_ENV !== 'production';
var log = require('debug-logger').config({ ensureNewline: ensureNewline })('sails-orientdb:adapter'),
Connection = require('./connection'),
utils = require('./utils');
/**
* sails-orientdb
*
* Most of the methods below are optional.
*
* If you don't need / can't get to every method, just implement what you have
* time for. The other methods will only fail if you try to call them!
*
* For many adapters, this file is all you need. For very complex adapters, you
* may need more flexiblity. In any case, it's probably a good idea to start
* with one file and refactor only if necessary. If you do go that route, it's
* conventional in Node to create a `./lib` directory for your private
* submodules and load them at the top of the file with other dependencies. e.g.
* var update = `require('./lib/update')`;
*/
module.exports = (function() {
// You'll want to maintain a reference to each connection
// that gets registered with this adapter.
//
// Keep track of all the connections used by the app
var connections = {};
// You may also want to store additional, private data
// per-connection (esp. if your data store uses persistent
// connections).
//
// Keep in mind that models can be configured to use different databases
// within the same app, at the same time.
//
// i.e. if you're writing a MariaDB adapter, you should be aware that one
// model might be configured as `host="localhost"` and another might be
// using
// `host="foo.com"` at the same time. Same thing goes for user, database,
// password, or any other config.
//
// You don't have to support this feature right off the bat in your
// adapter, but it ought to get done eventually.
//
// Sounds annoying to deal with...
// ...but it's not bad. In each method, acquire a connection using the config
// for the current model (looking it up from `_modelReferences`), establish
// a connection, then tear it down before calling your method's callback.
// Finally, as an optimization, you might use a db pool for each distinct
// connection configuration, partioning pools for each separate configuration
// for your adapter (i.e. worst case scenario is a pool for each model, best case
// scenario is one single single pool.) For many databases, any change to
// host OR database OR user OR password = separate pool.
// var _dbPools = {};
var adapter = {
identity: 'sails-orientdb',
// Set to true if this adapter supports (or requires) things like data
// types, validations, keys, etc.
// If true, the schema for models using this adapter will be
// automatically synced when the server starts.
// Not terribly relevant if your data store is not SQL/schemaful.
//
// If setting syncable, you should consider the migrate option,
// which allows you to set how the sync will be performed.
// It can be overridden globally in an app (config/adapters.js)
// and on a per-model basis.
//
// IMPORTANT:
// `migrate` is not a production data migration solution!
// In production, always use `migrate: safe`
//
// drop => Drop schema and data, then recreate it
// alter => Drop/add columns as necessary.
// safe => Don't change anything (good for production DBs)
//
syncable : true,
// Which type of primary key is used by default
pkFormat : 'string',
// Default configuration for connections
defaults : {
// Connection Configuration
database : 'waterline',
host : 'localhost',
port : 2424,
schema : true,
// Additional options
options: {
// DB/Oriento Options
//
// database type: graph | document
databaseType : 'graph',
//
// storage type: memory | plocal
storage : 'plocal',
//
// transport: binary | rest. Currently only binary is supported: https://github.com/codemix/oriento/issues/44
transport : 'binary',
//
// connection pool: by default oriento uses one socket per server, but it is also possible to use a connection
// pool by adding a pool object that will be sent to Oriento, e.g.: { max: 10 }
pool: null,
//
// Sets the oriento logger for error, log and debug. e.g.: { debug: console.log.bind(console) }
orientoLogger : {},
// Enable JTW Token in orientjs. http://orientdb.com/docs/2.1/Network-Binary-Protocol.html#token
useToken : false,
//
// database username, by default uses connection username set on config
// databaseUser : null,
//
// database password, by default uses connection password set on config
// databasePassword : null,
// Useful in REST APIs
//
// If `id` is URI encoded, decode it with `decodeURIComponent()` (useful when `id` comes from an URL)
decodeURIComponent : true,
//
// Replaces circular references with `id` after populate operations (useful when results will be JSONfied)
removeCircularReferences : false,
// migrations
//
// Drop tables without deleting edges/vertexes hence not ensuring graph consistency
// Will speed up drop operations. Only works with migration: 'alter' or 'drop'
unsafeDrop : false,
// other
//
// Turn parameterized queries on
parameterized : true,
//
// Waterline only allows populating 1 level below. fetchPlanLevel allows to
// to populate further levels below (experimental)
fetchPlanLevel : 1
}
},
/**
*
* This method runs when a model is initially registered at
* server-start-time. This is the only required method.
*
* @param {[type]} connection [description]
* @param {[type]} collection [description]
* @param {Function} cb [description]
* @return {[type]} [description]
*/
registerConnection : function(connection, collections, cb) {
log.debug('registerConnection: db=' + connection.database, ', connection=' + connection.identity);
if (!connection.identity)
return cb(new Error('Connection is missing an identity.'));
if (connections[connection.identity])
return cb(new Error('Connection is already registered.'));
// Add in logic here to initialize connection
// e.g. connections[connection.identity] = new Database(connection,
// collections);
connections[connection.identity] = new Connection(connection, collections, cb);
},
/**
* Teardown a Connection
*
* Fired when a model is unregistered, typically when the server is
* killed. Useful for tearing-down remaining open connections, etc.
*
* @param {Function} cb [description]
* @return {[type]} [description]
*/
teardown : function(conn, cb) {
log.debug('teardown:', conn);
/* istanbul ignore if: standard waterline-adapter code */
if ( typeof conn == 'function') {
cb = conn;
conn = null;
}
/* istanbul ignore if: standard waterline-adapter code */
if (!conn) {
connections = {};
return cb();
}
/* istanbul ignore if: standard waterline-adapter code */
if (!connections[conn])
return cb();
delete connections[conn];
cb();
},
/**
* Describe
*
* Return the Schema of a collection after first creating the collection
* and indexes if they don't exist.
*
* @param {String} connection
* @param {String} collection
* @param {Function} callback
*/
describe : function(connection, collection, cb) {
log.debug('describe:', collection);
// Add in logic here to describe a collection (e.g. DESCRIBE TABLE
// logic)
connections[connection].describe(collection, cb);
},
/**
* Define
*
* Create a new Orient Collection and set Index Values
* Add in logic here to create a collection (e.g. CREATE TABLE
* logic)
*
* @param {String} connection
* @param {String} collection
* @param {Object} definition
* @param {Function} cb
*/
define : function(connection, collection, definition, cb) {
log.debug('define:', collection);
// Create the collection and indexes
connections[connection].createCollection(collection, definition, cb);
},
/**
* Drop
*
* Drop a Collection
*
* @param {String} connectionName
* @param {String} collectionName
* @param {Array} relations
* @param {Function} callback
*/
drop : function(connection, collection, relations, cb) {
log.debug('drop:', collection);
// Add in logic here to delete a collection (e.g. DROP TABLE logic)
return connections[connection].drop(collection, relations, cb);
},
/**
* AddAttribute
*
* Add a property to a class
*
* @param {String} connection
* @param {String} collection
* @param {String} attrName
* @param {Object} attrDef
* @param {Function} cb
*/
addAttribute: function(connection, collection, attrName, attrDef, cb) {
log.debug('addAttribute: ' + collection + ', attrName:', attrName);
return connections[connection].addAttribute(collection, attrName, attrDef, cb);
},
/**
* Find
*
* Find all matching documents in a colletion.
*
* REQUIRED method if users expect to call Model.find(),
* Model.findOne(), or related.
*
* You should implement this method to respond with an array of
* instances. Waterline core will take care of supporting all the other
* different find methods/usages.
*
*/
find : function(connection, collection, options, cb) {
return connections[connection].find(collection, options, function(err, res){
if (err) { return cb(err); }
res.forEach(function(record){ utils.cleanOrientAttributes(record /*, TODO: add schema */); });
cb(null, res);
});
},
create : function(connection, collection, values, cb) {
return connections[connection].create(collection, values, cb);
},
update : function(connection, collection, options, values, cb) {
// TODO: On "1:1 update nested associations() when association have primary keys should update association values"
// test `values` includes an extraneous field `inspect`, this is a
// temporary workaround until we figure where `inspect` is coming from
if(values.inspect && typeof values.inspect === 'function') { delete values.inspect; }
return connections[connection].update(collection, options, values, function(err, res){
if (err) { return cb(err); }
res.forEach(function(record){ utils.cleanOrientAttributes(record /*, TODO: add schema */); });
cb(null, res);
});
},
destroy : function(connection, collection, options, cb) {
return connections[connection].destroy(collection, options, cb);
},
/**
* Join
*
* Peforms a join between 2-3 orientdb collections when Waterline core
* needs to satisfy a `.populate()`.
*
* @param {[type]} connection [description]
* @param {[type]} collection [description]
* @param {[type]} options [description]
* @param {Function} cb [description]
* @return {[type]} [description]
*/
join : function(connection, collection, options, cb) {
return connections[connection].join(collection, options, cb);
},
/*
* Custom methods
*
* Custom methods defined here will be available on all models which
* are hooked up to this adapter
*
* e.g.: foo: function (collectionName, options, cb) {
* return cb(null,"ok"); }, bar: function
* (collectionName, options, cb) { if (!options.jello) return
* cb("Failure!"); else return cb(); destroy: function (connection,
* collection, options, values, cb) { return cb(); } // So if you have three
* models: // Tiger, Sparrow, and User // 2 of which (Tiger and Sparrow)
* implement this custom adapter, // then you'll be able to access: // //
* Tiger.foo(...) // Tiger.bar(...) // Sparrow.foo(...) // Sparrow.bar(...) //
* Example success usage: // // (notice how the first argument goes away:)
* Tiger.foo({}, function (err, result) { if (err) return
* console.error(err); else console.log(result); // outputs: ok }); //
* Example error usage: // // (notice how the first argument goes away:)
* Sparrow.bar({test: 'yes'}, function (err, result){ if (err)
* console.error(err); else console.log(result); // outputs: Failure! })
*/
/**
* Create Edge
*
* Creates edge between two vertices pointed by from and to
*
* @param {Object} connection
* @param {Object} collection
* @param {Object} from
* @param {Object} to
* @param {Object} options
* @param {Object} cb
*/
createEdge : function(connection, collection, from, to, options, cb) {
return connections[connection].createEdge(from, to, options, cb);
},
/**
* Delete Edges
*
* Removes edges between two vertices pointed by from and to
*
* @param {Object} connection
* @param {Object} collection
* @param {Object} from
* @param {Object} to
* @param {Object} options
* @param {Object} cb
*/
deleteEdges : function(connection, collection, from, to, options, cb) {
return connections[connection].deleteEdges(from, to, options, cb);
},
/**
* Query
*
* Runs a SQL query against the database using Oriento's query method
* Will attempt to convert @rid's into ids.
*
* @param {Object} connection
* @param {Object} collection
* @param {String} query
* @param {String} options
* @param {Object} cb
*/
query : function(connection, collection, query, options, cb) {
return connections[connection].query(query, options, cb);
},
/**
* Native
*
* Give access to a native orientd collection object for running custom
* queries.
*
* @param {String} connection
* @param {String} collection
* @param {Function} callback
*/
native: function(connection, collection, cb) {
return connections[connection].native(collection, cb);
},
/**
* Get DB
*
* Returns the native OrientDB Object
*
* @param {Object} connection
* @param {Object} collection
* @param {Object} cb
*/
getDB : function(connection, collection, cb) {
return connections[connection].getDB(cb);
},
/**
* Get Server
*
* Returns the native Oriento connection object
*
* @param {Object} connection
* @param {Object} collection
* @param {Object} cb
*/
getServer : function(connection, collection, cb) {
return connections[connection].getServer(cb);
},
/**
* Remove Circular References
*
* Replaces circular references with `id` when one is available, otherwise it replaces the object
* with string '[Circular]'
*
* @param {Object} connection
* @param {Object} collection
* @param {Object} object
* @param {Object} cb
*/
removeCircularReferences : function(connection, collection, object, cb) {
utils.removeCircularReferences(object);
if (cb) {
cb(object);
}
return object;
},
/**
* Run Function
*
* Run an OrientDB server side function
*
* @param {Object} connection
* @param {Object} collection
* @param {String} functionName - the name of the server function
* @param {...Object} object - will be passed to server function
*/
runFunction : function(connection, collection, functionName) {
var args = Array.prototype.slice.call(arguments, 3);
return connections[connection].runFunction(functionName, args);
},
/**
* Increment
*
* Increments a field by a given amount
*
* @param {Object} connection
* @param {Object} collection
* @param {Object} criteria
* @param {String} field
* @param {Number} amount
* @param {Function} cb
*/
increment : function(connection, collection, criteria, field, amount, cb) {
return connections[connection].increment(collection, criteria, field, amount, cb);
}
};
// Expose adapter definition
return adapter;
})();