Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x | import and from './and.js'
import assign from './assign.js'
import eq from './eq.js'
import id from './identifier.js'
import inlineTableOfObjects from './inline-table-of-objects.js'
import keysOfObjects from './keys-of-objects.js'
import limitedHintsIdentifier from './limited-hints-identifier.js'
import list from './list.js'
import row from './row.js'
import tsql from './template.js'
import type { TableHintLimited } from './table-hint-limited.js'
import type S from './sanitised.js'
import type Sid from './sanitised-identifier.js'
const sourcePrefixed = (_: string): Sid => id([ 'Source', _ ])
const targetPrefixed = (_: string): Sid => id([ 'Target', _ ])
/** @returns merge dml that replaces target table with inlined source table. */
export const replaceObjects =
(
table: string | Sid,
onKeys: string[],
objects: readonly Record<string, unknown>[],
maybeObjectKeys?: string[],
maybeUpdateKeys?: string[],
maybeInsertKeys?: string[],
{ hints }: {
hints?: TableHintLimited[]
} = {}
): S => {
Iif (!Array.isArray(objects)) {
throw new TypeError(`Expected array of values, got ${objects}.`)
}
const table_ = limitedHintsIdentifier(table, hints)
Iif (objects.length === 0) {
return tsql`delete from ${table_};`
}
const objectKeys = maybeObjectKeys || keysOfObjects(objects)
const updateKeys = maybeUpdateKeys || objectKeys
const insertKeys = maybeInsertKeys || objectKeys
const update_ = list(updateKeys.map(_ => assign(_, sourcePrefixed(_))))
const on_ = and(...onKeys.map(_ => eq(sourcePrefixed(_), targetPrefixed(_))))
return tsql`
merge ${table_} as Target
using ${inlineTableOfObjects('Source', objects, objectKeys)}
on ${on_}
when not matched by source then
delete
when matched then
update set ${update_}
when not matched by target then
insert ${row(insertKeys.map(id))}
values ${row(insertKeys.map(sourcePrefixed))};
`
}
export default replaceObjects
|