How to set columns when using helpers in pg-promise

核能气质少年 提交于 2019-12-08 05:46:40

问题


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
)

I inserted the data below.

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

I originally inserted the following.

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])
}

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))

Here,

1. Can not insert when the key of the insert data is different from the . columns name of the table?

I know there is pgp.helpers.ColumnSet()

Error: Property 'id' does not exist.

The same error occurs.

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

2. When using the helpers above, how do I insert the current time current_timestamp in the database?

Thank you for your answers to the two questions.


回答1:


The following ColumnSet corrects all your problems:

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.

the application of CURRENT_TIMESTAMP is difficult to understand...

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

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.



来源:https://stackoverflow.com/questions/46260641/how-to-set-columns-when-using-helpers-in-pg-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!