From 46386b19a3cb8356bbdc4ea94ff0f75a913957f7 Mon Sep 17 00:00:00 2001 From: vinchent Date: Wed, 7 Aug 2024 12:07:21 +0200 Subject: [PATCH] inserting a new transaction --- internal/models/models.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/internal/models/models.go b/internal/models/models.go index 3defd81..ba8bef7 100644 --- a/internal/models/models.go +++ b/internal/models/models.go @@ -113,3 +113,31 @@ func (m *DBModel) GetWidget(id int) (Widget, error) { } return widget, nil } + +// InsertTransaction inserts a new txn, and returns its id +func (m *DBModel) InsertTransaction(txn Transaction) (int, error) { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + + stmt := `INSERT INTO transactions + (amount, currency, last_four, bank_return_code, + transaction_status_id, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?)` + + result, err := m.DB.ExecContext(ctx, stmt, + txn.Amount, + txn.Currency, + txn.LastFour, + txn.BankReturnCode, + txn.TransactionStatusID, + txn.CreatedAt, + txn.UpdatedAt) + if err != nil { + return 0, err + } + id, err := result.LastInsertId() + if err != nil { + return 0, err + } + return int(id), nil +}