Implementing SQL version of the receipts interface

Signed-off-by: Ethan Wellenreiter <ewellenreiter@gmail.com>
This commit is contained in:
Ethan Wellenreiter 2025-05-05 22:02:52 -04:00
parent 31ef839226
commit 65e18bf7a2

View File

@ -0,0 +1,66 @@
package storage
import (
"context"
"database/sql"
)
type SQLReceiptsStore struct {
db *sql.DB
}
func (s *SQLReceiptsStore) GetByID(ctx context.Context, id int64) (*Receipt, error) {
query := `SELECT id, groupid, data FROM receipts WHERE id = $1`
receipt := &Receipt{}
err := s.db.QueryRowContext(ctx, query, id).Scan(&receipt.ID, &receipt.OwnerID, &receipt.Data)
if err != nil {
return nil, err
}
return receipt, nil
}
func (s *SQLReceiptsStore) Create(ctx context.Context, receipt *Receipt) error {
query := `
INSERT INTO receipts (groupid, data)
VALUES ($1, $2) RETURNING id, created_at, updated_at`
ctx, cancel := context.WithTimeout(ctx, QueryTimeoutDuration)
defer cancel()
err := s.db.QueryRowContext(
ctx,
query,
receipt.OwnerID,
receipt.Data, // might need to marshal or serialize this
).Scan(
&receipt.ID,
&receipt.CreatedAt,
&receipt.UpdatedAt,
)
return err
}
func (s *SQLReceiptsStore) Delete(ctx context.Context, id int64) error {
query := `DELETE FROM receipts WHERE id = $1`
ctx, cancel := context.WithTimeout(ctx, QueryTimeoutDuration)
defer cancel()
res, err := s.db.ExecContext(ctx, query, id)
if err != nil {
return err
}
rows, err := res.RowsAffected()
if err != nil {
return err
}
if rows == 0 {
return ErrNotFound
}
return nil
}