All files / src modify-jsons.ts

86.48% Statements 32/37
0% Branches 0/1
100% Functions 10/10
87.09% Lines 27/31

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 6322x 22x 22x 22x 22x 22x     22x 22x           22x 7x     22x 6x     22x 2x       5x       22x         2x       2x 2x 4x 4x 2x 4x 2x     2x   2x                 22x  
import and from './and.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 tsql from './template.js'
import type S from './sanitised.js'
import type Sid from './sanitised-identifier.js'
import list from './list.js'
import assign from './assign.js'
 
export type Where = Record<string, unknown>
export type Update = Record<string, Record<string, unknown>>
 
export const sourcePrefixed =
  (_: Sid | string): Sid =>
    id([ 'Source', _ ])
 
export const targetPrefixed =
  (_: Sid | string): Sid =>
    id([ 'Target', _ ])
 
export const modify =
  (column: string, jsonKeys: string[]): S =>
    assign(
      targetPrefixed(column),
 
      // eslint-disable-next-line sonarjs/no-nested-template-literals
      jsonKeys.reduce((_, jsonKey) => tsql`json_modify(${_}, ${`$.${jsonKey}`}, json_query(${sourcePrefixed(column)}, ${`$.${jsonKey}`}))`, targetPrefixed(column) as S)
    ) as S
 
/** @returns MERGE DML for json columns, multiple rows via JSON_MODIFY and JSON_QUERY. */
export const modifyJsons = (
  table: Sid | string,
  entries: readonly Record<string, unknown>[]
): S => {
 
  Iif (entries.length === 0) {
    return tsql`select 0;`
  }
 
  const table_ = id(table)
  const objectKeys = keysOfObjects(entries)
  const onKeys = objectKeys.filter(_ => !_.endsWith('Json'))
  const jsonColumns = objectKeys.filter(_ => _.endsWith('Json'))
  const update_ = list(jsonColumns.map(jsonColumn => {
    const jsonKeys = keysOfObjects(entries.map(_ => _[jsonColumn] as Record<string, unknown>))
    return modify(jsonColumn, jsonKeys)
  }))
 
  const on_ = and(...onKeys.map(_ => eq(sourcePrefixed(_), targetPrefixed(_))))
 
  return tsql`
    merge ${table_} as ${id('Target')}
    using ${inlineTableOfObjects('Source', entries, objectKeys)}
    on ${on_}
    when matched then
      update set ${update_};
  `
}
 
export default modifyJsons