feat(model): primary key validation #9840
Open
+494
−99
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This PR adds primary key validation to the Model's
insert(),insertBatch(),update(), anddelete()methods (forinsert*whenuseAutoIncrementis disabled). This ensures that invalid primary key values are caught early with clear error messages, rather than causing confusing database errors.Previously, when you passed invalid values like 0, '0', or empty strings as primary keys, these values would often be silently ignored by the query builder.
The new
validateID()method inBaseModelnow explicitly rejects these invalid primary key values:null(for insert when auto-increment is disabled)0(integer zero)'0'(string zero)''(empty string)trueandfalse(booleans)[](empty array)[[1, 2]]When these values are detected, the model throws an
InvalidArgumentExceptionwith a specific message like "Invalid primary key: 0 is not allowed".Validation timing
update()anddelete(): Validation happens inBaseModelbeforebeforeUpdate/beforeDeleteevents, preventing invalid values from reaching event handlersinsert()andinsertBatch()(when auto-increment is disabled): Validation happens inModel::doInsert()andModel::doInsertBatch()after thebeforeInsertevent (allowing devs to use this event to produce the PK), but before database queriesIf developers have a legitimate need to use values like
0or'0'as primary keys (e.g., legacy systems), they can override thevalidateID()method in their model to customize the behavior.Checklist: