Skip to main content

radio_cli/
store.rs

1mod facets;
2mod geo;
3mod revisions;
4pub use revisions::ListRevision;
5
6use crate::error::{DomainError, ErrorCode};
7use crate::model::{Filter, Recording, Station};
8use anyhow::{Context, Result, bail};
9use rusqlite::{
10    Connection, OptionalExtension, TransactionBehavior, params, params_from_iter, types::Value,
11};
12use std::path::Path;
13
14const RECORDING_ORDER: &str =
15    "CASE WHEN json_valid(json) THEN json_extract(json,'$.started_at') END DESC,id DESC";
16const SCHEMA_VERSION: u32 = 11;
17
18pub(crate) enum Played {
19    Station(String),
20    Episode(String),
21}
22
23pub struct Store {
24    pub(crate) conn: Connection,
25}
26
27impl Store {
28    pub(crate) fn open_writer(path: &Path) -> Result<Self> {
29        // The session owner has already migrated the database. A short lock
30        // budget lets background writers retry and observe shutdown promptly.
31        let conn = Connection::open(path)?;
32        crate::podcast::register_functions(&conn)?;
33        conn.busy_timeout(std::time::Duration::from_millis(100))?;
34        conn.execute_batch("PRAGMA foreign_keys=ON; PRAGMA synchronous=NORMAL;")?;
35        Ok(Self { conn })
36    }
37
38    #[cfg(test)]
39    pub(crate) fn test_connection(&self) -> &Connection {
40        &self.conn
41    }
42
43    #[cfg(test)]
44    pub(crate) fn test_connection_mut(&mut self) -> &mut Connection {
45        &mut self.conn
46    }
47
48    pub(crate) fn open_reader(path: &Path) -> Result<Self> {
49        let conn = Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
50        crate::podcast::register_functions(&conn)?;
51        conn.busy_timeout(std::time::Duration::from_millis(100))?;
52        conn.execute_batch("PRAGMA cache_size=-4096;")?;
53        Ok(Self { conn })
54    }
55
56    pub(crate) fn interrupt_handle(&self) -> rusqlite::InterruptHandle {
57        self.conn.get_interrupt_handle()
58    }
59
60    pub(crate) fn cancel_queries_when(
61        &mut self,
62        cancel: impl FnMut() -> bool + Send + 'static,
63    ) -> Result<()> {
64        Ok(self.conn.progress_handler(1000, Some(cancel))?)
65    }
66
67    pub(crate) fn read_snapshot<T>(&self, read: impl FnOnce(&Self) -> Result<T>) -> Result<T> {
68        let tx = self.conn.unchecked_transaction()?;
69        // BEGIN is deferred. Pin the WAL snapshot before reading revisions
70        // so a count cached for an older snapshot cannot be reused for new rows.
71        tx.query_row("SELECT 1 FROM sqlite_schema LIMIT 1", [], |_| Ok(()))?;
72        let value = read(self)?;
73        tx.commit()?;
74        Ok(value)
75    }
76
77    pub fn open(path: &Path) -> Result<Self> {
78        let mut conn = Connection::open(path)?;
79        crate::podcast::register_functions(&conn)?;
80        conn.busy_timeout(std::time::Duration::from_secs(5))?;
81        conn.execute_batch(
82            "PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL;
83            PRAGMA cache_size=-4096; PRAGMA synchronous=NORMAL;",
84        )?;
85        let version: u32 = conn.pragma_query_value(None, "user_version", |r| r.get(0))?;
86        if version > SCHEMA_VERSION {
87            bail!(DomainError::new(ErrorCode::DatabaseTooNew));
88        }
89        if version < SCHEMA_VERSION {
90            let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
91            // Another process may have migrated while we waited for the lock.
92            let version: u32 = tx.pragma_query_value(None, "user_version", |r| r.get(0))?;
93            match version {
94                0 => tx.execute_batch(
95                    "CREATE TABLE stations (
96                        uuid TEXT PRIMARY KEY, name TEXT NOT NULL, search TEXT NOT NULL,
97                        country TEXT NOT NULL, languages TEXT NOT NULL, tags TEXT NOT NULL,
98                        bitrate INTEGER NOT NULL, popularity INTEGER NOT NULL,
99                        custom INTEGER NOT NULL, active INTEGER NOT NULL, json TEXT NOT NULL);
100                    CREATE INDEX station_country ON stations(country, bitrate);
101                    CREATE INDEX station_popularity ON stations(popularity DESC);
102                    CREATE TABLE favorites (
103                        uuid TEXT PRIMARY KEY REFERENCES stations(uuid), created_at TEXT NOT NULL);
104                    CREATE TABLE history (
105                        id INTEGER PRIMARY KEY, uuid TEXT NOT NULL REFERENCES stations(uuid), played_at TEXT NOT NULL);
106                    CREATE INDEX history_station ON history(uuid);
107                    CREATE TABLE streams (
108                        uuid TEXT NOT NULL REFERENCES stations(uuid), url TEXT NOT NULL, PRIMARY KEY(uuid,url));
109                    CREATE TABLE recordings (
110                        id TEXT PRIMARY KEY, status TEXT NOT NULL, json TEXT NOT NULL,
111                        recovery_pending INTEGER NOT NULL DEFAULT 0 CHECK(recovery_pending IN (0,1)));
112                    CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);"
113                )?,
114                1 => tx.execute_batch(
115                    "ALTER TABLE recordings ADD COLUMN recovery_pending INTEGER NOT NULL DEFAULT 0 CHECK(recovery_pending IN (0,1));
116                    -- Translate legacy diagnostics once, never during normal queries.
117                    UPDATE recordings SET recovery_pending=1 WHERE status='interrupted' AND json_extract(json,'$.error') LIKE '恢复失败:%';"
118                )?,
119                2..=SCHEMA_VERSION => {},
120                _ => bail!(DomainError::new(ErrorCode::DatabaseTooNew)),
121            }
122            if version < 3 {
123                tx.execute_batch(
124                    "ALTER TABLE stations ADD COLUMN normalized_url TEXT;
125                    CREATE INDEX station_url ON stations(normalized_url) WHERE active=1;",
126                )?;
127                let mut select = tx.prepare("SELECT uuid,json FROM stations")?;
128                let mut update =
129                    tx.prepare("UPDATE stations SET normalized_url=?2 WHERE uuid=?1")?;
130                let rows = select
131                    .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
132                for row in rows {
133                    let (uuid, json) = row?;
134                    let station: Station = serde_json::from_str(&json)?;
135                    update.execute(params![
136                        uuid,
137                        crate::service::normalized_url(station.primary_url()).ok()
138                    ])?;
139                }
140            }
141            if version < 4 {
142                tx.execute_batch(
143                    "CREATE TABLE facets_cache (
144                    kind INTEGER NOT NULL,value TEXT NOT NULL,n INTEGER NOT NULL CHECK(n>=0),
145                    PRIMARY KEY(kind,value)) WITHOUT ROWID;",
146                )?;
147                facets::rebuild(&tx)?;
148            }
149            if version < 5 {
150                tx.execute_batch(
151                    "CREATE INDEX station_sort ON stations(popularity DESC,name,uuid,active,custom,bitrate);
152                    CREATE INDEX station_name ON stations(name COLLATE NOCASE,uuid,active,custom,bitrate);
153                    CREATE INDEX station_bitrate ON stations(bitrate DESC,name,uuid,active,custom);
154                    CREATE INDEX station_active ON stations(active) WHERE active=1;
155                    CREATE INDEX station_directory ON stations(active) WHERE active=1 AND custom=0;
156                    DROP INDEX IF EXISTS station_popularity;
157                    CREATE VIRTUAL TABLE station_search USING fts5(search,
158                        content='stations',content_rowid='rowid',columnsize=0,detail=none,
159                        tokenize='trigram case_sensitive 1');
160                    INSERT INTO station_search(station_search) VALUES ('rebuild');
161                    CREATE VIRTUAL TABLE station_search_terms USING fts5vocab(station_search,'row');
162                    CREATE TABLE station_search_stats(term TEXT PRIMARY KEY,n INTEGER NOT NULL) WITHOUT ROWID;
163                    INSERT INTO station_search_stats SELECT term,doc FROM station_search_terms;
164                    INSERT INTO station_search_stats VALUES ('',(SELECT count(*) FROM stations));
165                    CREATE TRIGGER station_search_insert AFTER INSERT ON stations BEGIN
166                        INSERT INTO station_search(rowid,search) VALUES (new.rowid,new.search);
167                    END;
168                    CREATE TRIGGER station_search_delete AFTER DELETE ON stations BEGIN
169                        INSERT INTO station_search(station_search,rowid,search) VALUES ('delete',old.rowid,old.search);
170                    END;
171                    CREATE TRIGGER station_search_update AFTER UPDATE OF search ON stations
172                    WHEN old.search IS NOT new.search BEGIN
173                        INSERT INTO station_search(station_search,rowid,search) VALUES ('delete',old.rowid,old.search);
174                        INSERT INTO station_search(rowid,search) VALUES (new.rowid,new.search);
175                    END;
176                    ANALYZE;",
177                )?;
178            }
179            if version < 6 {
180                geo::migrate(&tx)?;
181            }
182            if version < 7 {
183                revisions::migrate(&tx)?;
184            }
185            if version < 8 {
186                tx.execute_batch(&format!(
187                    "CREATE INDEX IF NOT EXISTS recording_started ON recordings({RECORDING_ORDER});"
188                ))?;
189            }
190            if version < 9 {
191                crate::podcast::migrate(&tx)?;
192            }
193            if version < 10 {
194                crate::podcast::migrate_library(&tx)?;
195            }
196            if version < 11 {
197                crate::podcast::migrate_episode_order(&tx)?;
198            }
199            tx.pragma_update(None, "user_version", SCHEMA_VERSION)?;
200            tx.commit()?;
201        }
202        Ok(Self { conn })
203    }
204
205    pub fn upsert(&self, station: &Station) -> Result<()> {
206        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
207        Self::write_station(&tx, "stations", station)?;
208        geo::changed(&tx)?;
209        tx.commit()?;
210        Ok(())
211    }
212
213    pub fn bootstrap(
214        &mut self,
215        rows: &[Station],
216        mut cancelled: impl FnMut() -> bool,
217    ) -> Result<usize> {
218        let tx = self.conn.transaction()?;
219        for row in rows {
220            if cancelled() {
221                bail!(DomainError::new(ErrorCode::Cancelled));
222            }
223            Self::write_station_with_policy(&tx, "stations", row, false, false)?;
224        }
225        if cancelled() {
226            bail!(DomainError::new(ErrorCode::Cancelled));
227        }
228        if rows.is_empty() {
229            bail!(DomainError::new(ErrorCode::EmptyCatalog));
230        }
231        facets::rebuild(&tx)?;
232        if cancelled() {
233            bail!(DomainError::new(ErrorCode::Cancelled));
234        }
235        geo::changed(&tx)?;
236        tx.commit()?;
237        // Advisory maintenance must not fail an already published catalog.
238        let _ = self.refresh_search_stats();
239        Ok(rows.len())
240    }
241
242    fn write_station(conn: &Connection, table: &str, s: &Station) -> Result<()> {
243        Self::write_station_with_policy(conn, table, s, false, table == "stations")
244    }
245
246    fn write_station_with_policy(
247        conn: &Connection,
248        table: &str,
249        s: &Station,
250        custom: bool,
251        maintain_facets: bool,
252    ) -> Result<()> {
253        if s.stationuuid.is_empty() || s.name.trim().is_empty() {
254            bail!(DomainError::new(ErrorCode::InvalidStation));
255        }
256        uuid::Uuid::parse_str(&s.stationuuid).context(DomainError::new(ErrorCode::InvalidUuid))?;
257        let before = if maintain_facets {
258            facets::station_values(conn, &s.stationuuid)?
259        } else {
260            Default::default()
261        };
262        let sql = format!("INSERT INTO {table} (uuid,name,search,country,languages,tags,bitrate,popularity,custom,active,json,normalized_url,geo_x,geo_y)
263            VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14)
264            ON CONFLICT(uuid) DO UPDATE SET name=excluded.name,search=excluded.search,
265            country=excluded.country,languages=excluded.languages,tags=excluded.tags,
266            bitrate=excluded.bitrate,popularity=excluded.popularity,custom=excluded.custom,active=excluded.active,json=excluded.json,normalized_url=excluded.normalized_url,geo_x=excluded.geo_x,geo_y=excluded.geo_y
267            WHERE {table}.custom=0 OR {custom}");
268        // Facet queries compare normalized prefixes with binary SQL equality.
269        // Keep country codes uppercase and language/tag tokens Unicode lowercase
270        // here, for both catalog imports and custom stations.
271        let normalize = |value: &str| {
272            value
273                .split(',')
274                .map(|v| v.trim().to_lowercase())
275                .filter(|v| !v.is_empty())
276                .collect::<Vec<_>>()
277                .join(",")
278        };
279        let languages = normalize(&format!("{},{}", s.language, s.languagecodes));
280        let coordinates = crate::geo::coordinates(s.geo_lat, s.geo_long);
281        conn.prepare_cached(&sql)?.execute(params![
282            s.stationuuid,
283            s.name,
284            s.search_text(),
285            s.countrycode.to_uppercase(),
286            format!(",{languages},"),
287            format!(",{},", normalize(&s.tags)),
288            s.bitrate,
289            s.clickcount.min(i64::MAX as u64),
290            s.custom,
291            s.active,
292            serde_json::to_string(s)?,
293            crate::service::normalized_url(s.primary_url()).ok(),
294            coordinates.map(|p| p.0),
295            coordinates.map(|p| p.1)
296        ])?;
297        if maintain_facets {
298            facets::update(
299                conn,
300                &before,
301                &facets::station_values(conn, &s.stationuuid)?,
302            )?;
303        }
304        Ok(())
305    }
306
307    pub fn set_meta(&self, key: &str, value: &str) -> Result<()> {
308        Self::write_meta(&self.conn, key, value)
309    }
310
311    fn write_meta(conn: &Connection, key: &str, value: &str) -> Result<()> {
312        conn.execute(
313            "INSERT INTO meta(key,value) VALUES (?1,?2) ON CONFLICT(key) DO UPDATE SET value=excluded.value WHERE meta.value IS NOT excluded.value",
314            params![key, value],
315        )?;
316        Ok(())
317    }
318
319    pub(crate) fn save_session(
320        &self,
321        preferences: &std::collections::BTreeMap<String, String>,
322        plays: &[(Played, String)],
323    ) -> Result<()> {
324        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
325        for (play, at) in plays {
326            match play {
327                Played::Station(uuid) => {
328                    tx.execute(
329                        "INSERT INTO history(uuid,played_at) VALUES (?1,?2)",
330                        params![uuid, at],
331                    )?;
332                    let threshold = tx.last_insert_rowid().saturating_sub(1000);
333                    tx.execute("DELETE FROM history WHERE id<=?1", [threshold])?;
334                    Self::write_meta(&tx, "pref_last_station", uuid)?;
335                    Self::write_meta(&tx, "pref_last_media", "station")?;
336                }
337                Played::Episode(id) => {
338                    tx.execute(
339                        "INSERT INTO podcast_history(episode_id,played_at) VALUES (?1,?2)",
340                        params![id, at],
341                    )?;
342                    Self::write_meta(&tx, "pref_last_episode", id)?;
343                    Self::write_meta(&tx, "pref_last_media", "episode")?;
344                }
345            }
346        }
347        for (key, value) in preferences {
348            if let Some(id) = key.strip_prefix("podcast_progress:") {
349                Self::write_podcast_progress(&tx, id, &serde_json::from_str(value)?)?;
350                continue;
351            }
352            Self::write_meta(&tx, key, value)?;
353        }
354        tx.commit()?;
355        Ok(())
356    }
357
358    pub fn directory_count(&self) -> Result<usize> {
359        Ok(self.conn.query_row(
360            "SELECT count(*) FROM stations WHERE custom=0 AND active=1",
361            [],
362            |r| r.get(0),
363        )?)
364    }
365
366    pub fn incoming_count(&self) -> Result<usize> {
367        Ok(self
368            .conn
369            .query_row("SELECT count(*) FROM incoming", [], |r| r.get(0))?)
370    }
371
372    pub fn begin_sync(&self) -> Result<()> {
373        self.conn.execute_batch(
374            "DROP TABLE IF EXISTS temp.incoming;
375            CREATE TEMP TABLE incoming AS SELECT uuid,name,search,country,languages,tags,bitrate,popularity,custom,active,json,normalized_url,geo_x,geo_y FROM stations WHERE 0;
376            CREATE UNIQUE INDEX temp.incoming_uuid ON incoming(uuid);",
377        )?;
378        Ok(())
379    }
380
381    pub fn stage(&mut self, rows: &[Station]) -> Result<()> {
382        let tx = self.conn.transaction()?;
383        for row in rows {
384            let mut s = row.clone();
385            s.active = true;
386            s.custom = false;
387            Self::write_station(&tx, "incoming", &s)?;
388        }
389        tx.commit()?;
390        Ok(())
391    }
392
393    pub fn finish_sync(&mut self) -> Result<usize> {
394        self.finish_sync_cancellable(|| false, |_, _| Ok(None))
395    }
396
397    pub(crate) fn finish_sync_cancellable(
398        &mut self,
399        mut cancelled: impl FnMut() -> bool,
400        record_attempt: impl FnOnce(&Self, usize) -> Result<Option<DomainError>>,
401    ) -> Result<usize> {
402        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
403        let count: usize = self.incoming_count()?;
404        if count == 0 {
405            bail!(DomainError::new(ErrorCode::EmptyCatalog));
406        }
407        if let Some(rejected) = record_attempt(self, count)? {
408            // Keep the rejection report without touching the published catalog.
409            tx.commit()?;
410            return Err(rejected.into());
411        }
412        let search_changed: bool = tx.query_row(
413            "SELECT EXISTS(SELECT 1 FROM incoming i LEFT JOIN stations s ON s.uuid=i.uuid
414             WHERE s.uuid IS NULL OR (s.custom=0 AND s.search IS NOT i.search))",
415            [],
416            |r| r.get(0),
417        )?;
418        let facet_delta = facets::publication_delta(&tx)?;
419        if cancelled() {
420            bail!(DomainError::new(ErrorCode::Cancelled));
421        }
422        let removed = tx.execute(
423            "UPDATE stations SET active=0 WHERE custom=0 AND active=1
424             AND NOT EXISTS(SELECT 1 FROM incoming i WHERE i.uuid=stations.uuid)",
425            [],
426        )?;
427        let updated = tx.execute(
428            "INSERT INTO stations (uuid,name,search,country,languages,tags,bitrate,popularity,custom,active,json,normalized_url,geo_x,geo_y) SELECT uuid,name,search,country,languages,tags,bitrate,popularity,custom,active,json,normalized_url,geo_x,geo_y FROM incoming WHERE true
429            ON CONFLICT(uuid) DO UPDATE SET name=excluded.name,search=excluded.search,
430            country=excluded.country,languages=excluded.languages,tags=excluded.tags,
431            bitrate=excluded.bitrate,popularity=excluded.popularity,active=1,json=excluded.json,normalized_url=excluded.normalized_url,geo_x=excluded.geo_x,geo_y=excluded.geo_y
432            WHERE stations.custom=0 AND (
433                stations.active<>1 OR stations.json IS NOT excluded.json OR
434                stations.name IS NOT excluded.name OR stations.search IS NOT excluded.search OR
435                stations.country IS NOT excluded.country OR stations.languages IS NOT excluded.languages OR
436                stations.tags IS NOT excluded.tags OR stations.bitrate IS NOT excluded.bitrate OR
437                stations.popularity IS NOT excluded.popularity OR stations.normalized_url IS NOT excluded.normalized_url OR
438                stations.geo_x IS NOT excluded.geo_x OR stations.geo_y IS NOT excluded.geo_y)", [],
439        )?;
440        tx.execute(
441            "INSERT OR REPLACE INTO meta(key,value) VALUES ('last_sync',?1)",
442            [crate::timestamp::now()],
443        )?;
444        facets::apply_delta(&tx, facet_delta)?;
445        if cancelled() {
446            bail!(DomainError::new(ErrorCode::Cancelled));
447        }
448        if removed + updated > 0 {
449            geo::changed(&tx)?;
450        }
451        tx.commit()?;
452        // Planner maintenance cannot turn a successful publication into a
453        // reported failure after its transaction has already committed.
454        if search_changed {
455            let _ = self.refresh_search_stats();
456        }
457        if removed + updated > 0 {
458            let _ = self.conn.execute_batch("PRAGMA optimize;");
459        }
460        Ok(count)
461    }
462
463    // A different sync may have published between the rollback and this write.
464    pub(crate) fn record_rolled_back_sync(
465        &self,
466        previous: Option<&str>,
467        report: &str,
468    ) -> Result<()> {
469        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
470        if self.meta("last_sync_attempt")?.as_deref() == previous {
471            self.set_meta("last_sync_attempt", report)?;
472        }
473        Ok(tx.commit()?)
474    }
475
476    /// Connection activity for diagnostics, including preferences and SQL
477    /// maintenance. This is not a list cache key; use [`Self::list_revision`].
478    /// Values are meaningful only for repeated reads on the same connection.
479    pub fn revision(&self) -> Result<(u64, u64)> {
480        let external = self
481            .conn
482            .pragma_query_value(None, "data_version", |r| r.get(0))?;
483        Ok((external, self.conn.total_changes()))
484    }
485
486    pub fn meta(&self, key: &str) -> Result<Option<String>> {
487        Ok(self
488            .conn
489            .query_row("SELECT value FROM meta WHERE key=?1", [key], |r| r.get(0))
490            .optional()?)
491    }
492
493    pub fn count(&self) -> Result<usize> {
494        Ok(self
495            .conn
496            .query_row("SELECT count(*) FROM stations WHERE active=1", [], |r| {
497                r.get(0)
498            })?)
499    }
500
501    pub fn station(&self, uuid: &str) -> Result<Station> {
502        let row = self
503            .conn
504            .query_row(
505                "SELECT s.json,s.active,f.uuid IS NOT NULL FROM stations s
506            LEFT JOIN favorites f ON f.uuid=s.uuid WHERE s.uuid=?1",
507                [uuid],
508                |r| {
509                    Ok((
510                        r.get::<_, String>(0)?,
511                        r.get::<_, bool>(1)?,
512                        r.get::<_, bool>(2)?,
513                    ))
514                },
515            )
516            .optional()?
517            .context(DomainError::new(ErrorCode::StationNotFound))?;
518        let mut s: Station = serde_json::from_str(&row.0)?;
519        s.active = row.1;
520        s.favorite = row.2;
521        Ok(s)
522    }
523
524    fn conditions(&self, filter: &Filter) -> (String, Vec<Value>, &'static str) {
525        self.conditions_with_spatial(filter, true)
526    }
527
528    fn conditions_with_spatial(
529        &self,
530        filter: &Filter,
531        spatial: bool,
532    ) -> (String, Vec<Value>, &'static str) {
533        let mut clauses = vec![
534            "(s.active=1 OR s.custom=1 OR EXISTS(SELECT 1 FROM favorites f WHERE f.uuid=s.uuid))"
535                .to_owned(),
536        ];
537        let mut args = vec![];
538        // Token filters still use instr. Without a country index to narrow
539        // them, avoid random table lookups through a sorting index.
540        let mut source =
541            if filter.country.is_none() && (filter.language.is_some() || filter.tag.is_some()) {
542                "stations s NOT INDEXED"
543            } else {
544                "stations s"
545            };
546        if filter.favorites {
547            clauses.push("EXISTS(SELECT 1 FROM favorites f WHERE f.uuid=s.uuid)".into());
548        }
549        if filter.custom {
550            clauses.push("s.custom=1".into());
551        }
552        if filter.history {
553            clauses[0] = "1".into();
554        }
555        let mut text_candidates = false;
556        let query = filter.query.trim();
557        if !query.is_empty() {
558            // Resolve localized names at query time so existing catalogs do not
559            // need a resync or a rewrite of their original station metadata.
560            let codes: Vec<_> = crate::territories::matching_codes(query).collect();
561            let normalized = query.to_lowercase();
562            source = "stations s NOT INDEXED";
563            if !filter.history
564                && let Some(candidate) = self.trigram_candidate(&normalized)
565            {
566                text_candidates = true;
567                // A literal trigram narrows candidates; instr below checks
568                // the complete query without decoding positional postings.
569                let mut candidates =
570                    "SELECT rowid FROM station_search WHERE station_search MATCH ?".to_owned();
571                args.push(candidate.into());
572                if !codes.is_empty() {
573                    candidates.push_str(&format!(
574                        " UNION SELECT rowid FROM stations WHERE country IN ({})",
575                        vec!["?"; codes.len()].join(",")
576                    ));
577                    args.extend(codes.iter().map(|code| Value::from((*code).to_owned())));
578                }
579                clauses.push(
580                    if codes.is_empty()
581                        && !matches!(filter.geo, Some(crate::geo::GeoFilter::Cell(_)))
582                    {
583                        source =
584                            "station_search CROSS JOIN stations s ON s.rowid=station_search.rowid";
585                        "station_search MATCH ?".to_owned()
586                    } else {
587                        format!("s.rowid IN ({candidates})")
588                    },
589                );
590            }
591            if codes.is_empty() {
592                clauses.push("instr(s.search,?)>0".into());
593            } else {
594                let placeholders = vec!["?"; codes.len()].join(",");
595                clauses.push(format!(
596                    "(instr(s.search,?)>0 OR s.country IN ({placeholders}))"
597                ));
598            }
599            args.push(normalized.into());
600            args.extend(codes.into_iter().map(|code| Value::from(code.to_owned())));
601        }
602        if let Some(country) = &filter.country {
603            clauses.push("s.country=?".into());
604            args.push(country.to_uppercase().into());
605        }
606        for (col, value) in [("languages", &filter.language), ("tags", &filter.tag)] {
607            if let Some(value) = value {
608                clauses.push(format!("instr(s.{col},?)>0"));
609                args.push(format!(",{},", value.trim().to_lowercase()).into());
610            }
611        }
612        if filter.min_bitrate > 0 {
613            clauses.push("s.bitrate>=?".into());
614            args.push((filter.min_bitrate as i64).into());
615        }
616        if let Some(geo) = filter.geo {
617            clauses[0] = "s.active=1".into();
618            match geo {
619                crate::geo::GeoFilter::Missing => clauses.push("s.geo_x IS NULL".into()),
620                crate::geo::GeoFilter::Cell(bounds) if spatial => {
621                    clauses.push(geo::predicate(bounds, &mut args));
622                    // A full longitude scan through a non-covering spatial
623                    // index turns filtered world maps into random table reads.
624                    if (!text_candidates && bounds.width < crate::geo::WORLD_WIDTH)
625                        || geo::plain(filter)
626                    {
627                        source = "stations s INDEXED BY station_geo";
628                    }
629                    if filter.query.trim().is_empty()
630                        && let Some(country) = filter.country.as_ref().filter(|c| !c.is_empty())
631                        && self
632                            .conn
633                            .prepare_cached("SELECT n FROM facets_cache WHERE kind=0 AND value=?1")
634                            .and_then(|mut stmt| {
635                                stmt.query_row([country.to_uppercase()], |r| r.get::<_, usize>(0))
636                                    .optional()
637                            })
638                            .is_ok_and(|n| n.unwrap_or(0) <= geo::SORT_THRESHOLD)
639                    {
640                        // A small country is an upper bound on any of its map
641                        // cells. This hint only chooses an index, never rows.
642                        source = "stations s INDEXED BY station_country";
643                    }
644                }
645                crate::geo::GeoFilter::Cell(_) => {}
646            }
647        }
648        if filter.history {
649            // History retains at most 1000 entries. Drive the query from its
650            // distinct stations rather than probing history for every catalog
651            // row. CROSS JOIN preserves this bounded outer loop.
652            source = "(SELECT uuid,max(id) AS last_id FROM history GROUP BY uuid) recent
653                      CROSS JOIN stations s ON s.uuid=recent.uuid";
654        }
655        (clauses.join(" AND "), args, source)
656    }
657
658    /// One rare trigram supplies candidates; instr verifies the full literal.
659    /// Avoid positional phrase decoding for every row of a broad match.
660    fn trigram_candidate(&self, normalized: &str) -> Option<String> {
661        if normalized.chars().count() < 3 || normalized.contains('\0') {
662            return None;
663        }
664        let chars: Vec<_> = normalized.chars().collect();
665        let stride = ((chars.len() - 2) / 16).max(1);
666        let mut best = (usize::MAX, chars[..3].iter().collect::<String>());
667        // Bound vocabulary lookups for unusually long command-line queries.
668        let terms: std::collections::BTreeSet<String> = chars
669            .windows(3)
670            .step_by(stride)
671            .take(16)
672            .map(|part| part.iter().collect())
673            .collect();
674        for term in terms {
675            let frequency = self
676                .conn
677                .prepare_cached("SELECT n FROM station_search_stats WHERE term=?1")
678                .and_then(|mut s| s.query_row([&term], |r| r.get::<_, usize>(0)).optional());
679            // If statistics are unavailable, the literal remains a valid
680            // candidate. Query errors are reported by the actual FTS query.
681            let frequency = match frequency {
682                Ok(Some(n)) => n,
683                Ok(None) => 0,
684                Err(_) => continue,
685            };
686            if frequency < best.0 {
687                best = (frequency, term);
688            }
689            if frequency == 0 {
690                break;
691            }
692        }
693        let total: usize = self
694            .conn
695            .query_row(
696                "SELECT n FROM station_search_stats WHERE term=''",
697                [],
698                |r| r.get(0),
699            )
700            .unwrap_or(0);
701        // Statistics only choose a query strategy. Stale hints after a single
702        // station mutation never change the exact substring predicate.
703        if total > 0 && best.0 > total / 4 {
704            return None;
705        }
706        Some(format!("\"{}\"", best.1.replace('"', "\"\"")))
707    }
708
709    fn refresh_search_stats(&self) -> Result<()> {
710        // A single read statement pins a consistent snapshot for the vocabulary
711        // and row count. Collect before taking the main database's write lock:
712        // even a small vocabulary requires scanning FTS postings to count docs.
713        let stats = {
714            let mut stmt = self.conn.prepare(
715                "SELECT term,doc FROM station_search_terms
716                UNION ALL SELECT '',count(*) FROM stations",
717            )?;
718            stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))?
719                .collect::<rusqlite::Result<Vec<_>>>()?
720        };
721        // Publish all hints atomically. Concurrent station changes may make
722        // them stale, which only affects the choice of search strategy.
723        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
724        tx.execute("DELETE FROM station_search_stats", [])?;
725        {
726            let mut stmt = tx.prepare("INSERT INTO station_search_stats VALUES (?1,?2)")?;
727            for (term, count) in stats {
728                stmt.execute(params![term, count])?;
729            }
730        }
731        tx.commit()?;
732        Ok(())
733    }
734
735    fn search_order(filter: &Filter) -> &'static str {
736        if filter.history {
737            "recent.last_id DESC"
738        } else {
739            match filter.sort {
740                crate::model::Sort::Name => "s.name COLLATE NOCASE,s.uuid",
741                crate::model::Sort::Bitrate => "s.bitrate DESC,s.name,s.uuid",
742                crate::model::Sort::Votes => "json_extract(s.json,'$.votes') DESC,s.name,s.uuid",
743                crate::model::Sort::Clickcount => "s.popularity DESC,s.name,s.uuid",
744                crate::model::Sort::Random => "random()",
745            }
746        }
747    }
748
749    /// Locate a station without loading every preceding page into memory.
750    pub fn station_position(&self, uuid: &str, filter: &Filter) -> Result<Option<usize>> {
751        use crate::model::Sort;
752        let (conditions, mut args, source) = self.conditions(filter);
753        if !filter.history && matches!(filter.sort, Sort::Clickcount | Sort::Bitrate | Sort::Name) {
754            let tx = self.conn.unchecked_transaction()?;
755            let mut target_args = args.clone();
756            target_args.push(uuid.to_owned().into());
757            let target = tx
758                .query_row(
759                    &format!(
760                        "SELECT s.popularity,s.bitrate,s.name FROM {source}
761                    WHERE {conditions} AND s.uuid=?"
762                    ),
763                    params_from_iter(target_args),
764                    |r| {
765                        Ok((
766                            r.get::<_, i64>(0)?,
767                            r.get::<_, i64>(1)?,
768                            r.get::<_, String>(2)?,
769                        ))
770                    },
771                )
772                .optional()?;
773            let Some((popularity, bitrate, name)) = target else {
774                return Ok(None);
775            };
776            let count = |predicate: &str, values: Vec<Value>| -> Result<usize> {
777                let mut values_with_filter = args.clone();
778                values_with_filter.extend(values);
779                Ok(tx
780                    .prepare_cached(&format!(
781                        "SELECT count(*) FROM {source}
782                    WHERE {conditions} AND ({predicate})"
783                    ))?
784                    .query_row(params_from_iter(values_with_filter), |r| r.get(0))?)
785            };
786            // Separate ranges let each count use the leading sort key. DESC
787            // on the numeric key and ASC on ties cannot use one tuple '<'.
788            let position = if filter.sort == Sort::Name {
789                count("s.name COLLATE NOCASE < ?", vec![name.clone().into()])?
790                    + count(
791                        "s.name COLLATE NOCASE = ? AND s.uuid < ?",
792                        vec![name.into(), uuid.to_owned().into()],
793                    )?
794            } else {
795                let (column, value) = if filter.sort == Sort::Bitrate {
796                    ("bitrate", bitrate)
797                } else {
798                    ("popularity", popularity)
799                };
800                count(&format!("s.{column}>?"), vec![value.into()])?
801                    + count(
802                        &format!("s.{column}=? AND (s.name,s.uuid)<(?,?)"),
803                        vec![value.into(), name.into(), uuid.to_owned().into()],
804                    )?
805            };
806            tx.commit()?;
807            return Ok(Some(position));
808        }
809        let order = Self::search_order(filter);
810        let sql = format!(
811            "WITH ranked AS (
812            SELECT s.uuid,row_number() OVER (ORDER BY {order})-1 AS position
813            FROM {source} WHERE {conditions}
814        ) SELECT position FROM ranked WHERE uuid=?"
815        );
816        args.push(uuid.to_owned().into());
817        Ok(self
818            .conn
819            .query_row(&sql, params_from_iter(args), |row| row.get::<_, i64>(0))
820            .optional()?
821            .map(|position| position as usize))
822    }
823
824    pub fn search(&self, filter: &Filter) -> Result<Vec<Station>> {
825        // The bounded geographic probe and its page must see the same rows,
826        // including when called directly outside the TUI reader's snapshot.
827        let _snapshot = if filter.geo.is_some() && self.conn.is_autocommit() {
828            Some(self.conn.unchecked_transaction()?)
829        } else {
830            None
831        };
832        let (mut conditions, mut args, mut source) = self.conditions(filter);
833        // Probe matching row IDs, not just geographic density: a city may have
834        // thousands of stations but only a few matching the user's filters.
835        // Small result sets reuse the probe; dense sets use a sort index and a
836        // compact spatial membership set to avoid sorting random table reads.
837        if let Some(crate::geo::GeoFilter::Cell(bounds)) = filter.geo
838            && !filter.history
839            && let Some(index) = match filter.sort {
840                crate::model::Sort::Clickcount => Some("stations s INDEXED BY station_sort"),
841                crate::model::Sort::Name => Some("stations s INDEXED BY station_name"),
842                crate::model::Sort::Bitrate => Some("stations s INDEXED BY station_bitrate"),
843                _ => None,
844            }
845        {
846            let probe = format!(
847                "SELECT s.rowid FROM {source} WHERE {conditions} LIMIT {}",
848                geo::SORT_THRESHOLD + 1
849            );
850            // Unfiltered probes are covering index scans: count inside SQLite
851            // instead of copying thousands of IDs we will immediately discard.
852            let ids = if geo::plain(filter) {
853                None
854            } else {
855                Some(
856                    self.conn
857                        .prepare_cached(&probe)?
858                        .query_map(params_from_iter(&args), |r| r.get::<_, i64>(0))?
859                        .collect::<rusqlite::Result<Vec<_>>>()?,
860                )
861            };
862            let n = if let Some(ids) = &ids {
863                ids.len()
864            } else {
865                self.conn
866                    .prepare_cached(&format!("SELECT count(*) FROM ({probe})"))?
867                    .query_row(params_from_iter(&args), |r| r.get::<_, usize>(0))?
868            };
869            if n == 0 {
870                return Ok(vec![]);
871            }
872            if n <= geo::SORT_THRESHOLD
873                && let Some(ids) = ids
874            {
875                conditions = format!("s.rowid IN ({})", vec!["?"; ids.len()].join(","));
876                args = ids.into_iter().map(Value::Integer).collect();
877                source = "stations s";
878            } else if n > geo::SORT_THRESHOLD {
879                let mut spatial_args = vec![];
880                let spatial = geo::predicate(bounds, &mut spatial_args);
881                let candidates = format!(
882                    "SELECT s.rowid FROM stations s INDEXED BY station_geo WHERE s.active=1 AND {spatial}"
883                );
884                // Membership already checks coordinates. Keep the remaining
885                // predicates so the sort scan fetches table rows only when a
886                // non-covering filter actually needs them.
887                (conditions, args, _) = self.conditions_with_spatial(filter, false);
888                conditions = format!("s.rowid IN ({candidates}) AND {conditions}");
889                spatial_args.extend(args);
890                args = spatial_args;
891                source = index;
892            }
893        }
894        let order = Self::search_order(filter);
895        // The random page has already been shuffled. Other sorts still need
896        // their outer order, including history which overrides filter.sort.
897        let page_order = if filter.history {
898            " ORDER BY page.last_id DESC".to_owned()
899        } else if filter.sort == crate::model::Sort::Random {
900            String::new()
901        } else {
902            format!(" ORDER BY {order}")
903        };
904        let history_column = if filter.history {
905            ",recent.last_id"
906        } else {
907            ""
908        };
909        // Sort compact row references, fetching JSON only for the selected page.
910        let sql = format!(
911            "WITH page AS MATERIALIZED (
912            SELECT s.rowid AS id{history_column} FROM {source}
913            WHERE {conditions} ORDER BY {order} LIMIT ? OFFSET ?)
914            SELECT s.json,s.active,EXISTS(SELECT 1 FROM favorites f WHERE f.uuid=s.uuid)
915            FROM page JOIN stations s ON s.rowid=page.id{page_order}"
916        );
917        args.push((filter.limit.clamp(1, 1000) as i64).into());
918        args.push((filter.offset.min(i64::MAX as usize) as i64).into());
919        let mut stmt = self.conn.prepare_cached(&sql)?;
920        let rows = stmt.query_map(params_from_iter(args), |r| {
921            Ok((
922                r.get::<_, String>(0)?,
923                r.get::<_, bool>(1)?,
924                r.get::<_, bool>(2)?,
925            ))
926        })?;
927        rows.map(|row| {
928            let (json, active, favorite) = row?;
929            let mut s: Station = serde_json::from_str(&json)?;
930            s.active = active;
931            s.favorite = favorite;
932            Ok(s)
933        })
934        .collect()
935    }
936
937    pub fn random(&self, filter: &Filter, exclude: &[String]) -> Result<Option<Station>> {
938        let (mut conditions, mut args, source) = self.conditions(filter);
939        if !exclude.is_empty() {
940            let placeholders = vec!["?"; exclude.len()].join(",");
941            conditions.push_str(&format!(" AND s.uuid NOT IN ({placeholders})"));
942            args.extend(exclude.iter().cloned().map(Value::Text));
943        }
944        let sql = format!(
945            "SELECT s.uuid FROM {source}
946            WHERE {conditions} ORDER BY random() LIMIT 1"
947        );
948        let selected = self
949            .conn
950            .query_row(&sql, params_from_iter(args), |r| r.get::<_, String>(0))
951            .optional()?;
952        selected.map(|id| self.station(&id)).transpose()
953    }
954
955    pub fn facets(
956        &self,
957        kind: crate::model::FacetKind,
958        prefix: &str,
959    ) -> Result<Vec<crate::model::Facet>> {
960        self.facets_limited(kind, prefix, usize::MAX)
961    }
962
963    pub fn facets_limited(
964        &self,
965        kind: crate::model::FacetKind,
966        prefix: &str,
967        limit: usize,
968    ) -> Result<Vec<crate::model::Facet>> {
969        use crate::model::{Facet, FacetKind};
970        let (kind, prefix) = match kind {
971            FacetKind::Country => (0, prefix.trim().to_uppercase()),
972            FacetKind::Language => (1, prefix.trim().to_lowercase()),
973            FacetKind::Tag => (2, prefix.trim().to_lowercase()),
974        };
975        let codes = if kind == 0 {
976            crate::territories::matching_prefix_codes(&prefix).collect::<Vec<_>>()
977        } else {
978            Vec::new()
979        };
980        // Match localized names before LIMIT, so countries beyond the first
981        // candidate page remain reachable. Values and counts stay catalog data.
982        let localized = if codes.is_empty() {
983            String::new()
984        } else {
985            let placeholders = (4..4 + codes.len())
986                .map(|index| format!("?{index}"))
987                .collect::<Vec<_>>()
988                .join(",");
989            format!(" OR value IN ({placeholders})")
990        };
991        let mut args: Vec<Value> = vec![
992            kind.into(),
993            prefix.into(),
994            (limit.min(i64::MAX as usize) as i64).into(),
995        ];
996        args.extend(codes.into_iter().map(|code| Value::from(code.to_owned())));
997        let mut stmt = self.conn.prepare_cached(&format!(
998            "SELECT value,n FROM facets_cache WHERE kind=?1
999             AND (substr(value,1,length(?2))=?2{localized}) ORDER BY value LIMIT ?3",
1000        ))?;
1001        let rows = stmt.query_map(params_from_iter(args), |r| {
1002            Ok(Facet {
1003                value: r.get(0)?,
1004                count: r.get(1)?,
1005            })
1006        })?;
1007        Ok(rows.collect::<rusqlite::Result<_>>()?)
1008    }
1009
1010    pub fn favorite(&self, uuid: &str, add: bool) -> Result<()> {
1011        self.station(uuid)?;
1012        if add {
1013            self.conn.execute(
1014                "INSERT OR IGNORE INTO favorites(uuid,created_at) VALUES (?1,?2)",
1015                params![uuid, crate::timestamp::now()],
1016            )?;
1017        } else {
1018            self.conn
1019                .execute("DELETE FROM favorites WHERE uuid=?1", [uuid])?;
1020        }
1021        Ok(())
1022    }
1023
1024    pub fn toggle_favorite(&mut self, uuid: &str) -> Result<bool> {
1025        let tx = self
1026            .conn
1027            .transaction_with_behavior(TransactionBehavior::Immediate)?;
1028        tx.query_row("SELECT 1 FROM stations WHERE uuid=?1", [uuid], |r| {
1029            r.get::<_, u8>(0)
1030        })
1031        .optional()?
1032        .context(DomainError::new(ErrorCode::StationNotFound))?;
1033        let removed = tx.execute("DELETE FROM favorites WHERE uuid=?1", [uuid])?;
1034        let added = removed == 0;
1035        if added {
1036            tx.execute(
1037                "INSERT INTO favorites(uuid,created_at) VALUES (?1,?2)",
1038                params![uuid, crate::timestamp::now()],
1039            )?;
1040        }
1041        tx.commit()?;
1042        Ok(added)
1043    }
1044
1045    pub fn played(&self, uuid: &str) -> Result<()> {
1046        self.conn.execute(
1047            "INSERT INTO history(uuid,played_at) VALUES (?1,?2)",
1048            params![uuid, crate::timestamp::now()],
1049        )?;
1050        let threshold = self.conn.last_insert_rowid().saturating_sub(1000);
1051        self.conn
1052            .execute("DELETE FROM history WHERE id <= ?1", [threshold])?;
1053        Ok(())
1054    }
1055
1056    pub fn add_backup(&self, uuid: &str, url: &str) -> Result<()> {
1057        crate::config::validate_url(url)?;
1058        self.conn.execute(
1059            "INSERT OR IGNORE INTO streams(uuid,url) VALUES (?1,?2)",
1060            params![uuid, url],
1061        )?;
1062        Ok(())
1063    }
1064
1065    pub fn save_custom(&mut self, station: &Station, backups: Option<&[String]>) -> Result<()> {
1066        let tx = self
1067            .conn
1068            .transaction_with_behavior(TransactionBehavior::Immediate)?;
1069        Self::write_custom(&tx, station, backups)?;
1070        tx.commit()?;
1071        Ok(())
1072    }
1073
1074    pub(crate) fn edit_custom(
1075        &self,
1076        uuid: &str,
1077        backups: Option<&[String]>,
1078        edit: impl FnOnce(&mut Station) -> Result<()>,
1079    ) -> Result<Station> {
1080        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
1081        let mut station = self.station(uuid)?;
1082        if !station.custom {
1083            bail!(DomainError::new(ErrorCode::NotCustom));
1084        }
1085        edit(&mut station)?;
1086        Self::write_custom(&tx, &station, backups)?;
1087        let updated = self.station(uuid)?;
1088        tx.commit()?;
1089        Ok(updated)
1090    }
1091
1092    fn write_custom(
1093        tx: &rusqlite::Transaction<'_>,
1094        station: &Station,
1095        backups: Option<&[String]>,
1096    ) -> Result<()> {
1097        let key = crate::service::normalized_url(station.primary_url())?;
1098        if let Some(uuid) = tx.query_row(
1099            "SELECT uuid FROM stations WHERE active=1 AND normalized_url=?1 AND uuid<>?2 LIMIT 1",
1100            params![key, station.stationuuid], |r| r.get::<_, String>(0),
1101        ).optional()? {
1102            bail!(DomainError::new(ErrorCode::DuplicateStation).with("uuid", uuid));
1103        }
1104        Self::write_station_with_policy(tx, "stations", station, true, true)?;
1105        if let Some(backups) = backups {
1106            tx.execute("DELETE FROM streams WHERE uuid=?1", [&station.stationuuid])?;
1107            for url in backups {
1108                crate::config::validate_url(url)?;
1109                tx.execute(
1110                    "INSERT OR IGNORE INTO streams(uuid,url) VALUES (?1,?2)",
1111                    params![station.stationuuid, url],
1112                )?;
1113            }
1114        }
1115        geo::changed(tx)
1116    }
1117
1118    pub fn remove_custom(&mut self, uuid: &str, keep_references: bool) -> Result<bool> {
1119        let tx = self
1120            .conn
1121            .transaction_with_behavior(TransactionBehavior::Immediate)?;
1122        let json: String = tx
1123            .query_row(
1124                "SELECT json FROM stations WHERE uuid=?1 AND custom=1",
1125                [uuid],
1126                |r| r.get(0),
1127            )
1128            .optional()?
1129            .context(DomainError::new(ErrorCode::NotCustom))?;
1130        let mut station: Station = serde_json::from_str(&json)?;
1131        let referenced: bool = tx.query_row("SELECT EXISTS(SELECT 1 FROM favorites WHERE uuid=?1) OR EXISTS(SELECT 1 FROM history WHERE uuid=?1) OR EXISTS(SELECT 1 FROM recordings WHERE json_extract(json,'$.stationuuid')=?1)", [uuid], |r| r.get(0))?;
1132        tx.execute("DELETE FROM streams WHERE uuid=?1", [uuid])?;
1133        if referenced || keep_references {
1134            station.custom = false;
1135            station.active = false;
1136            station.url.clear();
1137            station.url_resolved.clear();
1138            Self::write_station_with_policy(&tx, "stations", &station, true, true)?;
1139        } else {
1140            let before = facets::station_values(&tx, uuid)?;
1141            tx.execute("DELETE FROM stations WHERE uuid=?1", [uuid])?;
1142            facets::update(&tx, &before, &Default::default())?;
1143        }
1144        geo::changed(&tx)?;
1145        tx.commit()?;
1146        Ok(referenced || keep_references)
1147    }
1148
1149    pub fn update_backups(
1150        &mut self,
1151        uuid: &str,
1152        add: &[String],
1153        remove: &[String],
1154    ) -> Result<Vec<String>> {
1155        self.station(uuid)?;
1156        let tx = self.conn.transaction()?;
1157        for url in remove {
1158            tx.execute(
1159                "DELETE FROM streams WHERE uuid=?1 AND url=?2",
1160                params![uuid, url],
1161            )?;
1162        }
1163        for url in add {
1164            crate::config::validate_url(url)?;
1165            tx.execute(
1166                "INSERT OR IGNORE INTO streams(uuid,url) VALUES (?1,?2)",
1167                params![uuid, url],
1168            )?;
1169        }
1170        tx.commit()?;
1171        self.backups(uuid)
1172    }
1173
1174    pub fn backups(&self, uuid: &str) -> Result<Vec<String>> {
1175        let mut stmt = self
1176            .conn
1177            .prepare("SELECT url FROM streams WHERE uuid=?1 ORDER BY rowid")?;
1178        Ok(stmt
1179            .query_map([uuid], |r| r.get(0))?
1180            .collect::<rusqlite::Result<_>>()?)
1181    }
1182
1183    pub fn save_recording(&self, recording: &Recording) -> Result<()> {
1184        self.conn.execute(
1185            "INSERT INTO recordings (id,status,json,recovery_pending) VALUES (?1,?2,?3,?4) ON CONFLICT(id) DO UPDATE SET status=excluded.status,json=excluded.json,recovery_pending=excluded.recovery_pending",
1186            params![
1187                recording.id,
1188                recording.status,
1189                serde_json::to_string(recording)?,
1190                recording.recovery_pending
1191            ],
1192        )?;
1193        Ok(())
1194    }
1195
1196    pub fn search_count(&self, filter: &Filter) -> Result<usize> {
1197        let (conditions, args, source) = self.conditions(filter);
1198        Ok(self
1199            .conn
1200            .prepare_cached(&format!("SELECT count(*) FROM {source} WHERE {conditions}"))?
1201            .query_row(params_from_iter(args), |r| r.get(0))?)
1202    }
1203
1204    pub fn recordings(&self, limit: usize) -> Result<Vec<Recording>> {
1205        self.recordings_page(limit, 0)
1206    }
1207
1208    pub fn recordings_count(&self) -> Result<usize> {
1209        Ok(self
1210            .conn
1211            .query_row("SELECT count(*) FROM recordings", [], |r| r.get(0))?)
1212    }
1213
1214    pub fn recording(&self, id: &str) -> Result<Recording> {
1215        let row = self
1216            .conn
1217            .query_row(
1218                "SELECT json,recovery_pending FROM recordings WHERE id=?1",
1219                [id],
1220                |r| Ok((r.get(0)?, r.get(1)?)),
1221            )
1222            .optional()?
1223            .context(DomainError::new(ErrorCode::RecordingNotFound))?;
1224        Self::read_recording(row)
1225    }
1226
1227    pub fn remove_recording_index(&self, id: &str) -> Result<()> {
1228        self.conn
1229            .execute("DELETE FROM recordings WHERE id=?1", [id])?;
1230        Ok(())
1231    }
1232
1233    pub fn recordings_page(&self, limit: usize, offset: usize) -> Result<Vec<Recording>> {
1234        let mut stmt = self.conn.prepare_cached(&format!("SELECT json,recovery_pending FROM recordings ORDER BY {RECORDING_ORDER} LIMIT ?1 OFFSET ?2"))?;
1235        let rows = stmt.query_map(
1236            params![
1237                limit.clamp(1, 1000) as i64,
1238                offset.min(i64::MAX as usize) as i64
1239            ],
1240            |r| Ok((r.get::<_, String>(0)?, r.get::<_, bool>(1)?)),
1241        )?;
1242        rows.map(|row| Self::read_recording(row?)).collect()
1243    }
1244
1245    fn read_recording((json, recovery_pending): (String, bool)) -> Result<Recording> {
1246        let mut record: Recording = serde_json::from_str(&json)?;
1247        record.recovery_pending = recovery_pending;
1248        Ok(record)
1249    }
1250
1251    pub fn unfinished_recordings(&self) -> Result<Vec<Recording>> {
1252        let mut stmt = self
1253            .conn
1254            .prepare("SELECT json,recovery_pending FROM recordings WHERE status IN ('recording','finalizing') OR recovery_pending=1")?;
1255        let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, bool>(1)?)))?;
1256        rows.map(|row| Self::read_recording(row?)).collect()
1257    }
1258}
1259
1260#[cfg(test)]
1261mod tests {
1262    use super::*;
1263
1264    #[test]
1265    fn rollback_diagnostics_preserve_a_newer_sync_report() -> Result<()> {
1266        let dir = tempfile::tempdir()?;
1267        let db = dir.path().join("radio.db");
1268        let store = Store::open(&db)?;
1269        store.record_rolled_back_sync(None, "first failure")?;
1270        let previous = store.meta("last_sync_attempt")?;
1271        assert_eq!(previous.as_deref(), Some("first failure"));
1272        let other = Store::open(&db)?;
1273        other.set_meta("last_sync_attempt", "newer attempt")?;
1274        store.record_rolled_back_sync(previous.as_deref(), "late failure")?;
1275        assert_eq!(
1276            store.meta("last_sync_attempt")?.as_deref(),
1277            Some("newer attempt")
1278        );
1279        Ok(())
1280    }
1281
1282    #[test]
1283    fn recording_order_index_migrates_without_losing_old_or_malformed_entries() {
1284        let dir = tempfile::tempdir().unwrap();
1285        let path = dir.path().join("radio.db");
1286        let store = Store::open(&path).unwrap();
1287        for (id, at) in [
1288            ("a", "2026-01-02"),
1289            ("b", "2026-01-02"),
1290            ("old", "2026-01-01"),
1291        ] {
1292            store
1293                .save_recording(&Recording {
1294                    id: id.into(),
1295                    stationuuid: "station".into(),
1296                    station_name: "Station".into(),
1297                    track: None,
1298                    source_url_resolved: "http://localhost/live".into(),
1299                    started_at: at.into(),
1300                    stopped_at: None,
1301                    media_duration_ms: Some(1000),
1302                    codec: "mp3".into(),
1303                    container: "mp3".into(),
1304                    path: id.into(),
1305                    final_path: None,
1306                    size_bytes: 1,
1307                    status: "complete".into(),
1308                    error: None,
1309                    reconnects: 0,
1310                    recovery_pending: false,
1311                })
1312                .unwrap();
1313        }
1314        crate::test_support::strip_podcast_episode_order(&store.conn);
1315        store
1316            .conn
1317            .execute_batch(
1318                "DROP INDEX recording_started; PRAGMA user_version=7;
1319            INSERT INTO recordings(id,status,json) VALUES ('broken','complete','invalid');",
1320            )
1321            .unwrap();
1322        drop(store);
1323        let store = Store::open(&path).unwrap();
1324        assert_eq!(store.recordings_count().unwrap(), 4);
1325        let page = store.recordings_page(2, 0).unwrap();
1326        assert_eq!(
1327            page.iter().map(|r| r.id.as_str()).collect::<Vec<_>>(),
1328            ["b", "a"]
1329        );
1330        assert_eq!(store.recordings_page(1, 2).unwrap()[0].id, "old");
1331        assert!(store.recordings_page(1, 3).is_err());
1332        let plan: Vec<String> = store.conn.prepare(&format!(
1333            "EXPLAIN QUERY PLAN SELECT json,recovery_pending FROM recordings ORDER BY {RECORDING_ORDER} LIMIT 100"
1334        )).unwrap().query_map([], |r| r.get(3)).unwrap().collect::<rusqlite::Result<_>>().unwrap();
1335        assert!(plan.iter().any(|line| line.contains("recording_started")));
1336        assert!(!plan.iter().any(|line| line.contains("TEMP B-TREE")));
1337    }
1338
1339    #[test]
1340    fn territory_queries_union_indexed_country_and_trigram_candidates() {
1341        let dir = tempfile::tempdir().unwrap();
1342        let mut store = Store::open(&dir.path().join("radio.db")).unwrap();
1343        let rows: Vec<_> = (0..100)
1344            .map(|i| Station {
1345                stationuuid: uuid::Uuid::new_v4().to_string(),
1346                name: match i {
1347                    1 => "爱尔兰音乐".into(),
1348                    2 => "爱尔兰广播".into(),
1349                    _ => format!("catalog station {i}"),
1350                },
1351                countrycode: if i == 0 || i == 2 { "IE" } else { "FR" }.into(),
1352                clickcount: i,
1353                active: true,
1354                ..Station::default()
1355            })
1356            .collect();
1357        store.bootstrap(&rows, || false).unwrap();
1358        let filter = Filter {
1359            query: " 爱尔兰 ".into(),
1360            limit: 100,
1361            ..Filter::default()
1362        };
1363        let actual: Vec<_> = store
1364            .search(&filter)
1365            .unwrap()
1366            .into_iter()
1367            .map(|row| row.stationuuid)
1368            .collect();
1369        assert_eq!(actual, [2, 1, 0].map(|i| rows[i].stationuuid.clone()));
1370        assert_eq!(store.search_count(&filter).unwrap(), 3);
1371        let (conditions, args, source) = store.conditions(&filter);
1372        let plan: Vec<String> = store
1373            .conn
1374            .prepare(&format!(
1375                "EXPLAIN QUERY PLAN SELECT s.rowid FROM {source} WHERE {conditions}"
1376            ))
1377            .unwrap()
1378            .query_map(params_from_iter(args), |r| r.get(3))
1379            .unwrap()
1380            .collect::<rusqlite::Result<_>>()
1381            .unwrap();
1382        for index in [
1383            "SEARCH s USING INTEGER PRIMARY KEY (rowid=?)",
1384            "station_search VIRTUAL TABLE INDEX",
1385            "station_country (country=?)",
1386        ] {
1387            assert!(plan.iter().any(|step| step.contains(index)), "{plan:?}");
1388        }
1389    }
1390
1391    #[test]
1392    fn search_statistics_collection_allows_a_concurrent_writer() {
1393        use std::sync::{
1394            Arc,
1395            atomic::{AtomicBool, Ordering},
1396        };
1397
1398        let dir = tempfile::tempdir().unwrap();
1399        let path = dir.path().join("radio.db");
1400        let mut store = Store::open(&path).unwrap();
1401        let rows: Vec<_> = (0..256)
1402            .map(|i| Station {
1403                stationuuid: uuid::Uuid::new_v4().to_string(),
1404                name: format!("station {i:05} jazz"),
1405                active: true,
1406                ..Station::default()
1407            })
1408            .collect();
1409        store.bootstrap(&rows, || false).unwrap();
1410        let writer = Connection::open(&path).unwrap();
1411        writer.busy_timeout(std::time::Duration::ZERO).unwrap();
1412        let attempted = Arc::new(AtomicBool::new(false));
1413        let succeeded = Arc::new(AtomicBool::new(false));
1414        let (attempt, success) = (attempted.clone(), succeeded.clone());
1415        store
1416            .conn
1417            .progress_handler(
1418                1000,
1419                Some(move || {
1420                    if !attempt.swap(true, Ordering::SeqCst) {
1421                        success.store(
1422                            writer
1423                                .execute("INSERT INTO meta VALUES ('concurrent','write')", [])
1424                                .is_ok(),
1425                            Ordering::SeqCst,
1426                        );
1427                    }
1428                    false
1429                }),
1430            )
1431            .unwrap();
1432        store.refresh_search_stats().unwrap();
1433        store
1434            .conn
1435            .progress_handler(0, None::<fn() -> bool>)
1436            .unwrap();
1437        assert!(attempted.load(Ordering::SeqCst));
1438        assert!(succeeded.load(Ordering::SeqCst));
1439        let actual: usize = store
1440            .conn
1441            .query_row(
1442                "SELECT n FROM station_search_stats WHERE term=''",
1443                [],
1444                |r| r.get(0),
1445            )
1446            .unwrap();
1447        assert_eq!(actual, rows.len());
1448        let differences: usize = store
1449            .conn
1450            .query_row(
1451                "SELECT count(*) FROM (
1452                    SELECT term,doc FROM station_search_terms
1453                    EXCEPT SELECT term,n FROM station_search_stats WHERE term<>'')",
1454                [],
1455                |r| r.get(0),
1456            )
1457            .unwrap();
1458        assert_eq!(differences, 0);
1459    }
1460
1461    #[test]
1462    fn failed_statistics_refresh_preserves_hints_and_successful_publication() {
1463        for sync in [false, true] {
1464            let dir = tempfile::tempdir().unwrap();
1465            let mut store = Store::open(&dir.path().join("radio.db")).unwrap();
1466            let row = |name: &str| Station {
1467                stationuuid: uuid::Uuid::new_v4().to_string(),
1468                name: name.into(),
1469                tags: name.into(),
1470                active: true,
1471                ..Station::default()
1472            };
1473            store.bootstrap(&[row("originalneedle")], || false).unwrap();
1474            let stats = || {
1475                store
1476                    .conn
1477                    .prepare("SELECT term,n FROM station_search_stats ORDER BY term")
1478                    .unwrap()
1479                    .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))
1480                    .unwrap()
1481                    .collect::<rusqlite::Result<Vec<_>>>()
1482                    .unwrap()
1483            };
1484            let before = stats();
1485            store
1486                .conn
1487                .execute_batch(
1488                    "CREATE TRIGGER reject_stats BEFORE INSERT ON station_search_stats
1489                BEGIN SELECT RAISE(ABORT,'statistics unavailable'); END;",
1490                )
1491                .unwrap();
1492            let replacement = row("replacementneedle");
1493            if sync {
1494                store.begin_sync().unwrap();
1495                store.stage(&[replacement]).unwrap();
1496                assert_eq!(store.finish_sync().unwrap(), 1);
1497                assert!(store.meta("last_sync").unwrap().is_some());
1498            } else {
1499                assert_eq!(store.bootstrap(&[replacement], || false).unwrap(), 1);
1500            }
1501            assert_eq!(
1502                store
1503                    .search_count(&Filter {
1504                        query: "replacementneedle".into(),
1505                        ..Filter::default()
1506                    })
1507                    .unwrap(),
1508                1
1509            );
1510            assert_eq!(
1511                store
1512                    .facets(crate::model::FacetKind::Tag, "replacement")
1513                    .unwrap()[0]
1514                    .count,
1515                1
1516            );
1517            let after: Vec<_> = store
1518                .conn
1519                .prepare("SELECT term,n FROM station_search_stats ORDER BY term")
1520                .unwrap()
1521                .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))
1522                .unwrap()
1523                .collect::<rusqlite::Result<_>>()
1524                .unwrap();
1525            assert_eq!(after, before);
1526        }
1527    }
1528
1529    #[test]
1530    fn connection_revision_distinguishes_local_and_external_activity() -> Result<()> {
1531        let dir = tempfile::tempdir()?;
1532        let path = dir.path().join("radio.db");
1533        let one = Store::open(&path)?;
1534        let two = Store::open(&path)?;
1535        let before = one.revision()?;
1536        one.set_meta("diagnostic", "first")?;
1537        let local = one.revision()?;
1538        assert_eq!(before.0, local.0);
1539        assert!(local.1 > before.1);
1540        two.set_meta("diagnostic", "second")?;
1541        let external = one.revision()?;
1542        assert_ne!(external.0, local.0);
1543        assert_eq!(external.1, local.1);
1544        Ok(())
1545    }
1546
1547    #[test]
1548    fn read_snapshot_pins_revision_before_a_concurrent_commit() {
1549        let dir = tempfile::tempdir().unwrap();
1550        let path = dir.path().join("radio.db");
1551        let writer = Store::open(&path).unwrap();
1552        let reader = Store::open_reader(&path).unwrap();
1553        let revision = reader
1554            .read_snapshot(|store| {
1555                let revision = store.list_revision(&Filter::default())?;
1556                writer.upsert(&Station {
1557                    stationuuid: uuid::Uuid::new_v4().to_string(),
1558                    name: "new row".into(),
1559                    active: true,
1560                    ..Station::default()
1561                })?;
1562                assert_eq!(store.list_revision(&Filter::default())?, revision);
1563                assert_eq!(store.count()?, 0);
1564                Ok(revision)
1565            })
1566            .unwrap();
1567        assert_ne!(reader.list_revision(&Filter::default()).unwrap(), revision);
1568        assert_eq!(reader.count().unwrap(), 1);
1569    }
1570
1571    #[test]
1572    fn cancellation_before_sync_commit_rolls_back_all_derived_data() {
1573        let dir = tempfile::tempdir().unwrap();
1574        let mut store = Store::open(&dir.path().join("radio.db")).unwrap();
1575        let row = |name: &str, tag: &str| Station {
1576            stationuuid: uuid::Uuid::new_v4().to_string(),
1577            name: name.into(),
1578            tags: tag.into(),
1579            active: true,
1580            ..Station::default()
1581        };
1582        store.upsert(&row("originalneedle", "originaltag")).unwrap();
1583        store.begin_sync().unwrap();
1584        store
1585            .stage(&[row("replacementneedle", "replacementtag")])
1586            .unwrap();
1587        assert!(
1588            store
1589                .finish_sync_cancellable(|| true, |_, _| Ok(None))
1590                .is_err()
1591        );
1592        assert_eq!(store.count().unwrap(), 1);
1593        for (query, expected) in [("originalneedle", 1), ("replacementneedle", 0)] {
1594            assert_eq!(
1595                store
1596                    .search_count(&Filter {
1597                        query: query.into(),
1598                        ..Filter::default()
1599                    })
1600                    .unwrap(),
1601                expected
1602            );
1603        }
1604        assert_eq!(
1605            store.facets(crate::model::FacetKind::Tag, "").unwrap()[0].value,
1606            "originaltag"
1607        );
1608        assert!(store.meta("last_sync").unwrap().is_none());
1609    }
1610
1611    #[test]
1612    fn sync_writes_only_changed_stations_and_facet_memberships() {
1613        let dir = tempfile::tempdir().unwrap();
1614        let mut store = Store::open(&dir.path().join("radio.db")).unwrap();
1615        let row = |name: &str| Station {
1616            stationuuid: uuid::Uuid::new_v4().to_string(),
1617            name: name.into(),
1618            tags: "jazz,jazz".into(),
1619            language: "english,en".into(),
1620            countrycode: "US".into(),
1621            active: true,
1622            ..Station::default()
1623        };
1624        let unchanged = row("unchanged");
1625        let mut changed = row("changed");
1626        let removed = row("removed");
1627        let mut revived = row("revived");
1628        revived.active = false;
1629        let mut custom = row("custom");
1630        custom.custom = true;
1631        for station in [&unchanged, &changed, &removed, &revived, &custom] {
1632            store.upsert(station).unwrap();
1633        }
1634        store
1635            .conn
1636            .execute_batch(
1637                "CREATE TABLE station_writes(uuid TEXT);
1638             CREATE TRIGGER audit_station_writes AFTER UPDATE ON stations
1639             BEGIN INSERT INTO station_writes VALUES(new.uuid); END;",
1640            )
1641            .unwrap();
1642        changed.tags = "rock,rock".into();
1643        changed.countrycode = "FR".into();
1644        revived.active = true;
1645        let mut collision = custom.clone();
1646        collision.custom = false;
1647        collision.tags = "wrong".into();
1648        let incoming = [unchanged.clone(), changed, revived, collision, row("new")];
1649        store.begin_sync().unwrap();
1650        store.stage(&incoming).unwrap();
1651        store.finish_sync().unwrap();
1652        let writes: Vec<String> = store
1653            .conn
1654            .prepare("SELECT uuid FROM station_writes")
1655            .unwrap()
1656            .query_map([], |r| r.get(0))
1657            .unwrap()
1658            .collect::<rusqlite::Result<_>>()
1659            .unwrap();
1660        assert_eq!(writes.len(), 3);
1661        assert!(!writes.contains(&unchanged.stationuuid));
1662        assert!(!writes.contains(&custom.stationuuid));
1663        assert!(!store.station(&removed.stationuuid).unwrap().active);
1664        assert_eq!(
1665            store.station(&custom.stationuuid).unwrap().tags,
1666            "jazz,jazz"
1667        );
1668        let facets = || {
1669            store
1670                .conn
1671                .prepare("SELECT kind,value,n FROM facets_cache ORDER BY kind,value")
1672                .unwrap()
1673                .query_map([], |r| {
1674                    Ok((
1675                        r.get::<_, u8>(0)?,
1676                        r.get::<_, String>(1)?,
1677                        r.get::<_, i64>(2)?,
1678                    ))
1679                })
1680                .unwrap()
1681                .collect::<rusqlite::Result<Vec<_>>>()
1682                .unwrap()
1683        };
1684        let delta_counts = facets();
1685        facets::rebuild(&store.conn).unwrap();
1686        assert_eq!(facets(), delta_counts);
1687        let geo_revision = store.geo_revision().unwrap();
1688        store.begin_sync().unwrap();
1689        store.stage(&incoming).unwrap();
1690        let before = store.conn.total_changes();
1691        store.finish_sync().unwrap();
1692        // Only last_sync changes: stations, indexes, facets, geographic and
1693        // search statistics remain untouched for an identical snapshot.
1694        assert_eq!(store.conn.total_changes() - before, 1);
1695        assert_eq!(store.geo_revision().unwrap(), geo_revision);
1696    }
1697}