在pg-promise中使用助手时如何设置列 [英] How to set columns when using helpers in pg-promise

查看:179
本文介绍了在pg-promise中使用助手时如何设置列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由node.js开发。我正在使用 pg-promise

Developed by node.js. I am using pg-promise.

插入以下数据时出现问题。

There is a problem with inserting the following data.

我想在下表中插入多行数据。

I want to insert multiple rows of data into the table below.

create table info (
  id varchar(20) not null,
  name varchar(20) not null,
  createdate timestamp with time zone not null
)

我在下面插入了数据。

let info = [
  { myid: '0001', myname: 'name1' },
  { myid: '0002', myname: 'name2' },
  { myid: '0003', myname: 'name3' },
]

我最初插入以下内容。

for (let i = 0; i <info.length; i ++) {
  db.none (`INSERT INTO info (id, name, createdate ') VALUES ($1, $2, CURRENT_TIMESTAMP)`, [info[i].id, info[i].name])
}

我想使用pg正确修复它

I want to fix it correctly using pg-promise.

const dataMulti = info
const cs = new pgp.helpers.ColumnSet(
[
  'id',
  'name',
  'createdate',
], {
  table: 'info',
})
await db.none(pgp.helpers.insert(dataMulti, cs))

此处,

1。当插入数据的键与时不同时,无法插入。表的列名称?


我知道有pgp.helpers.ColumnSet()

I know there is pgp.helpers.ColumnSet()

错误:属性'id'不存在。

Error: Property 'id' does not exist.

发生相同的错误。

我很好奇表列名称和
列设置的ColumnSet之间的关系。

I am curious about the relationship between table column names and ColumnSets for column settings.

2 。使用上面的助手时,如何在数据库中插入当前时间current_timestamp?

感谢您对两个问题的回答。

Thank you for your answers to the two questions.

推荐答案

以下 ColumnSet 纠正了所有问题:

const cs = new pgp.helpers.ColumnSet([
    {name: 'id', prop: 'myid'},
    {name: 'name', prop: 'myname'},
    {name: 'createdate', mod: '^', def: 'CURRENT_TIMESTAMP'}
], {
    table: 'info'
});

请参见专栏中提供了可用于配置各个列的内容。

See Column for what's available to configure individual columns.


CURRENT_TIMESTAMP 的应用很难理解...

the application of CURRENT_TIMESTAMP is difficult to understand...



{name: 'createdate', mod: '^', def: 'CURRENT_TIMESTAMP'}

这是名为 createdate 的列,默认值为 CURRENT_TIMESTAMP ,格式设置为 ^ (与:raw 相同),表示原始文本(无需转义)。除此之外, Column 类型对此进行了更详细的说明。

It is a column named createdate, with default value CURRENT_TIMESTAMP and formatting modifier ^ (same as :raw), which means raw text (no escaping needed). Other than that, Column type explains it in greater detail.

这篇关于在pg-promise中使用助手时如何设置列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆