如何使用nodejs pg-promise库将带有uuid数组的记录插入到pg表中

Tal*_*Tal 5 database postgresql uuid node.js promise

我需要在我的数据库中有一个表,其中包含一个列,这是一个uuid对象数组(uuid []类型)

但是当我尝试使用名为pg-promise的nodejs库插入它时它失败了

我收到以下错误消息告诉我,我需要重写演员或表达式

{"name":"error","length":206,"severity":"ERROR","code":"42804","hint":"You will need to rewrite or cast the expression.","position":"230","file":"src\\backend\\parse
r\\parse_target.c","line":"510","routine":"transformAssignedExpr"}
Run Code Online (Sandbox Code Playgroud)

这很奇怪,因为当我尝试在同一个精确的表上输入单个uuid到另一个列时我绝对没有问题(意思是,我没有代表uuid的问题,顺便说一下我从另一个lib创建它们作为文本变量,但是他们是普通的旧文本变量)

当我尝试将TEXT对象数组输入到同一列时(如果我将表更改为具有TEXT []列而不是UUID []列,我也没有问题)

这是我的代码

////////////////

var Promise = require('bluebird');
var pgpLib = require('pg-promise');
var pgp = pgpLib();
var cn = confUtil.pgDbConnectionConfiguration();
var db = pgp(cn);

//////////////////

var newEntity={};
newEntity.hash      = uuid.v4();    
newEntity.location  = {X:2394876,Y:2342342};
newEntity.mother    = uuid.v4();
newEntity.timestamp = Date.now();
newEntity.content   = {content:"blah"};
newEntity.sobList   = [uuid.v4(),uuid.v4(),uuid.v4()];
addEntity (newEntity);

////////////////////

function addEntity(newEntity) {
    var insertEntityQueryPrefix='insert into entities (';
    var insertEntityQueryMiddle=') values (';
    var insertEntityQueryPostfix="";
    var insertEntityQuery="";

    Object.keys(newEntity).forEach(function(key){
        insertEntityQueryPrefix=insertEntityQueryPrefix+'"'+key+'",';
        insertEntityQueryPostfix=insertEntityQueryPostfix+'${'+key+'},';
    });
    insertEntityQueryPrefix=insertEntityQueryPrefix.slice(0,-1);
    insertEntityQueryPostfix=insertEntityQueryPostfix.slice(0,-1)+")";  
    insertEntityQuery=insertEntityQueryPrefix+insertEntityQueryMiddle+insertEntityQueryPostfix;

    //longStoryShort  this is how the query template i used looked like
    /*
        "insert into entities ("hash","location","mother","timestamp","content","sobList") values (${hash},${location},${mother},${timestamp},${content},${sobList})"
    */
    //and this is the parameters object i fed to the query i ran it when it failed
    /*
        {
            "hash": "912f6d85-8b47-4d44-98a2-0bbef3727bbd",
            "location": {
                "X": 2394876,
                "Y": 2342342
            },
            "mother": "87312241-3781-4d7c-bf0b-2159fb6f7f74",
            "timestamp": 1440760511354,
            "content": {
                "content": "bla"
            },
            "sobList": [
                "6f2417e1-b2a0-4e21-8f1d-31e64dea6358",
                "417ade4b-d438-4565-abd3-a546713be194",
                "e4681d92-0c67-4bdf-973f-2c6a900a5fe4"
            ]
        }
    */

    return db.tx(function () {
        var processedInsertEntityQuery = this.any(insertEntityQuery,newEntity);
        return Promise.all([processedInsertEntityQuery])
    })
    .then(
        function (data) {
            return newEntity;
        }, 
        function (reason) {
            throw new Error(reason);
        });
}
Run Code Online (Sandbox Code Playgroud)

vit*_*y-t 4

插入 UUID 数组是一种特殊情况,需要显式类型转换,因为您将 UUIDuuid[]作为文本字符串数组传递到类型中。

您需要更改您的INSERT查询:替换${sobList}${sobList}::uuid[]. 这将指示 PostgeSQL 将字符串数组转换为 UUID 数组。

与您的问题无关,您在执行单个请求时不需要使用Promise.allinside 。db.tx您可以简单地从插入请求返回结果:

return this.none(insertEntityQuery,newEntity);
Run Code Online (Sandbox Code Playgroud)

尽管使用事务来执行单个请求同样毫无意义:)

更新

最新版本的pg-promise支持自定义类型格式化,因此您可以编写自己的自定义类型来进行查询格式化,从而避免显式类型转换。

对于在数组中使用 UUID-s 的示例,您可以实现自己的 UUID 类型:

const UUID = a => ({rawType = true, toPostgres = () => a.v4()});
Run Code Online (Sandbox Code Playgroud)

对于任何uuidValue数组或单独的内容,您都可以使用UUID(uuidValue)自动格式化。