All files / src insert-ignore.ts

82.14% Statements 23/28
50% Branches 3/6
100% Functions 5/5
80% Lines 20/25

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 6122x 22x 22x 22x 22x 22x 22x 22x           22x 10x     22x 20x                   22x                   10x       10x       10x 10x 10x   10x                 22x  
import and from './and.js'
import eq from './eq.js'
import id from './identifier.js'
import id_ from './limited-hints-identifier.js'
import inlineTableOfObjects from './inline-table-of-objects.js'
import keysOfObjects from './keys-of-objects.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'
 
export const sourcePrefixed =
  (_: Sid | string): Sid =>
    id([ 'Source', _ ])
 
export const targetPrefixed =
  (_: Sid | string): Sid =>
    id([ 'Target', _ ])
 
/**
 * @returns insert DML ignoring existing rows.
 *
 * If provided array of objects is empty, returns SELECT 0.
 *
 * Optional hits can be provided. Defaults to SERIALIZABLE hint.
 */
export const insertIgnore =
  (
    table: Sid | string,
    onKeys: string[],
    objects: Record<string, unknown>[],
    maybeObjectKeys?: string[],
    { hints = [ 'serializable' ] }: {
      hints?: TableHintLimited[]
    } = {}
  ): S => {
 
    Iif (!Array.isArray(objects)) {
      throw new TypeError(`Expected array of values, got ${objects}.`)
    }
 
    Iif (objects.length === 0) {
      return tsql`select 0;`
    }
 
    const objectKeys = maybeObjectKeys || keysOfObjects(objects)
    const on_ = and(...onKeys.map(_ => eq(sourcePrefixed(_), targetPrefixed(_))))
    const where_ = and(...onKeys.map(_ => eq(targetPrefixed(_), null)))
 
    return tsql`
      insert into ${id_(table, hints)} ${row(objectKeys.map(id))}
      select Source.*
      from ${inlineTableOfObjects('Source', objects, objectKeys)}
      left join ${id(table)} as Target on ${on_}
      where ${where_}
    `
  }
 
export default insertIgnore