From ad96e6627f77cc3badbbec864736d314a3e78f3b Mon Sep 17 00:00:00 2001
From: Gregor Best <gbe@unobtanium.de>
Date: Tue, 20 Apr 2021 22:00:09 +0200
Subject: [PATCH] Redirect to newly created entries

---
 handler-index.go |  2 +-
 vino.go          | 24 +++++++++++++++++++++---
 2 files changed, 22 insertions(+), 4 deletions(-)

diff --git a/handler-index.go b/handler-index.go
index e7405e5..cf0b064 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 f3242e7..37ae9fb 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) {
-- 
GitLab