fix: AfterQuery using safer right trim to clear FROM clause's joins #7150
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.
As a fix to this issue , clearing of db.Statement.Clauses["FROM"] was in introduced in this pull-request
At 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 index. Please observe below the case reproduced in current source codeIn the case above, wrong column name
pets.names
(instead of pets.name) is passed as query.When
Count()
is called afterFind()
on the the samegorm.DB
instance with a wrong query, it calls AfterQuery 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.What did this pull request do?
This Pull Request:
db.Statement.Clauses["FROM"].Joins
User Case Description
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.