diff --git a/handler-index.go b/handler-index.go index e7405e58ee1a877c5801d9e3d31bac057c3907cf..cf0b064df1dea076774870545c8d23a6705923be 100644 --- a/handler-index.go +++ b/handler-index.go @@ -94,5 +94,5 @@ func (h Handler) index(w http.ResponseWriter, r *http.Request) { return } - http.Redirect(w, r, "/", http.StatusSeeOther) // TODO: Is this the correct status? + http.Redirect(w, r, "/details?id="+strconv.Itoa(vino.ID), http.StatusSeeOther) // TODO: Is this the correct status? } diff --git a/vino.go b/vino.go index f3242e7e6ddba5e195caa2ef6346df1b9f020529..37ae9fbc205ad30f97a3287b17903468ac272ca9 100644 --- a/vino.go +++ b/vino.go @@ -107,7 +107,12 @@ func (v Vino) String() string { return fmt.Sprintf("{Name: %q, Rating: %d}", v.Name, v.Rating) } -func (v Vino) Store(ctx context.Context, db *sqlx.DB, op storeOperation) (err error) { +func (v *Vino) Store(ctx context.Context, db *sqlx.DB, op storeOperation) (err error) { + if op == Add && v.ID != 0 { + // If we already have an ID, the op needs to be an Update + return errors.New("add with already-set ID") + } + values := map[string]interface{}{ "name": v.Name, "rating": v.Rating, @@ -170,12 +175,25 @@ func (v Vino) Store(ctx context.Context, db *sqlx.DB, op storeOperation) (err er return err } - _, err = squirrel.Insert("wines"). + res, err := squirrel.Insert("wines"). SetMap(values). RunWith(tx). ExecContext(ctx) + if err != nil { + return err + } + + id, err := res.LastInsertId() + if err != nil { + return err + } - return err + // If it's an add (i.e. initial creation of an entry) fill in the ID + log.Println("insert result:", res, "id:", id) + + v.ID = int(id) + + return nil } func ListWines(ctx context.Context, db *sqlx.DB) ([]Vino, error) {