loopback-datasource-juggler/lib/datasource.js

1910 lines
55 KiB
JavaScript
Raw Normal View History

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');
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');
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`;
* some of the added methods may be remote methods.
2013-05-17 17:54:14 +00:00
*
2014-03-12 23:28:46 +00:00
* Define a data source for persisting models.
* Typically, you create a DataSource by calling createDataSource() on the LoopBack object; for example:
* ```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. The `settings` argument is an object that can have the following properties:
2013-05-17 17:54:14 +00:00
* - host
* - port
* - username
* - password
* - database
2014-03-12 23:28:46 +00:00
* - debug (Boolean, default is false)
2013-05-17 17:54:14 +00:00
*
2014-03-12 23:28:46 +00:00
* @desc 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
* });
* ```
2014-03-12 23:28:46 +00:00
* @class Define new DataSource
* @param {String} name Type of dataSource connector (mysql, mongoose, oracle, redis)
* @param {Object} settings Database-specific settings to establish connection (settings depend on specific connector). See above.
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;
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;
this.DataAccessObject = function () {
};
// define DataAccessObject methods
Object.keys(dao).forEach(function (name) {
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,
fnName: name
});
}
}.bind(this));
// define DataAccessObject.prototype methods
Object.keys(dao.prototype).forEach(function (name) {
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,
fnName: name
});
}
}.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
*/
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;
this.connector.log = function (query, start) {
dataSource.log(query, start);
};
this.connector.logger = function (query) {
var t1 = Date.now();
var log = this.log;
return function (q) {
log(q || query, t1);
};
};
}
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']
.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) {
2014-01-24 17:09:53 +00:00
/* ignore */
}
if (mod) {
break;
}
}
return mod;
}
/*!
* Resolve a connector by name
* @param name The connector name
* @returns {*}
* @private
*/
2014-01-24 17:09:53 +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) {
2014-07-14 15:56:33 +00:00
error = util.format('\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\n',
name, names.join('\n'), names[names.length -1]);
}
return {
connector: connector,
error: error
};
};
2013-08-13 16:37:09 +00:00
/**
* Set up the data source
* @param {String} name The name
* @param {Object} settings The settings
* @returns {*}
* @private
*/
2014-01-24 17:09:53 +00:00
DataSource.prototype.setup = function (name, settings) {
var dataSource = this;
var connector;
// support single settings object
if (name && typeof name === 'object' && !settings) {
settings = name;
name = undefined;
}
2013-05-17 17:54:14 +00:00
2014-01-24 17:09:53 +00:00
if (typeof settings === 'object') {
if (settings.initialize) {
connector = settings;
} else if (settings.connector) {
connector = settings.connector;
} else if (settings.adapter) {
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) {
debug('Settings: %j', this.settings);
2014-01-24 17:09:53 +00:00
}
// Disconnected by default
this.connected = false;
this.connecting = false;
2014-01-24 17:09:53 +00:00
if (typeof connector === 'string') {
name = connector;
connector = undefined;
}
name = name || (connector && connector.name);
this.name = name;
if (name && !connector) {
if (typeof name === 'object') {
// The first argument might be the connector itself
connector = name;
this.name = connector.name;
} else {
// The connector has not been resolved
var result = DataSource._resolveConnector(name);
connector = result.connector;
if (!connector) {
console.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) {
2013-05-17 17:54:14 +00:00
2014-01-24 17:09:53 +00:00
this._setupConnector();
// we have an connector now?
if (!this.connector) {
throw new Error('Connector is not defined correctly: it should create `connector` member of dataSource');
}
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
console.error('Connection fails: ', err, '\nIt will be retried for the next request.');
this.connecting = false;
}
2013-05-17 17:54:14 +00:00
2014-01-24 17:09:53 +00:00
}.bind(this);
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();
2013-05-17 17:54:14 +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
dataSource.connect = function (cb) {
var dataSource = this;
if (dataSource.connected || dataSource.connecting) {
process.nextTick(function () {
cb && cb();
});
return;
}
dataSource.connecting = true;
if (dataSource.connector.connect) {
dataSource.connector.connect(function (err, result) {
if (!err) {
dataSource.connected = true;
dataSource.connecting = false;
dataSource.emit('connected');
2013-05-17 17:54:14 +00:00
} else {
2014-01-24 17:09:53 +00:00
dataSource.connected = false;
dataSource.connecting = false;
dataSource.emit('error', err);
2013-05-17 17:54:14 +00:00
}
2014-01-24 17:09:53 +00:00
cb && cb(err, result);
});
} else {
process.nextTick(function () {
dataSource.connected = true;
dataSource.connecting = false;
dataSource.emit('connected');
cb && cb();
});
}
};
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;
}
2014-06-26 21:48:27 +00:00
DataSource.relationTypes = ['belongsTo', 'hasMany', 'hasAndBelongsToMany', 'hasOne'];
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
/*!
* Define scopes for the model class from the scopes object
* @param modelClass
* @param scopes
*/
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
}
}
};
/*!
* Define relations for the model class from the relations object
* @param modelClass
* @param relations
*/
2014-01-24 17:09:53 +00:00
DataSource.prototype.defineRelations = function (modelClass, relations) {
// Create a function for the closure in the loop
var createListener = function (name, relation, targetModel, throughModel) {
if (!isModelDataSourceAttached(targetModel)) {
targetModel.once('dataAccessConfigured', function (model) {
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();
params.as = name;
params.model = model;
2014-01-24 17:09:53 +00:00
if (throughModel) {
params.through = throughModel;
}
modelClass[relation.type].call(modelClass, name, params);
}
2014-01-24 17:09:53 +00:00
});
}
if (throughModel && !isModelDataSourceAttached(throughModel)) {
// Set up a listener to the through model
throughModel.once('dataAccessConfigured', function (model) {
2014-01-24 17:09:53 +00:00
if (isModelDataSourceAttached(targetModel)) {
// The target model is resolved
var params = traverse(relations).clone();
params.as = name;
params.model = targetModel;
params.through = model;
2014-01-24 17:09:53 +00:00
modelClass[relation.type].call(modelClass, name, params);
}
2014-01-24 17:09:53 +00:00
});
}
};
2014-01-24 17:09:53 +00:00
// Set up the relations
if (relations) {
for (var rn in relations) {
var r = relations[rn];
assert(DataSource.relationTypes.indexOf(r.type) !== -1, "Invalid relation type: " + r.type);
var targetModel = isModelClass(r.model) ? r.model : this.getModel(r.model, true);
var throughModel = null;
if (r.through) {
throughModel = isModelClass(r.through) ? r.through : this.getModel(r.through, true);
}
if ((!r.polymorphic && !isModelDataSourceAttached(targetModel)) || (throughModel && !isModelDataSourceAttached(throughModel))) {
2014-01-24 17:09:53 +00:00
// Create a listener to defer the relation set up
createListener(rn, r, targetModel, throughModel);
} else {
// The target model is resolved
var params = traverse(r).clone();
params.as = rn;
params.model = targetModel;
2014-01-24 17:09:53 +00:00
if (throughModel) {
params.through = throughModel;
}
2014-01-24 17:09:53 +00:00
modelClass[r.type].call(modelClass, rn, params);
}
}
2014-01-24 17:09:53 +00:00
}
};
/*!
* Set up the data access functions from the data source
* @param {Model} modelClass The model class
* @param {Object} settings The settings object
*/
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.properties[idName].type = idType;
}
if (this.connector.define) {
// pass control to connector
this.connector.define({
model: modelClass,
properties: modelClass.definition.properties,
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:
*
* ```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.
2014-03-12 23:28:46 +00:00
*
2013-05-17 17:54:14 +00:00
*/
2013-08-13 16:37:09 +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) {
throw new Error('Class name required');
}
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
*/
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
jutil.mixin(ModelCtor, DAO, {proxyFunctions: true, override: true});
2014-01-24 17:09:53 +00:00
// decorate operations as alias functions
2013-06-11 16:03:11 +00:00
Object.keys(ops).forEach(function (name) {
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)
.filter(function (key) {
// filter out the following keys
2014-01-24 17:09:53 +00:00
return ~[
'scope',
'fnName',
'prototype'
].indexOf(key);
})
.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
}
});
};
/**
2014-03-12 23:28:46 +00:00
* See ModelBuilder.getModel
*/
2014-01-24 17:09:53 +00:00
DataSource.prototype.getModel = function (name, forceCreate) {
return this.modelBuilder.getModel(name, forceCreate);
};
/**
2014-03-12 23:28:46 +00:00
* See ModelBuilder.getModelDefinition
*/
2014-01-24 17:09:53 +00:00
DataSource.prototype.getModelDefinition = function (name) {
return this.modelBuilder.getModelDefinition(name);
};
/**
* Get the data source types
* @returns {String[]} The data source type, such as ['db', 'nosql', 'mongodb'],
* ['rest'], or ['db', 'rdbms', 'mysql']
*/
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.
* @param {String} types Type name or an array of type names. Can also be array of Strings.
* @returns {Boolean} true if all types are supported by the data source
*/
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;
}
};
/**
* Attach an existing model to a data source.
2013-08-13 16:37:09 +00:00
*
* @param {Function} modelClass The model constructor
*/
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-11-12 06:06:43 +00:00
2013-08-13 16:37:09 +00:00
};
2013-05-17 21:41:04 +00:00
/**
* Define single property named `prop` on `model`
*
2014-03-12 23:28:46 +00:00
* @param {String} model Name of model
* @param {String} prop Name of property
* @param {Object} params Property settings
2013-05-17 21:41:04 +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
/**
* Drop each model table and re-create.
2014-06-10 21:27:58 +00:00
* This method applies only to database connectors. For MongoDB, it drops and creates indexes.
*
* **WARNING**: Calling this function deletes all data! Use `autoupdate()` to preserve data.
*
* @param {String} model Model to migrate. If not present, apply to all models. Can also be an array of Strings.
2014-06-10 21:27:58 +00:00
* @param {Function} [callback] Callback function. Optional.
*
2014-06-10 21:27:58 +00:00
2013-05-17 17:54:14 +00:00
*/
DataSource.prototype.automigrate = function (models, cb) {
2014-01-24 17:09:53 +00:00
this.freeze();
if (this.connector.automigrate) {
this.connector.automigrate(models, cb);
} else {
if ((!cb) && ('function' === typeof models)) {
cb = models;
models = undefined;
2013-05-17 17:54:14 +00:00
}
2014-01-24 17:09:53 +00:00
cb && process.nextTick(cb);
}
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.
*
* @param {String} model Model to migrate. If not present, apply to all models. Can also be an array of Strings.
2013-08-13 16:37:09 +00:00
* @param {Function} [cb] The callback function
2013-05-17 17:54:14 +00:00
*/
DataSource.prototype.autoupdate = function (models, cb) {
2014-01-24 17:09:53 +00:00
this.freeze();
if (this.connector.autoupdate) {
this.connector.autoupdate(models, cb);
} else {
if ((!cb) && ('function' === typeof models)) {
cb = models;
models = undefined;
2013-05-17 17:54:14 +00:00
}
2014-01-24 17:09:53 +00:00
cb && process.nextTick(cb);
}
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
*
* @param {Object} options The options
2014-03-12 23:28:46 +00:00
* @param {Function} Callback function. Optional.
2014-06-10 21:27:58 +00:00
* @options {Object} options Discovery options. See below.
* @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
2013-08-13 16:37:09 +00:00
*
2013-05-17 17:54:14 +00:00
*/
DataSource.prototype.discoverModelDefinitions = function (options, cb) {
2014-01-24 17:09:53 +00:00
this.freeze();
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
}
2013-05-17 17:54:14 +00:00
};
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
2013-08-13 16:37:09 +00:00
* @returns {*}
*/
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|
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
2013-08-13 16:37:09 +00:00
*
2013-05-17 17:54:14 +00:00
*/
2013-08-13 16:37:09 +00:00
DataSource.prototype.discoverModelProperties = function (modelName, options, cb) {
2013-05-17 17:54:14 +00:00
this.freeze();
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
}
};
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 {*}
*/
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)
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
2013-05-17 17:54:14 +00:00
*/
2014-01-24 17:09:53 +00:00
DataSource.prototype.discoverPrimaryKeys = function (modelName, options, cb) {
this.freeze();
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
}
2013-08-13 16:37:09 +00:00
};
2013-05-17 17:54:14 +00:00
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
* @property {String} owner|schema The database owner orschema
2013-08-13 16:37:09 +00:00
* @returns {*}
*/
2014-01-24 17:09:53 +00:00
DataSource.prototype.discoverPrimaryKeysSync = function (modelName, options) {
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
2013-05-17 17:54:14 +00:00
*
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
*
2013-05-17 17:54:14 +00:00
*/
2014-01-24 17:09:53 +00:00
DataSource.prototype.discoverForeignKeys = function (modelName, options, cb) {
this.freeze();
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
}
2013-08-13 16:37:09 +00:00
};
2013-05-17 17:54:14 +00:00
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 {*}
*/
2014-01-24 17:09:53 +00:00
DataSource.prototype.discoverForeignKeysSync = function (modelName, options) {
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.
*
* 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
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
2013-06-03 06:00:11 +00:00
*/
2014-01-24 17:09:53 +00:00
DataSource.prototype.discoverExportedForeignKeys = function (modelName, options, cb) {
this.freeze();
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
}
2013-08-13 16:37:09 +00:00
};
2013-06-03 06:00:11 +00:00
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 {*}
*/
2014-01-24 17:09:53 +00:00
DataSource.prototype.discoverExportedForeignKeysSync = function (modelName, options) {
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:**
*
* ```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
*
* @param {String} modelName The model name
* @param {Object} [options] The options
* @param {Function} [cb] The callback function
*/
DataSource.prototype.discoverSchema = function (modelName, 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;
2014-01-24 17:09:53 +00:00
this.discoverSchemas(modelName, options, function (err, schemas) {
if (err) {
cb && cb(err, schemas);
return;
}
for (var s in schemas) {
cb && cb(null, schemas[s]);
return;
}
});
2014-03-04 17:42:55 +00:00
};
2013-06-02 06:03:25 +00:00
2013-05-21 21:25:23 +00:00
/**
2014-06-10 21:27:58 +00:00
* Discover schema from a given modelName/view.
2013-08-13 16:37:09 +00:00
*
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
2013-05-21 21:25:23 +00:00
*/
DataSource.prototype.discoverSchemas = function (modelName, 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 = {};
}
var self = this;
var schemaName = this.connector.name || this.name;
var tasks = [
this.discoverModelProperties.bind(this, modelName, options),
this.discoverPrimaryKeys.bind(this, modelName, options) ];
var followingRelations = options.associations || options.relations;
if (followingRelations) {
tasks.push(this.discoverForeignKeys.bind(this, modelName, options));
}
async.parallel(tasks, function (err, results) {
if (err) {
cb && cb(err);
return;
}
2014-01-24 17:09:53 +00:00
var columns = results[0];
if (!columns || columns.length === 0) {
cb && cb();
return;
}
2014-01-24 17:09:53 +00:00
// Handle primary keys
var primaryKeys = results[1];
var pks = {};
primaryKeys.forEach(function (pk) {
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 = {
name: fromDBName(modelName, false),
options: {
idInjection: false // DO NOT add id property
},
properties: {
}
};
2014-01-24 17:09:53 +00:00
schema.options[schemaName] = {
schema: columns[0].owner,
table: modelName
};
2014-01-24 17:09:53 +00:00
columns.forEach(function (item) {
var i = item;
var propName = fromDBName(item.columnName, true);
schema.properties[propName] = {
type: item.type,
required: (item.nullable === 'N'),
length: item.dataLength,
precision: item.dataPrecision,
scale: item.dataScale
};
if (pks[item.columnName]) {
schema.properties[propName].id = pks[item.columnName];
}
schema.properties[propName][schemaName] = {
columnName: i.columnName,
dataType: i.dataType,
dataLength: i.dataLength,
dataPrecision: item.dataPrecision,
dataScale: item.dataScale,
nullable: i.nullable
};
});
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;
}
2014-01-24 17:09:53 +00:00
var otherTables = {};
if (followingRelations) {
// Handle foreign keys
var fks = {};
var foreignKeys = results[2];
foreignKeys.forEach(function (fk) {
var fkInfo = {
keySeq: fk.keySeq,
owner: fk.pkOwner,
tableName: fk.pkTableName,
columnName: fk.pkColumnName
};
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 = {};
foreignKeys.forEach(function (fk) {
var propName = fromDBName(fk.pkTableName, true);
schema.options.relations[propName] = {
model: fromDBName(fk.pkTableName, false),
type: 'belongsTo',
foreignKey: fromDBName(fk.fkColumnName, true)
};
2014-01-24 17:09:53 +00:00
var key = fk.pkOwner + '.' + fk.pkTableName;
if (!options.visited.hasOwnProperty(key) && !otherTables.hasOwnProperty(key)) {
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) {
cb && cb(null, 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];
}
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));
}
async.parallel(moreTasks, function (err, results) {
var result = results && results[0];
cb && cb(err, result);
});
}
});
};
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.
2013-06-02 06:03:25 +00:00
*/
DataSource.prototype.discoverSchemasSync = function (modelName, options) {
2014-01-24 17:09:53 +00:00
var self = this;
var schemaName = this.name || 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
2014-01-24 17:09:53 +00:00
// Handle primary keys
var primaryKeys = this.discoverPrimaryKeysSync(modelName, options);
var pks = {};
primaryKeys.forEach(function (pk) {
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: fromDBName(modelName, false),
options: {
idInjection: false // DO NOT add id property
},
properties: {
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
schema.options[schemaName] = {
schema: columns.length > 0 && columns[0].owner,
table: modelName
};
columns.forEach(function (item) {
var i = item;
var propName = fromDBName(item.columnName, true);
schema.properties[propName] = {
type: item.type,
required: (item.nullable === 'N'),
length: item.dataLength,
precision: item.dataPrecision,
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][schemaName] = {
columnName: i.columnName,
dataType: i.dataType,
dataLength: i.dataLength,
dataPrecision: item.dataPrecision,
dataScale: item.dataScale,
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);
foreignKeys.forEach(function (fk) {
var fkInfo = {
keySeq: fk.keySeq,
owner: fk.pkOwner,
tableName: fk.pkTableName,
columnName: fk.pkColumnName
};
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 = {};
foreignKeys.forEach(function (fk) {
var propName = fromDBName(fk.pkTableName, true);
schema.options.relations[propName] = {
model: fromDBName(fk.pkTableName, false),
type: 'belongsTo',
foreignKey: fromDBName(fk.fkColumnName, true)
};
var key = fk.pkOwner + '.' + fk.pkTableName;
if (!options.visited.hasOwnProperty(key) && !otherTables.hasOwnProperty(key)) {
otherTables[key] = {owner: fk.pkOwner, tableName: fk.pkTableName};
}
});
}
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-06-02 06:03:25 +00:00
2014-01-24 17:09:53 +00:00
}
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
2013-06-02 06:03:25 +00:00
*/
DataSource.prototype.discoverAndBuildModels = function (modelName, options, cb) {
2014-01-24 17:09:53 +00:00
var self = this;
this.discoverSchemas(modelName, options, function (err, schemas) {
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];
schemaList.push(schema);
}
2013-06-02 06:03:25 +00:00
2014-01-24 17:09:53 +00:00
var models = self.modelBuilder.buildModels(schemaList);
// Now attach the models to the data source
for (var m in models) {
models[m].attachTo(self);
}
cb && cb(err, models);
});
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 given owner/modelName synchronously.
2013-08-13 16:37:09 +00:00
*
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 {String} modelName The model name
* @param {Object} [options] The options
2013-06-02 06:03:25 +00:00
*/
DataSource.prototype.discoverAndBuildModelsSync = function (modelName, 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];
schemaList.push(schema);
}
2013-06-02 06:03:25 +00:00
2014-01-24 17:09:53 +00:00
var models = this.modelBuilder.buildModels(schemaList);
return models;
2013-08-13 16:37:09 +00:00
};
2013-06-02 06:03:25 +00:00
2013-05-17 17:54:14 +00:00
/**
* Check whether migrations needed
2014-06-10 21:27:58 +00:00
* This method applies only to SQL connectors.
* @param {String|String[]} [models] A model name or an array of model names. If not present, apply to all models.
2013-05-17 17:54:14 +00:00
*/
2013-08-13 16:37:09 +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) {
process.nextTick(function () {
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
* chema 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
*/
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
2013-05-17 17:54:14 +00:00
*/
DataSource.prototype.freeze = function freeze() {
2014-03-04 17:42:55 +00:00
if(!this.connector) {
throw new Error('The connector has not been initialized.');
}
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
/**
* Return table name for specified `modelName`
2013-08-13 16:37:09 +00:00
* @param {String} modelName The model name
2013-05-17 17:54:14 +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.
*/
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
*/
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
*/
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
*/
2014-01-24 17:09:53 +00:00
DataSource.prototype.idColumnName = function (modelName) {
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
*/
2014-01-24 17:09:53 +00:00
DataSource.prototype.idName = function (modelName) {
if (!this.getModelDefinition(modelName).idName) {
console.error('No id name', this.getModelDefinition(modelName));
}
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
*/
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
*/
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
2013-05-17 17:54:14 +00:00
*/
DataSource.prototype.defineForeignKey = function defineForeignKey(className, key, foreignClassName) {
var pkType = null;
var foreignModel = this.getModelDefinition(foreignClassName);
var 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
}
2014-01-24 17:09:53 +00:00
if (this.connector.defineForeignKey) {
var cb = function (err, keyType) {
if (err) throw err;
// Add the foreign key property to the data source _models
this.defineProperty(className, key, {type: keyType || pkType});
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, {type: pkType});
2014-01-24 17:09:53 +00:00
}
2013-05-17 17:54:14 +00:00
};
/**
* Close database connection
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) {
2014-01-24 17:09:53 +00:00
var self = this;
if (this.connected && (typeof this.connector.disconnect === 'function')) {
this.connector.disconnect(function (err, result) {
self.connected = false;
cb && cb(err, result);
});
} else {
process.nextTick(function () {
cb && cb();
});
}
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
* @returns {Function} The copy of the model constructor
*
* @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)) {
2013-05-17 17:54:14 +00:00
2014-01-24 17:09:53 +00:00
// store class in model pool
dataSource.modelBuilder.models[className] = Slave;
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,
settings: md.settings
});
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
/**
*
* @returns {EventEmitter}
* @private
*/
2014-01-24 17:09:53 +00:00
DataSource.prototype.transaction = function () {
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.name = dataSource.name;
transaction.settings = dataSource.settings;
transaction.connected = false;
transaction.connecting = false;
transaction.connector = dataSource.connector.transaction();
// create blank models pool
transaction.modelBuilder = new ModelBuilder();
transaction.models = transaction.modelBuilder.models;
transaction.definitions = transaction.modelBuilder.definitions;
for (var i in dataSource.modelBuilder.models) {
dataSource.copyModel.call(transaction, dataSource.modelBuilder.models[i]);
}
2013-05-17 17:54:14 +00:00
2014-01-24 17:09:53 +00:00
transaction.exec = function (cb) {
transaction.connector.exec(cb);
};
2013-05-17 17:54:14 +00:00
2014-01-24 17:09:53 +00:00
return transaction;
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
*/
DataSource.prototype.enableRemote = function (operation) {
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 {
2013-06-11 18:11:10 +00:00
throw new Error(operation + ' is not provided by the attached connector');
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()`.
*
*```js
* var oracle = loopback.createDataSource({
* connector: require('loopback-connector-oracle'),
* host: '...',
* ...
* });
* oracle.disableRemote('destroyAll');
* ```
* **Notes:**
*
* - 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
*/
DataSource.prototype.disableRemote = function (operation) {
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 {
2013-06-11 18:11:10 +00:00
throw new Error(operation + ' is not provided by the attached connector');
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
*/
DataSource.prototype.getOperation = function (operation) {
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;
}
}
}
/**
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
*/
DataSource.prototype.operations = function () {
return this._operations;
}
/**
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
*/
DataSource.prototype.defineOperation = function (name, options, fn) {
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}
*/
2014-01-24 17:09:53 +00:00
DataSource.prototype.isRelational = function () {
return this.connector && this.connector.relational;
};
2014-06-10 21:27:58 +00:00
/*!
2014-03-12 23:28:46 +00:00
* Check if the data source is ready.
* Returns a Boolean value.
2014-06-10 21:27:58 +00:00
* @param {Object} obj ?
* @param {Object} args ?
*/
2014-01-24 17:09:53 +00:00
DataSource.prototype.ready = function (obj, args) {
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-01-24 17:09:53 +00:00
var onConnected = null, onError = null;
onConnected = function () {
// Remove the error handler
self.removeListener('error', onError);
method.apply(obj, [].slice.call(args));
};
onError = function (err) {
// Remove the connected listener
self.removeListener('connected', onConnected);
var params = [].slice.call(args);
var cb = params.pop();
if (typeof cb === 'function') {
cb(err);
}
2014-01-24 17:09:53 +00:00
};
this.once('connected', onConnected);
this.once('error', onError);
if (!this.connecting) {
this.connect();
}
return true;
};
2013-05-17 17:54:14 +00:00
/**
2013-08-13 16:37:09 +00:00
* Define a hidden property
* @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,
value: value
});
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,
value: value
});
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;
/*!
* @deprecated Use ModelBuilder.registerType instead
* @param type
*/
2014-01-24 17:09:53 +00:00
DataSource.registerType = function (type) {
ModelBuilder.registerType(type);
};