Skip to content
This repository was archived by the owner on Apr 17, 2020. It is now read-only.

Commit 3f0143b

Browse files
author
Joel Mukuthu
committed
fix: ensure joined data is null if the row is empty
even if `first` is configured on the joined query
1 parent 1fb59bd commit 3f0143b

File tree

2 files changed

+26
-10
lines changed

2 files changed

+26
-10
lines changed

lib/KnormRelations.js

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,7 @@ class KnormRelations {
256256
}
257257

258258
join.parent = this;
259+
// depended on by @knorm/postgres
259260
join.config.joined = true;
260261
join.config.index = ++this.config.index;
261262
// TODO: support custom aliases
@@ -327,18 +328,16 @@ class KnormRelations {
327328
// values while parsing the row but at a cost of code complexity
328329
const isEmpty = Object.values(data).every(value => value === null);
329330

330-
if (first) {
331+
if (isEmpty) {
332+
// TODO: test this next `if`
333+
if (!parsedRow[as]) {
334+
parsedRow[as] = null;
335+
}
336+
} else if (first) {
331337
parsedRow[as] = data;
332338
} else {
333-
if (isEmpty) {
334-
// TODO: test this
335-
if (!parsedRow[as]) {
336-
parsedRow[as] = null;
337-
}
338-
} else {
339-
parsedRow[as] = parsedRow[as] || [];
340-
parsedRow[as].push(data);
341-
}
339+
parsedRow[as] = parsedRow[as] || [];
340+
parsedRow[as].push(data);
342341
}
343342
});
344343
}

test/KnormRelations.spec.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -644,6 +644,23 @@ describe('KnormRelations', () => {
644644
[new User({ id: 1, name: 'User 1', image: new Image({ id: 1 }) })]
645645
);
646646
});
647+
648+
// TODO: requires fixes in @knorm/postgres
649+
it.skip('includes other joined models as `null` if no rows were matched', async () => {
650+
const query = new Query(User).leftJoin(new Query(Image).first());
651+
await expect(
652+
query.fetch(),
653+
'to be fulfilled with sorted rows satisfying',
654+
[
655+
new User({
656+
id: 1,
657+
name: 'User 1',
658+
image: new Image({ id: 1 })
659+
}),
660+
new User({ id: 2, name: 'User 2', image: null })
661+
]
662+
);
663+
});
647664
});
648665

649666
it('creates a left join to the model on all fields wih references', async () => {

0 commit comments

Comments
 (0)