From 9a5bb6f3c79a4691cb8aa9678fad0e068c419976 Mon Sep 17 00:00:00 2001 From: Vitaly Tomilov Date: Fri, 6 Mar 2015 21:29:35 +0000 Subject: [PATCH] 1. fixing an issue with value formatting during a function call; 2. added as.csv(array) to convert an array of javascript values into csv of postgresql values --- index.js | 71 +++++++++++++++++++++++++++++++++----------------------- 1 file changed, 42 insertions(+), 29 deletions(-) diff --git a/index.js b/index.js index 8b43ed2a..3a6c8672 100644 --- a/index.js +++ b/index.js @@ -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; @@ -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; }; @@ -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; } @@ -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) + ');';