_update:function () { var ret = new comb.Promise(); this.dataset.filter(this._getPrimaryKeyQuery()).update(this.__changed) .chain(comb.hitch(this, "_updateReload"), comb.hitch(ret, "errback")) .then(comb.hitch(ret, "callback"), comb.hitch(ret, "errback")); return ret; },
run:function () { var ret = this.__runPromise; if (!ret) { if (sub) { level = level || 1; } else { level = null; } if (this.topic) { formatter.printTitle(this.topic, level); } var funcs = this.__ba.slice(); this.__shoulds.forEach(function (batch) { funcs = funcs.concat(this.__be); funcs.push(batch); funcs = funcs.concat(this.__ae); }, this); funcs = funcs.concat(this.__aa); var start = new Date(); var summaries = this.__summaries; ret = this.__runPromise = new comb.Promise(); comb.serial(funcs).then(comb.hitch(this, function () { var duration = new Date() - start; this._processSummary({summaries:summaries, duration:duration}, ret, "callback"); }), comb.hitch(this, function (err) { this.__run = true; var duration = new Date() - start; formatter.printError("Top level error", 1, err); this._processSummary({summaries:summaries, duration:duration}, ret, "callback"); })); } return ret.promise(); }
this._remove().then(comb.hitch(this, function () { this._hook("post", "remove").then(comb.hitch(this, function () { this._clearPrimaryKeys(); this.__isNew = true; ret.callback(this); }), comb.hitch(ret, "errback")); }), comb.hitch(ret, "errback"));
findOrCreate:function (q) { var ret = new comb.Promise() this.find(q).then(comb.hitch(this, function (res) { ret.callback(res || this.create()); }), comb.hitch(ret, "errback")); return ret; },
init:function () { this.oneToMany("legs", { model:"flightLeg", orderBy:"scheduledDepartureTime", fetchType:this.fetchType.EAGER }); this.addRoute("/flights/:airline", comb.hitch(this, function (params) { var ret = new comb.Promise(); this.byAirline(params.airline).then(function (flights) { ret.callback(flights.map(function (flight) { return flight.toObject(); })); }, comb.hitch(ret, "errback")); return ret; })); this.addRoute("/flights/departs/:airportCode", comb.hitch(this, function (params) { var ret = new comb.Promise(); this.departsFrom(params.airportCode).then(function (flights) { ret.callback(flights.map(function (flight) { return flight.toObject(); })); }, comb.hitch(ret, "errback")); return ret; })); this.addRoute("/flights/arrives/:airportCode", comb.hitch(this, function (params) { var ret = new comb.Promise(); this.arrivesAt(params.airportCode).then(function (flights) { ret.callback(flights.map(function (flight) { return flight.toObject(); })); }, comb.hitch(ret, "errback")); return ret; })); },
exports.loadModels = function() { var ret = new comb.Promise(); var options = { connection : {user : "******", password : "******", database : 'test'}, dir : "./data/migrations/model", start : 0, up : true }; moose.migrate(options) .chain(comb.hitch(moose, "loadSchema", "employee"), comb.hitch(ret, "errback")) .then(function(employee) { var Employee = moose.addModel(employee, { static : { //class methods findByGender : function(gender, callback, errback) { this.filter({gender : gender}).all(callback, errback); } }, instance : {} //instance methods }); ret.callback(); }, comb.hitch(console, "log")); return ret; };
var next = comb.hitch(this, function(res, err) { //reset my browser so I can get another. this.__browser = null; if (res) { !responses && (responses = {}); //if i have a response record it! responses[keys[count - 1]] = res; } if (err) { !errors && (errors = {}); errors[keys[count - 1]] = err; } if (count == length) { //looped through all my tests so callback promise.callback(responses, errors); } else if (count < length) { //call the next test! var key = keys[count++], file = testFiles[key], p; if (typeof file == "object") { this.__runTests(file).then(next); } else { if (this.logCommands) { logger.info(string.style("RUNNING: ", ["green", "bold", "underline"]) + string.style(key, ["yellow"])); } runTests(this.sodaClient, file, this.baseUrl, this.timeout).then(comb.hitch(this, next), comb.hitch(this, next, null)); } } });
var insertTable = comb.hitch(this, function (index) { if (index < tables.length) { var table = tables[index]; var isRestricted = this._static.isRestrictedPrimaryKey; var cols = ctiColumns[table], insert = {}; cols.forEach(function (c) { var val; if ((index != 0 || (index == 0 && (!isRestricted || pk.indexOf(c) == -1))) && !comb.isUndefined(val = this[c])) { insert[c] = val; } }, this); this.db.from(table).insert(insert).then(comb.hitch(this, function (id) { if (comb.isUndefined(this.primaryKeyValue) && !comb.isUndefined(id) && index == 0) { this.__ignore = true; //how to handle composite keys. this[pk] = id; this.__ignore = false; } insertTable(++index) }), comb.hitch(ret, "errback")); } else { this.__isNew = false; this.__isChanged = false; this._saveReload().then(comb.hitch(this, function () { ret.callback(this); }), comb.hitch(ret, "errback")); } });
exports.loadModels = function() { var ret = new comb.Promise(); var options = { connection : {user : "******", password : "******", database : 'test'}, dir : "./data/migrations/manyToOne", start : 0, up : true }; moose.migrate(options) .chain(comb.hitch(moose, "loadSchemas", ["company", "employee"]), comb.hitch(ret, "errback")) .then(function(company, employee) { var Company = moose.addModel(company); var Employee = moose.addModel(employee); //define associations Employee.manyToOne("company", {model : Company.tableName, key : {companyId : "id"}}); Company.oneToMany("employees", {model : Employee.tableName, orderBy : {id : "desc"}, key : {id : "companyId"}}); Company.oneToMany("omahaEmployees", { model : Employee.tableName, filter : function() { return Employee.filter({companyId : this.id, city : "Omaha"}).order("lastName"); } }); ret.callback(); }, comb.hitch(console, "log")); return ret; };
routes: function () { if (comb.isUndefined(this.__routes)) { var routes = this.__routes = [ ["get", "/" + this.tableName + "/:id", comb.hitch(this, "findByIdRoute")], ["delete", "/" + this.tableName + "/:id", comb.hitch(this, "removeByIdRoute")] ]; } return this.__routes; }
restart:function () { comb.serial([ hitch(this, "_hook", "pre", "restartService"), comb.hitch(this, "stop"), comb.hitch(this, "start"), hitch(this, "_hook", "post", "restartService") ]).addErrback(this.errorHandler.bind(this)); ; },
topic : function() { var options = { connection : {user : "******", password : "******", database : 'test'}, dir : "./data/migrations/migrations", start : 1, end : 1, up : true }; moose.migrate(options).then(comb.hitch(this, "callback", null), comb.hitch(this, "callback")); },
return this._checkTransaction(options, comb.hitch(this, function () { comb.isHash(vals) && this.__set(vals); var ret = new comb.Promise(); this._hook("pre", "save") .chain(comb.hitch(this, "_save"), comb.hitch(ret, "errback")).then(comb.hitch(this, function () { this._hook("post", "save").then(comb.hitch(ret, "callback", this), comb.hitch(ret, "errback")); }), comb.hitch(ret, "errback")); return ret; }));
it.should("convert dates", function () { var date = new Date(2004, 1, 1, 0, 0, 0); assert.deepEqual(patio.stringToDate('2004-02-01'), date); patio.dateFormat = patio.TWO_YEAR_DATE_FORMAT; assert.deepEqual(patio.stringToDate('04-02-01'), date); patio.dateFormat = patio.DEFAULT_DATE_FORMAT; assert.throws(comb.hitch(patio, "stringToDate", "2004-12--2")); assert.throws(comb.hitch(patio, "stringToDate", "a")); assert.throws(comb.hitch(patio, "stringToDate", "2004-25-2")); });
helper.createTables().then(function () { patio.import(__dirname + "/models").chain(function () { var Airport = patio.getModel("airport"), AirplaneType = patio.getModel("airplaneType"), Flight = patio.getModel("flight"); return comb.when( Airport.save(data.airports), AirplaneType.save(data.airplaneTypes), Flight.save(data.flights) ); }, comb.hitch(ret, "errback")) .then(comb.hitch(ret, "callback"), comb.hitch(ret, "errback")); }, comb.hitch(ret, "errback"));
exports.dropModels = function() { var ret = new comb.Promise(); var options = { connection : {user : "******", password : "******", database : 'test'}, dir : "./data/migrations/manyToOne", start : 0, up : false }; moose.migrate(options).chain(comb.hitch(moose, "closeConnection"), comb.hitch(ret, "errback")).then(comb.hitch(ret, "callback"), comb.hitch(ret, "errback")); return ret; };
var loadModels = function() { var ret = new comb.Promise(); moose.migrate(options) .chain(comb.hitch(moose, "loadSchema", "employee"), comb.hitch(ret, "errback")) .then(function(employee) { var Employee = moose.addModel(employee); ret.callback(); }, comb.hitch(console, "log")); return ret; };
this.dataset.insert(this._toObject()).then(comb.hitch(this, function (id) { this.__ignore = true; if (id) { this[pk] = id; } this.__ignore = false; this.__isNew = false; this.__isChanged = false; this._saveReload().then(comb.hitch(this, function () { ret.callback(this); }), comb.hitch(ret, "errback")); }), comb.hitch(ret, "errback"));
it.should("support renaming tables", function () { return comb.hitch(db, "createTable", "posts1")(function () { this.primaryKey("a"); }) .chain(comb.hitch(db, "renameTable", "posts1", "posts")) .chain(function () { assert.deepEqual(db.sqls, [ "CREATE TABLE posts_1 (a serial PRIMARY KEY)", "ALTER TABLE posts_1 RENAME TO posts" ]); }); });
topic:function(){ DB.reset(); var ret = []; patio.migrate(DB, __dirname + "/migrations/files/basic_integer_migration", {target:4, current:2}) .addCallback(comb.hitch(ret, "push")) .chain(comb.hitch(patio, "migrate", DB, __dirname + "/migrations/files/basic_integer_migration", {target:-1}), hitch(this, "callback")) .addCallback(comb.hitch(ret, "push")) .chain(comb.hitch(patio, "migrate", DB, __dirname + "/migrations/files/basic_integer_migration"), hitch(this, "callback")) .addCallback(comb.hitch(ret, "push")) .then(hitch(this, "callback", null, ret), hitch(this, "callback")); },
return this._checkTransaction(options, comb.hitch(this, function () { var ret = new Promise(); this._hook("pre", "remove").then(comb.hitch(this, function () { this._remove().then(comb.hitch(this, function () { this._hook("post", "remove").then(comb.hitch(this, function () { this._clearPrimaryKeys(); this.__isNew = true; ret.callback(this); }), comb.hitch(ret, "errback")); }), comb.hitch(ret, "errback")); }), comb.hitch(ret, "errback")); return ret; }));
"throw an error if the table/table alias has already been used":function () { assert.throws(comb.hitch(ds1, "graph", ds1, {x:"id"})); assert.doesNotThrow(comb.hitch(ds1, "graph", ds2, {x:"id"})); assert.throws(function () { ds1.graph(ds2, {x:"id"}).then(function (d) { d.graph(ds2, {x:"id"}); }) }); assert.doesNotThrow(function () { ds1.graph(ds2, {x:"id"}).then(function (d) { d.graph(ds2, {x:"id"}, {tableAlias:"blah"}); }) }) },
constructor : function(options) { options = options || {}; //create a tree for times so we can quickly find values less //than a specified time this.__timeTree = new comb.collections.AVLTree({ compare : function(a, b) { var ret = 0; if (a.expires < b.expires) { ret = -1; } else if (a.expires > b.expires) { ret = 1; } return ret; } }); //use a tree so we can have complex keys later //otherwise we are limited to just strings //also this performs great on look up! //Also allows quick lookups on multiple values var cmp = options.compare ? options.compare : function(a, b) { var ret = 0; if (a < b) { ret = -1; } else if (a > b) { ret = 1; } return ret; } this.__values = new comb.collections.AVLTree({ compare : function(a, b) { return cmp(a.key, b.key); } }); this.__cleanupInterval = setInterval(comb.hitch(this, this._checkValues), this.__checkInterval); },
var createTables = function () { return comb.serial([ function () { return DB.forceDropTable("child", "stepFather", "biologicalFather"); }, function () { return comb.when( DB.createTable("biologicalFather", function () { this.primaryKey("id"); this.name(String); }), DB.createTable("stepFather", function () { this.primaryKey("id"); this.name(String, {unique:true}); }) ); }, function () { return DB.createTable("child", function () { this.primaryKey("id"); this.name(String); this.foreignKey("biologicalFatherId", "biologicalFather", {key:"id"}); this.foreignKey("stepFatherId", "stepFather", {key:"name", type:String}); }); }, comb.hitch(patio, "syncModels") ]); };
topic:function(){ TSDB.reset(); var ret = []; patio.migrate(TSDB, __dirname + "/migrations/files/basic_integer_migration") .chain(comb.hitch(patio, "migrate", TSDB, __dirname + "/migrations/files/both_migration"), hitch(this, "callback", null)) .then(hitch(this, "callback"), hitch(this, "callback", null)); },
removeItem:function (item, model, remove, reload) { reload = comb.isBoolean(reload) ? reload : false; remove = comb.isBoolean(remove) ? remove : false; var ret = new comb.Promise().callback(model); if (!comb.isUndefinedOrNull(item)) { if (!model.isNew) { if (comb.isInstanceOf(item, this.model) && !item.isNew) { !remove && this._setAssociationKeys(model, item, null); var loaded = this.associationLoaded(model); return model._checkTransaction(comb.hitch(this, function () { return comb.executeInOrder(item, model, this, this.parent, function (item, model, self, parent) { item[remove ? "remove" : "save"](); if (loaded && reload) { return parent._reloadAssociationsForType(self.type, self.model, model); } return model; }); })); } } else { item = this._toModel(item); var items = this.getAssociation(model), index; if (!comb.isUndefinedOrNull(items) && (index = items.indexOf(item)) != -1) { items.splice(index, 1); } } } return ret; },
addAssociation:function (item, model, reload) { reload = comb.isBoolean(reload) ? reload : false; var ret = new comb.Promise().callback(model); if (!comb.isUndefinedOrNull(item)) { if (!model.isNew) { item = this._toModel(item); var loaded = this.associationLoaded(model); this._setAssociationKeys(model, item); var recip = this.model._findAssociation(this); if (recip) { recip[1].__setValue(item, model); } ret = model._checkTransaction(comb.hitch(this, function () { return comb.executeInOrder(item, model, this, this.parent, function (item, model, self, parent) { item.save(); if (loaded && reload) { return parent._reloadAssociationsForType(self.type, self.model, model); } else { return model; } }); })); } else { item = this._toModel(item); var items = this.getAssociation(model); if (comb.isUndefinedOrNull(items)) { this.__setValue(model, [item]); } else { items.push(item); } } } return ret; },
"should convert literals properly":function (ds) { assert.equal(ds.literal(sql.literal("(hello, world)")), "(hello, world)"); assert.equal(ds.literal("('hello', 'world')"), "'(''hello'', ''world'')'"); assert.equal(ds.literal("(hello, world)"), "'(hello, world)'"); assert.equal(ds.literal("hello, world"), "'hello, world'"); assert.equal(ds.literal('("hello", "world")'), "'(\"hello\", \"world\")'"); assert.equal(ds.literal("(\hello\, \world\)'"), "'(hello, world)'''"); assert.equal(ds.literal("\\'\\'"), "'\\\\''\\\\'''"); assert.strictEqual(ds.literal(1), "1"); assert.strictEqual(ds.literal(1.0), "1"); assert.strictEqual(ds.literal(1.01), "1.01"); assert.equal(ds.literal(sql.hello.lt(1)),'(hello < 1)'); assert.equal(ds.literal(sql.hello.gt(1)),'(hello > 1)'); assert.equal(ds.literal(sql.hello.lte(1)),'(hello <= 1)'); assert.equal(ds.literal(sql.hello.gte(1)),'(hello >= 1)'); assert.equal(ds.literal(sql.hello.like("test")),"(hello LIKE 'test')"); assert.equal(ds.literal(ds.from("test").order("name")),"(SELECT * FROM test ORDER BY name)"); assert.equal(ds.literal([1,2,3]),"(1, 2, 3)"); assert.equal(ds.literal([1,"2",3]),"(1, '2', 3)"); assert.equal(ds.literal([1,"\\'\\'",3]),"(1, '\\\\''\\\\''', 3)"); assert.equal(ds.literal(new sql.Year(2009)), '2009') assert.equal(ds.literal(new sql.TimeStamp(2009, 10, 10,10,10)), "'2009-11-10 10:10:00'"); assert.equal(ds.literal(new sql.DateTime(2009, 10, 10,10,10)), "'2009-11-10 10:10:00'"); assert.equal(ds.literal(new Date(2009,10,10)), "'2009-11-10'"); assert.equal(ds.literal(new sql.Time(11,10,10)), "'11:10:10'"); assert.equal(ds.literal(null), "NULL"); assert.equal(ds.literal(true), "'t'"); assert.equal(ds.literal(false), "'f'"); assert.equal(ds.literal({a : "b"}), "(a = 'b')"); assert.throws(comb.hitch(ds, "literal", /a/)); }
var printResults = function (studentDs, classDs) { //print the results studentDs.forEach( function (student) { var classes = student.classes; console.log(format("%s %s is enrolled in %s", student.firstName, student.lastName, !classes.length ? " no classes!" : "\n\t-" + classes.map( function (clas) { return clas.name; }).join("\n\t-"))); }).chain(comb.hitch(classDs, "forEach", function (cls) { console.log(format('"%s" has the following students enrolled: \n\t-%s', cls.name, cls.students.map( function (student) { return format("%s %s", student.firstName, student.lastName); }).join("\n\t-"))); return comb.when(cls.aboveAverageStudents, cls.averageStudents, cls.belowAverageStudents, function (res) { var aboveAverage = res[0].map( function (student) { return format("%s %s", student.firstName, student.lastName); }).join("\n\t-"), average = res[1].map( function (student) { return format("%s %s", student.firstName, student.lastName); }).join("\n\t-"), belowAverage = res[2].map( function (student) { return format("%s %s", student.firstName, student.lastName); }).join("\n\t-"); console.log(format('"%s" has the following above average students enrolled: \n\t-%s', cls.name, aboveAverage)); console.log(format('"%s" has the following average students enrolled: \n\t-%s', cls.name, average)); console.log(format('"%s" has the following below average students enrolled: \n\t-%s', cls.name, belowAverage)); }); }), disconnectError).then(disconnect, disconnectError); };
connPromise.then(hitch(this, function (conn) { this.__beginTransaction(conn, opts).then(hitch(this, function () { this.__transactionProxy(cb, conn).then(hitch(this, function (res) { this.__commitTransaction(conn).then(comb.hitch(this, "__transactionComplete", promise, "callback", conn), comb.hitch(this, "__transactionComplete", promise, "errback", conn)); }), hitch(this, "__rollback", promise, conn)); }), comb.hitch(this, "__transactionComplete", promise, "errback", conn)); }), comb.hitch(this, "__transactionComplete", promise, "errback"));