Fixtures - How do persist to db? #860
Unanswered
ElanHasson
asked this question in
Q&A
Replies: 1 comment
-
If you want to persist data to DB through migrations and fixtures, here's a working example I just tested: Files and folders:
type User struct {
bun.BaseModel `bun:"table:users,alias:u"`
ID int64 `bun:"id,pk,autoincrement"`
Name string `bun:"name,notnull"`
Email string `bun:"email"`
Password string `bun:"password"`
}
func init() {
Migrations.MustRegister(func(ctx context.Context, db *bun.DB) error {
db.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(true)))
// 1. Create table
_, err := db.NewCreateTable().
Model((*User)(nil)).
Exec(context.Background())
if err != nil {
panic(err)
}
// 1.1 Register model
db.RegisterModel((*User)(nil))
// 2. Load fixtures.
fixture := dbfixture.New(db)
if err := fixture.Load(ctx, os.DirFS("testdata"), "testdata.yml"); err != nil {
panic(err)
}
fmt.Println(" [up migration] ")
return nil
}, func(ctx context.Context, db *bun.DB) error {
fmt.Print(" [down migration] ")
return nil
})
}
package migrations
import "github.com/uptrace/bun/migrate"
var Migrations = migrate.NewMigrations()
func init() {
if err := Migrations.DiscoverCaller(); err != nil {
panic(err)
}
}
package main
import (
"context"
"database/sql"
"fmt"
"proj/migrations"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/driver/pgdriver"
"github.com/uptrace/bun/extra/bundebug"
"github.com/uptrace/bun/migrate"
)
var dsn = "postgres://postgres:@localhost:5432/test?sslmode=disable"
func main() {
sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn)))
db := bun.NewDB(sqldb, pgdialect.New())
db.AddQueryHook(bundebug.NewQueryHook(
bundebug.WithEnabled(false),
bundebug.FromEnv(""),
))
migrator := migrate.NewMigrator(db, migrations.Migrations)
ctx := context.Background()
err := migrator.Init(ctx)
if err != nil {
panic(err)
}
group, err := migrator.Migrate(context.Background())
if err != nil {
panic(err)
}
if group.IsZero() {
fmt.Printf("there are no new migrations to run (database is up to date)\n")
return
}
fmt.Printf("migrated to %s\n", group)
} To persist data into database, run the migration by running This is a simple example suitable for playing around with for an understanding, it still lacks the other functionalities to manage migrations like checking the status, and running a down migration. A full example to create a more fully featured CLI tool to manage migrations can be found here: |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I've got a go migration that looks like below.
How exactly do i persist the data to the DB? the docs are not clear and there doesn't seem to be an example of this.
Beta Was this translation helpful? Give feedback.
All reactions