feat: avoid unique constraint failures on repeat runs by randomizing seed identities

This commit is contained in:
2025-11-21 15:26:05 +01:00
parent 14ae6f815b
commit 6470425b96
2 changed files with 93 additions and 49 deletions

View File

@@ -280,28 +280,53 @@ type voteResult struct {
index int index int
} }
func generateRandomIdentifier() string {
const length = 12
const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
identifier := make([]byte, length)
for i := range identifier {
num, _ := rand.Int(rand.Reader, big.NewInt(int64(len(chars))))
identifier[i] = chars[num.Int64()]
}
return string(identifier)
}
func (p *ParallelProcessor) createSingleUser(userRepo repositories.UserRepository, index int) (database.User, error) { func (p *ParallelProcessor) createSingleUser(userRepo repositories.UserRepository, index int) (database.User, error) {
username := fmt.Sprintf("user_%d", index)
email := fmt.Sprintf("user_%d@goyco.local", index)
password := "password123" password := "password123"
randomID := generateRandomIdentifier()
username := fmt.Sprintf("user_%s", randomID)
email := fmt.Sprintf("user_%s@goyco.local", randomID)
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil { if err != nil {
return database.User{}, fmt.Errorf("hash password: %w", err) return database.User{}, fmt.Errorf("hash password: %w", err)
} }
user := &database.User{ const maxRetries = 10
Username: username, for attempt := 0; attempt < maxRetries; attempt++ {
Email: email, user, err := userRepo.GetByEmail(email)
Password: string(hashedPassword), if err == nil {
EmailVerified: true, return *user, nil
}
user = &database.User{
Username: username,
Email: email,
Password: string(hashedPassword),
EmailVerified: true,
}
if err := userRepo.Create(user); err != nil {
randomID = generateRandomIdentifier()
username = fmt.Sprintf("user_%s", randomID)
email = fmt.Sprintf("user_%s@goyco.local", randomID)
continue
}
return *user, nil
} }
if err := userRepo.Create(user); err != nil { return database.User{}, fmt.Errorf("failed to create user after %d attempts", maxRetries)
return database.User{}, fmt.Errorf("create user: %w", err)
}
return *user, nil
} }
func (p *ParallelProcessor) createSinglePost(postRepo repositories.PostRepository, authorID uint, index int) (database.Post, error) { func (p *ParallelProcessor) createSinglePost(postRepo repositories.PostRepository, authorID uint, index int) (database.Post, error) {
@@ -347,26 +372,35 @@ func (p *ParallelProcessor) createSinglePost(postRepo repositories.PostRepositor
} }
domain := sampleDomains[index%len(sampleDomains)] domain := sampleDomains[index%len(sampleDomains)]
path := generateRandomPath() randomID := generateRandomIdentifier()
path := fmt.Sprintf("/article/%s", randomID)
url := fmt.Sprintf("https://%s%s", domain, path) url := fmt.Sprintf("https://%s%s", domain, path)
content := fmt.Sprintf("Autogenerated seed post #%d\n\nThis is sample content for testing purposes. The post discusses %s and provides valuable insights.", index, title) content := fmt.Sprintf("Autogenerated seed post #%d\n\nThis is sample content for testing purposes. The post discusses %s and provides valuable insights.", index, title)
post := &database.Post{ const maxRetries = 10
Title: title, for attempt := 0; attempt < maxRetries; attempt++ {
URL: url, post := &database.Post{
Content: content, Title: title,
AuthorID: &authorID, URL: url,
UpVotes: 0, Content: content,
DownVotes: 0, AuthorID: &authorID,
Score: 0, UpVotes: 0,
DownVotes: 0,
Score: 0,
}
if err := postRepo.Create(post); err != nil {
randomID = generateRandomIdentifier()
path = fmt.Sprintf("/article/%s", randomID)
url = fmt.Sprintf("https://%s%s", domain, path)
continue
}
return *post, nil
} }
if err := postRepo.Create(post); err != nil { return database.Post{}, fmt.Errorf("failed to create post after %d attempts", maxRetries)
return database.Post{}, fmt.Errorf("create post: %w", err)
}
return *post, nil
} }
func (p *ParallelProcessor) createVotesForPost(voteRepo repositories.VoteRepository, users []database.User, post database.Post, avgVotesPerPost int) (int, error) { func (p *ParallelProcessor) createVotesForPost(voteRepo repositories.VoteRepository, users []database.User, post database.Post, avgVotesPerPost int) (int, error) {
@@ -406,8 +440,8 @@ func (p *ParallelProcessor) createVotesForPost(voteRepo repositories.VoteReposit
Type: voteType, Type: voteType,
} }
if err := voteRepo.Create(vote); err != nil { if err := voteRepo.CreateOrUpdate(vote); err != nil {
return totalVotes, fmt.Errorf("create vote: %w", err) return totalVotes, fmt.Errorf("create or update vote: %w", err)
} }
totalVotes++ totalVotes++

View File

@@ -8,11 +8,12 @@ import (
"math/big" "math/big"
"os" "os"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
"goyco/internal/config" "goyco/internal/config"
"goyco/internal/database" "goyco/internal/database"
"goyco/internal/repositories" "goyco/internal/repositories"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
) )
func HandleSeedCommand(cfg *config.Config, name string, args []string) error { func HandleSeedCommand(cfg *config.Config, name string, args []string) error {
@@ -169,12 +170,12 @@ func seedDatabase(userRepo repositories.UserRepository, postRepo repositories.Po
} }
if IsJSONOutput() { if IsJSONOutput() {
outputJSON(map[string]interface{}{ outputJSON(map[string]any{
"action": "seed_completed", "action": "seed_completed",
"users": len(allUsers), "users": len(allUsers),
"posts": len(posts), "posts": len(posts),
"votes": votes, "votes": votes,
"seed_user": map[string]interface{}{ "seed_user": map[string]any{
"id": seedUser.ID, "id": seedUser.ID,
"username": seedUser.Username, "username": seedUser.Username,
}, },
@@ -188,32 +189,41 @@ func seedDatabase(userRepo repositories.UserRepository, postRepo repositories.Po
} }
func ensureSeedUser(userRepo repositories.UserRepository) (*database.User, error) { func ensureSeedUser(userRepo repositories.UserRepository) (*database.User, error) {
seedUsername := "seed_admin"
seedEmail := "seed_admin@goyco.local"
seedPassword := "seed-password" seedPassword := "seed-password"
randomID := generateRandomIdentifier()
user, err := userRepo.GetByEmail(seedEmail) seedUsername := fmt.Sprintf("seed_admin_%s", randomID)
if err == nil { seedEmail := fmt.Sprintf("seed_admin_%s@goyco.local", randomID)
return user, nil
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(seedPassword), bcrypt.DefaultCost) hashedPassword, err := bcrypt.GenerateFromPassword([]byte(seedPassword), bcrypt.DefaultCost)
if err != nil { if err != nil {
return nil, fmt.Errorf("hash password: %w", err) return nil, fmt.Errorf("hash password: %w", err)
} }
user = &database.User{ const maxRetries = 10
Username: seedUsername, for range maxRetries {
Email: seedEmail, user, err := userRepo.GetByEmail(seedEmail)
Password: string(hashedPassword), if err == nil {
EmailVerified: true, return user, nil
}
user = &database.User{
Username: seedUsername,
Email: seedEmail,
Password: string(hashedPassword),
EmailVerified: true,
}
if err := userRepo.Create(user); err != nil {
randomID = generateRandomIdentifier()
seedUsername = fmt.Sprintf("seed_admin_%s", randomID)
seedEmail = fmt.Sprintf("seed_admin_%s@goyco.local", randomID)
continue
}
return user, nil
} }
if err := userRepo.Create(user); err != nil { return nil, fmt.Errorf("failed to create seed user after %d attempts", maxRetries)
return nil, fmt.Errorf("create seed user: %w", err)
}
return user, nil
} }
func createRandomUsers(userRepo repositories.UserRepository, count int) ([]database.User, error) { func createRandomUsers(userRepo repositories.UserRepository, count int) ([]database.User, error) {