80 lines
1.5 KiB
Go
80 lines
1.5 KiB
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
)
|
|
|
|
type SQLImagesStore struct {
|
|
db *sql.DB
|
|
}
|
|
|
|
func (s SQLImagesStore) GetByID(ctx context.Context, id int64) (*Image, error) {
|
|
query := `SELECT id, receiptid, created_at, path FROM images WHERE id = $1`
|
|
|
|
image := &Image{}
|
|
err := s.db.QueryRowContext(ctx, query, id).Scan(&image.ID, &image.ReceiptID, &image.CreatedAt, &image.Path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return image, nil
|
|
}
|
|
|
|
func (s SQLImagesStore) Create(ctx context.Context, img *Image) error {
|
|
query := `
|
|
INSERT INTO images (receiptid, path)
|
|
VALUES ($1, $2) RETURNING id, created_at`
|
|
|
|
ctx, cancel := context.WithTimeout(ctx, QueryTimeoutDuration)
|
|
defer cancel()
|
|
|
|
err := s.db.QueryRowContext(
|
|
ctx,
|
|
query,
|
|
img.ReceiptID,
|
|
img.Path, // might need to marshal or serialize this
|
|
).Scan(
|
|
&img.ID,
|
|
&img.CreatedAt,
|
|
)
|
|
return err
|
|
}
|
|
|
|
func (s SQLImagesStore) Delete(ctx context.Context, id int64) error {
|
|
query := `DELETE FROM images 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
|
|
}
|
|
|
|
func (s SQLImagesStore) ActivateImage(ctx context.Context, id int64) error {
|
|
query := `UPDATE images SET added = $1`
|
|
|
|
ctx, cancel := context.WithTimeout(ctx, QueryTimeoutDuration)
|
|
defer cancel()
|
|
|
|
_, err := s.db.ExecContext(ctx, query, true)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|