fix: AfterQuery using safer right trim while clearing from clause's j… #7153
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.
Summary:
As a fix to #7025 , clearing of
db.Statement.Clauses["FROM"]
was in introduced in #7027At https://github.com/go-gorm/gorm/blob/master/callbacks/query.go#L291 , it can cause a panic if
db.Statement.Clauses["FROM"].Joins
slice is being sliced using negative upper bound indexi.e. when
len(db.Statement.Joins) > len(v.Joins)
. Please observe below the case reproduced in current source codeSteps to reproduce:
In the case above, wrong column name
pets.names
(instead of pets.name) is passed as query.When Count() is called after
Find()
on the the samegorm.DB
instance with a wrong query, it callsAfterQuery
twice which in turn tries to trim the slice twice which now is empty after first trim. Hence instead of obtaining actual SQL error, it causes a panic due to index out of bound error.Checklist:
What did this pull request do?:
This Pull Request:
Safely trims the
db.Statement.Clauses["FROM"].Joins
Unit test for newly added functions for Safe right trimming of slice
User Case:
In one of my our projects, we are using gorm (just fantastic) as ORM support for Postgres. After upgrading gorm version from
v1.9.16 -> v1.25.11
, we identified panic in API due to broken migration which changes a column name causing the query to be wrong.Of course this is a minor fix requirement but much needed to prevent API server error and handle SQL error gracefully.