使用 pg-promise 将 ColumnSet 列转换为几何图形

Convert a ColumnSet column into geometry with pg-promise

我正在创建 ColumnSet object with pg-promise, according to :

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);
    }
}

为了转换纬度和经度,我写了这个方法:

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

但是我得到了这个错误:

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

据此page

Raw-text variables end with :raw or symbol ^, and prevent escaping the text. Such variables are not allowed to be null or undefined, or the method will throw TypeError = Values null/undefined cannot be used as raw text.

不执行point方法时,当然那个shape字段为空

首先,您误用了选项 prop,当目标 属性 名称与列名称不同时使用 is documented,这不是您的情况。

def,也如文档所述,表示缺少 属性 时的值。当 属性 设置为 nullundefined 时,不使用 def 的值。

您正在尝试覆盖结果值,这意味着您需要使用 属性 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'
});

使用 Custom Type Formatting 的版本如下所示:

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'
});