knex/test/integration/logger.js

102 lines
3.0 KiB
JavaScript
Raw Normal View History

/*global expect, d*/
'use strict';
module.exports = function () {
2013-12-27 14:44:21 -05:00
var _ = require('lodash');
// This is where all of the info from the query calls goes...
return {
client: function(knex) {
var Raw = require('../../lib/raw');
var client = knex.client;
client.initSchema();
var aliases = {
'pg': 'postgresql',
'sqlite': 'sqlite3'
};
2014-08-11 12:25:39 +02:00
function compareBindings(gotBindings, wantedBindings) {
if (_.isArray(wantedBindings)) {
expect(gotBindings.length).to.eql(wantedBindings.length);
_.each(wantedBindings, function (wantedBinding, index) {
if (_.isFunction(wantedBinding)) {
expect(wantedBinding(gotBindings[index])).to.eql(true);
} else {
expect(wantedBinding).to.eql(gotBindings[index]);
}
});
} else {
expect(gotBindings).to.eql(wantedBindings);
}
}
2013-12-27 14:44:21 -05:00
function testSqlTester(qb, dialect, statement, bindings, returnval) {
2013-12-27 14:44:21 -05:00
// Useful in cases where we want to just test the sql for both PG and SQLite3
if (_.isArray(dialect)) {
_.each(dialect, function(val) {
testSqlTester.call(this, val, statement, bindings, returnval);
}, qb);
2013-12-27 14:44:21 -05:00
} else if (client.dialect === dialect || aliases[dialect] === client.dialect) {
var sql = qb.toSQL();
2013-12-27 14:44:21 -05:00
if (statement) {
2013-12-27 14:44:21 -05:00
if (_.isArray(sql)) {
expect(_.pluck(sql, 'sql')).to.eql(statement);
} else {
expect(sql.sql).to.equal(statement);
}
}
if (bindings) {
2013-12-27 14:44:21 -05:00
if (_.isArray(sql)) {
2014-08-11 12:25:39 +02:00
compareBindings(_.pluck(sql, 'bindings'), bindings);
2013-12-27 14:44:21 -05:00
} else {
2014-08-11 12:25:39 +02:00
compareBindings(sql.bindings, bindings);
2013-12-27 14:44:21 -05:00
}
}
if (returnval !== undefined && returnval !== null) {
var oldThen = qb.then;
qb.then = function() {
2013-12-27 14:44:21 -05:00
var promise = oldThen.apply(this, []);
promise = promise.tap(function(resp) {
2014-09-02 22:03:14 +02:00
if (_.isFunction(returnval)) {
expect(!!returnval(resp)).to.equal(true);
} else {
expect(stripDates(resp)).to.eql(returnval);
}
2013-12-27 14:44:21 -05:00
});
return promise.then.apply(promise, arguments);
};
}
}
}
function stripDates(resp) {
if (!_.isObject(resp[0])) return resp;
return _.map(resp, function(val) {
return _.reduce(val, function(memo, val, key) {
if (_.contains(['created_at', 'updated_at'], key)) {
memo[key] = d;
} else {
memo[key] = val;
}
return memo;
}, {});
});
}
Raw.prototype.testSql =
client.QueryBuilder.prototype.testSql =
2013-12-27 14:44:21 -05:00
client.SchemaBuilder.prototype.testSql = function Logger$testSql(handler) {
handler(_.bind(testSqlTester, null, this));
2013-12-27 14:44:21 -05:00
return this;
};
return knex;
}
};
};