Skip to content

Commit

Permalink
Merge pull request #147 from nk-nekatr/nk/fixSubQuery
Browse files Browse the repository at this point in the history
fix subquery bug
  • Loading branch information
aravindet authored Oct 20, 2023
2 parents ae89e96 + a9d7e81 commit 20db266
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
24 changes: 21 additions & 3 deletions src/pg/filter/getAst.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,22 @@ export default function getAst(filter) {
return simplify(construct(filter));
}

function isValidSubQuery(node) {
if (!node || typeof node !== 'object') return false;

const keys = Object.keys(node);
for (const key of keys) {
if (key[0] === '$' && !['$and', '$or', '$not'].includes(key)) return false;
if (key[0] !== '$') return true;
}

for (const key in node) {
if (!isValidSubQuery(node[key])) return false;
}

return false;
}

function construct(node, prop, op) {
if (!node || typeof node !== 'object' || (prop && op)) {
if (op && prop) return [op, prop, node];
Expand All @@ -42,6 +58,11 @@ function construct(node, prop, op) {
if (Array.isArray(node)) {
return ['$or', node.map((item) => construct(item, prop, op))];
}

if (prop && isValidSubQuery(node)) {
return ['$sub', prop, construct(node)];
}

return [
'$and',
Object.entries(node).map(([key, val]) => {
Expand All @@ -58,9 +79,6 @@ function construct(node, prop, op) {
if (!prop) throw Error(`pgast.expected_prop_before:${key}`);
return construct(val, prop, key);
}
if (prop) {
return ['$sub', prop, construct({ [key]: val })];
}
return construct(val, key);
}),
];
Expand Down
21 changes: 21 additions & 0 deletions src/pg/test/filter/getSql.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,27 @@ test('join', () => {
);
});

test('join with multiple col', () => {
expect(
getSql(
{ posts: { category: 'programming', authorId: 'id1' } },
{
idCol: 'id',
schema: { types: { id: 'uuid' } },
joins: {
posts: {
table: 'posts',
refCol: 'authorId',
schema: { types: { category: 'text', authorId: 'text' } },
},
},
},
),
).toEqual(
sql`"id" IN (SELECT "authorId"::uuid FROM "posts" WHERE ("category" = ${'programming'}) AND ("authorId" = ${'id1'}))`,
);
});

test('keycts', () => {
const value = ['[email protected]', '[email protected]'];
expect(
Expand Down

0 comments on commit 20db266

Please sign in to comment.