Skip to content

Commit

Permalink
chore: simplify basic example
Browse files Browse the repository at this point in the history
  • Loading branch information
vmihailenco committed Dec 19, 2021
1 parent b25c555 commit dbb7d90
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 21 deletions.
13 changes: 0 additions & 13 deletions example/basic/fixture.yml

This file was deleted.

41 changes: 33 additions & 8 deletions example/basic/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@ import (
"context"
"database/sql"
"fmt"
"os"

"github.com/uptrace/bun"
"github.com/uptrace/bun/dbfixture"
"github.com/uptrace/bun/dialect/sqlitedialect"
"github.com/uptrace/bun/driver/sqliteshim"
"github.com/uptrace/bun/extra/bundebug"
Expand All @@ -28,12 +26,7 @@ func main() {
bundebug.FromEnv("BUNDEBUG"),
))

// Register models for the fixture.
db.RegisterModel((*User)(nil), (*Story)(nil))

// Create tables and load initial data.
fixture := dbfixture.New(db, dbfixture.WithRecreateTables())
if err := fixture.Load(ctx, os.DirFS("."), "fixture.yml"); err != nil {
if err := resetSchema(ctx, db); err != nil {
panic(err)
}

Expand Down Expand Up @@ -101,3 +94,35 @@ type Story struct {
AuthorID int64
Author *User `bun:"rel:belongs-to,join:author_id=id"`
}

func resetSchema(ctx context.Context, db *bun.DB) error {
if err := db.ResetModel(ctx, (*User)(nil), (*Story)(nil)); err != nil {
return err
}

users := []User{
{
Name: "admin",
Emails: []string{"admin1@admin", "admin2@admin"},
},
{
Name: "root",
Emails: []string{"root1@root", "root2@root"},
},
}
if _, err := db.NewInsert().Model(&users).Exec(ctx); err != nil {
return err
}

stories := []Story{
{
Title: "Cool story",
AuthorID: users[0].ID,
},
}
if _, err := db.NewInsert().Model(&stories).Exec(ctx); err != nil {
return err
}

return nil
}

0 comments on commit dbb7d90

Please sign in to comment.