Skip to content

Commit 8d166bf

Browse files
committed
Added toSQLParameters
1 parent 22d2795 commit 8d166bf

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed

src/index.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@ export * from "./executeQuery";
33
export * from "./query";
44
export * from "./insert";
55
export * from "./update";
6-
export * from "./delete";
6+
export * from "./delete";
7+
export * from "./utils";

src/tests/sql_query.spec.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { close } from "fs";
22
import { closeConnection, createConnection } from "../connection";
33
import { executeQuery, IDynamicQuery } from "../executeQuery";
44
import { sql_query } from "../query";
5+
import { toSQLParameters } from "../utils";
56

67
test("sql_query", async () => {
78
const connection = createConnection({
@@ -41,7 +42,7 @@ test("sql_query dynamic", async () => {
4142
(params: InputType): IDynamicQuery => {
4243
return {
4344
named: false,
44-
sql: `select * from pg_class where oid in (${params.oids.map((a, i) => { return "$" + (i + 1) }).join(",")})`,
45+
sql: `select * from pg_class where oid in (${toSQLParameters<string>(params.oids)})`,
4546
parameters: params.oids
4647
}
4748
}

src/utils.ts

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { wrapInArray } from "@blendsdk/stdlib/dist/wrapInArray";
2+
import { isNullOrUndefDefault } from "@blendsdk/stdlib/dist/isNullOrUndef";
3+
4+
/**
5+
* Creates a numbered parameter based the provided argument
6+
* to be used in an SQL query. This function is mainly used
7+
* from the IN(....) caluse.
8+
*
9+
* @export
10+
* @template ReturnType
11+
* @param {(any | any[])} args
12+
* @param {boolean} [asArray]
13+
* @returns {ReturnType}
14+
*/
15+
export function toSQLParameters<ReturnType extends string | string[]>(args: any | any[], asArray?: boolean): ReturnType {
16+
const tArgs = wrapInArray(args),
17+
aArgs = tArgs.map((a, i) => { return "$" + (i + 1); });
18+
asArray = isNullOrUndefDefault<boolean>(asArray, false);
19+
return asArray ? aArgs : aArgs.join(", ") as any;
20+
}

0 commit comments

Comments
 (0)