Skip to content

Instantly share code, notes, and snippets.

@drdaeman
Created July 19, 2011 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drdaeman/1093370 to your computer and use it in GitHub Desktop.
Save drdaeman/1093370 to your computer and use it in GitHub Desktop.
Support for bytea datatype for node-postgres
// types.js
// ...
var parseByteA = function(val) {
// Step 1: Find binary data length (and validate data)
var length = 0;
for (var i = 0; i < val.length; i++) {
if (val[i] == "\\") {
if (i >= val.length - 1)
throw "Invalid bytea encoding: '\\' at the end";
if (val[i + 1] == "\\") {
length += 1;
i += 1;
} else {
if (i >= val.length - 3)
throw "Invalid bytea encoding: not enough space for 3 octal digits after '\\' near the end";
if (!val.substr(i + 1, 3).match(/^[0-7]{3}$/))
throw "Invalid bytea encoding: '\\' is not followed by 3 octal digits at "+ I
length += 1;
i += 3;
}
} else {
if (val.charCodeAt(i) > 255)
throw "Invalid bytea encoding: multi-byte character at position " + i
length += 1;
}
}
// Step 2: Allocate buffer and fill it decoding the data
var buf = new Buffer(length),
pos = 0;
for (var i = 0; i < val.length; i++) {
if (val[i] == "\\") {
// No need for correctness checks as they were done in step 1
if (val[i + 1] == "\\") {
buf[pos] = 92; // 92 == "\\".charCodeAt(0) == val.charCodeAt(i + 1)
pos += 1;
i += 1;
} else {
buf[pos] = parseInt(val.substr(i + 1, 3), 8);
pos += 1;
i += 3;
}
} else {
buf[pos] = val.charCodeAt(i);
pos += 1;
}
}
return buf;
/*
// Alternate implementation (lacks error checking and probably more resource-hungry):
return new Buffer(val.replace(/\\([0-7]{3})/g, function (full_match, code) {
return String.fromCharCode(parseInt(code, 8));
}).replace(/\\\\/g, "\\"));
*/
};
// ...
registerStringTypeParser(17, parseByteA);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment