Files

58 lines
2.2 KiB
Go

package postgres
import (
"backend/internal/adapter/repository/postgres/queries"
"backend/internal/domain/model"
"context"
"encoding/json"
"github.com/google/uuid"
)
func attachment(r queries.Attachment) model.Attachment {
var variants []model.Variant
_ = json.Unmarshal(r.Variants, &variants)
return model.Attachment{ID: r.ID, ChatID: r.ChatID, OwnerID: r.OwnerID, Filename: r.Filename, ContentType: r.ContentType, SizeBytes: r.SizeBytes, SHA256: r.Sha256, Status: r.Status, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt, PipelineVersion: r.PipelineVersion, ErrorCode: r.ErrorCode, Variants: variants, StagingExpired: r.StagingExpired, StagingCleaned: r.StagingCleaned}
}
func (s *Store) ReserveAttachment(ctx context.Context, a model.Attachment) (model.Attachment, error) {
tx, e := s.pool.Begin(ctx)
if e != nil {
return model.Attachment{}, mapErr(e)
}
defer func() { _ = tx.Rollback(ctx) }()
q := s.q.WithTx(tx)
if _, e = q.ChargeAttachment(ctx, a.OwnerID); e != nil {
return model.Attachment{}, model.ErrStorageFull
}
r, e := q.InsertAttachment(ctx, queries.InsertAttachmentParams{ID: a.ID, ChatID: a.ChatID, OwnerID: a.OwnerID, Filename: a.Filename, ContentType: a.ContentType, SizeBytes: a.SizeBytes, Sha256: a.SHA256})
if e != nil {
return model.Attachment{}, mapErr(e)
}
if e = tx.Commit(ctx); e != nil {
return model.Attachment{}, mapErr(e)
}
return attachment(r), nil
}
func (s *Store) GetAttachment(ctx context.Context, id uuid.UUID) (model.Attachment, error) {
r, e := s.q.GetAttachment(ctx, id)
return attachment(r), mapErr(e)
}
func (s *Store) SetAttachmentStatus(ctx context.Context, id uuid.UUID, from, to string) (bool, error) {
n, e := s.q.SetAttachmentStatus(ctx, queries.SetAttachmentStatusParams{ID: id, Status: to, Status_2: from})
return n == 1, mapErr(e)
}
func (s *Store) ReconcileAttachments(ctx context.Context, after uuid.UUID) ([]model.Attachment, bool, error) {
rows, e := s.q.ReconcileAttachments(ctx, after)
if e != nil {
return nil, false, mapErr(e)
}
more := len(rows) > 100
if more {
rows = rows[:100]
}
out := make([]model.Attachment, len(rows))
for i, r := range rows {
out[i] = attachment(r)
}
return out, more, nil
}