More renames: schema -> dataSource, adapter -> connector
This commit is contained in:
parent
51286684bd
commit
6af4b1ba2f
|
@ -4,7 +4,7 @@ var path = require('path'),
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load LDL schemas from a json doc
|
* Load LDL schemas from a json doc
|
||||||
* @param schemaFile The schema json file
|
* @param schemaFile The dataSource json file
|
||||||
* @returns A map of schemas keyed by name
|
* @returns A map of schemas keyed by name
|
||||||
*/
|
*/
|
||||||
function loadSchemasSync(schemaFile, dataSource) {
|
function loadSchemasSync(schemaFile, dataSource) {
|
||||||
|
@ -13,7 +13,7 @@ function loadSchemasSync(schemaFile, dataSource) {
|
||||||
dataSource = new DataSource('memory');
|
dataSource = new DataSource('memory');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read the schema JSON file
|
// Read the dataSource JSON file
|
||||||
var schemas = JSON.parse(fs.readFileSync(schemaFile));
|
var schemas = JSON.parse(fs.readFileSync(schemaFile));
|
||||||
|
|
||||||
return dataSource.buildModels(schemas);
|
return dataSource.buildModels(schemas);
|
||||||
|
|
|
@ -142,38 +142,38 @@ function filtering(res, model, filter, instance) {
|
||||||
/**
|
/**
|
||||||
* Connection/Disconnection
|
* Connection/Disconnection
|
||||||
*/
|
*/
|
||||||
exports.initialize = function(schema, callback) {
|
exports.initialize = function(dataSource, callback) {
|
||||||
if (!cradle) return;
|
if (!cradle) return;
|
||||||
|
|
||||||
// when using cradle if we dont wait for the schema to be connected, the models fails to load correctly.
|
// when using cradle if we dont wait for the dataSource to be connected, the models fails to load correctly.
|
||||||
schema.waitForConnect = true;
|
dataSource.waitForConnect = true;
|
||||||
if (!schema.settings.url) {
|
if (!dataSource.settings.url) {
|
||||||
var host = schema.settings.host || 'localhost';
|
var host = dataSource.settings.host || 'localhost';
|
||||||
var port = schema.settings.port || '5984';
|
var port = dataSource.settings.port || '5984';
|
||||||
var options = schema.settings.options || {
|
var options = dataSource.settings.options || {
|
||||||
cache: true,
|
cache: true,
|
||||||
raw: false
|
raw: false
|
||||||
};
|
};
|
||||||
if (schema.settings.username) {
|
if (dataSource.settings.username) {
|
||||||
options.auth = {};
|
options.auth = {};
|
||||||
options.auth.username = schema.settings.username;
|
options.auth.username = dataSource.settings.username;
|
||||||
if (schema.settings.password) {
|
if (dataSource.settings.password) {
|
||||||
options.auth.password = schema.settings.password;
|
options.auth.password = dataSource.settings.password;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
var database = schema.settings.database || 'loopback-data';
|
var database = dataSource.settings.database || 'loopback-data';
|
||||||
|
|
||||||
schema.settings.host = host;
|
dataSource.settings.host = host;
|
||||||
schema.settings.port = port;
|
dataSource.settings.port = port;
|
||||||
schema.settings.database = database;
|
dataSource.settings.database = database;
|
||||||
schema.settings.options = options;
|
dataSource.settings.options = options;
|
||||||
}
|
}
|
||||||
schema.client = new(cradle.Connection)(schema.settings.host, schema.settings.port,schema.settings.options).database(schema.settings.database);
|
dataSource.client = new(cradle.Connection)(dataSource.settings.host, dataSource.settings.port,dataSource.settings.options).database(dataSource.settings.database);
|
||||||
|
|
||||||
createdbif(
|
createdbif(
|
||||||
schema.client,
|
dataSource.client,
|
||||||
errorHandler(callback, function() {
|
errorHandler(callback, function() {
|
||||||
schema.adapter = new CradleAdapter(schema.client);
|
dataSource.connector = new CradleAdapter(dataSource.client);
|
||||||
process.nextTick(callback);
|
process.nextTick(callback);
|
||||||
}));
|
}));
|
||||||
};
|
};
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
exports.initialize = function initializeSchema(schema, callback) {
|
exports.initialize = function initializeSchema(dataSource, callback) {
|
||||||
schema.adapter = new WebService();
|
dataSource.connector = new WebService();
|
||||||
process.nextTick(callback);
|
process.nextTick(callback);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
var geo = require('../geo');
|
var geo = require('../geo');
|
||||||
var utils = require('../utils');
|
var utils = require('../utils');
|
||||||
|
|
||||||
exports.initialize = function initializeSchema(schema, callback) {
|
exports.initialize = function initializeSchema(dataSource, callback) {
|
||||||
schema.adapter = new Memory();
|
dataSource.connector = new Memory();
|
||||||
schema.adapter.connect(callback);
|
dataSource.connector.connect(callback);
|
||||||
};
|
};
|
||||||
|
|
||||||
exports.Memory = Memory;
|
exports.Memory = Memory;
|
||||||
|
|
|
@ -5,9 +5,9 @@ var safeRequire = require('../utils').safeRequire;
|
||||||
*/
|
*/
|
||||||
var neo4j = safeRequire('neo4j');
|
var neo4j = safeRequire('neo4j');
|
||||||
|
|
||||||
exports.initialize = function initializeSchema(schema, callback) {
|
exports.initialize = function initializeSchema(dataSource, callback) {
|
||||||
schema.client = new neo4j.GraphDatabase(schema.settings.url);
|
dataSource.client = new neo4j.GraphDatabase(dataSource.settings.url);
|
||||||
schema.adapter = new Neo4j(schema.client);
|
dataSource.connector = new Neo4j(dataSource.client);
|
||||||
process.nextTick(callback);
|
process.nextTick(callback);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
@ -6,12 +6,12 @@ var safeRequire = require('../utils').safeRequire;
|
||||||
var uuid = require('node-uuid');
|
var uuid = require('node-uuid');
|
||||||
var riak = safeRequire('riak-js');
|
var riak = safeRequire('riak-js');
|
||||||
|
|
||||||
exports.initialize = function initializeSchema(schema, callback) {
|
exports.initialize = function initializeSchema(dataSource, callback) {
|
||||||
schema.client = riak.getClient({
|
dataSource.client = riak.getClient({
|
||||||
host: schema.settings.host || '127.0.0.1',
|
host: dataSource.settings.host || '127.0.0.1',
|
||||||
port: schema.settings.port || 8091
|
port: dataSource.settings.port || 8091
|
||||||
});
|
});
|
||||||
schema.adapter = new Riak(schema.client);
|
dataSource.connector = new Riak(dataSource.client);
|
||||||
};
|
};
|
||||||
|
|
||||||
function Riak(client) {
|
function Riak(client) {
|
||||||
|
|
72
lib/dao.js
72
lib/dao.js
|
@ -20,9 +20,9 @@ var fieldsToArray = require('./utils').fieldsToArray;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* DAO class - base class for all persist objects
|
* DAO class - base class for all persist objects
|
||||||
* provides **common API** to access any database adapter.
|
* provides **common API** to access any database connector.
|
||||||
* This class describes only abstract behavior layer, refer to `lib/adapters/*.js`
|
* This class describes only abstract behavior layer, refer to `lib/adapters/*.js`
|
||||||
* to learn more about specific adapter implementations
|
* to learn more about specific connector implementations
|
||||||
*
|
*
|
||||||
* `DataAccessObject` mixes `Inclusion` classes methods
|
* `DataAccessObject` mixes `Inclusion` classes methods
|
||||||
*
|
*
|
||||||
|
@ -41,7 +41,7 @@ function DataAccessObject() {
|
||||||
|
|
||||||
|
|
||||||
DataAccessObject._forDB = function (data) {
|
DataAccessObject._forDB = function (data) {
|
||||||
if(!(this.schema.isRelational && this.schema.isRelational())) {
|
if(!(this.dataSource.isRelational && this.dataSource.isRelational())) {
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
var res = {};
|
var res = {};
|
||||||
|
@ -67,7 +67,7 @@ DataAccessObject._forDB = function (data) {
|
||||||
* - instance (null or Model)
|
* - instance (null or Model)
|
||||||
*/
|
*/
|
||||||
DataAccessObject.create = function (data, callback) {
|
DataAccessObject.create = function (data, callback) {
|
||||||
if (stillConnecting(this.schema, this, arguments)) return;
|
if (stillConnecting(this.dataSource, this, arguments)) return;
|
||||||
|
|
||||||
var Model = this;
|
var Model = this;
|
||||||
var modelName = Model.modelName;
|
var modelName = Model.modelName;
|
||||||
|
@ -168,16 +168,16 @@ DataAccessObject.create.accepts = {arg: 'data', type: 'object', http: {source: '
|
||||||
DataAccessObject.create.returns = {arg: 'data', type: 'object'};
|
DataAccessObject.create.returns = {arg: 'data', type: 'object'};
|
||||||
DataAccessObject.create.http = {verb: 'post', path: '/'};
|
DataAccessObject.create.http = {verb: 'post', path: '/'};
|
||||||
|
|
||||||
function stillConnecting(schema, obj, args) {
|
function stillConnecting(dataSource, obj, args) {
|
||||||
if (schema.connected) return false; // Connected
|
if (dataSource.connected) return false; // Connected
|
||||||
|
|
||||||
var method = args.callee;
|
var method = args.callee;
|
||||||
// Set up a callback after the connection is established to continue the method call
|
// Set up a callback after the connection is established to continue the method call
|
||||||
schema.once('connected', function () {
|
dataSource.once('connected', function () {
|
||||||
method.apply(obj, [].slice.call(args));
|
method.apply(obj, [].slice.call(args));
|
||||||
});
|
});
|
||||||
if (!schema.connecting) {
|
if (!dataSource.connecting) {
|
||||||
schema.connect();
|
dataSource.connect();
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
@ -186,13 +186,13 @@ function stillConnecting(schema, obj, args) {
|
||||||
* Update or insert
|
* Update or insert
|
||||||
*/
|
*/
|
||||||
DataAccessObject.upsert = DataAccessObject.updateOrCreate = function upsert(data, callback) {
|
DataAccessObject.upsert = DataAccessObject.updateOrCreate = function upsert(data, callback) {
|
||||||
if (stillConnecting(this.schema, this, arguments)) return;
|
if (stillConnecting(this.dataSource, this, arguments)) return;
|
||||||
|
|
||||||
var Model = this;
|
var Model = this;
|
||||||
if (!data.id) return this.create(data, callback);
|
if (!data.id) return this.create(data, callback);
|
||||||
if (this.schema.adapter.updateOrCreate) {
|
if (this.dataSource.connector.updateOrCreate) {
|
||||||
var inst = new Model(data);
|
var inst = new Model(data);
|
||||||
this.schema.adapter.updateOrCreate(Model.modelName, inst.toObject(true), function (err, data) {
|
this.dataSource.connector.updateOrCreate(Model.modelName, inst.toObject(true), function (err, data) {
|
||||||
var obj;
|
var obj;
|
||||||
if (data) {
|
if (data) {
|
||||||
inst._initProperties(data);
|
inst._initProperties(data);
|
||||||
|
@ -250,10 +250,10 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, callback) {
|
||||||
* @param {Function} cb - callbacl called with (err, exists: Bool)
|
* @param {Function} cb - callbacl called with (err, exists: Bool)
|
||||||
*/
|
*/
|
||||||
DataAccessObject.exists = function exists(id, cb) {
|
DataAccessObject.exists = function exists(id, cb) {
|
||||||
if (stillConnecting(this.schema, this, arguments)) return;
|
if (stillConnecting(this.dataSource, this, arguments)) return;
|
||||||
|
|
||||||
if (id) {
|
if (id) {
|
||||||
this.schema.adapter.exists(this.modelName, id, cb);
|
this.dataSource.connector.exists(this.modelName, id, cb);
|
||||||
} else {
|
} else {
|
||||||
cb(new Error('Model::exists requires positive id argument'));
|
cb(new Error('Model::exists requires positive id argument'));
|
||||||
}
|
}
|
||||||
|
@ -270,9 +270,9 @@ DataAccessObject.exists.accepts = {arg: 'id', type: 'any'};
|
||||||
* @param {Function} cb - callback called with (err, instance)
|
* @param {Function} cb - callback called with (err, instance)
|
||||||
*/
|
*/
|
||||||
DataAccessObject.findById = function find(id, cb) {
|
DataAccessObject.findById = function find(id, cb) {
|
||||||
if (stillConnecting(this.schema, this, arguments)) return;
|
if (stillConnecting(this.dataSource, this, arguments)) return;
|
||||||
|
|
||||||
this.schema.adapter.find(this.modelName, id, function (err, data) {
|
this.dataSource.connector.find(this.modelName, id, function (err, data) {
|
||||||
var obj = null;
|
var obj = null;
|
||||||
if (data) {
|
if (data) {
|
||||||
if (!data.id) {
|
if (!data.id) {
|
||||||
|
@ -318,7 +318,7 @@ DataAccessObject.all = function () {
|
||||||
*/
|
*/
|
||||||
|
|
||||||
DataAccessObject.find = function find(params, cb) {
|
DataAccessObject.find = function find(params, cb) {
|
||||||
if (stillConnecting(this.schema, this, arguments)) return;
|
if (stillConnecting(this.dataSource, this, arguments)) return;
|
||||||
|
|
||||||
if (arguments.length === 1) {
|
if (arguments.length === 1) {
|
||||||
cb = params;
|
cb = params;
|
||||||
|
@ -329,7 +329,7 @@ DataAccessObject.find = function find(params, cb) {
|
||||||
params = params || {};
|
params = params || {};
|
||||||
var fields = params.fields;
|
var fields = params.fields;
|
||||||
var near = params && geo.nearFilter(params.where);
|
var near = params && geo.nearFilter(params.where);
|
||||||
var supportsGeo = !!this.schema.adapter.buildNearFilter;
|
var supportsGeo = !!this.dataSource.connector.buildNearFilter;
|
||||||
|
|
||||||
// normalize fields as array of included property names
|
// normalize fields as array of included property names
|
||||||
if(fields) {
|
if(fields) {
|
||||||
|
@ -339,11 +339,11 @@ DataAccessObject.find = function find(params, cb) {
|
||||||
if(near) {
|
if(near) {
|
||||||
if(supportsGeo) {
|
if(supportsGeo) {
|
||||||
// convert it
|
// convert it
|
||||||
this.schema.adapter.buildNearFilter(params, near);
|
this.dataSource.connector.buildNearFilter(params, near);
|
||||||
} else if(params.where) {
|
} else if(params.where) {
|
||||||
// do in memory query
|
// do in memory query
|
||||||
// using all documents
|
// using all documents
|
||||||
this.schema.adapter.all(this.modelName, {}, function (err, data) {
|
this.dataSource.connector.all(this.modelName, {}, function (err, data) {
|
||||||
var memory = new Memory();
|
var memory = new Memory();
|
||||||
var modelName = constr.modelName;
|
var modelName = constr.modelName;
|
||||||
|
|
||||||
|
@ -351,8 +351,8 @@ DataAccessObject.find = function find(params, cb) {
|
||||||
cb(err);
|
cb(err);
|
||||||
} else if(Array.isArray(data)) {
|
} else if(Array.isArray(data)) {
|
||||||
memory.define({
|
memory.define({
|
||||||
properties: constr.schema.definitions[constr.modelName].properties,
|
properties: constr.dataSource.definitions[constr.modelName].properties,
|
||||||
settings: constr.schema.definitions[constr.modelName].settings,
|
settings: constr.dataSource.definitions[constr.modelName].settings,
|
||||||
model: constr
|
model: constr
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -373,7 +373,7 @@ DataAccessObject.find = function find(params, cb) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
this.schema.adapter.all(this.modelName, params, function (err, data) {
|
this.dataSource.connector.all(this.modelName, params, function (err, data) {
|
||||||
if (data && data.forEach) {
|
if (data && data.forEach) {
|
||||||
data.forEach(function (d, i) {
|
data.forEach(function (d, i) {
|
||||||
var obj = new constr;
|
var obj = new constr;
|
||||||
|
@ -414,7 +414,7 @@ DataAccessObject.find.http = [
|
||||||
* @param {Function} cb - callback called with (err, instance)
|
* @param {Function} cb - callback called with (err, instance)
|
||||||
*/
|
*/
|
||||||
DataAccessObject.findOne = function findOne(params, cb) {
|
DataAccessObject.findOne = function findOne(params, cb) {
|
||||||
if (stillConnecting(this.schema, this, arguments)) return;
|
if (stillConnecting(this.dataSource, this, arguments)) return;
|
||||||
|
|
||||||
if (typeof params === 'function') {
|
if (typeof params === 'function') {
|
||||||
cb = params;
|
cb = params;
|
||||||
|
@ -437,9 +437,9 @@ DataAccessObject.findOne.returns = {arg: 'data', type: 'object'};
|
||||||
*/
|
*/
|
||||||
DataAccessObject.deleteAll =
|
DataAccessObject.deleteAll =
|
||||||
DataAccessObject.destroyAll = function destroyAll(cb) {
|
DataAccessObject.destroyAll = function destroyAll(cb) {
|
||||||
if (stillConnecting(this.schema, this, arguments)) return;
|
if (stillConnecting(this.dataSource, this, arguments)) return;
|
||||||
|
|
||||||
this.schema.adapter.destroyAll(this.modelName, function (err) {
|
this.dataSource.connector.destroyAll(this.modelName, function (err) {
|
||||||
if ('function' === typeof cb) {
|
if ('function' === typeof cb) {
|
||||||
cb(err);
|
cb(err);
|
||||||
}
|
}
|
||||||
|
@ -452,9 +452,9 @@ DataAccessObject.destroyAll = function destroyAll(cb) {
|
||||||
*/
|
*/
|
||||||
DataAccessObject.deleteById =
|
DataAccessObject.deleteById =
|
||||||
DataAccessObject.destroyById = function deleteById(id, cb) {
|
DataAccessObject.destroyById = function deleteById(id, cb) {
|
||||||
if (stillConnecting(this.schema, this, arguments)) return;
|
if (stillConnecting(this.dataSource, this, arguments)) return;
|
||||||
|
|
||||||
this.schema.adapter.destroy(this.modelName, id, function (err) {
|
this.dataSource.connector.destroy(this.modelName, id, function (err) {
|
||||||
if ('function' === typeof cb) {
|
if ('function' === typeof cb) {
|
||||||
cb(err);
|
cb(err);
|
||||||
}
|
}
|
||||||
|
@ -478,13 +478,13 @@ DataAccessObject.deleteById.http = [
|
||||||
* @param {Function} cb - callback, called with (err, count)
|
* @param {Function} cb - callback, called with (err, count)
|
||||||
*/
|
*/
|
||||||
DataAccessObject.count = function (where, cb) {
|
DataAccessObject.count = function (where, cb) {
|
||||||
if (stillConnecting(this.schema, this, arguments)) return;
|
if (stillConnecting(this.dataSource, this, arguments)) return;
|
||||||
|
|
||||||
if (typeof where === 'function') {
|
if (typeof where === 'function') {
|
||||||
cb = where;
|
cb = where;
|
||||||
where = null;
|
where = null;
|
||||||
}
|
}
|
||||||
this.schema.adapter.count(this.modelName, cb, where);
|
this.dataSource.connector.count(this.modelName, cb, where);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
@ -502,7 +502,7 @@ DataAccessObject.count.http = {verb: 'get', path: '/count'};
|
||||||
* @param callback(err, obj)
|
* @param callback(err, obj)
|
||||||
*/
|
*/
|
||||||
DataAccessObject.prototype.save = function (options, callback) {
|
DataAccessObject.prototype.save = function (options, callback) {
|
||||||
if (stillConnecting(this.constructor.schema, this, arguments)) return;
|
if (stillConnecting(this.constructor.dataSource, this, arguments)) return;
|
||||||
|
|
||||||
if (typeof options == 'function') {
|
if (typeof options == 'function') {
|
||||||
callback = options;
|
callback = options;
|
||||||
|
@ -578,11 +578,11 @@ DataAccessObject.prototype.isNewRecord = function () {
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Return adapter of current record
|
* Return connector of current record
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
DataAccessObject.prototype._adapter = function () {
|
DataAccessObject.prototype._adapter = function () {
|
||||||
return this.schema.adapter;
|
return this.dataSource.connector;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -592,7 +592,7 @@ DataAccessObject.prototype._adapter = function () {
|
||||||
*/
|
*/
|
||||||
DataAccessObject.prototype.delete =
|
DataAccessObject.prototype.delete =
|
||||||
DataAccessObject.prototype.destroy = function (cb) {
|
DataAccessObject.prototype.destroy = function (cb) {
|
||||||
if (stillConnecting(this.constructor.schema, this, arguments)) return;
|
if (stillConnecting(this.constructor.dataSource, this, arguments)) return;
|
||||||
|
|
||||||
this.trigger('destroy', function (destroyed) {
|
this.trigger('destroy', function (destroyed) {
|
||||||
this._adapter().destroy(this.constructor.modelName, this.id, function (err) {
|
this._adapter().destroy(this.constructor.modelName, this.id, function (err) {
|
||||||
|
@ -638,7 +638,7 @@ DataAccessObject.prototype.updateAttribute = function updateAttribute(name, valu
|
||||||
* @param {Function} callback - callback called with (err, instance)
|
* @param {Function} callback - callback called with (err, instance)
|
||||||
*/
|
*/
|
||||||
DataAccessObject.prototype.updateAttributes = function updateAttributes(data, cb) {
|
DataAccessObject.prototype.updateAttributes = function updateAttributes(data, cb) {
|
||||||
if (stillConnecting(this.constructor.schema, this, arguments)) return;
|
if (stillConnecting(this.constructor.dataSource, this, arguments)) return;
|
||||||
|
|
||||||
var inst = this;
|
var inst = this;
|
||||||
var model = this.constructor.modelName;
|
var model = this.constructor.modelName;
|
||||||
|
@ -703,7 +703,7 @@ DataAccessObject.prototype.updateAttributes.http = [
|
||||||
* @param {Function} callback - called with (err, instance) arguments
|
* @param {Function} callback - called with (err, instance) arguments
|
||||||
*/
|
*/
|
||||||
DataAccessObject.prototype.reload = function reload(callback) {
|
DataAccessObject.prototype.reload = function reload(callback) {
|
||||||
if (stillConnecting(this.constructor.schema, this, arguments)) return;
|
if (stillConnecting(this.constructor.dataSource, this, arguments)) return;
|
||||||
|
|
||||||
this.constructor.findById(this.id, callback);
|
this.constructor.findById(this.id, callback);
|
||||||
};
|
};
|
||||||
|
|
|
@ -25,14 +25,14 @@ exports.DataSource = DataSource;
|
||||||
var slice = Array.prototype.slice;
|
var slice = Array.prototype.slice;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* DataSource - adapter-specific classes factory.
|
* DataSource - connector-specific classes factory.
|
||||||
*
|
*
|
||||||
* All classes in single schema shares same adapter type and
|
* All classes in single dataSource shares same connector type and
|
||||||
* one database connection
|
* one database connection
|
||||||
*
|
*
|
||||||
* @param name - type of schema adapter (mysql, mongoose, sequelize, redis)
|
* @param name - type of dataSource connector (mysql, mongoose, sequelize, redis)
|
||||||
* @param settings - any database-specific settings which we need to
|
* @param settings - any database-specific settings which we need to
|
||||||
* establish connection (of course it depends on specific adapter)
|
* establish connection (of course it depends on specific connector)
|
||||||
*
|
*
|
||||||
* - host
|
* - host
|
||||||
* - port
|
* - port
|
||||||
|
@ -43,9 +43,9 @@ var slice = Array.prototype.slice;
|
||||||
*
|
*
|
||||||
* @example DataSource creation, waiting for connection callback
|
* @example DataSource creation, waiting for connection callback
|
||||||
* ```
|
* ```
|
||||||
* var schema = new DataSource('mysql', { database: 'myapp_test' });
|
* var dataSource = new DataSource('mysql', { database: 'myapp_test' });
|
||||||
* schema.define(...);
|
* dataSource.define(...);
|
||||||
* schema.on('connected', function () {
|
* dataSource.on('connected', function () {
|
||||||
* // work with database
|
* // work with database
|
||||||
* });
|
* });
|
||||||
* ```
|
* ```
|
||||||
|
@ -57,13 +57,13 @@ function DataSource(name, settings) {
|
||||||
ModelBuilder.call(this, arguments);
|
ModelBuilder.call(this, arguments);
|
||||||
|
|
||||||
// operation metadata
|
// operation metadata
|
||||||
// Initialize it before calling setup as the adapter might register operations
|
// Initialize it before calling setup as the connector might register operations
|
||||||
this._operations = {};
|
this._operations = {};
|
||||||
|
|
||||||
this.setup(name, settings);
|
this.setup(name, settings);
|
||||||
|
|
||||||
// connector
|
// connector
|
||||||
var connector = this.connector();
|
var connector = this.connector;
|
||||||
|
|
||||||
// DataAccessObject - connector defined or supply the default
|
// DataAccessObject - connector defined or supply the default
|
||||||
this.DataAccessObject = (connector && connector.DataAccessObject) ? connector.DataAccessObject : this.constructor.DataAccessObject;
|
this.DataAccessObject = (connector && connector.DataAccessObject) ? connector.DataAccessObject : this.constructor.DataAccessObject;
|
||||||
|
@ -117,8 +117,8 @@ for (var m in ModelBuilder) {
|
||||||
}
|
}
|
||||||
|
|
||||||
DataSource.prototype.setup = function(name, settings) {
|
DataSource.prototype.setup = function(name, settings) {
|
||||||
var schema = this;
|
var dataSource = this;
|
||||||
var adapter;
|
var connector;
|
||||||
|
|
||||||
// support single settings object
|
// support single settings object
|
||||||
if(name && typeof name === 'object') {
|
if(name && typeof name === 'object') {
|
||||||
|
@ -130,11 +130,11 @@ DataSource.prototype.setup = function(name, settings) {
|
||||||
|
|
||||||
if(typeof settings === 'object') {
|
if(typeof settings === 'object') {
|
||||||
if(settings.initialize) {
|
if(settings.initialize) {
|
||||||
adapter = settings;
|
connector = settings;
|
||||||
} else if(settings.connector) {
|
} else if(settings.connector) {
|
||||||
adapter = settings.connector;
|
connector = settings.connector;
|
||||||
} else if(settings.adapter) {
|
} else if(settings.connector) {
|
||||||
adapter = settings.adapter;
|
connector = settings.connector;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -146,42 +146,45 @@ DataSource.prototype.setup = function(name, settings) {
|
||||||
this.connected = false;
|
this.connected = false;
|
||||||
this.connecting = false;
|
this.connecting = false;
|
||||||
|
|
||||||
if (name && !adapter) {
|
if (name && !connector) {
|
||||||
// and initialize schema using adapter
|
// and initialize dataSource using connector
|
||||||
// this is only one initialization entry point of adapter
|
// this is only one initialization entry point of connector
|
||||||
// this module should define `adapter` member of `this` (schema)
|
// this module should define `connector` member of `this` (dataSource)
|
||||||
if (typeof name === 'object') {
|
if (typeof name === 'object') {
|
||||||
adapter = name;
|
connector = name;
|
||||||
this.name = adapter.name;
|
this.name = connector.name;
|
||||||
} else if (name.match(/^\//)) {
|
} else if (name.match(/^\//)) {
|
||||||
// try absolute path
|
// try absolute path
|
||||||
adapter = require(name);
|
connector = require(name);
|
||||||
} else if (existsSync(__dirname + '/adapters/' + name + '.js')) {
|
} else if (existsSync(__dirname + '/adapters/' + name + '.js')) {
|
||||||
// try built-in adapter
|
// try built-in connector
|
||||||
adapter = require('./adapters/' + name);
|
connector = require('./adapters/' + name);
|
||||||
} else {
|
} else {
|
||||||
// try foreign adapter
|
// try foreign connector
|
||||||
try {
|
try {
|
||||||
adapter = require('loopback-connector-' + name);
|
connector = require('loopback-connector-' + name);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return console.log('\nWARNING: LoopbackData adapter "' + name + '" is not installed,\nso your models would not work, to fix run:\n\n npm install loopback-connector-' + name, '\n');
|
return console.log('\nWARNING: LoopbackData connector "' + name + '" is not installed,\nso your models would not work, to fix run:\n\n npm install loopback-connector-' + name, '\n');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (adapter) {
|
if (connector) {
|
||||||
var postInit = function postInit() {
|
var postInit = function postInit() {
|
||||||
|
|
||||||
// we have an adaper now?
|
this.connector = this.connector || this.adapter;
|
||||||
if (!this.adapter) {
|
this.adapter = this.connector; // Keep the adapter as an alias to connector
|
||||||
throw new Error('Adapter is not defined correctly: it should create `adapter` member of schema');
|
|
||||||
|
// we have an connector now?
|
||||||
|
if (!this.connector) {
|
||||||
|
throw new Error('Connector is not defined correctly: it should create `connector` member of dataSource');
|
||||||
}
|
}
|
||||||
|
|
||||||
this.adapter.log = function (query, start) {
|
this.connector.log = function (query, start) {
|
||||||
schema.log(query, start);
|
dataSource.log(query, start);
|
||||||
};
|
};
|
||||||
|
|
||||||
this.adapter.logger = function (query) {
|
this.connector.logger = function (query) {
|
||||||
var t1 = Date.now();
|
var t1 = Date.now();
|
||||||
var log = this.log;
|
var log = this.log;
|
||||||
return function (q) {
|
return function (q) {
|
||||||
|
@ -194,31 +197,31 @@ DataSource.prototype.setup = function(name, settings) {
|
||||||
|
|
||||||
}.bind(this);
|
}.bind(this);
|
||||||
|
|
||||||
if ('function' === typeof adapter.initialize) {
|
if ('function' === typeof connector.initialize) {
|
||||||
// Call the async initialize method
|
// Call the async initialize method
|
||||||
adapter.initialize(this, postInit);
|
connector.initialize(this, postInit);
|
||||||
} else if('function' === typeof adapter) {
|
} else if('function' === typeof connector) {
|
||||||
// Use the adapter constructor directly
|
// Use the connector constructor directly
|
||||||
this.adapter = new adapter(this.settings);
|
this.connector = new connector(this.settings);
|
||||||
postInit();
|
postInit();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
schema.connect = function(cb) {
|
dataSource.connect = function(cb) {
|
||||||
var schema = this;
|
var dataSource = this;
|
||||||
if(schema.connected || schema.connecting) {
|
if(dataSource.connected || dataSource.connecting) {
|
||||||
process.nextTick(function() {
|
process.nextTick(function() {
|
||||||
cb && cb();
|
cb && cb();
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
schema.connecting = true;
|
dataSource.connecting = true;
|
||||||
if (schema.adapter.connect) {
|
if (dataSource.connector.connect) {
|
||||||
schema.adapter.connect(function(err, result) {
|
dataSource.connector.connect(function(err, result) {
|
||||||
if (!err) {
|
if (!err) {
|
||||||
schema.connected = true;
|
dataSource.connected = true;
|
||||||
schema.connecting = false;
|
dataSource.connecting = false;
|
||||||
schema.emit('connected');
|
dataSource.emit('connected');
|
||||||
}
|
}
|
||||||
cb && cb(err, result);
|
cb && cb(err, result);
|
||||||
});
|
});
|
||||||
|
@ -230,15 +233,6 @@ DataSource.prototype.setup = function(name, settings) {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the connector.
|
|
||||||
*/
|
|
||||||
|
|
||||||
DataSource.prototype.connector = function () {
|
|
||||||
// alias for adapter compatibility
|
|
||||||
return this.adapter;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Define class
|
* Define class
|
||||||
*
|
*
|
||||||
|
@ -252,7 +246,7 @@ DataSource.prototype.connector = function () {
|
||||||
*
|
*
|
||||||
* @example simple case
|
* @example simple case
|
||||||
* ```
|
* ```
|
||||||
* var User = schema.define('User', {
|
* var User = dataSource.define('User', {
|
||||||
* email: String,
|
* email: String,
|
||||||
* password: String,
|
* password: String,
|
||||||
* birthDate: Date,
|
* birthDate: Date,
|
||||||
|
@ -261,7 +255,7 @@ DataSource.prototype.connector = function () {
|
||||||
* ```
|
* ```
|
||||||
* @example more advanced case
|
* @example more advanced case
|
||||||
* ```
|
* ```
|
||||||
* var User = schema.define('User', {
|
* var User = dataSource.define('User', {
|
||||||
* email: { type: String, limit: 150, index: true },
|
* email: { type: String, limit: 150, index: true },
|
||||||
* password: { type: String, limit: 50 },
|
* password: { type: String, limit: 50 },
|
||||||
* birthDate: Date,
|
* birthDate: Date,
|
||||||
|
@ -286,9 +280,9 @@ DataSource.prototype.define = function defineClass(className, properties, settin
|
||||||
// add data access objects
|
// add data access objects
|
||||||
this.mixin(NewClass);
|
this.mixin(NewClass);
|
||||||
|
|
||||||
if(this.adapter && this.adapter.define) {
|
if(this.connector && this.connector.define) {
|
||||||
// pass control to adapter
|
// pass control to connector
|
||||||
this.adapter.define({
|
this.connector.define({
|
||||||
model: NewClass,
|
model: NewClass,
|
||||||
properties: properties,
|
properties: properties,
|
||||||
settings: settings
|
settings: settings
|
||||||
|
@ -347,23 +341,23 @@ DataSource.prototype.mixin = function (ModelCtor) {
|
||||||
*/
|
*/
|
||||||
|
|
||||||
DataSource.prototype.attach = function (ModelCtor) {
|
DataSource.prototype.attach = function (ModelCtor) {
|
||||||
var properties = ModelCtor.schema.definitions[ModelCtor.modelName].properties;
|
var properties = ModelCtor.dataSource.definitions[ModelCtor.modelName].properties;
|
||||||
var settings = ModelCtor.schema.definitions[ModelCtor.modelName].settings;
|
var settings = ModelCtor.dataSource.definitions[ModelCtor.modelName].settings;
|
||||||
var className = ModelCtor.modelName;
|
var className = ModelCtor.modelName;
|
||||||
|
|
||||||
this.mixin(ModelCtor);
|
this.mixin(ModelCtor);
|
||||||
|
|
||||||
if(this.adapter && this.adapter.define) {
|
if(this.connector && this.connector.define) {
|
||||||
// pass control to adapter
|
// pass control to connector
|
||||||
this.adapter.define({
|
this.connector.define({
|
||||||
model: ModelCtor,
|
model: ModelCtor,
|
||||||
properties: properties,
|
properties: properties,
|
||||||
settings: settings
|
settings: settings
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// redefine the schema
|
// redefine the dataSource
|
||||||
hiddenProperty(ModelCtor, 'schema', this);
|
hiddenProperty(ModelCtor, 'dataSource', this);
|
||||||
ModelCtor.dataSource = this;
|
ModelCtor.dataSource = this;
|
||||||
|
|
||||||
// add to def
|
// add to def
|
||||||
|
@ -387,8 +381,8 @@ DataSource.prototype.attach = function (ModelCtor) {
|
||||||
DataSource.prototype.defineProperty = function (model, prop, params) {
|
DataSource.prototype.defineProperty = function (model, prop, params) {
|
||||||
ModelBuilder.prototype.defineProperty.call(this, model, prop, params);
|
ModelBuilder.prototype.defineProperty.call(this, model, prop, params);
|
||||||
|
|
||||||
if (this.adapter.defineProperty) {
|
if (this.connector.defineProperty) {
|
||||||
this.adapter.defineProperty(model, prop, params);
|
this.connector.defineProperty(model, prop, params);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -400,8 +394,8 @@ DataSource.prototype.defineProperty = function (model, prop, params) {
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.automigrate = function (cb) {
|
DataSource.prototype.automigrate = function (cb) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.adapter.automigrate) {
|
if (this.connector.automigrate) {
|
||||||
this.adapter.automigrate(cb);
|
this.connector.automigrate(cb);
|
||||||
} else if (cb) {
|
} else if (cb) {
|
||||||
cb();
|
cb();
|
||||||
}
|
}
|
||||||
|
@ -413,8 +407,8 @@ DataSource.prototype.automigrate = function (cb) {
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.autoupdate = function (cb) {
|
DataSource.prototype.autoupdate = function (cb) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.adapter.autoupdate) {
|
if (this.connector.autoupdate) {
|
||||||
this.adapter.autoupdate(cb);
|
this.connector.autoupdate(cb);
|
||||||
} else if (cb) {
|
} else if (cb) {
|
||||||
cb();
|
cb();
|
||||||
}
|
}
|
||||||
|
@ -432,8 +426,8 @@ DataSource.prototype.autoupdate = function (cb) {
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverModelDefinitions = function (options, cb) {
|
DataSource.prototype.discoverModelDefinitions = function (options, cb) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.adapter.discoverModelDefinitions) {
|
if (this.connector.discoverModelDefinitions) {
|
||||||
this.adapter.discoverModelDefinitions(options, cb);
|
this.connector.discoverModelDefinitions(options, cb);
|
||||||
} else if (cb) {
|
} else if (cb) {
|
||||||
cb();
|
cb();
|
||||||
}
|
}
|
||||||
|
@ -442,8 +436,8 @@ DataSource.prototype.discoverModelDefinitions = function (options, cb) {
|
||||||
|
|
||||||
DataSource.prototype.discoverModelDefinitionsSync = function (options) {
|
DataSource.prototype.discoverModelDefinitionsSync = function (options) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.adapter.discoverModelDefinitionsSync) {
|
if (this.connector.discoverModelDefinitionsSync) {
|
||||||
return this.adapter.discoverModelDefinitionsSync(options);
|
return this.connector.discoverModelDefinitionsSync(options);
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
@ -457,8 +451,8 @@ DataSource.prototype.discoverModelDefinitionsSync = function (options) {
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverModelProperties = function (table, options, cb) {
|
DataSource.prototype.discoverModelProperties = function (table, options, cb) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.adapter.discoverModelProperties) {
|
if (this.connector.discoverModelProperties) {
|
||||||
this.adapter.discoverModelProperties(table, options, cb);
|
this.connector.discoverModelProperties(table, options, cb);
|
||||||
} else if (cb) {
|
} else if (cb) {
|
||||||
cb();
|
cb();
|
||||||
}
|
}
|
||||||
|
@ -466,8 +460,8 @@ DataSource.prototype.discoverModelProperties = function (table, options, cb) {
|
||||||
|
|
||||||
DataSource.prototype.discoverModelPropertiesSync = function (modelName, options) {
|
DataSource.prototype.discoverModelPropertiesSync = function (modelName, options) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.adapter.discoverModelPropertiesSync) {
|
if (this.connector.discoverModelPropertiesSync) {
|
||||||
return this.adapter.discoverModelPropertiesSync(modelName, options);
|
return this.connector.discoverModelPropertiesSync(modelName, options);
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
@ -476,7 +470,7 @@ DataSource.prototype.discoverModelPropertiesSync = function (modelName, options)
|
||||||
* Discover primary keys for a given owner/modelName
|
* Discover primary keys for a given owner/modelName
|
||||||
*
|
*
|
||||||
* Each primary key column description has the following columns:
|
* Each primary key column description has the following columns:
|
||||||
* owner String => table schema (may be null)
|
* owner String => table dataSource (may be null)
|
||||||
* tableName String => table name
|
* tableName String => table name
|
||||||
* columnName String => column name
|
* columnName String => column name
|
||||||
* keySeq Number => sequence number within primary key( a value of 1 represents the first column of the primary key, a value of 2 would represent the second column within the primary key).
|
* keySeq Number => sequence number within primary key( a value of 1 represents the first column of the primary key, a value of 2 would represent the second column within the primary key).
|
||||||
|
@ -488,8 +482,8 @@ DataSource.prototype.discoverModelPropertiesSync = function (modelName, options)
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverPrimaryKeys= function(modelName, options, cb) {
|
DataSource.prototype.discoverPrimaryKeys= function(modelName, options, cb) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.adapter.discoverPrimaryKeys) {
|
if (this.connector.discoverPrimaryKeys) {
|
||||||
this.adapter.discoverPrimaryKeys(modelName, options, cb);
|
this.connector.discoverPrimaryKeys(modelName, options, cb);
|
||||||
} else if (cb) {
|
} else if (cb) {
|
||||||
cb();
|
cb();
|
||||||
}
|
}
|
||||||
|
@ -497,8 +491,8 @@ DataSource.prototype.discoverPrimaryKeys= function(modelName, options, cb) {
|
||||||
|
|
||||||
DataSource.prototype.discoverPrimaryKeysSync= function(modelName, options) {
|
DataSource.prototype.discoverPrimaryKeysSync= function(modelName, options) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.adapter.discoverPrimaryKeysSync) {
|
if (this.connector.discoverPrimaryKeysSync) {
|
||||||
return this.adapter.discoverPrimaryKeysSync(modelName, options);
|
return this.connector.discoverPrimaryKeysSync(modelName, options);
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
@ -506,12 +500,12 @@ DataSource.prototype.discoverPrimaryKeysSync= function(modelName, options) {
|
||||||
/**
|
/**
|
||||||
* Discover foreign keys for a given owner/modelName
|
* Discover foreign keys for a given owner/modelName
|
||||||
*
|
*
|
||||||
* fkOwner String => foreign key table schema (may be null)
|
* fkOwner String => foreign key table dataSource (may be null)
|
||||||
* fkName String => foreign key name (may be null)
|
* fkName String => foreign key name (may be null)
|
||||||
* fkTableName String => foreign key table name
|
* fkTableName String => foreign key table name
|
||||||
* fkColumnName String => foreign key column name
|
* fkColumnName String => foreign key column name
|
||||||
* keySeq short => 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).
|
* keySeq short => 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)
|
* pkOwner String => primary key table dataSource being imported (may be null)
|
||||||
* pkName String => primary key name (may be null)
|
* pkName String => primary key name (may be null)
|
||||||
* pkTableName String => primary key table name being imported
|
* pkTableName String => primary key table name being imported
|
||||||
* pkColumnName String => primary key column name being imported
|
* pkColumnName String => primary key column name being imported
|
||||||
|
@ -523,8 +517,8 @@ DataSource.prototype.discoverPrimaryKeysSync= function(modelName, options) {
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverForeignKeys= function(modelName, options, cb) {
|
DataSource.prototype.discoverForeignKeys= function(modelName, options, cb) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.adapter.discoverForeignKeys) {
|
if (this.connector.discoverForeignKeys) {
|
||||||
this.adapter.discoverForeignKeys(modelName, options, cb);
|
this.connector.discoverForeignKeys(modelName, options, cb);
|
||||||
} else if (cb) {
|
} else if (cb) {
|
||||||
cb();
|
cb();
|
||||||
}
|
}
|
||||||
|
@ -532,8 +526,8 @@ DataSource.prototype.discoverForeignKeys= function(modelName, options, cb) {
|
||||||
|
|
||||||
DataSource.prototype.discoverForeignKeysSync= function(modelName, options) {
|
DataSource.prototype.discoverForeignKeysSync= function(modelName, options) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.adapter.discoverForeignKeysSync) {
|
if (this.connector.discoverForeignKeysSync) {
|
||||||
return this.adapter.discoverForeignKeysSync(modelName, options);
|
return this.connector.discoverForeignKeysSync(modelName, options);
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
@ -542,12 +536,12 @@ DataSource.prototype.discoverForeignKeysSync= function(modelName, options) {
|
||||||
* Retrieves a description of the foreign key columns that reference the given table's primary key columns (the foreign keys exported by a table).
|
* Retrieves a description of the foreign key columns that reference the given table's primary key columns (the foreign keys exported by a table).
|
||||||
* They are ordered by fkTableOwner, fkTableName, and keySeq.
|
* They are ordered by fkTableOwner, fkTableName, and keySeq.
|
||||||
*
|
*
|
||||||
* fkOwner String => foreign key table schema (may be null)
|
* fkOwner String => foreign key table dataSource (may be null)
|
||||||
* fkName String => foreign key name (may be null)
|
* fkName String => foreign key name (may be null)
|
||||||
* fkTableName String => foreign key table name
|
* fkTableName String => foreign key table name
|
||||||
* fkColumnName String => foreign key column name
|
* fkColumnName String => foreign key column name
|
||||||
* keySeq short => 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).
|
* keySeq short => 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)
|
* pkOwner String => primary key table dataSource being imported (may be null)
|
||||||
* pkName String => primary key name (may be null)
|
* pkName String => primary key name (may be null)
|
||||||
* pkTableName String => primary key table name being imported
|
* pkTableName String => primary key table name being imported
|
||||||
* pkColumnName String => primary key column name being imported
|
* pkColumnName String => primary key column name being imported
|
||||||
|
@ -558,8 +552,8 @@ DataSource.prototype.discoverForeignKeysSync= function(modelName, options) {
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverExportedForeignKeys= function(modelName, options, cb) {
|
DataSource.prototype.discoverExportedForeignKeys= function(modelName, options, cb) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.adapter.discoverExportedForeignKeys) {
|
if (this.connector.discoverExportedForeignKeys) {
|
||||||
this.adapter.discoverExportedForeignKeys(modelName, options, cb);
|
this.connector.discoverExportedForeignKeys(modelName, options, cb);
|
||||||
} else if (cb) {
|
} else if (cb) {
|
||||||
cb();
|
cb();
|
||||||
}
|
}
|
||||||
|
@ -567,8 +561,8 @@ DataSource.prototype.discoverExportedForeignKeys= function(modelName, options, c
|
||||||
|
|
||||||
DataSource.prototype.discoverExportedForeignKeysSync= function(modelName, options) {
|
DataSource.prototype.discoverExportedForeignKeysSync= function(modelName, options) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.adapter.discoverExportedForeignKeysSync) {
|
if (this.connector.discoverExportedForeignKeysSync) {
|
||||||
return this.adapter.discoverExportedForeignKeysSync(modelName, options);
|
return this.connector.discoverExportedForeignKeysSync(modelName, options);
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
@ -616,7 +610,7 @@ DataSource.prototype.discoverSchema = function (modelName, options, cb) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Discover schema from a given modelName/view
|
* Discover dataSource from a given modelName/view
|
||||||
*
|
*
|
||||||
* @param modelName
|
* @param modelName
|
||||||
* @param cb
|
* @param cb
|
||||||
|
@ -630,7 +624,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|
||||||
}
|
}
|
||||||
|
|
||||||
var self = this;
|
var self = this;
|
||||||
var dataSourceName = this.name || this.adapter.name;
|
var dataSourceName = this.name || this.connector.name;
|
||||||
|
|
||||||
var tasks = [
|
var tasks = [
|
||||||
this.discoverModelProperties.bind(this, modelName, options),
|
this.discoverModelProperties.bind(this, modelName, options),
|
||||||
|
@ -664,7 +658,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|
||||||
console.log('Primary keys: ', pks);
|
console.log('Primary keys: ', pks);
|
||||||
}
|
}
|
||||||
|
|
||||||
var schema = {
|
var dataSource = {
|
||||||
name: fromDBName(modelName, false),
|
name: fromDBName(modelName, false),
|
||||||
options: {
|
options: {
|
||||||
idInjection: false // DO NOT add id property
|
idInjection: false // DO NOT add id property
|
||||||
|
@ -673,8 +667,8 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
schema.options[dataSourceName] = {
|
dataSource.options[dataSourceName] = {
|
||||||
schema: columns[0].owner,
|
dataSource: columns[0].owner,
|
||||||
table: modelName
|
table: modelName
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -682,16 +676,16 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|
||||||
var i = item;
|
var i = item;
|
||||||
|
|
||||||
var propName = fromDBName(item.columnName, true);
|
var propName = fromDBName(item.columnName, true);
|
||||||
schema.properties[propName] = {
|
dataSource.properties[propName] = {
|
||||||
type: item.type,
|
type: item.type,
|
||||||
required: (item.nullable === 'N'),
|
required: (item.nullable === 'N'),
|
||||||
length: item.dataLength
|
length: item.dataLength
|
||||||
};
|
};
|
||||||
|
|
||||||
if (pks[item.columnName]) {
|
if (pks[item.columnName]) {
|
||||||
schema.properties[propName].id = pks[item.columnName];
|
dataSource.properties[propName].id = pks[item.columnName];
|
||||||
}
|
}
|
||||||
schema.properties[propName][dataSourceName] = {
|
dataSource.properties[propName][dataSourceName] = {
|
||||||
columnName: i.columnName,
|
columnName: i.columnName,
|
||||||
dataType: i.dataType,
|
dataType: i.dataType,
|
||||||
dataLength: i.dataLength,
|
dataLength: i.dataLength,
|
||||||
|
@ -704,9 +698,9 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|
||||||
var schemaKey = columns[0].owner + '.' + modelName;
|
var schemaKey = columns[0].owner + '.' + modelName;
|
||||||
if (!options.visited.hasOwnProperty(schemaKey)) {
|
if (!options.visited.hasOwnProperty(schemaKey)) {
|
||||||
if(self.settings.debug) {
|
if(self.settings.debug) {
|
||||||
console.log('Adding schema for ' + schemaKey);
|
console.log('Adding dataSource for ' + schemaKey);
|
||||||
}
|
}
|
||||||
options.visited[schemaKey] = schema;
|
options.visited[schemaKey] = dataSource;
|
||||||
}
|
}
|
||||||
|
|
||||||
var otherTables = {};
|
var otherTables = {};
|
||||||
|
@ -734,7 +728,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|
||||||
|
|
||||||
foreignKeys.forEach(function (fk) {
|
foreignKeys.forEach(function (fk) {
|
||||||
var propName = fromDBName(fk.pkTableName, true);
|
var propName = fromDBName(fk.pkTableName, true);
|
||||||
schema.properties[propName] = {
|
dataSource.properties[propName] = {
|
||||||
type: fromDBName(fk.pkTableName, false),
|
type: fromDBName(fk.pkTableName, false),
|
||||||
association: {
|
association: {
|
||||||
type: 'belongsTo',
|
type: 'belongsTo',
|
||||||
|
@ -755,7 +749,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|
||||||
var moreTasks = [];
|
var moreTasks = [];
|
||||||
for (var t in otherTables) {
|
for (var t in otherTables) {
|
||||||
if(self.settings.debug) {
|
if(self.settings.debug) {
|
||||||
console.log('Discovering related schema for ' + schemaKey);
|
console.log('Discovering related dataSource for ' + schemaKey);
|
||||||
}
|
}
|
||||||
var newOptions = {};
|
var newOptions = {};
|
||||||
for(var key in options) {
|
for(var key in options) {
|
||||||
|
@ -775,14 +769,14 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Discover schema from a given table/view
|
* Discover dataSource from a given table/view
|
||||||
*
|
*
|
||||||
* @param modelName
|
* @param modelName
|
||||||
* @param cb
|
* @param cb
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.discoverSchemasSync = function (modelName, options) {
|
DataSource.prototype.discoverSchemasSync = function (modelName, options) {
|
||||||
var self = this;
|
var self = this;
|
||||||
var dataSourceName = this.name || this.adapter.name;
|
var dataSourceName = this.name || this.connector.name;
|
||||||
|
|
||||||
var columns = this.discoverModelPropertiesSync(modelName, options);
|
var columns = this.discoverModelPropertiesSync(modelName, options);
|
||||||
if (!columns || columns.length === 0) {
|
if (!columns || columns.length === 0) {
|
||||||
|
@ -800,7 +794,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
|
||||||
console.log('Primary keys: ', pks);
|
console.log('Primary keys: ', pks);
|
||||||
}
|
}
|
||||||
|
|
||||||
var schema = {
|
var dataSource = {
|
||||||
name: fromDBName(modelName, false),
|
name: fromDBName(modelName, false),
|
||||||
options: {
|
options: {
|
||||||
idInjection: false // DO NOT add id property
|
idInjection: false // DO NOT add id property
|
||||||
|
@ -809,8 +803,8 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
schema.options[dataSourceName] = {
|
dataSource.options[dataSourceName] = {
|
||||||
schema: columns.length > 0 && columns[0].owner,
|
dataSource: columns.length > 0 && columns[0].owner,
|
||||||
table: modelName
|
table: modelName
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -818,16 +812,16 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
|
||||||
var i = item;
|
var i = item;
|
||||||
|
|
||||||
var propName = fromDBName(item.columnName, true);
|
var propName = fromDBName(item.columnName, true);
|
||||||
schema.properties[propName] = {
|
dataSource.properties[propName] = {
|
||||||
type: item.type,
|
type: item.type,
|
||||||
required: (item.nullable === 'N'),
|
required: (item.nullable === 'N'),
|
||||||
length: item.dataLength
|
length: item.dataLength
|
||||||
};
|
};
|
||||||
|
|
||||||
if (pks[item.columnName]) {
|
if (pks[item.columnName]) {
|
||||||
schema.properties[propName].id = pks[item.columnName];
|
dataSource.properties[propName].id = pks[item.columnName];
|
||||||
}
|
}
|
||||||
schema.properties[propName][dataSourceName] = {
|
dataSource.properties[propName][dataSourceName] = {
|
||||||
columnName: i.columnName,
|
columnName: i.columnName,
|
||||||
dataType: i.dataType,
|
dataType: i.dataType,
|
||||||
dataLength: i.dataLength,
|
dataLength: i.dataLength,
|
||||||
|
@ -840,9 +834,9 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
|
||||||
var schemaKey = columns[0].owner + '.' + modelName;
|
var schemaKey = columns[0].owner + '.' + modelName;
|
||||||
if (!options.visited.hasOwnProperty(schemaKey)) {
|
if (!options.visited.hasOwnProperty(schemaKey)) {
|
||||||
if (self.settings.debug) {
|
if (self.settings.debug) {
|
||||||
console.log('Adding schema for ' + schemaKey);
|
console.log('Adding dataSource for ' + schemaKey);
|
||||||
}
|
}
|
||||||
options.visited[schemaKey] = schema;
|
options.visited[schemaKey] = dataSource;
|
||||||
}
|
}
|
||||||
|
|
||||||
var otherTables = {};
|
var otherTables = {};
|
||||||
|
@ -870,7 +864,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
|
||||||
|
|
||||||
foreignKeys.forEach(function (fk) {
|
foreignKeys.forEach(function (fk) {
|
||||||
var propName = fromDBName(fk.pkTableName, true);
|
var propName = fromDBName(fk.pkTableName, true);
|
||||||
schema.properties[propName] = {
|
dataSource.properties[propName] = {
|
||||||
type: fromDBName(fk.pkTableName, false),
|
type: fromDBName(fk.pkTableName, false),
|
||||||
association: {
|
association: {
|
||||||
type: 'belongsTo',
|
type: 'belongsTo',
|
||||||
|
@ -891,7 +885,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
|
||||||
var moreTasks = [];
|
var moreTasks = [];
|
||||||
for (var t in otherTables) {
|
for (var t in otherTables) {
|
||||||
if (self.settings.debug) {
|
if (self.settings.debug) {
|
||||||
console.log('Discovering related schema for ' + schemaKey);
|
console.log('Discovering related dataSource for ' + schemaKey);
|
||||||
}
|
}
|
||||||
var newOptions = {};
|
var newOptions = {};
|
||||||
for(var key in options) {
|
for(var key in options) {
|
||||||
|
@ -922,8 +916,8 @@ DataSource.prototype.discoverAndBuildModels = function (modelName, options, cb)
|
||||||
|
|
||||||
var schemaList = [];
|
var schemaList = [];
|
||||||
for (var s in schemas) {
|
for (var s in schemas) {
|
||||||
var schema = schemas[s];
|
var dataSource = schemas[s];
|
||||||
schemaList.push(schema);
|
schemaList.push(dataSource);
|
||||||
}
|
}
|
||||||
|
|
||||||
var models = self.buildModels(schemaList);
|
var models = self.buildModels(schemaList);
|
||||||
|
@ -942,8 +936,8 @@ DataSource.prototype.discoverAndBuildModelsSync = function (modelName, options)
|
||||||
|
|
||||||
var schemaList = [];
|
var schemaList = [];
|
||||||
for (var s in schemas) {
|
for (var s in schemas) {
|
||||||
var schema = schemas[s];
|
var dataSource = schemas[s];
|
||||||
schemaList.push(schema);
|
schemaList.push(dataSource);
|
||||||
}
|
}
|
||||||
|
|
||||||
var models = this.buildModels(schemaList);
|
var models = this.buildModels(schemaList);
|
||||||
|
@ -956,8 +950,8 @@ DataSource.prototype.discoverAndBuildModelsSync = function (modelName, options)
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.isActual = function (cb) {
|
DataSource.prototype.isActual = function (cb) {
|
||||||
this.freeze();
|
this.freeze();
|
||||||
if (this.adapter.isActual) {
|
if (this.connector.isActual) {
|
||||||
this.adapter.isActual(cb);
|
this.connector.isActual(cb);
|
||||||
} else if (cb) {
|
} else if (cb) {
|
||||||
cb(null, true);
|
cb(null, true);
|
||||||
}
|
}
|
||||||
|
@ -965,7 +959,7 @@ DataSource.prototype.isActual = function (cb) {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Log benchmarked message. Do not redefine this method, if you need to grab
|
* Log benchmarked message. Do not redefine this method, if you need to grab
|
||||||
* chema logs, use `schema.on('log', ...)` emitter event
|
* chema logs, use `dataSource.on('log', ...)` emitter event
|
||||||
*
|
*
|
||||||
* @private used by adapters
|
* @private used by adapters
|
||||||
*/
|
*/
|
||||||
|
@ -974,11 +968,11 @@ DataSource.prototype.log = function (sql, t) {
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Freeze schema. Behavior depends on adapter
|
* Freeze dataSource. Behavior depends on connector
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.freeze = function freeze() {
|
DataSource.prototype.freeze = function freeze() {
|
||||||
if (this.adapter.freezeSchema) {
|
if (this.connector.freezeSchema) {
|
||||||
this.adapter.freezeSchema();
|
this.connector.freezeSchema();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -988,8 +982,8 @@ DataSource.prototype.freeze = function freeze() {
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.tableName = function (modelName) {
|
DataSource.prototype.tableName = function (modelName) {
|
||||||
var settings = this.definitions[modelName].settings;
|
var settings = this.definitions[modelName].settings;
|
||||||
if(settings[this.adapter.name]) {
|
if(settings[this.connector.name]) {
|
||||||
return settings[this.adapter.name].table || modelName;
|
return settings[this.connector.name].table || modelName;
|
||||||
} else {
|
} else {
|
||||||
return modelName;
|
return modelName;
|
||||||
}
|
}
|
||||||
|
@ -1006,8 +1000,8 @@ DataSource.prototype.columnName = function (modelName, propertyName) {
|
||||||
return propertyName;
|
return propertyName;
|
||||||
}
|
}
|
||||||
var property = this.definitions[modelName].properties[propertyName];
|
var property = this.definitions[modelName].properties[propertyName];
|
||||||
if(property && property[this.adapter.name]) {
|
if(property && property[this.connector.name]) {
|
||||||
return property[this.adapter.name].columnName || propertyName;
|
return property[this.connector.name].columnName || propertyName;
|
||||||
} else {
|
} else {
|
||||||
return propertyName;
|
return propertyName;
|
||||||
}
|
}
|
||||||
|
@ -1024,8 +1018,8 @@ DataSource.prototype.columnMetadata = function (modelName, propertyName) {
|
||||||
return propertyName;
|
return propertyName;
|
||||||
}
|
}
|
||||||
var property = this.definitions[modelName].properties[propertyName];
|
var property = this.definitions[modelName].properties[propertyName];
|
||||||
if(property && property[this.adapter.name]) {
|
if(property && property[this.connector.name]) {
|
||||||
return property[this.adapter.name];
|
return property[this.connector.name];
|
||||||
} else {
|
} else {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
@ -1040,8 +1034,8 @@ DataSource.prototype.columnNames = function (modelName) {
|
||||||
var props = this.definitions[modelName].properties;
|
var props = this.definitions[modelName].properties;
|
||||||
var cols = [];
|
var cols = [];
|
||||||
for(var p in props) {
|
for(var p in props) {
|
||||||
if(props[p][this.adapter.name]) {
|
if(props[p][this.connector.name]) {
|
||||||
cols.push(props[p][this.adapter.name].columnName || p);
|
cols.push(props[p][this.connector.name].columnName || p);
|
||||||
} else {
|
} else {
|
||||||
cols.push(p);
|
cols.push(p);
|
||||||
}
|
}
|
||||||
|
@ -1105,18 +1099,18 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key
|
||||||
// quit if key already defined
|
// quit if key already defined
|
||||||
if (this.definitions[className].properties[key]) return;
|
if (this.definitions[className].properties[key]) return;
|
||||||
|
|
||||||
if (this.adapter.defineForeignKey) {
|
if (this.connector.defineForeignKey) {
|
||||||
var cb = function (err, keyType) {
|
var cb = function (err, keyType) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
this.definitions[className].properties[key] = {type: keyType};
|
this.definitions[className].properties[key] = {type: keyType};
|
||||||
}.bind(this);
|
}.bind(this);
|
||||||
switch (this.adapter.defineForeignKey.length) {
|
switch (this.connector.defineForeignKey.length) {
|
||||||
case 4:
|
case 4:
|
||||||
this.adapter.defineForeignKey(className, key, foreignClassName, cb);
|
this.connector.defineForeignKey(className, key, foreignClassName, cb);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
case 3:
|
case 3:
|
||||||
this.adapter.defineForeignKey(className, key, cb);
|
this.connector.defineForeignKey(className, key, cb);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
@ -1131,8 +1125,8 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key
|
||||||
*/
|
*/
|
||||||
DataSource.prototype.disconnect = function disconnect(cb) {
|
DataSource.prototype.disconnect = function disconnect(cb) {
|
||||||
var self = this;
|
var self = this;
|
||||||
if (this.connected && (typeof this.adapter.disconnect === 'function')) {
|
if (this.connected && (typeof this.connector.disconnect === 'function')) {
|
||||||
this.adapter.disconnect(function(err, result) {
|
this.connector.disconnect(function(err, result) {
|
||||||
self.connected = false;
|
self.connected = false;
|
||||||
cb && cb(err, result);
|
cb && cb(err, result);
|
||||||
});
|
});
|
||||||
|
@ -1144,33 +1138,33 @@ DataSource.prototype.disconnect = function disconnect(cb) {
|
||||||
};
|
};
|
||||||
|
|
||||||
DataSource.prototype.copyModel = function copyModel(Master) {
|
DataSource.prototype.copyModel = function copyModel(Master) {
|
||||||
var schema = this;
|
var dataSource = this;
|
||||||
var className = Master.modelName;
|
var className = Master.modelName;
|
||||||
var md = Master.schema.definitions[className];
|
var md = Master.dataSource.definitions[className];
|
||||||
var Slave = function SlaveModel() {
|
var Slave = function SlaveModel() {
|
||||||
Master.apply(this, [].slice.call(arguments));
|
Master.apply(this, [].slice.call(arguments));
|
||||||
this.schema = schema;
|
this.dataSource = dataSource;
|
||||||
};
|
};
|
||||||
|
|
||||||
util.inherits(Slave, Master);
|
util.inherits(Slave, Master);
|
||||||
|
|
||||||
Slave.__proto__ = Master;
|
Slave.__proto__ = Master;
|
||||||
|
|
||||||
hiddenProperty(Slave, 'schema', schema);
|
hiddenProperty(Slave, 'dataSource', dataSource);
|
||||||
hiddenProperty(Slave, 'modelName', className);
|
hiddenProperty(Slave, 'modelName', className);
|
||||||
hiddenProperty(Slave, 'relations', Master.relations);
|
hiddenProperty(Slave, 'relations', Master.relations);
|
||||||
|
|
||||||
if (!(className in schema.models)) {
|
if (!(className in dataSource.models)) {
|
||||||
|
|
||||||
// store class in model pool
|
// store class in model pool
|
||||||
schema.models[className] = Slave;
|
dataSource.models[className] = Slave;
|
||||||
schema.definitions[className] = {
|
dataSource.definitions[className] = {
|
||||||
properties: md.properties,
|
properties: md.properties,
|
||||||
settings: md.settings
|
settings: md.settings
|
||||||
};
|
};
|
||||||
|
|
||||||
if ((!schema.isTransaction) && schema.adapter && schema.adapter.define) {
|
if ((!dataSource.isTransaction) && dataSource.connector && dataSource.connector.define) {
|
||||||
schema.adapter.define({
|
dataSource.connector.define({
|
||||||
model: Slave,
|
model: Slave,
|
||||||
properties: md.properties,
|
properties: md.properties,
|
||||||
settings: md.settings
|
settings: md.settings
|
||||||
|
@ -1183,28 +1177,28 @@ DataSource.prototype.copyModel = function copyModel(Master) {
|
||||||
};
|
};
|
||||||
|
|
||||||
DataSource.prototype.transaction = function() {
|
DataSource.prototype.transaction = function() {
|
||||||
var schema = this;
|
var dataSource = this;
|
||||||
var transaction = new EventEmitter;
|
var transaction = new EventEmitter;
|
||||||
transaction.isTransaction = true;
|
transaction.isTransaction = true;
|
||||||
transaction.origin = schema;
|
transaction.origin = dataSource;
|
||||||
transaction.name = schema.name;
|
transaction.name = dataSource.name;
|
||||||
transaction.settings = schema.settings;
|
transaction.settings = dataSource.settings;
|
||||||
transaction.connected = false;
|
transaction.connected = false;
|
||||||
transaction.connecting = false;
|
transaction.connecting = false;
|
||||||
transaction.adapter = schema.adapter.transaction();
|
transaction.connector = dataSource.connector.transaction();
|
||||||
|
|
||||||
// create blank models pool
|
// create blank models pool
|
||||||
transaction.models = {};
|
transaction.models = {};
|
||||||
transaction.definitions = {};
|
transaction.definitions = {};
|
||||||
|
|
||||||
for (var i in schema.models) {
|
for (var i in dataSource.models) {
|
||||||
schema.copyModel.call(transaction, schema.models[i]);
|
dataSource.copyModel.call(transaction, dataSource.models[i]);
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction.connect = schema.connect;
|
transaction.connect = dataSource.connect;
|
||||||
|
|
||||||
transaction.exec = function(cb) {
|
transaction.exec = function(cb) {
|
||||||
transaction.adapter.exec(cb);
|
transaction.connector.exec(cb);
|
||||||
};
|
};
|
||||||
|
|
||||||
return transaction;
|
return transaction;
|
||||||
|
@ -1272,7 +1266,7 @@ DataSource.prototype.defineOperation = function (name, options, fn) {
|
||||||
}
|
}
|
||||||
|
|
||||||
DataSource.prototype.isRelational = function() {
|
DataSource.prototype.isRelational = function() {
|
||||||
return this.adapter && this.adapter.relational;
|
return this.connector && this.connector.relational;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -5,7 +5,7 @@
|
||||||
var assert = require('assert');
|
var assert = require('assert');
|
||||||
|
|
||||||
/*!
|
/*!
|
||||||
* Get a near filter from a given where object. For adapter use only.
|
* Get a near filter from a given where object. For connector use only.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
exports.nearFilter = function nearFilter(where) {
|
exports.nearFilter = function nearFilter(where) {
|
||||||
|
|
|
@ -76,7 +76,7 @@ util.inherits(ModelBuilder, EventEmitter);
|
||||||
*
|
*
|
||||||
* @example simple case
|
* @example simple case
|
||||||
* ```
|
* ```
|
||||||
* var User = schema.define('User', {
|
* var User = dataSource.define('User', {
|
||||||
* email: String,
|
* email: String,
|
||||||
* password: String,
|
* password: String,
|
||||||
* birthDate: Date,
|
* birthDate: Date,
|
||||||
|
@ -85,7 +85,7 @@ util.inherits(ModelBuilder, EventEmitter);
|
||||||
* ```
|
* ```
|
||||||
* @example more advanced case
|
* @example more advanced case
|
||||||
* ```
|
* ```
|
||||||
* var User = schema.define('User', {
|
* var User = dataSource.define('User', {
|
||||||
* email: { type: String, limit: 150, index: true },
|
* email: { type: String, limit: 150, index: true },
|
||||||
* password: { type: String, limit: 50 },
|
* password: { type: String, limit: 50 },
|
||||||
* birthDate: Date,
|
* birthDate: Date,
|
||||||
|
@ -95,7 +95,7 @@ util.inherits(ModelBuilder, EventEmitter);
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
ModelBuilder.prototype.define = function defineClass(className, properties, settings, parent) {
|
ModelBuilder.prototype.define = function defineClass(className, properties, settings, parent) {
|
||||||
var schema = this;
|
var dataSource = this;
|
||||||
var args = slice.call(arguments);
|
var args = slice.call(arguments);
|
||||||
var pluralName = settings && settings.plural;
|
var pluralName = settings && settings.plural;
|
||||||
var ModelBaseClass = parent || require('./model.js');
|
var ModelBaseClass = parent || require('./model.js');
|
||||||
|
@ -110,13 +110,13 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
|
||||||
this.buildSchema(className, properties);
|
this.buildSchema(className, properties);
|
||||||
|
|
||||||
// every class can receive hash of data as optional param
|
// every class can receive hash of data as optional param
|
||||||
var ModelClass = function ModelConstructor(data, schema) {
|
var ModelClass = function ModelConstructor(data, dataSource) {
|
||||||
if(!(this instanceof ModelConstructor)) {
|
if(!(this instanceof ModelConstructor)) {
|
||||||
return new ModelConstructor(data, schema);
|
return new ModelConstructor(data, dataSource);
|
||||||
}
|
}
|
||||||
ModelBaseClass.apply(this, arguments);
|
ModelBaseClass.apply(this, arguments);
|
||||||
if(!this.schema) {
|
if(!this.dataSource) {
|
||||||
hiddenProperty(this, 'schema', schema || this.constructor.schema);
|
hiddenProperty(this, 'dataSource', dataSource || this.constructor.dataSource);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -127,7 +127,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
|
||||||
ModelClass.emit = events.emit.bind(events);
|
ModelClass.emit = events.emit.bind(events);
|
||||||
ModelClass.setMaxListeners = events.setMaxListeners.bind(events);
|
ModelClass.setMaxListeners = events.setMaxListeners.bind(events);
|
||||||
|
|
||||||
hiddenProperty(ModelClass, 'schema', schema);
|
hiddenProperty(ModelClass, 'dataSource', dataSource);
|
||||||
hiddenProperty(ModelClass, 'modelName', className);
|
hiddenProperty(ModelClass, 'modelName', className);
|
||||||
hiddenProperty(ModelClass, 'pluralModelName', pluralName || i8n.pluralize(className));
|
hiddenProperty(ModelClass, 'pluralModelName', pluralName || i8n.pluralize(className));
|
||||||
hiddenProperty(ModelClass, 'relations', {});
|
hiddenProperty(ModelClass, 'relations', {});
|
||||||
|
@ -206,7 +206,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
var c = schema.define(className, p, s, ModelClass);
|
var c = dataSource.define(className, p, s, ModelClass);
|
||||||
|
|
||||||
if(typeof c.setup === 'function') {
|
if(typeof c.setup === 'function') {
|
||||||
c.setup.call(c);
|
c.setup.call(c);
|
||||||
|
@ -236,7 +236,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
|
||||||
return s;
|
return s;
|
||||||
};
|
};
|
||||||
} else if(typeof DataType === 'string') {
|
} else if(typeof DataType === 'string') {
|
||||||
DataType = schema.getSchemaType(DataType);
|
DataType = dataSource.getSchemaType(DataType);
|
||||||
}
|
}
|
||||||
|
|
||||||
Object.defineProperty(ModelClass.prototype, attr, {
|
Object.defineProperty(ModelClass.prototype, attr, {
|
||||||
|
@ -337,7 +337,7 @@ ModelBuilder.prototype.defineProperty = function (model, prop, params) {
|
||||||
* db.defineProperty('Content', 'expiryDate', { type: Date, index: true });
|
* db.defineProperty('Content', 'expiryDate', { type: Date, index: true });
|
||||||
* db.defineProperty('Content', 'isExpired', { type: Boolean, index: true });
|
* db.defineProperty('Content', 'isExpired', { type: Boolean, index: true });
|
||||||
*
|
*
|
||||||
* // schema.extend allows to
|
* // dataSource.extend allows to
|
||||||
* // extend the content model with competition attributes
|
* // extend the content model with competition attributes
|
||||||
* db.extendModel('Content', {
|
* db.extendModel('Content', {
|
||||||
* competitionType: String,
|
* competitionType: String,
|
||||||
|
@ -357,27 +357,27 @@ ModelBuilder.prototype.extendModel = function (model, props) {
|
||||||
|
|
||||||
|
|
||||||
ModelBuilder.prototype.copyModel = function copyModel(Master) {
|
ModelBuilder.prototype.copyModel = function copyModel(Master) {
|
||||||
var schema = this;
|
var dataSource = this;
|
||||||
var className = Master.modelName;
|
var className = Master.modelName;
|
||||||
var md = Master.schema.definitions[className];
|
var md = Master.dataSource.definitions[className];
|
||||||
var Slave = function SlaveModel() {
|
var Slave = function SlaveModel() {
|
||||||
Master.apply(this, [].slice.call(arguments));
|
Master.apply(this, [].slice.call(arguments));
|
||||||
this.schema = schema;
|
this.dataSource = dataSource;
|
||||||
};
|
};
|
||||||
|
|
||||||
util.inherits(Slave, Master);
|
util.inherits(Slave, Master);
|
||||||
|
|
||||||
Slave.__proto__ = Master;
|
Slave.__proto__ = Master;
|
||||||
|
|
||||||
hiddenProperty(Slave, 'schema', schema);
|
hiddenProperty(Slave, 'dataSource', dataSource);
|
||||||
hiddenProperty(Slave, 'modelName', className);
|
hiddenProperty(Slave, 'modelName', className);
|
||||||
hiddenProperty(Slave, 'relations', Master.relations);
|
hiddenProperty(Slave, 'relations', Master.relations);
|
||||||
|
|
||||||
if (!(className in schema.models)) {
|
if (!(className in dataSource.models)) {
|
||||||
|
|
||||||
// store class in model pool
|
// store class in model pool
|
||||||
schema.models[className] = Slave;
|
dataSource.models[className] = Slave;
|
||||||
schema.definitions[className] = {
|
dataSource.definitions[className] = {
|
||||||
properties: md.properties,
|
properties: md.properties,
|
||||||
settings: md.settings
|
settings: md.settings
|
||||||
};
|
};
|
||||||
|
@ -461,9 +461,9 @@ ModelBuilder.prototype.getSchemaType = function(type) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build a schema
|
* Build a dataSource
|
||||||
* @param name The name of the schema
|
* @param name The name of the dataSource
|
||||||
* @param properties The properties of the schema
|
* @param properties The properties of the dataSource
|
||||||
* @param associations An array of associations between models
|
* @param associations An array of associations between models
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
|
@ -498,10 +498,10 @@ ModelBuilder.prototype.buildSchema = function(name, properties, associations) {
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build models from schema definitions
|
* Build models from dataSource definitions
|
||||||
* @param schemas The schemas can be one of the following three formats:
|
* @param schemas The schemas can be one of the following three formats:
|
||||||
* 1. An array of named schema definition JSON objects
|
* 1. An array of named dataSource definition JSON objects
|
||||||
* 2. A schema definition JSON object
|
* 2. A dataSource definition JSON object
|
||||||
* 3. A list of property definitions (anonymous)
|
* 3. A list of property definitions (anonymous)
|
||||||
* @returns {Object} A map of model constructors keyed by model name
|
* @returns {Object} A map of model constructors keyed by model name
|
||||||
*/
|
*/
|
||||||
|
@ -514,7 +514,7 @@ ModelBuilder.prototype.buildModels = function (schemas) {
|
||||||
// Only one item
|
// Only one item
|
||||||
schemas = [schemas];
|
schemas = [schemas];
|
||||||
} else {
|
} else {
|
||||||
// Anonymous schema
|
// Anonymous dataSource
|
||||||
schemas = [
|
schemas = [
|
||||||
{
|
{
|
||||||
name: 'Anonymous',
|
name: 'Anonymous',
|
||||||
|
@ -526,8 +526,8 @@ ModelBuilder.prototype.buildModels = function (schemas) {
|
||||||
var associations = [];
|
var associations = [];
|
||||||
for (var s in schemas) {
|
for (var s in schemas) {
|
||||||
var name = schemas[s].name;
|
var name = schemas[s].name;
|
||||||
var schema = this.buildSchema(name, schemas[s].properties, associations);
|
var dataSource = this.buildSchema(name, schemas[s].properties, associations);
|
||||||
var model = this.define(name, schema, schemas[s].options);
|
var model = this.define(name, dataSource, schemas[s].options);
|
||||||
models[name] = model;
|
models[name] = model;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
14
lib/model.js
14
lib/model.js
|
@ -17,9 +17,9 @@ var BASE_TYPES = ['String', 'Boolean', 'Number', 'Date', 'Text'];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Model class - base class for all persist objects
|
* Model class - base class for all persist objects
|
||||||
* provides **common API** to access any database adapter.
|
* provides **common API** to access any database connector.
|
||||||
* This class describes only abstract behavior layer, refer to `lib/adapters/*.js`
|
* This class describes only abstract behavior layer, refer to `lib/adapters/*.js`
|
||||||
* to learn more about specific adapter implementations
|
* to learn more about specific connector implementations
|
||||||
*
|
*
|
||||||
* `ModelBaseClass` mixes `Validatable` and `Hookable` classes methods
|
* `ModelBaseClass` mixes `Validatable` and `Hookable` classes methods
|
||||||
*
|
*
|
||||||
|
@ -132,7 +132,7 @@ ModelBaseClass.prototype._initProperties = function (data, applySetters) {
|
||||||
* @param {Object} params - various property configuration
|
* @param {Object} params - various property configuration
|
||||||
*/
|
*/
|
||||||
ModelBaseClass.defineProperty = function (prop, params) {
|
ModelBaseClass.defineProperty = function (prop, params) {
|
||||||
this.schema.defineProperty(this.modelName, prop, params);
|
this.dataSource.defineProperty(this.modelName, prop, params);
|
||||||
};
|
};
|
||||||
|
|
||||||
ModelBaseClass.whatTypeName = function (propName) {
|
ModelBaseClass.whatTypeName = function (propName) {
|
||||||
|
@ -159,14 +159,14 @@ ModelBaseClass.toString = function () {
|
||||||
/**
|
/**
|
||||||
* Convert instance to Object
|
* Convert instance to Object
|
||||||
*
|
*
|
||||||
* @param {Boolean} onlySchema - restrict properties to schema only, default false
|
* @param {Boolean} onlySchema - restrict properties to dataSource only, default false
|
||||||
* when onlySchema == true, only properties defined in schema returned,
|
* when onlySchema == true, only properties defined in dataSource returned,
|
||||||
* otherwise all enumerable properties returned
|
* otherwise all enumerable properties returned
|
||||||
* @returns {Object} - canonical object representation (no getters and setters)
|
* @returns {Object} - canonical object representation (no getters and setters)
|
||||||
*/
|
*/
|
||||||
ModelBaseClass.prototype.toObject = function (onlySchema) {
|
ModelBaseClass.prototype.toObject = function (onlySchema) {
|
||||||
var data = {};
|
var data = {};
|
||||||
var ds = this.constructor.schema.definitions[this.constructor.modelName];
|
var ds = this.constructor.dataSource.definitions[this.constructor.modelName];
|
||||||
var properties = ds.properties;
|
var properties = ds.properties;
|
||||||
var self = this;
|
var self = this;
|
||||||
|
|
||||||
|
@ -229,7 +229,7 @@ ModelBaseClass.prototype.propertyChanged = function propertyChanged(attr) {
|
||||||
ModelBaseClass.prototype.reset = function () {
|
ModelBaseClass.prototype.reset = function () {
|
||||||
var obj = this;
|
var obj = this;
|
||||||
Object.keys(obj).forEach(function (k) {
|
Object.keys(obj).forEach(function (k) {
|
||||||
if (k !== 'id' && !obj.constructor.schema.definitions[obj.constructor.modelName].properties[k]) {
|
if (k !== 'id' && !obj.constructor.dataSource.definitions[obj.constructor.modelName].properties[k]) {
|
||||||
delete obj[k];
|
delete obj[k];
|
||||||
}
|
}
|
||||||
if (obj.propertyChanged(k)) {
|
if (obj.propertyChanged(k)) {
|
||||||
|
|
|
@ -34,9 +34,9 @@ Relation.hasMany = function hasMany(anotherClass, params) {
|
||||||
anotherClass = params.model;
|
anotherClass = params.model;
|
||||||
} else {
|
} else {
|
||||||
var anotherClassName = i8n.singularize(anotherClass).toLowerCase();
|
var anotherClassName = i8n.singularize(anotherClass).toLowerCase();
|
||||||
for(var name in this.schema.models) {
|
for(var name in this.dataSource.models) {
|
||||||
if (name.toLowerCase() === anotherClassName) {
|
if (name.toLowerCase() === anotherClassName) {
|
||||||
anotherClass = this.schema.models[name];
|
anotherClass = this.dataSource.models[name];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -125,7 +125,7 @@ Relation.hasMany = function hasMany(anotherClass, params) {
|
||||||
|
|
||||||
if (!params.through) {
|
if (!params.through) {
|
||||||
// obviously, anotherClass should have attribute called `fk`
|
// obviously, anotherClass should have attribute called `fk`
|
||||||
anotherClass.schema.defineForeignKey(anotherClass.modelName, fk, this.modelName);
|
anotherClass.dataSource.defineForeignKey(anotherClass.modelName, fk, this.modelName);
|
||||||
}
|
}
|
||||||
|
|
||||||
function find(id, cb) {
|
function find(id, cb) {
|
||||||
|
@ -184,9 +184,9 @@ Relation.belongsTo = function (anotherClass, params) {
|
||||||
anotherClass = params.model;
|
anotherClass = params.model;
|
||||||
} else {
|
} else {
|
||||||
var anotherClassName = anotherClass.toLowerCase();
|
var anotherClassName = anotherClass.toLowerCase();
|
||||||
for(var name in this.schema.models) {
|
for(var name in this.dataSource.models) {
|
||||||
if (name.toLowerCase() === anotherClassName) {
|
if (name.toLowerCase() === anotherClassName) {
|
||||||
anotherClass = this.schema.models[name];
|
anotherClass = this.dataSource.models[name];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -202,7 +202,7 @@ Relation.belongsTo = function (anotherClass, params) {
|
||||||
multiple: false
|
multiple: false
|
||||||
};
|
};
|
||||||
|
|
||||||
this.schema.defineForeignKey(this.modelName, fk, anotherClass.modelName);
|
this.dataSource.defineForeignKey(this.modelName, fk, anotherClass.modelName);
|
||||||
this.prototype['__finders__'] = this.prototype['__finders__'] || {};
|
this.prototype['__finders__'] = this.prototype['__finders__'] || {};
|
||||||
|
|
||||||
this.prototype['__finders__'][methodName] = function (id, cb) {
|
this.prototype['__finders__'][methodName] = function (id, cb) {
|
||||||
|
@ -266,7 +266,7 @@ Relation.belongsTo = function (anotherClass, params) {
|
||||||
*/
|
*/
|
||||||
Relation.hasAndBelongsToMany = function hasAndBelongsToMany(anotherClass, params) {
|
Relation.hasAndBelongsToMany = function hasAndBelongsToMany(anotherClass, params) {
|
||||||
params = params || {};
|
params = params || {};
|
||||||
var models = this.schema.models;
|
var models = this.dataSource.models;
|
||||||
|
|
||||||
if ('string' === typeof anotherClass) {
|
if ('string' === typeof anotherClass) {
|
||||||
params.as = anotherClass;
|
params.as = anotherClass;
|
||||||
|
@ -285,7 +285,7 @@ Relation.hasAndBelongsToMany = function hasAndBelongsToMany(anotherClass, params
|
||||||
var name1 = this.modelName + anotherClass.modelName;
|
var name1 = this.modelName + anotherClass.modelName;
|
||||||
var name2 = anotherClass.modelName + this.modelName;
|
var name2 = anotherClass.modelName + this.modelName;
|
||||||
params.through = lookupModel(name1) || lookupModel(name2) ||
|
params.through = lookupModel(name1) || lookupModel(name2) ||
|
||||||
this.schema.define(name1);
|
this.dataSource.define(name1);
|
||||||
}
|
}
|
||||||
params.through.belongsTo(this);
|
params.through.belongsTo(this);
|
||||||
params.through.belongsTo(anotherClass);
|
params.through.belongsTo(anotherClass);
|
||||||
|
|
|
@ -9,7 +9,7 @@ function BaseSQL() {
|
||||||
BaseSQL.prototype.relational = true;
|
BaseSQL.prototype.relational = true;
|
||||||
|
|
||||||
BaseSQL.prototype.query = function () {
|
BaseSQL.prototype.query = function () {
|
||||||
throw new Error('query method should be declared in adapter');
|
throw new Error('query method should be declared in connector');
|
||||||
};
|
};
|
||||||
|
|
||||||
BaseSQL.prototype.command = function (sql, callback) {
|
BaseSQL.prototype.command = function (sql, callback) {
|
||||||
|
@ -33,7 +33,7 @@ BaseSQL.prototype.dataSource = function(model) {
|
||||||
if(!m) {
|
if(!m) {
|
||||||
console.trace('Model not found: ' + model);
|
console.trace('Model not found: ' + model);
|
||||||
}
|
}
|
||||||
return m.model.schema;
|
return m.model.dataSource;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -151,7 +151,7 @@ BaseSQL.prototype.id = function (model, prop) {
|
||||||
* @param name The name
|
* @param name The name
|
||||||
*/
|
*/
|
||||||
BaseSQL.prototype.escapeName = function (name) {
|
BaseSQL.prototype.escapeName = function (name) {
|
||||||
throw new Error('escapeName method should be declared in adapter');
|
throw new Error('escapeName method should be declared in connector');
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -15,29 +15,29 @@ function skip(name) {
|
||||||
delete batch[schemaName][name];
|
delete batch[schemaName][name];
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = function testSchema(exportCasesHere, schema) {
|
module.exports = function testSchema(exportCasesHere, dataSource) {
|
||||||
|
|
||||||
batch = exportCasesHere;
|
batch = exportCasesHere;
|
||||||
schemaName = schema.name;
|
schemaName = dataSource.name;
|
||||||
if (schema.name.match(/^\/.*\/test\/\.\.$/)) {
|
if (dataSource.name.match(/^\/.*\/test\/\.\.$/)) {
|
||||||
schemaName = schemaName.split('/').slice(-3).shift();
|
schemaName = schemaName.split('/').slice(-3).shift();
|
||||||
}
|
}
|
||||||
var start;
|
var start;
|
||||||
|
|
||||||
batch['should connect to database'] = function (test) {
|
batch['should connect to database'] = function (test) {
|
||||||
start = Date.now();
|
start = Date.now();
|
||||||
if (schema.connected) return test.done();
|
if (dataSource.connected) return test.done();
|
||||||
schema.on('connected', test.done);
|
dataSource.on('connected', test.done);
|
||||||
};
|
};
|
||||||
|
|
||||||
schema.log = function (a) {
|
dataSource.log = function (a) {
|
||||||
console.log(a);
|
console.log(a);
|
||||||
nbSchemaRequests++;
|
nbSchemaRequests++;
|
||||||
};
|
};
|
||||||
|
|
||||||
batch[schemaName] = {};
|
batch[schemaName] = {};
|
||||||
|
|
||||||
testOrm(schema);
|
testOrm(dataSource);
|
||||||
|
|
||||||
batch['all tests done'] = function (test) {
|
batch['all tests done'] = function (test) {
|
||||||
test.done();
|
test.done();
|
||||||
|
@ -45,7 +45,7 @@ module.exports = function testSchema(exportCasesHere, schema) {
|
||||||
};
|
};
|
||||||
|
|
||||||
function allTestsDone() {
|
function allTestsDone() {
|
||||||
schema.disconnect();
|
dataSource.disconnect();
|
||||||
console.log('Test done in %dms\n', Date.now() - start);
|
console.log('Test done in %dms\n', Date.now() - start);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -85,14 +85,14 @@ function clearAndCreate(model, data, callback) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function testOrm(schema) {
|
function testOrm(dataSource) {
|
||||||
var requestsAreCounted = schema.name !== 'mongodb';
|
var requestsAreCounted = dataSource.name !== 'mongodb';
|
||||||
|
|
||||||
var Post, User, Passport, Log, Dog;
|
var Post, User, Passport, Log, Dog;
|
||||||
|
|
||||||
it('should define class', function (test) {
|
it('should define class', function (test) {
|
||||||
|
|
||||||
User = schema.define('User', {
|
User = dataSource.define('User', {
|
||||||
name: { type: String, index: true },
|
name: { type: String, index: true },
|
||||||
email: { type: String, index: true },
|
email: { type: String, index: true },
|
||||||
bio: Text,
|
bio: Text,
|
||||||
|
@ -102,18 +102,18 @@ function testOrm(schema) {
|
||||||
passwd: { type: String, index: true }
|
passwd: { type: String, index: true }
|
||||||
});
|
});
|
||||||
|
|
||||||
Dog = schema.define('Dog', {
|
Dog = dataSource.define('Dog', {
|
||||||
name : { type: String, limit: 64, allowNull: false }
|
name : { type: String, limit: 64, allowNull: false }
|
||||||
});
|
});
|
||||||
|
|
||||||
Log = schema.define('Log', {
|
Log = dataSource.define('Log', {
|
||||||
ownerId : { type: Number, allowNull: true },
|
ownerId : { type: Number, allowNull: true },
|
||||||
name : { type: String, limit: 64, allowNull: false }
|
name : { type: String, limit: 64, allowNull: false }
|
||||||
});
|
});
|
||||||
|
|
||||||
Log.belongsTo(Dog, {as: 'owner', foreignKey: 'ownerId'});
|
Log.belongsTo(Dog, {as: 'owner', foreignKey: 'ownerId'});
|
||||||
|
|
||||||
schema.extendModel('User', {
|
dataSource.extendModel('User', {
|
||||||
settings: { type: Schema.JSON },
|
settings: { type: Schema.JSON },
|
||||||
extra: Object
|
extra: Object
|
||||||
});
|
});
|
||||||
|
@ -121,7 +121,7 @@ function testOrm(schema) {
|
||||||
var newuser = new User({settings: {hey: 'you'}});
|
var newuser = new User({settings: {hey: 'you'}});
|
||||||
test.ok(newuser.settings);
|
test.ok(newuser.settings);
|
||||||
|
|
||||||
Post = schema.define('Post', {
|
Post = dataSource.define('Post', {
|
||||||
title: { type: String, length: 255, index: true },
|
title: { type: String, length: 255, index: true },
|
||||||
subject: { type: String },
|
subject: { type: String },
|
||||||
content: { type: Text },
|
content: { type: Text },
|
||||||
|
@ -161,7 +161,7 @@ function testOrm(schema) {
|
||||||
// post.author() -- sync getter when called without params
|
// post.author() -- sync getter when called without params
|
||||||
// post.author(user) -- setter when called with object
|
// post.author(user) -- setter when called with object
|
||||||
|
|
||||||
Passport = schema.define('Passport', {
|
Passport = dataSource.define('Passport', {
|
||||||
number: String
|
number: String
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -179,7 +179,7 @@ function testOrm(schema) {
|
||||||
// instance methods
|
// instance methods
|
||||||
test.ok(user.save instanceof Function);
|
test.ok(user.save instanceof Function);
|
||||||
|
|
||||||
schema.automigrate(function (err) {
|
dataSource.automigrate(function (err) {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.log('Error while migrating');
|
console.log('Error while migrating');
|
||||||
console.log(err);
|
console.log(err);
|
||||||
|
@ -262,7 +262,7 @@ function testOrm(schema) {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should save only schema-defined field in database', function (test) {
|
it('should save only dataSource-defined field in database', function (test) {
|
||||||
Post.create({title: '1602', nonSchemaField: 'some value'}, function (err, post) {
|
Post.create({title: '1602', nonSchemaField: 'some value'}, function (err, post) {
|
||||||
test.ok(!post.nonSchemaField);
|
test.ok(!post.nonSchemaField);
|
||||||
post.a = 1;
|
post.a = 1;
|
||||||
|
@ -395,10 +395,10 @@ function testOrm(schema) {
|
||||||
});
|
});
|
||||||
|
|
||||||
if (
|
if (
|
||||||
!schema.name.match(/redis/) &&
|
!dataSource.name.match(/redis/) &&
|
||||||
schema.name !== 'memory' &&
|
dataSource.name !== 'memory' &&
|
||||||
schema.name !== 'neo4j' &&
|
dataSource.name !== 'neo4j' &&
|
||||||
schema.name !== 'cradle'
|
dataSource.name !== 'cradle'
|
||||||
)
|
)
|
||||||
it('relations key is working', function (test) {
|
it('relations key is working', function (test) {
|
||||||
test.ok(User.relations, 'Relations key should be defined');
|
test.ok(User.relations, 'Relations key should be defined');
|
||||||
|
@ -496,7 +496,7 @@ function testOrm(schema) {
|
||||||
test.equal(data.length, data2.length, 'Posts should be the same, since we are loading on the same object.');
|
test.equal(data.length, data2.length, 'Posts should be the same, since we are loading on the same object.');
|
||||||
requestsAreCounted && test.equal(nbInitialRequests, nbSchemaRequests, 'There should not be any request because value is cached.');
|
requestsAreCounted && test.equal(nbInitialRequests, nbSchemaRequests, 'There should not be any request because value is cached.');
|
||||||
|
|
||||||
if (schema.name === 'mongodb') { // for the moment mongodb doesn\'t support additional conditions on hasMany relations (see above)
|
if (dataSource.name === 'mongodb') { // for the moment mongodb doesn\'t support additional conditions on hasMany relations (see above)
|
||||||
test.done();
|
test.done();
|
||||||
} else {
|
} else {
|
||||||
user.posts({where: {id: data[0].id}}, function(err, data) {
|
user.posts({where: {id: data[0].id}}, function(err, data) {
|
||||||
|
@ -594,7 +594,7 @@ function testOrm(schema) {
|
||||||
{ title: 'Title A', subject: "A" },
|
{ title: 'Title A', subject: "A" },
|
||||||
{ title: 'Title B', subject: "A" },
|
{ title: 'Title B', subject: "A" },
|
||||||
{ title: 'Title C', subject: "D" }];
|
{ title: 'Title C', subject: "D" }];
|
||||||
var isRedis = Post.schema.name === 'redis';
|
var isRedis = Post.dataSource.name === 'redis';
|
||||||
var dates = isRedis ? [ 5, 9, 0, 17, 10, 9 ] : [
|
var dates = isRedis ? [ 5, 9, 0, 17, 10, 9 ] : [
|
||||||
new Date(1000 * 5 ),
|
new Date(1000 * 5 ),
|
||||||
new Date(1000 * 9),
|
new Date(1000 * 9),
|
||||||
|
@ -615,7 +615,7 @@ function testOrm(schema) {
|
||||||
doStringTest();
|
doStringTest();
|
||||||
doNumberTest();
|
doNumberTest();
|
||||||
|
|
||||||
if (schema.name == 'mongoose') {
|
if (dataSource.name == 'mongoose') {
|
||||||
doMultipleSortTest();
|
doMultipleSortTest();
|
||||||
doMultipleReverseSortTest();
|
doMultipleReverseSortTest();
|
||||||
}
|
}
|
||||||
|
@ -628,7 +628,7 @@ function testOrm(schema) {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Post.schema.log = console.log;
|
// Post.dataSource.log = console.log;
|
||||||
|
|
||||||
function doStringTest() {
|
function doStringTest() {
|
||||||
tests += 1;
|
tests += 1;
|
||||||
|
@ -728,11 +728,11 @@ function testOrm(schema) {
|
||||||
});
|
});
|
||||||
|
|
||||||
// if (
|
// if (
|
||||||
// !schema.name.match(/redis/) &&
|
// !dataSource.name.match(/redis/) &&
|
||||||
// schema.name !== 'memory' &&
|
// dataSource.name !== 'memory' &&
|
||||||
// schema.name !== 'neo4j' &&
|
// dataSource.name !== 'neo4j' &&
|
||||||
// schema.name !== 'cradle' &&
|
// dataSource.name !== 'cradle' &&
|
||||||
// schema.name !== 'nano'
|
// dataSource.name !== 'nano'
|
||||||
// )
|
// )
|
||||||
// it('should allow advanced queying: lt, gt, lte, gte, between', function (test) {
|
// it('should allow advanced queying: lt, gt, lte, gte, between', function (test) {
|
||||||
// Post.destroyAll(function () {
|
// Post.destroyAll(function () {
|
||||||
|
@ -792,8 +792,8 @@ function testOrm(schema) {
|
||||||
|
|
||||||
|
|
||||||
// if (
|
// if (
|
||||||
// schema.name === 'mysql' ||
|
// dataSource.name === 'mysql' ||
|
||||||
// schema.name === 'postgres'
|
// dataSource.name === 'postgres'
|
||||||
// )
|
// )
|
||||||
// it('should allow IN or NOT IN', function (test) {
|
// it('should allow IN or NOT IN', function (test) {
|
||||||
// User.destroyAll(function () {
|
// User.destroyAll(function () {
|
||||||
|
@ -962,11 +962,11 @@ function testOrm(schema) {
|
||||||
});
|
});
|
||||||
|
|
||||||
// if (
|
// if (
|
||||||
// !schema.name.match(/redis/) &&
|
// !dataSource.name.match(/redis/) &&
|
||||||
// schema.name !== 'memory' &&
|
// dataSource.name !== 'memory' &&
|
||||||
// schema.name !== 'neo4j' &&
|
// dataSource.name !== 'neo4j' &&
|
||||||
// schema.name !== 'cradle' &&
|
// dataSource.name !== 'cradle' &&
|
||||||
// schema.name !== 'nano'
|
// dataSource.name !== 'nano'
|
||||||
// )
|
// )
|
||||||
// it('belongsTo should be cached', function (test) {
|
// it('belongsTo should be cached', function (test) {
|
||||||
// User.findOne(function(err, user) {
|
// User.findOne(function(err, user) {
|
||||||
|
@ -1010,7 +1010,7 @@ function testOrm(schema) {
|
||||||
|
|
||||||
// });
|
// });
|
||||||
|
|
||||||
if (schema.name !== 'mongoose' && schema.name !== 'neo4j')
|
if (dataSource.name !== 'mongoose' && dataSource.name !== 'neo4j')
|
||||||
it('should update or create record', function (test) {
|
it('should update or create record', function (test) {
|
||||||
var newData = {
|
var newData = {
|
||||||
id: 1,
|
id: 1,
|
||||||
|
@ -1022,7 +1022,7 @@ function testOrm(schema) {
|
||||||
test.ok(updatedPost);
|
test.ok(updatedPost);
|
||||||
if (!updatedPost) throw Error('No post!');
|
if (!updatedPost) throw Error('No post!');
|
||||||
|
|
||||||
if (schema.name !== 'mongodb') {
|
if (dataSource.name !== 'mongodb') {
|
||||||
test.equal(newData.id, updatedPost.toObject().id);
|
test.equal(newData.id, updatedPost.toObject().id);
|
||||||
}
|
}
|
||||||
test.equal(newData.title, updatedPost.toObject().title);
|
test.equal(newData.title, updatedPost.toObject().title);
|
||||||
|
@ -1031,13 +1031,13 @@ function testOrm(schema) {
|
||||||
Post.findById(updatedPost.id, function (err, post) {
|
Post.findById(updatedPost.id, function (err, post) {
|
||||||
if (err) throw err;
|
if (err) throw err;
|
||||||
if (!post) throw Error('No post!');
|
if (!post) throw Error('No post!');
|
||||||
if (schema.name !== 'mongodb') {
|
if (dataSource.name !== 'mongodb') {
|
||||||
test.equal(newData.id, post.toObject().id);
|
test.equal(newData.id, post.toObject().id);
|
||||||
}
|
}
|
||||||
test.equal(newData.title, post.toObject().title);
|
test.equal(newData.title, post.toObject().title);
|
||||||
test.equal(newData.content, post.toObject().content);
|
test.equal(newData.content, post.toObject().content);
|
||||||
Post.updateOrCreate({id: 100001, title: 'hey'}, function (err, post) {
|
Post.updateOrCreate({id: 100001, title: 'hey'}, function (err, post) {
|
||||||
if (schema.name !== 'mongodb') test.equal(post.id, 100001);
|
if (dataSource.name !== 'mongodb') test.equal(post.id, 100001);
|
||||||
test.equal(post.title, 'hey');
|
test.equal(post.title, 'hey');
|
||||||
Post.findById(post.id, function (err, post) {
|
Post.findById(post.id, function (err, post) {
|
||||||
if (!post) throw Error('No post!');
|
if (!post) throw Error('No post!');
|
||||||
|
@ -1049,7 +1049,7 @@ function testOrm(schema) {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should work with custom setters and getters', function (test) {
|
it('should work with custom setters and getters', function (test) {
|
||||||
User.schema.defineForeignKey('User', 'passwd');
|
User.dataSource.defineForeignKey('User', 'passwd');
|
||||||
User.setter.passwd = function (pass) {
|
User.setter.passwd = function (pass) {
|
||||||
this._passwd = pass + 'salt';
|
this._passwd = pass + 'salt';
|
||||||
};
|
};
|
||||||
|
|
|
@ -75,8 +75,8 @@ describe('hooks', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('afterCreate should not be triggered on failed create', function(done) {
|
it('afterCreate should not be triggered on failed create', function(done) {
|
||||||
var old = User.schema.adapter.create;
|
var old = User.dataSource.connector.create;
|
||||||
User.schema.adapter.create = function(modelName, id, cb) {
|
User.dataSource.connector.create = function(modelName, id, cb) {
|
||||||
cb(new Error('error'));
|
cb(new Error('error'));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -84,7 +84,7 @@ describe('hooks', function() {
|
||||||
throw new Error('shouldn\'t be called')
|
throw new Error('shouldn\'t be called')
|
||||||
};
|
};
|
||||||
User.create(function (err, user) {
|
User.create(function (err, user) {
|
||||||
User.schema.adapter.create = old;
|
User.dataSource.connector.create = old;
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -224,9 +224,9 @@ describe('hooks', function() {
|
||||||
should.fail('afterUpdate shouldn\'t be called')
|
should.fail('afterUpdate shouldn\'t be called')
|
||||||
};
|
};
|
||||||
User.create(function (err, user) {
|
User.create(function (err, user) {
|
||||||
var save = User.schema.adapter.save;
|
var save = User.dataSource.connector.save;
|
||||||
User.schema.adapter.save = function(modelName, id, cb) {
|
User.dataSource.connector.save = function(modelName, id, cb) {
|
||||||
User.schema.adapter.save = save;
|
User.dataSource.connector.save = save;
|
||||||
cb(new Error('Error'));
|
cb(new Error('Error'));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -257,8 +257,8 @@ describe('hooks', function() {
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should not trigger after-hook on failed destroy', function(done) {
|
it('should not trigger after-hook on failed destroy', function(done) {
|
||||||
var destroy = User.schema.adapter.destroy;
|
var destroy = User.dataSource.connector.destroy;
|
||||||
User.schema.adapter.destroy = function(modelName, id, cb) {
|
User.dataSource.connector.destroy = function(modelName, id, cb) {
|
||||||
cb(new Error('error'));
|
cb(new Error('error'));
|
||||||
}
|
}
|
||||||
User.afterDestroy = function() {
|
User.afterDestroy = function() {
|
||||||
|
@ -266,7 +266,7 @@ describe('hooks', function() {
|
||||||
};
|
};
|
||||||
User.create(function (err, user) {
|
User.create(function (err, user) {
|
||||||
user.destroy(function(err) {
|
user.destroy(function(err) {
|
||||||
User.schema.adapter.destroy = destroy;
|
User.dataSource.connector.destroy = destroy;
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
@ -4,11 +4,11 @@ var should = require('./init.js');
|
||||||
var Schema = require('../').Schema;
|
var Schema = require('../').Schema;
|
||||||
|
|
||||||
describe('JSON property', function() {
|
describe('JSON property', function() {
|
||||||
var schema, Model;
|
var dataSource, Model;
|
||||||
|
|
||||||
it('should be defined', function() {
|
it('should be defined', function() {
|
||||||
schema = getSchema();
|
dataSource = getSchema();
|
||||||
Model = schema.define('Model', {propertyName: Schema.JSON});
|
Model = dataSource.define('Model', {propertyName: Schema.JSON});
|
||||||
var m = new Model;
|
var m = new Model;
|
||||||
(new Boolean('propertyName' in m)).should.eql(true);
|
(new Boolean('propertyName' in m)).should.eql(true);
|
||||||
should.not.exist(m.propertyName);
|
should.not.exist(m.propertyName);
|
||||||
|
|
|
@ -218,7 +218,7 @@ describe('Load models from json', function () {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load LDL schemas from a json doc
|
* Load LDL schemas from a json doc
|
||||||
* @param schemaFile The schema json file
|
* @param schemaFile The dataSource json file
|
||||||
* @returns A map of schemas keyed by name
|
* @returns A map of schemas keyed by name
|
||||||
*/
|
*/
|
||||||
function loadSchemasSync(schemaFile, dataSource) {
|
function loadSchemasSync(schemaFile, dataSource) {
|
||||||
|
@ -227,7 +227,7 @@ describe('Load models from json', function () {
|
||||||
dataSource = new DataSource('memory');
|
dataSource = new DataSource('memory');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read the schema JSON file
|
// Read the dataSource JSON file
|
||||||
var schemas = JSON.parse(fs.readFileSync(schemaFile));
|
var schemas = JSON.parse(fs.readFileSync(schemaFile));
|
||||||
|
|
||||||
return dataSource.buildModels(schemas);
|
return dataSource.buildModels(schemas);
|
||||||
|
|
|
@ -14,7 +14,7 @@ schemas =
|
||||||
nano:
|
nano:
|
||||||
url: 'http://localhost:5984/nano-test'
|
url: 'http://localhost:5984/nano-test'
|
||||||
|
|
||||||
testOrm = (schema) ->
|
testOrm = (dataSource) ->
|
||||||
|
|
||||||
User = Post = 'unknown'
|
User = Post = 'unknown'
|
||||||
maxUsers = 100
|
maxUsers = 100
|
||||||
|
@ -23,7 +23,7 @@ testOrm = (schema) ->
|
||||||
|
|
||||||
it 'should define simple', (test) ->
|
it 'should define simple', (test) ->
|
||||||
|
|
||||||
User = schema.define 'User', {
|
User = dataSource.define 'User', {
|
||||||
name: String,
|
name: String,
|
||||||
bio: Text,
|
bio: Text,
|
||||||
approved: Boolean,
|
approved: Boolean,
|
||||||
|
@ -31,7 +31,7 @@ testOrm = (schema) ->
|
||||||
age: Number
|
age: Number
|
||||||
}
|
}
|
||||||
|
|
||||||
Post = schema.define 'Post',
|
Post = dataSource.define 'Post',
|
||||||
title: { type: String, length: 255, index: true }
|
title: { type: String, length: 255, index: true }
|
||||||
content: { type: Text }
|
content: { type: Text }
|
||||||
date: { type: Date, detault: Date.now }
|
date: { type: Date, detault: Date.now }
|
||||||
|
@ -78,6 +78,6 @@ testOrm = (schema) ->
|
||||||
Object.keys(schemas).forEach (schemaName) ->
|
Object.keys(schemas).forEach (schemaName) ->
|
||||||
return if process.env.ONLY && process.env.ONLY != schemaName
|
return if process.env.ONLY && process.env.ONLY != schemaName
|
||||||
context schemaName, ->
|
context schemaName, ->
|
||||||
schema = new Schema schemaName, schemas[schemaName]
|
dataSource = new Schema schemaName, schemas[schemaName]
|
||||||
testOrm(schema)
|
testOrm(dataSource)
|
||||||
|
|
||||||
|
|
|
@ -3,23 +3,23 @@ var should = require('./init.js');
|
||||||
|
|
||||||
var db = getSchema(), slave = getSchema(), Model, SlaveModel;
|
var db = getSchema(), slave = getSchema(), Model, SlaveModel;
|
||||||
|
|
||||||
describe('schema', function() {
|
describe('dataSource', function() {
|
||||||
|
|
||||||
it('should define Model', function() {
|
it('should define Model', function() {
|
||||||
Model = db.define('Model');
|
Model = db.define('Model');
|
||||||
Model.schema.should.eql(db);
|
Model.dataSource.should.eql(db);
|
||||||
var m = new Model;
|
var m = new Model;
|
||||||
m.schema.should.eql(db);
|
m.dataSource.should.eql(db);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should clone existing model', function() {
|
it('should clone existing model', function() {
|
||||||
SlaveModel = slave.copyModel(Model);
|
SlaveModel = slave.copyModel(Model);
|
||||||
SlaveModel.schema.should.eql(slave);
|
SlaveModel.dataSource.should.eql(slave);
|
||||||
slave.should.not.eql(db);
|
slave.should.not.eql(db);
|
||||||
var sm = new SlaveModel;
|
var sm = new SlaveModel;
|
||||||
sm.should.be.instanceOf(Model);
|
sm.should.be.instanceOf(Model);
|
||||||
sm.schema.should.not.eql(db);
|
sm.dataSource.should.not.eql(db);
|
||||||
sm.schema.should.eql(slave);
|
sm.dataSource.should.eql(slave);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should automigrate', function(done) {
|
it('should automigrate', function(done) {
|
||||||
|
|
Loading…
Reference in New Issue