How can I execute raw SQL queries in Buffalo without having to set up my own db connection with sqlx
?
To clarify: I have my database connection defined in database.yml
, but I don't want to use Pop models at this time.
How can I execute raw SQL queries in Buffalo without having to set up my own db connection with sqlx
?
To clarify: I have my database connection defined in database.yml
, but I don't want to use Pop models at this time.
You can also define your RawQueries with Pop: https://godoc.org/github.com/gobuffalo/pop#Connection.RawQuery
Inside your Buffalo actions you could do something like this:
func (v myResource) MyMethod(c buffalo.Context) error {
// Get the DB connection from the context
tx, ok := c.Value("tx").(*pop.Connection) // you get your connection here
if !ok {
return errors.WithStack(errors.New("no transaction found"))
}
q := tx.RawQuery("select * from foo where id = ?", 1) // you make your query here
if err := q.All(model); err != nil {
return errors.WithStack(err)
}
}
This would be a solution to use Pop but not the predefined models. In that case you just use the connection which comes with the Buffalo context.