loopback-datasource-juggler/lib/datasource.js

2585 lines
81 KiB
JavaScript
Raw Normal View History

2016-04-01 22:25:16 +00:00
// Copyright IBM Corp. 2013,2016. All Rights Reserved.
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
// Turning on strict for this file breaks lots of test cases;
// disabling strict for this file
/* eslint-disable strict */
2013-08-13 16:37:09 +00:00
/*!
2013-05-17 17:54:14 +00:00
* Module dependencies
*/
2013-05-24 05:20:20 +00:00
var ModelBuilder = require('./model-builder.js').ModelBuilder;
2013-10-03 00:20:54 +00:00
var ModelDefinition = require('./model-definition.js');
var RelationDefinition = require('./relation-definition.js');
2015-05-20 22:02:44 +00:00
var OberserverMixin = require('./observer');
2013-05-28 05:20:30 +00:00
var jutil = require('./jutil');
var utils = require('./utils');
2013-05-17 17:54:14 +00:00
var ModelBaseClass = require('./model.js');
var DataAccessObject = require('./dao.js');
2014-03-04 01:16:37 +00:00
var defineScope = require('./scope.js').defineScope;
2013-05-17 17:54:14 +00:00
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var assert = require('assert');
var async = require('async');
var traverse = require('traverse');
2016-07-22 19:26:07 +00:00
var g = require('strong-globalize')();
var juggler = require('..');
Overall review of polymorphic relations In #1298, the spec/doc for polymorphic relations was reviewed **hasX relation** - `type`: **hasMany** - `as`: redefines **this** relation's name (optional) - `model`: **modelTo** - `polymorphic`: - typeOf `polymorphic` === `String` - matching **belongsTo** relation name - `foreignKey` is generated as `polymorphic + 'Id'`, - `discriminator` is generated as `polymorphic + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED** should display a warning, replaced by `selector` - `selector`: should match **belongsTo** relation name if the latter is defined with {polymorphic: true} - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'` --- **belongsTo relation** - `type`: **belongsTo** - `as`: redefines **this** relation's name (optional) - `model`: **NOT EXPECTED**: should throw an error at relation validation - `polymorphic`: - typeOf `polymorphic` === `Boolean` - `foreignKey` is generated as `relationName + 'Id'`, - `discriminator` is generated as `relationName + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED**: should display a warning, replaced by `selector` - `selector`: - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'`
2017-04-01 09:13:22 +00:00
var deprecated = require('depd')('loopback-datasource-juggler');
var Transaction = require('loopback-connector').Transaction;
2013-05-17 17:54:14 +00:00
2014-03-04 17:42:55 +00:00
if (process.env.DEBUG === 'loopback') {
// For back-compatibility
process.env.DEBUG = 'loopback:*';
}
var debug = require('debug')('loopback:datasource');
2014-03-12 23:28:46 +00:00
/*!
2013-05-17 17:54:14 +00:00
* Export public API
*/
exports.DataSource = DataSource;
2013-08-13 16:37:09 +00:00
/*!
2013-05-17 17:54:14 +00:00
* Helpers
*/
var slice = Array.prototype.slice;
/**
2014-03-12 23:28:46 +00:00
* LoopBack models can manipulate data via the DataSource object.
* Attaching a `DataSource` to a `Model` adds instance methods and static methods to the `Model`.
2013-05-17 17:54:14 +00:00
*
* Define a data source to persist model data.
* To create a DataSource programmatically, call `createDataSource()` on the LoopBack object; for example:
2014-03-12 23:28:46 +00:00
* ```js
* var oracle = loopback.createDataSource({
* connector: 'oracle',
* host: '111.22.333.44',
* database: 'MYDB',
* username: 'username',
* password: 'password'
* });
* ```
2013-05-17 17:54:14 +00:00
*
2014-03-12 23:28:46 +00:00
* All classes in single dataSource share same the connector type and
* one database connection.
*
* For example, the following creates a DataSource, and waits for a connection callback.
2013-05-17 17:54:14 +00:00
*
* ```
* var dataSource = new DataSource('mysql', { database: 'myapp_test' });
* dataSource.define(...);
* dataSource.on('connected', function () {
2013-05-17 17:54:14 +00:00
* // work with database
* });
* ```
* @class DataSource
* @param {String} [name] Optional name for datasource.
* @options {Object} settings Database-specific settings to establish connection (settings depend on specific connector).
* The table below lists a typical set for a relational database.
* @property {String} connector Database connector to use. For any supported connector, can be any of:
*
* - The connector module from `require(connectorName)`.
* - The full name of the connector module, such as 'loopback-connector-oracle'.
* - The short name of the connector module, such as 'oracle'.
* - A local module under `./connectors/` folder.
* @property {String} host Database server host name.
* @property {String} port Database server port number.
* @property {String} username Database user name.
* @property {String} password Database password.
* @property {String} database Name of the database to use.
* @property {Boolean} debug Display debugging information. Default is false.
*
* The constructor allows the following styles:
*
* 1. new DataSource(dataSourceName, settings). For example:
* - new DataSource('myDataSource', {connector: 'memory'});
* - new DataSource('myDataSource', {name: 'myDataSource', connector: 'memory'});
* - new DataSource('myDataSource', {name: 'anotherDataSource', connector: 'memory'});
*
* 2. new DataSource(settings). For example:
* - new DataSource({name: 'myDataSource', connector: 'memory'});
* - new DataSource({connector: 'memory'});
*
* 3. new DataSource(connectorModule, settings). For example:
* - new DataSource(connectorModule, {name: 'myDataSource})
* - new DataSource(connectorModule)
2013-05-17 17:54:14 +00:00
*/
function DataSource(name, settings, modelBuilder) {
2014-01-24 17:09:53 +00:00
if (!(this instanceof DataSource)) {
return new DataSource(name, settings);
}
2014-01-24 17:09:53 +00:00
// Check if the settings object is passed as the first argument
if (typeof name === 'object' && settings === undefined) {
settings = name;
name = undefined;
}
2014-01-24 17:09:53 +00:00
// Check if the first argument is a URL
if (typeof name === 'string' && name.indexOf('://') !== -1) {
name = utils.parseSettings(name);
}
2014-01-24 17:09:53 +00:00
// Check if the settings is in the form of URL string
if (typeof settings === 'string' && settings.indexOf('://') !== -1) {
settings = utils.parseSettings(settings);
}
2014-01-24 17:09:53 +00:00
this.modelBuilder = modelBuilder || new ModelBuilder();
this.models = this.modelBuilder.models;
this.definitions = this.modelBuilder.definitions;
this.juggler = juggler;
2014-01-24 17:09:53 +00:00
// operation metadata
// Initialize it before calling setup as the connector might register operations
this._operations = {};
2013-05-17 17:54:14 +00:00
2014-01-24 17:09:53 +00:00
this.setup(name, settings);
2014-01-24 17:09:53 +00:00
this._setupConnector();
// connector
var connector = this.connector;
// DataAccessObject - connector defined or supply the default
var dao = (connector && connector.DataAccessObject) || this.constructor.DataAccessObject;
2016-04-01 11:48:17 +00:00
this.DataAccessObject = function() {
2014-01-24 17:09:53 +00:00
};
// define DataAccessObject methods
2016-04-01 11:48:17 +00:00
Object.keys(dao).forEach(function(name) {
2014-01-24 17:09:53 +00:00
var fn = dao[name];
this.DataAccessObject[name] = fn;
if (typeof fn === 'function') {
this.defineOperation(name, {
accepts: fn.accepts,
'returns': fn.returns,
http: fn.http,
remoteEnabled: fn.shared ? true : false,
scope: this.DataAccessObject,
2016-04-01 11:48:17 +00:00
fnName: name,
2014-01-24 17:09:53 +00:00
});
}
}.bind(this));
// define DataAccessObject.prototype methods
2016-04-01 11:48:17 +00:00
Object.keys(dao.prototype).forEach(function(name) {
2014-01-24 17:09:53 +00:00
var fn = dao.prototype[name];
this.DataAccessObject.prototype[name] = fn;
if (typeof fn === 'function') {
this.defineOperation(name, {
prototype: true,
accepts: fn.accepts,
'returns': fn.returns,
http: fn.http,
remoteEnabled: fn.shared ? true : false,
scope: this.DataAccessObject.prototype,
2016-04-01 11:48:17 +00:00
fnName: name,
2014-01-24 17:09:53 +00:00
});
}
}.bind(this));
}
util.inherits(DataSource, EventEmitter);
2013-05-17 17:54:14 +00:00
// allow child classes to supply a data access object
DataSource.DataAccessObject = DataAccessObject;
2013-07-23 20:19:35 +00:00
/**
* Set up the connector instance for backward compatibility with JugglingDB schema/adapter
* @private
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype._setupConnector = function() {
2014-01-24 17:09:53 +00:00
this.connector = this.connector || this.adapter; // The legacy JugglingDB adapter will set up `adapter` property
this.adapter = this.connector; // Keep the adapter as an alias to connector
if (this.connector) {
if (!this.connector.dataSource) {
// Set up the dataSource if the connector doesn't do so
this.connector.dataSource = this;
2013-07-23 20:19:35 +00:00
}
2014-01-24 17:09:53 +00:00
var dataSource = this;
2016-04-01 11:48:17 +00:00
this.connector.log = function(query, start) {
2014-01-24 17:09:53 +00:00
dataSource.log(query, start);
};
2016-04-01 11:48:17 +00:00
this.connector.logger = function(query) {
2014-01-24 17:09:53 +00:00
var t1 = Date.now();
var log = this.log;
2016-04-01 11:48:17 +00:00
return function(q) {
2014-01-24 17:09:53 +00:00
log(q || query, t1);
};
};
2015-05-20 22:02:44 +00:00
// Configure the connector instance to mix in observer functions
jutil.mixin(this.connector, OberserverMixin);
2014-01-24 17:09:53 +00:00
}
2013-08-13 16:37:09 +00:00
};
2013-07-23 20:19:35 +00:00
// List possible connector module names
function connectorModuleNames(name) {
var names = []; // Check the name as is
if (!name.match(/^\//)) {
names.push('./connectors/' + name); // Check built-in connectors
if (name.indexOf('loopback-connector-') !== 0) {
names.push('loopback-connector-' + name); // Try loopback-connector-<name>
}
}
// Only try the short name if the connector is not from StrongLoop
if (['mongodb', 'oracle', 'mysql', 'postgresql', 'mssql', 'rest', 'soap', 'db2', 'cloudant']
.indexOf(name) === -1) {
names.push(name);
}
return names;
}
// testable with DI
function tryModules(names, loader) {
var mod;
loader = loader || require;
2014-01-24 17:09:53 +00:00
for (var m = 0; m < names.length; m++) {
try {
mod = loader(names[m]);
} catch (e) {
var notFound = e.code === 'MODULE_NOT_FOUND' &&
e.message && e.message.indexOf(names[m]) > 0;
if (notFound) {
debug('Module %s not found, will try another candidate.', names[m]);
continue;
}
debug('Cannot load connector %s: %s', names[m], e.stack || e);
throw e;
}
if (mod) {
break;
}
}
return mod;
}
/*!
* Resolve a connector by name
* @param name The connector name
* @returns {*}
* @private
*/
2016-04-01 11:48:17 +00:00
DataSource._resolveConnector = function(name, loader) {
var names = connectorModuleNames(name);
2014-01-24 17:09:53 +00:00
var connector = tryModules(names, loader);
var error = null;
2014-01-24 17:09:53 +00:00
if (!connector) {
2016-07-22 19:26:07 +00:00
error = g.f('\nWARNING: {{LoopBack}} connector "%s" is not installed ' +
'as any of the following modules:\n\n %s\n\nTo fix, run:\n\n {{npm install %s --save}}\n',
name, names.join('\n'), names[names.length - 1]);
}
return {
connector: connector,
2016-04-01 11:48:17 +00:00
error: error,
};
};
/**
2017-04-18 21:30:13 +00:00
* Connect to the data source.
* If no callback is provided, it will return a Promise.
* Emits the 'connect' event.
* @param callback
2017-04-18 21:30:13 +00:00
* @returns {Promise}
* @emits connected
*/
DataSource.prototype.connect = function(callback) {
callback = callback || utils.createPromiseCallback();
var self = this;
if (this.connected) {
// The data source is already connected, return immediately
process.nextTick(callback);
return callback.promise;
}
if (typeof this.connector.connect !== 'function') {
// Connector doesn't have the connect function
// Assume no connect is needed
self.connected = true;
self.connecting = false;
process.nextTick(function() {
self.emit('connected');
callback();
});
return callback.promise;
}
// Queue the callback
this.pendingConnectCallbacks = this.pendingConnectCallbacks || [];
this.pendingConnectCallbacks.push(callback);
// The connect is already in progress
if (this.connecting) return callback.promise;
// Set connecting flag to be true
this.connecting = true;
this.connector.connect(function(err, result) {
self.connecting = false;
if (!err) self.connected = true;
var cbs = self.pendingConnectCallbacks;
self.pendingConnectCallbacks = [];
if (!err) {
self.emit('connected');
} else {
self.emit('error', err);
}
// Invoke all pending callbacks
async.each(cbs, function(cb, done) {
try {
cb(err);
} catch (e) {
// Ignore error to make sure all callbacks are invoked
debug('Uncaught error raised by connect callback function: ', e);
} finally {
done();
}
}, function(err) {
if (err) throw err; // It should not happen
});
});
return callback.promise;
};
2013-08-13 16:37:09 +00:00
/**
* Set up the data source. The following styles are supported:
* ```js
* ds.setup('myDataSource', {connector: 'memory'}); // ds.name -> 'myDataSource'
* ds.setup('myDataSource', {name: 'myDataSource', connector: 'memory'}); // ds.name -> 'myDataSource'
* ds.setup('myDataSource', {name: 'anotherDataSource', connector: 'memory'}); // ds.name -> 'myDataSource' and a warning will be issued
* ds.setup({name: 'myDataSource', connector: 'memory'}); // ds.name -> 'myDataSource'
* ds.setup({connector: 'memory'}); // ds.name -> 'memory'
* ```
* @param {String} dsName The name of the datasource. If not set, use
* `settings.name`
2013-08-13 16:37:09 +00:00
* @param {Object} settings The settings
* @returns {*}
* @private
*/
DataSource.prototype.setup = function(dsName, settings) {
2014-01-24 17:09:53 +00:00
var dataSource = this;
var connector;
// First argument is an `object`
if (dsName && typeof dsName === 'object') {
if (settings === undefined) {
// setup({name: 'myDataSource', connector: 'memory'})
settings = dsName;
dsName = undefined;
} else {
// setup(connector, {name: 'myDataSource', host: 'localhost'})
connector = dsName;
dsName = undefined;
}
2014-01-24 17:09:53 +00:00
}
2013-05-17 17:54:14 +00:00
if (typeof dsName !== 'string') {
dsName = undefined;
}
2014-01-24 17:09:53 +00:00
if (typeof settings === 'object') {
if (settings.initialize) {
// Settings is the resolved connector instance
2014-01-24 17:09:53 +00:00
connector = settings;
// Set settings to undefined to avoid confusion
settings = undefined;
2014-01-24 17:09:53 +00:00
} else if (settings.connector) {
// Use `connector`
2014-01-24 17:09:53 +00:00
connector = settings.connector;
} else if (settings.adapter) {
// `adapter` as alias for `connector`
2014-01-24 17:09:53 +00:00
connector = settings.adapter;
2013-06-14 20:56:44 +00:00
}
2014-01-24 17:09:53 +00:00
}
// just save everything we get
this.settings = settings || {};
2014-03-04 17:42:55 +00:00
this.settings.debug = this.settings.debug || debug.enabled;
if (this.settings.debug) {
2014-03-04 17:42:55 +00:00
debug('Settings: %j', this.settings);
2014-01-24 17:09:53 +00:00
}
if (typeof settings === 'object' && typeof settings.name === 'string' &&
typeof dsName === 'string' && dsName !== settings.name) {
// setup('myDataSource', {name: 'anotherDataSource', connector: 'memory'});
// ds.name -> 'myDataSource' and a warning will be issued
console.warn(
'A datasource is created with name %j, which is different from the name in settings (%j). ' +
'Please adjust your configuration to ensure these names match.',
dsName, settings.name);
}
2014-01-24 17:09:53 +00:00
// Disconnected by default
this.connected = false;
this.connecting = false;
this.name = dsName || (typeof this.settings.name === 'string' && this.settings.name);
var connectorName;
2014-01-24 17:09:53 +00:00
if (typeof connector === 'string') {
// Connector needs to be resolved by name
connectorName = connector;
2014-01-24 17:09:53 +00:00
connector = undefined;
} else if ((typeof connector === 'object') && connector) {
connectorName = connector.name;
} else {
connectorName = dsName;
2014-01-24 17:09:53 +00:00
}
if (!this.name) {
// Fall back to connector name
this.name = connectorName;
}
if ((!connector) && connectorName) {
// The connector has not been resolved
var result = DataSource._resolveConnector(connectorName);
connector = result.connector;
if (!connector) {
console.error(result.error);
this.emit('error', new Error(result.error));
return;
2013-06-14 20:56:44 +00:00
}
2014-01-24 17:09:53 +00:00
}
2013-05-17 17:54:14 +00:00
2014-01-24 17:09:53 +00:00
if (connector) {
var postInit = function postInit(err, result) {
this._setupConnector();
// we have an connector now?
if (!this.connector) {
2016-07-22 19:26:07 +00:00
throw new Error(g.f('Connector is not defined correctly: ' +
'it should create `{{connector}}` member of dataSource'));
2014-01-24 17:09:53 +00:00
}
this.connected = !err; // Connected now
if (this.connected) {
this.emit('connected');
} else {
// The connection fails, let's report it and hope it will be recovered in the next call
2016-08-08 19:34:41 +00:00
g.error('Connection fails: %s\nIt will be retried for the next request.', err);
this.emit('error', err);
2014-01-24 17:09:53 +00:00
this.connecting = false;
}
}.bind(this);
try {
if ('function' === typeof connector.initialize) {
// Call the async initialize method
connector.initialize(this, postInit);
} else if ('function' === typeof connector) {
// Use the connector constructor directly
this.connector = new connector(this.settings);
postInit();
}
2016-04-01 11:48:17 +00:00
} catch (err) {
if (err.message) {
err.message = 'Cannot initialize connector ' +
JSON.stringify(connectorName) + ': ' +
err.message;
}
throw err;
2013-05-17 17:54:14 +00:00
}
2014-01-24 17:09:53 +00:00
}
2013-08-13 16:37:09 +00:00
};
2013-05-17 17:54:14 +00:00
function isModelClass(cls) {
2014-01-24 17:09:53 +00:00
if (!cls) {
return false;
}
return cls.prototype instanceof ModelBaseClass;
}
DataSource.relationTypes = Object.keys(RelationDefinition.RelationTypes);
2013-11-07 21:30:54 +00:00
function isModelDataSourceAttached(model) {
return model && (!model.settings.unresolved) && (model.dataSource instanceof DataSource);
}
2014-03-04 01:16:37 +00:00
/*!
2017-04-18 21:30:13 +00:00
* Define scopes for the model class from the scopes object. See
* [scopes](./Model-definition-JSON-file.html#scopes) for more information on
* scopes and valid options objects.
* @param {Object} modelClass - The model class that corresponds to the model
* definition that will be enhanced by the provided scopes.
* @param {Object} scopes A key-value collection of names and their object
* definitions
* @property options The options defined on the scope object.
2014-03-04 01:16:37 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.defineScopes = function(modelClass, scopes) {
if (scopes) {
for (var s in scopes) {
2014-08-08 22:52:30 +00:00
defineScope(modelClass, modelClass, s, scopes[s], {}, scopes[s].options);
2014-03-04 01:16:37 +00:00
}
}
};
/*!
2017-04-18 21:30:13 +00:00
* Define relations for the model class from the relations object. See
* [relations](./Model-definition-JSON-file.html#relations) for more information.
* @param {Object} modelClass - The model class that corresponds to the model
* definition that will be enhanced by the provided relations.
* @param {Object} relations A key-value collection of relation names and their
* object definitions.
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.defineRelations = function(modelClass, relations) {
var self = this;
2014-01-24 17:09:53 +00:00
Overall review of polymorphic relations In #1298, the spec/doc for polymorphic relations was reviewed **hasX relation** - `type`: **hasMany** - `as`: redefines **this** relation's name (optional) - `model`: **modelTo** - `polymorphic`: - typeOf `polymorphic` === `String` - matching **belongsTo** relation name - `foreignKey` is generated as `polymorphic + 'Id'`, - `discriminator` is generated as `polymorphic + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED** should display a warning, replaced by `selector` - `selector`: should match **belongsTo** relation name if the latter is defined with {polymorphic: true} - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'` --- **belongsTo relation** - `type`: **belongsTo** - `as`: redefines **this** relation's name (optional) - `model`: **NOT EXPECTED**: should throw an error at relation validation - `polymorphic`: - typeOf `polymorphic` === `Boolean` - `foreignKey` is generated as `relationName + 'Id'`, - `discriminator` is generated as `relationName + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED**: should display a warning, replaced by `selector` - `selector`: - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'`
2017-04-01 09:13:22 +00:00
// Wait for target/through models to be attached before setting up the relation
var deferRelationSetup = function(relationName, relation, targetModel, throughModel) {
2014-01-24 17:09:53 +00:00
if (!isModelDataSourceAttached(targetModel)) {
Overall review of polymorphic relations In #1298, the spec/doc for polymorphic relations was reviewed **hasX relation** - `type`: **hasMany** - `as`: redefines **this** relation's name (optional) - `model`: **modelTo** - `polymorphic`: - typeOf `polymorphic` === `String` - matching **belongsTo** relation name - `foreignKey` is generated as `polymorphic + 'Id'`, - `discriminator` is generated as `polymorphic + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED** should display a warning, replaced by `selector` - `selector`: should match **belongsTo** relation name if the latter is defined with {polymorphic: true} - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'` --- **belongsTo relation** - `type`: **belongsTo** - `as`: redefines **this** relation's name (optional) - `model`: **NOT EXPECTED**: should throw an error at relation validation - `polymorphic`: - typeOf `polymorphic` === `Boolean` - `foreignKey` is generated as `relationName + 'Id'`, - `discriminator` is generated as `relationName + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED**: should display a warning, replaced by `selector` - `selector`: - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'`
2017-04-01 09:13:22 +00:00
targetModel.once('dataAccessConfigured', function(targetModel) {
2014-01-24 17:09:53 +00:00
// Check if the through model doesn't exist or resolved
if (!throughModel || isModelDataSourceAttached(throughModel)) {
// The target model is resolved
var params = traverse(relation).clone();
Overall review of polymorphic relations In #1298, the spec/doc for polymorphic relations was reviewed **hasX relation** - `type`: **hasMany** - `as`: redefines **this** relation's name (optional) - `model`: **modelTo** - `polymorphic`: - typeOf `polymorphic` === `String` - matching **belongsTo** relation name - `foreignKey` is generated as `polymorphic + 'Id'`, - `discriminator` is generated as `polymorphic + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED** should display a warning, replaced by `selector` - `selector`: should match **belongsTo** relation name if the latter is defined with {polymorphic: true} - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'` --- **belongsTo relation** - `type`: **belongsTo** - `as`: redefines **this** relation's name (optional) - `model`: **NOT EXPECTED**: should throw an error at relation validation - `polymorphic`: - typeOf `polymorphic` === `Boolean` - `foreignKey` is generated as `relationName + 'Id'`, - `discriminator` is generated as `relationName + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED**: should display a warning, replaced by `selector` - `selector`: - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'`
2017-04-01 09:13:22 +00:00
params.as = relationName;
params.model = targetModel;
2014-01-24 17:09:53 +00:00
if (throughModel) {
params.through = throughModel;
}
Overall review of polymorphic relations In #1298, the spec/doc for polymorphic relations was reviewed **hasX relation** - `type`: **hasMany** - `as`: redefines **this** relation's name (optional) - `model`: **modelTo** - `polymorphic`: - typeOf `polymorphic` === `String` - matching **belongsTo** relation name - `foreignKey` is generated as `polymorphic + 'Id'`, - `discriminator` is generated as `polymorphic + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED** should display a warning, replaced by `selector` - `selector`: should match **belongsTo** relation name if the latter is defined with {polymorphic: true} - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'` --- **belongsTo relation** - `type`: **belongsTo** - `as`: redefines **this** relation's name (optional) - `model`: **NOT EXPECTED**: should throw an error at relation validation - `polymorphic`: - typeOf `polymorphic` === `Boolean` - `foreignKey` is generated as `relationName + 'Id'`, - `discriminator` is generated as `relationName + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED**: should display a warning, replaced by `selector` - `selector`: - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'`
2017-04-01 09:13:22 +00:00
modelClass[relation.type].call(modelClass, relationName, params);
}
2014-01-24 17:09:53 +00:00
});
}
2016-04-01 13:23:42 +00:00
2014-01-24 17:09:53 +00:00
if (throughModel && !isModelDataSourceAttached(throughModel)) {
// Set up a listener to the through model
Overall review of polymorphic relations In #1298, the spec/doc for polymorphic relations was reviewed **hasX relation** - `type`: **hasMany** - `as`: redefines **this** relation's name (optional) - `model`: **modelTo** - `polymorphic`: - typeOf `polymorphic` === `String` - matching **belongsTo** relation name - `foreignKey` is generated as `polymorphic + 'Id'`, - `discriminator` is generated as `polymorphic + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED** should display a warning, replaced by `selector` - `selector`: should match **belongsTo** relation name if the latter is defined with {polymorphic: true} - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'` --- **belongsTo relation** - `type`: **belongsTo** - `as`: redefines **this** relation's name (optional) - `model`: **NOT EXPECTED**: should throw an error at relation validation - `polymorphic`: - typeOf `polymorphic` === `Boolean` - `foreignKey` is generated as `relationName + 'Id'`, - `discriminator` is generated as `relationName + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED**: should display a warning, replaced by `selector` - `selector`: - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'`
2017-04-01 09:13:22 +00:00
throughModel.once('dataAccessConfigured', function(throughModel) {
2014-01-24 17:09:53 +00:00
if (isModelDataSourceAttached(targetModel)) {
// The target model is resolved
var params = traverse(relation).clone();
Overall review of polymorphic relations In #1298, the spec/doc for polymorphic relations was reviewed **hasX relation** - `type`: **hasMany** - `as`: redefines **this** relation's name (optional) - `model`: **modelTo** - `polymorphic`: - typeOf `polymorphic` === `String` - matching **belongsTo** relation name - `foreignKey` is generated as `polymorphic + 'Id'`, - `discriminator` is generated as `polymorphic + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED** should display a warning, replaced by `selector` - `selector`: should match **belongsTo** relation name if the latter is defined with {polymorphic: true} - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'` --- **belongsTo relation** - `type`: **belongsTo** - `as`: redefines **this** relation's name (optional) - `model`: **NOT EXPECTED**: should throw an error at relation validation - `polymorphic`: - typeOf `polymorphic` === `Boolean` - `foreignKey` is generated as `relationName + 'Id'`, - `discriminator` is generated as `relationName + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED**: should display a warning, replaced by `selector` - `selector`: - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'`
2017-04-01 09:13:22 +00:00
params.as = relationName;
params.model = targetModel;
Overall review of polymorphic relations In #1298, the spec/doc for polymorphic relations was reviewed **hasX relation** - `type`: **hasMany** - `as`: redefines **this** relation's name (optional) - `model`: **modelTo** - `polymorphic`: - typeOf `polymorphic` === `String` - matching **belongsTo** relation name - `foreignKey` is generated as `polymorphic + 'Id'`, - `discriminator` is generated as `polymorphic + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED** should display a warning, replaced by `selector` - `selector`: should match **belongsTo** relation name if the latter is defined with {polymorphic: true} - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'` --- **belongsTo relation** - `type`: **belongsTo** - `as`: redefines **this** relation's name (optional) - `model`: **NOT EXPECTED**: should throw an error at relation validation - `polymorphic`: - typeOf `polymorphic` === `Boolean` - `foreignKey` is generated as `relationName + 'Id'`, - `discriminator` is generated as `relationName + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED**: should display a warning, replaced by `selector` - `selector`: - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'`
2017-04-01 09:13:22 +00:00
params.through = throughModel;
modelClass[relation.type].call(modelClass, relationName, params);
}
2014-01-24 17:09:53 +00:00
});
}
};
2014-01-24 17:09:53 +00:00
// Set up the relations
if (relations) {
Overall review of polymorphic relations In #1298, the spec/doc for polymorphic relations was reviewed **hasX relation** - `type`: **hasMany** - `as`: redefines **this** relation's name (optional) - `model`: **modelTo** - `polymorphic`: - typeOf `polymorphic` === `String` - matching **belongsTo** relation name - `foreignKey` is generated as `polymorphic + 'Id'`, - `discriminator` is generated as `polymorphic + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED** should display a warning, replaced by `selector` - `selector`: should match **belongsTo** relation name if the latter is defined with {polymorphic: true} - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'` --- **belongsTo relation** - `type`: **belongsTo** - `as`: redefines **this** relation's name (optional) - `model`: **NOT EXPECTED**: should throw an error at relation validation - `polymorphic`: - typeOf `polymorphic` === `Boolean` - `foreignKey` is generated as `relationName + 'Id'`, - `discriminator` is generated as `relationName + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED**: should display a warning, replaced by `selector` - `selector`: - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'`
2017-04-01 09:13:22 +00:00
Object.keys(relations).forEach(function(relationName) {
var targetModel;
var r = relations[relationName];
Overall review of polymorphic relations In #1298, the spec/doc for polymorphic relations was reviewed **hasX relation** - `type`: **hasMany** - `as`: redefines **this** relation's name (optional) - `model`: **modelTo** - `polymorphic`: - typeOf `polymorphic` === `String` - matching **belongsTo** relation name - `foreignKey` is generated as `polymorphic + 'Id'`, - `discriminator` is generated as `polymorphic + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED** should display a warning, replaced by `selector` - `selector`: should match **belongsTo** relation name if the latter is defined with {polymorphic: true} - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'` --- **belongsTo relation** - `type`: **belongsTo** - `as`: redefines **this** relation's name (optional) - `model`: **NOT EXPECTED**: should throw an error at relation validation - `polymorphic`: - typeOf `polymorphic` === `Boolean` - `foreignKey` is generated as `relationName + 'Id'`, - `discriminator` is generated as `relationName + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED**: should display a warning, replaced by `selector` - `selector`: - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'`
2017-04-01 09:13:22 +00:00
validateRelation(relationName, r);
if (r.model) {
targetModel = isModelClass(r.model) ? r.model : self.getModel(r.model, true);
}
2014-01-24 17:09:53 +00:00
var throughModel = null;
if (r.through) {
throughModel = isModelClass(r.through) ? r.through : self.getModel(r.through, true);
2014-01-24 17:09:53 +00:00
}
2016-04-01 13:23:42 +00:00
if ((targetModel && !isModelDataSourceAttached(targetModel)) ||
(throughModel && !isModelDataSourceAttached(throughModel))) {
2014-01-24 17:09:53 +00:00
// Create a listener to defer the relation set up
Overall review of polymorphic relations In #1298, the spec/doc for polymorphic relations was reviewed **hasX relation** - `type`: **hasMany** - `as`: redefines **this** relation's name (optional) - `model`: **modelTo** - `polymorphic`: - typeOf `polymorphic` === `String` - matching **belongsTo** relation name - `foreignKey` is generated as `polymorphic + 'Id'`, - `discriminator` is generated as `polymorphic + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED** should display a warning, replaced by `selector` - `selector`: should match **belongsTo** relation name if the latter is defined with {polymorphic: true} - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'` --- **belongsTo relation** - `type`: **belongsTo** - `as`: redefines **this** relation's name (optional) - `model`: **NOT EXPECTED**: should throw an error at relation validation - `polymorphic`: - typeOf `polymorphic` === `Boolean` - `foreignKey` is generated as `relationName + 'Id'`, - `discriminator` is generated as `relationName + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED**: should display a warning, replaced by `selector` - `selector`: - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'`
2017-04-01 09:13:22 +00:00
deferRelationSetup(relationName, r, targetModel, throughModel);
2014-01-24 17:09:53 +00:00
} else {
// The target model is resolved
var params = traverse(r).clone();
Overall review of polymorphic relations In #1298, the spec/doc for polymorphic relations was reviewed **hasX relation** - `type`: **hasMany** - `as`: redefines **this** relation's name (optional) - `model`: **modelTo** - `polymorphic`: - typeOf `polymorphic` === `String` - matching **belongsTo** relation name - `foreignKey` is generated as `polymorphic + 'Id'`, - `discriminator` is generated as `polymorphic + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED** should display a warning, replaced by `selector` - `selector`: should match **belongsTo** relation name if the latter is defined with {polymorphic: true} - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'` --- **belongsTo relation** - `type`: **belongsTo** - `as`: redefines **this** relation's name (optional) - `model`: **NOT EXPECTED**: should throw an error at relation validation - `polymorphic`: - typeOf `polymorphic` === `Boolean` - `foreignKey` is generated as `relationName + 'Id'`, - `discriminator` is generated as `relationName + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED**: should display a warning, replaced by `selector` - `selector`: - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'`
2017-04-01 09:13:22 +00:00
params.as = relationName;
params.model = targetModel;
2014-01-24 17:09:53 +00:00
if (throughModel) {
params.through = throughModel;
}
Overall review of polymorphic relations In #1298, the spec/doc for polymorphic relations was reviewed **hasX relation** - `type`: **hasMany** - `as`: redefines **this** relation's name (optional) - `model`: **modelTo** - `polymorphic`: - typeOf `polymorphic` === `String` - matching **belongsTo** relation name - `foreignKey` is generated as `polymorphic + 'Id'`, - `discriminator` is generated as `polymorphic + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED** should display a warning, replaced by `selector` - `selector`: should match **belongsTo** relation name if the latter is defined with {polymorphic: true} - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'` --- **belongsTo relation** - `type`: **belongsTo** - `as`: redefines **this** relation's name (optional) - `model`: **NOT EXPECTED**: should throw an error at relation validation - `polymorphic`: - typeOf `polymorphic` === `Boolean` - `foreignKey` is generated as `relationName + 'Id'`, - `discriminator` is generated as `relationName + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED**: should display a warning, replaced by `selector` - `selector`: - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'`
2017-04-01 09:13:22 +00:00
modelClass[r.type].call(modelClass, relationName, params);
2014-01-24 17:09:53 +00:00
}
});
2014-01-24 17:09:53 +00:00
}
};
Overall review of polymorphic relations In #1298, the spec/doc for polymorphic relations was reviewed **hasX relation** - `type`: **hasMany** - `as`: redefines **this** relation's name (optional) - `model`: **modelTo** - `polymorphic`: - typeOf `polymorphic` === `String` - matching **belongsTo** relation name - `foreignKey` is generated as `polymorphic + 'Id'`, - `discriminator` is generated as `polymorphic + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED** should display a warning, replaced by `selector` - `selector`: should match **belongsTo** relation name if the latter is defined with {polymorphic: true} - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'` --- **belongsTo relation** - `type`: **belongsTo** - `as`: redefines **this** relation's name (optional) - `model`: **NOT EXPECTED**: should throw an error at relation validation - `polymorphic`: - typeOf `polymorphic` === `Boolean` - `foreignKey` is generated as `relationName + 'Id'`, - `discriminator` is generated as `relationName + 'Type'` - typeOf `polymorphic` === `Object` - `as`: **DEPRECATED**: should display a warning, replaced by `selector` - `selector`: - (required) if both foreignKey and discriminator are **NOT** provided - (extraneous) if both foreignKey and discriminator are provided - `foreignKey`: A property of modelTo, representing the fk to modelFrom's id. - generated by default as `selector + 'Id'` - `discriminator`: A property of modelTo, representing the actual modelFrom to be looked up and defined dynamically - generated by default as `selector + 'Type'`
2017-04-01 09:13:22 +00:00
function validateRelation(relationName, relation) {
var rn = relationName;
var r = relation;
var msg, code;
assert(DataSource.relationTypes.indexOf(r.type) !== -1, 'Invalid relation type: ' + r.type);
assert(isValidRelationName(rn), 'Invalid relation name: ' + rn);
// VALIDATION ERRORS
// non polymorphic belongsTo relations should have `model` defined
if (!r.polymorphic && r.type === 'belongsTo' && !r.model) {
msg = g.f('%s relation: %s requires param `model`', r.type, rn);
code = 'BELONGS_TO_MISSING_MODEL';
}
// polymorphic belongsTo relations should not have `model` defined
if (r.polymorphic && r.type === 'belongsTo' && r.model) {
msg = g.f('{{polymorphic}} %s relation: %s does not expect param `model`', r.type, rn);
code = 'POLYMORPHIC_BELONGS_TO_MODEL';
}
// polymorphic relations other than belongsTo should have `model` defined
if (r.polymorphic && r.type !== 'belongsTo' && !r.model) {
msg = g.f('{{polymorphic}} %s relation: %s requires param `model`', r.type, rn);
code = 'POLYMORPHIC_NOT_BELONGS_TO_MISSING_MODEL';
}
// polymorphic relations should provide both discriminator and foreignKey or none
if (r.polymorphic && r.polymorphic.foreignKey && !r.polymorphic.discriminator) {
msg = g.f('{{polymorphic}} %s relation: %s requires param `polymorphic.discriminator` ' +
'when param `polymorphic.foreignKey` is provided', r.type, rn);
code = 'POLYMORPHIC_MISSING_DISCRIMINATOR';
}
// polymorphic relations should provide both discriminator and foreignKey or none
if (r.polymorphic && r.polymorphic.discriminator && !r.polymorphic.foreignKey) {
msg = g.f('{{polymorphic}} %s relation: %s requires param `polymorphic.foreignKey` ' +
'when param `polymorphic.discriminator` is provided', r.type, rn);
code = 'POLYMORPHIC_MISSING_FOREIGN_KEY';
}
// polymorphic relations should not provide polymorphic.as when using custom foreignKey/discriminator
if (r.polymorphic && r.polymorphic.as && r.polymorphic.foreignKey) {
msg = g.f('{{polymorphic}} %s relation: %s does not expect param `polymorphic.as` ' +
'when defing custom `foreignKey`/`discriminator` ', r.type, rn);
code = 'POLYMORPHIC_EXTRANEOUS_AS';
}
// polymorphic relations should not provide polymorphic.as when using custom foreignKey/discriminator
if (r.polymorphic && r.polymorphic.selector && r.polymorphic.foreignKey) {
msg = g.f('{{polymorphic}} %s relation: %s does not expect param `polymorphic.selector` ' +
'when defing custom `foreignKey`/`discriminator` ', r.type, rn);
code = 'POLYMORPHIC_EXTRANEOUS_SELECTOR';
}
if (msg) {
var error = new Error(msg);
error.details = {code: code, rType: r.type, rName: rn};
throw error;
}
// DEPRECATION WARNINGS
if (r.polymorphic && r.polymorphic.as) {
deprecated(g.f('WARNING: {{polymorphic}} %s relation: %s uses keyword `polymorphic.as` which will ' +
'be DEPRECATED in LoopBack.next, refer to this doc for replacement solutions ' +
'(https://loopback.io/doc/en/lb3/Polymorphic-relations.html#deprecated-polymorphic-as)',
r.type, rn), r.type);
}
}
function isValidRelationName(relationName) {
var invalidRelationNames = ['trigger'];
return invalidRelationNames.indexOf(relationName) === -1;
}
/*!
2017-04-18 21:30:13 +00:00
* Set up the data access functions from the data source. Each data source will
* expose a data access object (DAO), which will be mixed into the modelClass.
* @param {Model} modelClass The model class that will receive DAO mixins.
* @param {Object} settings The settings object; typically allows any settings
* that would be valid for a typical Model object.
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.setupDataAccess = function(modelClass, settings) {
if (this.connector) {
// Check if the id property should be generated
var idName = modelClass.definition.idName();
var idProp = modelClass.definition.rawProperties[idName];
if (idProp && idProp.generated && this.connector.getDefaultIdType) {
// Set the default id type from connector's ability
var idType = this.connector.getDefaultIdType() || String;
idProp.type = idType;
modelClass.definition.rawProperties[idName].type = idType;
modelClass.definition.properties[idName].type = idType;
}
if (this.connector.define) {
// pass control to connector
this.connector.define({
model: modelClass,
properties: modelClass.definition.properties,
2016-04-01 11:48:17 +00:00
settings: settings,
});
}
2014-01-24 17:09:53 +00:00
}
2014-01-24 17:09:53 +00:00
// add data access objects
this.mixin(modelClass);
// define relations from LDL (options.relations)
2014-01-24 17:09:53 +00:00
var relations = settings.relationships || settings.relations;
this.defineRelations(modelClass, relations);
// Emit the dataAccessConfigured event to indicate all the methods for data
// access have been mixed into the model class
modelClass.emit('dataAccessConfigured', modelClass);
// define scopes from LDL (options.relations)
2014-03-04 01:16:37 +00:00
var scopes = settings.scopes || {};
this.defineScopes(modelClass, scopes);
};
2013-05-17 17:54:14 +00:00
/**
* Define a model class. Returns newly created model object.
* The first (String) argument specifying the model name is required.
* You can provide one or two JSON object arguments, to provide configuration options.
* See [Model definition reference](http://docs.strongloop.com/display/DOC/Model+definition+reference) for details.
*
2014-03-12 23:28:46 +00:00
* Simple example:
2013-05-17 17:54:14 +00:00
* ```
2014-03-12 23:28:46 +00:00
* var User = dataSource.createModel('User', {
2013-05-17 17:54:14 +00:00
* email: String,
* password: String,
* birthDate: Date,
* activated: Boolean
* });
* ```
2014-03-12 23:28:46 +00:00
* More advanced example
2013-05-17 17:54:14 +00:00
* ```
2014-03-12 23:28:46 +00:00
* var User = dataSource.createModel('User', {
2013-05-17 17:54:14 +00:00
* email: { type: String, limit: 150, index: true },
* password: { type: String, limit: 50 },
* birthDate: Date,
* registrationDate: {type: Date, default: function () { return new Date }},
* activated: { type: Boolean, default: false }
* });
* ```
2014-03-12 23:28:46 +00:00
* You can also define an ACL when you create a new data source with the `DataSource.create()` method. For example:
*
2014-03-12 23:28:46 +00:00
* ```js
* var Customer = ds.createModel('Customer', {
* name: {
* type: String,
* acls: [
* {principalType: ACL.USER, principalId: 'u001', accessType: ACL.WRITE, permission: ACL.DENY},
* {principalType: ACL.USER, principalId: 'u001', accessType: ACL.ALL, permission: ACL.ALLOW}
* ]
* }
* }, {
* acls: [
* {principalType: ACL.USER, principalId: 'u001', accessType: ACL.ALL, permission: ACL.ALLOW}
* ]
* });
* ```
*
* @param {String} className Name of the model to create.
* @param {Object} properties Hash of model properties in format `{property: Type, property2: Type2, ...}` or `{property: {type: Type}, property2: {type: Type2}, ...}`
* @options {Object} properties Other configuration options. This corresponds to the options key in the config object.
2017-04-18 21:30:13 +00:00
* @param {Object} settings A settings object that would typically be used for Model objects.
2013-05-17 17:54:14 +00:00
*/
2013-08-13 16:37:09 +00:00
2016-04-01 13:23:42 +00:00
DataSource.prototype.createModel =
DataSource.prototype.define = function defineClass(className, properties, settings) {
2014-01-24 17:09:53 +00:00
var args = slice.call(arguments);
2013-05-17 21:41:04 +00:00
2014-01-24 17:09:53 +00:00
if (!className) {
2016-07-22 19:26:07 +00:00
throw new Error(g.f('Class name required'));
2014-01-24 17:09:53 +00:00
}
if (args.length === 1) {
properties = {};
args.push(properties);
}
if (args.length === 2) {
settings = {};
args.push(settings);
}
2013-05-17 21:41:04 +00:00
2014-01-24 17:09:53 +00:00
properties = properties || {};
settings = settings || {};
2013-05-17 21:41:04 +00:00
2014-01-24 17:09:53 +00:00
if (this.isRelational()) {
// Set the strict mode to be true for relational DBs by default
if (settings.strict === undefined || settings.strict === null) {
settings.strict = true;
}
2014-01-24 17:09:53 +00:00
if (settings.strict === false) {
settings.strict = 'throw';
}
2014-01-24 17:09:53 +00:00
}
2014-01-24 17:09:53 +00:00
var modelClass = this.modelBuilder.define(className, properties, settings);
modelClass.dataSource = this;
2014-01-24 17:09:53 +00:00
if (settings.unresolved) {
return modelClass;
2014-01-24 17:09:53 +00:00
}
2013-05-17 17:54:14 +00:00
2014-01-24 17:09:53 +00:00
this.setupDataAccess(modelClass, settings);
modelClass.emit('dataSourceAttached', modelClass);
return modelClass;
};
2013-06-14 20:56:44 +00:00
/**
* Mixin DataAccessObject methods.
2013-08-13 16:37:09 +00:00
*
* @param {Function} ModelCtor The model constructor
2014-06-10 21:27:58 +00:00
* @private
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.mixin = function(ModelCtor) {
2013-06-11 16:03:11 +00:00
var ops = this.operations();
var DAO = this.DataAccessObject;
2014-01-24 17:09:53 +00:00
// mixin DAO
2016-08-19 17:46:59 +00:00
jutil.mixin(ModelCtor, DAO, {proxyFunctions: true, override: true});
2014-01-24 17:09:53 +00:00
// decorate operations as alias functions
2016-04-01 11:48:17 +00:00
Object.keys(ops).forEach(function(name) {
2013-06-11 16:03:11 +00:00
var op = ops[name];
var scope;
2014-01-24 17:09:53 +00:00
if (op.enabled) {
2013-06-11 16:03:11 +00:00
scope = op.prototype ? ModelCtor.prototype : ModelCtor;
// var sfn = scope[name] = function () {
// op.scope[op.fnName].apply(self, arguments);
// }
Object.keys(op)
2016-04-01 11:48:17 +00:00
.filter(function(key) {
// filter out the following keys
2014-01-24 17:09:53 +00:00
return ~[
'scope',
'fnName',
2016-04-01 11:48:17 +00:00
'prototype',
].indexOf(key);
})
2016-04-01 11:48:17 +00:00
.forEach(function(key) {
2014-01-24 17:09:53 +00:00
if (typeof op[key] !== 'undefined') {
op.scope[op.fnName][key] = op[key];
2013-06-11 16:03:11 +00:00
}
});
2013-06-11 16:03:11 +00:00
}
});
};
2017-04-26 20:43:44 +00:00
/*! Method will be deprecated in LoopBack.next
*/
/**
2017-04-18 21:30:13 +00:00
* See [ModelBuilder.getModel](http://apidocs.strongloop.com/loopback-datasource-juggler/#modelbuilder-prototype-getmodel)
* for details.
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.getModel = function(name, forceCreate) {
2014-01-24 17:09:53 +00:00
return this.modelBuilder.getModel(name, forceCreate);
};
2017-04-26 20:43:44 +00:00
/*! Method will be deprecated in LoopBack.next
*/
/**
2014-03-12 23:28:46 +00:00
* See ModelBuilder.getModelDefinition
2017-04-18 21:30:13 +00:00
* See [ModelBuilder.getModelDefinition](http://apidocs.strongloop.com/loopback-datasource-juggler/#modelbuilder-prototype-getmodeldefinition)
* for details.
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.getModelDefinition = function(name) {
2014-01-24 17:09:53 +00:00
return this.modelBuilder.getModelDefinition(name);
};
2017-04-26 20:43:44 +00:00
/*! Method will be deprecated in LoopBack.next
*/
/**
2017-04-18 21:30:13 +00:00
* Get the data source types collection.
* @returns {String[]} The data source type array.
* For example, ['db', 'nosql', 'mongodb'] would be represent a datasource of
* type 'db', with a subtype of 'nosql', and would use the 'mongodb' connector.
*
* Alternatively, ['rest'] would be a different type altogether, and would have
* no subtype.
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.getTypes = function() {
var getTypes = this.connector && this.connector.getTypes;
var types = getTypes && getTypes() || [];
if (typeof types === 'string') {
types = types.split(/[\s,\/]+/);
}
return types;
};
/**
2014-03-12 23:28:46 +00:00
* Check the data source supports the specified types.
2017-04-18 21:30:13 +00:00
* @param {String|String[]} types Type name or an array of type names.
2014-03-12 23:28:46 +00:00
* @returns {Boolean} true if all types are supported by the data source
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.supportTypes = function(types) {
var supportedTypes = this.getTypes();
if (Array.isArray(types)) {
// Check each of the types
for (var i = 0; i < types.length; i++) {
if (supportedTypes.indexOf(types[i]) === -1) {
// Not supported
return false;
}
}
return true;
} else {
// The types is a string
return supportedTypes.indexOf(types) !== -1;
}
};
2017-04-26 20:43:44 +00:00
/*! In future versions, this will not maintain a strict 1:1 relationship between datasources and model classes
* Moving forward, we will allow a model to be attached to a datasource. The model itself becomes a template.
*/
/**
* Attach an existing model to a data source.
2017-04-18 21:30:13 +00:00
* This will mixin all of the data access object functions (DAO) into your
* modelClass definition.
* @param {Function} modelClass The model constructor that will be enhanced by
* DAO mixins.
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.attach = function(modelClass) {
2014-01-24 17:09:53 +00:00
if (modelClass.dataSource === this) {
// Already attached to the data source
return modelClass;
}
2014-01-24 17:09:53 +00:00
if (modelClass.modelBuilder !== this.modelBuilder) {
this.modelBuilder.definitions[modelClass.modelName] = modelClass.definition;
this.modelBuilder.models[modelClass.modelName] = modelClass;
// reset the modelBuilder
modelClass.modelBuilder = this.modelBuilder;
}
// redefine the dataSource
modelClass.dataSource = this;
this.setupDataAccess(modelClass, modelClass.settings);
2013-11-12 06:06:43 +00:00
modelClass.emit('dataSourceAttached', modelClass);
return modelClass;
2013-08-13 16:37:09 +00:00
};
2017-04-26 20:43:44 +00:00
/*! Method will be deprecated in LoopBack.next
*/
2013-05-17 21:41:04 +00:00
/**
2017-04-18 21:30:13 +00:00
* Define a property with name `prop` on a target `model`. See
* [Properties](./Model-definition-JSON-file.html#properties) for more information
* regarding valid options for `params`.
2014-03-12 23:28:46 +00:00
* @param {String} model Name of model
* @param {String} prop Name of property
2017-04-18 21:30:13 +00:00
* @param {Property} params Property settings
2013-05-17 21:41:04 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.defineProperty = function(model, prop, params) {
2014-01-24 17:09:53 +00:00
this.modelBuilder.defineProperty(model, prop, params);
2013-05-17 21:41:04 +00:00
2014-01-24 17:09:53 +00:00
var resolvedProp = this.getModelDefinition(model).properties[prop];
2014-03-04 17:42:55 +00:00
if (this.connector && this.connector.defineProperty) {
2014-01-24 17:09:53 +00:00
this.connector.defineProperty(model, prop, resolvedProp);
}
2013-05-17 21:41:04 +00:00
};
2013-05-17 17:54:14 +00:00
/**
2017-04-18 21:30:13 +00:00
* Drop schema objects such as tables, indexes, views, triggers, etc that correspond
* to model definitions attached to this DataSource instance, specified by the `models` parameter.
*
* **WARNING**: In many situations, this will destroy data! `autoupdate()` will attempt to preserve
* data while updating the schema on your target DataSource, but this is not guaranteed to be safe.
*
2017-04-18 21:30:13 +00:00
* Please check the documentation for your specific connector(s) for a detailed breakdown of
* behaviors for automigrate!
*
2017-04-18 21:30:13 +00:00
* @param {String|String[]} [models] Model(s) to migrate. If not present, apply to all models.
2014-06-10 21:27:58 +00:00
* @param {Function} [callback] Callback function. Optional.
*
2013-05-17 17:54:14 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.automigrate = function(models, cb) {
2014-01-24 17:09:53 +00:00
this.freeze();
if ((!cb) && ('function' === typeof models)) {
cb = models;
models = undefined;
}
2015-06-15 07:43:47 +00:00
cb = cb || utils.createPromiseCallback();
if (!this.connector.automigrate) {
// NOOP
2015-06-15 07:43:47 +00:00
process.nextTick(cb);
return cb.promise;
}
// First argument is a model name
if ('string' === typeof models) {
models = [models];
}
var attachedModels = this.connector._models;
if (attachedModels && typeof attachedModels === 'object') {
models = models || Object.keys(attachedModels);
if (models.length === 0) {
2015-06-15 07:43:47 +00:00
process.nextTick(cb);
return cb.promise;
}
2016-04-01 11:48:17 +00:00
var invalidModels = models.filter(function(m) {
return !(m in attachedModels);
});
if (invalidModels.length) {
2016-04-01 11:48:17 +00:00
process.nextTick(function() {
2016-07-22 19:26:07 +00:00
cb(new Error(g.f('Cannot migrate models not attached to this datasource: %s',
invalidModels.join(' '))));
});
2015-06-15 07:43:47 +00:00
return cb.promise;
2013-05-17 17:54:14 +00:00
}
2014-01-24 17:09:53 +00:00
}
this.connector.automigrate(models, cb);
2015-06-15 07:43:47 +00:00
return cb.promise;
2013-05-17 17:54:14 +00:00
};
/**
* Update existing database tables.
2014-06-10 21:27:58 +00:00
* This method applies only to database connectors.
*
2017-04-18 21:30:13 +00:00
* **WARNING**: `autoupdate()` will attempt to preserve data while updating the
* schema on your target DataSource, but this is not guaranteed to be safe.
*
* Please check the documentation for your specific connector(s) for a detailed breakdown of
* behaviors for automigrate!*
*
* @param {String|String[]} [models] Model(s) to migrate. If not present, apply to all models.
2013-08-13 16:37:09 +00:00
* @param {Function} [cb] The callback function
2013-05-17 17:54:14 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.autoupdate = function(models, cb) {
2014-01-24 17:09:53 +00:00
this.freeze();
if ((!cb) && ('function' === typeof models)) {
cb = models;
models = undefined;
}
2015-06-23 10:14:34 +00:00
cb = cb || utils.createPromiseCallback();
if (!this.connector.autoupdate) {
// NOOP
2015-06-23 10:14:34 +00:00
process.nextTick(cb);
return cb.promise;
}
// First argument is a model name
if ('string' === typeof models) {
models = [models];
}
var attachedModels = this.connector._models;
if (attachedModels && typeof attachedModels === 'object') {
models = models || Object.keys(attachedModels);
if (models.length === 0) {
2015-06-23 10:14:34 +00:00
process.nextTick(cb);
return cb.promise;
}
2016-04-01 11:48:17 +00:00
var invalidModels = models.filter(function(m) {
return !(m in attachedModels);
});
if (invalidModels.length) {
2016-04-01 11:48:17 +00:00
process.nextTick(function() {
2016-07-22 19:26:07 +00:00
cb(new Error(g.f('Cannot migrate models not attached to this datasource: %s',
invalidModels.join(' '))));
});
2015-06-23 10:14:34 +00:00
return cb.promise;
2013-05-17 17:54:14 +00:00
}
2014-01-24 17:09:53 +00:00
}
this.connector.autoupdate(models, cb);
2015-06-23 10:14:34 +00:00
return cb.promise;
2013-05-17 17:54:14 +00:00
};
/**
* Discover existing database tables.
* This method returns an array of model objects, including {type, name, onwer}
2013-08-13 16:37:09 +00:00
*
2014-06-10 21:27:58 +00:00
* @options {Object} options Discovery options. See below.
* @param {Function} Callback function. Optional.
* @property {String} owner/schema The owner or schema to discover from.
* @property {Boolean} all If true, discover all models; if false, discover only models owned by the current user.
* @property {Boolean} views If true, include views; if false, only tables.
* @property {Number} limit Page size
* @property {Number} offset Starting index
2017-04-18 21:30:13 +00:00
* @returns {ModelDefinition[]}
2013-05-17 17:54:14 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.discoverModelDefinitions = function(options, cb) {
2014-01-24 17:09:53 +00:00
this.freeze();
2015-06-25 08:38:15 +00:00
if (cb === undefined && typeof options === 'function') {
cb = options;
options = {};
}
options = options || {};
cb = cb || utils.createPromiseCallback();
2014-01-24 17:09:53 +00:00
if (this.connector.discoverModelDefinitions) {
this.connector.discoverModelDefinitions(options, cb);
} else if (cb) {
2014-03-04 17:42:55 +00:00
process.nextTick(cb);
2014-01-24 17:09:53 +00:00
}
2015-06-25 08:38:15 +00:00
return cb.promise;
2013-05-17 17:54:14 +00:00
};
2017-04-26 20:43:44 +00:00
/*! Method will be completely removed in LoopBack.next
*/
2013-08-13 16:37:09 +00:00
/**
2014-06-10 21:27:58 +00:00
* The synchronous version of discoverModelDefinitions.
* @options {Object} options The options
* @property {Boolean} all If true, discover all models; if false, discover only models owned by the current user.
* @property {Boolean} views If true, nclude views; if false, only tables.
* @property {Number} limit Page size
* @property {Number} offset Starting index
2017-04-18 21:30:13 +00:00
* @returns {ModelDefinition[]}
2013-08-13 16:37:09 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.discoverModelDefinitionsSync = function(options) {
2014-01-24 17:09:53 +00:00
this.freeze();
if (this.connector.discoverModelDefinitionsSync) {
return this.connector.discoverModelDefinitionsSync(options);
}
return null;
2013-06-02 06:03:25 +00:00
};
2013-05-17 17:54:14 +00:00
/**
* Discover properties for a given model.
2013-08-13 16:37:09 +00:00
*
2014-06-10 21:27:58 +00:00
* Callback function return value is an object that can have the following properties:
2013-08-13 16:37:09 +00:00
*
2014-06-10 21:27:58 +00:00
*| Key | Type | Description |
*|-----|------|-------------|
*|owner | String | Database owner or schema|
*|tableName | String | Table/view name|
*|columnName | String | Column name|
*|dataType | String | Data type|
*|dataLength | Number | Data length|
*|dataPrecision | Number | Numeric data precision|
*|dataScale |Number | Numeric data scale|
*|nullable |Boolean | If true, then the data can be null|
2017-04-18 21:30:13 +00:00
* See [Properties](./Model-definition-JSON-file.html#properties) for more
* details on the Property return type.
2013-08-13 16:37:09 +00:00
* @param {String} modelName The table/view name
2014-06-10 21:27:58 +00:00
* @options {Object} options The options
* @property {String} owner|schema The database owner or schema
2014-03-12 23:28:46 +00:00
* @param {Function} cb Callback function. Optional
2017-04-18 21:30:13 +00:00
* @callback cb
* @returns {Promise} A promise that returns an array of Properties (Property[])
2013-08-13 16:37:09 +00:00
*
2013-05-17 17:54:14 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.discoverModelProperties = function(modelName, options, cb) {
2013-05-17 17:54:14 +00:00
this.freeze();
2015-06-25 08:38:15 +00:00
if (cb === undefined && typeof options === 'function') {
cb = options;
options = {};
}
options = options || {};
cb = cb || utils.createPromiseCallback();
if (this.connector.discoverModelProperties) {
2014-01-24 17:09:53 +00:00
this.connector.discoverModelProperties(modelName, options, cb);
2013-05-17 17:54:14 +00:00
} else if (cb) {
2014-03-04 17:42:55 +00:00
process.nextTick(cb);
2013-05-17 17:54:14 +00:00
}
2016-04-01 11:48:17 +00:00
return cb.promise;
2013-05-17 17:54:14 +00:00
};
2017-04-26 20:43:44 +00:00
/*! Method will be completely removed in LoopBack.next
*/
2013-08-13 16:37:09 +00:00
/**
* The synchronous version of discoverModelProperties
* @param {String} modelName The table/view name
* @param {Object} options The options
* @returns {*}
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.discoverModelPropertiesSync = function(modelName, options) {
2014-01-24 17:09:53 +00:00
this.freeze();
if (this.connector.discoverModelPropertiesSync) {
return this.connector.discoverModelPropertiesSync(modelName, options);
}
return null;
2013-06-02 06:03:25 +00:00
};
2013-05-17 17:54:14 +00:00
/**
2014-03-12 23:28:46 +00:00
* Discover primary keys for a given owner/modelName.
2014-06-10 21:27:58 +00:00
* Callback function return value is an object that can have the following properties:
2013-05-17 17:54:14 +00:00
*
2014-06-10 21:27:58 +00:00
*| Key | Type | Description |
*|-----|------|-------------|
*| owner |String | Table schema or owner (may be null). Owner defaults to current user.
*| tableName |String| Table name
*| columnName |String| Column name
*| keySeq |Number| Sequence number within primary key (1 indicates the first column in the primary key; 2 indicates the second column in the primary key).
*| pkName |String| Primary key name (may be null)
2017-04-18 21:30:13 +00:00
* See [ID Properties](./Model-definition-JSON-file.html#id-properties) for more
* information.
2013-08-13 16:37:09 +00:00
* @param {String} modelName The model name
2014-06-10 21:27:58 +00:00
* @options {Object} options The options
* @property {String} owner|schema The database owner or schema
2013-08-13 16:37:09 +00:00
* @param {Function} [cb] The callback function
2017-04-18 21:30:13 +00:00
* @returns {Promise} A promise with an array of Primary Keys (Property[])
2013-05-17 17:54:14 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.discoverPrimaryKeys = function(modelName, options, cb) {
2014-01-24 17:09:53 +00:00
this.freeze();
2015-06-25 08:38:15 +00:00
if (cb === undefined && typeof options === 'function') {
cb = options;
options = {};
}
options = options || {};
cb = cb || utils.createPromiseCallback();
2014-01-24 17:09:53 +00:00
if (this.connector.discoverPrimaryKeys) {
this.connector.discoverPrimaryKeys(modelName, options, cb);
} else if (cb) {
2014-03-04 17:42:55 +00:00
process.nextTick(cb);
2014-01-24 17:09:53 +00:00
}
2015-06-25 08:38:15 +00:00
return cb.promise;
2013-08-13 16:37:09 +00:00
};
2013-05-17 17:54:14 +00:00
2017-04-26 20:43:44 +00:00
/*! Method will be completely removed in LoopBack.next
*/
2013-08-13 16:37:09 +00:00
/**
* The synchronous version of discoverPrimaryKeys
* @param {String} modelName The model name
2014-06-10 21:27:58 +00:00
* @options {Object} options The options
2017-04-18 21:30:13 +00:00
* @property {String} owner|schema The database owner or schema
2013-08-13 16:37:09 +00:00
* @returns {*}
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.discoverPrimaryKeysSync = function(modelName, options) {
2014-01-24 17:09:53 +00:00
this.freeze();
if (this.connector.discoverPrimaryKeysSync) {
return this.connector.discoverPrimaryKeysSync(modelName, options);
}
return null;
2013-08-13 16:37:09 +00:00
};
2013-06-02 06:03:25 +00:00
2013-05-17 17:54:14 +00:00
/**
* Discover foreign keys for a given owner/modelName
2013-05-17 17:54:14 +00:00
*
2014-06-10 21:27:58 +00:00
* Callback function return value is an object that can have the following properties:
2013-08-13 16:37:09 +00:00
*
2014-06-10 21:27:58 +00:00
*| Key | Type | Description |
*|-----|------|-------------|
*|fkOwner |String | Foreign key table schema (may be null)
*|fkName |String | Foreign key name (may be null)
*|fkTableName |String | Foreign key table name
*|fkColumnName |String | Foreign key column name
*|keySeq |Number | Sequence number within a foreign key( a value of 1 represents the first column of the foreign key, a value of 2 would represent the second column within the foreign key).
*|pkOwner |String | Primary key table schema being imported (may be null)
*|pkName |String | Primary key name (may be null)
*|pkTableName |String | Primary key table name being imported
*|pkColumnName |String | Primary key column name being imported
2017-04-18 21:30:13 +00:00
* See [Relations](/Model-definition-JSON-file.html#relations) for more
* information.
2013-08-13 16:37:09 +00:00
* @param {String} modelName The model name
2014-06-10 21:27:58 +00:00
* @options {Object} options The options
* @property {String} owner|schema The database owner or schema
2013-08-13 16:37:09 +00:00
* @param {Function} [cb] The callback function
2017-04-18 21:30:13 +00:00
* @returns {Promise} A Promise with an array of foreign key relations.
*
2013-05-17 17:54:14 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.discoverForeignKeys = function(modelName, options, cb) {
2014-01-24 17:09:53 +00:00
this.freeze();
2015-06-25 08:38:15 +00:00
if (cb === undefined && typeof options === 'function') {
cb = options;
options = {};
}
options = options || {};
cb = cb || utils.createPromiseCallback();
2014-01-24 17:09:53 +00:00
if (this.connector.discoverForeignKeys) {
this.connector.discoverForeignKeys(modelName, options, cb);
} else if (cb) {
2014-03-04 17:42:55 +00:00
process.nextTick(cb);
2014-01-24 17:09:53 +00:00
}
2015-06-25 08:38:15 +00:00
return cb.promise;
2013-08-13 16:37:09 +00:00
};
2013-05-17 17:54:14 +00:00
2017-04-26 20:43:44 +00:00
/*! Method will be completely removed in LoopBack.next
*/
2013-08-13 16:37:09 +00:00
/**
* The synchronous version of discoverForeignKeys
*
* @param {String} modelName The model name
* @param {Object} options The options
* @returns {*}
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.discoverForeignKeysSync = function(modelName, options) {
2014-01-24 17:09:53 +00:00
this.freeze();
if (this.connector.discoverForeignKeysSync) {
return this.connector.discoverForeignKeysSync(modelName, options);
}
return null;
2014-03-04 17:42:55 +00:00
};
2013-06-02 06:03:25 +00:00
2013-06-03 06:00:11 +00:00
/**
2014-06-10 21:27:58 +00:00
* Retrieves a description of the foreign key columns that reference the given table's primary key columns
* (the foreign keys exported by a table), ordered by fkTableOwner, fkTableName, and keySeq.
*
2014-06-10 21:27:58 +00:00
* Callback function return value is an object that can have the following properties:
*
2014-06-10 21:27:58 +00:00
*| Key | Type | Description |
*|-----|------|-------------|
*|fkOwner |String | Foreign key table schema (may be null)
*|fkName |String | Foreign key name (may be null)
*|fkTableName |String | Foreign key table name
*|fkColumnName |String | Foreign key column name
*|keySeq |Number | Sequence number within a foreign key( a value of 1 represents the first column of the foreign key, a value of 2 would represent the second column within the foreign key).
*|pkOwner |String | Primary key table schema being imported (may be null)
*|pkName |String | Primary key name (may be null)
*|pkTableName |String | Primary key table name being imported
*|pkColumnName |String | Primary key column name being imported
2017-04-18 21:30:13 +00:00
* See [Relations](/Model-definition-JSON-file.html#relations) for more
* information.
2013-08-13 16:37:09 +00:00
*
* @param {String} modelName The model name
2014-06-10 21:27:58 +00:00
* @options {Object} options The options
* @property {String} owner|schema The database owner or schema
2013-08-13 16:37:09 +00:00
* @param {Function} [cb] The callback function
2017-04-18 21:30:13 +00:00
* @returns {Promise} A Promise with an array of exported foreign key relations.
2013-06-03 06:00:11 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.discoverExportedForeignKeys = function(modelName, options, cb) {
2014-01-24 17:09:53 +00:00
this.freeze();
2015-06-25 08:38:15 +00:00
if (cb === undefined && typeof options === 'function') {
cb = options;
options = {};
}
options = options || {};
cb = cb || utils.createPromiseCallback();
2014-01-24 17:09:53 +00:00
if (this.connector.discoverExportedForeignKeys) {
this.connector.discoverExportedForeignKeys(modelName, options, cb);
} else if (cb) {
2014-03-04 17:42:55 +00:00
process.nextTick(cb);
2014-01-24 17:09:53 +00:00
}
2015-06-25 08:38:15 +00:00
return cb.promise;
2013-08-13 16:37:09 +00:00
};
2013-06-03 06:00:11 +00:00
2017-04-26 20:43:44 +00:00
/*! Method will be completely removed in LoopBack.next
*/
2013-08-13 16:37:09 +00:00
/**
* The synchronous version of discoverExportedForeignKeys
* @param {String} modelName The model name
* @param {Object} options The options
* @returns {*}
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.discoverExportedForeignKeysSync = function(modelName, options) {
2014-01-24 17:09:53 +00:00
this.freeze();
if (this.connector.discoverExportedForeignKeysSync) {
return this.connector.discoverExportedForeignKeysSync(modelName, options);
}
return null;
};
2013-06-03 06:00:11 +00:00
2013-05-21 21:43:25 +00:00
function capitalize(str) {
2014-01-24 17:09:53 +00:00
if (!str) {
return str;
}
return str.charAt(0).toUpperCase() + ((str.length > 1) ? str.slice(1).toLowerCase() : '');
2013-05-21 21:43:25 +00:00
}
function fromDBName(dbName, camelCase) {
2014-01-24 17:09:53 +00:00
if (!dbName) {
return dbName;
}
var parts = dbName.split(/-|_/);
parts[0] = camelCase ? parts[0].toLowerCase() : capitalize(parts[0]);
2013-05-21 21:43:25 +00:00
2014-01-24 17:09:53 +00:00
for (var i = 1; i < parts.length; i++) {
parts[i] = capitalize(parts[i]);
}
return parts.join('');
2013-05-21 21:43:25 +00:00
}
2013-08-13 16:37:09 +00:00
/**
2014-03-12 23:28:46 +00:00
* Discover one schema from the given model without following the relations.
**Example schema from oracle connector:**
2014-03-12 23:28:46 +00:00
*
* ```js
* {
* "name": "Product",
* "options": {
* "idInjection": false,
* "oracle": {
* "schema": "BLACKPOOL",
* "table": "PRODUCT"
* }
* },
* "properties": {
* "id": {
* "type": "String",
* "required": true,
* "length": 20,
* "id": 1,
* "oracle": {
* "columnName": "ID",
* "dataType": "VARCHAR2",
* "dataLength": 20,
* "nullable": "N"
* }
* },
* "name": {
* "type": "String",
* "required": false,
* "length": 64,
* "oracle": {
* "columnName": "NAME",
* "dataType": "VARCHAR2",
* "dataLength": 64,
* "nullable": "Y"
* }
* },
* ...
* "fireModes": {
* "type": "String",
* "required": false,
* "length": 64,
* "oracle": {
* "columnName": "FIRE_MODES",
* "dataType": "VARCHAR2",
* "dataLength": 64,
* "nullable": "Y"
* }
* }
* }
* }
* ```
2013-08-13 16:37:09 +00:00
*
2017-04-18 21:30:13 +00:00
* @param {String} tableName The name of the table to discover.
* @options {Object} [options] An options object typically used for Relations.
* See [Relations](./Model-definition-JSON-file.html#relations) for more information.
2013-08-13 16:37:09 +00:00
* @param {Function} [cb] The callback function
2017-04-18 21:30:13 +00:00
* @returns {Promise} A promise object that resolves to a single schema.
2013-08-13 16:37:09 +00:00
*/
2017-04-18 21:30:13 +00:00
DataSource.prototype.discoverSchema = function(tableName, options, cb) {
2014-01-24 17:09:53 +00:00
options = options || {};
2014-01-24 17:09:53 +00:00
if (!cb && 'function' === typeof options) {
cb = options;
options = {};
}
options.visited = {};
options.relations = false;
2015-06-25 08:38:15 +00:00
cb = cb || utils.createPromiseCallback();
2017-04-18 21:30:13 +00:00
this.discoverSchemas(tableName, options, function(err, schemas) {
if (err || !schemas) {
2014-01-24 17:09:53 +00:00
cb && cb(err, schemas);
return;
}
for (var s in schemas) {
cb && cb(null, schemas[s]);
return;
}
});
2015-06-25 08:38:15 +00:00
return cb.promise;
2014-03-04 17:42:55 +00:00
};
2013-06-02 06:03:25 +00:00
2013-05-21 21:25:23 +00:00
/**
2017-04-18 21:30:13 +00:00
* Discover schema from a given tableName/viewName.
2013-08-13 16:37:09 +00:00
*
2017-04-18 21:30:13 +00:00
* @param {String} tableName The table name.
2014-06-10 21:27:58 +00:00
* @options {Object} [options] Options; see below.
* @property {String} owner|schema Database owner or schema name.
* @property {Boolean} relations True if relations (primary key/foreign key) are navigated; false otherwise.
* @property {Boolean} all True if all owners are included; false otherwise.
* @property {Boolean} views True if views are included; false otherwise.
2013-08-13 16:37:09 +00:00
* @param {Function} [cb] The callback function
2017-04-18 21:30:13 +00:00
* @returns {Promise} A promise object that resolves to an array of schemas.
2013-05-21 21:25:23 +00:00
*/
2017-04-18 21:30:13 +00:00
DataSource.prototype.discoverSchemas = function(tableName, options, cb) {
2014-01-24 17:09:53 +00:00
options = options || {};
2014-01-24 17:09:53 +00:00
if (!cb && 'function' === typeof options) {
cb = options;
options = {};
}
2015-06-25 08:38:15 +00:00
cb = cb || utils.createPromiseCallback();
2014-01-24 17:09:53 +00:00
var self = this;
var dbType = this.connector.name;
var nameMapper;
if (options.nameMapper === null) {
// No mapping
nameMapper = function(type, name) {
return name;
};
} else if (typeof options.nameMapper === 'function') {
// Custom name mapper
nameMapper = options.nameMapper;
} else {
// Default name mapper
nameMapper = function mapName(type, name) {
if (type === 'table' || type === 'model') {
return fromDBName(name, false);
2017-04-04 22:23:43 +00:00
} else if (type == 'fk') {
return fromDBName(name + 'Rel', true);
} else {
return fromDBName(name, true);
}
};
}
if (this.connector.discoverSchemas) {
// Delegate to the connector implementation
2017-04-18 21:30:13 +00:00
this.connector.discoverSchemas(tableName, options, cb);
2015-06-25 08:38:15 +00:00
return cb.promise;
}
2014-01-24 17:09:53 +00:00
var tasks = [
2017-04-18 21:30:13 +00:00
this.discoverModelProperties.bind(this, tableName, options),
this.discoverPrimaryKeys.bind(this, tableName, options)];
2014-01-24 17:09:53 +00:00
var followingRelations = options.associations || options.relations;
if (followingRelations) {
2017-04-18 21:30:13 +00:00
tasks.push(this.discoverForeignKeys.bind(this, tableName, options));
2014-01-24 17:09:53 +00:00
}
2016-04-01 11:48:17 +00:00
async.parallel(tasks, function(err, results) {
2014-01-24 17:09:53 +00:00
if (err) {
2015-06-25 08:38:15 +00:00
cb(err);
return cb.promise;
}
2014-01-24 17:09:53 +00:00
var columns = results[0];
if (!columns || columns.length === 0) {
2017-04-18 21:30:13 +00:00
cb(new Error(g.f('Table \'%s\' does not exist.', tableName)));
2015-06-25 08:38:15 +00:00
return cb.promise;
2014-01-24 17:09:53 +00:00
}
2014-01-24 17:09:53 +00:00
// Handle primary keys
var primaryKeys = results[1] || [];
2014-01-24 17:09:53 +00:00
var pks = {};
2016-04-01 11:48:17 +00:00
primaryKeys.forEach(function(pk) {
2014-01-24 17:09:53 +00:00
pks[pk.columnName] = pk.keySeq;
});
2014-01-24 17:09:53 +00:00
if (self.settings.debug) {
2014-03-04 17:42:55 +00:00
debug('Primary keys: ', pks);
}
2014-01-24 17:09:53 +00:00
var schema = {
2017-04-18 21:30:13 +00:00
name: nameMapper('table', tableName),
2014-01-24 17:09:53 +00:00
options: {
2016-04-01 11:48:17 +00:00
idInjection: false, // DO NOT add id property
2014-01-24 17:09:53 +00:00
},
2016-04-01 11:48:17 +00:00
properties: {},
2014-01-24 17:09:53 +00:00
};
schema.options[dbType] = {
2014-01-24 17:09:53 +00:00
schema: columns[0].owner,
2017-04-18 21:30:13 +00:00
table: tableName,
2014-01-24 17:09:53 +00:00
};
2016-04-01 11:48:17 +00:00
columns.forEach(function(item) {
var propName = nameMapper('column', item.columnName);
2014-01-24 17:09:53 +00:00
schema.properties[propName] = {
type: item.type,
2016-04-01 13:23:42 +00:00
required: (item.nullable === 'N' || item.nullable === 'NO' ||
item.nullable === 0 || item.nullable === false),
2014-01-24 17:09:53 +00:00
length: item.dataLength,
precision: item.dataPrecision,
2016-04-01 11:48:17 +00:00
scale: item.dataScale,
2014-01-24 17:09:53 +00:00
};
if (pks[item.columnName]) {
schema.properties[propName].id = pks[item.columnName];
}
var dbSpecific = schema.properties[propName][dbType] = {
columnName: item.columnName,
dataType: item.dataType,
dataLength: item.dataLength,
2014-01-24 17:09:53 +00:00
dataPrecision: item.dataPrecision,
dataScale: item.dataScale,
2016-04-01 11:48:17 +00:00
nullable: item.nullable,
2014-01-24 17:09:53 +00:00
};
// merge connector-specific properties
if (item[dbType]) {
for (var k in item[dbType]) {
dbSpecific[k] = item[dbType][k];
}
}
2014-01-24 17:09:53 +00:00
});
2014-01-24 17:09:53 +00:00
// Add current modelName to the visited tables
options.visited = options.visited || {};
2017-04-18 21:30:13 +00:00
var schemaKey = columns[0].owner + '.' + tableName;
2014-01-24 17:09:53 +00:00
if (!options.visited.hasOwnProperty(schemaKey)) {
if (self.settings.debug) {
2014-03-04 17:42:55 +00:00
debug('Adding schema for ' + schemaKey);
2014-01-24 17:09:53 +00:00
}
options.visited[schemaKey] = schema;
}
2014-01-24 17:09:53 +00:00
var otherTables = {};
if (followingRelations) {
// Handle foreign keys
var fks = {};
var foreignKeys = results[2] || [];
2016-04-01 11:48:17 +00:00
foreignKeys.forEach(function(fk) {
2014-01-24 17:09:53 +00:00
var fkInfo = {
keySeq: fk.keySeq,
owner: fk.pkOwner,
tableName: fk.pkTableName,
2016-04-01 11:48:17 +00:00
columnName: fk.pkColumnName,
2014-01-24 17:09:53 +00:00
};
if (fks[fk.fkName]) {
fks[fk.fkName].push(fkInfo);
} else {
fks[fk.fkName] = [fkInfo];
}
2014-01-24 17:09:53 +00:00
});
2013-05-22 19:17:14 +00:00
2014-01-24 17:09:53 +00:00
if (self.settings.debug) {
2014-03-04 17:42:55 +00:00
debug('Foreign keys: ', fks);
2014-01-24 17:09:53 +00:00
}
2014-01-24 17:09:53 +00:00
schema.options.relations = {};
2016-04-01 11:48:17 +00:00
foreignKeys.forEach(function(fk) {
2017-04-04 22:23:43 +00:00
var propName = nameMapper('fk', (fk.fkName || fk.pkTableName));
2014-01-24 17:09:53 +00:00
schema.options.relations[propName] = {
model: nameMapper('table', fk.pkTableName),
2014-01-24 17:09:53 +00:00
type: 'belongsTo',
2016-04-01 11:48:17 +00:00
foreignKey: nameMapper('column', fk.fkColumnName),
};
2014-01-24 17:09:53 +00:00
var key = fk.pkOwner + '.' + fk.pkTableName;
if (!options.visited.hasOwnProperty(key) && !otherTables.hasOwnProperty(key)) {
2016-08-19 17:46:59 +00:00
otherTables[key] = {owner: fk.pkOwner, tableName: fk.pkTableName};
}
2014-01-24 17:09:53 +00:00
});
}
2014-01-24 17:09:53 +00:00
if (Object.keys(otherTables).length === 0) {
2015-06-25 08:38:15 +00:00
cb(null, options.visited);
2014-01-24 17:09:53 +00:00
} else {
var moreTasks = [];
for (var t in otherTables) {
if (self.settings.debug) {
2014-03-04 17:42:55 +00:00
debug('Discovering related schema for ' + schemaKey);
}
2014-01-24 17:09:53 +00:00
var newOptions = {};
for (var key in options) {
newOptions[key] = options[key];
}
2014-01-24 17:09:53 +00:00
newOptions.owner = otherTables[t].owner;
2013-05-21 21:25:23 +00:00
2014-01-24 17:09:53 +00:00
moreTasks.push(DataSource.prototype.discoverSchemas.bind(self, otherTables[t].tableName, newOptions));
}
2016-04-01 11:48:17 +00:00
async.parallel(moreTasks, function(err, results) {
2014-01-24 17:09:53 +00:00
var result = results && results[0];
2015-06-25 08:38:15 +00:00
cb(err, result);
2014-01-24 17:09:53 +00:00
});
}
});
2015-06-25 08:38:15 +00:00
return cb.promise;
2014-01-24 17:09:53 +00:00
};
2013-06-02 06:03:25 +00:00
2017-04-26 20:43:44 +00:00
/*! Method will be completely removed in LoopBack.next
*/
2013-06-02 06:03:25 +00:00
/**
2013-08-13 16:37:09 +00:00
* Discover schema from a given table/view synchronously
* @param {String} modelName The model name
2014-06-10 21:27:58 +00:00
* @options {Object} [options] Options; see below.
* @property {String} owner|schema Database owner or schema name.
* @property {Boolean} relations True if relations (primary key/foreign key) are navigated; false otherwise.
* @property {Boolean} all True if all owners are included; false otherwise.
* @property {Boolean} views True if views are included; false otherwise.
2017-04-18 21:30:13 +00:00
* @returns {Array<Object>} An array of schema definition objects.
2013-06-02 06:03:25 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.discoverSchemasSync = function(modelName, options) {
2014-01-24 17:09:53 +00:00
var self = this;
var dbType = this.connector.name;
2013-06-02 06:03:25 +00:00
2014-01-24 17:09:53 +00:00
var columns = this.discoverModelPropertiesSync(modelName, options);
if (!columns || columns.length === 0) {
return [];
}
2013-06-02 06:03:25 +00:00
var nameMapper = options.nameMapper || function mapName(type, name) {
if (type === 'table' || type === 'model') {
return fromDBName(name, false);
} else {
return fromDBName(name, true);
}
};
2014-01-24 17:09:53 +00:00
// Handle primary keys
var primaryKeys = this.discoverPrimaryKeysSync(modelName, options);
var pks = {};
2016-04-01 11:48:17 +00:00
primaryKeys.forEach(function(pk) {
2014-01-24 17:09:53 +00:00
pks[pk.columnName] = pk.keySeq;
});
2013-06-02 06:03:25 +00:00
2014-01-24 17:09:53 +00:00
if (self.settings.debug) {
2014-03-04 17:42:55 +00:00
debug('Primary keys: ', pks);
2014-01-24 17:09:53 +00:00
}
var schema = {
name: nameMapper('table', modelName),
2014-01-24 17:09:53 +00:00
options: {
2016-04-01 11:48:17 +00:00
idInjection: false, // DO NOT add id property
2014-01-24 17:09:53 +00:00
},
2016-04-01 11:48:17 +00:00
properties: {},
2014-01-24 17:09:53 +00:00
};
2013-06-02 06:03:25 +00:00
schema.options[dbType] = {
2014-01-24 17:09:53 +00:00
schema: columns.length > 0 && columns[0].owner,
2016-04-01 11:48:17 +00:00
table: modelName,
2014-01-24 17:09:53 +00:00
};
2016-04-01 11:48:17 +00:00
columns.forEach(function(item) {
2014-01-24 17:09:53 +00:00
var i = item;
var propName = nameMapper('column', item.columnName);
2014-01-24 17:09:53 +00:00
schema.properties[propName] = {
type: item.type,
required: (item.nullable === 'N'),
length: item.dataLength,
precision: item.dataPrecision,
2016-04-01 11:48:17 +00:00
scale: item.dataScale,
2013-06-02 06:03:25 +00:00
};
2014-01-24 17:09:53 +00:00
if (pks[item.columnName]) {
schema.properties[propName].id = pks[item.columnName];
}
schema.properties[propName][dbType] = {
2014-01-24 17:09:53 +00:00
columnName: i.columnName,
dataType: i.dataType,
dataLength: i.dataLength,
dataPrecision: item.dataPrecision,
dataScale: item.dataScale,
2016-04-01 11:48:17 +00:00
nullable: i.nullable,
2013-06-02 06:03:25 +00:00
};
2014-01-24 17:09:53 +00:00
});
2013-06-02 06:03:25 +00:00
2014-01-24 17:09:53 +00:00
// Add current modelName to the visited tables
options.visited = options.visited || {};
var schemaKey = columns[0].owner + '.' + modelName;
if (!options.visited.hasOwnProperty(schemaKey)) {
if (self.settings.debug) {
2014-03-04 17:42:55 +00:00
debug('Adding schema for ' + schemaKey);
2014-01-24 17:09:53 +00:00
}
options.visited[schemaKey] = schema;
}
2013-06-02 06:03:25 +00:00
2014-01-24 17:09:53 +00:00
var otherTables = {};
var followingRelations = options.associations || options.relations;
if (followingRelations) {
// Handle foreign keys
var fks = {};
var foreignKeys = this.discoverForeignKeysSync(modelName, options);
2016-04-01 11:48:17 +00:00
foreignKeys.forEach(function(fk) {
2014-01-24 17:09:53 +00:00
var fkInfo = {
keySeq: fk.keySeq,
owner: fk.pkOwner,
tableName: fk.pkTableName,
2016-04-01 11:48:17 +00:00
columnName: fk.pkColumnName,
2014-01-24 17:09:53 +00:00
};
if (fks[fk.fkName]) {
fks[fk.fkName].push(fkInfo);
} else {
fks[fk.fkName] = [fkInfo];
}
2013-06-02 06:03:25 +00:00
});
2014-01-24 17:09:53 +00:00
if (self.settings.debug) {
2014-03-04 17:42:55 +00:00
debug('Foreign keys: ', fks);
2013-06-02 06:03:25 +00:00
}
2014-01-24 17:09:53 +00:00
schema.options.relations = {};
2016-04-01 11:48:17 +00:00
foreignKeys.forEach(function(fk) {
var propName = nameMapper('column', fk.pkTableName);
2014-01-24 17:09:53 +00:00
schema.options.relations[propName] = {
model: nameMapper('table', fk.pkTableName),
2014-01-24 17:09:53 +00:00
type: 'belongsTo',
2016-04-01 11:48:17 +00:00
foreignKey: nameMapper('column', fk.fkColumnName),
2014-01-24 17:09:53 +00:00
};
var key = fk.pkOwner + '.' + fk.pkTableName;
if (!options.visited.hasOwnProperty(key) && !otherTables.hasOwnProperty(key)) {
2016-08-19 17:46:59 +00:00
otherTables[key] = {owner: fk.pkOwner, tableName: fk.pkTableName};
2014-01-24 17:09:53 +00:00
}
});
}
2013-06-02 06:03:25 +00:00
2014-01-24 17:09:53 +00:00
if (Object.keys(otherTables).length === 0) {
return options.visited;
} else {
var moreTasks = [];
for (var t in otherTables) {
if (self.settings.debug) {
2014-03-04 17:42:55 +00:00
debug('Discovering related schema for ' + schemaKey);
2014-01-24 17:09:53 +00:00
}
var newOptions = {};
for (var key in options) {
newOptions[key] = options[key];
}
newOptions.owner = otherTables[t].owner;
self.discoverSchemasSync(otherTables[t].tableName, newOptions);
2013-06-02 06:03:25 +00:00
}
2014-01-24 17:09:53 +00:00
return options.visited;
}
2013-08-13 16:37:09 +00:00
};
2013-06-02 06:03:25 +00:00
/**
2014-06-10 21:27:58 +00:00
* Discover and build models from the specified owner/modelName.
*
2014-06-10 21:27:58 +00:00
* @param {String} modelName The model name.
* @options {Object} [options] Options; see below.
* @property {String} owner|schema Database owner or schema name.
* @property {Boolean} relations True if relations (primary key/foreign key) are navigated; false otherwise.
* @property {Boolean} all True if all owners are included; false otherwise.
* @property {Boolean} views True if views are included; false otherwise.
2013-08-13 16:37:09 +00:00
* @param {Function} [cb] The callback function
2017-04-18 21:30:13 +00:00
* @returns {Promise} A Promise object that resolves with a map of model
* constructors, keyed by model name
2013-06-02 06:03:25 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.discoverAndBuildModels = function(modelName, options, cb) {
2014-01-24 17:09:53 +00:00
var self = this;
options = options || {};
2016-04-01 11:48:17 +00:00
this.discoverSchemas(modelName, options, function(err, schemas) {
2014-01-24 17:09:53 +00:00
if (err) {
cb && cb(err, schemas);
return;
}
2013-06-02 06:03:25 +00:00
2014-01-24 17:09:53 +00:00
var schemaList = [];
for (var s in schemas) {
var schema = schemas[s];
if (options.base) {
schema.options = schema.options || {};
schema.options.base = options.base;
}
2014-01-24 17:09:53 +00:00
schemaList.push(schema);
}
2013-06-02 06:03:25 +00:00
var models = self.modelBuilder.buildModels(schemaList,
self.createModel.bind(self));
2014-01-24 17:09:53 +00:00
cb && cb(err, models);
});
2013-08-13 16:37:09 +00:00
};
2013-06-02 06:03:25 +00:00
2017-04-26 20:43:44 +00:00
/*! Method will be completely removed in LoopBack.next
*/
2013-06-02 06:03:25 +00:00
/**
2014-06-10 21:27:58 +00:00
* Discover and build models from the given owner/modelName synchronously.
* @param {String} modelName The model name.
* @options {Object} [options] Options; see below.
* @property {String} owner|schema Database owner or schema name.
* @property {Boolean} relations True if relations (primary key/foreign key) are navigated; false otherwise.
* @property {Boolean} all True if all owners are included; false otherwise.
* @property {Boolean} views True if views are included; false otherwise.
2013-08-13 16:37:09 +00:00
* @param {String} modelName The model name
* @param {Object} [options] The options
2017-04-18 21:30:13 +00:00
* @returns {Object} A map of model constructors, keyed by model name
2013-06-02 06:03:25 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.discoverAndBuildModelsSync = function(modelName, options) {
options = options || {};
2014-01-24 17:09:53 +00:00
var schemas = this.discoverSchemasSync(modelName, options);
2013-06-02 06:03:25 +00:00
2014-01-24 17:09:53 +00:00
var schemaList = [];
for (var s in schemas) {
var schema = schemas[s];
if (options.base) {
schema.options = schema.options || {};
schema.options.base = options.base;
}
2014-01-24 17:09:53 +00:00
schemaList.push(schema);
}
2013-06-02 06:03:25 +00:00
var models = this.modelBuilder.buildModels(schemaList,
this.createModel.bind(this));
2014-01-24 17:09:53 +00:00
return models;
2013-08-13 16:37:09 +00:00
};
2013-06-02 06:03:25 +00:00
/**
* Introspect a JSON object and build a model class
* @param {String} name Name of the model
* @param {Object} json The json object representing a model instance
* @param {Object} options Options
2017-04-18 21:30:13 +00:00
* @returns {Model} A Model class
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.buildModelFromInstance = function(name, json, options) {
// Introspect the JSON document to generate a schema
var schema = ModelBuilder.introspect(json);
// Create a model for the generated schema
return this.createModel(name, schema, options);
};
2013-05-17 17:54:14 +00:00
/**
2017-04-18 21:30:13 +00:00
* Check whether or not migrations are required for the database schema to match
* the Model definitions attached to the DataSource.
* Note: This method applies only to SQL connectors.
2014-06-10 21:27:58 +00:00
* @param {String|String[]} [models] A model name or an array of model names. If not present, apply to all models.
2017-04-18 21:30:13 +00:00
* @returns {Boolean} Whether or not migrations are required.
2013-05-17 17:54:14 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.isActual = function(models, cb) {
2014-01-24 17:09:53 +00:00
this.freeze();
if (this.connector.isActual) {
this.connector.isActual(models, cb);
} else {
if ((!cb) && ('function' === typeof models)) {
cb = models;
models = undefined;
}
if (cb) {
2016-04-01 11:48:17 +00:00
process.nextTick(function() {
2014-01-24 17:09:53 +00:00
cb(null, true);
});
2013-05-17 17:54:14 +00:00
}
2014-01-24 17:09:53 +00:00
}
2013-05-17 17:54:14 +00:00
};
/**
* Log benchmarked message. Do not redefine this method, if you need to grab
2017-04-18 21:30:13 +00:00
* schema logs, use `dataSource.on('log', ...)` emitter event
2013-05-17 17:54:14 +00:00
*
2013-07-23 21:40:44 +00:00
* @private used by connectors
2013-05-17 17:54:14 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.log = function(sql, t) {
2014-03-04 17:42:55 +00:00
debug(sql, t);
2014-01-24 17:09:53 +00:00
this.emit('log', sql, t);
2013-05-17 17:54:14 +00:00
};
/**
* Freeze dataSource. Behavior depends on connector
2017-04-26 20:43:44 +00:00
* To continuously add artifacts to datasource until it is frozen, but it is not really used in loopback.
2013-05-17 17:54:14 +00:00
*/
DataSource.prototype.freeze = function freeze() {
if (!this.connector) {
2016-07-22 19:26:07 +00:00
throw new Error(g.f('The connector has not been initialized.'));
2014-03-04 17:42:55 +00:00
}
2014-01-24 17:09:53 +00:00
if (this.connector.freezeDataSource) {
this.connector.freezeDataSource();
}
if (this.connector.freezeSchema) {
this.connector.freezeSchema();
}
2014-03-04 17:42:55 +00:00
};
2013-05-17 17:54:14 +00:00
/**
2017-04-18 21:30:13 +00:00
* Return table name for specified `modelName`.
* @param {String} modelName The model name.
* @returns {String} The table name.
2013-05-17 17:54:14 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.tableName = function(modelName) {
2014-01-24 17:09:53 +00:00
return this.getModelDefinition(modelName).tableName(this.connector.name);
};
/**
* Return column name for specified modelName and propertyName
2013-08-13 16:37:09 +00:00
* @param {String} modelName The model name
2014-06-10 21:27:58 +00:00
* @param {String} propertyName The property name
* @returns {String} columnName The column name.
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.columnName = function(modelName, propertyName) {
2014-01-24 17:09:53 +00:00
return this.getModelDefinition(modelName).columnName(this.connector.name, propertyName);
};
2013-05-29 17:03:01 +00:00
/**
* Return column metadata for specified modelName and propertyName
2013-08-13 16:37:09 +00:00
* @param {String} modelName The model name
2014-06-10 21:27:58 +00:00
* @param {String} propertyName The property name
2013-05-29 17:03:01 +00:00
* @returns {Object} column metadata
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.columnMetadata = function(modelName, propertyName) {
2014-01-24 17:09:53 +00:00
return this.getModelDefinition(modelName).columnMetadata(this.connector.name, propertyName);
2013-05-29 17:03:01 +00:00
};
/**
* Return column names for specified modelName
2013-08-13 16:37:09 +00:00
* @param {String} modelName The model name
* @returns {String[]} column names
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.columnNames = function(modelName) {
2014-01-24 17:09:53 +00:00
return this.getModelDefinition(modelName).columnNames(this.connector.name);
2013-05-17 17:54:14 +00:00
};
/**
* Find the ID column name
2013-08-13 16:37:09 +00:00
* @param {String} modelName The model name
* @returns {String} columnName for ID
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.idColumnName = function(modelName) {
2014-01-24 17:09:53 +00:00
return this.getModelDefinition(modelName).idColumnName(this.connector.name);
2013-08-13 16:37:09 +00:00
};
2013-05-23 01:04:05 +00:00
/**
2013-05-30 23:06:04 +00:00
* Find the ID property name
2013-08-13 16:37:09 +00:00
* @param {String} modelName The model name
* @returns {String} property name for ID
2013-05-23 01:04:05 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.idName = function(modelName) {
2014-01-24 17:09:53 +00:00
if (!this.getModelDefinition(modelName).idName) {
2016-07-22 19:26:07 +00:00
g.error('No {{id}} name %s', this.getModelDefinition(modelName));
2014-01-24 17:09:53 +00:00
}
return this.getModelDefinition(modelName).idName();
2013-08-13 16:37:09 +00:00
};
2013-05-30 23:06:04 +00:00
/**
* Find the ID property names sorted by the index
2013-08-13 16:37:09 +00:00
* @param {String} modelName The model name
* @returns {String[]} property names for IDs
2013-05-30 23:06:04 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.idNames = function(modelName) {
2014-01-24 17:09:53 +00:00
return this.getModelDefinition(modelName).idNames();
2013-08-13 16:37:09 +00:00
};
2013-05-30 23:06:04 +00:00
/**
* Find the id property definition
* @param {String} modelName The model name
* @returns {Object} The id property definition
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.idProperty = function(modelName) {
var def = this.getModelDefinition(modelName);
var idProps = def && def.ids();
return idProps && idProps[0] && idProps[0].property;
};
2013-05-17 17:54:14 +00:00
/**
2013-08-13 16:37:09 +00:00
* Define foreign key to another model
* @param {String} className The model name that owns the key
2014-03-12 23:28:46 +00:00
* @param {String} key Name of key field
2013-08-13 16:37:09 +00:00
* @param {String} foreignClassName The foreign model name
2015-08-11 20:30:15 +00:00
* @param {String} pkName (optional) primary key used for foreignKey
2013-05-17 17:54:14 +00:00
*/
2015-08-11 20:30:15 +00:00
DataSource.prototype.defineForeignKey = function defineForeignKey(className, key, foreignClassName, pkName) {
var pkType = null;
var foreignModel = this.getModelDefinition(foreignClassName);
2015-08-11 20:30:15 +00:00
pkName = pkName || foreignModel && foreignModel.idName();
if (pkName) {
pkType = foreignModel.properties[pkName].type;
}
var model = this.getModelDefinition(className);
if (model.properties[key]) {
if (pkType) {
// Reset the type of the foreign key
model.rawProperties[key].type = model.properties[key].type = pkType;
}
return;
2014-01-24 17:09:53 +00:00
}
2016-08-19 17:46:59 +00:00
var fkDef = {type: pkType};
2015-03-11 03:30:40 +00:00
var foreignMeta = this.columnMetadata(foreignClassName, pkName);
if (foreignMeta && (foreignMeta.dataType || foreignMeta.dataLength)) {
fkDef[this.connector.name] = {};
if (foreignMeta.dataType) {
fkDef[this.connector.name].dataType = foreignMeta.dataType;
}
2015-09-03 16:02:21 +00:00
if (foreignMeta.dataLength) {
fkDef[this.connector.name].dataLength = foreignMeta.dataLength;
}
}
2014-01-24 17:09:53 +00:00
if (this.connector.defineForeignKey) {
2016-04-01 11:48:17 +00:00
var cb = function(err, keyType) {
2014-01-24 17:09:53 +00:00
if (err) throw err;
fkDef.type = keyType || pkType;
2014-01-24 17:09:53 +00:00
// Add the foreign key property to the data source _models
this.defineProperty(className, key, fkDef);
2014-01-24 17:09:53 +00:00
}.bind(this);
switch (this.connector.defineForeignKey.length) {
case 4:
this.connector.defineForeignKey(className, key, foreignClassName, cb);
break;
default:
case 3:
this.connector.defineForeignKey(className, key, cb);
break;
2013-05-17 17:54:14 +00:00
}
2014-01-24 17:09:53 +00:00
} else {
// Add the foreign key property to the data source _models
this.defineProperty(className, key, fkDef);
2014-01-24 17:09:53 +00:00
}
2013-05-17 17:54:14 +00:00
};
/**
2017-04-18 21:30:13 +00:00
* Close connection to the DataSource.
2014-06-10 21:27:58 +00:00
* @param {Function} [cb] The callback function. Optional.
2013-05-17 17:54:14 +00:00
*/
DataSource.prototype.disconnect = function disconnect(cb) {
2017-04-26 20:43:44 +00:00
cb = cb || utils.createPromiseCallback();
2014-01-24 17:09:53 +00:00
var self = this;
if (this.connected && (typeof this.connector.disconnect === 'function')) {
2016-04-01 11:48:17 +00:00
this.connector.disconnect(function(err, result) {
2014-01-24 17:09:53 +00:00
self.connected = false;
cb && cb(err, result);
});
} else {
2016-04-01 11:48:17 +00:00
process.nextTick(function() {
self.connected = false;
2014-01-24 17:09:53 +00:00
cb && cb();
});
}
2017-04-26 20:43:44 +00:00
return cb.promise;
2013-05-17 17:54:14 +00:00
};
2013-08-13 16:37:09 +00:00
/**
2014-03-12 23:28:46 +00:00
* Copy the model from Master.
2013-08-13 16:37:09 +00:00
* @param {Function} Master The model constructor
2017-04-18 21:30:13 +00:00
* @returns {Model} A copy of the Model object constructor
2013-08-13 16:37:09 +00:00
*
* @private
*/
2013-05-17 17:54:14 +00:00
DataSource.prototype.copyModel = function copyModel(Master) {
2014-01-24 17:09:53 +00:00
var dataSource = this;
var className = Master.modelName;
var md = Master.modelBuilder.getModelDefinition(className);
var Slave = function SlaveModel() {
Master.apply(this, [].slice.call(arguments));
};
2013-05-17 17:54:14 +00:00
2014-01-24 17:09:53 +00:00
util.inherits(Slave, Master);
2013-05-17 17:54:14 +00:00
2014-01-24 17:09:53 +00:00
// Delegating static properties
Slave.__proto__ = Master;
2013-05-17 17:54:14 +00:00
2014-01-24 17:09:53 +00:00
hiddenProperty(Slave, 'dataSource', dataSource);
hiddenProperty(Slave, 'modelName', className);
hiddenProperty(Slave, 'relations', Master.relations);
2013-05-17 17:54:14 +00:00
2014-01-24 17:09:53 +00:00
if (!(className in dataSource.modelBuilder.models)) {
// store class in model pool
dataSource.modelBuilder.models[className] = Slave;
2016-04-01 13:23:42 +00:00
dataSource.modelBuilder.definitions[className] =
new ModelDefinition(dataSource.modelBuilder, md.name, md.properties, md.settings);
2013-05-17 17:54:14 +00:00
2014-01-24 17:09:53 +00:00
if ((!dataSource.isTransaction) && dataSource.connector && dataSource.connector.define) {
dataSource.connector.define({
model: Slave,
properties: md.properties,
2016-04-01 11:48:17 +00:00
settings: md.settings,
2014-01-24 17:09:53 +00:00
});
2013-05-17 17:54:14 +00:00
}
2014-01-24 17:09:53 +00:00
}
return Slave;
2013-05-17 17:54:14 +00:00
};
2013-08-13 16:37:09 +00:00
/**
2017-04-18 21:30:13 +00:00
* Run a transaction against the DataSource.
*
* This method can be used in different ways based on the passed arguments and
* type of underlying data source:
*
* If no `execute()` function is provided and the underlying DataSource is a
* database that supports transactions, a Promise is returned that resolves to
* an EventEmitter representing the transaction once it is ready.
* `transaction.models` can be used to receive versions of the DataSource's
* model classes which are bound to the created transaction, so that all their
* database methods automatically use the transaction. At the end of all
* database transactions, `transaction.commit()` can be called to commit the
* transactions, or `transaction.rollback()` to roll them back.
*
* If no `execute()` function is provided on a transient or memory DataSource,
* the EventEmitter representing the transaction is returned immediately. For
* backward compatibility, this object also supports `transaction.exec()`
* instead of `transaction.commit()`, and calling `transaction.rollback()` is
* not required on such transient and memory DataSource instances.
*
* If an `execute()` function is provided, then it is called as soon as the
* transaction is ready, receiving `transaction.models` as its first
* argument. `transaction.commit()` and `transaction.rollback()` are then
* automatically called at the end of `execute()`, based on whether exceptions
* happen during execution or not. If no callback is provided to be called at
* the end of the execution, a Promise object is returned that is resolved or
* rejected as soon as the execution is completed, and the transaction is
* committed or rolled back.
*
* @param {Function} execute The execute function, called with (models). Note
* that the instances in `models` are bound to the created transaction, and
* are therefore not identical with the models in `app.models`, but slaves
* thereof (optional).
* @options {Object} options The options to be passed to `beginTransaction()`
* when creating the transaction on database sources (optional).
* @param {Function} cb Callback called with (err)
* @returns {Promise | EventEmitter}
2013-08-13 16:37:09 +00:00
*/
DataSource.prototype.transaction = function(execute, options, cb) {
if (cb === undefined && typeof options === 'function') {
cb = options;
options = {};
} else {
options = options || {};
}
2014-01-24 17:09:53 +00:00
var dataSource = this;
var transaction = new EventEmitter();
2014-01-24 17:09:53 +00:00
for (var p in dataSource) {
transaction[p] = dataSource[p];
}
2014-01-24 17:09:53 +00:00
transaction.isTransaction = true;
transaction.origin = dataSource;
transaction.connected = false;
transaction.connecting = false;
// Don't allow creating transactions on a transaction data-source:
transaction.transaction = function() {
throw new Error(g.f('Nesting transactions is not supported'));
};
2014-01-24 17:09:53 +00:00
// Create a blank pool for the slave models bound to this transaction.
var modelBuilder = new ModelBuilder();
var slaveModels = modelBuilder.models;
transaction.modelBuilder = modelBuilder;
transaction.models = slaveModels;
transaction.definitions = modelBuilder.definitions;
// For performance reasons, use a getter per model and only call copyModel()
// for the models that are actually used. These getters are then replaced
// with the actual values on first use.
var masterModels = dataSource.modelBuilder.models;
Object.keys(masterModels).forEach(function(name) {
Object.defineProperty(slaveModels, name, {
enumerable: true,
configurable: true,
get: function() {
// Delete getter so copyModel() can redefine slaveModels[name].
// NOTE: No need to set the new value as copyModel() takes care of it.
delete slaveModels[name];
return dataSource.copyModel.call(transaction, masterModels[name]);
},
});
});
2013-05-17 17:54:14 +00:00
var done = function(err) {
if (err) {
transaction.rollback(function(error) {
cb(err || error);
});
} else {
transaction.commit(cb);
}
// Make sure cb() isn't called twice, e.g. if `execute` returns a
// thenable object and also calls the passed `cb` function.
done = function() {};
2014-01-24 17:09:53 +00:00
};
2013-05-17 17:54:14 +00:00
function handleExecute() {
if (execute) {
cb = cb || utils.createPromiseCallback();
try {
var result = execute(slaveModels, done);
if (result && typeof result.then === 'function') {
result.then(function() { done(); }, done);
}
} catch (err) {
done(err);
}
return cb.promise;
} else if (cb) {
cb(null, transaction);
} else {
return transaction;
}
}
function transactionCreated(err, tx) {
if (err) {
cb(err);
} else {
// Expose transaction on the created transaction dataSource so it can be
// retrieved again in determineOptions() in dao.js, as well as referenced
// in transaction.commit() and transaction.rollback() below.
transaction.currentTransaction = tx;
// Some connectors like Postgresql expose loobpack-connector as a property on the tx
if (!tx.observe && tx.connector) {
tx = tx.connector;
}
// Handle timeout and pass it on as an error.
tx.observe('timeout', function(context, next) {
const err = new Error(g.f('Transaction is rolled back due to timeout'));
err.code = 'TRANSACTION_TIMEOUT';
// Pass on the error to next(), so that the final 'timeout' observer in
// loopback-connector does not trigger a rollback by itself that we
// can't get a callback for when it's finished.
next(err);
// Call done(err) after, to execute the rollback here and reject the
// promise with the error when it's completed.
done(err);
});
handleExecute();
}
}
function ensureTransaction(transaction, cb) {
if (!transaction) {
process.nextTick(function() {
cb(new Error(g.f(
'Transaction is not ready, wait for the returned promise to resolve')));
});
}
return transaction;
}
var connector = dataSource.connector;
if (connector.transaction) {
// Create a transient or memory source transaction.
transaction.connector = connector.transaction();
transaction.commit =
transaction.exec = function(cb) {
this.connector.exec(cb);
};
transaction.rollback = function(cb) {
// No need to do anything here.
cb();
};
return handleExecute();
} else if (connector.beginTransaction) {
// Create a database source transaction.
transaction.exec =
transaction.commit = function(cb) {
ensureTransaction(this.currentTransaction, cb).commit(cb);
};
transaction.rollback = function(cb) {
ensureTransaction(this.currentTransaction, cb).rollback(cb);
};
// Always use callback / promise due to the use of beginTransaction()
cb = cb || utils.createPromiseCallback();
Transaction.begin(connector, options, transactionCreated);
return cb.promise;
} else {
throw new Error(g.f('DataSource does not support transactions'));
}
2013-05-17 17:54:14 +00:00
};
2013-06-11 16:03:11 +00:00
/**
2014-03-12 23:28:46 +00:00
* Enable remote access to a data source operation. Each [connector](#connector) has its own set of set
* remotely enabled and disabled operations. To list the operations, call `dataSource.operations()`.
2013-08-13 16:37:09 +00:00
* @param {String} operation The operation name
2013-06-11 16:03:11 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.enableRemote = function(operation) {
2013-06-11 16:03:11 +00:00
var op = this.getOperation(operation);
2014-01-24 17:09:53 +00:00
if (op) {
2013-06-11 16:03:11 +00:00
op.remoteEnabled = true;
} else {
2016-07-22 19:26:07 +00:00
throw new Error(g.f('%s is not provided by the attached connector', operation));
2013-06-11 16:03:11 +00:00
}
2016-04-01 11:48:17 +00:00
};
2013-06-11 16:03:11 +00:00
/**
2014-03-12 23:28:46 +00:00
* Disable remote access to a data source operation. Each [connector](#connector) has its own set of set enabled
* and disabled operations. To list the operations, call `dataSource.operations()`.
*
2014-03-12 23:28:46 +00:00
*```js
* var oracle = loopback.createDataSource({
* connector: require('loopback-connector-oracle'),
* host: '...',
* ...
* });
* oracle.disableRemote('destroyAll');
* ```
* **Notes:**
*
2014-03-12 23:28:46 +00:00
* - Disabled operations will not be added to attached models.
2014-06-10 21:27:58 +00:00
* - Disabling the remoting for a method only affects client access (it will still be available from server models).
* - Data sources must enable / disable operations before attaching or creating models.
2013-08-13 16:37:09 +00:00
* @param {String} operation The operation name
2013-06-11 16:03:11 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.disableRemote = function(operation) {
2013-06-11 16:03:11 +00:00
var op = this.getOperation(operation);
2014-01-24 17:09:53 +00:00
if (op) {
2013-06-11 16:03:11 +00:00
op.remoteEnabled = false;
} else {
2016-07-22 19:26:07 +00:00
throw new Error(g.f('%s is not provided by the attached connector', operation));
2013-06-11 16:03:11 +00:00
}
2016-04-01 11:48:17 +00:00
};
2013-06-11 16:03:11 +00:00
/**
* Get an operation's metadata.
2013-08-13 16:37:09 +00:00
* @param {String} operation The operation name
2013-06-11 16:03:11 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.getOperation = function(operation) {
2013-06-11 16:03:11 +00:00
var ops = this.operations();
2013-06-11 18:11:10 +00:00
var opKeys = Object.keys(ops);
2014-01-24 17:09:53 +00:00
for (var i = 0; i < opKeys.length; i++) {
2013-06-11 18:11:10 +00:00
var op = ops[opKeys[i]];
2014-01-24 17:09:53 +00:00
if (op.name === operation) {
2013-06-11 16:03:11 +00:00
return op;
}
}
2016-04-01 11:48:17 +00:00
};
2013-06-11 16:03:11 +00:00
/**
2014-03-12 23:28:46 +00:00
* Return JSON object describing all operations.
*
* Example return value:
* ```js
* {
* find: {
* remoteEnabled: true,
* accepts: [...],
* returns: [...]
* enabled: true
* },
* save: {
* remoteEnabled: true,
* prototype: true,
* accepts: [...],
* returns: [...],
* enabled: true
* },
* ...
* }
* ```
2013-06-11 16:03:11 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.operations = function() {
2013-06-11 16:03:11 +00:00
return this._operations;
2016-04-01 11:48:17 +00:00
};
2013-06-11 16:03:11 +00:00
/**
2013-08-13 16:37:09 +00:00
* Define an operation to the data source
* @param {String} name The operation name
* @param {Object} options The options
2014-03-12 23:28:46 +00:00
* @param {Function} fn The function
2013-06-11 16:03:11 +00:00
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.defineOperation = function(name, options, fn) {
2013-06-11 16:03:11 +00:00
options.fn = fn;
2013-06-11 18:11:10 +00:00
options.name = name;
2013-06-11 16:03:11 +00:00
this._operations[name] = options;
};
2013-06-11 16:03:11 +00:00
2013-08-13 16:37:09 +00:00
/**
* Check if the backend is a relational DB
* @returns {Boolean}
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.isRelational = function() {
2014-01-24 17:09:53 +00:00
return this.connector && this.connector.relational;
};
2017-04-18 21:30:13 +00:00
/**
2014-03-12 23:28:46 +00:00
* Check if the data source is ready.
* Returns a Boolean value.
2017-04-26 20:43:44 +00:00
* @param {Object} obj Deferred method call if the connector is not fully connected yet
* @param {Object} args argument passing to method call.
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.ready = function(obj, args) {
2014-01-24 17:09:53 +00:00
var self = this;
if (this.connected) {
// Connected
return false;
}
2014-01-24 17:09:53 +00:00
var method = args.callee;
// Set up a callback after the connection is established to continue the method call
2013-10-11 05:47:26 +00:00
2014-08-27 16:42:16 +00:00
var onConnected = null, onError = null, timeoutHandle = null;
onConnected = function() {
2014-01-24 17:09:53 +00:00
// Remove the error handler
self.removeListener('error', onError);
2014-08-27 16:42:16 +00:00
if (timeoutHandle) {
clearTimeout(timeoutHandle);
}
var params = [].slice.call(args);
try {
method.apply(obj, params);
} catch (err) {
// Catch the exception and report it via callback
var cb = params.pop();
if (typeof cb === 'function') {
process.nextTick(function() {
cb(err);
});
} else {
throw err;
}
}
2014-01-24 17:09:53 +00:00
};
2016-04-01 11:48:17 +00:00
onError = function(err) {
2014-01-24 17:09:53 +00:00
// Remove the connected listener
self.removeListener('connected', onConnected);
2014-08-27 16:42:16 +00:00
if (timeoutHandle) {
clearTimeout(timeoutHandle);
}
2014-01-24 17:09:53 +00:00
var params = [].slice.call(args);
var cb = params.pop();
if (typeof cb === 'function') {
process.nextTick(function() {
cb(err);
});
}
2014-01-24 17:09:53 +00:00
};
this.once('connected', onConnected);
this.once('error', onError);
// Set up a timeout to cancel the invocation
var timeout = this.settings.connectionTimeout || 5000;
2016-04-01 11:48:17 +00:00
timeoutHandle = setTimeout(function() {
self.removeListener('error', onError);
self.removeListener('connected', onConnected);
var params = [].slice.call(args);
var cb = params.pop();
if (typeof cb === 'function') {
2016-07-22 19:26:07 +00:00
cb(new Error(g.f('Timeout in connecting after %s ms', timeout)));
}
}, timeout);
2014-01-24 17:09:53 +00:00
if (!this.connecting) {
this.connect();
}
return true;
};
2014-08-20 23:31:23 +00:00
/**
* Ping the underlying connector to test the connections
* @param {Function} [cb] Callback function
*/
2016-04-01 11:48:17 +00:00
DataSource.prototype.ping = function(cb) {
2014-08-20 23:31:23 +00:00
var self = this;
if (self.connector.ping) {
this.connector.ping(cb);
} else if (self.connector.discoverModelProperties) {
self.discoverModelProperties('dummy', {}, cb);
} else {
2016-04-01 11:48:17 +00:00
process.nextTick(function() {
2016-07-22 19:26:07 +00:00
var err = self.connected ? null : new Error(g.f('Not connected'));
2014-08-20 23:31:23 +00:00
cb(err);
});
}
};
2017-04-26 20:43:44 +00:00
/*! The hidden property call is too expensive so it is not used that much
*/
2013-05-17 17:54:14 +00:00
/**
2013-08-13 16:37:09 +00:00
* Define a hidden property
2017-04-26 20:43:44 +00:00
* It is an utility to define a property to the Object with info flags
2013-08-13 16:37:09 +00:00
* @param {Object} obj The property owner
* @param {String} key The property name
* @param {Mixed} value The default value
2013-05-17 17:54:14 +00:00
*/
2013-08-13 16:37:09 +00:00
function hiddenProperty(obj, key, value) {
2014-01-24 17:09:53 +00:00
Object.defineProperty(obj, key, {
writable: false,
enumerable: false,
configurable: false,
2016-04-01 11:48:17 +00:00
value: value,
2014-01-24 17:09:53 +00:00
});
2013-05-17 17:54:14 +00:00
}
/**
* Define readonly property on object
*
2013-08-13 16:37:09 +00:00
* @param {Object} obj The property owner
* @param {String} key The property name
* @param {Mixed} value The default value
2013-05-17 17:54:14 +00:00
*/
function defineReadonlyProp(obj, key, value) {
2014-01-24 17:09:53 +00:00
Object.defineProperty(obj, key, {
writable: false,
enumerable: true,
configurable: true,
2016-04-01 11:48:17 +00:00
value: value,
2014-01-24 17:09:53 +00:00
});
2013-05-17 17:54:14 +00:00
}
// Carry over a few properties/methods from the ModelBuilder as some tests use them
DataSource.Text = ModelBuilder.Text;
DataSource.JSON = ModelBuilder.JSON;
DataSource.Any = ModelBuilder.Any;