Skip to content

Commit

Permalink
fix: use callback instead of struct for params
Browse files Browse the repository at this point in the history
  • Loading branch information
luantranminh committed Apr 20, 2024
1 parent d032753 commit 9aec9e0
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 22 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ The provider supports the following databases:

* **Foreign key constraints not generated correctly** -
If a [Customize JoinTable](https://gorm.io/docs/many_to_many.html#Customize-JoinTable) is defined in the schema,
you need to use the provider as a [Go Program](#as-go-file) and set it up using the `WithJoinTables` option.
you need to use the provider as a [Go Program](#as-go-file) and set it up using the `BeforeAutoMigrate` option.

for example if those are your models:
```go
Expand All @@ -210,9 +210,9 @@ The provider supports the following databases:
you should use the following code:
```go
stmts, err := gormschema.New("mysql")
.WithJoinTables(
gormschema.SetupJoinTableParams{Model: &models.Person{}, Field: "Addresses", JoinTable: &models.PersonAddress{}},
)
.BeforeAutoMigrate( func(db *gorm.DB) {
db.SetupJoinTable(&customjointable.Person{}, "Addresses", &customjointable.PersonAddress{})
})
.Load(&models.Person{}, &models.Address{})
```

Expand Down
25 changes: 7 additions & 18 deletions gormschema/gorm.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ func New(dialect string, opts ...Option) *Loader {
type (
// Loader is a Loader for gorm schema.
Loader struct {
dialect string
config *gorm.Config
joinTableCallbacks []func(*gorm.DB)
dialect string
config *gorm.Config
beforeAutoMigrate func(*gorm.DB)
}
// Option configures the Loader.
Option func(*Loader)
Expand Down Expand Up @@ -86,8 +86,8 @@ func (l *Loader) Load(models ...any) (string, error) {
db.Config.DisableForeignKeyConstraintWhenMigrating = true
}

for _, setupJoinTable := range l.joinTableCallbacks {
setupJoinTable(db)
if l.beforeAutoMigrate != nil {
l.beforeAutoMigrate(db)
}

if err = db.AutoMigrate(models...); err != nil {
Expand Down Expand Up @@ -167,18 +167,7 @@ func (m *migrator) CreateConstraints(models []any) error {
return nil
}

type SetupJoinTableParams struct {
Model any
Field string
JoinTable any
}

func (l *Loader) WithJoinTables(params ...SetupJoinTableParams) *Loader {
for _, p := range params {
l.joinTableCallbacks = append(l.joinTableCallbacks, func(db *gorm.DB) {
db.SetupJoinTable(p.Model, p.Field, p.JoinTable)
})
}

func (l *Loader) BeforeAutoMigrate(cb func(*gorm.DB)) *Loader {
l.beforeAutoMigrate = cb
return l
}

0 comments on commit 9aec9e0

Please sign in to comment.