Permalink
Browse files

added function construction

  • Loading branch information...
1 parent a11e923 commit 51bf71376cd233ff236e0f2399f33e7d6f425beb @chrisdew committed Nov 27, 2012
Showing with 46 additions and 9 deletions.
  1. +37 −9 lib/table.js
  2. +9 −0 test/table-test.js
View
@@ -3,6 +3,7 @@
var util = require('util');
var events = require('events');
var row = require('./row');
+var assert = require('assert');
exports.hello = hello;
exports.Table = Table;
@@ -77,6 +78,7 @@ Table.prototype.update = function(spec) {
for (var pk in this.rowsByPk) {
var r = this.rowsByPk[pk];
+ console.log("evaluate", r, evaluate(r));
if (evaluate(r)) {
count++;
r.update(spec.set);
@@ -87,17 +89,43 @@ Table.prototype.update = function(spec) {
function createFn(expr) {
console.log("createFn", expr);
+ if (typeof(expr) === "string") {
+ return function() {
+ return expr;
+ }
+ }
+ if (typeof(expr) === "number") {
+ return function() {
+ return expr;
+ }
+ }
+ if (expr.field) {
+ return function(r) {
+ return r[expr.field];
+ }
+ }
+
+ // by here we assume that it's a 2-arg function
+ assert(expr.fn);
+ assert(expr.args.length === 2);
+ var fn0 = createFn(expr.args[0]);
+ var fn1 = createFn(expr.args[1]);
if (expr.fn === 'equal') {
- return createEqual(expr.args);
+ return function(r) {
+ return fn0(r) === fn1(r);
+ }
}
-}
-
-function createEqual(args) {
- console.log("createEqual", args);
- if (args[0].field && (typeof args[1] === 'string' || typeof args[1] === 'number')) {
- return function(r) { return r[args[0].field] === args[1]; };
+ if (expr.fn === 'and') {
+ return function(r) {
+ return fn0(r) && fn1(r);
+ }
}
- if (args[1].field && (typeof args[0] === 'string' || typeof args[0] === 'number')) {
- return function(r) { return r[args[1].field] === args[0]; };
+ if (expr.fn === 'gt') {
+ return function(r) {
+ return fn0(r) > fn1(r);
+ }
}
+ throw "cannot handle " + JSON.stringify(expr);
}
+
+
View
@@ -67,5 +67,14 @@ describe('Table', function() {
bar.update({"table":"bar","set":[{"field":"foo","expr":"world"}],"where":{"expr":{"fn":"equal","args":[1, {field:"id"}]}}});
});
+ it('can handle a deeply nested where clause', function(done) {
+ bar.once('delta', function(delta) {
+ assert.deepEqual({"op":"update","table":"bar","pk":"1","set":[{"field":"foo","expr":"world2"}]}, delta);
+ done();
+ });
+ bar.update({"table":"bar","set":[{"field":"foo","expr":"world2"}],"where":{"expr":{"fn":"and","args":[{"fn":"equal","args":[{"field":"id"},1]},{"fn":"gt","args":[{"field":"id"},0]}]}}});
+ console.log(JSON.stringify(bar));
+ });
+
});

0 comments on commit 51bf713

Please sign in to comment.