Javascript pg promise:将函数作为参数传递给func()

Javascript pg promise:将函数作为参数传递给func(),javascript,postgresql,pg-promise,Javascript,Postgresql,Pg Promise,我正在使用访问我们的postgres数据库。我想调用一个存储的procfoo(geom),它接受一个几何数据类型(PostGIS)。不过,我一开始只有lats/lngs,所以我想使用postGIS转换它们 这看起来像这样: db.func('foo', 'ST_MakePoint(' + location.lat + ', ' + location.lng + ')') .then((result) => { console.log(bar); }); function

我正在使用访问我们的postgres数据库。我想调用一个存储的proc
foo(geom)
,它接受一个几何数据类型(PostGIS)。不过,我一开始只有lats/lngs,所以我想使用postGIS转换它们

这看起来像这样:

db.func('foo', 'ST_MakePoint(' + location.lat + ', ' + location.lng + ')')
  .then((result) => {
    console.log(bar);
  });
function Point(lat, lng) {
    this.lat = +lat;
    this.lng = +lng;
    this.rawType = true; /* use as raw/unescaped value */
    this.toPostgres = p => {
        return 'ST_MakePoint(' + p.lat + ',' + p.lng + ')';
    };
}
我现在得到一个错误,抱怨我有一个无效的几何体(转换没有发生)。我确信
ST_MakePoint
适用于我拥有的值。我猜在db上执行时,它会将其解释为字符串,而不是函数调用

我应该如何传递此参数以使其工作?

我是;)的作者

与通过格式化变量指定格式化模板的常规查询格式化不同,在使用方法和时跳过该模板,因此它们是从值类型中隐含的

最优雅的解决方案是使用库支持的,它允许您覆盖任何数据类型并提供自己的格式

你可以这样介绍你自己的课程
要点

db.func('foo', 'ST_MakePoint(' + location.lat + ', ' + location.lng + ')')
  .then((result) => {
    console.log(bar);
  });
function Point(lat, lng) {
    this.lat = +lat;
    this.lng = +lng;
    this.rawType = true; /* use as raw/unescaped value */
    this.toPostgres = p => {
        return 'ST_MakePoint(' + p.lat + ',' + p.lng + ')';
    };
}
然后可以将其作为常规值传入:

const p = new Point(1, 2);

db.func('foo', [p]).then(...)
或者,您可以直接执行查询。不要高估方法的价值,该方法只执行
SELECT*FROM foo
,因此您可以执行以下操作:

const p = 'ST_MakePoint(' + lat + ',' + lng + ')';

db.any('SELECT * FROM foo($1:raw)', p).then(...)
:raw
-注入原始/未扫描的值

在未来,与其猜测执行什么,不如尝试,或者至少处理

更新日期:2018年4月29日

已更新的语法,以遵守支持的最新版本

以及结束一个点的最短语法:

const point = (lat, lng) => ({
    toPostgres: ()=> pgp.as.format('ST_MakePoint($1, $2)', [lat, lng]),
    rawType: true
});
因此,您可以将其简单地传递为:

db.func('foo', point(1, 2))