forked from mtusi2026/mtusi2026lab4
65 lines
2.5 KiB
Go
65 lines
2.5 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
|
|
)
|
|
|
|
// Scan returns a bounded metadata page ordered by the stable primary key.
|
|
func (s *Store) Scan(ctx context.Context, after uuid.UUID, limit int) ([]dto.Attachment, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
|
defer cancel()
|
|
rows, err := s.pool.Query(ctx, `SELECT `+attachmentColumns+` FROM attachments WHERE id>@after ORDER BY id LIMIT @limit`, pgx.StrictNamedArgs{"after": after, "limit": limit})
|
|
if err != nil {
|
|
return nil, normalize(err)
|
|
}
|
|
defer rows.Close()
|
|
result := make([]dto.Attachment, 0)
|
|
for rows.Next() {
|
|
a, err := scanAttachment(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
result = append(result, a)
|
|
}
|
|
return result, normalize(rows.Err())
|
|
}
|
|
|
|
// Reclaim uses a durable deleting state to exclude publication during object cleanup.
|
|
func (s *Store) Reclaim(ctx context.Context, id uuid.UUID, cutoff time.Time, finish bool) (bool, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
|
defer cancel()
|
|
query := `UPDATE attachments SET status='deleting' WHERE id=@id AND created_at<@cutoff AND status IN ('uploading','deleting') AND NOT EXISTS(SELECT 1 FROM messages WHERE @textid=ANY(attachment_ids))`
|
|
if finish {
|
|
query = `DELETE FROM attachments WHERE id=@id AND created_at<@cutoff AND status='deleting' AND NOT EXISTS(SELECT 1 FROM messages WHERE @textid=ANY(attachment_ids))`
|
|
}
|
|
tag, err := s.pool.Exec(ctx, query, pgx.StrictNamedArgs{"id": id, "textid": id.String(), "cutoff": cutoff})
|
|
return tag.RowsAffected() == 1, normalize(err)
|
|
}
|
|
|
|
// MarkMissing preserves referenced metadata while recording or clearing an availability incident.
|
|
func (s *Store) MarkMissing(ctx context.Context, id uuid.UUID, missing bool) error {
|
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
|
defer cancel()
|
|
status := "ready"
|
|
if missing {
|
|
status = "missing"
|
|
}
|
|
_, err := s.pool.Exec(ctx, `UPDATE attachments SET status=@status,updated_at=clock_timestamp() WHERE id=@id AND status IN ('ready','missing')`, pgx.StrictNamedArgs{"id": id, "status": status})
|
|
return normalize(err)
|
|
}
|
|
|
|
// HasObject protects even unfinished durable reservations from orphan cleanup.
|
|
func (s *Store) HasObject(ctx context.Context, key string) (bool, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
|
defer cancel()
|
|
var exists bool
|
|
err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachments WHERE object_key=@key)`, pgx.StrictNamedArgs{"key": key}).Scan(&exists)
|
|
return exists, normalize(err)
|
|
}
|