diff --git a/backend/db.js b/backend/db.js index 8e2ddbd..2118d88 100644 --- a/backend/db.js +++ b/backend/db.js @@ -85,10 +85,21 @@ if (usePostgres) { prepare(sql) { const pgSql = convertPlaceholders(sql); return { - run: (...params) => client.query(pgSql, params).then(result => ({ - changes: result.rowCount, - lastInsertRowid: result.rows[0]?.id || null, - })), + run: (...params) => { + // BUGFIX (v8): lastInsertRowid innerhalb der Transaktion — + // identische RETURNING-Logik wie im outer prepare(). Ohne + // RETURNING id liefert pg keine rows → lastInsertRowid war + // null → Folge-Inserts (task_values mit task_id=null) schlugen + // mit FK-Verstoß fehl (500 beim Abschicken einer Vorlage). + const isInsert = pgSql.trim().toUpperCase().startsWith('INSERT'); + const finalSql = isInsert && !pgSql.toUpperCase().includes('RETURNING') + ? pgSql.replace(/;?\s*$/, ' RETURNING id') + : pgSql; + return client.query(finalSql, params).then(result => ({ + changes: result.rowCount, + lastInsertRowid: result.rows[0]?.id || null, + })); + }, get: (...params) => client.query(pgSql, params).then(result => result.rows[0] || null), all: (...params) => client.query(pgSql, params).then(result => result.rows), };