All files / src merge-1n.ts

88.23% Statements 15/17
75% Branches 3/4
100% Functions 1/1
87.5% Lines 14/16

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 4622x 22x 22x 22x 22x             22x                 5x 5x 5x 5x     5x 1x   4x                             22x  
import id from './identifier.js'
import inlineTable from './inline-table-of-column.js'
import limitedHintsIdentifier from './limited-hints-identifier.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'
 
/** @returns MERGE DML synchronising 1-n relation. */
export const merge1n =
  (
    table: Sid | string,
    [ lcolumn, rcolumn ]: [ Sid | string, Sid | string ],
    lid: unknown,
    values: unknown[],
    { hints = [ 'serializable' ] }: {
      hints?: TableHintLimited[]
    } = {}
  ): S => {
    const table_ = limitedHintsIdentifier(table, hints)
    const lcolumn_ = id(lcolumn)
    const rcolumn_ = id(rcolumn)
    Iif (!Array.isArray(values)) {
      throw new TypeError(`Expected array of values, got ${values}.`)
    }
    if (values.length === 0) {
      return tsql`delete from ${table_} where ${lcolumn_} = ${lid};`
    }
    return tsql`
      merge ${table_} as ${id('Target')}
      using ${inlineTable('Source', 'id', values)}
      on (
        ${id([ 'Target', lcolumn ])} = ${lid} and
        ${id([ 'Target', rcolumn ])} = ${id([ 'Source', 'id' ])}
      )
      when not matched by target then
        insert ${row([ lcolumn_, rcolumn_ ])}
        values ${row([ lid, id('Source.id') ])}
      when not matched by source and ${id([ 'Target', lcolumn ])} = ${lid} then
        delete;
    `
  }
 
export default merge1n