Skip to content

Commit 2c2c065

Browse files
committed
feat: added GORM's CreateConstraints function and Constraint struct
1 parent a09b1a9 commit 2c2c065

File tree

3 files changed

+55
-9
lines changed

3 files changed

+55
-9
lines changed

gorm/constraint.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package gorm
2+
3+
import (
4+
godatabases "github.com/ralvarezdev/go-databases"
5+
"gorm.io/gorm"
6+
)
7+
8+
type (
9+
// Constraint struct
10+
Constraint struct {
11+
model interface{}
12+
field string
13+
}
14+
)
15+
16+
// NewConstraint creates a new constraint
17+
func NewConstraint(model interface{}, field string) *Constraint {
18+
return &Constraint{
19+
model: model,
20+
field: field,
21+
}
22+
}
23+
24+
// CreateConstraint creates a new constraint
25+
func CreateConstraint(database *gorm.DB, constraint *Constraint) error {
26+
// Check if the database or the constraint is nil
27+
if database == nil {
28+
return godatabases.ErrNilDatabase
29+
}
30+
if constraint == nil {
31+
return ErrNilConstraint
32+
}
33+
34+
// Create the constraint
35+
return database.Migrator().CreateConstraint(
36+
constraint.model,
37+
constraint.field,
38+
)
39+
}
40+
41+
// CreateConstraints creates new constraints
42+
func CreateConstraints(database *gorm.DB, constraints []*Constraint) error {
43+
for _, constraint := range constraints {
44+
if err := CreateConstraint(database, constraint); err != nil {
45+
return err
46+
}
47+
}
48+
return nil
49+
}

gorm/errors.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,6 @@ import (
55
)
66

77
var (
8-
ErrNilJoinField = errors.New("join field cannot be nil")
8+
ErrNilJoinField = errors.New("join field cannot be nil")
9+
ErrNilConstraint = errors.New("constraint cannot be nil")
910
)

gorm/join_table.go

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ func NewJoinField(
2727
}
2828
}
2929

30-
// SetupJoinTable setups the join table between two models
30+
// SetupJoinTable setups the join table
3131
func SetupJoinTable(
3232
database *gorm.DB,
3333
joinField *JoinField,
@@ -47,17 +47,13 @@ func SetupJoinTable(
4747
)
4848
}
4949

50-
// SetupJoinTables setups the join tables between multiple models
50+
// SetupJoinTables setups the join tables
5151
func SetupJoinTables(
5252
database *gorm.DB,
5353
joinFields []*JoinField,
54-
) error {
54+
) (err error) {
5555
for _, joinField := range joinFields {
56-
err := SetupJoinTable(
57-
database,
58-
joinField,
59-
)
60-
if err != nil {
56+
if err = SetupJoinTable(database, joinField); err != nil {
6157
return err
6258
}
6359
}

0 commit comments

Comments
 (0)