Skip to content

Instantly share code, notes, and snippets.

@dimfeld
Created March 21, 2015 21:41
Show Gist options
  • Save dimfeld/6bc7d921040f9b6eeaed to your computer and use it in GitHub Desktop.
Save dimfeld/6bc7d921040f9b6eeaed to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
"use strict";
var es = require('event-stream');
var Promise = require("bluebird");
var pg = Promise.promisifyAll(require("pg.js"));
var pt = require("stream").PassThrough;
var copyStream = require("pg-copy-streams").from;
var _ = require("lodash");
var dsn;
var invalidInput = "abc,555,ghi\naaa,bbb,ccc\n";
var validInput = "abc,555,ghi\naaa,768,ccc\n";
var table = "test_table";
var createTable = "CREATE TABLE IF NOT EXISTS " + table + " (a varchar, b integer, c varchar);";
function doCopy(client, input) {
return new Promise(function(resolve, reject) {
var inputStream = pt();
var s = client.query(copyStream('COPY ' + table + ' FROM STDIN(FORMAT csv, DELIMITER \',\')'));
inputStream.pipe(s).on('error', reject).on('finish', resolve);
inputStream.push(input);
inputStream.end();
});
}
function runTest(client, input, expectPass) {
return doCopy(client, input).then(
function() {
if(expectPass) {
console.error("Passed, as expected");
} else {
console.error("Expected an error, but saw success!");
}
},
function(err) {
if(expectPass) {
console.error("Error", err, "was thrown, but expected success!");
} else {
console.error("Error", err, "was thrown, as expected");
}
throw err;
});
}
pg.connect(dsn, function(err, client, done) {
if(err) {
console.error("Connection error", err);
return;
}
client.queryAsync(createTable).
then(_.partial(runTest, client, validInput, true)).
then(_.partial(runTest, client, invalidInput, false)).
finally(done).done();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment