Skip to content

refactor: Make id == null checks in attach/detach repositories conditional on id nullability - #5318

Open
realmeylisdev wants to merge 3 commits into
serverpod:mainfrom
realmeylisdev:fix/3462-conditional-id-null-guards
Open

realmeylisdev wants to merge 3 commits into
serverpod:mainfrom
realmeylisdev:fix/3462-conditional-id-null-guards

Conversation

@realmeylisdev

Copy link
Copy Markdown
Contributor

Since #3437, models can declare non-nullable id fields (UUID ids with a defaultModel default). The generated attach/detach repository methods still unconditionally emitted if (x.id == null) { throw ArgumentError.notNull('x.id'); } guards, which are dead code for non-nullable ids and trigger the unnecessary_null_comparison lint (dead_code on Dart 3.10+). This was masked by adding a file-wide ignore_for_file to every relation-bearing generated file.

This PR makes the guards conditional on the static nullability of the checked model's id, decided per side of the relation, and removes the hasRelationWithNonNullableIds workaround as requested in the issue:

  • The enclosing model's id nullability comes from classDefinition.idField.type.nullable (the attach/detach builder chain now takes ModelClassDefinition, which is what the call site already passes).
  • The referenced model's id nullability comes from a new ObjectRelationDefinition.referenceIdType, populated by the dependency resolver. This has to happen at analysis time: the resolver has the referenced class definition in scope (including module models, e.g. module:auth:UserInfo), while the generator pipeline only ever receives project and shared models.
  • List-relation element id nullability comes from ListRelationDefinition.foreignKeyOwnerIdType. The implicit-relation branch stored the declaring class's id type instead of the foreign-key owner's, contradicting the property's own documentation — fixed to match the named branch. The property has been write-only in the generator since the feat: Allow non-nullable id field when defaultModel is set #3437 refactors, so this had no observable effect before; the two test expectations that snapshotted the old value are updated.
  • The nullability flags are threaded into the implementation-block builders as parameters bound to the same parameter slot each guard checks, because the same block builder is invoked by different callers with swapped argument roles (e.g. _buildAttachRowImplementationBlockExplicit checks the enclosing model's id via its first slot when called for the foreign-key-origin side, but the referenced model's id via that same slot when called for a list relation).
  • The .any((e) => e.id == null) list guards are gated by the same rule. The relation-field null check in the foreign-side detachRow (if ($field == null)) is kept unconditionally, since object-relation fields are always required to be declared nullable by validation.

Removing a guard is behavior-preserving: a statically non-nullable id can never hold null at runtime (the generated constructor coalesces a default, and fromJson/copyWith/row mapping all funnel through it), and the database layer independently rejects null ids in update. The existing integration tests already encode this — for unsaved rows of non-nullable-id models they expect DatabaseUpdateRowException, never the ArgumentError from the guard.

All generated code across the repo is regenerated in a separate commit (143 files, deletions only): every relation-bearing file loses the ignore header, and files referencing non-nullable-id models also lose the dead guard blocks. Mixed cases keep exactly the live side, e.g. CustomerIntAttachRepository.orders keeps the customerInt.id guard (nullable int? id) while the orderUuid.id guard (non-nullable UUID id) is no longer generated — this is the exact example from the issue. Re-running util/generate_all on the result produces no diff.

New tests in database_repository_attach_detach_guards_test.dart assert guard presence/absence on the generated method bodies for object relations (origin and foreign side), named and implicit list relations, and mixed-nullability combinations.

Fixes #3462

Pre-launch Checklist

  • I read the Contribute page and followed the process outlined there for submitting PRs.
  • This update contains only one single feature or bug fix and nothing else. (If you are submitting multiple fixes, please make multiple PRs.)
  • I read and followed the Dart Style Guide and formatted the code with dart format.
  • I listed at least one issue that this PR fixes in the description above.
  • I updated/added relevant documentation (doc comments with ///), and made sure that the documentation follows the same style as other Serverpod documentation. I checked spelling and grammar.
  • I added new tests to check the change I am making.
  • All existing and new tests are passing.
  • Any breaking changes are documented below.

Breaking changes

None. Generated code only loses statically unreachable guard blocks and the now-unnecessary lint suppressions; runtime behavior is unchanged. (ObjectRelationDefinition gains a required constructor parameter, but it is internal to the analyzer and constructed only by the resolver and CLI test utilities.)

…itional on id nullability

The generated attach/detach repository methods unconditionally emitted
`if (x.id == null) throw ArgumentError.notNull(...)` guards, which are
dead code when the checked model's id field is non-nullable (UUID ids
with a defaultModel default). The guards were masked by adding a
file-wide `ignore_for_file: unnecessary_null_comparison, dead_code` to
every relation-bearing generated file.

Each guard is now emitted only when the checked model's id is nullable,
decided per side of the relation:
- the enclosing model's id via `classDefinition.idField.type.nullable`,
- the referenced model's id via a new
  `ObjectRelationDefinition.referenceIdType` populated by the resolver
  (the generator never sees module class definitions, so this must be
  resolved at analysis time),
- list-relation element ids via `ListRelationDefinition.foreignKeyOwnerIdType`,
  fixing the implicit branch which stored the declaring class's id type
  instead of the foreign-key owner's (contradicting its own doc; the
  property was write-only in the generator, so this was unobservable).

The relation-field null check in foreign-side detachRow is kept
unconditionally since object-relation fields are always validated to be
nullable. The `hasRelationWithNonNullableIds` lint-suppression
workaround is removed.

Closes serverpod#3462
Regenerated via util/generate_all. All relation-bearing generated files
lose the `ignore_for_file: dead_code, unnecessary_null_comparison`
header; files referencing models with non-nullable ids additionally
lose the now-unreachable guard blocks.
@realmeylisdev

Copy link
Copy Markdown
Contributor Author

The two red checks are not analysis findings. dart analyze latest (3.41.5, ubuntu-latest) failed during melos bootstrap, before any analysis ran, on a Flutter infrastructure download error:

Failed to download https://storage.googleapis.com/flutter_infra_release/flutter//engine_stamp.json. Ensure you have network connectivity and then try again.
BootstrapException: Failed to install.: serverpod_auth_email_flutter

The windows-latest job was then canceled by the matrix fail-fast ("The operation was canceled."). All other checks are green, including serverpod generate, the pinned dart analyze/dart analyze downgrade, and the full unit/integration/E2E matrix. A re-run of the failed jobs should clear it — I don't have permissions to trigger that myself.

@realmeylisdev

Copy link
Copy Markdown
Contributor Author

Why 150 files: only 7 are the actual change (commit 76f4bdd — generator/analyzer + tests). The other 143 are regenerated goldens (commit abd96de, zero insertions, 250 deletions): the old workaround stamped the ignore_for_file header on every generated model with attach/detach repositories regardless of id nullability, so removing it deletes one header line from each of those files; only the non-nullable-id fixtures also lose guard blocks. The serverpod generate CI job fails on any generator/golden mismatch, so the regeneration must land in the same PR — same shape as #3437 (~5 CLI files + ~100 regenerated).

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.

refactor: Make checks of id == null on repository classes only present if id is nullable

1 participant