All files / src assign-object.ts

95% Statements 19/20
100% Branches 3/3
100% Functions 1/1
94.73% Lines 18/19

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 4422x 22x 22x 22x 22x                     10x 10x 10x 22x 3x 3x             3x   19x   10x 1x         1x   10x     22x  
import assign from './assign.js'
import id from './identifier.js'
import jsonPath from './json-path.js'
import list from './list.js'
import tsql from './template.js'
import type S from './sanitised.js'
 
/**
 * @returns assigment clause based on provided record, ie. for UPDATE SET.
 *
 * `undefined` entries are filtered out.
 *
 * Propagates undefined if there are no non-undefined entries.
 */
export function assignObject(record: Record<string, unknown>): undefined | S {
  const assignments: (undefined | S)[] = []
  const jsonAssignments: Record<string, S> = {}
  for (const [ lvalue, rvalue ] of Object.entries(record)) {
    if (lvalue.indexOf('->') !== -1) {
      const [ llvalue, lrvalue ] = lvalue.split('->')
      jsonAssignments[llvalue] = tsql`
        json_modify(
          ${jsonAssignments[llvalue] ?? id(llvalue)},
          ${jsonPath(lrvalue)},
          ${rvalue}
        )
      `
      continue
    }
    assignments.push(assign(id(lvalue), rvalue))
  }
  for (const [ lvalue, rvalue ] of Object.entries(jsonAssignments)) {
    const a = assign(id(lvalue), tsql`
      (
        ${rvalue}
      )
    `)
    assignments.push(a)
  }
  return list(assignments, undefined, ',\n')
}
 
export default assignObject