Files
tern-server/migrations/0003_messages_bodies_attachments.sql
Mateusz PstruchaandClaude Opus 5 4c1a6457c5 Initial sync server: IMAP engine, schema, and read API
Covers phases 1-2 of the build order in the architecture spec: the IMAP
sync engine (IDLE + UIDVALIDITY tracking + jittered reconnect, headers
first with lazy body fetch), the full data model, and a minimal REST API
for auth, accounts, folders, messages and delta polling.

Credentials are encrypted at rest with ChaCha20-Poly1305 rather than
libsodium secretbox, to avoid a system dependency for the same
construction.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 19:00:59 +02:00

61 lines
2.5 KiB
SQL

-- Core message store (server-architecture-spec.md §3.4, §3.6).
-- thread_id is its own generated id (not the root Message-ID) because threads
-- can merge later once a missing ancestor arrives — see §3.6.
CREATE TABLE folders (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (user_id, name)
);
CREATE TABLE messages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
account_id UUID NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
folder_id UUID REFERENCES folders(id) ON DELETE SET NULL,
uid BIGINT NOT NULL,
message_id TEXT, -- Message-ID header (not guaranteed unique across servers)
in_reply_to TEXT,
references_ TEXT[] NOT NULL DEFAULT '{}',
thread_id UUID NOT NULL DEFAULT gen_random_uuid(),
from_addr TEXT,
from_name TEXT,
to_addrs TEXT[] NOT NULL DEFAULT '{}',
cc_addrs TEXT[] NOT NULL DEFAULT '{}',
subject TEXT,
sent_at TIMESTAMPTZ,
flags TEXT[] NOT NULL DEFAULT '{}', -- \Seen, \Flagged, etc, plus app flags
spam_score REAL,
body_fetched BOOLEAN NOT NULL DEFAULT false, -- headers-first sync: body may be lazy
raw_blob_ref TEXT, -- filesystem path to the raw MIME blob
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (account_id, uid)
);
CREATE INDEX messages_account_id_idx ON messages(account_id);
CREATE INDEX messages_thread_id_idx ON messages(thread_id);
CREATE INDEX messages_message_id_idx ON messages(message_id);
CREATE INDEX messages_in_reply_to_idx ON messages(in_reply_to);
CREATE INDEX messages_sent_at_idx ON messages(sent_at DESC);
CREATE INDEX messages_folder_id_idx ON messages(folder_id);
CREATE TABLE bodies (
message_id UUID PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
text_body TEXT,
html_body TEXT
);
CREATE TABLE attachments (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
filename TEXT,
content_type TEXT,
size BIGINT NOT NULL,
content_hash TEXT NOT NULL, -- dedupe identical attachments across messages
blob_ref TEXT NOT NULL -- filesystem path derived from content_hash
);
CREATE INDEX attachments_message_id_idx ON attachments(message_id);
CREATE INDEX attachments_content_hash_idx ON attachments(content_hash);