Postgresql pg promise助手插入插入时跳过的替代方法是什么?

Postgresql pg promise助手插入插入时跳过的替代方法是什么?,postgresql,pg-promise,Postgresql,Pg Promise,我正在使用pg promise生成helpers.insert和helpers.update的插入和更新 更新工作正常,但我一直遇到与此问题类似的问题: i、 e.具有postgresql默认值的可选列会在输入数据上不存在属性时导致helpers.insert引发错误。在更新时,这会触发跳过功能,这很好,但正如文档所示,跳过不适用于插入,因此它会出错 const input = { yup: true }; const query = this.pgp.helpers.insert( in

我正在使用pg promise生成helpers.insert和helpers.update的插入和更新

更新工作正常,但我一直遇到与此问题类似的问题:

i、 e.具有postgresql默认值的可选列会在输入数据上不存在属性时导致helpers.insert引发错误。在更新时,这会触发跳过功能,这很好,但正如文档所示,跳过不适用于插入,因此它会出错

const input = { yup: true };

const query = this.pgp.helpers.insert(
  input,
  new this.pgp.helpers.ColumnSet(
    [
      { name: 'yup', skip: (col) => !col.exists },
      { name: 'nope', skip: (col) => !col.exists },
我很奇怪为什么skip不能在insert上工作?我有没有别的选择

使用def似乎有点冒险,因为我想使用postgresql默认值,而不是覆盖它们

我在互联网上搜寻,甚至在2016年发现@vitaly-t使用跳过功能回答了相同的问题,该功能后来似乎从helpers.insert中删除


所以我被卡住了。如何使相同的跳过功能适用于插入?

因此,如果有人发现自己处于相同的位置,我会想到以下方法:

export function column(name: string, prop?: string): IColumnConfig {
  return {
    name: name,
    prop: prop,
    skip: (col) => !col.exists,
  };
}
我不能说这是最优雅的方法。
但是它实现了我想要实现的目标。

跳过逻辑不会为插入增加任何价值,这就是为什么它不用于插入。它仅用于可以存在条件列的更新。对于insert,只需重用现有的ColumnSet对象,使用method.Hi vitaly-t重新定义这些列,我可能遗漏了一些东西,但我的insert中有很多可选列。它们是布尔值,默认为各种真/假状态,我希望能够在输入对象中省略它们,并具有与更新相同的行为。目前,我必须明确定义所有这些。它是有效的,但它是postgresql已经为我做的很多样板。foo boolean NOT NULL DEFAULT false、bar boolean NOT NULL DEFAULT true、baz boolean NOT NULL DEFAULT false,您缺少的是,对于插入,值与列名列表绑定。不能跳过其中一个,不能跳过另一个。而对于更新,它只是一组赋值,这就是使跳过逻辑成为可能的原因。我想我仍然有一个使用skip的单一插入的用例。因此,我有一个带有布尔值、默认值和可选fk关系的表。我在JS服务方法中没有得到fk id,我得到了uuid,所以我插入了一个子选择来插入我需要的fk。插入到foo a、b、c值中,从栏中选择id,其中。。。因为我在FK存在或不存在的地方有不同的插入,所以我必须为每个组合设置一个列。动态构建将是理想的,这正是skip功能所提供的。
export function relationship(
  table: string,
  name: string,
  prop?: string,
): IColumnConfig {
  return {
    name: name,
    prop: prop,
    mod: ':raw',
    init: (col) => {
      if (!col.exists || isEmpty(col.value)) {
        return 'NULL';
      }
      return `(SELECT ${table}.id FROM ${table} WHERE ${table}.uuid = $<${col.name}>)`;
    },
    skip: (col) => !col.exists,
  };
}
    const insert =
      this.pgp.helpers.insert(
        input,
        new this.pgp.helpers.ColumnSet(
          [
            relationship('bar', 'bar', 'barID'),
            { name: 'name' },
            { name: 'is_a', prop: 'isA', def: false },
            { name: 'is_b', prop: 'isB', def: false },
            { name: 'is_c', prop: 'isC', def: false },
            relationship('baz', 'baz', 'bazID'), // optional
          ],
          { table: 'foo' },
        ),
      ) +
      `
      RETURNING ${select}
      `;

    return await this.db.one(insert, input);