【问题标题】:ColumnSet Helpers - using Raw only when defaultColumnSet Helpers - 仅在默认情况下使用 Raw
【发布时间】:2020-07-08 11:50:14
【问题描述】:

我正在尝试使用 ColumnSet 帮助程序来生成插入和更新查询,但是我有一个列,如果传入,我想使用 pg-promise query-formatter 格式化数据,否则默认为:raw (^) ,在本例中为 now()

代码示例如下:

const cs = new helpers.ColumnSet([
    'lastname',
    {
        name: 'rental_date',
        mod: '^',
        def: 'now()'
    }
], { table: { table: 'book_rental', schema: 'public' } })


let rental1 =
    {
        lastname: 'Mueller', rental_date: '2020-05-01T12:15:063Z'
    };

let rental2 =
    {
        lastname: 'Smith'
    };


let insert = helpers.insert(rental1, cs)

db.result(insert)
    .then(data => res.json({ message: 'Ok!' }))
    .catch(err => res.json({ message: 'Not ok!' }))

Rental1 应INSERT INTO (last_name, rental_date) VALUES ('Mueller', '2020-05-01T12:15:063Z' ),而Rental2 应INSERT INTO (last_name, rental_date) VALUES ('Smith', now() )。但是,这会引发错误,因为 Rental1 也被格式化为 :raw。

这可能是一个常见的用例,所以我可能会遗漏一些东西......我如何使用帮助器实现这一点,以便只有在触发默认值时才使用 :raw 模式?

【问题讨论】:

    标签: pg-promise


    【解决方案1】:

    From the Raw Text documentation:

    这样的变量不能是nullundefined,因为在这种情况下含义不明确,这些值会抛出错误Values null/undefined cannot be used as raw text

    默认值,通过属性def are documented 提供,仅在属性缺失时使用:

    属性的默认值,仅在源对象没有该属性时使用。

    这意味着你正在创造一个无法运作的逻辑矛盾。


    在您的情况下可以有任意数量的有效解决方案,因为库的语法非常灵活。以下只是一些您可以选择的示例。

    接近 1

    {
        name: 'rental_date',
        init: c => c.exists ? c.value : {toPostgres: () => 'now()', rawText: true}
    }
    

    方法 2

    {
        name: 'rental_date',
        mod: ':raw',
        init: c => c.exists ? pgp.as.text(c.value) : 'now()'
    }
    

    方法 3 - 干净且可重用的示例,使用现代语法:

    const rawText = text => ({toPostgres: () => text, rawText: true});
    
    {
        name: 'rental_date',
        init: c => c.value ?? rawText('now()')
    }
    

    方法4 - 混合使用def

    {
        name: 'rental_date',
        def: 'now()',
        mod: ':raw',
        init: c => c.exists ? pgp.as.text(c.value) : c.value
    }
    

    方法 5

    const rawText = text => ({toPostgres: () => text, rawText: true});
    
    {
        name: 'rental_date',
        def: rawText('now()')
    }
    

    ...等等。

    也许解决方案 5 最适合您的需求,它既干净又可重复使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-21
      • 2012-02-29
      • 2010-12-02
      • 2012-11-24
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多