Fixtures

    A fixture is a plain YAML file with the ability to use text/templateopen in new window expressions to generate values. Bun unmarshals YAML data into Go models using and then saves the model in a database.

    Here is how a fixture for a User model might look like:

    1. - model: User
    2. rows:
    3. - _id: smith
    4. name: John Smith
    5. email: john@smith.com
    6. - _id: doe
    7. name: Jonh Doe
    8. email: john@doe.com
    9. created_at: '{{ now }}'
    10. rows:
    11. - name: "{{ $.User.smith.Name }}'s Org"
    12. owner_id: '{{ $.User.smith.ID }}'
    13. - name: "{{ $.User.doe.Name }}'s Org"

    Assuming the fixture is stored in testdata/fixture.yml, you can load it with the following code:

    By using fixture.WithRecreateTables() option, you can make bun drop existing tables and replace them with new ones. Or you can use fixture.WithTruncateTables() option to truncate tables.

    1. fixture := dbfixture.New(db, dbfixture.WithRecreateTables())
    2. fixture := dbfixture.New(db, dbfixture.WithTruncateTables())

    Later you can retrieve the loaded models using Row and methods:

    1. fmt.Println("Smith", fixture.MustRow("User.smith").(*User))

    You can also retrieve rows without _id field by a primary key:

    1. type User struct {
    2. ID int64 `bun:",pk,autoincrement"`
    3. Params UserParams `bun:"type:jsonb"`
    4. }
    5. type UserParams struct {
    6. Param1 string `yaml:"param1"`

    You can find the source code for the example above on GitHubopen in new window.