Skip to content

Commit 46bc3c0

Browse files
accounts+db: Add sql db DebitAccount query
This commit adds a separate `DebitAccount` 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.
1 parent 474c538 commit 46bc3c0

File tree

4 files changed

+37
-17
lines changed

4 files changed

+37
-17
lines changed

accounts/store_sql.go

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ const (
3535
type SQLQueries interface {
3636
AddAccountInvoice(ctx context.Context, arg sqlc.AddAccountInvoiceParams) error
3737
CreditAccount(ctx context.Context, arg sqlc.CreditAccountParams) (int64, error)
38+
DebitAccount(ctx context.Context, arg sqlc.DebitAccountParams) (int64, error)
3839
DeleteAccount(ctx context.Context, id int64) error
3940
DeleteAccountPayment(ctx context.Context, arg sqlc.DeleteAccountPaymentParams) error
4041
GetAccount(ctx context.Context, id int64) (sqlc.Account, error)
@@ -423,26 +424,17 @@ func (s *SQLStore) DebitAccount(ctx context.Context, alias AccountID,
423424
return err
424425
}
425426

426-
acct, err := db.GetAccount(ctx, id)
427-
if err != nil {
428-
return err
429-
}
430-
431-
if acct.CurrentBalanceMsat-int64(amount) < 0 {
427+
id, err = db.DebitAccount(
428+
ctx, sqlc.DebitAccountParams{
429+
ID: id,
430+
Amount: int64(amount),
431+
},
432+
)
433+
if errors.Is(err, sql.ErrNoRows) {
432434
return fmt.Errorf("cannot debit %v from the account "+
433435
"balance, as the resulting balance would be "+
434436
"below 0", int64(amount/1000))
435-
}
436-
437-
newBalance := acct.CurrentBalanceMsat - int64(amount)
438-
439-
_, err = db.UpdateAccountBalance(
440-
ctx, sqlc.UpdateAccountBalanceParams{
441-
ID: id,
442-
CurrentBalanceMsat: newBalance,
443-
},
444-
)
445-
if err != nil {
437+
} else if err != nil {
446438
return err
447439
}
448440

db/sqlc/accounts.sql.go

Lines changed: 20 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

db/sqlc/querier.go

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

db/sqlc/queries/accounts.sql

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,13 @@ SET current_balance_msat = current_balance_msat + sqlc.arg(amount)
1515
WHERE id = $1
1616
RETURNING id;
1717

18+
-- name: DebitAccount :one
19+
UPDATE accounts
20+
SET current_balance_msat = current_balance_msat - sqlc.arg(amount)
21+
WHERE id = $1
22+
AND current_balance_msat >= sqlc.arg(amount)
23+
RETURNING id;
24+
1825
-- name: UpdateAccountExpiry :one
1926
UPDATE accounts
2027
SET expiration = $1

0 commit comments

Comments
 (0)