带有 pg-promise 的复合类型

Composite types with pg-promise

这是一个示例代码:

battle.heroes = [{ id: hero.id, name: hero.name }]; //This is my array I want to insert
await db.one('INSERT INTO battles(mode, params, heroes) VALUES(${mode}, ${params}, ${heroes}) RETURNING id', {
    mode: battle.mode,
    params: battle.params,
    heroes: battle.heroes,
});

PostgreSQL 类型 'hero_info':

id int4
name varchar

通过 Custom Type Formatting 显示每个数组元素,方法是使用 rawTypetoPostgres 扩展现有对象,或者使用您自己的自定义类型,如下所示:

const hero = (id, name) => ({
   rawType: true,
   toPostgres: () => pgp.as.format('(, )::hero_info', [id, name])
});

用法示例:

const heroes = [hero(1, 'first'), hero(2, 'second')];

await db.one('INSERT INTO battles(mode, params, heroes) VALUES(${mode}, ${params}, ${heroes}) RETURNING id', {
    mode: battle.mode,
    params: battle.params,
    heroes
});

对于上面的代码,您的 heros 数组将正确格式化为:

array[(1, 'first')::hero_info, (2, 'second')::hero_info]