Skip to content

Commit

Permalink
1. fixing an issue with value formatting during a function call;
Browse files Browse the repository at this point in the history
2. added as.csv(array) to convert an array of javascript values into csv of postgresql values
  • Loading branch information
vitaly-t committed Mar 6, 2015
1 parent 5c7be80 commit 9a5bb6f
Showing 1 changed file with 42 additions and 29 deletions.
71 changes: 42 additions & 29 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ module.exports = function (options) {
return dbInit(this, cn, options);
};

// Namespace for type conversion helpers;
lib.as = $wrap;

// Exposing PG library instance, just for flexibility.
lib.pg = npm.pg;

Expand All @@ -54,32 +57,6 @@ module.exports = function (options) {
npm.pg.end();
};

// Namespace for type conversion helpers;
lib.as = {
bool: function (val) {
if ($isNull(val)) {
return 'null';
}
return val ? 'TRUE' : 'FALSE';
},
text: function (val) {
if ($isNull(val)) {
return 'null';
}
return $wrapText($fixQuotes(val));
},
date: function (val) {
if ($isNull(val)) {
return 'null';
}
if (val instanceof Date) {
return $wrapText(val.toUTCString());
} else {
throw new Error($wrapText(val) + " doesn't represent a valid Date object or value");
}
}
};

return lib;
};

Expand Down Expand Up @@ -343,12 +320,12 @@ function $wrapValue(val) {
}
switch (typeof(val)) {
case 'string':
return dbInst.as.text(val);
return $wrap.text(val);
case 'boolean':
return dbInst.as.bool(val);
return $wrap.bool(val);
default:
if (val instanceof Date) {
return dbInst.as.date(val);
return $wrap.date(val);
} else {
return val;
}
Expand All @@ -370,6 +347,42 @@ function $formatValues(values) {
return s;
}

// Value wrapper to be exposed through 'pgp.as' namespace;
var $wrap = {
text: function (txt) {
if ($isNull(txt)) {
return 'null';
}
return $wrapText($fixQuotes(txt));
},
bool: function (val) {
if ($isNull(val)) {
return 'null';
}
return val ? 'TRUE' : 'FALSE';
},
date: function (d) {
if ($isNull(d)) {
return 'null';
}
if (d instanceof Date) {
return $wrapText(d.toUTCString());
} else {
throw new Error($wrapText(d) + " doesn't represent a valid Date object or value");
}
},
csv: function (arr) {
if ($isNull(arr)) {
return 'null';
}
if (Array.isArray(arr)) {
return $formatValues(arr);
} else {
throw new Error($wrapText(arr) + " doesn't represent a valid Array object or value");
}
}
};

// Formats a proper function call from the parameters.
function $createFuncQuery(funcName, params) {
return 'select * from ' + funcName + '(' + $formatValues(params) + ');';
Expand Down

0 comments on commit 9a5bb6f

Please sign in to comment.