Created
June 29, 2020 15:24
-
-
Save dennbagas/8f1fe6a7ef77dd39f6ba6f4ee4a88970 to your computer and use it in GitHub Desktop.
Postgres UPDATE multiple Row and Value Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type UpdateTuple = [primary, value_a, value_b]; | |
async updateMultiple(data: UpdateTuple[]) { | |
return this.manager.transaction(async (transactionalManager) => { | |
if (data.length === 0) { | |
throw 'data cannot be empty'; | |
} | |
// generate parameter index for pgsql query | |
const paramsIndex = data.map((v, i) => { | |
const index = v.map((_, j) => '$' + (i + i + j + 1)); | |
return `(${index})`; | |
}); | |
// flatten the data to make odd even order | |
const parameters = flatten(data); // using lodash.flatten() | |
const queryResult = await transactionalManager.query( | |
`UPDATE table_name AS u SET primary = u2.primary, column_a = u2.column_a, column_b = u2.column_b FROM (VALUES ` + | |
`${paramsIndex}` + | |
`) AS u2(primary, column_a, column_b) WHERE u2.primary = u.primary RETURNING u.primary, u.column_a, u.column_b;`, | |
parameters | |
); | |
// result query: | |
// UPDATE table_name AS u | |
// SET primary = u2.primary, column_a = u2.column_a, column_b = u2.column_b | |
// FROM (VALUES | |
// ($1,$2,$3), | |
// ($4,$5,$6) | |
// ) AS u2(primary, column_a, column_b) | |
// WHERE u2.primary = u.primary | |
// RETURNING u.primary, u.column_a, u.column_b; | |
// -- PARAMETERS: [1,"hello","world",2,"multiple","row update"] | |
return { returning: queryResult[0], affectedRow: queryResult[1] }; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment