github.com/paulwerner/bookkeeper@v0.1.0/store/transactionStore.go (about) 1 package store 2 3 import ( 4 "database/sql" 5 6 d "github.com/paulwerner/bookkeeper/pkg/domain" 7 "github.com/paulwerner/bookkeeper/pkg/uc" 8 ) 9 10 type transactionStore struct { 11 db *sql.DB 12 } 13 14 func NewTransactionStore(db *sql.DB) uc.TransactionStore { 15 return &transactionStore{ 16 db: db, 17 } 18 } 19 20 func (ts *transactionStore) Create(tx d.Transaction) (*d.Transaction, error) { 21 sqlStatement := `INSERT INTO transactions ( 22 id, 23 account_id, 24 description, 25 amount, 26 currency 27 ) VALUES ($1, $2, $3, $4, $5)` 28 if _, err := ts.db.Exec(sqlStatement, tx.ID, tx.Account.ID, tx.Description, tx.Amount, tx.Currency); err != nil { 29 return nil, err 30 } 31 return ts.FindByIDAndAccount(tx.ID, tx.Account.ID) 32 } 33 34 func (ts *transactionStore) FindAll(aID d.AccountID) (txs []d.Transaction, err error) { 35 sqlStatement := `SELECT id, account_id, description, amount, currency FROM transactions WHERE account_id=$1` 36 rows, err := ts.db.Query(sqlStatement, aID) 37 defer rows.Close() 38 if err != nil && err != sql.ErrNoRows { 39 err = d.ErrInternalError 40 return 41 } 42 for rows.Next() { 43 var tx d.Transaction 44 err = rows.Scan(&tx.ID, &tx.Account.ID, &tx.Description, &tx.Amount, &tx.Currency) 45 if err != nil { 46 err = d.ErrInternalError 47 return 48 } 49 txs = append(txs, tx) 50 } 51 return 52 } 53 54 func (ts *transactionStore) FindByIDAndAccount(id d.TransactionID, aID d.AccountID) (*d.Transaction, error) { 55 var tx d.Transaction 56 sqlStatement := `SELECT id, account_id, description, amount, currency FROM transactions WHERE id=$1 AND account_id=$2` 57 if err := ts.db.QueryRow(sqlStatement, id, aID). 58 Scan(&tx.ID, &tx.Account.ID, &tx.Description, &tx.Amount, &tx.Currency); err != nil { 59 switch err { 60 case sql.ErrNoRows: 61 err = d.ErrNotFound 62 default: 63 err = d.ErrInternalError 64 } 65 return nil, err 66 } 67 return &tx, nil 68 }