sha256 Content Hash Dedups Uploads

Deduplicate uploads by content: a generated sha256 column plus a unique expression index rejects the second identical payload at insert time.

SqlData Integrity

Code

snippet
CREATE TABLE uploads (
    id           int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    content      text NOT NULL,
    content_hash bytea GENERATED ALWAYS AS (sha256(convert_to(content, 'UTF8'))) STORED
);

-- 内容寻址:表达式唯一索引让同内容第二行直接违反约束
CREATE UNIQUE INDEX uploads_hash_unique ON uploads (content_hash);

INSERT INTO uploads (content) VALUES ('report-v1');
INSERT INTO uploads (content) VALUES ('report-v2');

DO $$
BEGIN
    INSERT INTO uploads (content) VALUES ('report-v1');
    RAISE NOTICE 'duplicate accepted';
EXCEPTION
    WHEN unique_violation THEN
        RAISE NOTICE 'duplicate rejected: same content hash';
END $$;

SELECT id, content, encode(content_hash, 'hex') AS hash_hex FROM uploads ORDER BY id;

What the code does

SELECT / INSERT / CREATE statements share the script, touching uploads.

Breaking the statements into their working parts: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Applying it

Run the statement against the uploads table.

Statements that matter

DO $$
BEGIN
    INSERT INTO uploads (content) VALUES ('report-v1');
    RAISE NOTICE 'duplicate accepted';
EXCEPTION
    WHEN unique_violation THEN
        RAISE NOTICE 'duplicate rejected: same content hash';
END $$;
CREATE TABLE uploads (
    id           int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    content      text NOT NULL,
    content_hash bytea GENERATED ALWAYS AS (sha256(convert_to(content, 'UTF8'))) STORED
);
SELECT id, content, encode(content_hash, 'hex') AS hash_hex FROM uploads ORDER BY id;

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
`uploads`.