Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

fixed tests and cleaned up some code into utils

  • Loading branch information...
commit dceb10d5358335559a80309716ba29dadddabb76 1 parent 1d115f4
@malkomalko malkomalko authored
View
2  .gitignore
@@ -1,2 +1,2 @@
.DS_Store
-.fastlegz
+.fastlegs
View
2  Makefile
@@ -5,7 +5,7 @@ node-command := xargs -n 1 -I file expresso file
test: setup test-unit test-integration
setup:
- @[ -e ".fastlegz" ] || node test/bootstrap/init.js
+ @[ -e ".fastlegs" ] || node test/bootstrap/init.js
test-unit:
@find test/unit -name "*_test.js" | $(node-command)
View
33 README.md
@@ -4,4 +4,35 @@ PostgreSQL ORM on top of node-postgres.
## Installation
- npm install FastLegS
+ npm install FastLegS
+
+## Quickstart
+
+ var FastLegS = require('FastLegS);
+
+ var connectionParams = {
+ user: 'shes'
+ , password: 'got'
+ , database: 'legs'
+ , host: 'localhost'
+ , port: 5432
+ }
+
+ FastLegS.connect(connectionParams);
+
+ var Post = FastLegS.Base.extend({
+ tableName: 'posts',
+ primaryKey: 'id'
+ });
+
+ Post.create({ title: 'Some Title 1', body: 'Some body 1' }, function(err, results) {
+ Post.find({ 'title.ilike': '%title%' }, { only: ['id', 'body'] }, function(err, post) {
+ // Hooray!
+ });
+ });
+
+#The Full Monty
+
+For the time being while we are writing up the most awesome README you've
+ever seen, why don't you try checking out our amazing tests for the full
+story.
View
34 lib/fast_legs/base.js
@@ -47,18 +47,22 @@ Base.prototype.find = function(selector, opts, callback) {
self.client.emit('query', selectStatement, function(err, result) {
var results = null;
- if (_(opts.include).isUndefined()) {
- if (_(selector).isArray())
- results = _.isUndefined(result) ? [] : result.rows;
- else if (_(selector).isNumber() || _(selector).isString())
- results = _.isUndefined(result.rows[0]) ? null : result.rows[0];
- else
- results = _.isUndefined(result) ? [] : result.rows;
-
- callback(err, results);
+ if (err && err.message === 'column "invalid" does not exist') {
+ callback(undefined, []);
} else {
- results = _.isUndefined(result) ? [] : result.rows;
- handleIncludes(self, results, selector, opts.include, callback);
+ if (_(opts.include).isUndefined()) {
+ if (_(selector).isArray())
+ results = _.isUndefined(result) ? [] : result.rows;
+ else if (_(selector).isNumber() || _(selector).isString())
+ results = _.isUndefined(result.rows[0]) ? null : result.rows[0];
+ else
+ results = _.isUndefined(result) ? [] : result.rows;
+
+ callback(err, results);
+ } else {
+ results = _.isUndefined(result) ? [] : result.rows;
+ handleIncludes(self, results, selector, opts.include, callback);
+ }
}
});
};
@@ -77,8 +81,12 @@ Base.prototype.destroy = function(selector, callback) {
var destroyStatement = Statements.destroy(self, selector);
self.client.emit('query', destroyStatement, function(err, results) {
- var deletedRows = _(results).isUndefined() ? 0 : results.rowCount;
- callback(err, deletedRows);
+ if (err && err.message === 'column "invalid" does not exist') {
+ callback(undefined, 0);
+ } else {
+ var deletedRows = _(results).isUndefined() ? 0 : results.rowCount;
+ callback(err, deletedRows);
+ }
});
}
View
2  lib/fast_legs/index.js
@@ -1,4 +1,4 @@
-exports.version = '0.0.1';
+exports.version = '0.0.2';
var _ = global._ = require('underscore')
, Base = require('./base')
View
122 lib/fast_legs/statements.js
@@ -1,3 +1,5 @@
+var utils = require('./utils');
+
exports.select = function(model, selector, opts) {
var fields = buildSelectFields(model, opts)
, stmt = "SELECT " + fields + " FROM " + model.tableName
@@ -52,29 +54,14 @@ exports.information = function(model) {
var buildInsertFields = function(model, fields) {
if (_(fields).isArray()) {
- var keys = _(fields).chain()
- .map(function(field) {
- return _(field).keys();
- })
- .flatten()
- .uniq()
- .value();
-
- var vals = _(fields).chain()
- .map(function(field) {
- var vals = _(keys).map(function(key) {
- return quote(field[key]);
- });
- return "(" + vals + ")";
- })
- .join(', ')
- .value();
+ var keys = utils.keysFromObject(fields)
+ , vals = buildMultiInsert(fields, keys);
return "(" + keys + ") VALUES " + vals;
} else {
- var fields = validFields(model, fields)
+ var fields = utils.validFields(model, fields)
, keys = _(fields).keys().join(',')
- , vals = toCsv(fields);
+ , vals = utils.toCsv(fields);
return "(" + keys + ") VALUES(" + vals + ") RETURNING *";
}
@@ -88,6 +75,18 @@ var buildLimitClause = function(opts) {
}
};
+var buildMultiInsert = function(fields, keys) {
+ return _(fields).chain()
+ .map(function(field) {
+ var vals = _(keys).map(function(key) {
+ return utils.quote(field[key]);
+ });
+ return "(" + vals + ")";
+ })
+ .join(', ')
+ .value();
+};
+
var buildOperator = function(key, value) {
var field = key.split('.')[0];
@@ -129,7 +128,7 @@ var buildOperator = function(key, value) {
var operator = "=";
}
- return field + ' ' + operator + ' ' + quote(value);
+ return field + ' ' + operator + ' ' + utils.quote(value);
};
var buildOrderClause = function(opts) {
@@ -163,99 +162,38 @@ var buildSelectFields = function(model, opts) {
};
var buildUpdateFields = function(model, fields) {
- var fields = validFields(model, fields)
+ var fields = utils.validFields(model, fields)
, pred = _(fields).chain()
.map(function(value, key) {
- return key + '=' + quote(value);
+ return key + '=' + utils.quote(value);
})
.join(', ')
.value();
- return nil(pred) ? '' : " SET " + pred;
+ return utils.nil(pred) ? '' : " SET " + pred;
};
var buildWhereClause = function(model, selector) {
- if (_(selector).isArray()) {
- var ids = toCsv(selector);
+ if (utils.nil(selector)) {
+ var pred = '';
+ } else if (_(selector).isArray()) {
+ var ids = utils.toCsv(selector);
var pred = model.primaryKey + " IN (" + ids + ")";
} else if (_(selector).isNumber() || _(selector).isString()) {
var id = selector;
var pred = model.primaryKey + " = '" + id + "'";
- } else if (nil(selector)){
- var pred = '';
} else {
var pred = _(selector).chain()
.map(function(value, key) {
- if (fieldIsValid(model, key))
+ if (utils.fieldIsValid(model, key))
return buildOperator(key, value);
})
.compact()
.join(' AND ')
.value();
- pred += nil(pred) ? 'INVALID' : '';
- }
-
- return nil(pred) ? '' : " WHERE " + pred;
-};
-
-var fieldIsValid = function(model, field) {
- var columns = _(model._fields).pluck('column_name');
- return _.include(columns, field.split('.')[0]);
-};
-
-var nil = function(value) {
- if (_(value).isUndefined() || _(value).isNull() || _(value).isNaN()) {
- return true;
- } else if (_(value).isArray() && _(value).isEmpty()) {
- return true;
- } else if (value.toString() === '[object Object]' && _(value).isEmpty()) {
- return true;
- } else if (_(value).isString() && _(value).isEmpty()) {
- return true;
- } else {
- return false;
- }
-};
-
-var quote = function(value) {
- if (nil(value)) {
- return "NULL";
- } else if (_(value).isNumber()) {
- return value;
- } else if (_(value).isArray()) {
- return "(" + toCsv(value) + ")";
- } else if (_(value).isDate()) {
- return "'" + toDateTime(value) + "'";
- } else {
- return "'" + value + "'";
+ pred += utils.nil(pred) ? 'INVALID' : '';
}
-};
-
-var toCsv = function(list, keys) {
- return _(list).chain()
- .values()
- .map(function(o) { return quote(o) })
- .join(',')
- .value();
-};
-
-var toDateTime = function(value) {
- if (_(value).isDate()) {
- return value.getFullYear()
- + '/' + (value.getMonth()+1)
- + '/' + (value.getDate())
- + ' ' + (value.getHours())
- + ':' + (value.getMinutes())
- + ':' + (value.getSeconds());
- }
-};
-var validFields = function(model, fields) {
- var returnFields = {};
- _(fields).each(function(value, key) {
- if (fieldIsValid(model, key)) {
- returnFields[key] = value;
- }
- });
- return returnFields;
+ return utils.nil(pred) ? '' : " WHERE " + pred;
+ // return where === ' WHERE INVALID' ? '' : where;
};
View
71 lib/fast_legs/utils.js
@@ -0,0 +1,71 @@
+var fieldIsValid = exports.fieldIsValid = function(model, field) {
+ var columns = _(model._fields).pluck('column_name');
+ return _.include(columns, field.split('.')[0]);
+};
+
+var keysFromObject = exports.keysFromObject = function(fields) {
+ return _(fields).chain()
+ .map(function(field) {
+ return _(field).keys();
+ })
+ .flatten()
+ .uniq()
+ .value();
+};
+
+var nil = exports.nil = function(value) {
+ if (_(value).isUndefined() || _(value).isNull() || _(value).isNaN()) {
+ return true;
+ } else if (_(value).isArray() && _(value).isEmpty()) {
+ return true;
+ } else if (value.toString() === '[object Object]' && _(value).isEmpty()) {
+ return true;
+ } else if (_(value).isString() && _(value).isEmpty()) {
+ return true;
+ } else {
+ return false;
+ }
+};
+
+var quote = exports.quote = function(value) {
+ if (nil(value)) {
+ return "NULL";
+ } else if (_(value).isNumber()) {
+ return value;
+ } else if (_(value).isArray()) {
+ return "(" + toCsv(value) + ")";
+ } else if (_(value).isDate()) {
+ return "'" + toDateTime(value) + "'";
+ } else {
+ return "'" + value + "'";
+ }
+};
+
+var toCsv = exports.toCsv = function(list, keys) {
+ return _(list).chain()
+ .values()
+ .map(function(o) { return quote(o) })
+ .join(',')
+ .value();
+};
+
+var toDateTime = exports.toDateTime = function(value) {
+ if (_(value).isDate()) {
+ return value.getFullYear()
+ + '/' + (value.getMonth()+1)
+ + '/' + (value.getDate())
+ + ' ' + (value.getHours())
+ + ':' + (value.getMinutes())
+ + ':' + (value.getSeconds());
+ }
+};
+
+var validFields = exports.validFields = function(model, fields) {
+ var returnFields = {};
+ _(fields).each(function(value, key) {
+ if (fieldIsValid(model, key)) {
+ returnFields[key] = value;
+ }
+ });
+ return returnFields;
+};
View
2  package.json
@@ -1,6 +1,6 @@
{
"name": "FastLegS",
- "version": "0.0.1",
+ "version": "0.0.2",
"description": "PostgreSQL ORM on top of node-postgres",
"tags" : ["orm", "pg", "postgres"],
"author": "Didit Tech <development@didit.com>",
View
2  test/bootstrap/init.js
@@ -66,7 +66,7 @@ async.series({
function(cb) { client.query(create.comments_post_id_index, cb); }
], function(err, results) {
if (!err) {
- fs.writeFile('.fastlegz',
+ fs.writeFile('.fastlegs',
JSON.stringify(config),
function (err) {
client.end();
View
20 test/integration/integration_test.js
@@ -4,7 +4,7 @@ var helper = require('../test_helper.js')
module.exports = {
'integrates': function() {
- var config = fs.readFileSync(__dirname + '/../../.fastlegz', 'utf8');
+ var config = fs.readFileSync(__dirname + '/../../.fastlegs', 'utf8');
config = JSON.parse(config);
var connParams = {
@@ -122,14 +122,14 @@ module.exports = {
callback(err, results);
});
},
- 'find: multiple records': function(callback) {
+ 'find: multiple comments by id': function(callback) {
var ids = _.pluck(comments, 'id');
Comment.find(ids, function(err, results) {
assert.eql(ids.length, results.length);
callback(err, results)
})
},
- 'find: ignores unknown columns': function(callback) {
+ 'find: properly ignores unknown columns': function(callback) {
Post.find({ 'body': 'Some body 2' }, {
only: ['id', 'bad_field']
}, function(err, results) {
@@ -153,25 +153,25 @@ module.exports = {
callback(err, results);
});
},
- 'destroy: model by primary key': function(callback) {
+ 'destroy: comment by primary key': function(callback) {
Comment.destroy(8, function(err, results) {
assert.eql(1, results);
callback(err, results);
});
},
- 'destroy: multiple records by primary key': function(callback) {
+ 'destroy: multiple comments by primary key': function(callback) {
Comment.destroy([7, 6], function(err, results) {
assert.eql(2, results);
callback(err, results);
});
},
- 'destroy: by a basic selector': function(callback) {
+ 'destroy: comment via a basic selector': function(callback) {
Comment.destroy({ 'comment':'Comment 5' }, function(err, results) {
assert.eql(1, results);
callback(err, results);
});
},
- 'destroy: all records for model': function(callback) {
+ 'destroy: all comments': function(callback) {
Comment.destroy(function(err, results) {
assert.eql(4, results);
callback(err, results);
@@ -209,14 +209,14 @@ module.exports = {
});
},
'find: nothing': function(callback) {
- Post.find(posts.id, function(err, result) {
+ Post.find(posts[0].id, function(err, result) {
assert.isNull(result);
callback(err, result);
});
},
- 'find: no clients with bad selector': function(callback) {
+ 'find: no posts with bad selector': function(callback) {
Post.find({ 'bad_field': 12 }, function(err, result) {
- assert.eql([1234], result);
+ assert.eql([], result);
callback(err, result);
});
}
Please sign in to comment.
Something went wrong with that request. Please try again.