Fix the on-demand connection

This commit is contained in:
Raymond Feng 2013-05-17 16:21:12 -07:00
parent 7caaeb2623
commit fca91e3400
3 changed files with 25 additions and 19 deletions

View File

@ -1,20 +1,6 @@
var DataSource = require('../../jugglingdb').DataSource; var DataSource = require('../../jugglingdb').DataSource;
var ds = new DataSource('memory'); var ds = new DataSource('memory');
var Article = ds.define('Article', {title: String});
var Tag = ds.define('Tag', {name: String});
Article.hasAndBelongsToMany('tags');
Article.create(function(e, article) {
article.tags.create({name: 'popular'}, function (err, data) {
Article.findOne(function(e, article) {
article.tags(function(e, tags) {
console.log(tags);
});
});
});
});
// define models // define models
var Post = ds.define('Post', { var Post = ds.define('Post', {
title: { type: String, length: 255 }, title: { type: String, length: 255 },
@ -91,8 +77,19 @@ User.create({name: 'Ray'}, function (err, data) {
console.log(data); console.log(data);
}); });
var count = 5; var Article = ds.define('Article', {title: String});
setInterval(function() {console.log(count--); if(!count) process.exit(0);}, 100); var Tag = ds.define('Tag', {name: String});
Article.hasAndBelongsToMany('tags');
Article.create(function(e, article) {
article.tags.create({name: 'popular'}, function (err, data) {
Article.findOne(function(e, article) {
article.tags(function(e, tags) {
console.log(tags);
});
});
});
});

View File

@ -150,13 +150,16 @@ DataAccessObject.create = function (data, callback) {
}; };
function stillConnecting(schema, obj, args) { function stillConnecting(schema, obj, args) {
if (schema.connected) return false; if (schema.connected) return false; // Connected
if (schema.connecting) return true;
var method = args.callee; var method = args.callee;
// Set up a callback after the connection is established to continue the method call
schema.once('connected', function () { schema.once('connected', function () {
method.apply(obj, [].slice.call(args)); method.apply(obj, [].slice.call(args));
}); });
if (!schema.connecting) {
schema.connect(); schema.connect();
}
return true; return true;
}; };

View File

@ -128,6 +128,12 @@ DataSource.prototype.setup = function(name, settings) {
schema.connect = function(cb) { schema.connect = function(cb) {
var schema = this; var schema = this;
if(schema.connected) {
if (cb) {
process.nextTick(cb);
}
return;
}
schema.connecting = true; schema.connecting = true;
if (schema.adapter.connect) { if (schema.adapter.connect) {
schema.adapter.connect(function(err) { schema.adapter.connect(function(err) {