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 d50d503
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 21 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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{}},
)
.WithJoinTables( 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) WithJoinTables(cb func(*gorm.DB)) *Loader {
l.beforeAutoMigrate = cb
return l
}

0 comments on commit d50d503

Please sign in to comment.