Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/database/pool/multi-insert.ts
Views: 687
/*1The pg driver doesn't support inserting multiple rows in a single2query. There is a simple workaround at34https://github.com/brianc/node-postgres/issues/957#issuecomment-42685239356which I think would work for up to 100000/n rows, n is the number of values.7I copied it here.89Example:1011var videos = [["Peru is a nice country.", "limaGuy"], ["Breaking bad is a great show.", "mikeGuy"], ["I like the winter.", "novemberGuy"]]1213Query(14`INSERT INTO videos (title, author) VALUES ${expand(videos.length, 2)}`,15flatten(videos)16)17*/1819// expand(3, 2) returns "($1, $2), ($3, $4), ($5, $6)"20function expand(rowCount: number, columnCount: number, startAt = 1): string {21let index = startAt;22return Array(rowCount)23.fill(0)24.map(25() =>26`(${Array(columnCount)27.fill(0)28.map(() => `$${index++}`)29.join(", ")})`30)31.join(", ");32}3334// flatten([[1, 2], [3, 4]]) returns [1, 2, 3, 4]35function flatten(arr: any[][]): any[] {36const newArr: any[] = [];37arr.forEach((v) => v.forEach((p) => newArr.push(p)));38return newArr;39}4041export default function format(42query: string, // the usual query, but without the VALUES part, e.g., "INSERT INTO videos (title, author)".43values: any[][] // the values as an array of arrays (the rows)44): { query: string; values: any[] } {45return {46query: `${query} VALUES ${expand(values.length, values?.[0].length ?? 0)}`,47values: flatten(values),48};49}505152