为什么Knex无法正确识别Postgres数组列?

时间:2020-03-27 20:49:13

标签: arrays postgresql knex.js

我有一张看起来像下面的表:

create table if not exists gameTemplate00.construction (
    player          uuid                                constraint "[construction] Player foreign key"
                                                            references gameTemplate00.player(id),
    colony          uuid                                constraint "[construction] Colony foreign key"
                                                            references gameTemplate00.colony(id),
    location        text,                               -- All subcolonies at this location contribute to production
    investment      uint8   default 0                   not null,
    cost            uint8                               not null,
    history         uint8[3] default '{null,null,null}' not null,
    priority        uint2,
    allocation      allocation                          not null,
    repeat          boolean default false               not null,
    dispatch        text, -- what to do with the vessel once complete
    project         text,                               -- free form name for player, can be null
    constraint "[construction] Priority must be unique for a given subcolony" 
        unique(colony, location, priority)
);

当我查询它并使用以下命令从Knex获取结果时

            db('construction')
                .withSchema('gametemplate00')
                .where('colony', payload.colony)
                .where('location', payload.location)
            .then((constructionListResult: any) => {
                ws.send(JSON.stringify(constructionListResult));
                console.log(constructionListResult);
            })

它返回以下内容:

 {
    player: '5f43f33b-dba6-43ca-bc0c-0516e5d29968',
    investment: '0',
    cost: '1000',
    history: '{NULL,NULL,NULL}',
    priority: '4',
    allocation: { kind: 'percent', amount: 0.35 },
    repeat: false,
    dispatch: null,
    project: 'whenever'
  }

分配是一个jsonb域,它可以正确识别该域并为其构建json对象。但是该数组很烂,并显示为字符串。

这是因为我使用Knex进行了某些错误配置,还是根本无法识别postgresql数组列?对于我来说,这是最没有问题的示例,但是在其他方面,必须自己解决这些问题将成为真正的痛苦。

1 个答案:

答案 0 :(得分:1)

这与自定义类型数组有关(来自pguint postgres扩展)。尽管过去其他人在使用数组时遇到了麻烦,但这一点已经解决了很多年,并且看起来应该可以立即使用(对于内置类型)。

一个similar problem sheds light

Knex已经在使用另一个名为pg-types的库。如果我将其包含在代码中,则可以强制其将无符号整数视为适当的整数:

import * as pg from 'pg';

const newTypes = {
    INT1:     16522,
    UINT1:    16532,
    UINT2:    16542,
    UINT4:    16552,
    UINT8:    16562,
}

// add statements like below for each of the custom types

pg.types.setTypeParser(newTypes.UINT8, (value: string) => {
    return parseInt(value);
});

数据库中还为每种自定义类型提供了数组的oid,可以通过以下方式找到它们:

SELECT oid, typname FROM pg_catalog.pg_type where typname like '_uint%';

但是我不清楚如何将它们实际解析为适当的数组。如果/当我知道答案时,我会更新答案。