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