Skip to content

Commit 9901f64

Browse files
authored
fix: correct JOIN order for nested includes with junction tables (#29)
1 parent b496bff commit 9901f64

File tree

2 files changed

+11
-10
lines changed

2 files changed

+11
-10
lines changed

src/lib/build.ts

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -48,17 +48,18 @@ export function buildSelectQuery<T = unknown, R extends string = "none">(
4848

4949
// Handle include
5050
if (query.include) {
51-
for (const [relation, relationQuery] of Object.entries(query.include)) {
52-
if (!relations[relation]) {
53-
throw new Error(`Relation ${relation} is not defined`);
51+
for (const [relationName, relationQuery] of Object.entries(query.include)) {
52+
const relation = relations[relationName];
53+
if (!relation) {
54+
throw new Error(`Relation ${relationName} is not defined`);
5455
}
5556
const innerQuery = buildSelectQuery(
56-
relation,
57+
relationName,
5758
relationQuery,
5859
relations,
5960
true,
6061
);
61-
args.join += join("LEFT LATERAL", relations[relation], innerQuery);
62+
args.join += join("LEFT LATERAL", relation, innerQuery);
6263
}
6364
}
6465

@@ -214,12 +215,12 @@ export function sql(
214215
},
215216
): string {
216217
let sql = `${params?.select || params?.delete || params?.update || ""}`;
217-
if (params.join) {
218-
sql += `${params.join}`;
219-
}
220218
if (append?.join) {
221219
sql += `${append?.join}`;
222220
}
221+
if (params.join) {
222+
sql += `${params.join}`;
223+
}
223224
if (params.where && Object.keys(params.where).length > 0) {
224225
sql += ` WHERE ${where(params.where, "AND", params.relations || {})}`;
225226
}

src/test/build.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ describe("sql", () => {
3737
};
3838
const result = sql(params, append);
3939
expect(result).toBe(
40-
"SELECT * FROM table JOIN other_table ON table.id = other_table.table_id JOIN another_table ON table.id = another_table.table_id",
40+
"SELECT * FROM table JOIN another_table ON table.id = another_table.table_id JOIN other_table ON table.id = other_table.table_id",
4141
);
4242
});
4343

@@ -101,7 +101,7 @@ describe("sql", () => {
101101
};
102102
const result = sql(params, append);
103103
expect(result).toBe(
104-
`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"`,
104+
`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"`,
105105
);
106106
});
107107
});

0 commit comments

Comments
 (0)