Skip to content

Commit

Permalink
fix: add foreign key for account table
Browse files Browse the repository at this point in the history
  • Loading branch information
cukhoaimon committed Feb 1, 2024
1 parent 9268412 commit 964b54b
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 2 deletions.
7 changes: 7 additions & 0 deletions api/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package api
import (
"database/sql"
"errors"
"github.com/lib/pq"
"log"
"net/http"

db "github.com/cukhoaimon/SimpleBank/db/sqlc"
Expand Down Expand Up @@ -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
}
Expand Down
4 changes: 3 additions & 1 deletion db/migration/000002_add_users.up.sql
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ CREATE TABLE "users" (
);

--CREATE INDEX ON "accounts" ("owner", "currency");
ALTER TABLE "accounts" ADD CONSTRAINT "owner_currency_key" UNIQUE ("owner", "currency");
ALTER TABLE "accounts" ADD CONSTRAINT "owner_currency_key" UNIQUE ("owner", "currency");

ALTER TABLE "accounts" ADD FOREIGN KEY ("owner") REFERENCES "users" ("username");
4 changes: 3 additions & 1 deletion db/sqlc/account.sql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
}
Expand Down

0 comments on commit 964b54b

Please sign in to comment.