Implementing SQL Image Store
Signed-off-by: Ethan Wellenreiter <ewellenreiter@gmail.com>
This commit is contained in:
parent
47f6cf8885
commit
9e580c50cc
79
backend/internal/storage/sql-images.go
Normal file
79
backend/internal/storage/sql-images.go
Normal file
@ -0,0 +1,79 @@
|
||||
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
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user