如何在事务中插入多行(来自请求正文)
How to insert multiple rows (from a req. body) in a transaction
请问有没有办法通过req插入多行。正文(来自前端)。我设法创建了一种插入一行的方法,但如果可能的话,我想插入多行 task
而只插入一次 job
。
我读到过一种方法是使用 json 数组并循环它,但不知道该怎么做。如果你有其他方法,那也是一个很大的帮助!
我目前正在使用 node.js / express.js 作为后端,并使用 node-postgres 作为与数据库的连接。
//2. Declare an asynchronous function for the PG transaction
async function execute() {
// Promise chain for pg Pool client
const client = await pool
.connect()
.catch(err => {
console.log("\nclient.connect():", err.name);
// iterate over the error object attributes
for (item in err) {
if (err[item] = undefined) {
process.stdout.write(item + " - " + err[item] + " ");
}
}
//end the Pool instance
console.log("\n");
process.exit();
});
try {
//Initiate the Postgres transaction
await client.query("BEGIN");
try {
const sqlString = `WITH INSERTED AS (
INSERT INTO jobs (job_name) VALUES
() RETURNING id)
INSERT INTO tasks(
employee_id, job_id) VALUES
(,(
SELECT id FROM inserted
))`;
const sqlValues = [job_name, employee_id
];
// Pass SQL string to the query() method
await client.query(sqlString, sqlValues, function(err, result) {
console.log("client.query() SQL result:", result);
if (err) {
console.log("\nclient.query():", err);
// Rollback before executing another transaction
client.query("ROLLBACK");
console.log("Transaction ROLLBACK called");
} else {
client.query("COMMIT");
console.log("client.query() COMMIT row count:", result.rowCount);
}
});
} catch (er) {
// Rollback before executing another transaction
client.query("ROLLBACK");
console.log("client.query():", er);
console.log("Transaction ROLLBACK called");
}
} finally {
client.release();
console.log("Client is released");
}
}
execute();
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
});
谢谢!
在第二个 INSERT 和 UNNEST() 中使用 SELECT 从数组中获取所有项目:
WITH INSERTED AS (
INSERT INTO jobs (job_name)
VALUES()
RETURNING id
)
INSERT INTO tasks(employee_id, job_id)
SELECT UNNEST() -- PostgreSQL array input, you might need another function for your type of input
, id
FROM inserted;
编辑:使用一些 json 对象作为输入的示例:
WITH INSERTED AS (
INSERT INTO jobs (job_name)
VALUES(::json #>> '{name}') -- selects the name from the json object as TEXT
RETURNING id
)
INSERT INTO tasks(employee_id, job_id)
SELECT column1
, id
FROM inserted
, json_to_recordset(::json #> '{tasks}') AS t(column1 int, column2 text);
$1 是单个 json-对象,它被使用了两次。 PostgreSQL 将提取 INSERT 所需的元素。
请问有没有办法通过req插入多行。正文(来自前端)。我设法创建了一种插入一行的方法,但如果可能的话,我想插入多行 task
而只插入一次 job
。
我读到过一种方法是使用 json 数组并循环它,但不知道该怎么做。如果你有其他方法,那也是一个很大的帮助!
我目前正在使用 node.js / express.js 作为后端,并使用 node-postgres 作为与数据库的连接。
//2. Declare an asynchronous function for the PG transaction
async function execute() {
// Promise chain for pg Pool client
const client = await pool
.connect()
.catch(err => {
console.log("\nclient.connect():", err.name);
// iterate over the error object attributes
for (item in err) {
if (err[item] = undefined) {
process.stdout.write(item + " - " + err[item] + " ");
}
}
//end the Pool instance
console.log("\n");
process.exit();
});
try {
//Initiate the Postgres transaction
await client.query("BEGIN");
try {
const sqlString = `WITH INSERTED AS (
INSERT INTO jobs (job_name) VALUES
() RETURNING id)
INSERT INTO tasks(
employee_id, job_id) VALUES
(,(
SELECT id FROM inserted
))`;
const sqlValues = [job_name, employee_id
];
// Pass SQL string to the query() method
await client.query(sqlString, sqlValues, function(err, result) {
console.log("client.query() SQL result:", result);
if (err) {
console.log("\nclient.query():", err);
// Rollback before executing another transaction
client.query("ROLLBACK");
console.log("Transaction ROLLBACK called");
} else {
client.query("COMMIT");
console.log("client.query() COMMIT row count:", result.rowCount);
}
});
} catch (er) {
// Rollback before executing another transaction
client.query("ROLLBACK");
console.log("client.query():", er);
console.log("Transaction ROLLBACK called");
}
} finally {
client.release();
console.log("Client is released");
}
}
execute();
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
});
谢谢!
在第二个 INSERT 和 UNNEST() 中使用 SELECT 从数组中获取所有项目:
WITH INSERTED AS (
INSERT INTO jobs (job_name)
VALUES()
RETURNING id
)
INSERT INTO tasks(employee_id, job_id)
SELECT UNNEST() -- PostgreSQL array input, you might need another function for your type of input
, id
FROM inserted;
编辑:使用一些 json 对象作为输入的示例:
WITH INSERTED AS (
INSERT INTO jobs (job_name)
VALUES(::json #>> '{name}') -- selects the name from the json object as TEXT
RETURNING id
)
INSERT INTO tasks(employee_id, job_id)
SELECT column1
, id
FROM inserted
, json_to_recordset(::json #> '{tasks}') AS t(column1 int, column2 text);
$1 是单个 json-对象,它被使用了两次。 PostgreSQL 将提取 INSERT 所需的元素。