-
Notifications
You must be signed in to change notification settings - Fork 0
/
account.go
94 lines (83 loc) · 2.18 KB
/
account.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package bank
import (
"net/http"
// sqlite3 "github.com/mattn/go-sqlite3"
"database/sql"
"github.com/ewxrjk/bank/pkg/bcommon"
)
// Account defines a single account.
type Account struct {
// Name of the account
Account string
// Current balance
Balance int
}
// ErrNoSuchAccount is returned when accessing an account which does not exist.
var ErrNoSuchAccount = bcommon.HTTPError{"account does not exist", http.StatusNotFound}
// ErrAccountHasBalance is returned when deleting a nonempty account.
var ErrAccountHasBalance = bcommon.HTTPError{"account has a nonzero balance", http.StatusBadRequest}
// GetAccounts returns the list of account names.
func GetAccounts(tx *sql.Tx) (accounts []string, err error) {
var rows *sql.Rows
if rows, err = tx.Query("SELECT user FROM accounts ORDER BY user"); err != nil {
return
}
defer rows.Close()
accounts = []string{}
for rows.Next() {
var account string
if err = rows.Scan(&account); err != nil {
return
}
accounts = append(accounts, account)
}
return
}
// Get fills in the data for a account.
func (a *Account) Get(tx *sql.Tx, account string) (err error) {
err = tx.QueryRow("SELECT user, balance FROM accounts WHERE user=?", account).Scan(&a.Account, &a.Balance)
if err == sql.ErrNoRows {
err = ErrNoSuchAccount
}
if err != nil {
return
}
return
}
// Put updates account data in the database.
// Set new to true to create or false to update.
func (a *Account) Put(tx *sql.Tx, new bool) (err error) {
if new {
_, err = tx.Exec("INSERT INTO accounts (user, balance) VALUES (?, ?)", a.Account, a.Balance)
} else {
_, err = tx.Exec("UPDATE accounts SET balance=? WHERE user=?", a.Balance, a.Account)
}
if err != nil {
return
}
return
}
// Delete deletes an account.
//
// Accounts with nonzero balances cannot be deleted.
func (a *Account) Delete(tx *sql.Tx) (err error) {
if err = a.Get(tx, a.Account); err != nil {
return
}
if a.Balance != 0 {
return ErrAccountHasBalance
}
var r sql.Result
if r, err = tx.Exec("DELETE FROM accounts WHERE user=?", a.Account); err != nil {
return
}
var rows int64
if rows, err = r.RowsAffected(); err != nil {
return
}
if rows != 1 {
err = ErrNoSuchAccount
return
}
return
}