From 964b54b84170ea1de45561c011bef51246abad0e Mon Sep 17 00:00:00 2001 From: cukhoaimon Date: Thu, 1 Feb 2024 16:09:41 +0700 Subject: [PATCH] fix: add foreign key for account table --- api/account.go | 7 +++++++ db/migration/000002_add_users.up.sql | 4 +++- db/sqlc/account.sql_test.go | 4 +++- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/api/account.go b/api/account.go index df48396..55764fd 100644 --- a/api/account.go +++ b/api/account.go @@ -3,6 +3,8 @@ package api import ( "database/sql" "errors" + "github.com/lib/pq" + "log" "net/http" db "github.com/cukhoaimon/SimpleBank/db/sqlc" @@ -30,6 +32,11 @@ func (server *Server) createAccount(ctx *gin.Context) { account, err := server.store.CreateAccount(ctx, arg) if err != nil { + var pqErr *pq.Error + if errors.As(err, &pqErr) { + log.Println(pqErr.Code.Name()) + } + ctx.JSON(http.StatusInternalServerError, errorResponse(err)) return } diff --git a/db/migration/000002_add_users.up.sql b/db/migration/000002_add_users.up.sql index 52c2b86..d6a2516 100644 --- a/db/migration/000002_add_users.up.sql +++ b/db/migration/000002_add_users.up.sql @@ -8,4 +8,6 @@ CREATE TABLE "users" ( ); --CREATE INDEX ON "accounts" ("owner", "currency"); -ALTER TABLE "accounts" ADD CONSTRAINT "owner_currency_key" UNIQUE ("owner", "currency"); \ No newline at end of file +ALTER TABLE "accounts" ADD CONSTRAINT "owner_currency_key" UNIQUE ("owner", "currency"); + +ALTER TABLE "accounts" ADD FOREIGN KEY ("owner") REFERENCES "users" ("username"); \ No newline at end of file diff --git a/db/sqlc/account.sql_test.go b/db/sqlc/account.sql_test.go index 225ed2b..f51b954 100644 --- a/db/sqlc/account.sql_test.go +++ b/db/sqlc/account.sql_test.go @@ -11,8 +11,10 @@ import ( ) func createRandomAccount(t *testing.T) Account { + user := createRandomUser(t) + arg := CreateAccountParams{ - Owner: utils.RandomOwner(), + Owner: user.Username, Balance: utils.RandomMoney(), Currency: utils.RandomCurrency(), }