Files
spend-sparrow/db/account.go
Tim Wundenberg b20a48be25
Some checks failed
Build Docker Image / Build-Docker-Image (push) Failing after 6m59s
feat: use sqlx
2025-05-04 15:53:41 +02:00

119 lines
2.7 KiB
Go

package db
import (
"spend-sparrow/log"
"spend-sparrow/types"
"github.com/jmoiron/sqlx"
"github.com/google/uuid"
)
type Account interface {
Insert(account *types.Account) error
Update(account *types.Account) error
GetAll(groupId uuid.UUID) ([]*types.Account, error)
Get(groupId uuid.UUID, id uuid.UUID) (*types.Account, error)
Delete(id uuid.UUID) error
}
type AccountSqlite struct {
db *sqlx.DB
}
func NewAccountSqlite(db *sqlx.DB) *AccountSqlite {
return &AccountSqlite{db: db}
}
func (db AccountSqlite) Insert(account *types.Account) error {
_, err := db.db.Exec(`
INSERT INTO account (id, group_id, name, current_balance, oink_balance, created_at, created_by)
VALUES (?,?,?,?,?,?,?)`, account.Id, account.GroupId, 0, 0, account.CreatedAt, account.CreatedBy)
if err != nil {
log.Error("Error inserting account: %v", err)
return types.ErrInternal
}
return nil
}
func (db AccountSqlite) Update(account *types.Account) error {
_, err := db.db.Exec(`
UPDATE account
name = ?,
current_balance = ?,
last_transaction = ?,
oink_balance = ?,
updated_at = ?,
updated_by = ?,
WHERE id = ?
AND group_id = ?`, account.Name, account.CurrentBalance, account.LastTransaction, account.OinkBalance, account.UpdatedAt, account.UpdatedBy, account.Id, account.GroupId)
if err != nil {
log.Error("Error updating account: %v", err)
return types.ErrInternal
}
return nil
}
func (db AccountSqlite) GetAll(groupId uuid.UUID) ([]*types.Account, error) {
accounts := make([]*types.Account, 0)
err := db.db.Select(&accounts, `
SELECT
id, name,
current_balance, last_transaction, oink_balance,
created_at, created_by, updated_at, updated_by
FROM account
WHERE group_id = ?
ORDER BY name`, groupId)
if err != nil {
log.Error("Could not getAll accounts: %v", err)
return nil, types.ErrInternal
}
return accounts, nil
}
func (db AccountSqlite) Get(groupId uuid.UUID, id uuid.UUID) (*types.Account, error) {
account := &types.Account{}
err := db.db.Get(account, `
SELECT
id, name,
current_balance, last_transaction, oink_balance,
created_at, created_by, updated_at, updated_by
FROM account
WHERE group_id = ?
AND id = ?`, groupId, id)
if err != nil {
log.Error("Could not get accounts: %v", err)
return nil, types.ErrInternal
}
return account, nil
}
func (db AccountSqlite) Delete(id uuid.UUID) error {
res, err := db.db.Exec("DELETE FROM account WHERE id = ?", id)
if err != nil {
log.Error("Error deleting account: %v", err)
return types.ErrInternal
}
rows, err := res.RowsAffected()
if err != nil {
log.Error("Error deleting account, getting rows affected: %v", err)
return types.ErrInternal
}
if rows == 0 {
return ErrNotFound
}
return nil
}