Files
sm-user-plugin/console/backfill_handles.go
Jakub Zych c43ba87371 fix: user:backfill-handles opens its own database
- without a published *gorm.DB the command opens one with lagoon.OpenFromApp
  for its run and closes it, as the plugin's other commands do (withDB)
- TestBackfillHandlesOpensFromConfigWhenUnpublished; README CLI note
2026-10-20 23:07:14 +02:00

52 lines
1.5 KiB
Go

package console
import (
"context"
"fmt"
"git.golem15.com/golem15/sm-user-plugin/classes"
"git.golem15.com/golem15/sm-user-plugin/models"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/bonfire"
"git.golem15.com/golem15/summercms/modules/lagoon"
"gorm.io/gorm"
)
// BackfillHandles fills a unique handle on every user row that still has none.
// It uses the database the serve command published or, when it runs as a
// console command, opens one from the config for the duration of the run,
// as the plugin's other commands do.
func BackfillHandles(app *backpack.App) bonfire.Command {
return bonfire.Command{
Name: "user:backfill-handles",
Description: "Assign unique handles to users that do not have one (D-15)",
Run: func(ctx context.Context, _ bonfire.Input, out bonfire.Output) error {
if app == nil {
return fmt.Errorf("user:backfill-handles: app is nil")
}
gdb, ok := app.Lookup[*gorm.DB]()
if !ok || gdb == nil {
sqlDB, opened, err := lagoon.OpenFromApp(ctx, app)
if err != nil {
return fmt.Errorf("user:backfill-handles: %w", err)
}
defer sqlDB.Close()
gdb = opened
}
var users []models.User
if err := gdb.WithContext(ctx).Where("handle IS NULL OR handle = ''").Find(&users).Error; err != nil {
return err
}
n := 0
for i := range users {
if err := classes.AssignHandle(ctx, gdb, &users[i]); err != nil {
return err
}
n++
}
out.Success(fmt.Sprintf("Assigned handles to %d user(s)", n))
return nil
},
}
}