Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions src/lib/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,17 +48,18 @@ export function buildSelectQuery<T = unknown, R extends string = "none">(

// Handle include
if (query.include) {
for (const [relation, relationQuery] of Object.entries(query.include)) {
if (!relations[relation]) {
throw new Error(`Relation ${relation} is not defined`);
for (const [relationName, relationQuery] of Object.entries(query.include)) {
const relation = relations[relationName];
if (!relation) {
throw new Error(`Relation ${relationName} is not defined`);
}
const innerQuery = buildSelectQuery(
relation,
relationName,
relationQuery,
relations,
true,
);
args.join += join("LEFT LATERAL", relations[relation], innerQuery);
args.join += join("LEFT LATERAL", relation, innerQuery);
}
}

Expand Down Expand Up @@ -214,12 +215,12 @@ export function sql(
},
): string {
let sql = `${params?.select || params?.delete || params?.update || ""}`;
if (params.join) {
sql += `${params.join}`;
}
if (append?.join) {
sql += `${append?.join}`;
}
if (params.join) {
sql += `${params.join}`;
}
if (params.where && Object.keys(params.where).length > 0) {
sql += ` WHERE ${where(params.where, "AND", params.relations || {})}`;
}
Expand Down
4 changes: 2 additions & 2 deletions src/test/build.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ describe("sql", () => {
};
const result = sql(params, append);
expect(result).toBe(
"SELECT * FROM table JOIN other_table ON table.id = other_table.table_id JOIN another_table ON table.id = another_table.table_id",
"SELECT * FROM table JOIN another_table ON table.id = another_table.table_id JOIN other_table ON table.id = other_table.table_id",
);
});

Expand Down Expand Up @@ -101,7 +101,7 @@ describe("sql", () => {
};
const result = sql(params, append);
expect(result).toBe(
`SELECT * FROM table JOIN other_table ON table.id = other_table.table_id JOIN another_table ON table.id = another_table.table_id WHERE "id" = 1 AND other_table.name = "test" GROUP BY "name" HAVING COUNT("name") = 1 ORDER BY "name" ASC LIMIT 10 OFFSET 5 RETURNING "id", "name"`,
`SELECT * FROM table JOIN another_table ON table.id = another_table.table_id JOIN other_table ON table.id = other_table.table_id WHERE "id" = 1 AND other_table.name = "test" GROUP BY "name" HAVING COUNT("name") = 1 ORDER BY "name" ASC LIMIT 10 OFFSET 5 RETURNING "id", "name"`,
);
});
});
Expand Down