All files / src/utils sql.ts

94.74% Statements 18/19
83.33% Branches 5/6
100% Functions 6/6
93.75% Lines 15/16
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  1x 6x 1x 16x 16x 31x     31x 31x 11x   20x 20x   16x 31x 31x       16x                      
import * as pg from "pg";
 
type IndexGetter = (value: any) => string;
 
export const SQLFragment = (parts: TemplateStringsArray, ...inValues: any[]) => (
  getValueIndex: IndexGetter,
): strinIg =>
  parts.reduce((prev, curr, valIdx) => `${prev}${getValueIndex(inValues[valIdx - 1])}${curr}`);
 
export const SQL = (parts: TemplateStringsArray, ...inValues: any[]): pg.QueryConfig => {
  const outValues: any[] = [];
 
  const getValueIndex = (value: any): string => {
    if (value == null) {
      return `NULL`;
    }
    const found = outValues.indexOf(value);
    if (found > -1) {
      return `$${found + 1}`;
    }
    outValues.push(value);
    return `$${outValues.length}`;
  };
 
  const outText = parts.reduce((prev, curr) => {
    const value = inValues.shift();
    return typeof value === "function"
      ? `${prev}${value(getValueIndex)}${curr}`
      : `${prev}${getValueIndex(value)}${curr}`;
  });
 
  return { text: outText, values: outValues };
};