Last active
October 3, 2020 16:27
-
-
Save friendlyanon/49ba6bf7f8b44b97d347dac1f69d7eae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const arrayMarker = Symbol("sql.array"); | |
export interface ArraySqlReplacement { | |
[arrayMarker]: true; | |
array: any[]; | |
joiner: string; | |
} | |
const isArraySqlReplacement = (value: any): value is ArraySqlReplacement => | |
typeof value === "object" && value !== null && value[arrayMarker]; | |
export function sql( | |
fragments: TemplateStringsArray, | |
...values: any[] | |
): [string, any[]] { | |
const fragmentsIt = fragments[Symbol.iterator](); | |
const strings = [fragmentsIt.next().value]; | |
const bindings = []; | |
let index = 1; | |
for (const value of values) { | |
if (isArraySqlReplacement(value)) { | |
const { array, joiner } = value; | |
strings.push(array.map(() => "$" + index++).join(joiner)); | |
bindings.push(...array); | |
} else { | |
strings.push("$" + index++); | |
bindings.push(value); | |
} | |
strings.push(fragmentsIt.next().value); | |
} | |
return [strings.join(""), bindings]; | |
} | |
sql.array = (array: any[], joiner: string = ", "): ArraySqlReplacement => | |
({ [arrayMarker]: true, array, joiner }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment