1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | const ModelBuilder = require('./model-builder.js').ModelBuilder;
|
14 | const ModelDefinition = require('./model-definition.js');
|
15 | const RelationDefinition = require('./relation-definition.js');
|
16 | const OberserverMixin = require('./observer');
|
17 | const jutil = require('./jutil');
|
18 | const utils = require('./utils');
|
19 | const ModelBaseClass = require('./model.js');
|
20 | const DataAccessObject = require('./dao.js');
|
21 | const defineScope = require('./scope.js').defineScope;
|
22 | const EventEmitter = require('events').EventEmitter;
|
23 | const util = require('util');
|
24 | const assert = require('assert');
|
25 | const async = require('async');
|
26 | const traverse = require('traverse');
|
27 | const g = require('strong-globalize')();
|
28 | const juggler = require('..');
|
29 | const deprecated = require('depd')('loopback-datasource-juggler');
|
30 | const Transaction = require('loopback-connector').Transaction;
|
31 | const pascalCase = require('change-case').pascalCase;
|
32 | const camelCase = require('change-case').camelCase;
|
33 |
|
34 | if (process.env.DEBUG === 'loopback') {
|
35 |
|
36 | process.env.DEBUG = 'loopback:*';
|
37 | }
|
38 | const debug = require('debug')('loopback:datasource');
|
39 |
|
40 |
|
41 |
|
42 |
|
43 | exports.DataSource = DataSource;
|
44 |
|
45 |
|
46 |
|
47 |
|
48 | const slice = Array.prototype.slice;
|
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 | function DataSource(name, settings, modelBuilder) {
|
111 | if (!(this instanceof DataSource)) {
|
112 | return new DataSource(name, settings);
|
113 | }
|
114 |
|
115 |
|
116 | if (typeof name === 'object' && settings === undefined) {
|
117 | settings = name;
|
118 | name = undefined;
|
119 | }
|
120 |
|
121 |
|
122 | if (typeof name === 'string' && name.indexOf('://') !== -1) {
|
123 | name = utils.parseSettings(name);
|
124 | }
|
125 |
|
126 |
|
127 | if (typeof settings === 'string' && settings.indexOf('://') !== -1) {
|
128 | settings = utils.parseSettings(settings);
|
129 | }
|
130 |
|
131 |
|
132 |
|
133 | if (settings) settings = Object.assign({}, settings);
|
134 |
|
135 | if (typeof name === 'object') name = Object.assign({}, name);
|
136 |
|
137 | this.modelBuilder = modelBuilder || new ModelBuilder();
|
138 | this.models = this.modelBuilder.models;
|
139 | this.definitions = this.modelBuilder.definitions;
|
140 | this.juggler = juggler;
|
141 | this._queuedInvocations = 0;
|
142 |
|
143 |
|
144 |
|
145 | this._operations = {};
|
146 |
|
147 | this.setup(name, settings);
|
148 |
|
149 | this._setupConnector();
|
150 |
|
151 |
|
152 | const connector = this.connector;
|
153 |
|
154 |
|
155 | const dao = (connector && connector.DataAccessObject) || this.constructor.DataAccessObject;
|
156 | this.DataAccessObject = function() {
|
157 | };
|
158 |
|
159 |
|
160 | Object.keys(dao).forEach(function(name) {
|
161 | const fn = dao[name];
|
162 | this.DataAccessObject[name] = fn;
|
163 |
|
164 | if (typeof fn === 'function') {
|
165 | this.defineOperation(name, {
|
166 | accepts: fn.accepts,
|
167 | 'returns': fn.returns,
|
168 | http: fn.http,
|
169 | remoteEnabled: fn.shared ? true : false,
|
170 | scope: this.DataAccessObject,
|
171 | fnName: name,
|
172 | });
|
173 | }
|
174 | }.bind(this));
|
175 |
|
176 |
|
177 | Object.keys(dao.prototype || []).forEach(function(name) {
|
178 | const fn = dao.prototype[name];
|
179 | this.DataAccessObject.prototype[name] = fn;
|
180 | if (typeof fn === 'function') {
|
181 | this.defineOperation(name, {
|
182 | prototype: true,
|
183 | accepts: fn.accepts,
|
184 | 'returns': fn.returns,
|
185 | http: fn.http,
|
186 | remoteEnabled: fn.shared ? true : false,
|
187 | scope: this.DataAccessObject.prototype,
|
188 | fnName: name,
|
189 | });
|
190 | }
|
191 | }.bind(this));
|
192 | }
|
193 |
|
194 | util.inherits(DataSource, EventEmitter);
|
195 |
|
196 |
|
197 | DataSource.DataAccessObject = DataAccessObject;
|
198 |
|
199 |
|
200 |
|
201 |
|
202 | DataSource.DEFAULT_MAX_OFFLINE_REQUESTS = 16;
|
203 |
|
204 |
|
205 |
|
206 |
|
207 |
|
208 | DataSource.prototype._setupConnector = function() {
|
209 | this.connector = this.connector || this.adapter;
|
210 | this.adapter = this.connector;
|
211 | if (this.connector) {
|
212 | if (!this.connector.dataSource) {
|
213 |
|
214 | this.connector.dataSource = this;
|
215 | }
|
216 | const dataSource = this;
|
217 |
|
218 |
|
219 | dataSource.setMaxListeners(dataSource.getMaxOfflineRequests());
|
220 |
|
221 | this.connector.log = function(query, start) {
|
222 | dataSource.log(query, start);
|
223 | };
|
224 |
|
225 | this.connector.logger = function(query) {
|
226 | const t1 = Date.now();
|
227 | const log = this.log;
|
228 | return function(q) {
|
229 | log(q || query, t1);
|
230 | };
|
231 | };
|
232 |
|
233 | jutil.mixin(this.connector, OberserverMixin);
|
234 | }
|
235 | };
|
236 |
|
237 |
|
238 | function connectorModuleNames(name) {
|
239 | const names = [];
|
240 | if (!name.match(/^\//)) {
|
241 | names.push('./connectors/' + name);
|
242 | if (name.indexOf('loopback-connector-') !== 0) {
|
243 | names.push('loopback-connector-' + name);
|
244 | }
|
245 | }
|
246 |
|
247 | if (['mongodb', 'oracle', 'mysql', 'postgresql', 'mssql', 'rest', 'soap', 'db2', 'cloudant']
|
248 | .indexOf(name) === -1) {
|
249 | names.push(name);
|
250 | }
|
251 | return names;
|
252 | }
|
253 |
|
254 |
|
255 | function tryModules(names, loader) {
|
256 | let mod;
|
257 | loader = loader || require;
|
258 | for (let m = 0; m < names.length; m++) {
|
259 | try {
|
260 | mod = loader(names[m]);
|
261 | } catch (e) {
|
262 | const notFound = e.code === 'MODULE_NOT_FOUND' &&
|
263 | e.message && e.message.indexOf(names[m]) > 0;
|
264 |
|
265 | if (notFound) {
|
266 | debug('Module %s not found, will try another candidate.', names[m]);
|
267 | continue;
|
268 | }
|
269 |
|
270 | debug('Cannot load connector %s: %s', names[m], e.stack || e);
|
271 | throw e;
|
272 | }
|
273 | if (mod) {
|
274 | break;
|
275 | }
|
276 | }
|
277 | return mod;
|
278 | }
|
279 |
|
280 |
|
281 |
|
282 |
|
283 |
|
284 |
|
285 |
|
286 | DataSource._resolveConnector = function(name, loader) {
|
287 | const names = connectorModuleNames(name);
|
288 | const connector = tryModules(names, loader);
|
289 | let error = null;
|
290 | if (!connector) {
|
291 | error = g.f('\nWARNING: {{LoopBack}} connector "%s" is not installed ' +
|
292 | 'as any of the following modules:\n\n %s\n\nTo fix, run:\n\n {{npm install %s --save}}\n',
|
293 | name, names.join('\n'), names[names.length - 1]);
|
294 | }
|
295 | return {
|
296 | connector: connector,
|
297 | error: error,
|
298 | };
|
299 | };
|
300 |
|
301 |
|
302 |
|
303 |
|
304 |
|
305 |
|
306 |
|
307 |
|
308 |
|
309 | DataSource.prototype.connect = function(callback) {
|
310 | callback = callback || utils.createPromiseCallback();
|
311 | const self = this;
|
312 | if (this.connected) {
|
313 |
|
314 | process.nextTick(callback);
|
315 | return callback.promise;
|
316 | }
|
317 | if (typeof this.connector.connect !== 'function') {
|
318 |
|
319 |
|
320 | self.connected = true;
|
321 | self.connecting = false;
|
322 | process.nextTick(function() {
|
323 | self.emit('connected');
|
324 | callback();
|
325 | });
|
326 | return callback.promise;
|
327 | }
|
328 |
|
329 |
|
330 | this.pendingConnectCallbacks = this.pendingConnectCallbacks || [];
|
331 | this.pendingConnectCallbacks.push(callback);
|
332 |
|
333 |
|
334 | if (this.connecting) return callback.promise;
|
335 | this.connector.connect(function(err, result) {
|
336 | self.connecting = false;
|
337 | if (!err) self.connected = true;
|
338 | const cbs = self.pendingConnectCallbacks;
|
339 | self.pendingConnectCallbacks = [];
|
340 | if (!err) {
|
341 | self.emit('connected');
|
342 | } else {
|
343 | self.emit('error', err);
|
344 | }
|
345 |
|
346 | async.each(cbs, function(cb, done) {
|
347 | try {
|
348 | cb(err);
|
349 | } catch (e) {
|
350 |
|
351 | debug('Uncaught error raised by connect callback function: ', e);
|
352 | } finally {
|
353 | done();
|
354 | }
|
355 | }, function(err) {
|
356 | if (err) throw err;
|
357 | });
|
358 | });
|
359 |
|
360 |
|
361 |
|
362 |
|
363 | this.connecting = true;
|
364 | return callback.promise;
|
365 | };
|
366 |
|
367 |
|
368 |
|
369 |
|
370 |
|
371 |
|
372 |
|
373 |
|
374 |
|
375 |
|
376 |
|
377 |
|
378 |
|
379 |
|
380 |
|
381 |
|
382 | DataSource.prototype.setup = function(dsName, settings) {
|
383 | const dataSource = this;
|
384 | let connector;
|
385 |
|
386 |
|
387 | if (dsName && typeof dsName === 'object') {
|
388 | if (settings === undefined) {
|
389 |
|
390 | settings = dsName;
|
391 | dsName = undefined;
|
392 | } else {
|
393 |
|
394 | connector = dsName;
|
395 | dsName = undefined;
|
396 | }
|
397 | }
|
398 |
|
399 | if (typeof dsName !== 'string') {
|
400 | dsName = undefined;
|
401 | }
|
402 |
|
403 | if (typeof settings === 'object') {
|
404 | if (settings.initialize) {
|
405 |
|
406 | connector = settings;
|
407 |
|
408 | settings = undefined;
|
409 | } else if (settings.connector) {
|
410 |
|
411 | connector = settings.connector;
|
412 | } else if (settings.adapter) {
|
413 |
|
414 | connector = settings.adapter;
|
415 | }
|
416 | }
|
417 |
|
418 |
|
419 | this.settings = settings || {};
|
420 |
|
421 | this.settings.debug = this.settings.debug || debug.enabled;
|
422 |
|
423 | if (this.settings.debug) {
|
424 | debug('Settings: %j', this.settings);
|
425 | }
|
426 |
|
427 | if (typeof settings === 'object' && typeof settings.name === 'string' &&
|
428 | typeof dsName === 'string' && dsName !== settings.name) {
|
429 |
|
430 |
|
431 | console.warn(
|
432 | 'A datasource is created with name %j, which is different from the name in settings (%j). ' +
|
433 | 'Please adjust your configuration to ensure these names match.',
|
434 | dsName, settings.name,
|
435 | );
|
436 | }
|
437 |
|
438 |
|
439 | this.connected = false;
|
440 | this.connecting = false;
|
441 | this.initialized = false;
|
442 |
|
443 | this.name = dsName || (typeof this.settings.name === 'string' && this.settings.name);
|
444 |
|
445 | let connectorName;
|
446 | if (typeof connector === 'string') {
|
447 |
|
448 | connectorName = connector;
|
449 | connector = undefined;
|
450 | } else if ((typeof connector === 'object') && connector) {
|
451 | connectorName = connector.name;
|
452 | } else {
|
453 | connectorName = dsName;
|
454 | }
|
455 | if (!this.name) {
|
456 |
|
457 | this.name = connectorName;
|
458 | }
|
459 |
|
460 | if ((!connector) && connectorName) {
|
461 |
|
462 | const result = DataSource._resolveConnector(connectorName);
|
463 | connector = result.connector;
|
464 | if (!connector) {
|
465 | console.error(result.error);
|
466 | this.emit('error', new Error(result.error));
|
467 | return;
|
468 | }
|
469 | }
|
470 |
|
471 | if (connector) {
|
472 | const postInit = function postInit(err, result) {
|
473 | this._setupConnector();
|
474 |
|
475 | if (!this.connector) {
|
476 | throw new Error(g.f('Connector is not defined correctly: ' +
|
477 | 'it should create `{{connector}}` member of dataSource'));
|
478 | }
|
479 | if (!err) {
|
480 | this.initialized = true;
|
481 | this.emit('initialized');
|
482 | }
|
483 | debug('Connector is initialized for dataSource %s', this.name);
|
484 |
|
485 |
|
486 | if (!this.settings.lazyConnect) {
|
487 | this.connected = (!err) && (result !== false);
|
488 | }
|
489 | if (this.connected) {
|
490 | debug('DataSource %s is now connected to %s', this.name, this.connector.name);
|
491 | this.emit('connected');
|
492 | } else if (err) {
|
493 |
|
494 |
|
495 | this.connecting = false;
|
496 | if (this._queuedInvocations) {
|
497 |
|
498 |
|
499 | debug('Connection fails: %s\nIt will be retried for the next request.', err);
|
500 | } else {
|
501 | g.error('Connection fails: %s\nIt will be retried for the next request.', err);
|
502 | this.emit('error', err);
|
503 | }
|
504 | } else {
|
505 |
|
506 | debug('DataSource %s will be connected to connector %s', this.name,
|
507 | this.connector.name);
|
508 | }
|
509 | }.bind(this);
|
510 |
|
511 | try {
|
512 | if ('function' === typeof connector.initialize) {
|
513 |
|
514 | debug('Initializing connector %s', connector.name);
|
515 | connector.initialize(this, postInit);
|
516 | } else if ('function' === typeof connector) {
|
517 |
|
518 | this.connector = new connector(this.settings);
|
519 | postInit();
|
520 | }
|
521 | } catch (err) {
|
522 | if (err.message) {
|
523 | err.message = 'Cannot initialize connector ' +
|
524 | JSON.stringify(connectorName) + ': ' +
|
525 | err.message;
|
526 | }
|
527 | throw err;
|
528 | }
|
529 | }
|
530 | };
|
531 |
|
532 | function isModelClass(cls) {
|
533 | if (!cls) {
|
534 | return false;
|
535 | }
|
536 | return cls.prototype instanceof ModelBaseClass;
|
537 | }
|
538 |
|
539 | DataSource.relationTypes = Object.keys(RelationDefinition.RelationTypes);
|
540 |
|
541 | function isModelDataSourceAttached(model) {
|
542 | return model && (!model.settings.unresolved) && (model.dataSource instanceof DataSource);
|
543 | }
|
544 |
|
545 |
|
546 |
|
547 |
|
548 |
|
549 |
|
550 |
|
551 |
|
552 |
|
553 |
|
554 |
|
555 | DataSource.prototype.defineScopes = function(modelClass, scopes) {
|
556 | if (scopes) {
|
557 | for (const s in scopes) {
|
558 | defineScope(modelClass, modelClass, s, scopes[s], {}, scopes[s].options);
|
559 | }
|
560 | }
|
561 | };
|
562 |
|
563 |
|
564 |
|
565 |
|
566 |
|
567 |
|
568 |
|
569 |
|
570 |
|
571 | DataSource.prototype.defineRelations = function(modelClass, relations) {
|
572 | const self = this;
|
573 |
|
574 |
|
575 | const deferRelationSetup = function(relationName, relation, targetModel, throughModel) {
|
576 | if (!isModelDataSourceAttached(targetModel)) {
|
577 | targetModel.once('dataAccessConfigured', function(targetModel) {
|
578 |
|
579 | if (!throughModel || isModelDataSourceAttached(throughModel)) {
|
580 |
|
581 | const params = traverse(relation).clone();
|
582 | params.as = relationName;
|
583 | params.model = targetModel;
|
584 | if (throughModel) {
|
585 | params.through = throughModel;
|
586 | }
|
587 | modelClass[relation.type].call(modelClass, relationName, params);
|
588 | }
|
589 | });
|
590 | }
|
591 |
|
592 | if (throughModel && !isModelDataSourceAttached(throughModel)) {
|
593 |
|
594 | throughModel.once('dataAccessConfigured', function(throughModel) {
|
595 | if (isModelDataSourceAttached(targetModel)) {
|
596 |
|
597 | const params = traverse(relation).clone();
|
598 | params.as = relationName;
|
599 | params.model = targetModel;
|
600 | params.through = throughModel;
|
601 | modelClass[relation.type].call(modelClass, relationName, params);
|
602 | }
|
603 | });
|
604 | }
|
605 | };
|
606 |
|
607 |
|
608 | if (relations) {
|
609 | Object.keys(relations).forEach(function(relationName) {
|
610 | let targetModel;
|
611 | const r = relations[relationName];
|
612 |
|
613 | validateRelation(relationName, r);
|
614 |
|
615 | if (r.model) {
|
616 | targetModel = isModelClass(r.model) ? r.model : self.getModel(r.model, true);
|
617 | }
|
618 |
|
619 | let throughModel = null;
|
620 | if (r.through) {
|
621 | throughModel = isModelClass(r.through) ? r.through : self.getModel(r.through, true);
|
622 | }
|
623 |
|
624 | if ((targetModel && !isModelDataSourceAttached(targetModel)) ||
|
625 | (throughModel && !isModelDataSourceAttached(throughModel))) {
|
626 |
|
627 | deferRelationSetup(relationName, r, targetModel, throughModel);
|
628 | } else {
|
629 |
|
630 | const params = traverse(r).clone();
|
631 | params.as = relationName;
|
632 | params.model = targetModel;
|
633 | if (throughModel) {
|
634 | params.through = throughModel;
|
635 | }
|
636 | modelClass[r.type].call(modelClass, relationName, params);
|
637 | }
|
638 | });
|
639 | }
|
640 | };
|
641 |
|
642 | function validateRelation(relationName, relation) {
|
643 | const rn = relationName;
|
644 | const r = relation;
|
645 | let msg, code;
|
646 |
|
647 | assert(DataSource.relationTypes.indexOf(r.type) !== -1, 'Invalid relation type: ' + r.type);
|
648 | assert(isValidRelationName(rn), 'Invalid relation name: ' + rn);
|
649 |
|
650 |
|
651 |
|
652 |
|
653 | if (!r.polymorphic && r.type === 'belongsTo' && !r.model) {
|
654 | msg = g.f('%s relation: %s requires param `model`', r.type, rn);
|
655 | code = 'BELONGS_TO_MISSING_MODEL';
|
656 | }
|
657 |
|
658 | if (r.polymorphic && r.type === 'belongsTo' && r.model) {
|
659 | msg = g.f('{{polymorphic}} %s relation: %s does not expect param `model`', r.type, rn);
|
660 | code = 'POLYMORPHIC_BELONGS_TO_MODEL';
|
661 | }
|
662 |
|
663 | if (r.polymorphic && r.type !== 'belongsTo' && !r.model) {
|
664 | msg = g.f('{{polymorphic}} %s relation: %s requires param `model`', r.type, rn);
|
665 | code = 'POLYMORPHIC_NOT_BELONGS_TO_MISSING_MODEL';
|
666 | }
|
667 |
|
668 | if (r.polymorphic && r.polymorphic.foreignKey && !r.polymorphic.discriminator) {
|
669 | msg = g.f('{{polymorphic}} %s relation: %s requires param `polymorphic.discriminator` ' +
|
670 | 'when param `polymorphic.foreignKey` is provided', r.type, rn);
|
671 | code = 'POLYMORPHIC_MISSING_DISCRIMINATOR';
|
672 | }
|
673 |
|
674 | if (r.polymorphic && r.polymorphic.discriminator && !r.polymorphic.foreignKey) {
|
675 | msg = g.f('{{polymorphic}} %s relation: %s requires param `polymorphic.foreignKey` ' +
|
676 | 'when param `polymorphic.discriminator` is provided', r.type, rn);
|
677 | code = 'POLYMORPHIC_MISSING_FOREIGN_KEY';
|
678 | }
|
679 |
|
680 | if (r.polymorphic && r.polymorphic.as && r.polymorphic.foreignKey) {
|
681 | msg = g.f('{{polymorphic}} %s relation: %s does not expect param `polymorphic.as` ' +
|
682 | 'when defing custom `foreignKey`/`discriminator` ', r.type, rn);
|
683 | code = 'POLYMORPHIC_EXTRANEOUS_AS';
|
684 | }
|
685 |
|
686 | if (r.polymorphic && r.polymorphic.selector && r.polymorphic.foreignKey) {
|
687 | msg = g.f('{{polymorphic}} %s relation: %s does not expect param `polymorphic.selector` ' +
|
688 | 'when defing custom `foreignKey`/`discriminator` ', r.type, rn);
|
689 | code = 'POLYMORPHIC_EXTRANEOUS_SELECTOR';
|
690 | }
|
691 |
|
692 | if (msg) {
|
693 | const error = new Error(msg);
|
694 | error.details = {code: code, rType: r.type, rName: rn};
|
695 | throw error;
|
696 | }
|
697 |
|
698 |
|
699 | if (r.polymorphic && r.polymorphic.as) {
|
700 | deprecated(g.f('WARNING: {{polymorphic}} %s relation: %s uses keyword `polymorphic.as` which will ' +
|
701 | 'be DEPRECATED in LoopBack.next, refer to this doc for replacement solutions ' +
|
702 | '(https://loopback.io/doc/en/lb3/Polymorphic-relations.html#deprecated-polymorphic-as)',
|
703 | r.type, rn), r.type);
|
704 | }
|
705 | }
|
706 |
|
707 | function isValidRelationName(relationName) {
|
708 | const invalidRelationNames = ['trigger'];
|
709 | return invalidRelationNames.indexOf(relationName) === -1;
|
710 | }
|
711 |
|
712 |
|
713 |
|
714 |
|
715 |
|
716 |
|
717 |
|
718 |
|
719 | DataSource.prototype.setupDataAccess = function(modelClass, settings) {
|
720 | if (this.connector) {
|
721 |
|
722 | const idName = modelClass.definition.idName();
|
723 | const idProp = modelClass.definition.rawProperties[idName];
|
724 | if (idProp && idProp.generated && idProp.useDefaultIdType !== false && this.connector.getDefaultIdType) {
|
725 |
|
726 | const idType = this.connector.getDefaultIdType() || String;
|
727 | idProp.type = idType;
|
728 | modelClass.definition.rawProperties[idName].type = idType;
|
729 | modelClass.definition.properties[idName].type = idType;
|
730 | }
|
731 | if (this.connector.define) {
|
732 |
|
733 | this.connector.define({
|
734 | model: modelClass,
|
735 | properties: modelClass.definition.properties,
|
736 | settings: settings,
|
737 | });
|
738 | }
|
739 | }
|
740 |
|
741 |
|
742 | this.mixin(modelClass);
|
743 |
|
744 |
|
745 | const relations = settings.relationships || settings.relations;
|
746 | this.defineRelations(modelClass, relations);
|
747 |
|
748 |
|
749 |
|
750 | modelClass.emit('dataAccessConfigured', modelClass);
|
751 |
|
752 |
|
753 | const scopes = settings.scopes || {};
|
754 | this.defineScopes(modelClass, scopes);
|
755 | };
|
756 |
|
757 |
|
758 |
|
759 |
|
760 |
|
761 |
|
762 |
|
763 |
|
764 |
|
765 |
|
766 |
|
767 |
|
768 |
|
769 |
|
770 |
|
771 |
|
772 |
|
773 |
|
774 |
|
775 |
|
776 |
|
777 |
|
778 |
|
779 |
|
780 |
|
781 |
|
782 |
|
783 |
|
784 |
|
785 |
|
786 |
|
787 |
|
788 |
|
789 |
|
790 |
|
791 |
|
792 |
|
793 |
|
794 |
|
795 |
|
796 |
|
797 |
|
798 |
|
799 |
|
800 |
|
801 |
|
802 |
|
803 |
|
804 |
|
805 |
|
806 | DataSource.prototype.createModel =
|
807 | DataSource.prototype.define = function defineClass(className, properties, settings) {
|
808 | const args = slice.call(arguments);
|
809 |
|
810 | if (!className) {
|
811 | throw new Error(g.f('Class name required'));
|
812 | }
|
813 | if (args.length === 1) {
|
814 | properties = {};
|
815 | args.push(properties);
|
816 | }
|
817 | if (args.length === 2) {
|
818 | settings = {};
|
819 | args.push(settings);
|
820 | }
|
821 |
|
822 | properties = properties || {};
|
823 | settings = settings || {};
|
824 |
|
825 | if (this.isRelational()) {
|
826 |
|
827 | if (settings.strict === undefined || settings.strict === null) {
|
828 | settings.strict = true;
|
829 | }
|
830 | if (settings.strict === false) {
|
831 | console.warn("WARNING: relational database doesn't support {strict: false} mode." +
|
832 | ` {strict: true} mode will be set for model ${className} instead.`);
|
833 | settings.strict = true;
|
834 | }
|
835 | }
|
836 |
|
837 | const modelClass = this.modelBuilder.define(className, properties, settings);
|
838 | modelClass.dataSource = this;
|
839 |
|
840 | if (settings.unresolved) {
|
841 | return modelClass;
|
842 | }
|
843 |
|
844 | this.setupDataAccess(modelClass, settings);
|
845 | modelClass.emit('dataSourceAttached', modelClass);
|
846 |
|
847 | return modelClass;
|
848 | };
|
849 |
|
850 |
|
851 |
|
852 |
|
853 |
|
854 |
|
855 | DataSource.prototype.deleteModelByName = function(modelName) {
|
856 | this.modelBuilder.deleteModelByName(modelName);
|
857 | delete this.connector._models[modelName];
|
858 | };
|
859 |
|
860 |
|
861 |
|
862 |
|
863 |
|
864 | DataSource.prototype.deleteAllModels = function() {
|
865 | for (const m in this.modelBuilder.models) {
|
866 | this.deleteModelByName(m);
|
867 | }
|
868 | };
|
869 |
|
870 |
|
871 |
|
872 |
|
873 |
|
874 |
|
875 |
|
876 |
|
877 | DataSource.prototype.mixin = function(ModelCtor) {
|
878 | const ops = this.operations();
|
879 | const DAO = this.DataAccessObject;
|
880 |
|
881 |
|
882 | jutil.mixin(ModelCtor, DAO, {proxyFunctions: true, override: true});
|
883 |
|
884 |
|
885 | Object.keys(ops).forEach(function(name) {
|
886 | const op = ops[name];
|
887 | let scope;
|
888 |
|
889 | if (op.enabled) {
|
890 | scope = op.prototype ? ModelCtor.prototype : ModelCtor;
|
891 |
|
892 |
|
893 |
|
894 | Object.keys(op)
|
895 | .filter(function(key) {
|
896 |
|
897 | return ~[
|
898 | 'scope',
|
899 | 'fnName',
|
900 | 'prototype',
|
901 | ].indexOf(key);
|
902 | })
|
903 | .forEach(function(key) {
|
904 | if (typeof op[key] !== 'undefined') {
|
905 | op.scope[op.fnName][key] = op[key];
|
906 | }
|
907 | });
|
908 | }
|
909 | });
|
910 | };
|
911 |
|
912 |
|
913 |
|
914 |
|
915 |
|
916 |
|
917 |
|
918 | DataSource.prototype.getModel = function(name, forceCreate) {
|
919 | return this.modelBuilder.getModel(name, forceCreate);
|
920 | };
|
921 |
|
922 |
|
923 |
|
924 |
|
925 |
|
926 |
|
927 |
|
928 |
|
929 | DataSource.prototype.getModelDefinition = function(name) {
|
930 | return this.modelBuilder.getModelDefinition(name);
|
931 | };
|
932 |
|
933 |
|
934 |
|
935 |
|
936 |
|
937 |
|
938 |
|
939 |
|
940 |
|
941 |
|
942 |
|
943 |
|
944 | DataSource.prototype.getTypes = function() {
|
945 | const getTypes = this.connector && this.connector.getTypes;
|
946 | let types = getTypes && getTypes() || [];
|
947 | if (typeof types === 'string') {
|
948 | types = types.split(/[\s,\/]+/);
|
949 | }
|
950 | return types;
|
951 | };
|
952 |
|
953 |
|
954 |
|
955 |
|
956 |
|
957 |
|
958 | DataSource.prototype.supportTypes = function(types) {
|
959 | const supportedTypes = this.getTypes();
|
960 | if (Array.isArray(types)) {
|
961 |
|
962 | for (let i = 0; i < types.length; i++) {
|
963 | if (supportedTypes.indexOf(types[i]) === -1) {
|
964 |
|
965 | return false;
|
966 | }
|
967 | }
|
968 | return true;
|
969 | } else {
|
970 |
|
971 | return supportedTypes.indexOf(types) !== -1;
|
972 | }
|
973 | };
|
974 |
|
975 |
|
976 |
|
977 |
|
978 |
|
979 |
|
980 |
|
981 |
|
982 |
|
983 |
|
984 |
|
985 |
|
986 | DataSource.prototype.attach = function(modelClass) {
|
987 | if (modelClass.dataSource === this) {
|
988 |
|
989 | return modelClass;
|
990 | }
|
991 |
|
992 | if (modelClass.modelBuilder !== this.modelBuilder) {
|
993 | this.modelBuilder.definitions[modelClass.modelName] = modelClass.definition;
|
994 | this.modelBuilder.models[modelClass.modelName] = modelClass;
|
995 |
|
996 | modelClass.modelBuilder = this.modelBuilder;
|
997 | }
|
998 |
|
999 |
|
1000 | modelClass.dataSource = this;
|
1001 |
|
1002 | this.setupDataAccess(modelClass, modelClass.settings);
|
1003 | modelClass.emit('dataSourceAttached', modelClass);
|
1004 | return modelClass;
|
1005 | };
|
1006 |
|
1007 |
|
1008 |
|
1009 |
|
1010 |
|
1011 |
|
1012 |
|
1013 |
|
1014 |
|
1015 |
|
1016 |
|
1017 | DataSource.prototype.defineProperty = function(model, prop, params) {
|
1018 | this.modelBuilder.defineProperty(model, prop, params);
|
1019 |
|
1020 | const resolvedProp = this.getModelDefinition(model).properties[prop];
|
1021 | if (this.connector && this.connector.defineProperty) {
|
1022 | this.connector.defineProperty(model, prop, resolvedProp);
|
1023 | }
|
1024 | };
|
1025 |
|
1026 |
|
1027 |
|
1028 |
|
1029 |
|
1030 |
|
1031 |
|
1032 |
|
1033 |
|
1034 |
|
1035 |
|
1036 |
|
1037 |
|
1038 |
|
1039 |
|
1040 | DataSource.prototype.automigrate = function(models, cb) {
|
1041 | this.freeze();
|
1042 |
|
1043 | if ((!cb) && ('function' === typeof models)) {
|
1044 | cb = models;
|
1045 | models = undefined;
|
1046 | }
|
1047 |
|
1048 | cb = cb || utils.createPromiseCallback();
|
1049 |
|
1050 | if (!this.connector.automigrate) {
|
1051 |
|
1052 | process.nextTick(cb);
|
1053 | return cb.promise;
|
1054 | }
|
1055 |
|
1056 |
|
1057 | if ('string' === typeof models) {
|
1058 | models = [models];
|
1059 | }
|
1060 |
|
1061 | const attachedModels = this.connector._models;
|
1062 |
|
1063 | if (attachedModels && typeof attachedModels === 'object') {
|
1064 | models = models || Object.keys(attachedModels);
|
1065 |
|
1066 | if (models.length === 0) {
|
1067 | process.nextTick(cb);
|
1068 | return cb.promise;
|
1069 | }
|
1070 |
|
1071 | const invalidModels = models.filter(function(m) {
|
1072 | return !(m in attachedModels);
|
1073 | });
|
1074 |
|
1075 | if (invalidModels.length) {
|
1076 | process.nextTick(function() {
|
1077 | cb(new Error(g.f('Cannot migrate models not attached to this datasource: %s',
|
1078 | invalidModels.join(' '))));
|
1079 | });
|
1080 | return cb.promise;
|
1081 | }
|
1082 | }
|
1083 |
|
1084 | const args = [models, cb];
|
1085 | args.callee = this.automigrate;
|
1086 | const queued = this.ready(this, args);
|
1087 | if (queued) {
|
1088 |
|
1089 | return cb.promise;
|
1090 | }
|
1091 |
|
1092 | this.connector.automigrate(models, cb);
|
1093 | return cb.promise;
|
1094 | };
|
1095 |
|
1096 |
|
1097 |
|
1098 |
|
1099 |
|
1100 |
|
1101 |
|
1102 |
|
1103 |
|
1104 |
|
1105 |
|
1106 |
|
1107 |
|
1108 |
|
1109 | DataSource.prototype.autoupdate = function(models, cb) {
|
1110 | this.freeze();
|
1111 |
|
1112 | if ((!cb) && ('function' === typeof models)) {
|
1113 | cb = models;
|
1114 | models = undefined;
|
1115 | }
|
1116 |
|
1117 | cb = cb || utils.createPromiseCallback();
|
1118 |
|
1119 | if (!this.connector.autoupdate) {
|
1120 |
|
1121 | process.nextTick(cb);
|
1122 | return cb.promise;
|
1123 | }
|
1124 |
|
1125 |
|
1126 | if ('string' === typeof models) {
|
1127 | models = [models];
|
1128 | }
|
1129 |
|
1130 | const attachedModels = this.connector._models;
|
1131 |
|
1132 | if (attachedModels && typeof attachedModels === 'object') {
|
1133 | models = models || Object.keys(attachedModels);
|
1134 |
|
1135 | if (models.length === 0) {
|
1136 | process.nextTick(cb);
|
1137 | return cb.promise;
|
1138 | }
|
1139 |
|
1140 | const invalidModels = models.filter(function(m) {
|
1141 | return !(m in attachedModels);
|
1142 | });
|
1143 |
|
1144 | if (invalidModels.length) {
|
1145 | process.nextTick(function() {
|
1146 | cb(new Error(g.f('Cannot migrate models not attached to this datasource: %s',
|
1147 | invalidModels.join(' '))));
|
1148 | });
|
1149 | return cb.promise;
|
1150 | }
|
1151 | }
|
1152 |
|
1153 | const args = [models, cb];
|
1154 | args.callee = this.autoupdate;
|
1155 | const queued = this.ready(this, args);
|
1156 | if (queued) {
|
1157 |
|
1158 | return cb.promise;
|
1159 | }
|
1160 |
|
1161 | this.connector.autoupdate(models, cb);
|
1162 | return cb.promise;
|
1163 | };
|
1164 |
|
1165 |
|
1166 |
|
1167 |
|
1168 |
|
1169 |
|
1170 |
|
1171 |
|
1172 |
|
1173 |
|
1174 |
|
1175 |
|
1176 |
|
1177 |
|
1178 | DataSource.prototype.discoverModelDefinitions = function(options, cb) {
|
1179 | this.freeze();
|
1180 |
|
1181 | if (cb === undefined && typeof options === 'function') {
|
1182 | cb = options;
|
1183 | options = {};
|
1184 | }
|
1185 | options = options || {};
|
1186 | cb = cb || utils.createPromiseCallback();
|
1187 |
|
1188 | if (this.connector.discoverModelDefinitions) {
|
1189 | this.connector.discoverModelDefinitions(options, cb);
|
1190 | } else if (cb) {
|
1191 | process.nextTick(cb);
|
1192 | }
|
1193 | return cb.promise;
|
1194 | };
|
1195 |
|
1196 |
|
1197 |
|
1198 |
|
1199 |
|
1200 |
|
1201 |
|
1202 |
|
1203 |
|
1204 |
|
1205 |
|
1206 |
|
1207 | DataSource.prototype.discoverModelDefinitionsSync = function(options) {
|
1208 | this.freeze();
|
1209 | if (this.connector.discoverModelDefinitionsSync) {
|
1210 | return this.connector.discoverModelDefinitionsSync(options);
|
1211 | }
|
1212 | return null;
|
1213 | };
|
1214 |
|
1215 |
|
1216 |
|
1217 |
|
1218 |
|
1219 |
|
1220 |
|
1221 |
|
1222 |
|
1223 |
|
1224 |
|
1225 |
|
1226 |
|
1227 |
|
1228 |
|
1229 |
|
1230 |
|
1231 |
|
1232 |
|
1233 |
|
1234 |
|
1235 |
|
1236 |
|
1237 |
|
1238 |
|
1239 |
|
1240 | DataSource.prototype.discoverModelProperties = function(modelName, options, cb) {
|
1241 | this.freeze();
|
1242 |
|
1243 | if (cb === undefined && typeof options === 'function') {
|
1244 | cb = options;
|
1245 | options = {};
|
1246 | }
|
1247 | options = options || {};
|
1248 | cb = cb || utils.createPromiseCallback();
|
1249 |
|
1250 | if (this.connector.discoverModelProperties) {
|
1251 | this.connector.discoverModelProperties(modelName, options, cb);
|
1252 | } else if (cb) {
|
1253 | process.nextTick(cb);
|
1254 | }
|
1255 | return cb.promise;
|
1256 | };
|
1257 |
|
1258 |
|
1259 |
|
1260 |
|
1261 |
|
1262 |
|
1263 |
|
1264 |
|
1265 |
|
1266 | DataSource.prototype.discoverModelPropertiesSync = function(modelName, options) {
|
1267 | this.freeze();
|
1268 | if (this.connector.discoverModelPropertiesSync) {
|
1269 | return this.connector.discoverModelPropertiesSync(modelName, options);
|
1270 | }
|
1271 | return null;
|
1272 | };
|
1273 |
|
1274 |
|
1275 |
|
1276 |
|
1277 |
|
1278 |
|
1279 |
|
1280 |
|
1281 |
|
1282 |
|
1283 |
|
1284 |
|
1285 |
|
1286 |
|
1287 |
|
1288 |
|
1289 |
|
1290 |
|
1291 |
|
1292 |
|
1293 | DataSource.prototype.discoverPrimaryKeys = function(modelName, options, cb) {
|
1294 | this.freeze();
|
1295 |
|
1296 | if (cb === undefined && typeof options === 'function') {
|
1297 | cb = options;
|
1298 | options = {};
|
1299 | }
|
1300 | options = options || {};
|
1301 | cb = cb || utils.createPromiseCallback();
|
1302 |
|
1303 | if (this.connector.discoverPrimaryKeys) {
|
1304 | this.connector.discoverPrimaryKeys(modelName, options, cb);
|
1305 | } else if (cb) {
|
1306 | process.nextTick(cb);
|
1307 | }
|
1308 | return cb.promise;
|
1309 | };
|
1310 |
|
1311 |
|
1312 |
|
1313 |
|
1314 |
|
1315 |
|
1316 |
|
1317 |
|
1318 |
|
1319 |
|
1320 | DataSource.prototype.discoverPrimaryKeysSync = function(modelName, options) {
|
1321 | this.freeze();
|
1322 | if (this.connector.discoverPrimaryKeysSync) {
|
1323 | return this.connector.discoverPrimaryKeysSync(modelName, options);
|
1324 | }
|
1325 | return null;
|
1326 | };
|
1327 |
|
1328 |
|
1329 |
|
1330 |
|
1331 |
|
1332 |
|
1333 |
|
1334 |
|
1335 |
|
1336 |
|
1337 |
|
1338 |
|
1339 |
|
1340 |
|
1341 |
|
1342 |
|
1343 |
|
1344 |
|
1345 |
|
1346 |
|
1347 |
|
1348 |
|
1349 |
|
1350 |
|
1351 |
|
1352 |
|
1353 | DataSource.prototype.discoverForeignKeys = function(modelName, options, cb) {
|
1354 | this.freeze();
|
1355 |
|
1356 | if (cb === undefined && typeof options === 'function') {
|
1357 | cb = options;
|
1358 | options = {};
|
1359 | }
|
1360 | options = options || {};
|
1361 | cb = cb || utils.createPromiseCallback();
|
1362 |
|
1363 | if (this.connector.discoverForeignKeys) {
|
1364 | this.connector.discoverForeignKeys(modelName, options, cb);
|
1365 | } else if (cb) {
|
1366 | process.nextTick(cb);
|
1367 | }
|
1368 | return cb.promise;
|
1369 | };
|
1370 |
|
1371 |
|
1372 |
|
1373 |
|
1374 |
|
1375 |
|
1376 |
|
1377 |
|
1378 |
|
1379 |
|
1380 | DataSource.prototype.discoverForeignKeysSync = function(modelName, options) {
|
1381 | this.freeze();
|
1382 | if (this.connector.discoverForeignKeysSync) {
|
1383 | return this.connector.discoverForeignKeysSync(modelName, options);
|
1384 | }
|
1385 | return null;
|
1386 | };
|
1387 |
|
1388 |
|
1389 |
|
1390 |
|
1391 |
|
1392 |
|
1393 |
|
1394 |
|
1395 |
|
1396 |
|
1397 |
|
1398 |
|
1399 |
|
1400 |
|
1401 |
|
1402 |
|
1403 |
|
1404 |
|
1405 |
|
1406 |
|
1407 |
|
1408 |
|
1409 |
|
1410 |
|
1411 |
|
1412 |
|
1413 |
|
1414 | DataSource.prototype.discoverExportedForeignKeys = function(modelName, options, cb) {
|
1415 | this.freeze();
|
1416 |
|
1417 | if (cb === undefined && typeof options === 'function') {
|
1418 | cb = options;
|
1419 | options = {};
|
1420 | }
|
1421 | options = options || {};
|
1422 | cb = cb || utils.createPromiseCallback();
|
1423 |
|
1424 | if (this.connector.discoverExportedForeignKeys) {
|
1425 | this.connector.discoverExportedForeignKeys(modelName, options, cb);
|
1426 | } else if (cb) {
|
1427 | process.nextTick(cb);
|
1428 | }
|
1429 | return cb.promise;
|
1430 | };
|
1431 |
|
1432 |
|
1433 |
|
1434 |
|
1435 |
|
1436 |
|
1437 |
|
1438 |
|
1439 |
|
1440 | DataSource.prototype.discoverExportedForeignKeysSync = function(modelName, options) {
|
1441 | this.freeze();
|
1442 | if (this.connector.discoverExportedForeignKeysSync) {
|
1443 | return this.connector.discoverExportedForeignKeysSync(modelName, options);
|
1444 | }
|
1445 | return null;
|
1446 | };
|
1447 |
|
1448 | function capitalize(str) {
|
1449 | if (!str) {
|
1450 | return str;
|
1451 | }
|
1452 | return str.charAt(0).toUpperCase() + ((str.length > 1) ? str.slice(1).toLowerCase() : '');
|
1453 | }
|
1454 |
|
1455 |
|
1456 |
|
1457 |
|
1458 |
|
1459 |
|
1460 |
|
1461 |
|
1462 |
|
1463 | function fromDBName(name, caseFunction) {
|
1464 | if (!name) {
|
1465 | return name;
|
1466 | }
|
1467 | if (typeof caseFunction === 'function') {
|
1468 | return caseFunction(name);
|
1469 | }
|
1470 | return name;
|
1471 | }
|
1472 |
|
1473 |
|
1474 |
|
1475 |
|
1476 |
|
1477 |
|
1478 |
|
1479 |
|
1480 |
|
1481 |
|
1482 |
|
1483 |
|
1484 |
|
1485 |
|
1486 |
|
1487 |
|
1488 |
|
1489 |
|
1490 |
|
1491 |
|
1492 |
|
1493 |
|
1494 |
|
1495 |
|
1496 |
|
1497 |
|
1498 |
|
1499 |
|
1500 |
|
1501 |
|
1502 |
|
1503 |
|
1504 |
|
1505 |
|
1506 |
|
1507 |
|
1508 |
|
1509 |
|
1510 |
|
1511 |
|
1512 |
|
1513 |
|
1514 |
|
1515 |
|
1516 |
|
1517 |
|
1518 |
|
1519 |
|
1520 |
|
1521 |
|
1522 |
|
1523 |
|
1524 |
|
1525 |
|
1526 |
|
1527 |
|
1528 |
|
1529 |
|
1530 |
|
1531 |
|
1532 |
|
1533 | DataSource.prototype.discoverSchema = function(tableName, options, cb) {
|
1534 | options = options || {};
|
1535 |
|
1536 | if (!cb && 'function' === typeof options) {
|
1537 | cb = options;
|
1538 | options = {};
|
1539 | }
|
1540 | options.visited = {};
|
1541 | options.relations = false;
|
1542 |
|
1543 | cb = cb || utils.createPromiseCallback();
|
1544 |
|
1545 | this.discoverSchemas(tableName, options, function(err, schemas) {
|
1546 | if (err || !schemas) {
|
1547 | cb && cb(err, schemas);
|
1548 | return;
|
1549 | }
|
1550 | for (const s in schemas) {
|
1551 | cb && cb(null, schemas[s]);
|
1552 | return;
|
1553 | }
|
1554 | });
|
1555 | return cb.promise;
|
1556 | };
|
1557 |
|
1558 |
|
1559 |
|
1560 |
|
1561 |
|
1562 |
|
1563 |
|
1564 |
|
1565 |
|
1566 |
|
1567 |
|
1568 |
|
1569 |
|
1570 | DataSource.prototype.discoverSchemas = function(tableName, options, cb) {
|
1571 | options = options || {};
|
1572 |
|
1573 | if (!cb && 'function' === typeof options) {
|
1574 | cb = options;
|
1575 | options = {};
|
1576 | }
|
1577 | cb = cb || utils.createPromiseCallback();
|
1578 |
|
1579 | const self = this;
|
1580 | const dbType = this.connector.name;
|
1581 |
|
1582 | let nameMapper;
|
1583 | const disableCamelCase = !!options.disableCamelCase;
|
1584 |
|
1585 | if (options.nameMapper === null) {
|
1586 |
|
1587 | nameMapper = function(type, name) {
|
1588 | return name;
|
1589 | };
|
1590 | } else if (typeof options.nameMapper === 'function') {
|
1591 |
|
1592 | nameMapper = options.nameMapper;
|
1593 | } else {
|
1594 |
|
1595 | nameMapper = function mapName(type, name) {
|
1596 | if (type === 'table' || type === 'model') {
|
1597 | return fromDBName(name, pascalCase);
|
1598 | } else if (type == 'fk') {
|
1599 | if (disableCamelCase) {
|
1600 | return fromDBName(name + 'Rel');
|
1601 | } else {
|
1602 | return fromDBName(name + 'Rel', camelCase);
|
1603 | }
|
1604 | } else {
|
1605 | if (disableCamelCase) {
|
1606 | return fromDBName(name);
|
1607 | } else {
|
1608 | return fromDBName(name, camelCase);
|
1609 | }
|
1610 | }
|
1611 | };
|
1612 | }
|
1613 |
|
1614 | if (this.connector.discoverSchemas) {
|
1615 |
|
1616 | this.connector.discoverSchemas(tableName, options, cb);
|
1617 | return cb.promise;
|
1618 | }
|
1619 |
|
1620 | const tasks = [
|
1621 | this.discoverModelProperties.bind(this, tableName, options),
|
1622 | this.discoverPrimaryKeys.bind(this, tableName, options)];
|
1623 |
|
1624 | const followingRelations = options.associations || options.relations;
|
1625 | if (followingRelations) {
|
1626 | tasks.push(this.discoverForeignKeys.bind(this, tableName, options));
|
1627 | }
|
1628 |
|
1629 | async.parallel(tasks, function(err, results) {
|
1630 | if (err) {
|
1631 | cb(err);
|
1632 | return cb.promise;
|
1633 | }
|
1634 |
|
1635 | const columns = results[0];
|
1636 | if (!columns || columns.length === 0) {
|
1637 | cb(new Error(g.f('Table \'%s\' does not exist.', tableName)));
|
1638 | return cb.promise;
|
1639 | }
|
1640 |
|
1641 |
|
1642 | const primaryKeys = results[1] || [];
|
1643 | const pks = {};
|
1644 | primaryKeys.forEach(function(pk) {
|
1645 | pks[pk.columnName] = pk.keySeq;
|
1646 | });
|
1647 |
|
1648 | if (self.settings.debug) {
|
1649 | debug('Primary keys: ', pks);
|
1650 | }
|
1651 |
|
1652 | const schema = {
|
1653 | name: nameMapper('table', tableName),
|
1654 | options: {
|
1655 | idInjection: false,
|
1656 | },
|
1657 | properties: {},
|
1658 | };
|
1659 |
|
1660 | schema.options[dbType] = {
|
1661 | schema: columns[0].owner,
|
1662 | table: tableName,
|
1663 | };
|
1664 |
|
1665 | columns.forEach(function(item) {
|
1666 | const propName = nameMapper('column', item.columnName);
|
1667 | schema.properties[propName] = {
|
1668 | type: item.type,
|
1669 | required: (item.nullable === 'N' || item.nullable === 'NO' ||
|
1670 | item.nullable === 0 || item.nullable === false),
|
1671 | length: item.dataLength,
|
1672 | precision: item.dataPrecision,
|
1673 | scale: item.dataScale,
|
1674 | };
|
1675 |
|
1676 | if (pks[item.columnName]) {
|
1677 | schema.properties[propName].id = pks[item.columnName];
|
1678 | }
|
1679 | const dbSpecific = schema.properties[propName][dbType] = {
|
1680 | columnName: item.columnName,
|
1681 | dataType: item.dataType,
|
1682 | dataLength: item.dataLength,
|
1683 | dataPrecision: item.dataPrecision,
|
1684 | dataScale: item.dataScale,
|
1685 | nullable: item.nullable,
|
1686 | };
|
1687 |
|
1688 | if (item[dbType]) {
|
1689 | for (const k in item[dbType]) {
|
1690 | dbSpecific[k] = item[dbType][k];
|
1691 | }
|
1692 | }
|
1693 | });
|
1694 |
|
1695 |
|
1696 | options.visited = options.visited || {};
|
1697 | const schemaKey = columns[0].owner + '.' + tableName;
|
1698 | if (!options.visited.hasOwnProperty(schemaKey)) {
|
1699 | if (self.settings.debug) {
|
1700 | debug('Adding schema for ' + schemaKey);
|
1701 | }
|
1702 | options.visited[schemaKey] = schema;
|
1703 | }
|
1704 |
|
1705 | const otherTables = {};
|
1706 | if (followingRelations) {
|
1707 |
|
1708 | const fks = {};
|
1709 | const foreignKeys = results[2] || [];
|
1710 | foreignKeys.forEach(function(fk) {
|
1711 | const fkInfo = {
|
1712 | keySeq: fk.keySeq,
|
1713 | owner: fk.pkOwner,
|
1714 | tableName: fk.pkTableName,
|
1715 | columnName: fk.pkColumnName,
|
1716 | };
|
1717 | if (fks[fk.fkName]) {
|
1718 | fks[fk.fkName].push(fkInfo);
|
1719 | } else {
|
1720 | fks[fk.fkName] = [fkInfo];
|
1721 | }
|
1722 | });
|
1723 |
|
1724 | if (self.settings.debug) {
|
1725 | debug('Foreign keys: ', fks);
|
1726 | }
|
1727 |
|
1728 | schema.options.relations = {};
|
1729 | foreignKeys.forEach(function(fk) {
|
1730 | const propName = nameMapper('fk', (fk.fkName || fk.pkTableName));
|
1731 | schema.options.relations[propName] = {
|
1732 | model: nameMapper('table', fk.pkTableName),
|
1733 | type: 'belongsTo',
|
1734 | foreignKey: nameMapper('column', fk.fkColumnName),
|
1735 | };
|
1736 |
|
1737 | const key = fk.pkOwner + '.' + fk.pkTableName;
|
1738 | if (!options.visited.hasOwnProperty(key) && !otherTables.hasOwnProperty(key)) {
|
1739 | otherTables[key] = {owner: fk.pkOwner, tableName: fk.pkTableName};
|
1740 | }
|
1741 | });
|
1742 | }
|
1743 |
|
1744 | if (Object.keys(otherTables).length === 0) {
|
1745 | cb(null, options.visited);
|
1746 | } else {
|
1747 | const moreTasks = [];
|
1748 | for (const t in otherTables) {
|
1749 | if (self.settings.debug) {
|
1750 | debug('Discovering related schema for ' + schemaKey);
|
1751 | }
|
1752 | const newOptions = {};
|
1753 | for (const key in options) {
|
1754 | newOptions[key] = options[key];
|
1755 | }
|
1756 | newOptions.owner = otherTables[t].owner;
|
1757 |
|
1758 | moreTasks.push(DataSource.prototype.discoverSchemas.bind(self, otherTables[t].tableName, newOptions));
|
1759 | }
|
1760 | async.parallel(moreTasks, function(err, results) {
|
1761 | const result = results && results[0];
|
1762 | cb(err, result);
|
1763 | });
|
1764 | }
|
1765 | });
|
1766 | return cb.promise;
|
1767 | };
|
1768 |
|
1769 |
|
1770 |
|
1771 |
|
1772 |
|
1773 |
|
1774 |
|
1775 |
|
1776 |
|
1777 |
|
1778 |
|
1779 |
|
1780 |
|
1781 | DataSource.prototype.discoverSchemasSync = function(modelName, options) {
|
1782 | const self = this;
|
1783 | const dbType = this.connector.name;
|
1784 |
|
1785 | const columns = this.discoverModelPropertiesSync(modelName, options);
|
1786 | if (!columns || columns.length === 0) {
|
1787 | return [];
|
1788 | }
|
1789 | const disableCamelCase = !!options.disableCamelCase;
|
1790 |
|
1791 | const nameMapper = options.nameMapper || function mapName(type, name) {
|
1792 | if (type === 'table' || type === 'model') {
|
1793 | return fromDBName(name, pascalCase);
|
1794 | } else {
|
1795 | if (disableCamelCase) {
|
1796 | return fromDBName(name);
|
1797 | } else {
|
1798 | return fromDBName(name, camelCase);
|
1799 | }
|
1800 | }
|
1801 | };
|
1802 |
|
1803 |
|
1804 | const primaryKeys = this.discoverPrimaryKeysSync(modelName, options);
|
1805 | const pks = {};
|
1806 | primaryKeys.forEach(function(pk) {
|
1807 | pks[pk.columnName] = pk.keySeq;
|
1808 | });
|
1809 |
|
1810 | if (self.settings.debug) {
|
1811 | debug('Primary keys: ', pks);
|
1812 | }
|
1813 |
|
1814 | const schema = {
|
1815 | name: nameMapper('table', modelName),
|
1816 | options: {
|
1817 | idInjection: false,
|
1818 | },
|
1819 | properties: {},
|
1820 | };
|
1821 |
|
1822 | schema.options[dbType] = {
|
1823 | schema: columns.length > 0 && columns[0].owner,
|
1824 | table: modelName,
|
1825 | };
|
1826 |
|
1827 | columns.forEach(function(item) {
|
1828 | const i = item;
|
1829 |
|
1830 | const propName = nameMapper('column', item.columnName);
|
1831 | schema.properties[propName] = {
|
1832 | type: item.type,
|
1833 | required: (item.nullable === 'N'),
|
1834 | length: item.dataLength,
|
1835 | precision: item.dataPrecision,
|
1836 | scale: item.dataScale,
|
1837 | };
|
1838 |
|
1839 | if (pks[item.columnName]) {
|
1840 | schema.properties[propName].id = pks[item.columnName];
|
1841 | }
|
1842 | schema.properties[propName][dbType] = {
|
1843 | columnName: i.columnName,
|
1844 | dataType: i.dataType,
|
1845 | dataLength: i.dataLength,
|
1846 | dataPrecision: item.dataPrecision,
|
1847 | dataScale: item.dataScale,
|
1848 | nullable: i.nullable,
|
1849 | };
|
1850 | });
|
1851 |
|
1852 |
|
1853 | options.visited = options.visited || {};
|
1854 | const schemaKey = columns[0].owner + '.' + modelName;
|
1855 | if (!options.visited.hasOwnProperty(schemaKey)) {
|
1856 | if (self.settings.debug) {
|
1857 | debug('Adding schema for ' + schemaKey);
|
1858 | }
|
1859 | options.visited[schemaKey] = schema;
|
1860 | }
|
1861 |
|
1862 | const otherTables = {};
|
1863 | const followingRelations = options.associations || options.relations;
|
1864 | if (followingRelations) {
|
1865 |
|
1866 | const fks = {};
|
1867 | const foreignKeys = this.discoverForeignKeysSync(modelName, options);
|
1868 | foreignKeys.forEach(function(fk) {
|
1869 | const fkInfo = {
|
1870 | keySeq: fk.keySeq,
|
1871 | owner: fk.pkOwner,
|
1872 | tableName: fk.pkTableName,
|
1873 | columnName: fk.pkColumnName,
|
1874 | };
|
1875 | if (fks[fk.fkName]) {
|
1876 | fks[fk.fkName].push(fkInfo);
|
1877 | } else {
|
1878 | fks[fk.fkName] = [fkInfo];
|
1879 | }
|
1880 | });
|
1881 |
|
1882 | if (self.settings.debug) {
|
1883 | debug('Foreign keys: ', fks);
|
1884 | }
|
1885 |
|
1886 | schema.options.relations = {};
|
1887 | foreignKeys.forEach(function(fk) {
|
1888 | const propName = nameMapper('column', fk.pkTableName);
|
1889 | schema.options.relations[propName] = {
|
1890 | model: nameMapper('table', fk.pkTableName),
|
1891 | type: 'belongsTo',
|
1892 | foreignKey: nameMapper('column', fk.fkColumnName),
|
1893 | };
|
1894 |
|
1895 | const key = fk.pkOwner + '.' + fk.pkTableName;
|
1896 | if (!options.visited.hasOwnProperty(key) && !otherTables.hasOwnProperty(key)) {
|
1897 | otherTables[key] = {owner: fk.pkOwner, tableName: fk.pkTableName};
|
1898 | }
|
1899 | });
|
1900 | }
|
1901 |
|
1902 | if (Object.keys(otherTables).length === 0) {
|
1903 | return options.visited;
|
1904 | } else {
|
1905 | const moreTasks = [];
|
1906 | for (const t in otherTables) {
|
1907 | if (self.settings.debug) {
|
1908 | debug('Discovering related schema for ' + schemaKey);
|
1909 | }
|
1910 | const newOptions = {};
|
1911 | for (const key in options) {
|
1912 | newOptions[key] = options[key];
|
1913 | }
|
1914 | newOptions.owner = otherTables[t].owner;
|
1915 | self.discoverSchemasSync(otherTables[t].tableName, newOptions);
|
1916 | }
|
1917 | return options.visited;
|
1918 | }
|
1919 | };
|
1920 |
|
1921 |
|
1922 |
|
1923 |
|
1924 |
|
1925 |
|
1926 |
|
1927 |
|
1928 |
|
1929 |
|
1930 |
|
1931 |
|
1932 |
|
1933 |
|
1934 | DataSource.prototype.discoverAndBuildModels = function(modelName, options, cb) {
|
1935 | const self = this;
|
1936 | options = options || {};
|
1937 | this.discoverSchemas(modelName, options, function(err, schemas) {
|
1938 | if (err) {
|
1939 | cb && cb(err, schemas);
|
1940 | return;
|
1941 | }
|
1942 |
|
1943 | const schemaList = [];
|
1944 | for (const s in schemas) {
|
1945 | const schema = schemas[s];
|
1946 | if (options.base) {
|
1947 | schema.options = schema.options || {};
|
1948 | schema.options.base = options.base;
|
1949 | }
|
1950 | schemaList.push(schema);
|
1951 | }
|
1952 |
|
1953 | const models = self.modelBuilder.buildModels(schemaList,
|
1954 | self.createModel.bind(self));
|
1955 |
|
1956 | cb && cb(err, models);
|
1957 | });
|
1958 | };
|
1959 |
|
1960 |
|
1961 |
|
1962 |
|
1963 |
|
1964 |
|
1965 |
|
1966 |
|
1967 |
|
1968 |
|
1969 |
|
1970 |
|
1971 |
|
1972 |
|
1973 |
|
1974 |
|
1975 | DataSource.prototype.discoverAndBuildModelsSync = function(modelName, options) {
|
1976 | options = options || {};
|
1977 | const schemas = this.discoverSchemasSync(modelName, options);
|
1978 |
|
1979 | const schemaList = [];
|
1980 | for (const s in schemas) {
|
1981 | const schema = schemas[s];
|
1982 | if (options.base) {
|
1983 | schema.options = schema.options || {};
|
1984 | schema.options.base = options.base;
|
1985 | }
|
1986 | schemaList.push(schema);
|
1987 | }
|
1988 |
|
1989 | const models = this.modelBuilder.buildModels(schemaList,
|
1990 | this.createModel.bind(this));
|
1991 |
|
1992 | return models;
|
1993 | };
|
1994 |
|
1995 |
|
1996 |
|
1997 |
|
1998 |
|
1999 |
|
2000 |
|
2001 |
|
2002 | DataSource.prototype.buildModelFromInstance = function(name, json, options) {
|
2003 |
|
2004 | const schema = ModelBuilder.introspect(json);
|
2005 |
|
2006 |
|
2007 | return this.createModel(name, schema, options);
|
2008 | };
|
2009 |
|
2010 |
|
2011 |
|
2012 |
|
2013 |
|
2014 |
|
2015 |
|
2016 |
|
2017 | DataSource.prototype.isActual = function(models, cb) {
|
2018 | this.freeze();
|
2019 | if (this.connector.isActual) {
|
2020 | this.connector.isActual(models, cb);
|
2021 | } else {
|
2022 | if ((!cb) && ('function' === typeof models)) {
|
2023 | cb = models;
|
2024 | models = undefined;
|
2025 | }
|
2026 | if (cb) {
|
2027 | process.nextTick(function() {
|
2028 | cb(null, true);
|
2029 | });
|
2030 | }
|
2031 | }
|
2032 | };
|
2033 |
|
2034 |
|
2035 |
|
2036 |
|
2037 |
|
2038 |
|
2039 |
|
2040 | DataSource.prototype.log = function(sql, t) {
|
2041 | debug(sql, t);
|
2042 | this.emit('log', sql, t);
|
2043 | };
|
2044 |
|
2045 |
|
2046 |
|
2047 |
|
2048 |
|
2049 | DataSource.prototype.freeze = function freeze() {
|
2050 | if (!this.connector) {
|
2051 | throw new Error(g.f('The connector has not been initialized.'));
|
2052 | }
|
2053 | if (this.connector.freezeDataSource) {
|
2054 | this.connector.freezeDataSource();
|
2055 | }
|
2056 | if (this.connector.freezeSchema) {
|
2057 | this.connector.freezeSchema();
|
2058 | }
|
2059 | };
|
2060 |
|
2061 |
|
2062 |
|
2063 |
|
2064 |
|
2065 |
|
2066 | DataSource.prototype.tableName = function(modelName) {
|
2067 | return this.getModelDefinition(modelName).tableName(this.connector.name);
|
2068 | };
|
2069 |
|
2070 |
|
2071 |
|
2072 |
|
2073 |
|
2074 |
|
2075 |
|
2076 | DataSource.prototype.columnName = function(modelName, propertyName) {
|
2077 | return this.getModelDefinition(modelName).columnName(this.connector.name, propertyName);
|
2078 | };
|
2079 |
|
2080 |
|
2081 |
|
2082 |
|
2083 |
|
2084 |
|
2085 |
|
2086 | DataSource.prototype.columnMetadata = function(modelName, propertyName) {
|
2087 | return this.getModelDefinition(modelName).columnMetadata(this.connector.name, propertyName);
|
2088 | };
|
2089 |
|
2090 |
|
2091 |
|
2092 |
|
2093 |
|
2094 |
|
2095 | DataSource.prototype.columnNames = function(modelName) {
|
2096 | return this.getModelDefinition(modelName).columnNames(this.connector.name);
|
2097 | };
|
2098 |
|
2099 |
|
2100 |
|
2101 |
|
2102 |
|
2103 |
|
2104 |
|
2105 |
|
2106 |
|
2107 |
|
2108 |
|
2109 |
|
2110 | DataSource.prototype.idColumnName = function(modelName) {
|
2111 | return this.getModelDefinition(modelName).idColumnName(this.connector.name);
|
2112 | };
|
2113 |
|
2114 |
|
2115 |
|
2116 |
|
2117 |
|
2118 |
|
2119 | DataSource.prototype.idName = function(modelName) {
|
2120 | if (!this.getModelDefinition(modelName).idName) {
|
2121 | g.error('No {{id}} name %s', this.getModelDefinition(modelName));
|
2122 | }
|
2123 | return this.getModelDefinition(modelName).idName();
|
2124 | };
|
2125 |
|
2126 |
|
2127 |
|
2128 |
|
2129 |
|
2130 |
|
2131 | DataSource.prototype.idNames = function(modelName) {
|
2132 | return this.getModelDefinition(modelName).idNames();
|
2133 | };
|
2134 |
|
2135 |
|
2136 |
|
2137 |
|
2138 |
|
2139 |
|
2140 | DataSource.prototype.idProperty = function(modelName) {
|
2141 | const def = this.getModelDefinition(modelName);
|
2142 | const idProps = def && def.ids();
|
2143 | return idProps && idProps[0] && idProps[0].property;
|
2144 | };
|
2145 |
|
2146 |
|
2147 |
|
2148 |
|
2149 |
|
2150 |
|
2151 |
|
2152 |
|
2153 | DataSource.prototype.defineForeignKey = function defineForeignKey(className, key, foreignClassName, pkName) {
|
2154 | let pkType = null;
|
2155 | const foreignModel = this.getModelDefinition(foreignClassName);
|
2156 | pkName = pkName || foreignModel && foreignModel.idName();
|
2157 | if (pkName) {
|
2158 | pkType = foreignModel.properties[pkName].type;
|
2159 | }
|
2160 | const model = this.getModelDefinition(className);
|
2161 | if (model.properties[key]) {
|
2162 | if (pkType) {
|
2163 |
|
2164 | model.rawProperties[key].type = model.properties[key].type = pkType;
|
2165 | }
|
2166 | return;
|
2167 | }
|
2168 |
|
2169 | const fkDef = {type: pkType};
|
2170 | const foreignMeta = this.columnMetadata(foreignClassName, pkName);
|
2171 | if (foreignMeta && (foreignMeta.dataType || foreignMeta.dataLength)) {
|
2172 | fkDef[this.connector.name] = {};
|
2173 | if (foreignMeta.dataType) {
|
2174 | fkDef[this.connector.name].dataType = foreignMeta.dataType;
|
2175 | }
|
2176 | if (foreignMeta.dataLength) {
|
2177 | fkDef[this.connector.name].dataLength = foreignMeta.dataLength;
|
2178 | }
|
2179 | }
|
2180 | if (this.connector.defineForeignKey) {
|
2181 | const cb = function(err, keyType) {
|
2182 | if (err) throw err;
|
2183 | fkDef.type = keyType || pkType;
|
2184 |
|
2185 | this.defineProperty(className, key, fkDef);
|
2186 | }.bind(this);
|
2187 | switch (this.connector.defineForeignKey.length) {
|
2188 | case 4:
|
2189 | this.connector.defineForeignKey(className, key, foreignClassName, cb);
|
2190 | break;
|
2191 | default:
|
2192 | case 3:
|
2193 | this.connector.defineForeignKey(className, key, cb);
|
2194 | break;
|
2195 | }
|
2196 | } else {
|
2197 |
|
2198 | this.defineProperty(className, key, fkDef);
|
2199 | }
|
2200 | };
|
2201 |
|
2202 |
|
2203 |
|
2204 |
|
2205 |
|
2206 | DataSource.prototype.disconnect = function disconnect(cb) {
|
2207 | cb = cb || utils.createPromiseCallback();
|
2208 | const self = this;
|
2209 | if (this.connected && (typeof this.connector.disconnect === 'function')) {
|
2210 | this.connector.disconnect(function(err, result) {
|
2211 | self.connected = false;
|
2212 | cb && cb(err, result);
|
2213 | });
|
2214 | } else {
|
2215 | process.nextTick(function() {
|
2216 | self.connected = false;
|
2217 | cb && cb();
|
2218 | });
|
2219 | }
|
2220 | return cb.promise;
|
2221 | };
|
2222 |
|
2223 |
|
2224 |
|
2225 |
|
2226 |
|
2227 |
|
2228 |
|
2229 | DataSource.prototype.stop = DataSource.prototype.disconnect;
|
2230 |
|
2231 |
|
2232 |
|
2233 |
|
2234 |
|
2235 |
|
2236 |
|
2237 |
|
2238 | DataSource.prototype.copyModel = function copyModel(Master) {
|
2239 | const dataSource = this;
|
2240 | const className = Master.modelName;
|
2241 | const md = Master.modelBuilder.getModelDefinition(className);
|
2242 | const Slave = function SlaveModel() {
|
2243 | Master.apply(this, [].slice.call(arguments));
|
2244 | };
|
2245 |
|
2246 | util.inherits(Slave, Master);
|
2247 |
|
2248 |
|
2249 | Slave.__proto__ = Master;
|
2250 |
|
2251 | hiddenProperty(Slave, 'dataSource', dataSource);
|
2252 | hiddenProperty(Slave, 'modelName', className);
|
2253 | hiddenProperty(Slave, 'relations', Master.relations);
|
2254 |
|
2255 | if (!(className in dataSource.modelBuilder.models)) {
|
2256 |
|
2257 | dataSource.modelBuilder.models[className] = Slave;
|
2258 | dataSource.modelBuilder.definitions[className] =
|
2259 | new ModelDefinition(dataSource.modelBuilder, md.name, md.properties, md.settings);
|
2260 |
|
2261 | if ((!dataSource.isTransaction) && dataSource.connector && dataSource.connector.define) {
|
2262 | dataSource.connector.define({
|
2263 | model: Slave,
|
2264 | properties: md.properties,
|
2265 | settings: md.settings,
|
2266 | });
|
2267 | }
|
2268 | }
|
2269 |
|
2270 | return Slave;
|
2271 | };
|
2272 |
|
2273 |
|
2274 |
|
2275 |
|
2276 |
|
2277 |
|
2278 |
|
2279 |
|
2280 |
|
2281 |
|
2282 |
|
2283 |
|
2284 |
|
2285 |
|
2286 |
|
2287 |
|
2288 |
|
2289 |
|
2290 |
|
2291 |
|
2292 |
|
2293 |
|
2294 |
|
2295 |
|
2296 |
|
2297 |
|
2298 |
|
2299 |
|
2300 |
|
2301 |
|
2302 |
|
2303 |
|
2304 |
|
2305 |
|
2306 |
|
2307 |
|
2308 |
|
2309 |
|
2310 |
|
2311 |
|
2312 | DataSource.prototype.transaction = function(execute, options, cb) {
|
2313 | if (cb === undefined && typeof options === 'function') {
|
2314 | cb = options;
|
2315 | options = {};
|
2316 | } else {
|
2317 | options = options || {};
|
2318 | }
|
2319 |
|
2320 | const dataSource = this;
|
2321 | const transaction = new EventEmitter();
|
2322 |
|
2323 | for (const p in dataSource) {
|
2324 | transaction[p] = dataSource[p];
|
2325 | }
|
2326 |
|
2327 | transaction.isTransaction = true;
|
2328 | transaction.origin = dataSource;
|
2329 | transaction.connected = false;
|
2330 | transaction.connecting = false;
|
2331 |
|
2332 |
|
2333 | transaction.transaction = function() {
|
2334 | throw new Error(g.f('Nesting transactions is not supported'));
|
2335 | };
|
2336 |
|
2337 |
|
2338 | const modelBuilder = new ModelBuilder();
|
2339 | const slaveModels = modelBuilder.models;
|
2340 | transaction.modelBuilder = modelBuilder;
|
2341 | transaction.models = slaveModels;
|
2342 | transaction.definitions = modelBuilder.definitions;
|
2343 |
|
2344 |
|
2345 |
|
2346 |
|
2347 | const masterModels = dataSource.modelBuilder.models;
|
2348 | Object.keys(masterModels).forEach(function(name) {
|
2349 | Object.defineProperty(slaveModels, name, {
|
2350 | enumerable: true,
|
2351 | configurable: true,
|
2352 | get: function() {
|
2353 |
|
2354 |
|
2355 | delete slaveModels[name];
|
2356 | return dataSource.copyModel.call(transaction, masterModels[name]);
|
2357 | },
|
2358 | });
|
2359 | });
|
2360 |
|
2361 | let done = function(err) {
|
2362 | if (err) {
|
2363 | transaction.rollback(function(error) {
|
2364 | cb(err || error);
|
2365 | });
|
2366 | } else {
|
2367 | transaction.commit(cb);
|
2368 | }
|
2369 |
|
2370 |
|
2371 | done = function() {};
|
2372 | };
|
2373 |
|
2374 | function handleExecute() {
|
2375 | if (execute) {
|
2376 | cb = cb || utils.createPromiseCallback();
|
2377 | try {
|
2378 | const result = execute(slaveModels, done);
|
2379 | if (result && typeof result.then === 'function') {
|
2380 | result.then(function() { done(); }, done);
|
2381 | }
|
2382 | } catch (err) {
|
2383 | done(err);
|
2384 | }
|
2385 | return cb.promise;
|
2386 | } else if (cb) {
|
2387 | cb(null, transaction);
|
2388 | } else {
|
2389 | return transaction;
|
2390 | }
|
2391 | }
|
2392 |
|
2393 | function transactionCreated(err, tx) {
|
2394 | if (err) {
|
2395 | cb(err);
|
2396 | } else {
|
2397 |
|
2398 |
|
2399 |
|
2400 | transaction.currentTransaction = tx;
|
2401 |
|
2402 |
|
2403 | if (!tx.observe && tx.connector) {
|
2404 | tx = tx.connector;
|
2405 | }
|
2406 |
|
2407 | tx.observe('timeout', function(context, next) {
|
2408 | const err = new Error(g.f('Transaction is rolled back due to timeout'));
|
2409 | err.code = 'TRANSACTION_TIMEOUT';
|
2410 |
|
2411 |
|
2412 |
|
2413 | next(err);
|
2414 |
|
2415 |
|
2416 | done(err);
|
2417 | });
|
2418 | handleExecute();
|
2419 | }
|
2420 | }
|
2421 |
|
2422 | function ensureTransaction(transaction, cb) {
|
2423 | if (!transaction) {
|
2424 | process.nextTick(function() {
|
2425 | cb(new Error(g.f(
|
2426 | 'Transaction is not ready, wait for the returned promise to resolve',
|
2427 | )));
|
2428 | });
|
2429 | }
|
2430 | return transaction;
|
2431 | }
|
2432 |
|
2433 | const connector = dataSource.connector;
|
2434 | if (connector.transaction) {
|
2435 |
|
2436 | transaction.connector = connector.transaction();
|
2437 | transaction.commit =
|
2438 | transaction.exec = function(cb) {
|
2439 | this.connector.exec(cb);
|
2440 | };
|
2441 | transaction.rollback = function(cb) {
|
2442 |
|
2443 | cb();
|
2444 | };
|
2445 | return handleExecute();
|
2446 | } else if (connector.beginTransaction) {
|
2447 |
|
2448 | transaction.exec =
|
2449 | transaction.commit = function(cb) {
|
2450 | ensureTransaction(this.currentTransaction, cb).commit(cb);
|
2451 | };
|
2452 | transaction.rollback = function(cb) {
|
2453 | ensureTransaction(this.currentTransaction, cb).rollback(cb);
|
2454 | };
|
2455 |
|
2456 | cb = cb || utils.createPromiseCallback();
|
2457 | Transaction.begin(connector, options, transactionCreated);
|
2458 | return cb.promise;
|
2459 | } else {
|
2460 | throw new Error(g.f('DataSource does not support transactions'));
|
2461 | }
|
2462 | };
|
2463 |
|
2464 |
|
2465 |
|
2466 |
|
2467 |
|
2468 |
|
2469 |
|
2470 | DataSource.prototype.enableRemote = function(operation) {
|
2471 | const op = this.getOperation(operation);
|
2472 | if (op) {
|
2473 | op.remoteEnabled = true;
|
2474 | } else {
|
2475 | throw new Error(g.f('%s is not provided by the attached connector', operation));
|
2476 | }
|
2477 | };
|
2478 |
|
2479 |
|
2480 |
|
2481 |
|
2482 |
|
2483 |
|
2484 |
|
2485 |
|
2486 |
|
2487 |
|
2488 |
|
2489 |
|
2490 |
|
2491 |
|
2492 |
|
2493 |
|
2494 |
|
2495 |
|
2496 |
|
2497 |
|
2498 |
|
2499 | DataSource.prototype.disableRemote = function(operation) {
|
2500 | const op = this.getOperation(operation);
|
2501 | if (op) {
|
2502 | op.remoteEnabled = false;
|
2503 | } else {
|
2504 | throw new Error(g.f('%s is not provided by the attached connector', operation));
|
2505 | }
|
2506 | };
|
2507 |
|
2508 |
|
2509 |
|
2510 |
|
2511 |
|
2512 |
|
2513 | DataSource.prototype.getOperation = function(operation) {
|
2514 | const ops = this.operations();
|
2515 | const opKeys = Object.keys(ops);
|
2516 |
|
2517 | for (let i = 0; i < opKeys.length; i++) {
|
2518 | const op = ops[opKeys[i]];
|
2519 |
|
2520 | if (op.name === operation) {
|
2521 | return op;
|
2522 | }
|
2523 | }
|
2524 | };
|
2525 |
|
2526 |
|
2527 |
|
2528 |
|
2529 |
|
2530 |
|
2531 |
|
2532 |
|
2533 |
|
2534 |
|
2535 |
|
2536 |
|
2537 |
|
2538 |
|
2539 |
|
2540 |
|
2541 |
|
2542 |
|
2543 |
|
2544 |
|
2545 |
|
2546 |
|
2547 |
|
2548 |
|
2549 | DataSource.prototype.operations = function() {
|
2550 | return this._operations;
|
2551 | };
|
2552 |
|
2553 |
|
2554 |
|
2555 |
|
2556 |
|
2557 |
|
2558 |
|
2559 | DataSource.prototype.defineOperation = function(name, options, fn) {
|
2560 | options.fn = fn;
|
2561 | options.name = name;
|
2562 | this._operations[name] = options;
|
2563 | };
|
2564 |
|
2565 |
|
2566 |
|
2567 |
|
2568 |
|
2569 | DataSource.prototype.isRelational = function() {
|
2570 | return this.connector && this.connector.relational;
|
2571 | };
|
2572 |
|
2573 |
|
2574 |
|
2575 |
|
2576 |
|
2577 |
|
2578 |
|
2579 |
|
2580 |
|
2581 |
|
2582 |
|
2583 |
|
2584 | DataSource.prototype.queueInvocation = DataSource.prototype.ready =
|
2585 | function(obj, args) {
|
2586 | const self = this;
|
2587 | debug('Datasource %s: connected=%s connecting=%s', this.name,
|
2588 | this.connected, this.connecting);
|
2589 | if (this.connected) {
|
2590 |
|
2591 | return false;
|
2592 | }
|
2593 |
|
2594 | this._queuedInvocations++;
|
2595 |
|
2596 | const method = args.callee;
|
2597 |
|
2598 |
|
2599 | let onConnected = null, onError = null, timeoutHandle = null;
|
2600 | onConnected = function() {
|
2601 | debug('Datasource %s is now connected - executing method %s', self.name, method.name);
|
2602 | this._queuedInvocations--;
|
2603 |
|
2604 | self.removeListener('error', onError);
|
2605 | if (timeoutHandle) {
|
2606 | clearTimeout(timeoutHandle);
|
2607 | }
|
2608 | const params = [].slice.call(args);
|
2609 | try {
|
2610 | method.apply(obj, params);
|
2611 | } catch (err) {
|
2612 |
|
2613 | const cb = params.pop();
|
2614 | if (typeof cb === 'function') {
|
2615 | process.nextTick(function() {
|
2616 | cb(err);
|
2617 | });
|
2618 | } else {
|
2619 | throw err;
|
2620 | }
|
2621 | }
|
2622 | };
|
2623 | onError = function(err) {
|
2624 | debug('Datasource %s fails to connect - aborting method %s', self.name, method.name);
|
2625 | this._queuedInvocations--;
|
2626 |
|
2627 | self.removeListener('connected', onConnected);
|
2628 | if (timeoutHandle) {
|
2629 | clearTimeout(timeoutHandle);
|
2630 | }
|
2631 | const params = [].slice.call(args);
|
2632 | const cb = params.pop();
|
2633 | if (typeof cb === 'function') {
|
2634 | process.nextTick(function() {
|
2635 | cb(err);
|
2636 | });
|
2637 | }
|
2638 | };
|
2639 | this.once('connected', onConnected);
|
2640 | this.once('error', onError);
|
2641 |
|
2642 |
|
2643 | const timeout = this.settings.connectionTimeout || 5000;
|
2644 | timeoutHandle = setTimeout(function() {
|
2645 | debug('Datasource %s fails to connect due to timeout - aborting method %s',
|
2646 | self.name, method.name);
|
2647 | this._queuedInvocations--;
|
2648 | self.connecting = false;
|
2649 | self.removeListener('error', onError);
|
2650 | self.removeListener('connected', onConnected);
|
2651 | const params = [].slice.call(args);
|
2652 | const cb = params.pop();
|
2653 | if (typeof cb === 'function') {
|
2654 | cb(new Error(g.f('Timeout in connecting after %s ms', timeout)));
|
2655 | }
|
2656 | }, timeout);
|
2657 |
|
2658 | if (!this.connecting) {
|
2659 | debug('Connecting datasource %s to connector %s', this.name, this.connector.name);
|
2660 |
|
2661 |
|
2662 |
|
2663 |
|
2664 | this.connect(() => {});
|
2665 | }
|
2666 | return true;
|
2667 | };
|
2668 |
|
2669 |
|
2670 |
|
2671 |
|
2672 |
|
2673 | DataSource.prototype.ping = function(cb) {
|
2674 | cb = cb || utils.createPromiseCallback();
|
2675 | const self = this;
|
2676 | if (self.connector.ping) {
|
2677 | this.connector.ping(cb);
|
2678 | } else if (self.connector.discoverModelProperties) {
|
2679 | self.discoverModelProperties('dummy', {}, cb);
|
2680 | } else {
|
2681 | process.nextTick(function() {
|
2682 | const err = self.connected ? null : new Error(g.f('Not connected'));
|
2683 | cb(err);
|
2684 | });
|
2685 | }
|
2686 | return cb.promise;
|
2687 | };
|
2688 |
|
2689 |
|
2690 |
|
2691 |
|
2692 |
|
2693 |
|
2694 |
|
2695 |
|
2696 |
|
2697 |
|
2698 | DataSource.prototype.execute = function(command, args = [], options = {}) {
|
2699 | assert(typeof command === 'string' || typeof command === 'object',
|
2700 | '"command" must be a string or an object.');
|
2701 | assert(typeof args === 'object',
|
2702 | '"args" must be an object, an array or undefined.');
|
2703 | assert(typeof options === 'object',
|
2704 | '"options" must be an object or undefined.');
|
2705 |
|
2706 | if (!this.connector) {
|
2707 | return Promise.reject(errorNotImplemented(
|
2708 | `DataSource "${this.name}" is missing a connector to execute the command.`,
|
2709 | ));
|
2710 | }
|
2711 |
|
2712 | if (!this.connector.execute) {
|
2713 | return Promise.reject(new errorNotImplemented(
|
2714 | `The connector "${this.connector.name}" used by dataSource "${this.name}" ` +
|
2715 | 'does not implement "execute()" API.',
|
2716 | ));
|
2717 | }
|
2718 |
|
2719 | return new Promise((resolve, reject) => {
|
2720 | this.connector.execute(command, args, options, onExecuted);
|
2721 | function onExecuted(err, result) {
|
2722 | if (err) return reject(err);
|
2723 | if (arguments.length > 2) {
|
2724 | result = Array.prototype.slice.call(arguments, 1);
|
2725 | }
|
2726 | resolve(result);
|
2727 | }
|
2728 | });
|
2729 |
|
2730 | function errorNotImplemented(msg) {
|
2731 | const err = new Error(msg);
|
2732 | err.code = 'NOT_IMPLEMENTED';
|
2733 | return err;
|
2734 | }
|
2735 | };
|
2736 |
|
2737 |
|
2738 |
|
2739 |
|
2740 |
|
2741 |
|
2742 |
|
2743 |
|
2744 | DataSource.prototype.beginTransaction = function(options) {
|
2745 | return Transaction.begin(this.connector, options);
|
2746 | };
|
2747 |
|
2748 |
|
2749 |
|
2750 |
|
2751 | DataSource.prototype.getMaxOfflineRequests = function() {
|
2752 |
|
2753 |
|
2754 |
|
2755 |
|
2756 | let maxOfflineRequests = DataSource.DEFAULT_MAX_OFFLINE_REQUESTS;
|
2757 | if (
|
2758 | this.settings &&
|
2759 | this.settings.maxOfflineRequests
|
2760 | ) {
|
2761 | if (typeof this.settings.maxOfflineRequests !== 'number')
|
2762 | throw new Error('maxOfflineRequests must be a number');
|
2763 |
|
2764 | maxOfflineRequests = this.settings.maxOfflineRequests;
|
2765 | }
|
2766 | return maxOfflineRequests;
|
2767 | };
|
2768 |
|
2769 |
|
2770 |
|
2771 |
|
2772 |
|
2773 |
|
2774 |
|
2775 |
|
2776 |
|
2777 |
|
2778 | function hiddenProperty(obj, key, value) {
|
2779 | Object.defineProperty(obj, key, {
|
2780 | writable: false,
|
2781 | enumerable: false,
|
2782 | configurable: false,
|
2783 | value: value,
|
2784 | });
|
2785 | }
|
2786 |
|
2787 |
|
2788 |
|
2789 |
|
2790 |
|
2791 |
|
2792 |
|
2793 |
|
2794 | function defineReadonlyProp(obj, key, value) {
|
2795 | Object.defineProperty(obj, key, {
|
2796 | writable: false,
|
2797 | enumerable: true,
|
2798 | configurable: true,
|
2799 | value: value,
|
2800 | });
|
2801 | }
|
2802 |
|
2803 |
|
2804 | DataSource.Text = ModelBuilder.Text;
|
2805 | DataSource.JSON = ModelBuilder.JSON;
|
2806 | DataSource.Any = ModelBuilder.Any;
|