Introduce own Numeric type and revert to stdlib from pgx

This commit is contained in:
2021-12-02 21:29:44 +00:00
parent 6f8a94ff5d
commit 4646356b2d
16 changed files with 136 additions and 57 deletions

View File

@ -22,39 +22,72 @@ type CreateAccountParams struct {
}
func (q *Queries) CreateAccount(ctx context.Context, arg CreateAccountParams) (Account, error) {
row := q.db.QueryRow(ctx, createAccount, arg.Name, arg.BudgetID)
row := q.db.QueryRowContext(ctx, createAccount, arg.Name, arg.BudgetID)
var i Account
err := row.Scan(&i.ID, &i.BudgetID, &i.Name)
return i, err
}
const getAccounts = `-- name: GetAccounts :many
SELECT accounts.id, accounts.name, SUM(transactions.amount) as balance FROM accounts
SELECT accounts.id, accounts.budget_id, accounts.name FROM accounts
WHERE accounts.budget_id = $1
AND transactions.date < NOW()
GROUP BY accounts.id, accounts.name
`
type GetAccountsRow struct {
ID uuid.UUID
Name string
Balance int64
}
func (q *Queries) GetAccounts(ctx context.Context, budgetID uuid.UUID) ([]GetAccountsRow, error) {
rows, err := q.db.Query(ctx, getAccounts, budgetID)
func (q *Queries) GetAccounts(ctx context.Context, budgetID uuid.UUID) ([]Account, error) {
rows, err := q.db.QueryContext(ctx, getAccounts, budgetID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetAccountsRow
var items []Account
for rows.Next() {
var i GetAccountsRow
if err := rows.Scan(&i.ID, &i.Name, &i.Balance); err != nil {
var i Account
if err := rows.Scan(&i.ID, &i.BudgetID, &i.Name); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getAccountsWithBalance = `-- name: GetAccountsWithBalance :many
SELECT accounts.id, accounts.name, SUM(transactions.amount)::decimal(12,2) as balance
FROM accounts
LEFT JOIN transactions ON transactions.account_id = accounts.id
WHERE accounts.budget_id = $1
AND transactions.date < NOW()
GROUP BY accounts.id, accounts.name
`
type GetAccountsWithBalanceRow struct {
ID uuid.UUID
Name string
Balance Numeric
}
func (q *Queries) GetAccountsWithBalance(ctx context.Context, budgetID uuid.UUID) ([]GetAccountsWithBalanceRow, error) {
rows, err := q.db.QueryContext(ctx, getAccountsWithBalance, budgetID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetAccountsWithBalanceRow
for rows.Next() {
var i GetAccountsWithBalanceRow
if err := rows.Scan(&i.ID, &i.Name, &i.Balance); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}