CREATE TABLE users ( id uuid PRIMARY KEY, username text NOT NULL UNIQUE CHECK(username ~ '^[a-z0-9_]{3,32}$'), display_name text NOT NULL CHECK(length(btrim(display_name))>0 AND length(display_name)<=100), password_hash text NOT NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp() ); CREATE TABLE chats (id uuid PRIMARY KEY, title text NOT NULL CHECK(length(btrim(title))>0 AND length(title)<=100), created_at timestamptz NOT NULL DEFAULT clock_timestamp()); CREATE TABLE members (chat_id uuid REFERENCES chats ON DELETE CASCADE, user_id uuid REFERENCES users, PRIMARY KEY(chat_id,user_id)); CREATE INDEX members_user ON members(user_id,chat_id); CREATE TABLE attachments ( id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats, owner_id uuid NOT NULL REFERENCES users, object_key text NOT NULL UNIQUE, filename text NOT NULL, content_type text NOT NULL, size_bytes bigint NOT NULL, sha256 char(64) NOT NULL, status text NOT NULL CHECK(status IN ('queued','processing','ready','failed')), error_code text, staging_key text NOT NULL, variants jsonb NOT NULL DEFAULT '[]'::jsonb, pipeline_version integer NOT NULL DEFAULT 1, created_at timestamptz NOT NULL DEFAULT clock_timestamp(), updated_at timestamptz NOT NULL DEFAULT clock_timestamp() ); CREATE INDEX attachments_chat ON attachments(chat_id,id); CREATE TABLE messages (id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats, sender_id uuid NOT NULL REFERENCES users, text text NOT NULL CHECK(length(text)<=4000), created_at timestamptz NOT NULL DEFAULT clock_timestamp()); CREATE TABLE message_attachments (message_id uuid REFERENCES messages ON DELETE CASCADE, attachment_id uuid REFERENCES attachments, position smallint NOT NULL, PRIMARY KEY(message_id,attachment_id), UNIQUE(message_id,position)); CREATE INDEX messages_history ON messages(chat_id,created_at,id); CREATE TABLE sessions (token_hash text PRIMARY KEY, user_id uuid NOT NULL REFERENCES users, expires_at timestamptz NOT NULL); CREATE INDEX sessions_expiry ON sessions(expires_at); CREATE TABLE attachment_jobs ( job_id uuid PRIMARY KEY, attachment_id uuid NOT NULL REFERENCES attachments(id), pipeline_version integer NOT NULL, attempt integer NOT NULL DEFAULT 0, state text NOT NULL DEFAULT 'pending' CHECK(state IN ('pending','published','processing','failed','done')), available_at timestamptz NOT NULL DEFAULT clock_timestamp(), lease_until timestamptz, last_error text, created_at timestamptz NOT NULL DEFAULT clock_timestamp(), UNIQUE(attachment_id,pipeline_version) ); CREATE INDEX attachment_jobs_pending ON attachment_jobs(available_at) WHERE state IN ('pending','published','processing'); CREATE TABLE attachment_job_audit ( id bigserial PRIMARY KEY, job_id uuid NOT NULL REFERENCES attachment_jobs(job_id), event text NOT NULL, detail text, created_at timestamptz NOT NULL DEFAULT clock_timestamp() );