From 7cb508eb8a77e08b96706c6268039cb70870d16a Mon Sep 17 00:00:00 2001 From: towards-a-new-leftypol Date: Wed, 28 Feb 2024 00:29:28 -0500 Subject: [PATCH] Add attachment_idx column, constraint and populate it --- sql/add_attachment_idx.sql | 11 +++++++++++ sql/initialize.sql | 6 +++++- 2 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 sql/add_attachment_idx.sql diff --git a/sql/add_attachment_idx.sql b/sql/add_attachment_idx.sql new file mode 100644 index 0000000..f591fc1 --- /dev/null +++ b/sql/add_attachment_idx.sql @@ -0,0 +1,11 @@ +WITH indexed_attachments AS ( + SELECT + attachment_id, + ROW_NUMBER() OVER (PARTITION BY post_id ORDER BY attachment_id) AS index + FROM + attachments +) +UPDATE attachments +SET attachment_idx = indexed_attachments.index +FROM indexed_attachments +WHERE attachments.attachment_id = indexed_attachments.attachment_id; diff --git a/sql/initialize.sql b/sql/initialize.sql index 341e0b6..3893249 100644 --- a/sql/initialize.sql +++ b/sql/initialize.sql @@ -121,12 +121,16 @@ CREATE TABLE IF NOT EXISTS attachments , board_filename text NOT NULL , spoiler boolean NOT NULL DEFAULT true , file_size_bytes int + , attachment_idx int NOT NULL , CONSTRAINT post_fk FOREIGN KEY (post_id) REFERENCES posts (post_id) ON DELETE CASCADE + , CONSTRAINT unique_post_attachment_idx UNIQUE (post_id, attachment_idx) ); CREATE INDEX attachments_creation_time_idx ON attachments (creation_time); CREATE INDEX attachments_post_id_idx ON attachments (post_id); CREATE INDEX attachments_sha256_hash_idx ON attachments (sha256_hash); --- +CREATE INDEX attachments_attachment_idx_idx ON attachments (attachment_idx); + + -- Index using the bktree extension for quickly getting the closest phashes CREATE INDEX attachments_phash_bktree_index ON attachments USING spgist (phash bktree_ops);