Skip to content

Commit 8c7b870

Browse files
committed
refactor: added HasConstraint checker on GORM's CreateConstraint function
1 parent 2c2c065 commit 8c7b870

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

gorm/constraint.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,20 @@ func NewConstraint(model interface{}, field string) *Constraint {
2121
}
2222
}
2323

24+
// HasConstraint checks if a constraint exists
25+
func HasConstraint(database *gorm.DB, constraint *Constraint) bool {
26+
// Check if the database or the constraint is nil
27+
if database == nil || constraint == nil {
28+
return false
29+
}
30+
31+
// Check if the constraint exists
32+
return database.Migrator().HasConstraint(
33+
constraint.model,
34+
constraint.field,
35+
)
36+
}
37+
2438
// CreateConstraint creates a new constraint
2539
func CreateConstraint(database *gorm.DB, constraint *Constraint) error {
2640
// Check if the database or the constraint is nil
@@ -31,6 +45,11 @@ func CreateConstraint(database *gorm.DB, constraint *Constraint) error {
3145
return ErrNilConstraint
3246
}
3347

48+
// Check if the constraint exists
49+
if HasConstraint(database, constraint) {
50+
return nil
51+
}
52+
3453
// Create the constraint
3554
return database.Migrator().CreateConstraint(
3655
constraint.model,

0 commit comments

Comments
 (0)