Skip to content

fix: [#738] The Orm Creating event can be triggered when the query with the Model method#1163

Merged
hwbrzzl merged 6 commits intov1.15.xfrom
bowen/#738
Aug 19, 2025
Merged

fix: [#738] The Orm Creating event can be triggered when the query with the Model method#1163
hwbrzzl merged 6 commits intov1.15.xfrom
bowen/#738

Conversation

@hwbrzzl
Copy link
Contributor

@hwbrzzl hwbrzzl commented Aug 17, 2025

📑 Description

Closes goravel/goravel#738

This pull request refines how ORM lifecycle events are triggered in the GORM query logic, especially for batch operations involving slices and mass deletes. The core improvement is to prevent event hooks from being triggered when the destination is a slice (for create, update, save, retrieve events) or when deleting/force-deleting mass records without a specific ID. This ensures event handlers only run for single-record operations, improving correctness and preventing unintended side effects. The test suite has been expanded to cover these new behaviors, and the event handler code has been updated to panic if the new constraints are violated, aiding debugging.

Event Handling Logic Improvements:

  • Updated database/gorm/query.go so that lifecycle event hooks (creating, created, saving, saved, updating, updated, retrieved) return early and do not trigger when the destination is a slice, preventing events from firing on batch operations. [1] [2] [3] [4]
  • For delete-related events (deleting, deleted, forceDeleting, forceDeleted), hooks now only trigger if the destination has an ID, ensuring events are not fired for mass deletes.

Helper Functions:

  • Added isSlice and hasID helper functions in database/gorm/query.go to support the new event logic, checking if a destination is a slice or has an ID.

Test Coverage Enhancements:

  • Expanded the test suite in database/gorm/query_test.go to verify that events are not triggered for slice-based operations and mass deletes, including new test cases for create, save, retrieve, and delete scenarios. [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

Event Handler Safety:

  • Updated User.DispatchesEvents in database/gorm/test_models.go to panic if event hooks are called with a slice destination or without an ID, enforcing the new contract and surfacing violations during testing. [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

These changes collectively make event triggering more robust and predictable, especially in batch operations and mass record modifications.

✅ Checks

  • Added test cases for my code

@codecov
Copy link

codecov bot commented Aug 18, 2025

Codecov Report

❌ Patch coverage is 63.63636% with 52 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (v1.15.x@2926125). Learn more about missing BASE report.

Files with missing lines Patch % Lines
database/gorm/test_models.go 33.33% 11 Missing and 11 partials ⚠️
mail/mail.go 36.84% 12 Missing ⚠️
database/gorm/query.go 80.43% 6 Missing and 3 partials ⚠️
database/service_provider.go 0.00% 4 Missing ⚠️
console/console/build_command.go 0.00% 3 Missing ⚠️
support/docker/container_manager.go 85.71% 0 Missing and 1 partial ⚠️
support/docker/utils.go 75.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             v1.15.x    #1163   +/-   ##
==========================================
  Coverage           ?   68.69%           
==========================================
  Files              ?      219           
  Lines              ?    18962           
  Branches           ?        0           
==========================================
  Hits               ?    13026           
  Misses             ?     5259           
  Partials           ?      677           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.


func isSlice(dest any) bool {
destType := reflect.Indirect(reflect.ValueOf(dest)).Type()
return destType.Kind() == reflect.Slice
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be better to write
return destType.Kind() == reflect.Slice || destType.Kind() == reflect.Array
so that both slices and arrays are supported?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, updated.

@hwbrzzl hwbrzzl marked this pull request as ready for review August 18, 2025 09:37
Copilot AI review requested due to automatic review settings August 18, 2025 09:37
@hwbrzzl hwbrzzl requested a review from a team as a code owner August 18, 2025 09:37
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This pull request addresses a bug where ORM lifecycle events were incorrectly triggering during batch operations and mass deletes. The fix ensures that event handlers only execute for single-record operations by adding early returns when the destination is a slice (for create/update/save/retrieve events) or when deleting records without a specific ID (for delete events).

  • Added guards to prevent event triggering on slice destinations and mass deletes
  • Enhanced test coverage to verify the new event behavior
  • Improved error handling throughout the codebase by explicitly handling return values

Reviewed Changes

Copilot reviewed 21 out of 21 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
database/gorm/query.go Core event logic improvements with slice/ID checks and helper functions
database/gorm/query_test.go Expanded test coverage for slice operations and mass delete scenarios
database/gorm/test_models.go Added panic checks in event handlers to enforce new constraints
database/gorm/event.go Minor boolean logic simplification
Various files Improved error handling by explicitly handling function return values

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

@almas-x
Copy link
Contributor

almas-x commented Aug 18, 2025

I noticed that there are many places where errors are explicitly ignored, typically written as _ = xxx or within defer func() { _ = xxx }. Would it be better to encapsulate this pattern in a helper function, such as

func silence(fn func() error) { _ = fn() }

This would also make usages with defer more concise, for example: defer silence(xxx)

@hwbrzzl
Copy link
Contributor Author

hwbrzzl commented Aug 18, 2025

@almas-x Good point, we can create another PR to optimize this.

@hwbrzzl
Copy link
Contributor Author

hwbrzzl commented Aug 18, 2025

I modified them due to the lint error.

@hwbrzzl hwbrzzl changed the title fix: The Orm Creating event can be triggered when the query with the Model method fix: [#738] The Orm Creating event can be triggered when the query with the Model method Aug 18, 2025
@hwbrzzl hwbrzzl merged commit 08f8015 into v1.15.x Aug 19, 2025
12 checks passed
@hwbrzzl hwbrzzl deleted the bowen/#738 branch August 19, 2025 01:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants