-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
af50ce9
commit 14b9ba9
Showing
3 changed files
with
15 additions
and
42 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,39 +1,8 @@ | ||
import Knex, { Knex as IKnex } from 'knex'; | ||
import Knex from 'knex'; | ||
import knexConfig from '../../../knexfile'; | ||
|
||
const environment = process.env.NODE_ENV || 'development'; | ||
const cfg = knexConfig[environment]; | ||
const knex = Knex(cfg); | ||
|
||
export default knex; | ||
|
||
export async function batchUpdate( | ||
trx: IKnex.Transaction, | ||
tableName: string, | ||
records: any, | ||
fields: string[] | ||
) { | ||
if (records.length === 0) return; | ||
const stringListUpdates = records | ||
.map((record: any) => { | ||
const values = fields.map((field) => { | ||
if (record[field]?.type === 'timestamp') { | ||
return `to_timestamp(${record[field].value})`; | ||
} | ||
|
||
if (record[field] !== undefined) { | ||
return `'${record[field]}'`; | ||
} | ||
return 'NULL'; | ||
}); | ||
return `(${record.id}, ${values.join(', ')})`; | ||
}) | ||
.join(','); | ||
const query = ` | ||
UPDATE ${tableName} | ||
SET ${fields.map((field) => `${field} = temp.${field}`).join(', ')} | ||
FROM (VALUES ${stringListUpdates}) AS temp(id, ${fields.join(', ')}) | ||
WHERE temp.id = ${tableName}.id | ||
`; | ||
await trx.raw(query); | ||
} |
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
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