use rusqlite::{Connection, params};
use super::{Index, ms};
use crate::claude::seats::{Seat, SeatId};
use crate::core::harness::Harness;
pub(crate) fn seat_tables(conn: &Connection) -> rusqlite::Result<Vec<String>> {
let tables: Vec<String> = conn
.prepare(
"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'
AND name != 'seats' ORDER BY name",
)?
.query_map([], |r| r.get(0))?
.collect::<Result<_, _>>()?;
let mut out = Vec::new();
for t in tables {
let has_seat = conn
.prepare("SELECT 1 FROM pragma_table_info(?1) WHERE name = 'seat'")?
.exists([&t])?;
if has_seat {
out.push(t);
}
}
Ok(out)
}
pub(super) fn list_legacy_labels(conn: &Connection) -> rusqlite::Result<usize> {
let mut labels = std::collections::BTreeSet::new();
for t in seat_tables(conn)? {
let mut st = conn.prepare(&format!(
"SELECT DISTINCT seat FROM {t} WHERE seat IS NOT NULL"
))?;
for v in st.query_map([], |r| r.get::<_, String>(0))? {
let v = v?;
if !SeatId::looks_like_id(&v) {
labels.insert(v);
}
}
}
for l in &labels {
conn.execute(
"INSERT INTO seats(seat, label, dir, seen_at) VALUES (?1, ?1, NULL, 0) ON CONFLICT(seat) DO NOTHING",
[l],
)?;
}
Ok(labels.len())
}
impl Index {
pub(super) fn adopt_seats(&mut self, seats: &[Seat]) -> anyhow::Result<()> {
let sig: Vec<(SeatId, String, Harness)> = seats
.iter()
.map(|s| (s.id.clone(), s.label.clone(), s.harness))
.collect();
if self.adopted.as_ref() == Some(&sig) {
return Ok(());
}
let tx = self
.conn
.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
let legacy: Vec<String> = tx
.prepare_cached("SELECT seat FROM seats WHERE dir IS NULL")?
.query_map([], |r| r.get(0))?
.collect::<Result<_, _>>()?;
let mut moved = 0;
for s in seats {
if !legacy.contains(&s.label) {
continue;
}
let mut left = 0;
for t in seat_tables(&tx)? {
moved += tx.execute(
&format!("UPDATE OR IGNORE {t} SET seat = ?1 WHERE seat = ?2"),
params![s.id, s.label],
)?;
left += tx.query_row(
&format!("SELECT COUNT(*) FROM {t} WHERE seat = ?1"),
[&s.label],
|r| r.get::<_, i64>(0),
)?;
}
if left == 0 {
tx.execute(
"DELETE FROM seats WHERE seat = ?1 AND dir IS NULL",
[&s.label],
)?;
}
}
let now = ms(chrono::Utc::now());
for s in seats {
tx.execute(
"INSERT INTO seats(seat, label, dir, harness, seen_at) VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT(seat) DO UPDATE SET label = excluded.label, dir = excluded.dir, harness = excluded.harness, seen_at = excluded.seen_at",
params![s.id, s.label, s.dir.to_string_lossy(), s.harness.key(), now],
)?;
}
if moved > 0 {
super::bump_settled(&tx)?;
}
tx.commit()?;
self.adopted = Some(sig);
Ok(())
}
pub fn seat_labels(&self) -> anyhow::Result<Vec<(SeatId, String)>> {
Ok(self
.conn
.prepare_cached("SELECT seat, label FROM seats ORDER BY label")?
.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
.collect::<Result<_, _>>()?)
}
pub fn seats_with_transcripts(&self) -> anyhow::Result<std::collections::BTreeSet<SeatId>> {
Ok(self
.conn
.prepare_cached("SELECT seat FROM files UNION SELECT seat FROM sessions")?
.query_map([], |r| r.get(0))?
.collect::<Result<_, _>>()?)
}
}