Socket
Socket
Sign inDemoInstall

mapper

Package Overview
Dependencies
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mapper - npm Package Compare versions

Comparing version 0.2.3-pre to 0.2.4-pre

example/app.js

226

lib/client.js

@@ -5,3 +5,3 @@ /**

var mysql = require("mysql-libmysqlclient");
var mysql = require('mysql-libmysqlclient');
var EventEmitter = require('events').EventEmitter;

@@ -16,4 +16,20 @@ var _ = require('lodash')._;

* Client.
*
* @param {Object} config Database settings = {
* {String} database Database name.
* {String} user Database user.
* {String} password Database password.
* {String} [host] MySQL host. Defaults to 'localhost'.
* {Number} [port] MySQL port. Defaults to 3306.
*
* {String} charset Character set option.
* {Boolean} [disableAutoReconnect] Whether to auto reconnect. ON by default.
* {Function} [configureFn] `function(client)` For setting additional MySQL options on connection.
* }
*
* @param {Object} options Mapper options = {
* {Boolean} verbose Whether to log SQL statements and other information useful when debugging.
* {Boolean} strict Whether to warn when invalid table fields are used in objects.
* }
*/
function Client(config, options) {

@@ -30,3 +46,3 @@ options = options || {};

return this;
};
}

@@ -36,46 +52,80 @@ Client.prototype.__proto__ = EventEmitter.prototype;

/**
* Connects to MySQL server.
*/
Client.prototype.connect = function() {
var that = this;
that.doConnect();
if (this.connected) this.client.closeSync();
this.on('query', function(query, values, callback) {
var config = this.config;
var client = mysql.createConnectionSync();
this.client = client;
client.initSync();
if (!that.connected) that.doConnect();
// values is optional.
if (arguments.length === 2) {
callback = values;
values = null;
if (config.configureFn) {
config.configureFn(this.client);
}
else {
if (config.charset) {
client.setOptionSync(mysql.MYSQL_SET_CHARSET_NAME, config.charset);
}
else if (values) {
// arrays may contain arrays for IN operator
if (typeof values[0] !== 'undefined') values = _.flatten(values);
query = that.format(query, values);
if (!config.disableAutoReconnect) {
client.setOptionSync(mysql.MYSQL_OPT_RECONNECT, 1);
}
}
if (that.verbose) console.log("SQL => "+query);
client.realConnectSync(config.host, config.user, config.password, config.database, config.port);
if (config.database) {
client.query('USE '+config.database);
}
that.client.query(query, function(err, result) {
if (!client) throw new Error('Could not connect with this configuration.', config);
return this.connected = true;
};
if (err) {
console.error("SQL =>", query);
console.error(err);
that.emit('error', err);
return callback(err);
}
// libmysqlclient does not return the actual rows, fetch them
if (result.fieldCount) {
result.fetchAll(function(err, rows) {
if (err) that.emit('error', err);
/**
* Executes a query.
*
* @param {String} query SQL statement with optional placeholders.
* @param {String|Array} values The values for placeholders.
* @param {Function} cb The callback result function.
*/
Client.prototype.all = Client.prototype.exec = function(query, values, cb) {
var that = this;
//console.log("rows => ", rows);
callback(err, rows);
});
}
else {
//console.log("result => ", result);
callback(err, result);
}
});
// values is optional.
if (arguments.length === 2) {
cb = values;
values = null;
}
else if (values) {
// arrays may contain arrays for IN operator
if (typeof values[0] !== 'undefined') values = _.flatten(values);
query = that.format(query, values);
}
if (that.verbose) console.log("SQL=> "+query);
that.client.query(query, function(err, result) {
if (err) {
console.error("SQL=>", query);
console.error(err);
that.emit('error', err);
return cb(err);
}
// libmysqlclient does not return the actual rows, fetch them
if (result.fieldCount) {
result.fetchAll(function(err, rows) {
if (err) that.emit('error', err);
//console.log("rows => ", rows);
cb(err, rows);
});
}
else {
//console.log("result => ", result);
cb(err, result);
}
});

@@ -85,3 +135,11 @@ }

/**
* Formats a SQL string containing placeholders.
*
* @param {String} sql The statement.
* @param {Any} params The values for placeholders.
*/
Client.prototype.format = function(sql, params) {
if (!params) return sql;
var that = this;

@@ -106,4 +164,3 @@ // clone it

Client.prototype.escape = function(val) {
var client = this.client,
escape = this.escape;
var client = this.client;

@@ -138,21 +195,5 @@ if (val === undefined || val === null) return 'NULL';

this.client.closeSync();
}
};
Client.prototype.doConnect = function() {
var config = this.config;
this.client = mysql.createConnectionSync();
this.client.initSync();
if (config.charset) {
this.client.setOptionSync(mysql.MYSQL_SET_CHARSET_NAME, config.charset);
}
this.client.realConnectSync(config.host, config.user, config.password, config.database, config.port);
if (config.database) {
this.client.query('USE '+config.database);
}
if (!this.client) throw new Error('Could not connect with this configuration.', config);
return this.connected = true;
}
/**

@@ -170,3 +211,3 @@ * Execute `sql` and return a column value.

this.emit('query', sql, values, function(err, rows) {
this.exec(sql, values, function(err, rows) {
if (err) return cb(err);

@@ -178,39 +219,6 @@

});
}
};
/**
* Executes `sql` without returning a value.
*
* This actually returns a result but does not do any extra processing
* on it. TODO, there should be a way to optimize this.
*
* @example
* mapper.client.exec("CREATE TABLE foo");
*/
Client.prototype.exec = function(sql, values, cb) {
if (arguments.length === 2) {
cb = values;
values = null;
}
this.emit('query', sql, values, cb);
}
/**
* Executes `sql` and returns one or more rows.
*
* @example
* mapper.client.query('select title, blurb from posts where title = ?', ['a title'], cb);
*/
Client.prototype.all = function(sql, values, cb) {
if (arguments.length === 2) {
cb = values;
values = null;
}
this.emit('query', sql, values, cb);
}
/**
* Executes `sql` and returns exactly one row.

@@ -222,2 +230,4 @@ *

Client.prototype.one = function(sql, values, cb) {
var that = this;
if (arguments.length === 2) {

@@ -228,23 +238,21 @@ cb = values;

// TODO should force to one by adding LIMIT 1 or maybe there is
// a mysql feature like @maxrows
this.emit('query', sql, values, function(err, rows) {
this.exec(sql, values, function(err, rows) {
if (err) return cb(err);
if (rows.length > 1) {
var message = 'Expected one result, got '+rows.length+': ' + that.format(sql, values);
if (that.strict) return cb(message);
if (that.verbose) console.log(message);
}
cb(null, rows[0]);
});
}
};
/**
* Executes a query synchronously.
*/
Client.prototype.execSync = function(sql, values) {
this.connected || this.doConnect();
if (arguments.length === 2) {
cb = values;
values = null;
}
// values is optional.
if (arguments.length === 2) {
callback = values;
values = null;
} else if (values) {
if (values) {
// arrays may contain arrays for IN operator

@@ -256,3 +264,3 @@ if (typeof values[0] !== 'undefined') values = _.flatten(values);

try {
if (this.verbose) console.log("SQL => "+sql);
if (this.verbose) console.log("SQL=> "+sql);

@@ -272,4 +280,5 @@ var result = this.client.querySync(sql);

}
}
};
Client.prototype._execSeriesParallel = function() {

@@ -355,3 +364,2 @@ // remove callback, rest are queries

Client.prototype.execParallel = function() {

@@ -358,0 +366,0 @@ var args = __slice.call(arguments, 0);

@@ -10,2 +10,3 @@ /**

RelationType = Relation.RelationType,
utils = require('./utils'),
__slice = [].slice;

@@ -43,3 +44,3 @@

return this;
};
}

@@ -84,3 +85,3 @@

return this;
}
};

@@ -219,4 +220,4 @@

*/
Dao.prototype.create = function(obj, callback) {
this.insert(obj).exec(callback);
Dao.prototype.create = function(obj, cb) {
this.insert(obj).exec(cb);
};

@@ -227,8 +228,29 @@

*/
Dao.prototype.byId = function(id, callback) {
this.id(id).exec(callback);
Dao.prototype.findById = Dao.prototype.byId = function(id, cb) {
this.where({id: id}).one(cb);
};
/**
* Saves an object using its primary key.
*
* @see Relation
*/
Dao.prototype.save = function(obj, cb) {
var relation = new Relation(this);
var keyName = this.schema.primaryKey;
var keyValue = obj[keyName];
var props = _.omit(obj, keyName);
relation.update().set(props).id(keyValue).exec(cb);
};
/**
* Deletes a row by id.
*/
Dao.prototype.deleteById = Dao.prototype.byId = function(id, cb) {
this.delete().id(id).exec(cb);
};
/**
* Direct fetch functions.

@@ -250,8 +272,10 @@ */

this.client.all.apply(this.client, __slice.call(arguments, 0));
}
};
Dao.prototype.count = function(cb) {
this.client.scalar("SELECT count(*) AS N FROM "+this.escapedTableName, cb);
}
};
Dao.prototype.one = function(cb) {

@@ -262,9 +286,9 @@ if (arguments.length === 1)

this.client.one.apply(this.client, __slice.call(arguments, 0));
}
};
Dao.prototype.truncate = function(cb) {
this.client.exec("TRUNCATE "+this.escapedTableName, cb);
}
};
/**

@@ -284,3 +308,3 @@ * Private functions

if (schemaCache[tableName]) return schemaCache[tableName];
var sql, rows, schema, primaryKey, row;
var sql, row, rows, primaryKey, schema;

@@ -294,3 +318,3 @@ sql = "SELECT column_name, is_nullable, data_type, " +

var row = _.find(rows, function(row) {
row = _.find(rows, function(row) {
return row.column_key === 'PRI';

@@ -303,12 +327,11 @@ });

var schema = {
schema = {
relations: {},
_fields: rows,
columns: _.pluck(rows, 'column_name'),
tableName: tableName,
primaryKey: primaryKey,
escapedTableName: "`"+tableName+"`"
primaryKey: primaryKey
};
utils.escapeNames(schema);
return schemaCache[tableName] = schema;
};
}

@@ -315,0 +338,0 @@

/**
* Module dependencies.
*/
"use strict";
'use strict';
var Base = require('./base')
, Client = require('./client')
, Dao = require('./dao'),
__slice = [].slice;
var Client = require('./client');
var Dao = require('./dao');
/**
* Mapper.
*/
var Mapper = function() {

@@ -20,7 +18,12 @@ this.version = '0.2.0';

/**
* Connects to the database.
*
* @see Client
*/
Mapper.prototype.connect = function(config, options) {
options = options || {};
if (!options.strict) options.strict = false;
var client = new Client(config, options);
client.connect();
this.Base = new Base(client);
client.connect()
this.client = client;

@@ -32,6 +35,10 @@ this.options = options;

/**
* Map a table to a data access object.
*
* @see Dao
*/
Mapper.prototype.map = function(tableName, primaryKey) {
primaryKey = primaryKey || "id";
var dao = new Dao({client: this.client, tableName: tableName, primaryKey: primaryKey, strict: this.options.strict });
return dao;
primaryKey = primaryKey || 'id';
return new Dao({client: this.client, tableName: tableName, primaryKey: primaryKey, strict: this.options.strict });
};

@@ -38,0 +45,0 @@

@@ -6,5 +6,2 @@ var _ = require('lodash');

function QueryBuilder(options) {

@@ -68,3 +65,3 @@ options = options || {};

else
buffer[SELECT] = fields.join(',');
buffer[SELECT] = this.csv(fields, ',');
}

@@ -127,3 +124,3 @@

return this;
}
};

@@ -154,3 +151,3 @@ QueryBuilder.prototype.id = function(val) {

if (i > 0) sql += ", "
sql += field+" = "+escape(any[field]);
sql += escapedField(field) + " = " + escape(any[field]);
}

@@ -161,2 +158,7 @@ }

return this;
};
function escapedField(name) {
return '`' + name + '`';
}

@@ -178,3 +180,3 @@

QueryBuilder.prototype.where = function(any, locals) {
var id, ids, locals, pred, that = this;
var pred, that = this;

@@ -184,8 +186,8 @@ if (_.isString(any)) {

} else {
pred = _.chain(any)
pred = _(any)
.map(function(value, key) {
var keyop = extractKeyOperator(key)
, key = keyop[0]
, operator = keyop[1]
, expression = buildExpression(key, operator, value);
var keyop = extractKeyOperator(key);
key = keyop[0];
var operator = keyop[1];
var expression = buildExpression(key, operator, value);

@@ -196,8 +198,7 @@ if (_.include(that.schema.columns, key)) {

else if (that.strict) {
throw new Error("STRICT: Ivalid column "+key);
throw new Error("STRICT: Invalid column "+key);
}
})
.compact()
.join(' AND ')
.value();
.join(' AND ');

@@ -215,3 +216,3 @@ if (_.isEmpty(pred)) {

return this;
}
};

@@ -227,6 +228,8 @@

this.reset();
var sql, that = this;
var sql, fields, vals;
if (Array.isArray(any)) {
var i, len, fields = validFields(this, any[0]), obj, vals = "";
fields = validFields(this, any[0]);
vals = "";
var i, len, obj;

@@ -239,9 +242,9 @@ for (i = 0, len = any.length; i < len; i++) {

}
sql = "("+fields.join(', ')+") VALUES " + vals;
sql = "(" + this.csv(fields, ', ') + ") VALUES " + vals;
}
else if (_.isObject(any)) {
var fields = validFields(this, any)
, vals = escapeCsvObjectValues(any, fields);
sql = "(" + fields.join(', ') + ") VALUES (" + vals + ")";
fields = validFields(this, any);
vals = escapeCsvObjectValues(any, fields);
sql = "(" + this.csv(fields, ', ') + ") VALUES (" + vals + ")";
}

@@ -262,3 +265,3 @@

return this;
}
};

@@ -268,3 +271,3 @@ QueryBuilder.prototype.limit = function(num) {

return this;
}
} ;

@@ -274,3 +277,3 @@ QueryBuilder.prototype.order = function(clause) {

return this;
}
};

@@ -281,3 +284,3 @@ QueryBuilder.prototype.page = function(pageOffset, rowsPerPage) {

return this;
}
};

@@ -335,5 +338,4 @@

var result = buffer.join(" ") + ";";
return result;
}
return buffer.join(" ") + ";";
};

@@ -375,5 +377,15 @@ QueryBuilder.prototype.sql = function(sql) {

return result;
}
};
QueryBuilder.prototype.csv = function(fields, separator) {
var schema = this.schema;
return _(fields)
.map(function(name) {
return schema.escapedColumns[name];
})
.join(separator);
};
/**

@@ -415,3 +427,3 @@ * Private Methods

return key + operator + value
return escapedField(key) + operator + value
}

@@ -454,3 +466,3 @@

return "'"+val+"'";
};
}

@@ -469,3 +481,3 @@

return result;
};
}

@@ -490,3 +502,3 @@

return sql;
};
}

@@ -497,5 +509,4 @@

for (key in obj) {
if (!obj.hasOwnProperty(key)) continue;
if (columns.indexOf(key) > -1)
keys.push(key)
if (obj.hasOwnProperty(key) && columns.indexOf(key) > -1)
keys.push(key);
else if (strict)

@@ -502,0 +513,0 @@ throw new Error("STRICT: Invalid column "+key);

@@ -35,3 +35,3 @@ var _ = require('lodash'),

query(this, "one", cb);
}
};

@@ -48,3 +48,3 @@ /**

});
}
};

@@ -65,3 +65,3 @@

query(this, "all", cb);
}
};

@@ -75,5 +75,4 @@

Relation.prototype.exec = function(cb) {
// TODO optimize later, currently behaves just like all
this.client.emit('query', this.toSql(), cb);
}
this.client.exec(this.toSql(), cb);
};

@@ -89,3 +88,3 @@

this.client.scalar(this.toSql(), cb);
}
};

@@ -98,4 +97,5 @@

function buildRelation(that, relationItem, rows, relation) {
var RelationDao = relationItem.RelationDao,
relation = relation || RelationDao.select(),
var RelationDao = relationItem.RelationDao;
relation = relation || RelationDao.select();
var
fieldName = relationItem.fieldName,

@@ -108,2 +108,4 @@ relationTableName = relation.dao.schema.escapedTableName,

var relationIdField;
// Caller may have set SELECT or WHERE clause

@@ -124,3 +126,3 @@ if (relation.isChangedBuffer(Index.SELECT))

var thatIdField = thatTableName+"."+that.dao.primaryKey;
var relationIdField = relationTableName+"."+relation.dao.primaryKey;
relationIdField = relationTableName+"."+relation.dao.primaryKey;
ids = _.pluck(rows, fieldName);

@@ -158,7 +160,7 @@ return relation

// WHERE PostsTags.postId IN ($ids);
var throughRelation = relationItem.ThroughDao.select(),
throughTableName = throughRelation.dao.schema.escapedTableName,
relationIdField = relationTableName+"."+throughRelation.dao.primaryKey,
throughJoin = throughTableName+"."+relationItem.joinFieldName,
throughField = throughTableName+"."+fieldName;
var throughRelation = relationItem.ThroughDao.select();
var throughTableName = throughRelation.dao.schema.escapedTableName;
relationIdField = relationTableName+"."+throughRelation.dao.primaryKey;
var throughJoin = throughTableName+"."+relationItem.joinFieldName;
var throughField = throughTableName+"."+fieldName;

@@ -212,4 +214,4 @@ ids = _.pluck(rows, that.dao.primaryKey);

// Allows customzed retrieval like retrieving a single page of comments
// intead of all.
// Allows customized retrieval like retrieving a single page of comments
// instead of all.
if (item.lambda) {

@@ -257,3 +259,3 @@ if (item.lambda.length === 1) {

}
};
}

@@ -260,0 +262,0 @@

@@ -37,3 +37,3 @@ /**

var keysFromObject = exports.keysFromObject = function(fields) {
return _(fields).chain()
return _(fields)
.map(function(field) {

@@ -79,7 +79,5 @@ return _(field).keys();

var toCsv = exports.toCsv = function(list, keys, outValues) {
return _(list).chain()
.values()
return _(list)
.map(function(o) { outValues.push(o); return '?'; })
.join(',')
.value();
.join(',');
};

@@ -107,4 +105,102 @@

}
};
}
return returnFields;
};
/**
* Escapes names in the schema and stores them so it is not performed when building statements.
*
* @param schema
*/
function escapeNames(schema) {
schema.columns = _.pluck(schema._fields, 'column_name');
schema.escapedColumns = {};
schema.columns.forEach(function(name) {
schema.escapedColumns[name] = '`' + name + '`';
});
schema.escapedTableName = '`' + schema.tableName + '`';
}
exports.escapeNames = escapeNames;
function escape(val) {
if (val === undefined || val === null) {
return 'NULL';
}
switch (typeof val) {
case 'boolean': return (val) ? 'true' : 'false';
case 'number': return val+'';
}
if (Array.isArray(val)) {
var sanitized = val.map(function( v ) { return escape(v); } );
return sanitized.join(',');
}
if (typeof val === 'object') {
val = (typeof val.toISOString === 'function')
? val.toISOString()
: val.toString();
}
val = val.replace(/['\\\0\n\r\b\t\x1a]/g, function(s) {
switch(s) {
case '\0': return '\\0';
case '\n': return '\\n';
case '\r': return '\\r';
case '\b': return '\\b';
case '\t': return '\\t';
case '\x1a': return '\\Z';
case '\'': return '\'\'';
default: return '\\'+s;
}
});
return '\''+val+'\'';
}
exports.escape = escape;
function escapeCsvObjectValues(obj, keys) {
if (!keys) keys = Object.keys(obj);
var i, item, len, result = '';
for (i = 0, len = keys.length; i < len; i++) {
item = obj[keys[i]];
if (i > 0)
result += ', ';
result += escape(item);
}
return result;
}
exports.escapeCsvObjectValues = escapeCsvObjectValues;
/**
* Formats prepared statement.
*
* @param sql
* @param params
* @return {String}
*/
function format(sql, params) {
// need clone for shifting
params = params ? params.concat() : [];
sql = sql.replace(/\?/g, function() {
if (params.length == 0) {
throw new Error('ZERO parameters given');
}
var val = params.shift();
return escape(val);
});
if (params.length) {
throw Error('too many parameters given');
}
return sql;
}
exports.format = format;
{
"name": "mapper",
"version": "0.2.3-pre",
"description": "Lightweight, blazing fast ODM on top of mysql-libmysqlclient.",
"tags" : ["odm", "mysql", "mysql-libmysqlclient"],
"contributors": [
{ "name": "Didit Tech <development@didit.com>" }
"version": "0.2.4-pre",
"description": "Lightweight, blazing fast MySQL data mapper.",
"tags": [
"odm",
"mysql",
"mysql-libmysqlclient"
],
"author": {
"name": "Mario Gutierrez", "email": "mario@mgutz.com"
"name": "Mario Gutierrez",
"email": "mario@mgutz.com"
},
"homepage": "https://github.com/mgutz/mapper",
"dependencies": {
"async": "~0.1.22",
"mysql-libmysqlclient": "~1.5.1",
"lodash": "~0.7.0"
"lodash": "~1.0.0-rc.3"
},
"devDependencies": {
"mysql": "2.0.0-alpha5",
"mocha": "~1.2.2",
"chai": "~0.5.3",
"underscore.string": ">= 2.1.1"
"underscore.string": ">= 2.1.1",
"mocha": "~1.7.4",
"chai": "~1.4.2",
"express": "~3.0.6"
},
"main": "index",
"scripts": { "test": "make test" },
"engines": { "node": ">= 0.6" },
"licenses" : [{
"type" : "MIT"
, "url" : "http://github.com/didit-tech/FastLegS/raw/master/LICENSE"
}]
"scripts": {
"test": "make test"
},
"engines": {
"node": ">= 0.6"
},
"licenses": [
{
"type": "MIT",
"url": "http://github.com/mgutz/mapper/raw/master/LICENSE"
}
]
}

@@ -8,14 +8,9 @@ # Mapper

Current node.js ORMs try to add business logic to models with statics,
virtual attributes, validations, pseudo-class inheritance. They're bloated.
As an example, why have validations in the ORM when you could do validations
in a separate module and share that between client and server? Simpler is better
as development move towards single page apps, data services and shared code.
Wanted a lightweight data mapper that is fast and likes SQL.
See [mapper-obtvse example project](https://github.com/mgutz/mapper-obtvse.git)
## Install
To use mapper
# optional, on ubuntu
To use mapper in your project
# For Ubuntu
sudo apt-get install libmysqlclient-dev

@@ -25,8 +20,16 @@

To run Backbone or AngularJS Example
NOTE: There are currently two mapper implementations. The legacy
as used in `test/integration/legacy.js` which will be obseleted.
The current implementeation is used in `test/integration/integrationTest.js`.
git clone git://github.com/mgutz/mapper.git
cd mapper
npm install -d
make test # creates necessary database and config.json
node example/app.js
then browse `http://localhost:3000`
## TODO
Connection pooling - adding SOON
## Quickstart

@@ -54,12 +57,15 @@

CRUD
Create
var insertId;
// insert a new post
// These are equivalent, where first is more SQL like
Post.insert({ title: 'First Post' }).exec(function(err, result) {
insertId = result.insertId;
});
Post.create({ title: 'First Post' }, function(err, result) { ... });
// select inserted post
Retrieve
// Select inserted post
Post.where({ id: insertId }).one(function(err, post) {

@@ -69,2 +75,6 @@ assert.equal(post.title, 'First Post,');

Post.findById(insertId, function(err, post) { ... });
Update
// update inserted post

@@ -79,2 +89,8 @@ Post

// if doc has id set, then save is simple. Note,
// pluck only the columns you want updated
Post.save(doc, function(err, result) { ... });
Delete
// delete all posts with a specific title

@@ -85,3 +101,5 @@ Post.delete().where({ title: 'New Title' }).exec(function(err, result) {

Post.deleteById(insertId, function(err, result) {});
Gets the first page of posts and populate comments property with

@@ -122,12 +140,12 @@ the second page of comments for each post retrieved.

Mapper.client.execSeries(
"SELECT * FROM posts WHERE author = ?", [1],
"SELECT * FROM posts WHERE author = ?", [1],
// SQL may be separated by `,`
"SELECT * ",
"FROM comments WHERE author = ?", [1],
// SQL may be separated by `,`
"SELECT * ",
"FROM comments WHERE author = ?", [1],
function(err, results) {
// posts are in results[0][0..n]
// comments are in results[1][0..n]
}
function(err, results) {
// posts are in results[0][0..n]
// comments are in results[1][0..n]
}
);

@@ -139,6 +157,6 @@

Mapper.client.execParallel(
"SELECT * FROM posts WHERE author = ?", [1],
"SELECT * FROM comments WHERE author = ?", [1],
function(err, results) {
}
"SELECT * FROM posts WHERE author = ?", [1],
"SELECT * FROM comments WHERE author = ?", [1],
function(err, results) {
}
);

@@ -179,3 +197,4 @@

Even more surprising is Mapper is faster than MongoDB using the official MongoDB driver for node.js.
Even more surprising is Mapper is faster than MongoDB using the official MongoDB
driver for node.js.

@@ -182,0 +201,0 @@ ## Implementation Best Practice

var async = require("async")
, config = require("../../.mapper.json");
, config = require("../../config.json");

@@ -4,0 +4,0 @@

var async = require("async")
, config = require("../../.mapper.json")
, config = require("../../config.json")
, Mapper = require("../..");

@@ -4,0 +4,0 @@

var async = require("async")
, config = require("../../.mapper.json")
, Mapper = require("../..");
, config = require("../../config.json")
, Mapper = require("../..")
, verbose = false
;

@@ -22,3 +24,3 @@ Mapper.connect(config);

.exec(function(err, result) {
//if (iteration === 2) console.log(result);
if (verbose && iteration === 2) console.log(result);
insertId = result.insertId;

@@ -28,14 +30,13 @@ cb(err);

} else {
UserDao.select('userName', 'firstName', 'lastName').limit(50).all(cb);
// .all(function(err, found) {
// if (iteration === 3) console.log(found);
// cb(err);
// });
UserDao
.select('userName', 'firstName', 'lastName')
.limit(50)
.all(function(err, found) {
if (verbose && iteration === 3) console.log(found);
cb(err);
});
}
},
function(err) {
if (err) console.error(err);
cb(err);
}
cb
);

@@ -45,3 +46,4 @@ }

testMapper(function(err) {
if (err) console.error(err);
process.exit();
});
var async = require("async")
, config = require("../../.mapper.json");
, config = require("../../config.json");

@@ -4,0 +4,0 @@

@@ -29,3 +29,3 @@ var prompt = require("./prompt")

"CREATE TABLE Tags (\
id integer NOT NULL,\
id integer NOT NULL primary key auto_increment, \
name varchar(64))",

@@ -55,7 +55,22 @@

"CREATE INDEX comments_post_id \
ON Comments(postId)"
ON Comments(postId)",
todos:
"CREATE TABLE Todos ( \
id integer NOT NULL auto_increment, \
`text` text NOT null, \
`order` int, \
done boolean, \
CONSTRAINT todos_pkey PRIMARY KEY (id))",
keywords:
"CREATE TABLE Keywords ( \
id integer NOT NULL, \
`text` text NOT null, \
`order` int, \
CONSTRAINT todos_pkey PRIMARY KEY (id))"
};
console.log("\nMapper. Please enter your MySQL credentials " +
"and a database for us to create.\n");
console.log("\nPlease enter your MySQL credentials " +
"to create test database.\n");

@@ -98,7 +113,9 @@ async.series({

function(cb) { client.query(create.comments, cb); },
function(cb) { client.query(create.commentsPostIdIndex, cb); }
function(cb) { client.query(create.commentsPostIdIndex, cb); },
function(cb) { client.query(create.todos, cb); },
function(cb) { client.query(create.keywords, cb); }
], function(err, results) {
if (err) console.error(err);
if (!err) {
fs.writeFile('.mapper.json', JSON.stringify(config), function (err) {
fs.writeFile('config.json', JSON.stringify(config), function (err) {
client.closeSync();

@@ -105,0 +122,0 @@ process.exit();

@@ -57,2 +57,10 @@ /**

var keywords = [
{ id: 1, text: 'select', order: 1},
{ id: 2, text: 'delete', order: 2},
{ id: 3, text: 'insert', order: 3},
{ id: 4, text: 'update', order: 4},
];
var Comment = Mapper.map("Comments")

@@ -62,2 +70,3 @@ , Post = Mapper.map("Posts")

, MoreDetail = Mapper.map("PostMoreDetails")
, Keyword = Mapper.map("Keywords")
, Tag = Mapper.map("Tags");

@@ -93,2 +102,3 @@

function(cb) { Post.truncate(cb); },
function(cb) { Keyword.truncate(cb); },

@@ -99,3 +109,4 @@ function(cb) { Post.insert(posts).exec(cb); },

function(cb) { MoreDetail.insert(moreDetails).exec(cb); },
function(cb) { PostTag.insert(postsTags).exec(cb); }
function(cb) { PostTag.insert(postsTags).exec(cb); },
function(cb) { Keyword.insert(keywords).exec(cb); }
];

@@ -107,4 +118,33 @@

describe("Insert", function() {
it('using columns named after keywords', function(done) {
Keyword
.insert({text: 'create', order: 9000})
.exec(function(err, result) {
assert.ifError(err);
Keyword.findById(result.insertId, function(err, found) {
assert.ifError(err);
assert.equal('create', found.text);
assert.equal(9000, found.order);
done();
});
});
})
});
describe("Select", function() {
it('find columns named after keywords', function(done) {
Keyword
.select('text', 'order')
.where({text: 'select'})
.all(function(err, rows) {
assert.ifError(err);
assert.equal(1, rows.length);
assert.equal('select', rows[0].text);
done();
});
});
it('find a post by primary key using object', function(done) {

@@ -184,5 +224,2 @@ Post

it('finds a post using string and only return certain fields', function(done) {

@@ -446,2 +483,28 @@ Post

});
it('columns named after keywords', function(done) {
Keyword
.set({text: 'updated'})
.where({text: 'update'})
.exec(function(err) {
assert.ifError(err);
Keyword.findById(4, function(err, found) {
assert.equal('updated', found.text);
done();
});
});
});
it('columns named after keywords', function(done) {
Keyword
.set({text: 'updated'})
.where({text: 'update'})
.exec(function(err) {
assert.ifError(err);
Keyword.findById(4, function(err, found) {
assert.equal('updated', found.text);
done();
});
});
});
}); // end Update

@@ -452,2 +515,16 @@

it('columns named after keywords', function(done) {
Keyword
.delete()
.where({text: 'delete'})
.exec(function(err) {
assert.ifError(err);
Keyword.findById(2, function(err, found) {
assert.ifError(err);
assert.isUndefined(found);
done();
});
});
});
it('comment by primary key', function(done) {

@@ -497,2 +574,43 @@ Comment.delete().id(8).exec(function(err, results) {

}); // DELETE
describe('Sugar', function() {
it('should find by id', function(done) {
Tag.findById(1, function(err, row) {
assert.equal(row.name, 'funny');
done();
});
});
it('should delete by id', function(done) {
Tag.deleteById(2, function(err, result) {
assert.equal(result.affectedRows, 1);
Tag.findById(2, function(err, found) {
assert.isUndefined(found);
done();
})
});
});
it('should create', function(done) {
Tag.create({name: 'new tag'}, function(err, result) {
assert.isTrue(result.insertId > 4);
done();
});
});
it('should save', function(done) {
Tag.findById(3, function(err, row) {
assert.equal(row.name, 'javascript');
row.name = 'awesomescript';
Tag.save(row, function(err, result) {
assert.equal(result.affectedRows, 1);
Tag.findById(3, function(err, found) {
assert.equal('awesomescript', found.name);
done();
});
});
});
});
});

@@ -499,0 +617,0 @@

var assert = global.assert = require('chai').assert,
config = require('../.mapper.json'),
config = require('../config.json'),
Mapper = require('..');

@@ -4,0 +4,0 @@

@@ -9,2 +9,3 @@ /**

QueryBuilder = helper.QueryBuilder,
utils = require('../../lib/utils'),
Index = QueryBuilder.Index;

@@ -27,6 +28,5 @@

schema.columns = _(schema._fields).pluck('column_name');
schema.escapedTableName = '`'+schema.tableName+'`';
utils.escapeNames(schema);
// whitespace doesn't matter to sql but it's esier to write unit test
// whitespace doesn't matter to sql but it's easier to write unit test
// if spaces are normalized

@@ -39,3 +39,3 @@ var oldEqual = assert.equal;

oldEqual.apply(assert, Array.prototype.slice.call(arguments));
}
};

@@ -108,3 +108,3 @@ var qb = new QueryBuilder({schema: schema});

"DELETE FROM `model_name` " +
"WHERE name = 'foo';"
"WHERE `name` = 'foo';"
);

@@ -121,4 +121,4 @@ });

"DELETE FROM `model_name` " +
"WHERE name = 'foo' " +
"AND email = 'bar@bah.com';"
"WHERE `name` = 'foo' " +
"AND `email` = 'bar@bah.com';"
);

@@ -136,4 +136,4 @@ });

"DELETE FROM `model_name` " +
"WHERE name = 'foo' " +
"AND email = 'bar@bah.com';"
"WHERE `name` = 'foo' " +
"AND `email` = 'bar@bah.com';"
);

@@ -151,4 +151,4 @@ });

"DELETE FROM `model_name` " +
"WHERE name = 'foo' " +
"AND email = 'bar@bah.com';"
"WHERE `name` = 'foo' " +
"AND `email` = 'bar@bah.com';"
);

@@ -166,3 +166,3 @@ });

qb.insert(obj).toSql(),
"INSERT INTO `model_name`(index, name) " +
"INSERT INTO `model_name`(`index`, `name`) " +
"VALUES ('1234', 'Joseph');"

@@ -177,3 +177,3 @@ );

qb.insert(obj).toSql(),
"INSERT INTO `model_name`(index, name) " +
"INSERT INTO `model_name`(`index`, `name`) " +
"VALUES ('1234', 'Joseph'), ('2222', 'Jane');"

@@ -188,3 +188,3 @@ );

qb.insert(obj).toSql(),
"INSERT INTO `model_name`(index) " +
"INSERT INTO `model_name`(`index`) " +
"VALUES ('1234');"

@@ -250,3 +250,3 @@ );

"SELECT * FROM `model_name` " +
"WHERE name = 'awesome sauce';"
"WHERE `name` = 'awesome sauce';"
);

@@ -261,4 +261,4 @@ });

"SELECT * FROM `model_name` " +
"WHERE name = 'awesome sauce' " +
"AND email = 'joepancakes@email.com';"
"WHERE `name` = 'awesome sauce' " +
"AND `email` = 'joepancakes@email.com';"
);

@@ -277,4 +277,4 @@ });

"SELECT index, email FROM `model_name` " +
"WHERE name = 'awesome sauce' " +
"AND email = 'joepancakes@email.com';"
"WHERE `name` = 'awesome sauce' " +
"AND `email` = 'joepancakes@email.com';"
);

@@ -292,5 +292,5 @@ });

"SELECT index,email FROM `model_name` " +
"WHERE name = 'awesome sauce' " +
"AND email = 'joepancakes@email.com';"
"SELECT `index`,`email` FROM `model_name` " +
"WHERE `name` = 'awesome sauce' " +
"AND `email` = 'joepancakes@email.com';"
);

@@ -308,5 +308,5 @@ });

"SELECT index,email FROM `model_name` " +
"WHERE name = 'awesome sauce' " +
"AND email = 'joepancakes@email.com';"
"SELECT `index`,`email` FROM `model_name` " +
"WHERE `name` = 'awesome sauce' " +
"AND `email` = 'joepancakes@email.com';"
);

@@ -326,4 +326,4 @@ });

"SELECT * FROM `model_name` " +
"WHERE name = 'awesome sauce' " +
"AND email = 'joepancakes@email.com';"
"WHERE `name` = 'awesome sauce' " +
"AND `email` = 'joepancakes@email.com';"
);

@@ -344,4 +344,4 @@ });

"SELECT index, email FROM `model_name` " +
"WHERE name = 'awesome sauce' " +
"AND email = 'joepancakes@email.com' " +
"WHERE `name` = 'awesome sauce' " +
"AND `email` = 'joepancakes@email.com' " +
"LIMIT 25;"

@@ -362,4 +362,4 @@ );

"SELECT index, email FROM `model_name` " +
"WHERE name = 'awesome sauce' " +
"AND email = 'joepancakes@email.com' " +
"WHERE `name` = 'awesome sauce' " +
"AND `email` = 'joepancakes@email.com' " +
"OFFSET 25;"

@@ -381,4 +381,4 @@ );

"SELECT index, email FROM `model_name` " +
"WHERE name = 'awesome sauce' " +
"AND email = 'joepancakes@email.com' " +
"WHERE `name` = 'awesome sauce' " +
"AND `email` = 'joepancakes@email.com' " +
"LIMIT 10 " +

@@ -402,4 +402,4 @@ "OFFSET 25;"

"SELECT index, email FROM `model_name` " +
"WHERE name = 'awesome sauce' " +
"AND email = 'joepancakes@email.com' " +
"WHERE `name` = 'awesome sauce' " +
"AND `email` = 'joepancakes@email.com' " +
"ORDER BY field " +

@@ -423,4 +423,4 @@ "LIMIT 50;"

"SELECT index, email FROM `model_name` " +
"WHERE name = 'awesome sauce' " +
"AND email = 'joepancakes@email.com' " +
"WHERE `name` = 'awesome sauce' " +
"AND `email` = 'joepancakes@email.com' " +
"ORDER BY field " +

@@ -443,4 +443,4 @@ "LIMIT 50 " +

"SELECT index, email FROM `model_name` " +
"WHERE name = 'awesome sauce' " +
"AND email = 'joepancakes@email.com' " +
"WHERE `name` = 'awesome sauce' " +
"AND `email` = 'joepancakes@email.com' " +
"ORDER BY field DESC,field2;"

@@ -462,6 +462,6 @@ );

"SELECT * FROM `model_name` " +
"WHERE name <> 'awesome sauce' " +
"AND name in ('one','two') " +
"AND age not in (1,3) " +
"AND age = 1" +
"WHERE `name` <> 'awesome sauce' " +
"AND `name` in ('one','two') " +
"AND `age` not in (1,3) " +
"AND `age` = 1" +
";"

@@ -481,3 +481,3 @@ );

"SELECT * FROM `model_name` " +
"WHERE name = 'foo';"
"WHERE `name` = 'foo';"
);

@@ -515,3 +515,3 @@ });

"SELECT * FROM `model_name` " +
"WHERE name IS NULL;"
"WHERE `name` IS NULL;"
);

@@ -538,4 +538,4 @@ });

"UPDATE `model_name` " +
"SET index = '1234', name = 'Joseph' " +
"WHERE age > 15;"
"SET `index` = '1234', `name` = 'Joseph' " +
"WHERE `age` > 15;"
);

@@ -550,5 +550,5 @@ }),

"UPDATE A " +
"SET index = '1234', name = 'Joseph' " +
"SET `index` = '1234', `name` = 'Joseph' " +
"FROM table A "+
"WHERE age > 15;"
"WHERE `age` > 15;"
);

@@ -568,4 +568,4 @@ }),

"UPDATE `model_name` " +
"SET age = 8, name = 'Bob', email = 'bob@email.com' " +
"WHERE name = 'joe';"
"SET `age` = 8, `name` = 'Bob', `email` = 'bob@email.com' " +
"WHERE `name` = 'joe';"
);

@@ -599,3 +599,3 @@ });

"UPDATE `model_name` " +
"SET age = 8, name = 'Bob', email = 'bob@email.com';"
"SET `age` = 8, `name` = 'Bob', `email` = 'bob@email.com';"
);

@@ -602,0 +602,0 @@ });

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc