All files / src insert-objects.ts

91.66% Statements 22/24
80% Branches 4/5
100% Functions 3/3
90.47% Lines 19/21

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 5322x 22x 22x 22x 22x 22x 22x                       22x           7x       7x 1x     6x 6x 6x   6x 2x             1107x 4x           22x  
import auto from './auto.js'
import id from './identifier.js'
import inlineTableOfObjects from './inline-table-of-objects.js'
import keysOfObjects from './keys-of-objects.js'
import list from './list.js'
import row from './row.js'
import tsql from './template.js'
import type S from './sanitised.js'
import type Sid from './sanitised-identifier.js'
 
/**
 * @returns multiple row insert DML.
 *
 * @see insertIgnore for DML which ignores existing rows.
 *
 * @see insertNotMatched for DML which ignores existing rows using MERGE statement.
 */
export const insertObjects =
  (
    table: Sid | string,
    objects: Record<string, unknown>[],
    maybeKeys?: string[]
  ): S => {
 
    Iif (!Array.isArray(objects)) {
      throw new TypeError(`Expected array of values, got ${objects}.`)
    }
 
    if (objects.length === 0) {
      return tsql`select 0;`
    }
 
    const table_ = id(table)
    const keys = maybeKeys ?? keysOfObjects(objects)
    const keys_ = list(keys.map(id))
 
    if (objects.length > 1000) {
      return tsql`
        insert into ${table_} (${keys_})
        select Source.*
        from ${inlineTableOfObjects('Source', objects, keys)}
      `
    }
 
    const values_ = list(objects.map(object => row(keys.map(key => auto(object[key])))))
    return tsql`
      insert into ${table_} (${keys_})
      values ${values_}
    `
  }
 
export default insertObjects