More renames: schema -> dataSource, adapter -> connector

This commit is contained in:
Raymond Feng 2013-07-23 11:16:43 -07:00
parent 51286684bd
commit 6af4b1ba2f
19 changed files with 345 additions and 351 deletions

View File

@ -4,7 +4,7 @@ var path = require('path'),
/**
* 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
*/
function loadSchemasSync(schemaFile, dataSource) {
@ -13,7 +13,7 @@ function loadSchemasSync(schemaFile, dataSource) {
dataSource = new DataSource('memory');
}
// Read the schema JSON file
// Read the dataSource JSON file
var schemas = JSON.parse(fs.readFileSync(schemaFile));
return dataSource.buildModels(schemas);

View File

@ -142,38 +142,38 @@ function filtering(res, model, filter, instance) {
/**
* Connection/Disconnection
*/
exports.initialize = function(schema, callback) {
exports.initialize = function(dataSource, callback) {
if (!cradle) return;
// when using cradle if we dont wait for the schema to be connected, the models fails to load correctly.
schema.waitForConnect = true;
if (!schema.settings.url) {
var host = schema.settings.host || 'localhost';
var port = schema.settings.port || '5984';
var options = schema.settings.options || {
// when using cradle if we dont wait for the dataSource to be connected, the models fails to load correctly.
dataSource.waitForConnect = true;
if (!dataSource.settings.url) {
var host = dataSource.settings.host || 'localhost';
var port = dataSource.settings.port || '5984';
var options = dataSource.settings.options || {
cache: true,
raw: false
};
if (schema.settings.username) {
if (dataSource.settings.username) {
options.auth = {};
options.auth.username = schema.settings.username;
if (schema.settings.password) {
options.auth.password = schema.settings.password;
options.auth.username = dataSource.settings.username;
if (dataSource.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;
schema.settings.port = port;
schema.settings.database = database;
schema.settings.options = options;
dataSource.settings.host = host;
dataSource.settings.port = port;
dataSource.settings.database = database;
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(
schema.client,
dataSource.client,
errorHandler(callback, function() {
schema.adapter = new CradleAdapter(schema.client);
dataSource.connector = new CradleAdapter(dataSource.client);
process.nextTick(callback);
}));
};

View File

@ -1,5 +1,5 @@
exports.initialize = function initializeSchema(schema, callback) {
schema.adapter = new WebService();
exports.initialize = function initializeSchema(dataSource, callback) {
dataSource.connector = new WebService();
process.nextTick(callback);
};

View File

@ -1,9 +1,9 @@
var geo = require('../geo');
var utils = require('../utils');
exports.initialize = function initializeSchema(schema, callback) {
schema.adapter = new Memory();
schema.adapter.connect(callback);
exports.initialize = function initializeSchema(dataSource, callback) {
dataSource.connector = new Memory();
dataSource.connector.connect(callback);
};
exports.Memory = Memory;

View File

@ -5,9 +5,9 @@ var safeRequire = require('../utils').safeRequire;
*/
var neo4j = safeRequire('neo4j');
exports.initialize = function initializeSchema(schema, callback) {
schema.client = new neo4j.GraphDatabase(schema.settings.url);
schema.adapter = new Neo4j(schema.client);
exports.initialize = function initializeSchema(dataSource, callback) {
dataSource.client = new neo4j.GraphDatabase(dataSource.settings.url);
dataSource.connector = new Neo4j(dataSource.client);
process.nextTick(callback);
};

View File

@ -6,12 +6,12 @@ var safeRequire = require('../utils').safeRequire;
var uuid = require('node-uuid');
var riak = safeRequire('riak-js');
exports.initialize = function initializeSchema(schema, callback) {
schema.client = riak.getClient({
host: schema.settings.host || '127.0.0.1',
port: schema.settings.port || 8091
exports.initialize = function initializeSchema(dataSource, callback) {
dataSource.client = riak.getClient({
host: dataSource.settings.host || '127.0.0.1',
port: dataSource.settings.port || 8091
});
schema.adapter = new Riak(schema.client);
dataSource.connector = new Riak(dataSource.client);
};
function Riak(client) {

View File

@ -20,9 +20,9 @@ var fieldsToArray = require('./utils').fieldsToArray;
/**
* 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`
* to learn more about specific adapter implementations
* to learn more about specific connector implementations
*
* `DataAccessObject` mixes `Inclusion` classes methods
*
@ -41,7 +41,7 @@ function DataAccessObject() {
DataAccessObject._forDB = function (data) {
if(!(this.schema.isRelational && this.schema.isRelational())) {
if(!(this.dataSource.isRelational && this.dataSource.isRelational())) {
return data;
}
var res = {};
@ -67,7 +67,7 @@ DataAccessObject._forDB = function (data) {
* - instance (null or Model)
*/
DataAccessObject.create = function (data, callback) {
if (stillConnecting(this.schema, this, arguments)) return;
if (stillConnecting(this.dataSource, this, arguments)) return;
var Model = this;
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.http = {verb: 'post', path: '/'};
function stillConnecting(schema, obj, args) {
if (schema.connected) return false; // Connected
function stillConnecting(dataSource, obj, args) {
if (dataSource.connected) return false; // Connected
var method = args.callee;
// 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));
});
if (!schema.connecting) {
schema.connect();
if (!dataSource.connecting) {
dataSource.connect();
}
return true;
};
@ -186,13 +186,13 @@ function stillConnecting(schema, obj, args) {
* Update or insert
*/
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;
if (!data.id) return this.create(data, callback);
if (this.schema.adapter.updateOrCreate) {
if (this.dataSource.connector.updateOrCreate) {
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;
if (data) {
inst._initProperties(data);
@ -250,10 +250,10 @@ DataAccessObject.findOrCreate = function findOrCreate(query, data, callback) {
* @param {Function} cb - callbacl called with (err, exists: Bool)
*/
DataAccessObject.exists = function exists(id, cb) {
if (stillConnecting(this.schema, this, arguments)) return;
if (stillConnecting(this.dataSource, this, arguments)) return;
if (id) {
this.schema.adapter.exists(this.modelName, id, cb);
this.dataSource.connector.exists(this.modelName, id, cb);
} else {
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)
*/
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;
if (data) {
if (!data.id) {
@ -318,7 +318,7 @@ DataAccessObject.all = function () {
*/
DataAccessObject.find = function find(params, cb) {
if (stillConnecting(this.schema, this, arguments)) return;
if (stillConnecting(this.dataSource, this, arguments)) return;
if (arguments.length === 1) {
cb = params;
@ -329,7 +329,7 @@ DataAccessObject.find = function find(params, cb) {
params = params || {};
var fields = params.fields;
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
if(fields) {
@ -339,11 +339,11 @@ DataAccessObject.find = function find(params, cb) {
if(near) {
if(supportsGeo) {
// convert it
this.schema.adapter.buildNearFilter(params, near);
this.dataSource.connector.buildNearFilter(params, near);
} else if(params.where) {
// do in memory query
// 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 modelName = constr.modelName;
@ -351,8 +351,8 @@ DataAccessObject.find = function find(params, cb) {
cb(err);
} else if(Array.isArray(data)) {
memory.define({
properties: constr.schema.definitions[constr.modelName].properties,
settings: constr.schema.definitions[constr.modelName].settings,
properties: constr.dataSource.definitions[constr.modelName].properties,
settings: constr.dataSource.definitions[constr.modelName].settings,
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) {
data.forEach(function (d, i) {
var obj = new constr;
@ -414,7 +414,7 @@ DataAccessObject.find.http = [
* @param {Function} cb - callback called with (err, instance)
*/
DataAccessObject.findOne = function findOne(params, cb) {
if (stillConnecting(this.schema, this, arguments)) return;
if (stillConnecting(this.dataSource, this, arguments)) return;
if (typeof params === 'function') {
cb = params;
@ -437,9 +437,9 @@ DataAccessObject.findOne.returns = {arg: 'data', type: 'object'};
*/
DataAccessObject.deleteAll =
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) {
cb(err);
}
@ -452,9 +452,9 @@ DataAccessObject.destroyAll = function destroyAll(cb) {
*/
DataAccessObject.deleteById =
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) {
cb(err);
}
@ -478,13 +478,13 @@ DataAccessObject.deleteById.http = [
* @param {Function} cb - callback, called with (err, count)
*/
DataAccessObject.count = function (where, cb) {
if (stillConnecting(this.schema, this, arguments)) return;
if (stillConnecting(this.dataSource, this, arguments)) return;
if (typeof where === 'function') {
cb = where;
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)
*/
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') {
callback = options;
@ -578,11 +578,11 @@ DataAccessObject.prototype.isNewRecord = function () {
};
/**
* Return adapter of current record
* Return connector of current record
* @private
*/
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.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._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)
*/
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 model = this.constructor.modelName;
@ -703,7 +703,7 @@ DataAccessObject.prototype.updateAttributes.http = [
* @param {Function} callback - called with (err, instance) arguments
*/
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);
};

View File

@ -25,14 +25,14 @@ exports.DataSource = DataSource;
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
*
* @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
* establish connection (of course it depends on specific adapter)
* establish connection (of course it depends on specific connector)
*
* - host
* - port
@ -43,9 +43,9 @@ var slice = Array.prototype.slice;
*
* @example DataSource creation, waiting for connection callback
* ```
* var schema = new DataSource('mysql', { database: 'myapp_test' });
* schema.define(...);
* schema.on('connected', function () {
* var dataSource = new DataSource('mysql', { database: 'myapp_test' });
* dataSource.define(...);
* dataSource.on('connected', function () {
* // work with database
* });
* ```
@ -57,13 +57,13 @@ function DataSource(name, settings) {
ModelBuilder.call(this, arguments);
// 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.setup(name, settings);
// connector
var connector = this.connector();
var connector = this.connector;
// DataAccessObject - connector defined or supply the default
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) {
var schema = this;
var adapter;
var dataSource = this;
var connector;
// support single settings object
if(name && typeof name === 'object') {
@ -130,11 +130,11 @@ DataSource.prototype.setup = function(name, settings) {
if(typeof settings === 'object') {
if(settings.initialize) {
adapter = settings;
connector = settings;
} else if(settings.connector) {
adapter = settings.connector;
} else if(settings.adapter) {
adapter = settings.adapter;
connector = settings.connector;
} else if(settings.connector) {
connector = settings.connector;
}
}
@ -146,42 +146,45 @@ DataSource.prototype.setup = function(name, settings) {
this.connected = false;
this.connecting = false;
if (name && !adapter) {
// and initialize schema using adapter
// this is only one initialization entry point of adapter
// this module should define `adapter` member of `this` (schema)
if (name && !connector) {
// and initialize dataSource using connector
// this is only one initialization entry point of connector
// this module should define `connector` member of `this` (dataSource)
if (typeof name === 'object') {
adapter = name;
this.name = adapter.name;
connector = name;
this.name = connector.name;
} else if (name.match(/^\//)) {
// try absolute path
adapter = require(name);
connector = require(name);
} else if (existsSync(__dirname + '/adapters/' + name + '.js')) {
// try built-in adapter
adapter = require('./adapters/' + name);
// try built-in connector
connector = require('./adapters/' + name);
} else {
// try foreign adapter
// try foreign connector
try {
adapter = require('loopback-connector-' + name);
connector = require('loopback-connector-' + name);
} 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() {
// we have an adaper now?
if (!this.adapter) {
throw new Error('Adapter is not defined correctly: it should create `adapter` member of schema');
this.connector = this.connector || this.adapter;
this.adapter = this.connector; // Keep the adapter as an alias to connector
// 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) {
schema.log(query, start);
this.connector.log = function (query, start) {
dataSource.log(query, start);
};
this.adapter.logger = function (query) {
this.connector.logger = function (query) {
var t1 = Date.now();
var log = this.log;
return function (q) {
@ -194,31 +197,31 @@ DataSource.prototype.setup = function(name, settings) {
}.bind(this);
if ('function' === typeof adapter.initialize) {
if ('function' === typeof connector.initialize) {
// Call the async initialize method
adapter.initialize(this, postInit);
} else if('function' === typeof adapter) {
// Use the adapter constructor directly
this.adapter = new adapter(this.settings);
connector.initialize(this, postInit);
} else if('function' === typeof connector) {
// Use the connector constructor directly
this.connector = new connector(this.settings);
postInit();
}
}
schema.connect = function(cb) {
var schema = this;
if(schema.connected || schema.connecting) {
dataSource.connect = function(cb) {
var dataSource = this;
if(dataSource.connected || dataSource.connecting) {
process.nextTick(function() {
cb && cb();
});
return;
}
schema.connecting = true;
if (schema.adapter.connect) {
schema.adapter.connect(function(err, result) {
dataSource.connecting = true;
if (dataSource.connector.connect) {
dataSource.connector.connect(function(err, result) {
if (!err) {
schema.connected = true;
schema.connecting = false;
schema.emit('connected');
dataSource.connected = true;
dataSource.connecting = false;
dataSource.emit('connected');
}
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
*
@ -252,7 +246,7 @@ DataSource.prototype.connector = function () {
*
* @example simple case
* ```
* var User = schema.define('User', {
* var User = dataSource.define('User', {
* email: String,
* password: String,
* birthDate: Date,
@ -261,7 +255,7 @@ DataSource.prototype.connector = function () {
* ```
* @example more advanced case
* ```
* var User = schema.define('User', {
* var User = dataSource.define('User', {
* email: { type: String, limit: 150, index: true },
* password: { type: String, limit: 50 },
* birthDate: Date,
@ -286,9 +280,9 @@ DataSource.prototype.define = function defineClass(className, properties, settin
// add data access objects
this.mixin(NewClass);
if(this.adapter && this.adapter.define) {
// pass control to adapter
this.adapter.define({
if(this.connector && this.connector.define) {
// pass control to connector
this.connector.define({
model: NewClass,
properties: properties,
settings: settings
@ -347,23 +341,23 @@ DataSource.prototype.mixin = function (ModelCtor) {
*/
DataSource.prototype.attach = function (ModelCtor) {
var properties = ModelCtor.schema.definitions[ModelCtor.modelName].properties;
var settings = ModelCtor.schema.definitions[ModelCtor.modelName].settings;
var properties = ModelCtor.dataSource.definitions[ModelCtor.modelName].properties;
var settings = ModelCtor.dataSource.definitions[ModelCtor.modelName].settings;
var className = ModelCtor.modelName;
this.mixin(ModelCtor);
if(this.adapter && this.adapter.define) {
// pass control to adapter
this.adapter.define({
if(this.connector && this.connector.define) {
// pass control to connector
this.connector.define({
model: ModelCtor,
properties: properties,
settings: settings
});
}
// redefine the schema
hiddenProperty(ModelCtor, 'schema', this);
// redefine the dataSource
hiddenProperty(ModelCtor, 'dataSource', this);
ModelCtor.dataSource = this;
// add to def
@ -387,8 +381,8 @@ DataSource.prototype.attach = function (ModelCtor) {
DataSource.prototype.defineProperty = function (model, prop, params) {
ModelBuilder.prototype.defineProperty.call(this, model, prop, params);
if (this.adapter.defineProperty) {
this.adapter.defineProperty(model, prop, params);
if (this.connector.defineProperty) {
this.connector.defineProperty(model, prop, params);
}
};
@ -400,8 +394,8 @@ DataSource.prototype.defineProperty = function (model, prop, params) {
*/
DataSource.prototype.automigrate = function (cb) {
this.freeze();
if (this.adapter.automigrate) {
this.adapter.automigrate(cb);
if (this.connector.automigrate) {
this.connector.automigrate(cb);
} else if (cb) {
cb();
}
@ -413,8 +407,8 @@ DataSource.prototype.automigrate = function (cb) {
*/
DataSource.prototype.autoupdate = function (cb) {
this.freeze();
if (this.adapter.autoupdate) {
this.adapter.autoupdate(cb);
if (this.connector.autoupdate) {
this.connector.autoupdate(cb);
} else if (cb) {
cb();
}
@ -432,8 +426,8 @@ DataSource.prototype.autoupdate = function (cb) {
*/
DataSource.prototype.discoverModelDefinitions = function (options, cb) {
this.freeze();
if (this.adapter.discoverModelDefinitions) {
this.adapter.discoverModelDefinitions(options, cb);
if (this.connector.discoverModelDefinitions) {
this.connector.discoverModelDefinitions(options, cb);
} else if (cb) {
cb();
}
@ -442,8 +436,8 @@ DataSource.prototype.discoverModelDefinitions = function (options, cb) {
DataSource.prototype.discoverModelDefinitionsSync = function (options) {
this.freeze();
if (this.adapter.discoverModelDefinitionsSync) {
return this.adapter.discoverModelDefinitionsSync(options);
if (this.connector.discoverModelDefinitionsSync) {
return this.connector.discoverModelDefinitionsSync(options);
}
return null;
};
@ -457,8 +451,8 @@ DataSource.prototype.discoverModelDefinitionsSync = function (options) {
*/
DataSource.prototype.discoverModelProperties = function (table, options, cb) {
this.freeze();
if (this.adapter.discoverModelProperties) {
this.adapter.discoverModelProperties(table, options, cb);
if (this.connector.discoverModelProperties) {
this.connector.discoverModelProperties(table, options, cb);
} else if (cb) {
cb();
}
@ -466,8 +460,8 @@ DataSource.prototype.discoverModelProperties = function (table, options, cb) {
DataSource.prototype.discoverModelPropertiesSync = function (modelName, options) {
this.freeze();
if (this.adapter.discoverModelPropertiesSync) {
return this.adapter.discoverModelPropertiesSync(modelName, options);
if (this.connector.discoverModelPropertiesSync) {
return this.connector.discoverModelPropertiesSync(modelName, options);
}
return null;
};
@ -476,7 +470,7 @@ DataSource.prototype.discoverModelPropertiesSync = function (modelName, options)
* Discover primary keys for a given owner/modelName
*
* 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
* 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).
@ -488,8 +482,8 @@ DataSource.prototype.discoverModelPropertiesSync = function (modelName, options)
*/
DataSource.prototype.discoverPrimaryKeys= function(modelName, options, cb) {
this.freeze();
if (this.adapter.discoverPrimaryKeys) {
this.adapter.discoverPrimaryKeys(modelName, options, cb);
if (this.connector.discoverPrimaryKeys) {
this.connector.discoverPrimaryKeys(modelName, options, cb);
} else if (cb) {
cb();
}
@ -497,8 +491,8 @@ DataSource.prototype.discoverPrimaryKeys= function(modelName, options, cb) {
DataSource.prototype.discoverPrimaryKeysSync= function(modelName, options) {
this.freeze();
if (this.adapter.discoverPrimaryKeysSync) {
return this.adapter.discoverPrimaryKeysSync(modelName, options);
if (this.connector.discoverPrimaryKeysSync) {
return this.connector.discoverPrimaryKeysSync(modelName, options);
}
return null;
}
@ -506,12 +500,12 @@ DataSource.prototype.discoverPrimaryKeysSync= function(modelName, options) {
/**
* 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)
* fkTableName String => foreign key table 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).
* 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)
* pkTableName String => primary key table 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) {
this.freeze();
if (this.adapter.discoverForeignKeys) {
this.adapter.discoverForeignKeys(modelName, options, cb);
if (this.connector.discoverForeignKeys) {
this.connector.discoverForeignKeys(modelName, options, cb);
} else if (cb) {
cb();
}
@ -532,8 +526,8 @@ DataSource.prototype.discoverForeignKeys= function(modelName, options, cb) {
DataSource.prototype.discoverForeignKeysSync= function(modelName, options) {
this.freeze();
if (this.adapter.discoverForeignKeysSync) {
return this.adapter.discoverForeignKeysSync(modelName, options);
if (this.connector.discoverForeignKeysSync) {
return this.connector.discoverForeignKeysSync(modelName, options);
}
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).
* 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)
* fkTableName String => foreign key table 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).
* 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)
* pkTableName String => primary key table 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) {
this.freeze();
if (this.adapter.discoverExportedForeignKeys) {
this.adapter.discoverExportedForeignKeys(modelName, options, cb);
if (this.connector.discoverExportedForeignKeys) {
this.connector.discoverExportedForeignKeys(modelName, options, cb);
} else if (cb) {
cb();
}
@ -567,8 +561,8 @@ DataSource.prototype.discoverExportedForeignKeys= function(modelName, options, c
DataSource.prototype.discoverExportedForeignKeysSync= function(modelName, options) {
this.freeze();
if (this.adapter.discoverExportedForeignKeysSync) {
return this.adapter.discoverExportedForeignKeysSync(modelName, options);
if (this.connector.discoverExportedForeignKeysSync) {
return this.connector.discoverExportedForeignKeysSync(modelName, options);
}
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 cb
@ -630,7 +624,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
}
var self = this;
var dataSourceName = this.name || this.adapter.name;
var dataSourceName = this.name || this.connector.name;
var tasks = [
this.discoverModelProperties.bind(this, modelName, options),
@ -664,7 +658,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
console.log('Primary keys: ', pks);
}
var schema = {
var dataSource = {
name: fromDBName(modelName, false),
options: {
idInjection: false // DO NOT add id property
@ -673,8 +667,8 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
}
};
schema.options[dataSourceName] = {
schema: columns[0].owner,
dataSource.options[dataSourceName] = {
dataSource: columns[0].owner,
table: modelName
};
@ -682,16 +676,16 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
var i = item;
var propName = fromDBName(item.columnName, true);
schema.properties[propName] = {
dataSource.properties[propName] = {
type: item.type,
required: (item.nullable === 'N'),
length: item.dataLength
};
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,
dataType: i.dataType,
dataLength: i.dataLength,
@ -704,9 +698,9 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
var schemaKey = columns[0].owner + '.' + modelName;
if (!options.visited.hasOwnProperty(schemaKey)) {
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 = {};
@ -734,7 +728,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
foreignKeys.forEach(function (fk) {
var propName = fromDBName(fk.pkTableName, true);
schema.properties[propName] = {
dataSource.properties[propName] = {
type: fromDBName(fk.pkTableName, false),
association: {
type: 'belongsTo',
@ -755,7 +749,7 @@ DataSource.prototype.discoverSchemas = function (modelName, options, cb) {
var moreTasks = [];
for (var t in otherTables) {
if(self.settings.debug) {
console.log('Discovering related schema for ' + schemaKey);
console.log('Discovering related dataSource for ' + schemaKey);
}
var newOptions = {};
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 cb
*/
DataSource.prototype.discoverSchemasSync = function (modelName, options) {
var self = this;
var dataSourceName = this.name || this.adapter.name;
var dataSourceName = this.name || this.connector.name;
var columns = this.discoverModelPropertiesSync(modelName, options);
if (!columns || columns.length === 0) {
@ -800,7 +794,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
console.log('Primary keys: ', pks);
}
var schema = {
var dataSource = {
name: fromDBName(modelName, false),
options: {
idInjection: false // DO NOT add id property
@ -809,8 +803,8 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
}
};
schema.options[dataSourceName] = {
schema: columns.length > 0 && columns[0].owner,
dataSource.options[dataSourceName] = {
dataSource: columns.length > 0 && columns[0].owner,
table: modelName
};
@ -818,16 +812,16 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
var i = item;
var propName = fromDBName(item.columnName, true);
schema.properties[propName] = {
dataSource.properties[propName] = {
type: item.type,
required: (item.nullable === 'N'),
length: item.dataLength
};
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,
dataType: i.dataType,
dataLength: i.dataLength,
@ -840,9 +834,9 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
var schemaKey = columns[0].owner + '.' + modelName;
if (!options.visited.hasOwnProperty(schemaKey)) {
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 = {};
@ -870,7 +864,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
foreignKeys.forEach(function (fk) {
var propName = fromDBName(fk.pkTableName, true);
schema.properties[propName] = {
dataSource.properties[propName] = {
type: fromDBName(fk.pkTableName, false),
association: {
type: 'belongsTo',
@ -891,7 +885,7 @@ DataSource.prototype.discoverSchemasSync = function (modelName, options) {
var moreTasks = [];
for (var t in otherTables) {
if (self.settings.debug) {
console.log('Discovering related schema for ' + schemaKey);
console.log('Discovering related dataSource for ' + schemaKey);
}
var newOptions = {};
for(var key in options) {
@ -922,8 +916,8 @@ DataSource.prototype.discoverAndBuildModels = function (modelName, options, cb)
var schemaList = [];
for (var s in schemas) {
var schema = schemas[s];
schemaList.push(schema);
var dataSource = schemas[s];
schemaList.push(dataSource);
}
var models = self.buildModels(schemaList);
@ -942,8 +936,8 @@ DataSource.prototype.discoverAndBuildModelsSync = function (modelName, options)
var schemaList = [];
for (var s in schemas) {
var schema = schemas[s];
schemaList.push(schema);
var dataSource = schemas[s];
schemaList.push(dataSource);
}
var models = this.buildModels(schemaList);
@ -956,8 +950,8 @@ DataSource.prototype.discoverAndBuildModelsSync = function (modelName, options)
*/
DataSource.prototype.isActual = function (cb) {
this.freeze();
if (this.adapter.isActual) {
this.adapter.isActual(cb);
if (this.connector.isActual) {
this.connector.isActual(cb);
} else if (cb) {
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
* chema logs, use `schema.on('log', ...)` emitter event
* chema logs, use `dataSource.on('log', ...)` emitter event
*
* @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() {
if (this.adapter.freezeSchema) {
this.adapter.freezeSchema();
if (this.connector.freezeSchema) {
this.connector.freezeSchema();
}
}
@ -988,8 +982,8 @@ DataSource.prototype.freeze = function freeze() {
*/
DataSource.prototype.tableName = function (modelName) {
var settings = this.definitions[modelName].settings;
if(settings[this.adapter.name]) {
return settings[this.adapter.name].table || modelName;
if(settings[this.connector.name]) {
return settings[this.connector.name].table || modelName;
} else {
return modelName;
}
@ -1006,8 +1000,8 @@ DataSource.prototype.columnName = function (modelName, propertyName) {
return propertyName;
}
var property = this.definitions[modelName].properties[propertyName];
if(property && property[this.adapter.name]) {
return property[this.adapter.name].columnName || propertyName;
if(property && property[this.connector.name]) {
return property[this.connector.name].columnName || propertyName;
} else {
return propertyName;
}
@ -1024,8 +1018,8 @@ DataSource.prototype.columnMetadata = function (modelName, propertyName) {
return propertyName;
}
var property = this.definitions[modelName].properties[propertyName];
if(property && property[this.adapter.name]) {
return property[this.adapter.name];
if(property && property[this.connector.name]) {
return property[this.connector.name];
} else {
return null;
}
@ -1040,8 +1034,8 @@ DataSource.prototype.columnNames = function (modelName) {
var props = this.definitions[modelName].properties;
var cols = [];
for(var p in props) {
if(props[p][this.adapter.name]) {
cols.push(props[p][this.adapter.name].columnName || p);
if(props[p][this.connector.name]) {
cols.push(props[p][this.connector.name].columnName || p);
} else {
cols.push(p);
}
@ -1105,18 +1099,18 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key
// quit if key already defined
if (this.definitions[className].properties[key]) return;
if (this.adapter.defineForeignKey) {
if (this.connector.defineForeignKey) {
var cb = function (err, keyType) {
if (err) throw err;
this.definitions[className].properties[key] = {type: keyType};
}.bind(this);
switch (this.adapter.defineForeignKey.length) {
switch (this.connector.defineForeignKey.length) {
case 4:
this.adapter.defineForeignKey(className, key, foreignClassName, cb);
this.connector.defineForeignKey(className, key, foreignClassName, cb);
break;
default:
case 3:
this.adapter.defineForeignKey(className, key, cb);
this.connector.defineForeignKey(className, key, cb);
break;
}
} else {
@ -1131,8 +1125,8 @@ DataSource.prototype.defineForeignKey = function defineForeignKey(className, key
*/
DataSource.prototype.disconnect = function disconnect(cb) {
var self = this;
if (this.connected && (typeof this.adapter.disconnect === 'function')) {
this.adapter.disconnect(function(err, result) {
if (this.connected && (typeof this.connector.disconnect === 'function')) {
this.connector.disconnect(function(err, result) {
self.connected = false;
cb && cb(err, result);
});
@ -1144,33 +1138,33 @@ DataSource.prototype.disconnect = function disconnect(cb) {
};
DataSource.prototype.copyModel = function copyModel(Master) {
var schema = this;
var dataSource = this;
var className = Master.modelName;
var md = Master.schema.definitions[className];
var md = Master.dataSource.definitions[className];
var Slave = function SlaveModel() {
Master.apply(this, [].slice.call(arguments));
this.schema = schema;
this.dataSource = dataSource;
};
util.inherits(Slave, Master);
Slave.__proto__ = Master;
hiddenProperty(Slave, 'schema', schema);
hiddenProperty(Slave, 'dataSource', dataSource);
hiddenProperty(Slave, 'modelName', className);
hiddenProperty(Slave, 'relations', Master.relations);
if (!(className in schema.models)) {
if (!(className in dataSource.models)) {
// store class in model pool
schema.models[className] = Slave;
schema.definitions[className] = {
dataSource.models[className] = Slave;
dataSource.definitions[className] = {
properties: md.properties,
settings: md.settings
};
if ((!schema.isTransaction) && schema.adapter && schema.adapter.define) {
schema.adapter.define({
if ((!dataSource.isTransaction) && dataSource.connector && dataSource.connector.define) {
dataSource.connector.define({
model: Slave,
properties: md.properties,
settings: md.settings
@ -1183,28 +1177,28 @@ DataSource.prototype.copyModel = function copyModel(Master) {
};
DataSource.prototype.transaction = function() {
var schema = this;
var dataSource = this;
var transaction = new EventEmitter;
transaction.isTransaction = true;
transaction.origin = schema;
transaction.name = schema.name;
transaction.settings = schema.settings;
transaction.origin = dataSource;
transaction.name = dataSource.name;
transaction.settings = dataSource.settings;
transaction.connected = false;
transaction.connecting = false;
transaction.adapter = schema.adapter.transaction();
transaction.connector = dataSource.connector.transaction();
// create blank models pool
transaction.models = {};
transaction.definitions = {};
for (var i in schema.models) {
schema.copyModel.call(transaction, schema.models[i]);
for (var i in dataSource.models) {
dataSource.copyModel.call(transaction, dataSource.models[i]);
}
transaction.connect = schema.connect;
transaction.connect = dataSource.connect;
transaction.exec = function(cb) {
transaction.adapter.exec(cb);
transaction.connector.exec(cb);
};
return transaction;
@ -1272,7 +1266,7 @@ DataSource.prototype.defineOperation = function (name, options, fn) {
}
DataSource.prototype.isRelational = function() {
return this.adapter && this.adapter.relational;
return this.connector && this.connector.relational;
}
/**

View File

@ -5,7 +5,7 @@
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) {

View File

@ -76,7 +76,7 @@ util.inherits(ModelBuilder, EventEmitter);
*
* @example simple case
* ```
* var User = schema.define('User', {
* var User = dataSource.define('User', {
* email: String,
* password: String,
* birthDate: Date,
@ -85,7 +85,7 @@ util.inherits(ModelBuilder, EventEmitter);
* ```
* @example more advanced case
* ```
* var User = schema.define('User', {
* var User = dataSource.define('User', {
* email: { type: String, limit: 150, index: true },
* password: { type: String, limit: 50 },
* birthDate: Date,
@ -95,7 +95,7 @@ util.inherits(ModelBuilder, EventEmitter);
* ```
*/
ModelBuilder.prototype.define = function defineClass(className, properties, settings, parent) {
var schema = this;
var dataSource = this;
var args = slice.call(arguments);
var pluralName = settings && settings.plural;
var ModelBaseClass = parent || require('./model.js');
@ -110,13 +110,13 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
this.buildSchema(className, properties);
// 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)) {
return new ModelConstructor(data, schema);
return new ModelConstructor(data, dataSource);
}
ModelBaseClass.apply(this, arguments);
if(!this.schema) {
hiddenProperty(this, 'schema', schema || this.constructor.schema);
if(!this.dataSource) {
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.setMaxListeners = events.setMaxListeners.bind(events);
hiddenProperty(ModelClass, 'schema', schema);
hiddenProperty(ModelClass, 'dataSource', dataSource);
hiddenProperty(ModelClass, 'modelName', className);
hiddenProperty(ModelClass, 'pluralModelName', pluralName || i8n.pluralize(className));
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') {
c.setup.call(c);
@ -236,7 +236,7 @@ ModelBuilder.prototype.define = function defineClass(className, properties, sett
return s;
};
} else if(typeof DataType === 'string') {
DataType = schema.getSchemaType(DataType);
DataType = dataSource.getSchemaType(DataType);
}
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', 'isExpired', { type: Boolean, index: true });
*
* // schema.extend allows to
* // dataSource.extend allows to
* // extend the content model with competition attributes
* db.extendModel('Content', {
* competitionType: String,
@ -357,27 +357,27 @@ ModelBuilder.prototype.extendModel = function (model, props) {
ModelBuilder.prototype.copyModel = function copyModel(Master) {
var schema = this;
var dataSource = this;
var className = Master.modelName;
var md = Master.schema.definitions[className];
var md = Master.dataSource.definitions[className];
var Slave = function SlaveModel() {
Master.apply(this, [].slice.call(arguments));
this.schema = schema;
this.dataSource = dataSource;
};
util.inherits(Slave, Master);
Slave.__proto__ = Master;
hiddenProperty(Slave, 'schema', schema);
hiddenProperty(Slave, 'dataSource', dataSource);
hiddenProperty(Slave, 'modelName', className);
hiddenProperty(Slave, 'relations', Master.relations);
if (!(className in schema.models)) {
if (!(className in dataSource.models)) {
// store class in model pool
schema.models[className] = Slave;
schema.definitions[className] = {
dataSource.models[className] = Slave;
dataSource.definitions[className] = {
properties: md.properties,
settings: md.settings
};
@ -461,9 +461,9 @@ ModelBuilder.prototype.getSchemaType = function(type) {
}
/**
* Build a schema
* @param name The name of the schema
* @param properties The properties of the schema
* Build a dataSource
* @param name The name of the dataSource
* @param properties The properties of the dataSource
* @param associations An array of associations between models
* @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:
* 1. An array of named schema definition JSON objects
* 2. A schema definition JSON object
* 1. An array of named dataSource definition JSON objects
* 2. A dataSource definition JSON object
* 3. A list of property definitions (anonymous)
* @returns {Object} A map of model constructors keyed by model name
*/
@ -514,7 +514,7 @@ ModelBuilder.prototype.buildModels = function (schemas) {
// Only one item
schemas = [schemas];
} else {
// Anonymous schema
// Anonymous dataSource
schemas = [
{
name: 'Anonymous',
@ -526,8 +526,8 @@ ModelBuilder.prototype.buildModels = function (schemas) {
var associations = [];
for (var s in schemas) {
var name = schemas[s].name;
var schema = this.buildSchema(name, schemas[s].properties, associations);
var model = this.define(name, schema, schemas[s].options);
var dataSource = this.buildSchema(name, schemas[s].properties, associations);
var model = this.define(name, dataSource, schemas[s].options);
models[name] = model;
}

View File

@ -17,9 +17,9 @@ var BASE_TYPES = ['String', 'Boolean', 'Number', 'Date', 'Text'];
/**
* 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`
* to learn more about specific adapter implementations
* to learn more about specific connector implementations
*
* `ModelBaseClass` mixes `Validatable` and `Hookable` classes methods
*
@ -132,7 +132,7 @@ ModelBaseClass.prototype._initProperties = function (data, applySetters) {
* @param {Object} params - various property configuration
*/
ModelBaseClass.defineProperty = function (prop, params) {
this.schema.defineProperty(this.modelName, prop, params);
this.dataSource.defineProperty(this.modelName, prop, params);
};
ModelBaseClass.whatTypeName = function (propName) {
@ -159,14 +159,14 @@ ModelBaseClass.toString = function () {
/**
* Convert instance to Object
*
* @param {Boolean} onlySchema - restrict properties to schema only, default false
* when onlySchema == true, only properties defined in schema returned,
* @param {Boolean} onlySchema - restrict properties to dataSource only, default false
* when onlySchema == true, only properties defined in dataSource returned,
* otherwise all enumerable properties returned
* @returns {Object} - canonical object representation (no getters and setters)
*/
ModelBaseClass.prototype.toObject = function (onlySchema) {
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 self = this;
@ -229,7 +229,7 @@ ModelBaseClass.prototype.propertyChanged = function propertyChanged(attr) {
ModelBaseClass.prototype.reset = function () {
var obj = this;
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];
}
if (obj.propertyChanged(k)) {

View File

@ -34,9 +34,9 @@ Relation.hasMany = function hasMany(anotherClass, params) {
anotherClass = params.model;
} else {
var anotherClassName = i8n.singularize(anotherClass).toLowerCase();
for(var name in this.schema.models) {
for(var name in this.dataSource.models) {
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) {
// 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) {
@ -184,9 +184,9 @@ Relation.belongsTo = function (anotherClass, params) {
anotherClass = params.model;
} else {
var anotherClassName = anotherClass.toLowerCase();
for(var name in this.schema.models) {
for(var name in this.dataSource.models) {
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
};
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__'][methodName] = function (id, cb) {
@ -266,7 +266,7 @@ Relation.belongsTo = function (anotherClass, params) {
*/
Relation.hasAndBelongsToMany = function hasAndBelongsToMany(anotherClass, params) {
params = params || {};
var models = this.schema.models;
var models = this.dataSource.models;
if ('string' === typeof anotherClass) {
params.as = anotherClass;
@ -285,7 +285,7 @@ Relation.hasAndBelongsToMany = function hasAndBelongsToMany(anotherClass, params
var name1 = this.modelName + anotherClass.modelName;
var name2 = anotherClass.modelName + this.modelName;
params.through = lookupModel(name1) || lookupModel(name2) ||
this.schema.define(name1);
this.dataSource.define(name1);
}
params.through.belongsTo(this);
params.through.belongsTo(anotherClass);

View File

@ -9,7 +9,7 @@ function BaseSQL() {
BaseSQL.prototype.relational = true;
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) {
@ -33,7 +33,7 @@ BaseSQL.prototype.dataSource = function(model) {
if(!m) {
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
*/
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');
};
/**

View File

@ -15,29 +15,29 @@ function skip(name) {
delete batch[schemaName][name];
}
module.exports = function testSchema(exportCasesHere, schema) {
module.exports = function testSchema(exportCasesHere, dataSource) {
batch = exportCasesHere;
schemaName = schema.name;
if (schema.name.match(/^\/.*\/test\/\.\.$/)) {
schemaName = dataSource.name;
if (dataSource.name.match(/^\/.*\/test\/\.\.$/)) {
schemaName = schemaName.split('/').slice(-3).shift();
}
var start;
batch['should connect to database'] = function (test) {
start = Date.now();
if (schema.connected) return test.done();
schema.on('connected', test.done);
if (dataSource.connected) return test.done();
dataSource.on('connected', test.done);
};
schema.log = function (a) {
dataSource.log = function (a) {
console.log(a);
nbSchemaRequests++;
};
batch[schemaName] = {};
testOrm(schema);
testOrm(dataSource);
batch['all tests done'] = function (test) {
test.done();
@ -45,7 +45,7 @@ module.exports = function testSchema(exportCasesHere, schema) {
};
function allTestsDone() {
schema.disconnect();
dataSource.disconnect();
console.log('Test done in %dms\n', Date.now() - start);
}
@ -85,14 +85,14 @@ function clearAndCreate(model, data, callback) {
}
}
function testOrm(schema) {
var requestsAreCounted = schema.name !== 'mongodb';
function testOrm(dataSource) {
var requestsAreCounted = dataSource.name !== 'mongodb';
var Post, User, Passport, Log, Dog;
it('should define class', function (test) {
User = schema.define('User', {
User = dataSource.define('User', {
name: { type: String, index: true },
email: { type: String, index: true },
bio: Text,
@ -102,18 +102,18 @@ function testOrm(schema) {
passwd: { type: String, index: true }
});
Dog = schema.define('Dog', {
Dog = dataSource.define('Dog', {
name : { type: String, limit: 64, allowNull: false }
});
Log = schema.define('Log', {
Log = dataSource.define('Log', {
ownerId : { type: Number, allowNull: true },
name : { type: String, limit: 64, allowNull: false }
});
Log.belongsTo(Dog, {as: 'owner', foreignKey: 'ownerId'});
schema.extendModel('User', {
dataSource.extendModel('User', {
settings: { type: Schema.JSON },
extra: Object
});
@ -121,7 +121,7 @@ function testOrm(schema) {
var newuser = new User({settings: {hey: 'you'}});
test.ok(newuser.settings);
Post = schema.define('Post', {
Post = dataSource.define('Post', {
title: { type: String, length: 255, index: true },
subject: { type: String },
content: { type: Text },
@ -161,7 +161,7 @@ function testOrm(schema) {
// post.author() -- sync getter when called without params
// post.author(user) -- setter when called with object
Passport = schema.define('Passport', {
Passport = dataSource.define('Passport', {
number: String
});
@ -179,7 +179,7 @@ function testOrm(schema) {
// instance methods
test.ok(user.save instanceof Function);
schema.automigrate(function (err) {
dataSource.automigrate(function (err) {
if (err) {
console.log('Error while migrating');
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) {
test.ok(!post.nonSchemaField);
post.a = 1;
@ -395,10 +395,10 @@ function testOrm(schema) {
});
if (
!schema.name.match(/redis/) &&
schema.name !== 'memory' &&
schema.name !== 'neo4j' &&
schema.name !== 'cradle'
!dataSource.name.match(/redis/) &&
dataSource.name !== 'memory' &&
dataSource.name !== 'neo4j' &&
dataSource.name !== 'cradle'
)
it('relations key is working', function (test) {
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.');
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();
} else {
user.posts({where: {id: data[0].id}}, function(err, data) {
@ -594,7 +594,7 @@ function testOrm(schema) {
{ title: 'Title A', subject: "A" },
{ title: 'Title B', subject: "A" },
{ 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 ] : [
new Date(1000 * 5 ),
new Date(1000 * 9),
@ -615,7 +615,7 @@ function testOrm(schema) {
doStringTest();
doNumberTest();
if (schema.name == 'mongoose') {
if (dataSource.name == 'mongoose') {
doMultipleSortTest();
doMultipleReverseSortTest();
}
@ -628,7 +628,7 @@ function testOrm(schema) {
return 0;
}
// Post.schema.log = console.log;
// Post.dataSource.log = console.log;
function doStringTest() {
tests += 1;
@ -728,11 +728,11 @@ function testOrm(schema) {
});
// if (
// !schema.name.match(/redis/) &&
// schema.name !== 'memory' &&
// schema.name !== 'neo4j' &&
// schema.name !== 'cradle' &&
// schema.name !== 'nano'
// !dataSource.name.match(/redis/) &&
// dataSource.name !== 'memory' &&
// dataSource.name !== 'neo4j' &&
// dataSource.name !== 'cradle' &&
// dataSource.name !== 'nano'
// )
// it('should allow advanced queying: lt, gt, lte, gte, between', function (test) {
// Post.destroyAll(function () {
@ -792,8 +792,8 @@ function testOrm(schema) {
// if (
// schema.name === 'mysql' ||
// schema.name === 'postgres'
// dataSource.name === 'mysql' ||
// dataSource.name === 'postgres'
// )
// it('should allow IN or NOT IN', function (test) {
// User.destroyAll(function () {
@ -962,11 +962,11 @@ function testOrm(schema) {
});
// if (
// !schema.name.match(/redis/) &&
// schema.name !== 'memory' &&
// schema.name !== 'neo4j' &&
// schema.name !== 'cradle' &&
// schema.name !== 'nano'
// !dataSource.name.match(/redis/) &&
// dataSource.name !== 'memory' &&
// dataSource.name !== 'neo4j' &&
// dataSource.name !== 'cradle' &&
// dataSource.name !== 'nano'
// )
// it('belongsTo should be cached', function (test) {
// 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) {
var newData = {
id: 1,
@ -1022,7 +1022,7 @@ function testOrm(schema) {
test.ok(updatedPost);
if (!updatedPost) throw Error('No post!');
if (schema.name !== 'mongodb') {
if (dataSource.name !== 'mongodb') {
test.equal(newData.id, updatedPost.toObject().id);
}
test.equal(newData.title, updatedPost.toObject().title);
@ -1031,13 +1031,13 @@ function testOrm(schema) {
Post.findById(updatedPost.id, function (err, post) {
if (err) throw err;
if (!post) throw Error('No post!');
if (schema.name !== 'mongodb') {
if (dataSource.name !== 'mongodb') {
test.equal(newData.id, post.toObject().id);
}
test.equal(newData.title, post.toObject().title);
test.equal(newData.content, post.toObject().content);
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');
Post.findById(post.id, function (err, post) {
if (!post) throw Error('No post!');
@ -1049,7 +1049,7 @@ function testOrm(schema) {
});
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) {
this._passwd = pass + 'salt';
};

View File

@ -75,8 +75,8 @@ describe('hooks', function() {
});
it('afterCreate should not be triggered on failed create', function(done) {
var old = User.schema.adapter.create;
User.schema.adapter.create = function(modelName, id, cb) {
var old = User.dataSource.connector.create;
User.dataSource.connector.create = function(modelName, id, cb) {
cb(new Error('error'));
}
@ -84,7 +84,7 @@ describe('hooks', function() {
throw new Error('shouldn\'t be called')
};
User.create(function (err, user) {
User.schema.adapter.create = old;
User.dataSource.connector.create = old;
done();
});
});
@ -224,9 +224,9 @@ describe('hooks', function() {
should.fail('afterUpdate shouldn\'t be called')
};
User.create(function (err, user) {
var save = User.schema.adapter.save;
User.schema.adapter.save = function(modelName, id, cb) {
User.schema.adapter.save = save;
var save = User.dataSource.connector.save;
User.dataSource.connector.save = function(modelName, id, cb) {
User.dataSource.connector.save = save;
cb(new Error('Error'));
}
@ -257,8 +257,8 @@ describe('hooks', function() {
});
it('should not trigger after-hook on failed destroy', function(done) {
var destroy = User.schema.adapter.destroy;
User.schema.adapter.destroy = function(modelName, id, cb) {
var destroy = User.dataSource.connector.destroy;
User.dataSource.connector.destroy = function(modelName, id, cb) {
cb(new Error('error'));
}
User.afterDestroy = function() {
@ -266,7 +266,7 @@ describe('hooks', function() {
};
User.create(function (err, user) {
user.destroy(function(err) {
User.schema.adapter.destroy = destroy;
User.dataSource.connector.destroy = destroy;
done();
});
});

View File

@ -4,11 +4,11 @@ var should = require('./init.js');
var Schema = require('../').Schema;
describe('JSON property', function() {
var schema, Model;
var dataSource, Model;
it('should be defined', function() {
schema = getSchema();
Model = schema.define('Model', {propertyName: Schema.JSON});
dataSource = getSchema();
Model = dataSource.define('Model', {propertyName: Schema.JSON});
var m = new Model;
(new Boolean('propertyName' in m)).should.eql(true);
should.not.exist(m.propertyName);

View File

@ -218,7 +218,7 @@ describe('Load models from json', function () {
/**
* 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
*/
function loadSchemasSync(schemaFile, dataSource) {
@ -227,7 +227,7 @@ describe('Load models from json', function () {
dataSource = new DataSource('memory');
}
// Read the schema JSON file
// Read the dataSource JSON file
var schemas = JSON.parse(fs.readFileSync(schemaFile));
return dataSource.buildModels(schemas);

View File

@ -14,7 +14,7 @@ schemas =
nano:
url: 'http://localhost:5984/nano-test'
testOrm = (schema) ->
testOrm = (dataSource) ->
User = Post = 'unknown'
maxUsers = 100
@ -23,7 +23,7 @@ testOrm = (schema) ->
it 'should define simple', (test) ->
User = schema.define 'User', {
User = dataSource.define 'User', {
name: String,
bio: Text,
approved: Boolean,
@ -31,7 +31,7 @@ testOrm = (schema) ->
age: Number
}
Post = schema.define 'Post',
Post = dataSource.define 'Post',
title: { type: String, length: 255, index: true }
content: { type: Text }
date: { type: Date, detault: Date.now }
@ -78,6 +78,6 @@ testOrm = (schema) ->
Object.keys(schemas).forEach (schemaName) ->
return if process.env.ONLY && process.env.ONLY != schemaName
context schemaName, ->
schema = new Schema schemaName, schemas[schemaName]
testOrm(schema)
dataSource = new Schema schemaName, schemas[schemaName]
testOrm(dataSource)

View File

@ -3,23 +3,23 @@ var should = require('./init.js');
var db = getSchema(), slave = getSchema(), Model, SlaveModel;
describe('schema', function() {
describe('dataSource', function() {
it('should define Model', function() {
Model = db.define('Model');
Model.schema.should.eql(db);
Model.dataSource.should.eql(db);
var m = new Model;
m.schema.should.eql(db);
m.dataSource.should.eql(db);
});
it('should clone existing model', function() {
SlaveModel = slave.copyModel(Model);
SlaveModel.schema.should.eql(slave);
SlaveModel.dataSource.should.eql(slave);
slave.should.not.eql(db);
var sm = new SlaveModel;
sm.should.be.instanceOf(Model);
sm.schema.should.not.eql(db);
sm.schema.should.eql(slave);
sm.dataSource.should.not.eql(db);
sm.dataSource.should.eql(slave);
});
it('should automigrate', function(done) {