Home >Backend Development >Golang >How do I use TOML fixtures to seed my database in a development environment using the Go Buffalo framework?
When developing with the Go Buffalo framework, we often need to seed the database to populate the test and development environments with some initial data. TOML is a simple and easy-to-read configuration file format that can be used to define data. So how do we use TOML files to seed our database? In this article, PHP editor Xiaoxin will introduce you to a simple method to seed a database using TOML devices in the development environment of the Go Buffalo framework. Let’s take a look!
I am trying to use TOML fixtures to seed my development database in the Go Buffalo framework. However, I can't find a clear example or documentation on how to do this.
To seed the database you can use grifts. When creating a new application, a dummy placeholder grift should be generated at grifts/db.go
like this:
package grifts import "github.com/gobuffalo/grift/grift" var _ = grift.namespace("db", func() { grift.desc("seed", "seeds a database") grift.add("seed", func(c *grift.context) error { // add db seeding stuff here return nil }) })
I tried using model.loadfixture("seed widgets")
in grift, but had some panic because it's not in the test environment. I don't think there is direct support for database seeding from toml installations, but it would be a useful feature. However, looking at the code in loadfixture we can build our own fixture loading:
Suppose you have a fixture for a scene named name = "seed widgets"
:
package grifts import ( "fmt" "os" "strings" "github.com/gobuffalo/grift/grift" "github.com/gobuffalo/suite/v4" "github.com/gobuffalo/suite/v4/fix" ) var _ = grift.Namespace("db", func() { grift.Desc("seed", "Seeds a database") grift.Add("seed", func(c *grift.Context) error { // The DB connection will connect to the environment set in `GO_ENV` (defaults to `test`) // Set this environment variable in your `.env` file to `development` // NOTE: it may be better to put seed fixtures in a different directory // to seperate concerns model, err := suite.NewModelWithFixtures(os.DirFS("./fixtures")) if err != nil { return err } sc, err := fix.Find("seed widgets") if err != nil { return err } for _, table := range sc.Tables { for _, row := range table.Row { q := "insert into " + table.Name keys := []string{} skeys := []string{} for k := range row { keys = append(keys, k) skeys = append(skeys, ":"+k) } q = q + fmt.Sprintf(" (%s) values (%s)", strings.Join(keys, ","), strings.Join(skeys, ",")) if _, err = model.DB.Store.NamedExec(q, row); err != nil { return err } } } return nil }) })
The above is the detailed content of How do I use TOML fixtures to seed my database in a development environment using the Go Buffalo framework?. For more information, please follow other related articles on the PHP Chinese website!