Skip to content

fix(factory): compose relationship creation - #769

Open
abdusco wants to merge 1 commit into
stephenafamo:mainfrom
abdusco:fix/factory-composable-relations
Open

abdusco wants to merge 1 commit into
stephenafamo:mainfrom
abdusco:fix/factory-composable-relations

Conversation

@abdusco

@abdusco abdusco commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Problem

Creating an optional direct parent relationship through a factory currently writes the child once, creates the parent, then writes the child again to set its foreign key. The final data is correct, but the second write is unnecessary and triggers observable update side effects.

This is not the best behavior for temporal or versioned tables, audit triggers, and any other database feature that reacts to updates.

Minimal reproduction

Generate factories for these two tables:

CREATE TABLE sponsors (
    id INTEGER PRIMARY KEY
);

CREATE TABLE videos (
    id INTEGER PRIMARY KEY,
    sponsor_id INTEGER UNIQUE REFERENCES sponsors(id)
);

Create an update-audit trigger on videos, then create a video with a new sponsor:

video := factory.New().NewVideo(
    factory.VideoMods.WithNewSponsor(),
).CreateOrFail(ctx, t, db)

Expected: the returned video includes its sponsor and no videos update occurs.

Actual on main: the video includes its sponsor, but the audit trigger records one UPDATE after both records have been created.

I reproduced this on local PostgreSQL 18.4: upstream main recorded one update; this branch recorded zero.

Fix

Create direct parent and child relationships as part of one creation flow whenever the relationship is represented by the child foreign key. The factory inserts the child with the parent foreign key already set, avoiding the follow-up relationship update. Explicit foreign-key values remain sufficient to reference an existing parent, and cascading parent setup only fills relationships that are required.

@abdusco
abdusco force-pushed the fix/factory-composable-relations branch 3 times, most recently from dfab765 to 02149f4 Compare September 6, 2026 17:56
@abdusco
abdusco force-pushed the fix/factory-composable-relations branch from 02149f4 to 55db4d7 Compare September 6, 2026 18:18
@abdusco
abdusco marked this pull request as ready for review September 6, 2026 18:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant