如何使用nodejs pg-promise库

时间:2015-08-28 11:34:44

标签: database node.js postgresql promise uuid

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

但是当我尝试使用名为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"}
这很奇怪 因为当我尝试在同一个精确的表上输入单个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);
        });
}

1 个答案:

答案 0 :(得分:3)

插入UUID-s数组是一种需要显式类型转换的特殊情况,因为您将UUID-s作为文本字符串数组传递给类型uuid[]

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

与您的问题无关,在执行一个请求时,您无需在Promise.all内使用db.tx。您只需返回插入请求的结果:

return this.none(insertEntityQuery,newEntity);

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

<强>更新

pg-promise的最新版本支持Custom Type Formatting,因此您可以为查询格式编写自己的自定义类型,避免使用显式类型转换。

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

function UUID(value) {
    this.uuid = value;
    this.rawType = true; // force raw format on output;
    this.toPostgres = function () {
        return this.uuid.v4();
    };
}