Skip to content

Commit

Permalink
fix: EntityManager.hydrate should clear dirty fields. (#1099)
Browse files Browse the repository at this point in the history
This is just handling primitives; there is probably more work to be
done in realizing that m2o values have changed, and keeping both sides
of the newly-updated relation in sync.
  • Loading branch information
stephenh committed May 24, 2024
1 parent e9346ae commit 87beb7a
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
7 changes: 6 additions & 1 deletion packages/orm/src/EntityManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1487,10 +1487,15 @@ export class EntityManager<C = unknown, Entity extends EntityW = EntityW> {
getInstanceData(entity).row = row;
// And then only refresh the data keys that have already been serde-d from rows
// (this keeps us from deserializing data out of rows that we don't need).
const { data } = getInstanceData(entity);
const { data, originalData } = getInstanceData(entity);
const changedFields = (entity as any).changes.fields;
for (const fieldName of Object.keys(data)) {
const serde = getMetadata(entity).allFields[fieldName].serde ?? fail(`Missing serde for ${fieldName}`);
serde.setOnEntity(data, row);
// Make the field look not-dirty
if (changedFields.includes(fieldName)) {
delete originalData[fieldName];
}
}
}
entities[i++] = entity;
Expand Down
8 changes: 5 additions & 3 deletions packages/tests/integration/src/EntityManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -702,10 +702,12 @@ describe("EntityManager", () => {
await insertAuthor({ first_name: "a1" });
const em = newEntityManager();
const a1 = await em.load(Author, "1");
await knex.update({ first_name: "a1b" }).into("authors");
a1.firstName = "a2";
expect(a1.changes.firstName.hasChanged).toBe(true);
await knex.update({ first_name: "a3" }).into("authors");
const [a1b] = em.hydrate(Author, await knex.select("*").from("authors"), { overwriteExisting: true });
expect(a1b).toStrictEqual(a1);
expect(a1b.firstName).toEqual("a1b");
expect(a1b.firstName).toEqual("a3");
expect(a1.changes.firstName.hasChanged).toBe(false);
});

it("ignores sets of the same value", async () => {
Expand Down

0 comments on commit 87beb7a

Please sign in to comment.