diff --git a/src/db/migrations/006_backfill_publishers.sql b/src/db/migrations/006_backfill_publishers.sql new file mode 100644 index 0000000..4a08f69 --- /dev/null +++ b/src/db/migrations/006_backfill_publishers.sql @@ -0,0 +1,9 @@ +-- Backfill publishers table from existing torrent pubkeys. +-- Safe to run on databases that already have publisher rows (ON CONFLICT is a no-op for those). +INSERT INTO publishers (pubkey, torrents_n, last_seen) +SELECT pubkey, COUNT(*), MAX(ingested_at) +FROM torrents +GROUP BY pubkey +ON CONFLICT(pubkey) DO UPDATE SET + torrents_n = MAX(publishers.torrents_n, excluded.torrents_n), + last_seen = MAX(publishers.last_seen, excluded.last_seen); diff --git a/src/db/queries.rs b/src/db/queries.rs index 668eff9..499a0cd 100644 --- a/src/db/queries.rs +++ b/src/db/queries.rs @@ -87,6 +87,19 @@ pub async fn insert_torrent(pool: &SqlitePool, r: &TorrentRecord) -> anyhow::Res return Ok(()); } + // Ensure the publisher row exists and bump their counters + sqlx::query( + "INSERT INTO publishers (pubkey, torrents_n, last_seen) + VALUES (?, 1, ?) + ON CONFLICT(pubkey) DO UPDATE SET + torrents_n = torrents_n + 1, + last_seen = excluded.last_seen", + ) + .bind(&r.pubkey) + .bind(r.ingested_at) + .execute(&mut *tx) + .await?; + for url in &r.trackers { sqlx::query("INSERT OR IGNORE INTO trackers (event_id, url) VALUES (?,?)") .bind(&r.event_id)