Skip to content

Commit

Permalink
accounts+db: Add sql db CreditAccount query
Browse files Browse the repository at this point in the history
This commit adds a separate `CreditAccount` query to the sql db, to
incentivize not setting the balance directly, but rather instead
increase and decrease the balance by a specific amount.

We also update the sql store to use the new query function, instead of
setting the balance directly.
  • Loading branch information
ViktorTigerstrom committed Feb 18, 2025
1 parent 21c0677 commit 44ae7e0
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 11 deletions.
16 changes: 5 additions & 11 deletions accounts/store_sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ const (
//nolint:lll
type SQLQueries interface {
AddAccountInvoice(ctx context.Context, arg sqlc.AddAccountInvoiceParams) error
CreditAccount(ctx context.Context, arg sqlc.CreditAccountParams) (int64, error)
DeleteAccount(ctx context.Context, id int64) error
DeleteAccountPayment(ctx context.Context, arg sqlc.DeleteAccountPaymentParams) error
GetAccount(ctx context.Context, id int64) (sqlc.Account, error)
Expand Down Expand Up @@ -396,17 +397,10 @@ func (s *SQLStore) IncreaseAccountBalance(ctx context.Context, alias AccountID,
return err
}

acct, err := db.GetAccount(ctx, id)
if err != nil {
return err
}

newBalance := acct.CurrentBalanceMsat + int64(amount)

_, err = db.UpdateAccountBalance(
ctx, sqlc.UpdateAccountBalanceParams{
ID: id,
CurrentBalanceMsat: newBalance,
_, err = db.CreditAccount(
ctx, sqlc.CreditAccountParams{
ID: id,
Amount: int64(amount),
},
)
if err != nil {
Expand Down
19 changes: 19 additions & 0 deletions db/sqlc/accounts.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions db/sqlc/querier.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions db/sqlc/queries/accounts.sql
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ SET current_balance_msat = $1
WHERE id = $2
RETURNING id;

-- name: CreditAccount :one
UPDATE accounts
SET current_balance_msat = current_balance_msat + sqlc.arg(amount)
WHERE id = $1
RETURNING id;

-- name: UpdateAccountExpiry :one
UPDATE accounts
SET expiration = $1
Expand Down

0 comments on commit 44ae7e0

Please sign in to comment.