(args: BulkUpdateOptions<TTable, TIdCol, TValueCol>)
| 20 | }; |
| 21 | |
| 22 | export async function bulkUpdate< |
| 23 | TTable extends PgTable, |
| 24 | TIdCol extends PgColumn, |
| 25 | TValueCol extends PgColumn, |
| 26 | >(args: BulkUpdateOptions<TTable, TIdCol, TValueCol>): Promise<number> { |
| 27 | if (args.updates.length === 0) return 0; |
| 28 | |
| 29 | const idType = args.idColumn.getSQLType(); |
| 30 | const valueType = args.valueColumn.getSQLType(); |
| 31 | let totalRowCount = 0; |
| 32 | |
| 33 | for (const chunk of chunkArray(args.updates, args.chunkSize ?? 3000)) { |
| 34 | const valueColumnName = sql.identifier(args.valueColumn.name); |
| 35 | const updateResult = await args.tx.execute(sql` |
| 36 | UPDATE ${args.table} |
| 37 | SET ${valueColumnName} = v.new_value |
| 38 | FROM (VALUES ${sql.join( |
| 39 | chunk.map( |
| 40 | ({ id, value }) => sql`(${id}::${sql.raw(idType)}, ${value}::${sql.raw(valueType)})` |
| 41 | ), |
| 42 | sql`, ` |
| 43 | )}) AS v(id, new_value) |
| 44 | WHERE ${args.idColumn} = v.id |
| 45 | `); |
| 46 | totalRowCount += updateResult?.rowCount ?? 0; |
| 47 | } |
| 48 | |
| 49 | return totalRowCount; |
| 50 | } |
no test coverage detected