Search code examples
gosqlx

Inserting request body into database


I'm developing an API using Go, SQLX, postgres and go-swagger.

In POST method handler I get a request body of a type defined and validated by swagger. After validation I'd like to insert that into a postgres table.

I haven't found much documentation about the subject except for the following snippet:

sqlStatement := `
INSERT INTO users (age, email, first_name, last_name)
VALUES ($1, $2, $3, $4)
RETURNING id`
  id := 0
  err = db.QueryRow(sqlStatement, 30, "[email protected]", "Jonathan", "Calhoun").Scan(&id)

Which means I need to describe every single field of the struct I want to persist.

Is there a method that will just take a struct to be saved in a table?

db.save(struct)

Solution

  • It's in the examples in the README:

    // Named queries can use structs, so if you have an existing struct (i.e. person := &Person{}) that you have populated, you can pass it in as &person
    tx.NamedExec("INSERT INTO person (first_name, last_name, email) VALUES (:first_name, :last_name, :email)", &Person{"Jane", "Citizen", "[email protected]"})