From 9f5f5413d12d7197b4c832864c467bf1a0f73d8a Mon Sep 17 00:00:00 2001 From: Deepak Date: Tue, 29 Dec 2020 18:44:37 -0600 Subject: [PATCH] Adds insert plan function --- store/postgres.go | 15 +++++++++++++-- store/postgres_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/store/postgres.go b/store/postgres.go index 06f1241..d4c126f 100644 --- a/store/postgres.go +++ b/store/postgres.go @@ -1,7 +1,6 @@ package store import ( - "fmt" "gitea.deepak.science/deepak/gogmagog/models" "gitea.deepak.science/deepak/gogmagog/util" "github.com/jmoiron/sqlx" @@ -55,5 +54,17 @@ func (store *postgresStore) SelectPlanByID(id int) (*models.Plan, error) { } func (store *postgresStore) InsertPlan(plan *models.Plan) (int, error) { - return 0, fmt.Errorf("Unimplemented method") + queryString := store.db.Rebind("INSERT INTO plans (plan_date) VALUES (?) RETURNING plan_id") + tx := store.db.MustBegin() + var id int + err := tx.Get(&id, queryString, plan.PlanDate) + if err != nil { + tx.Rollback() + return -1, err + } + err = tx.Commit() + if err != nil { + return -1, err + } + return id, nil } diff --git a/store/postgres_test.go b/store/postgres_test.go index afabdb9..90de7a7 100644 --- a/store/postgres_test.go +++ b/store/postgres_test.go @@ -68,6 +68,35 @@ func TestSelectPlanByID(t *testing.T) { } } +func TestInsertPlan(t *testing.T) { + // setup + assert := assert.New(t) + + str, mock := getDbMock(t) + planDate, _ := time.Parse("2006-01-02", "2021-01-01") + plan := &models.Plan{PlanDate: planDate} + + idToUse := 8 + + rows := sqlmock.NewRows([]string{"plan_id"}).AddRow(8) + + mock.ExpectBegin() + mock.ExpectQuery("^INSERT INTO plans \\(plan_date\\) VALUES \\(\\$1\\) RETURNING plan_id$"). + WithArgs(planDate). + WillReturnRows(rows) + mock.ExpectCommit() + + // function under test + insertedId, err := str.InsertPlan(plan) + // check results + assert.Nil(err) + assert.EqualValues(idToUse, insertedId) + if err := mock.ExpectationsWereMet(); err != nil { + t.Errorf("unfulfilled expectations: %s", err) + } + +} + func TestErrPlanByID(t *testing.T) { assert := assert.New(t)