tercul-backend/test/fixtures/loader.go

60 lines
1.2 KiB
Go

package fixtures
import (
"context"
"fmt"
"gorm.io/gorm"
)
// Loader provides methods to load fixtures into the database
type Loader struct {
db *gorm.DB
}
// NewLoader creates a new fixture loader
func NewLoader(db *gorm.DB) *Loader {
return &Loader{db: db}
}
// LoadAll loads all fixtures into the database in the correct order
func (l *Loader) LoadAll(ctx context.Context) error {
// Load in order to respect foreign key constraints
loaders := []struct {
name string
fn func(context.Context, *gorm.DB) error
}{
{"users", LoadUsers},
{"authors", LoadAuthors},
{"works", LoadWorks},
{"translations", LoadTranslations},
}
for _, loader := range loaders {
if err := loader.fn(ctx, l.db); err != nil {
return fmt.Errorf("failed to load %s: %w", loader.name, err)
}
}
return nil
}
// Clear removes all fixture data from the database
func (l *Loader) Clear(ctx context.Context) error {
// Delete in reverse order to respect foreign key constraints
tables := []string{
"translations",
"works",
"authors",
"users",
}
for _, table := range tables {
if err := l.db.Exec(fmt.Sprintf("DELETE FROM %s", table)).Error; err != nil {
return fmt.Errorf("failed to clear %s: %w", table, err)
}
}
return nil
}