Skip to content

Commit c5e44b0

Browse files
authored
feat: omit empty logical operators (AND, OR, NOT) from query (#26)
- Updated query builder logic to filter out invalid or missing conditions for `AND`, `OR`, and `NOT` operators. - Logical operators are now only included in the query if their corresponding conditions array is non-empty. - Returns an empty query or default query if no valid conditions are present for any logical operator. - Prevents incorrect query structures like `{ AND: [], OR: [], NOT: [] }` from being generated.
1 parent 1cc2fc2 commit c5e44b0

File tree

2 files changed

+36
-5
lines changed

2 files changed

+36
-5
lines changed

src/lib/where.ts

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -115,16 +115,23 @@ function handleLogicalOperator(
115115
whereClauses: string[],
116116
) {
117117
if (operator === "NOT") {
118-
whereClauses.push(
119-
`NOT(${where(value as QueryWhereCondition, "AND", relations)})`,
120-
);
118+
const notClause = where(value as QueryWhereCondition, "AND", relations);
119+
if (notClause !== "") {
120+
whereClauses.push(`NOT(${notClause})`);
121+
}
121122
return;
122123
}
123124
const subWhereClauses: string[] = [];
124125
for (const condition of value as QueryWhereCondition[]) {
125-
subWhereClauses.push(`${where(condition, operator, relations)}`);
126+
const whereClause = where(condition, operator, relations);
127+
if (whereClause !== "") {
128+
subWhereClauses.push(whereClause);
129+
}
130+
}
131+
132+
if (subWhereClauses.length > 0) {
133+
whereClauses.push(`(${subWhereClauses.join(` ${operator} `)})`);
126134
}
127-
whereClauses.push(`(${subWhereClauses.join(` ${operator} `)})`);
128135
return;
129136
}
130137

src/test/where.test.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,30 @@ describe("where", () => {
4848
expect(result).toBe(`NOT("id" = 1 AND "name" = 'John')`);
4949
});
5050

51+
it("should ignore empty AND", () => {
52+
const conditions: QueryWhereCondition = { id: 1, AND: [] };
53+
const result = where(conditions);
54+
expect(result).toBe(`"id" = 1`);
55+
});
56+
57+
it("should ignore empty OR", () => {
58+
const conditions: QueryWhereCondition = { id: 1, OR: [] };
59+
const result = where(conditions);
60+
expect(result).toBe(`"id" = 1`);
61+
});
62+
63+
it("should ignore empty NOT", () => {
64+
const conditions = { id: 1, NOT: {} };
65+
const result = where(conditions);
66+
expect(result).toBe(`"id" = 1`);
67+
});
68+
69+
it("should ignore nested empty operators", () => {
70+
const conditions = { id: 1, AND: [{ OR: [{ AND: [] }] }] };
71+
const result = where(conditions);
72+
expect(result).toBe(`"id" = 1`);
73+
});
74+
5175
it("should handle different types of operators", () => {
5276
// Test for greaterThan and lessThan
5377
expect(where({ id: { greaterThan: 1, lessThan: 10 } })).toBe(

0 commit comments

Comments
 (0)