Skip to content

Commit

Permalink
Add join nested (#31)
Browse files Browse the repository at this point in the history
Signed-off-by: Tobias Gurtzick <[email protected]>
  • Loading branch information
wzrdtales authored Sep 4, 2023
1 parent caf47b0 commit 51ed0bc
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { inspect } from "util";
import { describe, it, expect } from "@jest/globals";
import sql, { empty, join, raw, Sql } from "./index.js";
import sql, { empty, join, joinNested, raw, Sql } from "./index.js";

describe("sql template tag", () => {
it("should generate sql", () => {
Expand Down Expand Up @@ -149,4 +149,27 @@ describe("sql template tag", () => {
expect(query.values).toEqual([value]);
});
});

describe("joinNested", () => {
it("should join nested list", () => {
const query = joinNested([
[1, 2, 3],
[5, 2, 3],
]);

expect(query.text).toEqual("($1,$2,$3),($4,$5,$6)");
expect(query.values).toEqual([1, 2, 3, 5, 2, 3]);
});

it("should error joining an empty list", () => {
expect(() => joinNested([])).toThrowError(TypeError);
});

it("should error joining an nested empty list", () => {
expect(() => joinNested([[]])).toThrowError(TypeError);
});
it("should error joining an nested non uniform list", () => {
expect(() => joinNested([[1, 2], [1, 3], [1]])).toThrowError(TypeError);
});
});
});
32 changes: 32 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,38 @@ export function join(
);
}

/**
* Create a SQL query for a list of structred values. Very useful for bulk
* inserts.
*/
export function joinNested(values: Array<RawValue[]>, separator = ",") {
if (values.length === 0) {
throw new TypeError(
"Expected `joinNested([][])` to be called with an array of multiple elements, but got an empty array"
);
}

const len = values[0].length;

if (len === 0) {
throw new TypeError(
"Expected `joinNested([][])` to be called with an nested array of multiple elements, but got an empty array"
);
}

const v = values.map((x, index) => {
if (x.length !== len) {
throw new TypeError(
`Expected joinNested([][${len}]) instead param at index ${index} had a length of ${x.length}`
);
}

return new Sql(["(", ...Array(x.length - 1).fill(separator), ")"], x);
});

return new Sql(["", ...Array(v.length - 1).fill(separator), ""], v);
}

/**
* Create raw SQL statement.
*/
Expand Down

0 comments on commit 51ed0bc

Please sign in to comment.