postgres:动态多次更新语法错误

问题描述 投票:0回答:1

获取 PostgresError:此查询的语法错误:

exports.updateMatches = async ({ payload: { matches } }) => {
  const formattedMatches = objArrToArr(matches);
  const cols = Object.keys(matches[0]);
  const colsWOId = cols
    .filter((item) => item !== "id")
    .map((item) => camelToSnake(item));
    
  return await sql`
        update matches
        set ${colsWOId.map((col) => `${sql(col)} = excluded.${sql(col)}`).join(", ")}
        from (values ${sql(formattedMatches)}) as excluded(${cols.join(", ")})
        where matches.id = (excluded.id):: int
            returning *;`;
};

注意:使用 postgres npm 包,它们不支持 sql.identifier()/sql.raw()。尝试遵循官方文档中的 sql 格式:

一个查询中的多个更新:

const users = [
  [1, 'John', 34],
  [2, 'Jane', 27],
]
await sql`
  update users set name = update_data.name, age = (update_data.age)::int
  from (values ${sql(users)}) as update_data (id, name, age)
  where users.id = (update_data.id)::int
  returning users.id, users.name, users.age
`     

来自库的错误详细信息:

PostgresError: syntax error at or near "FROM"
at ErrorResponse (/home/raf/apps/tourna-pro/api/node_modules/postgres/cjs/src/connection.js:788:26)
at handle (/home/raf/apps/tourna-pro/api/node_modules/postgres/cjs/src/connection.js:474:6)
at Socket.data (/home/raf/apps/tourna-pro/api/node_modules/postgres/cjs/src/connection.js:315:9)
at Socket.emit (node:events:519:28)
at addChunk (node:internal/streams/readable:559:12)
at readableAddChunkPushByteMode (node:internal/streams/readable:510:3)
at Readable.push (node:internal/streams/readable:390:5)
at TCP.onStreamRead (node:internal/stream_base_commons:191:23)
at cachedError (/home/raf/apps/tourna-pro/api/node_modules/postgres/cjs/src/query.js:170:23)
at new Query (/home/raf/apps/tourna-pro/api/node_modules/postgres/cjs/src/query.js:36:24)
at sql (/home/raf/apps/tourna-pro/api/node_modules/postgres/cjs/src/index.js:112:11)
at exports.updateMatches (/home/raf/apps/tourna-pro/api/src/service/tournament-format.js:139:24)
severity_local: 'ERROR',
severity: 'ERROR',
code: '42601',
position: '148',
file: 'scan.l',
line: '1242',
routine: 'scanner_yyerror'   
postgresql
1个回答
0
投票

你能尝试一下吗?

const updatedUsers = await sql`
  UPDATE users 
  SET name = update_data.name, 
      age = (update_data.age)::int
  FROM (VALUES ${sql(users.map(user => `(${user.join(',')})`))}) AS update_data (id, name, age)
  WHERE users.id = (update_data.id)::int
  RETURNING users.id, users.name, users.age;

您的错误主要似乎是由于没有正确处理用户输入数组

© www.soinside.com 2019 - 2024. All rights reserved.