fix: foreign key issue with thumbnails (#824)

This commit is contained in:
Matt
2025-06-29 12:24:22 -04:00
committed by GitHub
parent d83767f4c2
commit f30c9d9156
8 changed files with 80 additions and 17 deletions

View File

@@ -0,0 +1,8 @@
-- +goose Up
alter table public.attachments
drop constraint attachments_attachments_thumbnail;
alter table public.attachments
add constraint attachments_attachments_thumbnail
foreign key (attachment_thumbnail) references public.attachments
on delete set null;

View File

@@ -0,0 +1,45 @@
-- +goose Up
create table attachments_dg_tmp
(
id uuid not null
primary key,
created_at datetime not null,
updated_at datetime not null,
type text default 'attachment' not null,
"primary" bool default false not null,
path text not null,
title text not null,
mime_type text default 'application/octet-stream' not null,
item_attachments uuid
constraint attachments_items_attachments
references items
on delete cascade,
attachment_thumbnail uuid
constraint attachments_attachments_thumbnail
references attachments
on delete set null
);
insert into attachments_dg_tmp(id, created_at, updated_at, type, "primary", path, title, mime_type, item_attachments,
attachment_thumbnail)
select id,
created_at,
updated_at,
type,
"primary",
path,
title,
mime_type,
item_attachments,
attachment_thumbnail
from attachments;
drop table attachments;
alter table attachments_dg_tmp
rename to attachments;
CREATE INDEX IF NOT EXISTS idx_attachments_item_id ON attachments(item_attachments);
CREATE INDEX IF NOT EXISTS idx_attachments_path ON attachments(path);
CREATE INDEX IF NOT EXISTS idx_attachments_type ON attachments(type);
CREATE INDEX IF NOT EXISTS idx_attachments_thumbnail ON attachments(attachment_thumbnail);

View File

@@ -316,6 +316,28 @@ func (r *AttachmentRepo) Delete(ctx context.Context, id uuid.UUID) error {
}
// If this is the last attachment for this path, delete the file
if len(all) == 1 {
thumb, err := doc.QueryThumbnail().First(ctx)
if err != nil && !ent.IsNotFound(err) {
log.Err(err).Msg("failed to query thumbnail for attachment")
return err
}
if thumb != nil {
thumbBucket, err := blob.OpenBucket(ctx, r.GetConnString())
if err != nil {
log.Err(err).Msg("failed to open bucket for thumbnail deletion")
return err
}
err = thumbBucket.Delete(ctx, thumb.Path)
if err != nil {
return err
}
_ = doc.Update().SetNillableThumbnailID(nil).SaveX(ctx)
_ = thumb.Update().SetNillableThumbnailID(nil).SaveX(ctx)
err = r.db.Attachment.DeleteOneID(thumb.ID).Exec(ctx)
if err != nil {
return err
}
}
bucket, err := blob.OpenBucket(ctx, r.GetConnString())
if err != nil {
log.Err(err).Msg("failed to open bucket")