package postgres import ( "context" "errors" "fmt" "time" "github.com/jackc/pgx/v5" "gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model" ) func (s *Store) CreateAttachment(ctx context.Context, attachment model.Attachment) (model.Attachment, error) { const query = ` INSERT INTO attachments ( id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key ) SELECT $1, $2, $3, $4, $5, $6, $7, $8 WHERE EXISTS ( SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3 ) RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, created_at, updated_at` err := s.pool.QueryRow( ctx, query, attachment.ID, attachment.ChatID, attachment.OwnerID, attachment.Filename, attachment.ContentType, attachment.SizeBytes, attachment.SHA256, attachment.ObjectKey, ).Scan( &attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename, &attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey, &attachment.CreatedAt, &attachment.UpdatedAt, ) if errors.Is(err, pgx.ErrNoRows) { return model.Attachment{}, ErrNotFound } if err != nil { return model.Attachment{}, fmt.Errorf("create attachment: %w", err) } return readyAttachment(attachment), nil } func (s *Store) AttachmentForUser(ctx context.Context, attachmentID, userID string) (model.Attachment, error) { const query = ` SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.object_key, a.created_at, a.updated_at FROM attachments a JOIN chat_members member ON member.chat_id = a.chat_id AND member.user_id = $2 WHERE a.id = $1` var attachment model.Attachment err := s.pool.QueryRow(ctx, query, attachmentID, userID).Scan( &attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename, &attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey, &attachment.CreatedAt, &attachment.UpdatedAt, ) if errors.Is(err, pgx.ErrNoRows) { return model.Attachment{}, ErrNotFound } if err != nil { return model.Attachment{}, fmt.Errorf("get attachment for user: %w", err) } return readyAttachment(attachment), nil } func (s *Store) AttachmentByStorage(ctx context.Context, attachmentID, objectKey string) (model.Attachment, error) { const query = ` SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, created_at, updated_at FROM attachments WHERE id = $1 AND object_key = $2` var attachment model.Attachment err := s.pool.QueryRow(ctx, query, attachmentID, objectKey).Scan( &attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename, &attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey, &attachment.CreatedAt, &attachment.UpdatedAt, ) if errors.Is(err, pgx.ErrNoRows) { return model.Attachment{}, ErrNotFound } if err != nil { return model.Attachment{}, fmt.Errorf("get attachment by storage: %w", err) } return readyAttachment(attachment), nil } func (s *Store) ListAttachments(ctx context.Context, afterObjectKey string, limit int) ([]model.Attachment, string, error) { if limit < 1 || limit > 1000 { return nil, "", fmt.Errorf("attachment list limit must be between 1 and 1000") } const query = ` SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, created_at, updated_at FROM attachments WHERE object_key > $1 ORDER BY object_key LIMIT $2` rows, err := s.pool.Query(ctx, query, afterObjectKey, limit+1) if err != nil { return nil, "", fmt.Errorf("list attachments: %w", err) } defer rows.Close() attachments, err := pgx.CollectRows(rows, pgx.RowToFunc[model.Attachment](func(row pgx.CollectableRow) (model.Attachment, error) { var attachment model.Attachment err := row.Scan( &attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename, &attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey, &attachment.CreatedAt, &attachment.UpdatedAt, ) return readyAttachment(attachment), err })) if err != nil { return nil, "", fmt.Errorf("scan attachments: %w", err) } var next string if len(attachments) > limit { attachments = attachments[:limit] next = attachments[len(attachments)-1].ObjectKey } return attachments, next, nil } func (s *Store) AttachmentReferenced(ctx context.Context, attachmentID string) (bool, error) { const query = `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1)` var referenced bool if err := s.pool.QueryRow(ctx, query, attachmentID).Scan(&referenced); err != nil { return false, fmt.Errorf("check attachment references: %w", err) } return referenced, nil } func (s *Store) DeleteAttachmentIfUnreferencedBefore( ctx context.Context, attachmentID string, createdBefore time.Time, ) (bool, error) { const query = ` DELETE FROM attachments a WHERE a.id = $1 AND a.created_at <= $2 AND NOT EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)` result, err := s.pool.Exec(ctx, query, attachmentID, createdBefore) if err != nil { return false, fmt.Errorf("delete old unreferenced attachment: %w", err) } return result.RowsAffected() == 1, nil } func readyAttachment(attachment model.Attachment) model.Attachment { attachment.Status = "ready" attachment.Variants = []model.Variant{} return attachment }