-
-
Notifications
You must be signed in to change notification settings - Fork 4.1k
Add WhereHas and WhereDoesntHave helpers for relationship filtering #7642
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
vzaica
wants to merge
6
commits into
go-gorm:master
Choose a base branch
from
vzaica:feature/where-has
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+428
−0
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,209 @@ | ||
| package callbacks | ||
|
|
||
| import ( | ||
| "fmt" | ||
|
|
||
| "gorm.io/gorm" | ||
| "gorm.io/gorm/clause" | ||
| "gorm.io/gorm/schema" | ||
| ) | ||
|
|
||
| func whereHasDb(db *gorm.DB) *gorm.DB { | ||
| tx := db.Session(&gorm.Session{Context: db.Statement.Context, NewDB: true, SkipHooks: db.Statement.SkipHooks, Initialized: true}) | ||
|
|
||
| return tx | ||
| } | ||
|
|
||
| var relationHandlers = map[schema.RelationshipType]func(*gorm.DB, *gorm.DB, *schema.Relationship, []interface{}) (*gorm.DB, error){ | ||
| schema.Many2Many: existsMany2many, | ||
| schema.BelongsTo: existsBelongsTo, | ||
| schema.HasMany: existsHasMany, | ||
| schema.HasOne: existsHasOne, | ||
| } | ||
|
|
||
| func newWhereHas(db *gorm.DB, isDoesntHave bool, relationName string, conds []interface{}, s *schema.Schema) (*clause.Where, error) { | ||
| var err error | ||
|
|
||
| rel, ok := s.Relationships.Relations[relationName] | ||
| if !ok { | ||
| return nil, fmt.Errorf("relation %s not found", relationName) | ||
| } | ||
|
|
||
| tx := whereHasDb(db) | ||
|
|
||
| reflectResults := rel.FieldSchema.MakeSlice().Elem() | ||
|
|
||
| firstPrimaryField := "" | ||
| otherPrimaryFields := make([]interface{}, 0) | ||
|
|
||
| for i, name := range rel.FieldSchema.PrimaryFieldDBNames { | ||
| if i == 0 { | ||
| firstPrimaryField = name | ||
| } else { | ||
| otherPrimaryFields = append(otherPrimaryFields, name) | ||
| } | ||
| } | ||
|
|
||
| tx = tx.Model(reflectResults.Addr().Interface()).Select(firstPrimaryField, otherPrimaryFields...) | ||
| if err = tx.Statement.Parse(tx.Statement.Model); err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| handler, ok := relationHandlers[rel.Type] | ||
| if !ok { | ||
| return nil, fmt.Errorf("unsupported relation type: %v", rel.Type) | ||
| } | ||
|
|
||
| tx, err = handler(db, tx, rel, conds) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| cond := "EXISTS(?)" | ||
| if isDoesntHave { | ||
| cond = "NOT " + cond | ||
| } | ||
|
|
||
| cl := clause.Where{ | ||
| Exprs: []clause.Expression{ | ||
| clause.Expr{ | ||
| SQL: cond, | ||
| Vars: []interface{}{tx}, | ||
| WithoutParentheses: false, | ||
| }, | ||
| }, | ||
| } | ||
|
|
||
| return &cl, nil | ||
| } | ||
|
|
||
| func existsHasOne(mainQuery *gorm.DB, existsQuery *gorm.DB, rel *schema.Relationship, conds []interface{}) (*gorm.DB, error) { | ||
| return existsHasMany(mainQuery, existsQuery, rel, conds) | ||
| } | ||
|
|
||
| func existsHasMany(mainQuery *gorm.DB, existsQuery *gorm.DB, rel *schema.Relationship, conds []interface{}) (*gorm.DB, error) { | ||
| if len(rel.References) < 1 { | ||
| return nil, fmt.Errorf("relation %s has no references", rel.Name) | ||
| } | ||
|
|
||
| for _, reference := range rel.References { | ||
| if reference.PrimaryKey != nil { | ||
| existsQuery.Statement.AddClause(clause.Where{ | ||
| Exprs: []clause.Expression{ | ||
| clause.Eq{ | ||
| Column: clause.Column{Table: existsQuery.Statement.Table, Name: reference.ForeignKey.DBName}, | ||
| Value: clause.Column{Table: mainQuery.Statement.Table, Name: reference.PrimaryKey.DBName}, | ||
| }, | ||
| }, | ||
| }) | ||
| } else { | ||
| existsQuery.Statement.AddClause(clause.Where{ | ||
| Exprs: []clause.Expression{ | ||
| clause.Eq{ | ||
| Column: clause.Column{Table: existsQuery.Statement.Table, Name: reference.ForeignKey.DBName}, | ||
| Value: reference.PrimaryValue, | ||
| }, | ||
| }, | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| existsQuery = applyConds(existsQuery, conds) | ||
|
|
||
| return existsQuery, nil | ||
| } | ||
|
|
||
| func existsBelongsTo(mainQuery *gorm.DB, existsQuery *gorm.DB, rel *schema.Relationship, conds []interface{}) (*gorm.DB, error) { | ||
| if len(rel.References) < 1 { | ||
| return nil, fmt.Errorf("relation %s has no references", rel.Name) | ||
| } | ||
|
|
||
| for _, reference := range rel.References { | ||
| existsQuery.Statement.AddClause(clause.Where{ | ||
| Exprs: []clause.Expression{ | ||
| clause.Eq{ | ||
| Column: clause.Column{Table: existsQuery.Statement.Table, Name: reference.PrimaryKey.DBName}, | ||
| Value: clause.Column{Table: mainQuery.Statement.Table, Name: reference.ForeignKey.DBName}, | ||
| }, | ||
| }, | ||
| }) | ||
| } | ||
|
|
||
| existsQuery = applyConds(existsQuery, conds) | ||
|
|
||
| return existsQuery, nil | ||
| } | ||
|
|
||
| func existsMany2many(mainQuery *gorm.DB, existsQuery *gorm.DB, rel *schema.Relationship, conds []interface{}) (*gorm.DB, error) { | ||
| if rel.JoinTable != nil { | ||
| var parentTableField *schema.Reference = nil | ||
| var primaryTableField *schema.Reference = nil | ||
|
|
||
| for _, reference := range rel.References { | ||
| if !reference.OwnPrimaryKey { | ||
| parentTableField = reference | ||
| } else { | ||
| primaryTableField = reference | ||
| } | ||
| } | ||
|
|
||
| if parentTableField == nil { | ||
| return nil, fmt.Errorf("relation %s has no parent table field", rel.Name) | ||
| } | ||
|
|
||
| if primaryTableField == nil { | ||
| return nil, fmt.Errorf("relation %s has no primary table field", rel.Name) | ||
| } | ||
|
|
||
| fromClause := clause.From{ | ||
| Tables: nil, | ||
| Joins: []clause.Join{ | ||
| { | ||
| Type: clause.InnerJoin, | ||
| Table: clause.Table{Name: rel.JoinTable.Table}, | ||
| ON: clause.Where{ | ||
| Exprs: []clause.Expression{ | ||
| clause.Eq{ | ||
| Column: clause.Column{Table: rel.JoinTable.Table, Name: parentTableField.ForeignKey.DBName}, | ||
| Value: clause.Column{Table: existsQuery.Statement.Table, Name: parentTableField.PrimaryKey.DBName}, | ||
| }, | ||
| }, | ||
| }, | ||
| }, | ||
| }, | ||
| } | ||
|
|
||
| existsQuery.Statement.AddClause(fromClause) | ||
|
|
||
| existsQuery.Statement.AddClause(clause.Where{ | ||
| Exprs: []clause.Expression{ | ||
| clause.Eq{ | ||
| Column: clause.Column{Table: rel.JoinTable.Table, Name: primaryTableField.ForeignKey.DBName}, | ||
| Value: clause.Column{Table: mainQuery.Statement.Table, Name: primaryTableField.PrimaryKey.DBName}, | ||
| }, | ||
| }, | ||
| }) | ||
|
|
||
| existsQuery = applyConds(existsQuery, conds) | ||
| } | ||
|
|
||
| return existsQuery, nil | ||
| } | ||
|
|
||
| func applyConds(existsQuery *gorm.DB, conds []interface{}) *gorm.DB { | ||
| inlineConds := make([]interface{}, 0) | ||
|
|
||
| for _, cond := range conds { | ||
| if fc, ok := cond.(func(*gorm.DB) *gorm.DB); ok { | ||
| existsQuery = fc(existsQuery) | ||
| } else { | ||
| inlineConds = append(inlineConds, cond) | ||
| } | ||
| } | ||
|
|
||
| if len(inlineConds) > 0 { | ||
| existsQuery = existsQuery.Where(inlineConds[0], inlineConds[1:]...) | ||
| } | ||
|
|
||
| return existsQuery | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[BestPractice]
Array bounds safety issue:
applyCondsassumes that ifinlineCondshas length > 0, it can safely accessinlineConds[0]and pass the rest as variadic args. However, there's a subtle issue - ifinlineCondshas only one element,inlineConds[1:]...will be an empty slice, which is fine. But for better readability and explicit handling:Suggested Change
⚡ Committable suggestion
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.
Context for Agents
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This part of the code is inspired by the code in the file callbacks/preload.go (line 288) and this code is correct, does not cause errors, and I think readability is better than the proposed version.