首页 > 解决方案 > 使用 pg-promise 将 ColumnSet 列转换为几何

问题描述

我正在使用 pg-promise 创建一个ColumnSet对象,根据这个

const cs = new pgp.helpers.ColumnSet([
    {name: 'Id',prop: 'Id'},
    {name: 'Lat',prop: 'Lat'},
    {name: 'Lng',prop: 'Lng'},
    {name: 'CreationDateTime',prop: 'CreationDateTime'},
    {name: 'Topic',prop: 'Topic'},
    {name: 'UserId',prop: 'UserId'},
    {name: 'shape',mod: ':raw',prop: 'shape',def: 'point'},
    {name: 'UserName',prop: 'UserName'},
    {name: 'appName',prop: 'appName'},
    {name: 'appVersion',prop: 'appVersion'}
], {
    table: 'Location'
});

def: 'point'点是转换为几何的方法——这是一个值,或者我如何运行点方法并在此列(形状)中进行绑定?

并为批量插入编写此方法:

async function insertMany(values) {
    try {
        let results = await db.none(pgp.helpers.insert(values, cs));
    } catch (error) {
        console.log(error);
    }
}

为了转换 lat 和 lng 我写了这个方法:

const point = (lat, lng) => ({
    toPostgres: () => pgp.as.format('ST_SetSRID(ST_MakePoint($1, $2), 4326)', [Lag, Lng]),
    rawType: true
});

但我得到了这个错误:

TypeError: Values null/undefined cannot be used as raw text

根据此页面

原始文本变量以 :raw 或符号 ^ 结尾,并防止文本转义。此类变量不允许为 null 或 undefined,否则方法会抛出 TypeError = Values null/undefined cannot be used as raw text。

当不执行点方法时,该形状字段当然为空。

标签: node.jspostgresqlpg-promise

解决方案


首先,您正在滥用 option prop,该选项被记录为在目标属性名称与列名称不同时使用,这不是您的情况。

并且def,正如还记录的那样,表示缺少属性时的值。当该属性设置为nullor时,不使用undefined的值。def

您正在尝试覆盖结果值,这意味着您需要使用 property init

point另一个问题 - 您在实现切换案例中的变量。

总之,您的代码应如下所示:

const getPoint = col => {
    const p = col.value;
    // we assume that when not null, the property is an object of {lat, lng},
    // otherwise we will insert NULL.
    return p ? pgp.as.format('ST_SetSRID(ST_MakePoint(${lat}, ${lng}), 4326)', p) : 'NULL';
};

const cs = new pgp.helpers.ColumnSet([
    'Id',
    'Lat',
    'Lng',
    'CreationDateTime',
    'Topic',
    'UserId',
    {name: 'shape', mod: ':raw', init: getPoint},
    'UserName',
    'appName',
    'appVersion',
], {
    table: 'Location'
});

使用自定义类型格式的版本如下所示:

const getPoint = col => {
    const p = col.value;
    if(p) {
        return {
            toPostgres: () => pgp.as.format('ST_SetSRID(ST_MakePoint(${lat}, ${lng}), 4326)', p),
            rawType: true
           };
    }
    // otherwise, we return nothing, which will result into NULL automatically
};

const cs = new pgp.helpers.ColumnSet([
    'Id',
    'Lat',
    'Lng',
    'CreationDateTime',
    'Topic',
    'UserId',
    {name: 'shape', init: getPoint},
    'UserName',
    'appName',
    'appVersion',
], {
    table: 'Location'
});

推荐阅读