Skip to content

Latest commit

 

History

History
969 lines (843 loc) · 40.7 KB

data-model.md

File metadata and controls

969 lines (843 loc) · 40.7 KB

Boond data model

This chapter defines the persistent model. PostgreSQL 16 is the reference database. The wire model in ../SPEC.md is authoritative; this schema is a concrete implementation that satisfies it. All timestamps are timestamptz and are serialized as UTC RFC 3339 with three fractional digits.

1. Design rules

  1. Integer IDs for user/collection/raindrop. bigint identity columns. Core wire IDs are JSON numbers. Start collections at 1,000,000 and raindrops at 1,000,000,000 to keep the legacy look and avoid tiny IDs colliding with system IDs.
  2. String IDs for object-like entities. OAuth clients, highlights, backups, and invites use 24-hex or opaque strings. Highlight/backup/client IDs are char(24).
  3. System collections are not rows. 0, -1, -99 are virtual. A raindrop in Trash stores collection_id = -99 and trashed_from_collection_id.
  4. Owner vs creator. raindrops.owner_id is the owner of the collection at the time of the write; creator_id is the original author. creatorRef is emitted when they differ.
  5. Denormalized counts are caches. collections.count and user_stats are recomputed in the mutation transaction or by the reconciler. They are never authoritative for access control or data integrity.
  6. Outbox for side effects. Search indexing, jobs, and analytics are driven by outbox rows written in the same transaction as the mutation. This is required for correctness under retries.
  7. Soft delete only where needed. Collections and raindrops in Trash remain rows. Permanent deletion is physical. Account deletion uses users.deleted_at for 24 hours, then a purge job removes everything.
  8. Opaque lastAction. Store a global sequence value and a per-row version; format the wire token as <RFC3339>:<sequence>. Clients only compare equality.

2. Extensions and types

CREATE EXTENSION IF NOT EXISTS citext;
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE TYPE collection_view AS ENUM ('list', 'simple', 'grid', 'masonry');
CREATE TYPE share_role      AS ENUM ('viewer', 'member');
CREATE TYPE raindrop_type   AS ENUM ('link', 'article', 'image', 'video', 'document', 'audio', 'book');
CREATE TYPE cache_status    AS ENUM ('retry', 'ready', 'failed', 'invalid-origin', 'invalid-timeout', 'invalid-size');
CREATE TYPE backup_status   AS ENUM ('queued', 'running', 'ready', 'failed', 'expired');
CREATE TYPE file_kind       AS ENUM ('raindrop_file', 'cover', 'avatar', 'oauth_icon', 'archive', 'backup');
CREATE TYPE job_status      AS ENUM ('queued', 'running', 'succeeded', 'failed', 'dead');

CREATE SEQUENCE last_action_seq AS BIGINT START 1;

citext makes usernames, emails, and tags case-insensitive for uniqueness while preserving display case (stored separately where needed).

3. Identity and account

3.1 users

CREATE TABLE users (
    id                  BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    username            CITEXT NOT NULL,
    full_name           TEXT NOT NULL DEFAULT '',
    email               CITEXT NOT NULL,
    email_md5           CHAR(32) NOT NULL,
    email_confirmed     BOOLEAN NOT NULL DEFAULT FALSE,
    password_hash       TEXT,
    avatar_file_id      UUID,
    pro                 BOOLEAN NOT NULL DEFAULT TRUE,
    pro_expire          TIMESTAMPTZ,
    config              JSONB NOT NULL DEFAULT '{}'::jsonb,
    files_used_bytes    BIGINT NOT NULL DEFAULT 0,
    files_quota_bytes   BIGINT NOT NULL DEFAULT 100000000000,
    files_last_check_point TIMESTAMPTZ NOT NULL DEFAULT now(),
    registered_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at          TIMESTAMPTZ NOT NULL DEFAULT now(),
    last_action         BIGINT NOT NULL DEFAULT nextval('last_action_seq'),
    deleted_at          TIMESTAMPTZ,
    CONSTRAINT users_username_key UNIQUE (username),
    CONSTRAINT users_email_key UNIQUE (email),
    CONSTRAINT users_username_format CHECK (username ~ '^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$'),
    CONSTRAINT users_full_name_len CHECK (char_length(full_name) <= 1000),
    CONSTRAINT users_quota_positive CHECK (files_quota_bytes >= 0),
    CONSTRAINT users_used_nonnegative CHECK (files_used_bytes >= 0)
);

CREATE INDEX users_active_idx ON users (id) WHERE deleted_at IS NULL;
CREATE INDEX users_registered_idx ON users (registered_at DESC);
  • username is the public name. full_name is the display name. Both are emitted.
  • email_md5 is md5(lower(email)); maintain in the application (or a trigger).
  • password_hash is NULL for social-only accounts; password emits password_hash IS NOT NULL.
  • config is merged, not replaced, on PUT /user. Validate known keys in the application; keep unknown keys.
  • pro is always TRUE for active accounts. A DB CHECK (pro) is not used because operators may temporarily set false for legacy imports; the API forces true.
  • last_action is bumped with nextval('last_action_seq') in the same transaction as any user-visible mutation.

3.1a Admin and settings

Migration 0010_admin.sql adds:

ALTER TABLE users ADD COLUMN is_admin BOOLEAN NOT NULL DEFAULT FALSE;

CREATE TABLE settings (
    key        TEXT PRIMARY KEY,
    value      TEXT NOT NULL DEFAULT '',
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
  • is_admin gates /admin; it is not exposed as a public user field beyond admin in the admin API.
  • settings stores admin-panel environment overrides. They are copied into the process environment before config.Load on the next startup. Database URL, JWT secret, and admin password are not allowed to be overridden this way.

3.2 user_groups and group_collections

CREATE TABLE user_groups (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id     BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    public_id   TEXT NOT NULL,                    -- g1, g2, ...
    title       TEXT NOT NULL DEFAULT 'My Collections',
    hidden      BOOLEAN NOT NULL DEFAULT FALSE,
    sort        INTEGER NOT NULL DEFAULT 0,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (user_id, public_id),
    CHECK (public_id ~ '^g[0-9]+$'),
    CHECK (char_length(title) <= 200)
);

-- group_collections is created after collections (§4.1) because it references it.
  • public_id is the _id emitted in user.groups[] (g1, g2, …).
  • Only root accessible collections belong to groups. A shared root appears in the collaborator's group. The owner's groups are independent of the collaborator's.
  • UNIQUE (group_id, position) makes reorder atomic; when reordering, update positions in a single statement or defer the constraint (DEFERRABLE INITIALLY DEFERRED if needed).

3.3 Sessions

CREATE TABLE sessions (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id         BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    token_hash      BYTEA NOT NULL UNIQUE,        -- sha256(token)
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    last_seen_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    expires_at      TIMESTAMPTZ NOT NULL,
    revoked_at      TIMESTAMPTZ,
    ip              INET,
    user_agent      TEXT,
    CHECK (expires_at > created_at)
);

CREATE INDEX sessions_user_active_idx ON sessions (user_id, expires_at)
    WHERE revoked_at IS NULL;
CREATE INDEX sessions_expiry_idx ON sessions (expires_at);

3.4 TOTP and recovery codes

CREATE TABLE user_totp (
    user_id       BIGINT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
    secret_enc    BYTEA NOT NULL,                 -- AES-GCM(secret)
    enabled       BOOLEAN NOT NULL DEFAULT FALSE,
    confirmed_at  TIMESTAMPTZ,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE user_recovery_codes (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id     BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    code_hash   BYTEA NOT NULL,                   -- sha256(normalized code)
    used_at     TIMESTAMPTZ,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX recovery_codes_user_idx ON user_recovery_codes (user_id)
    WHERE used_at IS NULL;

-- Short-lived login challenge created after a correct password when TFA is enabled.
CREATE TABLE tfa_challenges (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id     BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    token_hash  BYTEA NOT NULL UNIQUE,             -- sha256(challenge)
    expires_at  TIMESTAMPTZ NOT NULL,
    attempts    INTEGER NOT NULL DEFAULT 0,
    used_at     TIMESTAMPTZ,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    CHECK (expires_at > created_at)
);

CREATE INDEX tfa_challenges_expiry_idx ON tfa_challenges (expires_at)
    WHERE used_at IS NULL;

-- Single-use desktop handoff JWTs.
CREATE TABLE jwt_replay (
    jti         TEXT PRIMARY KEY,
    user_id     BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    expires_at  TIMESTAMPTZ NOT NULL,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX jwt_replay_expiry_idx ON jwt_replay (expires_at);

3.5 Provider connections and email tokens

CREATE TABLE user_connections (
    user_id             BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    provider            TEXT NOT NULL,             -- google, apple, dropbox, gdrive, onedrive, ...
    external_id         TEXT,
    email               CITEXT,
    access_token_enc    BYTEA,
    refresh_token_enc   BYTEA,
    expires_at          TIMESTAMPTZ,
    enabled             BOOLEAN NOT NULL DEFAULT TRUE,
    created_at          TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at          TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (user_id, provider)
);

CREATE TABLE email_tokens (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id     BIGINT REFERENCES users(id) ON DELETE CASCADE,
    purpose     TEXT NOT NULL,                    -- verify, reset, invite, backup
    token_hash  BYTEA NOT NULL UNIQUE,
    email       CITEXT,
    payload     JSONB NOT NULL DEFAULT '{}'::jsonb,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    expires_at  TIMESTAMPTZ NOT NULL,
    used_at     TIMESTAMPTZ
);

CREATE INDEX email_tokens_user_purpose_idx ON email_tokens (user_id, purpose)
    WHERE used_at IS NULL;

4. Collections and sharing

4.1 collections

CREATE TABLE collections (
    id              BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1000000) PRIMARY KEY,
    owner_id        BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    parent_id       BIGINT REFERENCES collections(id) ON DELETE CASCADE,
    title           TEXT NOT NULL,
    description     TEXT NOT NULL DEFAULT '',
    slug            TEXT NOT NULL,
    public          BOOLEAN NOT NULL DEFAULT FALSE,
    expanded        BOOLEAN NOT NULL DEFAULT FALSE,
    view            collection_view NOT NULL DEFAULT 'list',
    sort            NUMERIC(20,6) NOT NULL DEFAULT 0,
    color           CHAR(7) NOT NULL DEFAULT '#0c797d',
    cover           JSONB NOT NULL DEFAULT '[]'::jsonb,   -- [url] or []
    cover_file_id   UUID,
    count           INTEGER NOT NULL DEFAULT 0,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    last_action     BIGINT NOT NULL DEFAULT nextval('last_action_seq'),
    version         BIGINT NOT NULL DEFAULT 1,
    UNIQUE (owner_id, slug),
    CHECK (id > 0),
    CHECK (char_length(title) BETWEEN 1 AND 1000),
    CHECK (char_length(description) <= 10000),
    CHECK (color ~ '^#[0-9a-fA-F]{6}$'),
    CHECK (jsonb_typeof(cover) = 'array' AND jsonb_array_length(cover) <= 1)
);

CREATE INDEX collections_owner_parent_sort_idx
    ON collections (owner_id, parent_id, sort, id);
CREATE INDEX collections_parent_idx ON collections (parent_id);
CREATE INDEX collections_owner_updated_idx ON collections (owner_id, updated_at DESC);
CREATE INDEX collections_public_idx ON collections (owner_id, id) WHERE public;
CREATE INDEX collections_slug_trgm_idx ON collections USING gin (slug gin_trgm_ops);

-- Depends on collections; user_groups was created in §3.2.
CREATE TABLE group_collections (
    group_id       UUID NOT NULL REFERENCES user_groups(id) ON DELETE CASCADE,
    collection_id  BIGINT NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
    position       INTEGER NOT NULL,
    PRIMARY KEY (group_id, collection_id),
    UNIQUE (group_id, position) DEFERRABLE INITIALLY DEFERRED
);

CREATE INDEX group_collections_collection_idx ON group_collections (collection_id);
  • A collection and its parent must have the same owner. Enforce in the service layer (a trigger would need a recursive lookup; still add a deferred check if desired).
  • slug is unique per owner. Generate a suffix on collision. It is immutable after creation unless the owner explicitly supplies a new slug; changing title must not regenerate it, or existing public links break.
  • count is direct active raindrops, recomputed as: SELECT count(*) FROM raindrops WHERE collection_id = collections.id AND deleted_at IS NULL.
  • version increments on every update; last_action uses the global sequence. The DB type is BIGINT, but the wire emits it as a string ("42") because clients treat both lastAction and version as opaque and compare them by equality; the format is not part of the contract.
  • cover is an array for the wire; store the URL(s) and keep cover_file_id for uploaded covers so the bytes can be cleaned up.
  • Root order is not sort; it is user_groups/group_collections. sort orders children within a parent.

4.2 Shares and invitations

CREATE TABLE collection_shares (
    collection_id  BIGINT NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
    user_id        BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    role           share_role NOT NULL,
    created_by     BIGINT NOT NULL REFERENCES users(id),
    created_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (collection_id, user_id)
);

CREATE INDEX shares_user_idx ON collection_shares (user_id);

CREATE TABLE collection_invites (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    collection_id   BIGINT NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
    token_hash      BYTEA NOT NULL UNIQUE,
    role            share_role NOT NULL,
    email           CITEXT,
    reusable        BOOLEAN NOT NULL DEFAULT FALSE,
    created_by      BIGINT NOT NULL REFERENCES users(id),
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    expires_at      TIMESTAMPTZ,
    revoked_at      TIMESTAMPTZ,
    accepted_by     BIGINT REFERENCES users(id),
    accepted_at     TIMESTAMPTZ,
    CHECK (NOT reusable OR email IS NULL)
);

CREATE INDEX invites_collection_idx ON collection_invites (collection_id)
    WHERE revoked_at IS NULL;
CREATE INDEX invites_email_idx ON collection_invites (email)
    WHERE accepted_at IS NULL AND revoked_at IS NULL;
  • A reusable link (email IS NULL, reusable=TRUE) can be accepted by many users.
  • A per-email invite is single-use. accepted_at/accepted_by record acceptance.
  • When an owner unshares, revoke all invites for the collection.
  • Inheritance: a share on a parent applies to descendants. Do not materialize inherited shares; resolve with a recursive CTE:
WITH RECURSIVE ancestors AS (
    SELECT id, parent_id FROM collections WHERE id = $1
    UNION ALL
    SELECT c.id, c.parent_id
    FROM collections c
    JOIN ancestors a ON c.id = a.parent_id
)
SELECT max(CASE s.role WHEN 'member' THEN 3 WHEN 'viewer' THEN 2 ELSE 0 END) AS level
FROM ancestors a
LEFT JOIN collection_shares s ON s.collection_id = a.id AND s.user_id = $2;

Add access.for, access.root, access.draggable in the serializer. A share row on a descendant can grant a higher role than an inherited row.

5. Raindrops, highlights, tags

5.1 raindrops

CREATE TABLE raindrops (
    id                       BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1000000000) PRIMARY KEY,
    owner_id                 BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    creator_id               BIGINT NOT NULL REFERENCES users(id),
    collection_id            BIGINT NOT NULL,             -- may be -99; not an FK
    trashed_from_collection_id BIGINT,
    title                    TEXT NOT NULL DEFAULT '',
    excerpt                  TEXT NOT NULL DEFAULT '',
    note                     TEXT NOT NULL DEFAULT '',
    link                     TEXT NOT NULL,
    canonical_url            TEXT NOT NULL,
    duplicate_key            TEXT NOT NULL,
    domain                   TEXT NOT NULL DEFAULT '',
    type                     raindrop_type NOT NULL DEFAULT 'link',
    cover                    TEXT,
    media                    JSONB NOT NULL DEFAULT '[]'::jsonb,
    important                BOOLEAN NOT NULL DEFAULT FALSE,
    broken                   BOOLEAN NOT NULL DEFAULT FALSE,
    removed                  BOOLEAN NOT NULL DEFAULT FALSE,   -- true iff collection_id = -99
    broken_checked_at        TIMESTAMPTZ,
    duplicate_of             BIGINT REFERENCES raindrops(id) ON DELETE SET NULL,
    cache_status             cache_status,
    cache_size               BIGINT,
    cache_created_at         TIMESTAMPTZ,
    file_id                  UUID,
    order_index              NUMERIC(20,6) NOT NULL DEFAULT 0,
    reminder_at              TIMESTAMPTZ,
    content_text             TEXT NOT NULL DEFAULT '',
    tags_text                TEXT NOT NULL DEFAULT '',
    highlights_text          TEXT NOT NULL DEFAULT '',
    search_vector            TSVECTOR GENERATED ALWAYS AS (
        setweight(to_tsvector('simple', coalesce(title, '')), 'A') ||
        setweight(to_tsvector('simple', coalesce(tags_text, '')), 'B') ||
        setweight(to_tsvector('simple', coalesce(excerpt, '')), 'C') ||
        setweight(to_tsvector('simple', coalesce(note, '')), 'C') ||
        setweight(to_tsvector('simple', coalesce(highlights_text, '')), 'C') ||
        setweight(to_tsvector('simple', coalesce(link, '') || ' ' || coalesce(domain, '')), 'D') ||
        setweight(to_tsvector('simple', coalesce(content_text, '')), 'D')
    ) STORED,
    created_at               TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at               TIMESTAMPTZ NOT NULL DEFAULT now(),
    deleted_at               TIMESTAMPTZ,
    CHECK (char_length(title) <= 1000),
    CHECK (char_length(excerpt) <= 10000),
    CHECK (char_length(note) <= 10000),
    CHECK (collection_id = -99 OR collection_id > 0 OR collection_id = -1),
    CHECK (removed = (collection_id = -99)),
    CHECK (jsonb_typeof(media) = 'array'),
    CHECK (cache_status IS NULL OR cache_status <> 'ready' OR cache_created_at IS NOT NULL)
);

CREATE INDEX raindrops_collection_active_idx
    ON raindrops (collection_id, created_at DESC, id DESC)
    WHERE deleted_at IS NULL;
CREATE INDEX raindrops_owner_active_idx
    ON raindrops (owner_id, created_at DESC, id DESC)
    WHERE deleted_at IS NULL;
CREATE INDEX raindrops_owner_updated_idx
    ON raindrops (owner_id, updated_at DESC)
    WHERE deleted_at IS NULL;
CREATE INDEX raindrops_order_idx
    ON raindrops (collection_id, order_index, id)
    WHERE deleted_at IS NULL;
CREATE INDEX raindrops_duplicate_idx
    ON raindrops (owner_id, duplicate_key)
    WHERE deleted_at IS NULL;
CREATE INDEX raindrops_reminder_idx
    ON raindrops (reminder_at)
    WHERE reminder_at IS NOT NULL AND deleted_at IS NULL;
CREATE INDEX raindrops_cache_idx
    ON raindrops (cache_status)
    WHERE cache_status IN ('retry', 'failed');
CREATE INDEX raindrops_search_idx ON raindrops USING gin (search_vector);
CREATE INDEX raindrops_title_trgm_idx ON raindrops USING gin (title gin_trgm_ops);
CREATE INDEX raindrops_link_trgm_idx ON raindrops USING gin (link gin_trgm_ops);
CREATE INDEX raindrops_file_idx ON raindrops (file_id) WHERE file_id IS NOT NULL;
  • owner_id is the collection owner. creator_id is the original saver. On move to another owner's collection (only via a share), update owner_id to the target collection owner and keep creator_id.
  • collection_id=-1 means Unsorted; -99 means Trash. Positive IDs must exist; validate in the service, not with an FK, because of the negative sentinels.
  • duplicate_key is computed by the URL normalizer: lowercase scheme/host, strip www., default ports, trailing slash, fragment, and tracking params (utm_*, ref, ref_src, source, fbclid, gclid, etc.). It is not necessarily the stored link; preserve the user's URL for display.
  • duplicate_of points to the canonical (oldest) raindrop with the same key. It is maintained by a job; null means canonical. duplicate in JSON is this ID. On delete of a canonical row, a job promotes the next-oldest duplicate and rewrites duplicate_of; the FK's ON DELETE SET NULL is only a safety net, not the intended promotion path.
  • search_vector uses the simple configuration to avoid language-specific stemming surprises; pg_trgm handles prefix/fuzzy. See search.md.
  • content_text is filled from archives/PDF extraction; tags_text and highlights_text are maintained by the tag/highlight services (space-separated text) so the generated vector stays immutable.
  • order_index is renumbered contiguously on insert/reorder. Fractional values are allowed during a move and normalized by a job.
  • deleted_at is used for account-deletion tombstones and admin recovery, not for Trash (Trash is collection_id=-99). Active queries filter deleted_at IS NULL.
  • cache_status is the wire cache.status; cache_size/cache_created_at complete the object.

5.2 highlights

CREATE TABLE highlights (
    id            CHAR(24) PRIMARY KEY,             -- 24 lowercase hex
    raindrop_id   BIGINT NOT NULL REFERENCES raindrops(id) ON DELETE CASCADE,
    user_id       BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    text          TEXT NOT NULL,
    note          TEXT NOT NULL DEFAULT '',
    color         TEXT NOT NULL DEFAULT 'yellow',
    position      JSONB,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    CHECK (id ~ '^[0-9a-f]{24}$'),
    CHECK (char_length(text) BETWEEN 1 AND 10000),
    CHECK (char_length(note) <= 10000),
    CHECK (color IN ('blue','brown','cyan','gray','green','indigo','orange','pink','purple','red','teal','yellow'))
);

CREATE INDEX highlights_raindrop_idx ON highlights (raindrop_id, created_at);
CREATE INDEX highlights_user_idx ON highlights (user_id, created_at DESC);
CREATE INDEX highlights_text_trgm_idx ON highlights USING gin (text gin_trgm_ops);

position is opaque JSON: {start, end, xpath, textPrefix, textSuffix} or an equivalent anchor model. Validate size (≤4 KiB) and types; never execute it.

highlights.user_id is the creator of the highlight. A collaborator with write access may create/edit a highlight on an item owned by the collection owner; the highlight is visible to everyone who can read the item. Deleting the raindrop cascades all highlights. The API does not expose the creator identity in the highlight object.

Tags are owner-scoped; highlights are creator-scoped. Document this asymmetry.

5.3 Tags

CREATE TABLE tags (
    id            BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    owner_id      BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    name          CITEXT NOT NULL,
    display_name  TEXT NOT NULL,
    count         INTEGER NOT NULL DEFAULT 0,
    last_used_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (owner_id, name),
    CHECK (char_length(display_name) BETWEEN 1 AND 100)
);

CREATE TABLE raindrop_tags (
    raindrop_id  BIGINT NOT NULL REFERENCES raindrops(id) ON DELETE CASCADE,
    tag_id       BIGINT NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
    PRIMARY KEY (raindrop_id, tag_id)
);

CREATE INDEX tags_owner_count_idx ON tags (owner_id, count DESC, name);
CREATE INDEX raindrop_tags_tag_idx ON raindrop_tags (tag_id);
  • Tags are scoped to the collection owner, not the collaborator. A member editing a shared item modifies the owner's tag namespace; all collaborators see the same tags. This matches the shared-library model and avoids a per-user tag overlay that the clients do not understand.
  • name is normalized (trim, collapse whitespace, case-insensitive); display_name preserves the first-seen case.
  • Tag counts are active raindrops only (exclude -99/deleted).
  • On rename, merge counts and update display_name if the target is new.
  • tags_text on raindrops is updated by the tag service in the same transaction.

6. Files, archives, backups

6.1 files

CREATE TABLE files (
    id             UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    owner_id       BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    kind           file_kind NOT NULL,
    object_key     TEXT NOT NULL UNIQUE,
    original_name  TEXT NOT NULL DEFAULT '',
    mime           TEXT NOT NULL,
    size_bytes     BIGINT NOT NULL,
    sha256         BYTEA NOT NULL,
    width          INTEGER,
    height         INTEGER,
    created_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
    deleted_at     TIMESTAMPTZ,
    CHECK (size_bytes >= 0)
);

CREATE INDEX files_owner_idx ON files (owner_id, kind, created_at DESC)
    WHERE deleted_at IS NULL;
CREATE INDEX files_sha_idx ON files (sha256) WHERE deleted_at IS NULL;

-- Deferred FKs for columns declared before the files table existed.
ALTER TABLE users
    ADD CONSTRAINT users_avatar_file_fk FOREIGN KEY (avatar_file_id)
    REFERENCES files(id) ON DELETE SET NULL;
ALTER TABLE collections
    ADD CONSTRAINT collections_cover_file_fk FOREIGN KEY (cover_file_id)
    REFERENCES files(id) ON DELETE SET NULL;
ALTER TABLE raindrops
    ADD CONSTRAINT raindrops_file_fk FOREIGN KEY (file_id)
    REFERENCES files(id) ON DELETE SET NULL;
  • object_key is relative to the storage bucket/root: raindrop/{user}/{id}/{name}, cover/{user}/{id}.webp, avatar/{user}/{hash}.webp, archive/{user}/{id}/index.html, backup/{user}/{id}.zip.
  • Uploads are deduplicated by (owner_id, sha256, kind) only when the logical name and permissions allow it; otherwise keep separate metadata rows pointing at one object.
  • files_used_bytes on users is incremented by size_bytes for kind='raindrop_file' only, matching product docs (covers/avatars/archives don't count toward the upload quota).

6.2 Archives

CREATE TABLE archives (
    raindrop_id  BIGINT PRIMARY KEY REFERENCES raindrops(id) ON DELETE CASCADE,
    status       cache_status NOT NULL DEFAULT 'retry',
    file_id      UUID REFERENCES files(id) ON DELETE SET NULL,
    size_bytes   BIGINT,
    error        TEXT,
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    CHECK (status <> 'ready' OR file_id IS NOT NULL)
);

CREATE INDEX archives_status_idx ON archives (status)
    WHERE status IN ('retry', 'failed');

archives is the detailed record; raindrops.cache_status/size/created_at is the denormalized wire cache object. Keep them consistent in the same transaction.

6.3 Backups

CREATE TABLE backups (
    id            CHAR(24) PRIMARY KEY,
    user_id       BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    status        backup_status NOT NULL DEFAULT 'queued',
    error         TEXT,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    completed_at  TIMESTAMPTZ,
    expires_at    TIMESTAMPTZ,
    CHECK (id ~ '^[0-9a-f]{24}$')
);

CREATE INDEX backups_user_idx ON backups (user_id, created_at DESC);

CREATE TABLE backup_artifacts (
    backup_id  CHAR(24) NOT NULL REFERENCES backups(id) ON DELETE CASCADE,
    format     TEXT NOT NULL CHECK (format IN ('html','csv','zip')),
    file_id    UUID NOT NULL REFERENCES files(id) ON DELETE RESTRICT,
    size_bytes BIGINT NOT NULL,
    PRIMARY KEY (backup_id, format)
);

Retention: 30 newest ready backups per user; expired rows are marked expired and their artifacts deleted by a job. The API's additive size/format fields are derived from backup_artifacts (sum(size_bytes), array_agg(format)); no duplicate columns are needed.

7. OAuth

CREATE TABLE oauth_clients (
    id            CHAR(24) PRIMARY KEY,
    owner_id      BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    name          TEXT NOT NULL,
    description   TEXT NOT NULL DEFAULT '',
    site          TEXT NOT NULL DEFAULT '',
    icon_file_id  UUID REFERENCES files(id) ON DELETE SET NULL,
    redirects     TEXT[] NOT NULL DEFAULT '{}',
    secret_enc    BYTEA NOT NULL,
    active        BOOLEAN NOT NULL DEFAULT TRUE,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    CHECK (id ~ '^[0-9a-f]{24}$'),
    CHECK (char_length(name) BETWEEN 1 AND 200),
    CHECK (array_length(redirects, 1) IS NULL OR array_length(redirects, 1) <= 20)
);

CREATE INDEX oauth_clients_owner_idx ON oauth_clients (owner_id, created_at DESC);

CREATE TABLE oauth_tokens (
    id               UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    client_id        CHAR(24) NOT NULL REFERENCES oauth_clients(id) ON DELETE CASCADE,
    user_id          BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    access_hash      BYTEA NOT NULL,
    refresh_hash     BYTEA,
    test             BOOLEAN NOT NULL DEFAULT FALSE,
    test_token_enc   BYTEA,                       -- required when test=TRUE
    scope            TEXT[] NOT NULL DEFAULT '{}', -- stored/echoed, not enforced in v1
    access_expires_at  TIMESTAMPTZ,
    refresh_expires_at TIMESTAMPTZ,
    created_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
    last_used_at     TIMESTAMPTZ,
    revoked_at       TIMESTAMPTZ,
    UNIQUE (access_hash),
    UNIQUE (refresh_hash)
);

CREATE INDEX oauth_tokens_user_client_idx ON oauth_tokens (user_id, client_id)
    WHERE revoked_at IS NULL;

CREATE TABLE oauth_codes (
    code_hash        BYTEA PRIMARY KEY,
    client_id        CHAR(24) NOT NULL REFERENCES oauth_clients(id) ON DELETE CASCADE,
    user_id          BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    redirect_uri     TEXT NOT NULL,
    code_challenge   TEXT,
    challenge_method TEXT CHECK (challenge_method IN ('S256')),
    created_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
    expires_at       TIMESTAMPTZ NOT NULL,
    used_at          TIMESTAMPTZ
);

CREATE INDEX oauth_codes_expiry_idx ON oauth_codes (expires_at);
  • secret_enc is encrypted at rest because the owner UI shows the secret. Never log it.
  • Access/refresh tokens are random 32-byte values with prefixes (rdt_, rdr_), stored as SHA-256 hashes. Test tokens additionally need to be shown again; store an encrypted copy in oauth_tokens (add test_token_enc BYTEA) or derive it from a per-client deterministic secret — prefer an encrypted copy.
  • A test token is a token row with test=TRUE, refresh_hash=NULL, access_expires_at=NULL.
  • oauth_codes are single-use; delete or mark used_at on exchange.
  • Authorization code TTL 60 seconds; access token 14 days; refresh token 30 days, rotated on use.

8. Jobs, outbox, audit, searches, devices

8.1 outbox

CREATE TABLE outbox (
    id            BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    aggregate     TEXT NOT NULL,                  -- raindrop:123, collection:456, user:32
    event         TEXT NOT NULL,                  -- created, updated, deleted, share_changed, ...
    payload       JSONB NOT NULL DEFAULT '{}'::jsonb,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    available_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    processed_at  TIMESTAMPTZ,
    attempts      INTEGER NOT NULL DEFAULT 0,
    last_error    TEXT
);

CREATE INDEX outbox_pending_idx ON outbox (available_at, id)
    WHERE processed_at IS NULL;

8.2 jobs (fallback queue when River is not used)

CREATE TABLE jobs (
    id            BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    kind          TEXT NOT NULL,                  -- parse, archive, screenshot, broken, backup, ...
    payload       JSONB NOT NULL,
    status        job_status NOT NULL DEFAULT 'queued',
    priority      INTEGER NOT NULL DEFAULT 0,
    run_at        TIMESTAMPTZ NOT NULL DEFAULT now(),
    attempts      INTEGER NOT NULL DEFAULT 0,
    max_attempts  INTEGER NOT NULL DEFAULT 8,
    locked_by     TEXT,
    locked_at     TIMESTAMPTZ,
    last_error    TEXT,
    idempotency_key TEXT UNIQUE,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX jobs_ready_idx ON jobs (run_at, priority DESC, id)
    WHERE status = 'queued';
CREATE INDEX jobs_running_idx ON jobs (locked_at)
    WHERE status = 'running';

-- Optional PostgreSQL-backed rate limiter for multi-instance deployments.
CREATE TABLE rate_limit_buckets (
    bucket_key  TEXT PRIMARY KEY,
    tokens      NUMERIC(20,6) NOT NULL,
    reset_at    TIMESTAMPTZ NOT NULL,
    updated_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Counts that need asynchronous reconciliation.
CREATE TABLE stats_dirty (
    user_id        BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    collection_id  BIGINT,
    marked_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    reason         TEXT NOT NULL,
    PRIMARY KEY (user_id, collection_id)
);

-- Optional idempotency for retried destructive requests (P8).
CREATE TABLE idempotency_keys (
    key         TEXT PRIMARY KEY,
    user_id     BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    method      TEXT NOT NULL,
    path        TEXT NOT NULL,
    response    JSONB NOT NULL,
    expires_at  TIMESTAMPTZ NOT NULL,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX idempotency_expiry_idx ON idempotency_keys (expires_at);

River (Postgres-backed) is the recommended implementation; this table documents the semantics and is a valid fallback.

8.3 Recent searches and devices

CREATE TABLE recent_searches (
    user_id        BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    query          TEXT NOT NULL,
    collection_ref BIGINT NOT NULL DEFAULT 0,
    searched_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (user_id, query)
);

CREATE INDEX recent_searches_user_idx ON recent_searches (user_id, searched_at DESC);

CREATE TABLE devices (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id     BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    platform    TEXT NOT NULL,                    -- android, ios, web
    token_hash  BYTEA NOT NULL UNIQUE,
    token_enc   BYTEA NOT NULL,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    last_seen_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

8.4 Audit log

CREATE TABLE audit_log (
    id          BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    user_id     BIGINT REFERENCES users(id) ON DELETE SET NULL,
    action      TEXT NOT NULL,
    target_type TEXT,
    target_id   TEXT,
    ip          INET,
    user_agent  TEXT,
    detail      JSONB NOT NULL DEFAULT '{}'::jsonb,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX audit_user_time_idx ON audit_log (user_id, created_at DESC);

Never put secrets, passwords, tokens, or full email bodies in detail.

8.5 User stats cache

CREATE TABLE user_stats (
    user_id          BIGINT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
    all_count        INTEGER NOT NULL DEFAULT 0,
    unsorted_count   INTEGER NOT NULL DEFAULT 0,
    trash_count      INTEGER NOT NULL DEFAULT 0,
    duplicates_count INTEGER NOT NULL DEFAULT 0,
    broken_count     INTEGER NOT NULL DEFAULT 0,
    changed_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);

Refresh in the same transaction for small changes, or mark dirty and reconcile. GET /user/stats can also compute directly for correctness; the table is an optimization.

9. Query patterns and indexes

Query Index
Collections by owner/parent, ordered collections_owner_parent_sort_idx
Root accessible collections for a user owner index + share/user index; union all
Raindrop list in collection, newest raindrops_collection_active_idx
Raindrop list all, newest raindrops_owner_active_idx
Manual order raindrops_order_idx
Search raindrops_search_idx, trigram indexes
Duplicate grouping raindrops_duplicate_idx
Tag counts tags_owner_count_idx
Raindrop tags raindrop_tags_tag_idx
Highlights for item highlights_raindrop_idx
Highlights by user highlights_user_idx
Backups by user backups_user_idx
OAuth tokens by user/client oauth_tokens_user_client_idx
Expiring sessions sessions_expiry_idx
Pending jobs jobs_ready_idx
Public pages collections_public_idx

Accessible-collection queries for shared users:

-- Owned plus directly shared, plus descendants of shared parents.
WITH RECURSIVE shared_roots AS (
    SELECT c.id
    FROM collections c
    JOIN collection_shares s ON s.collection_id = c.id
    WHERE s.user_id = $1
    UNION
    SELECT c.id
    FROM collections c
    WHERE c.owner_id = $1
),
tree AS (
    SELECT id FROM shared_roots
    UNION ALL
    SELECT c.id FROM collections c JOIN tree t ON c.parent_id = t.id
)
SELECT DISTINCT id FROM tree;

Cache this per request in a CTE or a temporary table for list queries. Do not run a recursive query per raindrop.

10. Invariants and constraints

  1. A collection's parent belongs to the same owner.
  2. A collection cannot be its own ancestor (service check; optionally a trigger).
  3. A share cannot target the owner (owner has implicit level 4).
  4. Only root collections appear in group_collections.
  5. A raindrop's collection_id is -1, -99, or an existing positive collection.
  6. owner_id matches the collection owner for positive collection IDs.
  7. Highlights belong to the same owner as the raindrop (collaborators may create highlights? Product allows members to highlight; set user_id to the collaborator and allow it if they have write access. owner_id remains the collection owner.)
  8. A file is deleted only when no raindrop/collection/avatar/archive/backup references it.
  9. tags.count equals the number of active raindrops linked via raindrop_tags.
  10. collections.count equals active direct raindrops.
  11. oauth_tokens.access_hash is unique among non-revoked rows.
  12. collection_invites reusable rows have no email; per-email rows are single-use.
  13. user_groups.public_id is unique per user and matches ^g\d+$.
  14. Trash items are excluded from counts, search, public pages, and exports except Trash-scoped requests.
  15. deleted_at IS NULL for all API-visible rows.

11. Migrations and data lifecycle

  • Use goose (or golang-migrate) with embedded SQL migrations. One migration per logical change; never edit an applied migration.
  • Seed no user data. On first boot, optionally create an admin user from BOOND_BOOTSTRAP_EMAIL/BOOND_BOOTSTRAP_PASSWORD; print a one-time random password if not provided.
  • Account deletion: set users.deleted_at, revoke sessions/tokens, enqueue purge. Purge after 24 hours: delete files, archives, backups, raindrops, collections, tags, OAuth clients, and the user row. Audit entries keep user_id=NULL.
  • Backups: row + artifacts; expired artifacts deleted after 30 days. Never include uploaded file bytes in backups.
  • Vacuum/analyze after bulk imports; use CREATE INDEX CONCURRENTLY for large tables in production migrations.

12. Mapping legacy JSON to rows

Wire field Row
user._id, creatorRef._id users.id
user.name users.username
user.fullName users.full_name
user.files.lastCheckPoint users.files_last_check_point
collection.$id raindrops.collection_id
parent.$id collections.parent_id
collectionId same as collection.$id
sort (collection) collections.sort
order (raindrop) raindrops.order_index
lastUpdate updated_at
created created_at
cache.status/size/created raindrops.cache_*
file.{name,size,type} files joined via file_id
reminder.date raindrops.reminder_at
highlights[] highlights rows by raindrop_id
tags[] raindrop_tags → tags.display_name
duplicate raindrops.duplicate_of
access.level computed from owner/share/inheritance/public
collaborators synthesized object {"$id":"<24hex>"} derived from the collection ID (e.g. md5(concat('collection:', id))[:24]); presence means shared. It is not a real foreign key.
groups[] user_groups + group_collections
config users.config JSONB

Unknown legacy fields SHOULD be preserved in raindrops.media, collections.cover, or a per-entity extra JSONB column if an operator needs lossless import. Boond does not expose arbitrary extra fields in API responses unless explicitly mapped.