SPB Git

Repository Public License

Schema.swift 12.9 KB 327 lines swift

1import Foundation23/// The ordered migration list. **Adding a schema change is one line here** plus the migration body below.4/// Never edit a migration that has shipped.5public enum Schema {6    public static let migrations: [Migration] = [7        Migration(version: 1, name: "initial schema", sql: v1),8        Migration(version: 2, name: "history frecency and host key", apply: v2HistoryFrecency),9    ]1011    public static var latestVersion: Int { migrations.count }1213    // MARK: - v11415    /// Conventions: ids are TEXT UUIDs, dates are REAL seconds since 1970, booleans are INTEGER 0/1,16    /// nested value types are JSON TEXT. `sort_order` is used because `order` is an SQL keyword.17    static let v1 = """18    CREATE TABLE app_state (19        key TEXT PRIMARY KEY, value TEXT NOT NULL20    ) WITHOUT ROWID;2122    CREATE TABLE settings (23        key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at REAL NOT NULL24    ) WITHOUT ROWID;2526    -- The CHECK is the last line of defence of "ghost profiles are never written".27    CREATE TABLE profiles (28        id TEXT PRIMARY KEY,29        name TEXT NOT NULL,30        kind TEXT NOT NULL CHECK (kind = 'standard'),31        data_store_identifier TEXT NOT NULL UNIQUE,32        tint TEXT NOT NULL,33        created_at REAL NOT NULL34    );3536    CREATE TABLE spaces (37        id TEXT PRIMARY KEY,38        profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,39        name TEXT NOT NULL,40        symbol TEXT NOT NULL,41        tint TEXT NOT NULL,42        sort_order INTEGER NOT NULL DEFAULT 0,43        ring INTEGER NOT NULL DEFAULT 0,44        angle REAL NOT NULL DEFAULT 0,45        is_archived INTEGER NOT NULL DEFAULT 0,46        focus TEXT NOT NULL,47        created_at REAL NOT NULL,48        updated_at REAL NOT NULL49    );50    CREATE INDEX idx_spaces_profile ON spaces(profile_id, sort_order);5152    CREATE TABLE windows (53        id TEXT PRIMARY KEY,54        space_id TEXT NOT NULL REFERENCES spaces(id) ON DELETE CASCADE,55        frame TEXT,56        tab_layout TEXT NOT NULL,57        selected_tab_id TEXT,58        split TEXT,59        is_sidebar_collapsed INTEGER NOT NULL DEFAULT 0,60        is_agent_panel_open INTEGER NOT NULL DEFAULT 0,61        agent_panel_width REAL NOT NULL DEFAULT 360,62        is_full_screen INTEGER NOT NULL DEFAULT 0,63        sort_order INTEGER NOT NULL DEFAULT 0,64        closed_at REAL65    );66    CREATE INDEX idx_windows_space ON windows(space_id);67    CREATE INDEX idx_windows_closed ON windows(closed_at);6869    CREATE TABLE tab_groups (70        id TEXT PRIMARY KEY,71        space_id TEXT NOT NULL REFERENCES spaces(id) ON DELETE CASCADE,72        name TEXT NOT NULL,73        tint TEXT NOT NULL,74        is_collapsed INTEGER NOT NULL DEFAULT 0,75        sort_order INTEGER NOT NULL DEFAULT 076    );77    CREATE INDEX idx_tab_groups_space ON tab_groups(space_id, sort_order);7879    -- parent_id is deferred so a batch can insert a child before its parent inside one transaction.80    CREATE TABLE tabs (81        id TEXT PRIMARY KEY,82        window_id TEXT NOT NULL REFERENCES windows(id) ON DELETE CASCADE,83        space_id TEXT NOT NULL REFERENCES spaces(id) ON DELETE CASCADE,84        parent_id TEXT REFERENCES tabs(id) ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED,85        group_id TEXT REFERENCES tab_groups(id) ON DELETE SET NULL,86        url TEXT,87        title TEXT NOT NULL DEFAULT '',88        favicon_url TEXT,89        is_pinned INTEGER NOT NULL DEFAULT 0,90        is_muted INTEGER NOT NULL DEFAULT 0,91        sort_order INTEGER NOT NULL DEFAULT 0,92        lifecycle TEXT NOT NULL,93        session_state BLOB,94        zoom REAL NOT NULL DEFAULT 1,95        user_agent_mode TEXT NOT NULL,96        is_reader_active INTEGER NOT NULL DEFAULT 0,97        created_at REAL NOT NULL,98        last_active_at REAL NOT NULL,99        closed_at REAL100    );101    CREATE INDEX idx_tabs_window ON tabs(window_id, closed_at, sort_order);102    CREATE INDEX idx_tabs_space ON tabs(space_id, closed_at);103    CREATE INDEX idx_tabs_group ON tabs(group_id) WHERE group_id IS NOT NULL;104    CREATE INDEX idx_tabs_parent ON tabs(parent_id) WHERE parent_id IS NOT NULL;105    CREATE INDEX idx_tabs_closed ON tabs(closed_at) WHERE closed_at IS NOT NULL;106107    -- History: one row per distinct URL of a profile, one row per visit.108    CREATE TABLE history_urls (109        id INTEGER PRIMARY KEY,110        profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,111        url TEXT NOT NULL,112        host TEXT NOT NULL DEFAULT '',113        title TEXT NOT NULL DEFAULT '',114        visit_count INTEGER NOT NULL DEFAULT 0,115        typed_count INTEGER NOT NULL DEFAULT 0,116        last_visited_at REAL NOT NULL,117        UNIQUE (profile_id, url)118    );119    CREATE INDEX idx_history_urls_recent ON history_urls(profile_id, last_visited_at DESC);120    CREATE INDEX idx_history_urls_host ON history_urls(profile_id, host);121122    CREATE TABLE history_visits (123        id TEXT PRIMARY KEY,124        url_id INTEGER NOT NULL REFERENCES history_urls(id) ON DELETE CASCADE,125        profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,126        space_id TEXT,127        title TEXT NOT NULL DEFAULT '',128        visited_at REAL NOT NULL,129        transition TEXT NOT NULL130    );131    CREATE INDEX idx_history_visits_profile ON history_visits(profile_id, visited_at DESC);132    CREATE INDEX idx_history_visits_url ON history_visits(url_id, visited_at);133134    -- External-content FTS5 index over history_urls, kept in sync by triggers. Prefix indexes make135    -- "type three letters" queries a lookup instead of a term scan.136    CREATE VIRTUAL TABLE history_fts USING fts5(137        title, url, content='history_urls', content_rowid='id',138        tokenize="unicode61 remove_diacritics 2", prefix='1 2 3'139    );140    CREATE TRIGGER history_urls_ai AFTER INSERT ON history_urls BEGIN141        INSERT INTO history_fts(rowid, title, url) VALUES (new.id, new.title, new.url);142    END;143    CREATE TRIGGER history_urls_ad AFTER DELETE ON history_urls BEGIN144        INSERT INTO history_fts(history_fts, rowid, title, url) VALUES ('delete', old.id, old.title, old.url);145    END;146    CREATE TRIGGER history_urls_au AFTER UPDATE OF title, url ON history_urls BEGIN147        INSERT INTO history_fts(history_fts, rowid, title, url) VALUES ('delete', old.id, old.title, old.url);148        INSERT INTO history_fts(rowid, title, url) VALUES (new.id, new.title, new.url);149    END;150151    CREATE TABLE bookmarks (152        id TEXT PRIMARY KEY,153        profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,154        parent_id TEXT REFERENCES bookmarks(id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,155        kind TEXT NOT NULL,156        title TEXT NOT NULL,157        url TEXT,158        sort_order INTEGER NOT NULL DEFAULT 0,159        is_favorite INTEGER NOT NULL DEFAULT 0,160        created_at REAL NOT NULL,161        updated_at REAL NOT NULL162    );163    CREATE INDEX idx_bookmarks_parent ON bookmarks(profile_id, parent_id, sort_order);164    CREATE INDEX idx_bookmarks_url ON bookmarks(profile_id, url);165    CREATE INDEX idx_bookmarks_favorite ON bookmarks(profile_id, sort_order) WHERE is_favorite = 1;166167    CREATE TABLE bookmark_tags (168        bookmark_id TEXT NOT NULL REFERENCES bookmarks(id) ON DELETE CASCADE,169        tag TEXT NOT NULL,170        position INTEGER NOT NULL DEFAULT 0,171        PRIMARY KEY (bookmark_id, tag)172    ) WITHOUT ROWID;173    CREATE INDEX idx_bookmark_tags_tag ON bookmark_tags(tag);174175    CREATE TABLE downloads (176        id TEXT PRIMARY KEY,177        profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,178        source_url TEXT NOT NULL,179        origin_url TEXT,180        filename TEXT NOT NULL,181        destination_path TEXT,182        mime_type TEXT,183        bytes_received INTEGER NOT NULL DEFAULT 0,184        total_bytes INTEGER,185        state TEXT NOT NULL,186        resume_data BLOB,187        error_description TEXT,188        started_at REAL NOT NULL,189        finished_at REAL190    );191    CREATE INDEX idx_downloads_profile ON downloads(profile_id, started_at DESC);192    CREATE INDEX idx_downloads_state ON downloads(state);193194    -- origin_port is -1 for "default port" so the uniqueness constraint needs no expression index.195    CREATE TABLE permissions (196        id TEXT PRIMARY KEY,197        profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,198        origin_scheme TEXT NOT NULL,199        origin_host TEXT NOT NULL,200        origin_port INTEGER NOT NULL DEFAULT -1,201        kind TEXT NOT NULL,202        verdict TEXT NOT NULL,203        decided_at REAL NOT NULL,204        expires_at REAL,205        UNIQUE (profile_id, origin_scheme, origin_host, origin_port, kind)206    );207208    CREATE TABLE archives (209        id TEXT PRIMARY KEY,210        profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,211        url TEXT NOT NULL,212        title TEXT NOT NULL,213        format TEXT NOT NULL,214        relative_path TEXT NOT NULL,215        byte_size INTEGER NOT NULL,216        content_hash TEXT NOT NULL,217        is_complete INTEGER NOT NULL,218        missing TEXT NOT NULL,219        captured_at REAL NOT NULL220    );221    CREATE INDEX idx_archives_profile ON archives(profile_id, captured_at DESC);222    CREATE INDEX idx_archives_url ON archives(profile_id, url);223224    CREATE TABLE page_snapshots (225        id TEXT PRIMARY KEY,226        profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,227        url TEXT NOT NULL,228        title TEXT NOT NULL,229        body TEXT NOT NULL,230        archive_id TEXT REFERENCES archives(id) ON DELETE SET NULL,231        taken_at REAL NOT NULL232    );233    CREATE INDEX idx_page_snapshots_url ON page_snapshots(profile_id, url, taken_at DESC);234235    -- Notes, canvases and agent runs outlive their space (space_id becomes NULL); deleting a *profile*236    -- removes them explicitly (DataLifecycle.deleteProfile).237    CREATE TABLE notes (238        id TEXT PRIMARY KEY,239        space_id TEXT REFERENCES spaces(id) ON DELETE SET NULL,240        url TEXT,241        title TEXT NOT NULL DEFAULT '',242        body TEXT NOT NULL,243        quote TEXT,244        tint TEXT,245        created_at REAL NOT NULL,246        updated_at REAL NOT NULL247    );248    CREATE INDEX idx_notes_space ON notes(space_id, updated_at DESC);249    CREATE INDEX idx_notes_url ON notes(url);250251    CREATE TABLE canvas_documents (252        id TEXT PRIMARY KEY,253        space_id TEXT REFERENCES spaces(id) ON DELETE SET NULL,254        title TEXT NOT NULL,255        cards TEXT NOT NULL,256        connections TEXT NOT NULL,257        viewport TEXT NOT NULL,258        created_at REAL NOT NULL,259        updated_at REAL NOT NULL260    );261    CREATE INDEX idx_canvas_space ON canvas_documents(space_id, updated_at DESC);262263    CREATE TABLE agent_runs (264        id TEXT PRIMARY KEY,265        space_id TEXT REFERENCES spaces(id) ON DELETE SET NULL,266        goal TEXT NOT NULL,267        provider_id TEXT NOT NULL,268        model TEXT NOT NULL,269        status TEXT NOT NULL,270        steps TEXT NOT NULL,271        citations TEXT NOT NULL,272        answer TEXT,273        usage TEXT NOT NULL,274        budget TEXT NOT NULL,275        started_at REAL NOT NULL,276        finished_at REAL277    );278    CREATE INDEX idx_agent_runs_started ON agent_runs(started_at DESC);279    CREATE INDEX idx_agent_runs_space ON agent_runs(space_id);280281    CREATE TABLE workflows (282        id TEXT PRIMARY KEY,283        name TEXT NOT NULL,284        source TEXT NOT NULL,285        language_version INTEGER NOT NULL,286        created_at REAL NOT NULL,287        updated_at REAL NOT NULL,288        last_run_at REAL289    );290291    CREATE TABLE sync_records (292        id TEXT PRIMARY KEY,293        entity TEXT NOT NULL,294        entity_id TEXT NOT NULL,295        version INTEGER NOT NULL,296        device_id TEXT NOT NULL,297        modified_at REAL NOT NULL,298        deleted_at REAL,299        payload_hash TEXT,300        UNIQUE (entity, entity_id)301    );302    CREATE INDEX idx_sync_records_version ON sync_records(version);303    """304305    // MARK: - v2306307    /// Added when the omnibox ranking was designed: `frecency` is a time-invariant score (see `Frecency`) and308    /// `host_key` is the host without a leading `www.`, used for host-prefix boosts and "delete this site".309    /// Existing rows are backfilled from their visits.310    static let v2HistoryFrecency: @Sendable (SQLiteConnection) throws -> Void = { connection in311        try connection.executeScript("""312        ALTER TABLE history_urls ADD COLUMN host_key TEXT NOT NULL DEFAULT '';313        ALTER TABLE history_urls ADD COLUMN frecency REAL NOT NULL DEFAULT \(Frecency.none);314        """)315        for row in try connection.query("SELECT id, host FROM history_urls") {316            let host: String = try row.get("host")317            try connection.execute("UPDATE history_urls SET host_key = ? WHERE id = ?",318                                   [Frecency.hostKey(host), try row.get("id", as: Int64.self)])319        }320        try HistorySQL.recomputeFrecency(connection, where: "1 = 1", [])321        try connection.executeScript("""322        CREATE INDEX idx_history_urls_host_key ON history_urls(profile_id, host_key);323        CREATE INDEX idx_history_urls_frecency ON history_urls(profile_id, frecency DESC);324        """)325    }326}327
Files main
Menu

Theme