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 VOTES_EXPR: &str = "CASE WHEN json_valid(json) THEN json_extract(json,'$.votes') END";
17const VOTES_EXPR_S: &str = "CASE WHEN json_valid(s.json) THEN json_extract(s.json,'$.votes') END";
18const SCHEMA_VERSION: u32 = 11;
19
20fn ensure_perf_indexes(conn: &Connection) -> Result<()> {
21 conn.execute_batch(&format!(
22 "CREATE INDEX IF NOT EXISTS station_votes ON stations({VOTES_EXPR} DESC,name,uuid,active,custom,bitrate);
23 CREATE INDEX IF NOT EXISTS station_custom ON stations(custom) WHERE custom=1;
24 CREATE INDEX IF NOT EXISTS station_country_sort ON stations(country,popularity DESC,name,uuid,active,custom,bitrate);
25 CREATE INDEX IF NOT EXISTS recording_unfinished ON recordings(id) WHERE status IN ('recording','finalizing') OR recovery_pending=1;
26 CREATE INDEX IF NOT EXISTS podcast_continue ON podcast_progress(episode_id) WHERE completed=0 AND position_ms>0;"
27 ))?;
28 Ok(())
29}
30
31pub(crate) fn next_utf8_prefix(prefix: &str) -> Option<String> {
33 let mut chars: Vec<char> = prefix.chars().collect();
34 while let Some(c) = chars.pop() {
35 let mut code = u32::from(c);
36 while code < u32::from(char::MAX) {
37 code += 1;
38 if let Some(next) = char::from_u32(code) {
39 chars.push(next);
40 return Some(chars.into_iter().collect());
41 }
42 }
43 }
44 None
45}
46
47fn normalize_csv_tokens(dst: &mut String, parts: &[&str]) {
48 dst.clear();
49 dst.push(',');
50 let mut any = false;
51 for part in parts {
52 for token in part.split(',') {
53 let trimmed = token.trim();
54 if trimmed.is_empty() {
55 continue;
56 }
57 if any {
58 dst.push(',');
59 }
60 for c in trimmed.chars() {
61 for lc in c.to_lowercase() {
62 dst.push(lc);
63 }
64 }
65 any = true;
66 }
67 }
68 dst.push(',');
69}
70
71pub(crate) enum Played {
72 Station(String),
73 Episode(String),
74}
75
76pub struct Store {
77 pub(crate) conn: Connection,
78}
79
80impl Store {
81 pub(crate) fn is_busy(error: &anyhow::Error) -> bool {
82 error.downcast_ref::<rusqlite::Error>().is_some_and(|e| {
83 matches!(
84 e,
85 rusqlite::Error::SqliteFailure(code, _)
86 if matches!(
87 code.code,
88 rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked
89 )
90 )
91 })
92 }
93
94 pub(crate) fn open_writer(path: &Path) -> Result<Self> {
95 let conn = Connection::open(path)?;
98 crate::podcast::register_functions(&conn)?;
99 conn.busy_timeout(std::time::Duration::from_millis(100))?;
100 conn.execute_batch("PRAGMA foreign_keys=ON; PRAGMA synchronous=NORMAL;")?;
101 Ok(Self { conn })
102 }
103
104 #[cfg(test)]
105 pub(crate) fn test_connection(&self) -> &Connection {
106 &self.conn
107 }
108
109 #[cfg(test)]
110 pub(crate) fn test_connection_mut(&mut self) -> &mut Connection {
111 &mut self.conn
112 }
113
114 pub(crate) fn open_reader(path: &Path) -> Result<Self> {
115 let conn = Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
116 crate::podcast::register_functions(&conn)?;
117 conn.busy_timeout(std::time::Duration::from_millis(100))?;
118 conn.execute_batch("PRAGMA cache_size=-4096;")?;
119 Ok(Self { conn })
120 }
121
122 pub(crate) fn interrupt_handle(&self) -> rusqlite::InterruptHandle {
123 self.conn.get_interrupt_handle()
124 }
125
126 pub(crate) fn cancel_queries_when(
127 &mut self,
128 cancel: impl FnMut() -> bool + Send + 'static,
129 ) -> Result<()> {
130 Ok(self.conn.progress_handler(1000, Some(cancel))?)
131 }
132
133 pub(crate) fn read_snapshot<T>(&self, read: impl FnOnce(&Self) -> Result<T>) -> Result<T> {
134 let tx = self.conn.unchecked_transaction()?;
135 tx.query_row("SELECT 1 FROM sqlite_schema LIMIT 1", [], |_| Ok(()))?;
138 let value = read(self)?;
139 tx.commit()?;
140 Ok(value)
141 }
142
143 pub fn open(path: &Path) -> Result<Self> {
144 let mut conn = Connection::open(path)?;
145 crate::podcast::register_functions(&conn)?;
146 conn.busy_timeout(std::time::Duration::from_secs(5))?;
147 conn.execute_batch(
148 "PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL;
149 PRAGMA cache_size=-4096; PRAGMA synchronous=NORMAL;",
150 )?;
151 let version: u32 = conn.pragma_query_value(None, "user_version", |r| r.get(0))?;
152 if version > SCHEMA_VERSION {
153 bail!(DomainError::new(ErrorCode::DatabaseTooNew));
154 }
155 if version < SCHEMA_VERSION {
156 let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
157 let version: u32 = tx.pragma_query_value(None, "user_version", |r| r.get(0))?;
159 match version {
160 0 => tx.execute_batch(
161 "CREATE TABLE stations (
162 uuid TEXT PRIMARY KEY, name TEXT NOT NULL, search TEXT NOT NULL,
163 country TEXT NOT NULL, languages TEXT NOT NULL, tags TEXT NOT NULL,
164 bitrate INTEGER NOT NULL, popularity INTEGER NOT NULL,
165 custom INTEGER NOT NULL, active INTEGER NOT NULL, json TEXT NOT NULL);
166 CREATE INDEX station_country ON stations(country, bitrate);
167 CREATE INDEX station_popularity ON stations(popularity DESC);
168 CREATE TABLE favorites (
169 uuid TEXT PRIMARY KEY REFERENCES stations(uuid), created_at TEXT NOT NULL);
170 CREATE TABLE history (
171 id INTEGER PRIMARY KEY, uuid TEXT NOT NULL REFERENCES stations(uuid), played_at TEXT NOT NULL);
172 CREATE INDEX history_station ON history(uuid);
173 CREATE TABLE streams (
174 uuid TEXT NOT NULL REFERENCES stations(uuid), url TEXT NOT NULL, PRIMARY KEY(uuid,url));
175 CREATE TABLE recordings (
176 id TEXT PRIMARY KEY, status TEXT NOT NULL, json TEXT NOT NULL,
177 recovery_pending INTEGER NOT NULL DEFAULT 0 CHECK(recovery_pending IN (0,1)));
178 CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);"
179 )?,
180 1 => tx.execute_batch(
181 "ALTER TABLE recordings ADD COLUMN recovery_pending INTEGER NOT NULL DEFAULT 0 CHECK(recovery_pending IN (0,1));
182 -- Translate legacy diagnostics once, never during normal queries.
183 UPDATE recordings SET recovery_pending=1 WHERE status='interrupted' AND json_extract(json,'$.error') LIKE '恢复失败:%';"
184 )?,
185 2..=SCHEMA_VERSION => {},
186 _ => bail!(DomainError::new(ErrorCode::DatabaseTooNew)),
187 }
188 if version < 3 {
189 tx.execute_batch(
190 "ALTER TABLE stations ADD COLUMN normalized_url TEXT;
191 CREATE INDEX station_url ON stations(normalized_url) WHERE active=1;",
192 )?;
193 let mut select = tx.prepare("SELECT uuid,json FROM stations")?;
194 let mut update =
195 tx.prepare("UPDATE stations SET normalized_url=?2 WHERE uuid=?1")?;
196 let rows = select
197 .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
198 for row in rows {
199 let (uuid, json) = row?;
200 let station: Station = serde_json::from_str(&json)?;
201 update.execute(params![
202 uuid,
203 crate::config::normalized_url(station.primary_url()).ok()
204 ])?;
205 }
206 }
207 if version < 4 {
208 tx.execute_batch(
209 "CREATE TABLE facets_cache (
210 kind INTEGER NOT NULL,value TEXT NOT NULL,n INTEGER NOT NULL CHECK(n>=0),
211 PRIMARY KEY(kind,value)) WITHOUT ROWID;",
212 )?;
213 facets::rebuild(&tx)?;
214 }
215 if version < 5 {
216 tx.execute_batch(
217 "CREATE INDEX station_sort ON stations(popularity DESC,name,uuid,active,custom,bitrate);
218 CREATE INDEX station_name ON stations(name COLLATE NOCASE,uuid,active,custom,bitrate);
219 CREATE INDEX station_bitrate ON stations(bitrate DESC,name,uuid,active,custom);
220 CREATE INDEX station_active ON stations(active) WHERE active=1;
221 CREATE INDEX station_directory ON stations(active) WHERE active=1 AND custom=0;
222 DROP INDEX IF EXISTS station_popularity;
223 CREATE VIRTUAL TABLE station_search USING fts5(search,
224 content='stations',content_rowid='rowid',columnsize=0,detail=none,
225 tokenize='trigram case_sensitive 1');
226 INSERT INTO station_search(station_search) VALUES ('rebuild');
227 CREATE VIRTUAL TABLE station_search_terms USING fts5vocab(station_search,'row');
228 CREATE TABLE station_search_stats(term TEXT PRIMARY KEY,n INTEGER NOT NULL) WITHOUT ROWID;
229 INSERT INTO station_search_stats SELECT term,doc FROM station_search_terms;
230 INSERT INTO station_search_stats VALUES ('',(SELECT count(*) FROM stations));
231 CREATE TRIGGER station_search_insert AFTER INSERT ON stations BEGIN
232 INSERT INTO station_search(rowid,search) VALUES (new.rowid,new.search);
233 END;
234 CREATE TRIGGER station_search_delete AFTER DELETE ON stations BEGIN
235 INSERT INTO station_search(station_search,rowid,search) VALUES ('delete',old.rowid,old.search);
236 END;
237 CREATE TRIGGER station_search_update AFTER UPDATE OF search ON stations
238 WHEN old.search IS NOT new.search BEGIN
239 INSERT INTO station_search(station_search,rowid,search) VALUES ('delete',old.rowid,old.search);
240 INSERT INTO station_search(rowid,search) VALUES (new.rowid,new.search);
241 END;
242 ANALYZE;",
243 )?;
244 }
245 if version < 6 {
246 geo::migrate(&tx)?;
247 }
248 if version < 7 {
249 revisions::migrate(&tx)?;
250 }
251 if version < 8 {
252 tx.execute_batch(&format!(
253 "CREATE INDEX IF NOT EXISTS recording_started ON recordings({RECORDING_ORDER});"
254 ))?;
255 }
256 if version < 9 {
257 crate::podcast::migrate(&tx)?;
258 }
259 if version < 10 {
260 crate::podcast::migrate_library(&tx)?;
261 }
262 if version < 11 {
263 crate::podcast::migrate_episode_order(&tx)?;
264 }
265 ensure_perf_indexes(&tx)?;
266 tx.pragma_update(None, "user_version", SCHEMA_VERSION)?;
267 tx.commit()?;
268 } else {
269 let has_indexes: bool = conn.query_row(
270 "SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='index' AND name='station_votes')",
271 [],
272 |r| r.get(0),
273 )?;
274 if !has_indexes {
275 let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
276 ensure_perf_indexes(&tx)?;
277 tx.commit()?;
278 }
279 }
280 Ok(Self { conn })
281 }
282
283 pub fn upsert(&self, station: &Station) -> Result<()> {
284 let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
285 Self::write_station(&tx, "stations", station)?;
286 geo::changed(&tx)?;
287 tx.commit()?;
288 Ok(())
289 }
290
291 pub fn bootstrap(
292 &mut self,
293 rows: &[Station],
294 mut cancelled: impl FnMut() -> bool,
295 ) -> Result<usize> {
296 let tx = self.conn.transaction()?;
297 for row in rows {
298 if cancelled() {
299 bail!(DomainError::new(ErrorCode::Cancelled));
300 }
301 Self::write_station_with_policy(&tx, "stations", row, false, false)?;
302 }
303 if cancelled() {
304 bail!(DomainError::new(ErrorCode::Cancelled));
305 }
306 if rows.is_empty() {
307 bail!(DomainError::new(ErrorCode::EmptyCatalog));
308 }
309 facets::rebuild(&tx)?;
310 if cancelled() {
311 bail!(DomainError::new(ErrorCode::Cancelled));
312 }
313 geo::changed(&tx)?;
314 tx.commit()?;
315 let _ = self.refresh_search_stats();
317 Ok(rows.len())
318 }
319
320 fn write_station(conn: &Connection, table: &str, s: &Station) -> Result<()> {
321 Self::write_station_with_policy(conn, table, s, false, table == "stations")
322 }
323
324 fn write_station_with_policy(
325 conn: &Connection,
326 table: &str,
327 s: &Station,
328 custom: bool,
329 maintain_facets: bool,
330 ) -> Result<()> {
331 let mut languages = String::new();
332 let mut tags = String::new();
333 Self::write_station_buffered(
334 conn,
335 table,
336 s,
337 custom,
338 maintain_facets,
339 &mut languages,
340 &mut tags,
341 )
342 }
343
344 fn write_station_buffered(
345 conn: &Connection,
346 table: &str,
347 s: &Station,
348 custom: bool,
349 maintain_facets: bool,
350 languages: &mut String,
351 tags: &mut String,
352 ) -> Result<()> {
353 if s.stationuuid.is_empty() || s.name.trim().is_empty() {
354 bail!(DomainError::new(ErrorCode::InvalidStation));
355 }
356 uuid::Uuid::parse_str(&s.stationuuid).context(DomainError::new(ErrorCode::InvalidUuid))?;
357 let before = if maintain_facets {
358 facets::station_values(conn, &s.stationuuid)?
359 } else {
360 Default::default()
361 };
362 let sql = match (table, custom) {
363 ("incoming", _) => {
364 "INSERT INTO incoming (uuid,name,search,country,languages,tags,bitrate,popularity,custom,active,json,normalized_url,geo_x,geo_y)
365 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14)
366 ON CONFLICT(uuid) DO UPDATE SET name=excluded.name,search=excluded.search,
367 country=excluded.country,languages=excluded.languages,tags=excluded.tags,
368 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
369 WHERE incoming.custom=0"
370 }
371 ("stations", true) => {
372 "INSERT INTO stations (uuid,name,search,country,languages,tags,bitrate,popularity,custom,active,json,normalized_url,geo_x,geo_y)
373 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14)
374 ON CONFLICT(uuid) DO UPDATE SET name=excluded.name,search=excluded.search,
375 country=excluded.country,languages=excluded.languages,tags=excluded.tags,
376 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"
377 }
378 _ => {
379 "INSERT INTO stations (uuid,name,search,country,languages,tags,bitrate,popularity,custom,active,json,normalized_url,geo_x,geo_y)
380 VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14)
381 ON CONFLICT(uuid) DO UPDATE SET name=excluded.name,search=excluded.search,
382 country=excluded.country,languages=excluded.languages,tags=excluded.tags,
383 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
384 WHERE stations.custom=0"
385 }
386 };
387 normalize_csv_tokens(languages, &[&s.language, &s.languagecodes]);
391 normalize_csv_tokens(tags, &[&s.tags]);
392 let coordinates = crate::geo::coordinates(s.geo_lat, s.geo_long);
393 conn.prepare_cached(sql)?.execute(params![
394 s.stationuuid,
395 s.name,
396 s.search_text(),
397 s.countrycode.trim().to_uppercase(),
398 languages.as_str(),
399 tags.as_str(),
400 s.bitrate,
401 s.clickcount.min(i64::MAX as u64),
402 s.custom,
403 s.active,
404 serde_json::to_string(s)?,
405 crate::config::normalized_url(s.primary_url()).ok(),
406 coordinates.map(|p| p.0),
407 coordinates.map(|p| p.1)
408 ])?;
409 if maintain_facets {
410 facets::update(
411 conn,
412 &before,
413 &facets::station_values(conn, &s.stationuuid)?,
414 )?;
415 }
416 Ok(())
417 }
418
419 pub fn set_meta(&self, key: &str, value: &str) -> Result<()> {
420 Self::write_meta(&self.conn, key, value)
421 }
422
423 fn write_meta(conn: &Connection, key: &str, value: &str) -> Result<()> {
424 conn.execute(
425 "INSERT INTO meta(key,value) VALUES (?1,?2) ON CONFLICT(key) DO UPDATE SET value=excluded.value WHERE meta.value IS NOT excluded.value",
426 params![key, value],
427 )?;
428 Ok(())
429 }
430
431 pub(crate) fn save_session(
432 &self,
433 preferences: &std::collections::BTreeMap<String, String>,
434 plays: &[(Played, String)],
435 ) -> Result<()> {
436 let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
437 for (play, at) in plays {
438 match play {
439 Played::Station(uuid) => {
440 tx.execute(
441 "INSERT INTO history(uuid,played_at) VALUES (?1,?2)",
442 params![uuid, at],
443 )?;
444 let threshold = tx.last_insert_rowid().saturating_sub(1000);
445 tx.execute("DELETE FROM history WHERE id<=?1", [threshold])?;
446 Self::write_meta(&tx, "pref_last_station", uuid)?;
447 Self::write_meta(&tx, "pref_last_media", "station")?;
448 }
449 Played::Episode(id) => {
450 tx.execute(
451 "INSERT INTO podcast_history(episode_id,played_at) VALUES (?1,?2)",
452 params![id, at],
453 )?;
454 Self::write_meta(&tx, "pref_last_episode", id)?;
455 Self::write_meta(&tx, "pref_last_media", "episode")?;
456 }
457 }
458 }
459 for (key, value) in preferences {
460 if let Some(id) = key.strip_prefix("podcast_progress:") {
461 Self::write_podcast_progress(&tx, id, &serde_json::from_str(value)?)?;
462 continue;
463 }
464 Self::write_meta(&tx, key, value)?;
465 }
466 tx.commit()?;
467 Ok(())
468 }
469
470 pub fn directory_count(&self) -> Result<usize> {
471 Ok(self.conn.query_row(
472 "SELECT count(*) FROM stations WHERE custom=0 AND active=1",
473 [],
474 |r| r.get(0),
475 )?)
476 }
477
478 pub fn incoming_count(&self) -> Result<usize> {
479 Ok(self
480 .conn
481 .query_row("SELECT count(*) FROM incoming", [], |r| r.get(0))?)
482 }
483
484 pub fn begin_sync(&self) -> Result<()> {
485 self.conn.execute_batch(
486 "DROP TABLE IF EXISTS temp.incoming;
487 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;
488 CREATE UNIQUE INDEX temp.incoming_uuid ON incoming(uuid);",
489 )?;
490 Ok(())
491 }
492
493 pub fn stage(&mut self, rows: &[Station]) -> Result<()> {
494 let tx = self.conn.transaction()?;
495 let mut languages = String::with_capacity(64);
496 let mut tags = String::with_capacity(64);
497 for row in rows {
498 if row.active && !row.custom {
499 Self::write_station_buffered(
500 &tx,
501 "incoming",
502 row,
503 false,
504 false,
505 &mut languages,
506 &mut tags,
507 )?;
508 } else {
509 let mut s = row.clone();
510 s.active = true;
511 s.custom = false;
512 Self::write_station_buffered(
513 &tx,
514 "incoming",
515 &s,
516 false,
517 false,
518 &mut languages,
519 &mut tags,
520 )?;
521 }
522 }
523 tx.commit()?;
524 Ok(())
525 }
526
527 pub fn finish_sync(&mut self) -> Result<usize> {
528 self.finish_sync_cancellable(|| false, |_, _| Ok(None))
529 }
530
531 pub(crate) fn finish_sync_cancellable(
532 &mut self,
533 mut cancelled: impl FnMut() -> bool,
534 record_attempt: impl FnOnce(&Self, usize) -> Result<Option<DomainError>>,
535 ) -> Result<usize> {
536 let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
537 let count: usize = self.incoming_count()?;
538 if count == 0 {
539 bail!(DomainError::new(ErrorCode::EmptyCatalog));
540 }
541 if let Some(rejected) = record_attempt(self, count)? {
542 tx.commit()?;
544 return Err(rejected.into());
545 }
546 let initial: bool = tx.query_row(
547 "SELECT NOT EXISTS(SELECT 1 FROM stations LIMIT 1)",
548 [],
549 |r| r.get(0),
550 )?;
551 let search_changed: bool = if initial {
552 true
553 } else {
554 tx.query_row(
555 "SELECT EXISTS(SELECT 1 FROM incoming i LEFT JOIN stations s ON s.uuid=i.uuid
556 WHERE s.uuid IS NULL OR (s.custom=0 AND s.search IS NOT i.search))",
557 [],
558 |r| r.get(0),
559 )?
560 };
561 let facet_delta = facets::publication_delta(&tx, initial)?;
562 if cancelled() {
563 bail!(DomainError::new(ErrorCode::Cancelled));
564 }
565 tx.execute_batch(
568 "DROP TRIGGER IF EXISTS revision_stations_INSERT;
569 DROP TRIGGER IF EXISTS revision_stations_UPDATE;",
570 )?;
571 let (removed, updated) = if initial {
572 tx.execute_batch("DROP TRIGGER IF EXISTS station_search_insert;")?;
573 let inserted = tx.execute(
574 "INSERT INTO stations (uuid,name,search,country,languages,tags,bitrate,popularity,custom,active,json,normalized_url,geo_x,geo_y)
575 SELECT uuid,name,search,country,languages,tags,bitrate,popularity,custom,active,json,normalized_url,geo_x,geo_y FROM incoming",
576 [],
577 )?;
578 tx.execute_batch(
579 "INSERT INTO station_search(station_search) VALUES ('rebuild');
580 CREATE TRIGGER station_search_insert AFTER INSERT ON stations BEGIN
581 INSERT INTO station_search(rowid,search) VALUES (new.rowid,new.search);
582 END;",
583 )?;
584 (0usize, inserted)
585 } else {
586 let removed = tx.execute(
587 "UPDATE stations SET active=0 WHERE custom=0 AND active=1
588 AND NOT EXISTS(SELECT 1 FROM incoming i WHERE i.uuid=stations.uuid)",
589 [],
590 )?;
591 let updated = tx.execute(
592 "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
593 ON CONFLICT(uuid) DO UPDATE SET name=excluded.name,search=excluded.search,
594 country=excluded.country,languages=excluded.languages,tags=excluded.tags,
595 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
596 WHERE stations.custom=0 AND (
597 stations.active<>1 OR stations.json IS NOT excluded.json OR
598 stations.name IS NOT excluded.name OR stations.search IS NOT excluded.search OR
599 stations.country IS NOT excluded.country OR stations.languages IS NOT excluded.languages OR
600 stations.tags IS NOT excluded.tags OR stations.bitrate IS NOT excluded.bitrate OR
601 stations.popularity IS NOT excluded.popularity OR stations.normalized_url IS NOT excluded.normalized_url OR
602 stations.geo_x IS NOT excluded.geo_x OR stations.geo_y IS NOT excluded.geo_y)", [],
603 )?;
604 (removed, updated)
605 };
606 if removed + updated > 0 {
607 tx.execute(
608 "UPDATE content_revisions SET n=n+?1 WHERE name='stations'",
609 [(removed + updated) as i64],
610 )?;
611 }
612 tx.execute_batch(
613 "CREATE TRIGGER revision_stations_INSERT AFTER INSERT ON stations BEGIN
614 UPDATE content_revisions SET n=n+1 WHERE name='stations'; END;
615 CREATE TRIGGER revision_stations_UPDATE AFTER UPDATE ON stations BEGIN
616 UPDATE content_revisions SET n=n+1 WHERE name='stations'; END;",
617 )?;
618 tx.execute(
619 "INSERT OR REPLACE INTO meta(key,value) VALUES ('last_sync',?1)",
620 [crate::timestamp::now()],
621 )?;
622 facets::apply_delta(&tx, facet_delta)?;
623 if cancelled() {
624 bail!(DomainError::new(ErrorCode::Cancelled));
625 }
626 if removed + updated > 0 {
627 geo::changed(&tx)?;
628 }
629 tx.commit()?;
630 if search_changed {
633 let _ = self.refresh_search_stats();
634 }
635 if removed + updated > 0 {
636 let _ = self.conn.execute_batch("PRAGMA optimize;");
637 }
638 Ok(count)
639 }
640
641 pub(crate) fn record_rolled_back_sync(
643 &self,
644 previous: Option<&str>,
645 report: &str,
646 ) -> Result<()> {
647 let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
648 if self.meta("last_sync_attempt")?.as_deref() == previous {
649 self.set_meta("last_sync_attempt", report)?;
650 }
651 Ok(tx.commit()?)
652 }
653
654 pub fn revision(&self) -> Result<(u64, u64)> {
658 let external = self
659 .conn
660 .pragma_query_value(None, "data_version", |r| r.get(0))?;
661 Ok((external, self.conn.total_changes()))
662 }
663
664 pub fn meta(&self, key: &str) -> Result<Option<String>> {
665 Ok(self
666 .conn
667 .query_row("SELECT value FROM meta WHERE key=?1", [key], |r| r.get(0))
668 .optional()?)
669 }
670
671 pub fn count(&self) -> Result<usize> {
672 Ok(self
673 .conn
674 .query_row("SELECT count(*) FROM stations WHERE active=1", [], |r| {
675 r.get(0)
676 })?)
677 }
678
679 pub fn station(&self, uuid: &str) -> Result<Station> {
680 let row = self
681 .conn
682 .query_row(
683 "SELECT s.json,s.active,f.uuid IS NOT NULL FROM stations s
684 LEFT JOIN favorites f ON f.uuid=s.uuid WHERE s.uuid=?1",
685 [uuid],
686 |r| {
687 Ok((
688 r.get::<_, String>(0)?,
689 r.get::<_, bool>(1)?,
690 r.get::<_, bool>(2)?,
691 ))
692 },
693 )
694 .optional()?
695 .context(DomainError::new(ErrorCode::StationNotFound))?;
696 let mut s: Station = serde_json::from_str(&row.0)?;
697 s.active = row.1;
698 s.favorite = row.2;
699 Ok(s)
700 }
701
702 fn conditions(&self, filter: &Filter) -> (String, Vec<Value>, &'static str) {
703 self.conditions_with_spatial(filter, true)
704 }
705
706 fn conditions_with_spatial(
707 &self,
708 filter: &Filter,
709 spatial: bool,
710 ) -> (String, Vec<Value>, &'static str) {
711 let mut clauses = vec![
712 "(s.active=1 OR s.custom=1 OR EXISTS(SELECT 1 FROM favorites f WHERE f.uuid=s.uuid))"
713 .to_owned(),
714 ];
715 let mut args = vec![];
716 let mut source =
719 if filter.country.is_none() && (filter.language.is_some() || filter.tag.is_some()) {
720 "stations s NOT INDEXED"
721 } else {
722 "stations s"
723 };
724 if filter.favorites && filter.history {
725 clauses.push("EXISTS(SELECT 1 FROM favorites f WHERE f.uuid=s.uuid)".into());
726 } else if filter.favorites {
727 clauses[0] = "1".into();
728 }
729 if filter.custom {
730 clauses.push("s.custom=1".into());
731 if !filter.history && !filter.favorites {
732 clauses[0] = "1".into();
733 }
734 }
735 if filter.history {
736 clauses[0] = "1".into();
737 }
738 let mut text_candidates = false;
739 let query = filter.query.trim();
740 if !query.is_empty() {
741 let codes: Vec<_> = crate::territories::matching_codes(query).collect();
744 let normalized = query.to_lowercase();
745 source = "stations s NOT INDEXED";
746 if !filter.history
747 && !filter.favorites
748 && let Some(candidate) = self.trigram_candidate(&normalized)
749 {
750 text_candidates = true;
751 let mut candidates =
754 "SELECT rowid FROM station_search WHERE station_search MATCH ?".to_owned();
755 args.push(candidate.into());
756 if !codes.is_empty() {
757 candidates.push_str(&format!(
758 " UNION SELECT rowid FROM stations WHERE country IN ({})",
759 vec!["?"; codes.len()].join(",")
760 ));
761 args.extend(codes.iter().map(|code| Value::from((*code).to_owned())));
762 }
763 clauses.push(
764 if codes.is_empty()
765 && !matches!(filter.geo, Some(crate::geo::GeoFilter::Cell(_)))
766 {
767 source =
768 "station_search CROSS JOIN stations s ON s.rowid=station_search.rowid";
769 "station_search MATCH ?".to_owned()
770 } else {
771 format!("s.rowid IN ({candidates})")
772 },
773 );
774 }
775 if codes.is_empty() {
776 clauses.push("instr(s.search,?)>0".into());
777 } else {
778 let placeholders = vec!["?"; codes.len()].join(",");
779 clauses.push(format!(
780 "(instr(s.search,?)>0 OR s.country IN ({placeholders}))"
781 ));
782 }
783 args.push(normalized.into());
784 args.extend(codes.into_iter().map(|code| Value::from(code.to_owned())));
785 }
786 if let Some(country) = &filter.country {
787 clauses.push("s.country=?".into());
788 args.push(country.trim().to_uppercase().into());
789 }
790 for (col, value) in [("languages", &filter.language), ("tags", &filter.tag)] {
791 if let Some(value) = value {
792 clauses.push(format!("instr(s.{col},?)>0"));
793 args.push(format!(",{},", value.trim().to_lowercase()).into());
794 }
795 }
796 if filter.min_bitrate > 0 {
797 clauses.push("s.bitrate>=?".into());
798 args.push((filter.min_bitrate as i64).into());
799 }
800 if let Some(geo) = filter.geo {
801 clauses[0] = "s.active=1".into();
802 match geo {
803 crate::geo::GeoFilter::Missing => clauses.push("s.geo_x IS NULL".into()),
804 crate::geo::GeoFilter::Cell(bounds) if spatial => {
805 clauses.push(geo::predicate(bounds, &mut args));
806 let geo_covering = !filter.favorites
807 && !filter.history
808 && filter.query.trim().is_empty()
809 && filter.language.is_none()
810 && filter.tag.is_none();
811 if (!text_candidates && bounds.width < crate::geo::WORLD_WIDTH)
814 || geo::plain(filter)
815 || geo_covering
816 {
817 source = "stations s INDEXED BY station_geo";
818 }
819 if filter.query.trim().is_empty()
820 && let Some(country) = filter.country.as_ref().filter(|c| !c.is_empty())
821 && self
822 .conn
823 .prepare_cached("SELECT n FROM facets_cache WHERE kind=0 AND value=?1")
824 .and_then(|mut stmt| {
825 stmt.query_row([country.trim().to_uppercase()], |r| {
826 r.get::<_, usize>(0)
827 })
828 .optional()
829 })
830 .is_ok_and(|n| n.unwrap_or(0) <= geo::SORT_THRESHOLD)
831 {
832 source = "stations s INDEXED BY station_country";
835 }
836 }
837 crate::geo::GeoFilter::Cell(_) => {}
838 }
839 }
840 if filter.history {
841 source = "(SELECT uuid,max(id) AS last_id FROM history GROUP BY uuid) recent
845 CROSS JOIN stations s ON s.uuid=recent.uuid";
846 } else if filter.favorites {
847 source = "favorites f CROSS JOIN stations s ON s.uuid=f.uuid";
848 }
849 (clauses.join(" AND "), args, source)
850 }
851
852 fn trigram_candidate(&self, normalized: &str) -> Option<String> {
855 if normalized.chars().count() < 3 || normalized.contains('\0') {
856 return None;
857 }
858 let chars: Vec<_> = normalized.chars().collect();
859 let stride = ((chars.len() - 2) / 16).max(1);
860 let mut best = (usize::MAX, chars[..3].iter().collect::<String>());
861 let terms: std::collections::BTreeSet<String> = chars
863 .windows(3)
864 .step_by(stride)
865 .take(16)
866 .map(|part| part.iter().collect())
867 .collect();
868 for term in terms {
869 let frequency = self
870 .conn
871 .prepare_cached("SELECT n FROM station_search_stats WHERE term=?1")
872 .and_then(|mut s| s.query_row([&term], |r| r.get::<_, usize>(0)).optional());
873 let frequency = match frequency {
876 Ok(Some(n)) => n,
877 Ok(None) => 0,
878 Err(_) => continue,
879 };
880 if frequency < best.0 {
881 best = (frequency, term);
882 }
883 if frequency == 0 {
884 break;
885 }
886 }
887 let total: usize = self
888 .conn
889 .query_row(
890 "SELECT n FROM station_search_stats WHERE term=''",
891 [],
892 |r| r.get(0),
893 )
894 .unwrap_or(0);
895 if total > 0 && best.0 > total / 4 {
898 return None;
899 }
900 Some(format!("\"{}\"", best.1.replace('"', "\"\"")))
901 }
902
903 fn refresh_search_stats(&self) -> Result<()> {
904 let stats = {
908 let mut stmt = self.conn.prepare(
909 "SELECT term,doc FROM station_search_terms
910 UNION ALL SELECT '',count(*) FROM stations",
911 )?;
912 stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))?
913 .collect::<rusqlite::Result<Vec<_>>>()?
914 };
915 let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
918 tx.execute("DELETE FROM station_search_stats", [])?;
919 {
920 let mut stmt = tx.prepare("INSERT INTO station_search_stats VALUES (?1,?2)")?;
921 for (term, count) in stats {
922 stmt.execute(params![term, count])?;
923 }
924 }
925 tx.commit()?;
926 Ok(())
927 }
928
929 fn search_order(filter: &Filter) -> &'static str {
930 if filter.history {
931 "recent.last_id DESC"
932 } else {
933 match filter.sort {
934 crate::model::Sort::Name => "s.name COLLATE NOCASE,s.uuid",
935 crate::model::Sort::Bitrate => "s.bitrate DESC,s.name,s.uuid",
936 crate::model::Sort::Votes => {
937 "CASE WHEN json_valid(s.json) THEN json_extract(s.json,'$.votes') END DESC,s.name,s.uuid"
938 }
939 crate::model::Sort::Clickcount => "s.popularity DESC,s.name,s.uuid",
940 crate::model::Sort::Random => "random()",
941 }
942 }
943 }
944
945 pub fn station_position(&self, uuid: &str, filter: &Filter) -> Result<Option<usize>> {
947 use crate::model::Sort;
948 let (conditions, mut args, source) = self.conditions(filter);
949 if !filter.history
950 && matches!(
951 filter.sort,
952 Sort::Clickcount | Sort::Bitrate | Sort::Name | Sort::Votes
953 )
954 {
955 let tx = self
956 .conn
957 .is_autocommit()
958 .then(|| self.conn.unchecked_transaction())
959 .transpose()?;
960 let conn = tx.as_deref().unwrap_or(&self.conn);
961 let mut target_args = args.clone();
962 target_args.push(uuid.to_owned().into());
963 let target = conn
964 .query_row(
965 &format!(
966 "SELECT s.popularity,s.bitrate,s.name,{VOTES_EXPR_S} FROM {source}
967 WHERE {conditions} AND s.uuid=?"
968 ),
969 params_from_iter(target_args),
970 |r| {
971 Ok((
972 r.get::<_, i64>(0)?,
973 r.get::<_, i64>(1)?,
974 r.get::<_, String>(2)?,
975 r.get::<_, Option<Value>>(3)?,
976 ))
977 },
978 )
979 .optional()?;
980 let Some((popularity, bitrate, name, votes)) = target else {
981 return Ok(None);
982 };
983 let count = |predicate: &str, values: Vec<Value>| -> Result<usize> {
984 let mut values_with_filter = args.clone();
985 values_with_filter.extend(values);
986 Ok(conn
987 .prepare_cached(&format!(
988 "SELECT count(*) FROM {source}
989 WHERE {conditions} AND ({predicate})"
990 ))?
991 .query_row(params_from_iter(values_with_filter), |r| r.get(0))?)
992 };
993 let position = if filter.sort == Sort::Name {
996 count("s.name COLLATE NOCASE < ?", vec![name.clone().into()])?
997 + count(
998 "s.name COLLATE NOCASE = ? AND s.uuid < ?",
999 vec![name.into(), uuid.to_owned().into()],
1000 )?
1001 } else if filter.sort == Sort::Votes {
1002 match votes {
1003 Some(v) if !matches!(v, Value::Null) => {
1004 count(&format!("{VOTES_EXPR_S}>?"), vec![v.clone()])?
1005 + count(
1006 &format!("{VOTES_EXPR_S}=? AND (s.name,s.uuid)<(?,?)"),
1007 vec![v, name.into(), uuid.to_owned().into()],
1008 )?
1009 }
1010 _ => {
1011 count(&format!("{VOTES_EXPR_S} IS NOT NULL"), vec![])?
1012 + count(
1013 &format!("{VOTES_EXPR_S} IS NULL AND (s.name,s.uuid)<(?,?)"),
1014 vec![name.into(), uuid.to_owned().into()],
1015 )?
1016 }
1017 }
1018 } else {
1019 let (column, value) = if filter.sort == Sort::Bitrate {
1020 ("bitrate", bitrate)
1021 } else {
1022 ("popularity", popularity)
1023 };
1024 count(&format!("s.{column}>?"), vec![value.into()])?
1025 + count(
1026 &format!("s.{column}=? AND (s.name,s.uuid)<(?,?)"),
1027 vec![value.into(), name.into(), uuid.to_owned().into()],
1028 )?
1029 };
1030 if let Some(tx) = tx {
1031 tx.commit()?;
1032 }
1033 return Ok(Some(position));
1034 }
1035 let order = Self::search_order(filter);
1036 let sql = format!(
1037 "WITH ranked AS (
1038 SELECT s.uuid,row_number() OVER (ORDER BY {order})-1 AS position
1039 FROM {source} WHERE {conditions}
1040 ) SELECT position FROM ranked WHERE uuid=?"
1041 );
1042 args.push(uuid.to_owned().into());
1043 Ok(self
1044 .conn
1045 .query_row(&sql, params_from_iter(args), |row| row.get::<_, i64>(0))
1046 .optional()?
1047 .map(|position| position as usize))
1048 }
1049
1050 pub fn search(&self, filter: &Filter) -> Result<Vec<Station>> {
1051 let _snapshot = if filter.geo.is_some() && self.conn.is_autocommit() {
1054 Some(self.conn.unchecked_transaction()?)
1055 } else {
1056 None
1057 };
1058 let (mut conditions, mut args, mut source) = self.conditions(filter);
1059 if let Some(crate::geo::GeoFilter::Cell(bounds)) = filter.geo
1064 && !filter.history
1065 && !filter.favorites
1066 && let Some(index) = match filter.sort {
1067 crate::model::Sort::Clickcount => Some("stations s INDEXED BY station_sort"),
1068 crate::model::Sort::Name => Some("stations s INDEXED BY station_name"),
1069 crate::model::Sort::Bitrate => Some("stations s INDEXED BY station_bitrate"),
1070 crate::model::Sort::Votes => Some("stations s INDEXED BY station_votes"),
1071 _ => None,
1072 }
1073 {
1074 let probe = format!(
1075 "SELECT s.rowid FROM {source} WHERE {conditions} LIMIT {}",
1076 geo::SORT_THRESHOLD + 1
1077 );
1078 let ids = if geo::plain(filter) {
1081 None
1082 } else {
1083 Some(
1084 self.conn
1085 .prepare_cached(&probe)?
1086 .query_map(params_from_iter(&args), |r| r.get::<_, i64>(0))?
1087 .collect::<rusqlite::Result<Vec<_>>>()?,
1088 )
1089 };
1090 let n = if let Some(ids) = &ids {
1091 ids.len()
1092 } else {
1093 self.conn
1094 .prepare_cached(&format!("SELECT count(*) FROM ({probe})"))?
1095 .query_row(params_from_iter(&args), |r| r.get::<_, usize>(0))?
1096 };
1097 if n == 0 {
1098 return Ok(vec![]);
1099 }
1100 if n <= geo::SORT_THRESHOLD
1101 && let Some(ids) = ids
1102 {
1103 conditions = format!("s.rowid IN ({})", vec!["?"; ids.len()].join(","));
1104 args = ids.into_iter().map(Value::Integer).collect();
1105 source = "stations s";
1106 } else if n > geo::SORT_THRESHOLD {
1107 let mut spatial_args = vec![];
1108 let spatial = geo::predicate(bounds, &mut spatial_args);
1109 let candidates = format!(
1110 "SELECT s.rowid FROM stations s INDEXED BY station_geo WHERE s.active=1 AND {spatial}"
1111 );
1112 (conditions, args, _) = self.conditions_with_spatial(filter, false);
1116 conditions = format!("s.rowid IN ({candidates}) AND {conditions}");
1117 spatial_args.extend(args);
1118 args = spatial_args;
1119 source = index;
1120 }
1121 }
1122 let order = Self::search_order(filter);
1123 let limit = filter.limit.clamp(1, 1000);
1124 if source == "stations s NOT INDEXED"
1129 && !filter.history
1130 && !filter.favorites
1131 && filter.geo.is_none()
1132 && filter.offset.saturating_add(limit) <= 500
1133 && let Some((sort_index, covers_country)) = match filter.sort {
1134 crate::model::Sort::Clickcount if filter.country.is_some() => {
1135 Some(("station_country_sort", true))
1136 }
1137 crate::model::Sort::Clickcount => Some(("station_sort", false)),
1138 crate::model::Sort::Name => Some(("station_name", false)),
1139 crate::model::Sort::Bitrate => Some(("station_bitrate", false)),
1140 crate::model::Sort::Votes => Some(("station_votes", false)),
1141 crate::model::Sort::Random => None,
1142 }
1143 {
1144 let mut probe_clauses = vec![if filter.custom {
1145 "s.custom=1".to_owned()
1146 } else {
1147 "(s.active=1 OR s.custom=1 OR EXISTS(SELECT 1 FROM favorites f WHERE f.uuid=s.uuid))"
1148 .to_owned()
1149 }];
1150 let mut probe_args: Vec<Value> = vec![];
1151 if covers_country && let Some(country) = &filter.country {
1152 probe_clauses.push("s.country=?".into());
1153 probe_args.push(country.trim().to_uppercase().into());
1154 }
1155 if filter.min_bitrate > 0 {
1156 probe_clauses.push("s.bitrate>=?".into());
1157 probe_args.push((filter.min_bitrate as i64).into());
1158 }
1159 let probe_sql = format!(
1160 "WITH probe AS (
1161 SELECT s.rowid AS id FROM stations s INDEXED BY {sort_index}
1162 WHERE {} ORDER BY {order} LIMIT 4096
1163 )
1164 SELECT s.json,s.active,EXISTS(SELECT 1 FROM favorites f WHERE f.uuid=s.uuid)
1165 FROM probe CROSS JOIN stations s ON s.rowid=probe.id
1166 WHERE {conditions} LIMIT ? OFFSET ?",
1167 probe_clauses.join(" AND ")
1168 );
1169 probe_args.extend(args.iter().cloned());
1170 probe_args.push((limit as i64).into());
1171 probe_args.push((filter.offset.min(i64::MAX as usize) as i64).into());
1172 let mut stmt = self.conn.prepare_cached(&probe_sql)?;
1173 let rows = stmt.query_map(params_from_iter(probe_args), |r| {
1174 Ok((
1175 r.get::<_, String>(0)?,
1176 r.get::<_, bool>(1)?,
1177 r.get::<_, bool>(2)?,
1178 ))
1179 })?;
1180 let mut page = Vec::with_capacity(limit);
1181 for row in rows {
1182 let (json, active, favorite) = row?;
1183 let mut s: Station = serde_json::from_str(&json)?;
1184 s.active = active;
1185 s.favorite = favorite;
1186 page.push(s);
1187 }
1188 if page.len() == limit {
1189 return Ok(page);
1190 }
1191 }
1192 let page_order = if filter.history {
1195 " ORDER BY page.last_id DESC".to_owned()
1196 } else if filter.sort == crate::model::Sort::Random {
1197 String::new()
1198 } else {
1199 format!(" ORDER BY {order}")
1200 };
1201 let history_column = if filter.history {
1202 ",recent.last_id"
1203 } else {
1204 ""
1205 };
1206 let sql = format!(
1208 "WITH page AS MATERIALIZED (
1209 SELECT s.rowid AS id{history_column} FROM {source}
1210 WHERE {conditions} ORDER BY {order} LIMIT ? OFFSET ?)
1211 SELECT s.json,s.active,EXISTS(SELECT 1 FROM favorites f WHERE f.uuid=s.uuid)
1212 FROM page JOIN stations s ON s.rowid=page.id{page_order}"
1213 );
1214 args.push((limit as i64).into());
1215 args.push((filter.offset.min(i64::MAX as usize) as i64).into());
1216 let mut stmt = self.conn.prepare_cached(&sql)?;
1217 let rows = stmt.query_map(params_from_iter(args), |r| {
1218 Ok((
1219 r.get::<_, String>(0)?,
1220 r.get::<_, bool>(1)?,
1221 r.get::<_, bool>(2)?,
1222 ))
1223 })?;
1224 rows.map(|row| {
1225 let (json, active, favorite) = row?;
1226 let mut s: Station = serde_json::from_str(&json)?;
1227 s.active = active;
1228 s.favorite = favorite;
1229 Ok(s)
1230 })
1231 .collect()
1232 }
1233
1234 pub fn random(&self, filter: &Filter, exclude: &[String]) -> Result<Option<Station>> {
1235 let (mut conditions, mut args, source) = self.conditions(filter);
1236 if !filter.history
1241 && !filter.favorites
1242 && !filter.custom
1243 && source.starts_with("stations s")
1244 {
1245 let bounds: Option<(i64, i64)> = self
1249 .conn
1250 .prepare_cached(
1251 "SELECT (SELECT min(rowid) FROM stations),(SELECT max(rowid) FROM stations)",
1252 )?
1253 .query_row([], |r| {
1254 Ok((r.get::<_, Option<i64>>(0)?, r.get::<_, Option<i64>>(1)?))
1255 })
1256 .ok()
1257 .and_then(|(lo, hi)| Some((lo?, hi?)));
1258 if let Some((lo, hi)) = bounds
1259 && lo <= hi
1260 {
1261 use rand::Rng;
1262 let probe_sql = format!(
1263 "SELECT s.uuid,s.json,s.active,EXISTS(SELECT 1 FROM favorites f WHERE f.uuid=s.uuid)
1264 FROM stations s WHERE s.rowid=? AND {conditions}"
1265 );
1266 let mut stmt = self.conn.prepare_cached(&probe_sql)?;
1267 let mut rng = rand::rng();
1268 let mut probe_args = Vec::with_capacity(args.len() + 1);
1269 probe_args.push(Value::Integer(0));
1270 probe_args.extend(args.iter().cloned());
1271 for _ in 0..16 {
1272 probe_args[0] = Value::Integer(rng.random_range(lo..=hi));
1273 let hit = stmt
1274 .query_row(params_from_iter(&probe_args), |r| {
1275 Ok((
1276 r.get::<_, String>(0)?,
1277 r.get::<_, String>(1)?,
1278 r.get::<_, bool>(2)?,
1279 r.get::<_, bool>(3)?,
1280 ))
1281 })
1282 .optional()?;
1283 if let Some((uuid, json, active, favorite)) = hit
1284 && !exclude.iter().any(|x| x == &uuid)
1285 {
1286 let mut s: Station = serde_json::from_str(&json)?;
1287 s.active = active;
1288 s.favorite = favorite;
1289 return Ok(Some(s));
1290 }
1291 }
1292 }
1293 }
1294 if !exclude.is_empty() {
1295 let placeholders = vec!["?"; exclude.len()].join(",");
1296 conditions.push_str(&format!(" AND s.uuid NOT IN ({placeholders})"));
1297 args.extend(exclude.iter().cloned().map(Value::Text));
1298 }
1299 let sql = format!(
1300 "SELECT s.uuid FROM {source}
1301 WHERE {conditions} ORDER BY random() LIMIT 1"
1302 );
1303 let selected = self
1304 .conn
1305 .query_row(&sql, params_from_iter(args), |r| r.get::<_, String>(0))
1306 .optional()?;
1307 selected.map(|id| self.station(&id)).transpose()
1308 }
1309
1310 pub fn facets(
1311 &self,
1312 kind: crate::model::FacetKind,
1313 prefix: &str,
1314 ) -> Result<Vec<crate::model::Facet>> {
1315 self.facets_limited(kind, prefix, usize::MAX)
1316 }
1317
1318 pub fn facets_limited(
1319 &self,
1320 kind: crate::model::FacetKind,
1321 prefix: &str,
1322 limit: usize,
1323 ) -> Result<Vec<crate::model::Facet>> {
1324 use crate::model::{Facet, FacetKind};
1325 let (kind, prefix) = match kind {
1326 FacetKind::Country => (0, prefix.trim().to_uppercase()),
1327 FacetKind::Language => (1, prefix.trim().to_lowercase()),
1328 FacetKind::Tag => (2, prefix.trim().to_lowercase()),
1329 };
1330 let limit = limit.min(i64::MAX as usize) as i64;
1331 let codes = if kind == 0 {
1332 crate::territories::matching_prefix_codes(&prefix).collect::<Vec<_>>()
1333 } else {
1334 Vec::new()
1335 };
1336 let (sql, args) = if prefix.is_empty() {
1339 (
1340 "SELECT value,n FROM facets_cache WHERE kind=?1 ORDER BY value LIMIT ?2".to_owned(),
1341 vec![Value::from(kind), Value::from(limit)],
1342 )
1343 } else if codes.is_empty() {
1344 if let Some(upper) = next_utf8_prefix(&prefix) {
1345 (
1346 "SELECT value,n FROM facets_cache WHERE kind=?1 AND value>=?2 AND value<?3 ORDER BY value LIMIT ?4".to_owned(),
1347 vec![
1348 Value::from(kind),
1349 Value::from(prefix),
1350 Value::from(upper),
1351 Value::from(limit),
1352 ],
1353 )
1354 } else {
1355 (
1356 "SELECT value,n FROM facets_cache WHERE kind=?1 AND value>=?2 ORDER BY value LIMIT ?3".to_owned(),
1357 vec![Value::from(kind), Value::from(prefix), Value::from(limit)],
1358 )
1359 }
1360 } else {
1361 let mut args: Vec<Value> = vec![Value::from(kind), Value::from(prefix.clone())];
1362 let range_clause = if let Some(upper) = next_utf8_prefix(&prefix) {
1363 args.push(Value::from(upper));
1364 "value>=?2 AND value<?3"
1365 } else {
1366 "value>=?2"
1367 };
1368 let first_code = args.len() + 1;
1369 let placeholders = (first_code..first_code + codes.len())
1370 .map(|i| format!("?{i}"))
1371 .collect::<Vec<_>>()
1372 .join(",");
1373 args.extend(codes.into_iter().map(|c| Value::from(c.to_owned())));
1374 let limit_param = args.len() + 1;
1375 args.push(Value::from(limit));
1376 (
1377 format!(
1378 "SELECT value,n FROM facets_cache WHERE kind=?1 AND {range_clause}
1379 UNION
1380 SELECT value,n FROM facets_cache WHERE kind=?1 AND value IN ({placeholders})
1381 ORDER BY value LIMIT ?{limit_param}"
1382 ),
1383 args,
1384 )
1385 };
1386 let mut stmt = self.conn.prepare_cached(&sql)?;
1387 let rows = stmt.query_map(params_from_iter(args), |r| {
1388 Ok(Facet {
1389 value: r.get(0)?,
1390 count: r.get(1)?,
1391 })
1392 })?;
1393 Ok(rows.collect::<rusqlite::Result<_>>()?)
1394 }
1395
1396 pub fn favorite(&self, uuid: &str, add: bool) -> Result<()> {
1397 self.station(uuid)?;
1398 if add {
1399 self.conn.execute(
1400 "INSERT OR IGNORE INTO favorites(uuid,created_at) VALUES (?1,?2)",
1401 params![uuid, crate::timestamp::now()],
1402 )?;
1403 } else {
1404 self.conn
1405 .execute("DELETE FROM favorites WHERE uuid=?1", [uuid])?;
1406 }
1407 Ok(())
1408 }
1409
1410 pub fn toggle_favorite(&mut self, uuid: &str) -> Result<bool> {
1411 let tx = self
1412 .conn
1413 .transaction_with_behavior(TransactionBehavior::Immediate)?;
1414 tx.query_row("SELECT 1 FROM stations WHERE uuid=?1", [uuid], |r| {
1415 r.get::<_, u8>(0)
1416 })
1417 .optional()?
1418 .context(DomainError::new(ErrorCode::StationNotFound))?;
1419 let removed = tx.execute("DELETE FROM favorites WHERE uuid=?1", [uuid])?;
1420 let added = removed == 0;
1421 if added {
1422 tx.execute(
1423 "INSERT INTO favorites(uuid,created_at) VALUES (?1,?2)",
1424 params![uuid, crate::timestamp::now()],
1425 )?;
1426 }
1427 tx.commit()?;
1428 Ok(added)
1429 }
1430
1431 pub fn played(&self, uuid: &str) -> Result<()> {
1432 self.conn.execute(
1433 "INSERT INTO history(uuid,played_at) VALUES (?1,?2)",
1434 params![uuid, crate::timestamp::now()],
1435 )?;
1436 let threshold = self.conn.last_insert_rowid().saturating_sub(1000);
1437 self.conn
1438 .execute("DELETE FROM history WHERE id <= ?1", [threshold])?;
1439 Ok(())
1440 }
1441
1442 pub fn add_backup(&self, uuid: &str, url: &str) -> Result<()> {
1443 crate::config::validate_url(url)?;
1444 self.conn.execute(
1445 "INSERT OR IGNORE INTO streams(uuid,url) VALUES (?1,?2)",
1446 params![uuid, url],
1447 )?;
1448 Ok(())
1449 }
1450
1451 pub fn save_custom(&mut self, station: &Station, backups: Option<&[String]>) -> Result<()> {
1452 let tx = self
1453 .conn
1454 .transaction_with_behavior(TransactionBehavior::Immediate)?;
1455 Self::write_custom(&tx, station, backups)?;
1456 tx.commit()?;
1457 Ok(())
1458 }
1459
1460 pub(crate) fn edit_custom(
1461 &self,
1462 uuid: &str,
1463 backups: Option<&[String]>,
1464 edit: impl FnOnce(&mut Station) -> Result<()>,
1465 ) -> Result<Station> {
1466 let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
1467 let mut station = self.station(uuid)?;
1468 if !station.custom {
1469 bail!(DomainError::new(ErrorCode::NotCustom));
1470 }
1471 edit(&mut station)?;
1472 Self::write_custom(&tx, &station, backups)?;
1473 let updated = self.station(uuid)?;
1474 tx.commit()?;
1475 Ok(updated)
1476 }
1477
1478 fn write_custom(
1479 tx: &rusqlite::Transaction<'_>,
1480 station: &Station,
1481 backups: Option<&[String]>,
1482 ) -> Result<()> {
1483 let key = crate::config::normalized_url(station.primary_url())?;
1484 if let Some(uuid) = tx.query_row(
1485 "SELECT uuid FROM stations WHERE active=1 AND normalized_url=?1 AND uuid<>?2 LIMIT 1",
1486 params![key, station.stationuuid], |r| r.get::<_, String>(0),
1487 ).optional()? {
1488 bail!(DomainError::new(ErrorCode::DuplicateStation).with("uuid", uuid));
1489 }
1490 Self::write_station_with_policy(tx, "stations", station, true, true)?;
1491 if let Some(backups) = backups {
1492 tx.execute("DELETE FROM streams WHERE uuid=?1", [&station.stationuuid])?;
1493 for url in backups {
1494 crate::config::validate_url(url)?;
1495 tx.execute(
1496 "INSERT OR IGNORE INTO streams(uuid,url) VALUES (?1,?2)",
1497 params![station.stationuuid, url],
1498 )?;
1499 }
1500 }
1501 geo::changed(tx)
1502 }
1503
1504 pub fn remove_custom(&mut self, uuid: &str, keep_references: bool) -> Result<bool> {
1505 let tx = self
1506 .conn
1507 .transaction_with_behavior(TransactionBehavior::Immediate)?;
1508 let json: String = tx
1509 .query_row(
1510 "SELECT json FROM stations WHERE uuid=?1 AND custom=1",
1511 [uuid],
1512 |r| r.get(0),
1513 )
1514 .optional()?
1515 .context(DomainError::new(ErrorCode::NotCustom))?;
1516 let mut station: Station = serde_json::from_str(&json)?;
1517 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))?;
1518 tx.execute("DELETE FROM streams WHERE uuid=?1", [uuid])?;
1519 if referenced || keep_references {
1520 station.custom = false;
1521 station.active = false;
1522 station.url.clear();
1523 station.url_resolved.clear();
1524 Self::write_station_with_policy(&tx, "stations", &station, true, true)?;
1525 } else {
1526 let before = facets::station_values(&tx, uuid)?;
1527 tx.execute("DELETE FROM stations WHERE uuid=?1", [uuid])?;
1528 facets::update(&tx, &before, &Default::default())?;
1529 }
1530 geo::changed(&tx)?;
1531 tx.commit()?;
1532 Ok(referenced || keep_references)
1533 }
1534
1535 pub fn update_backups(
1536 &mut self,
1537 uuid: &str,
1538 add: &[String],
1539 remove: &[String],
1540 ) -> Result<Vec<String>> {
1541 self.station(uuid)?;
1542 let tx = self.conn.transaction()?;
1543 for url in remove {
1544 tx.execute(
1545 "DELETE FROM streams WHERE uuid=?1 AND url=?2",
1546 params![uuid, url],
1547 )?;
1548 }
1549 for url in add {
1550 crate::config::validate_url(url)?;
1551 tx.execute(
1552 "INSERT OR IGNORE INTO streams(uuid,url) VALUES (?1,?2)",
1553 params![uuid, url],
1554 )?;
1555 }
1556 tx.commit()?;
1557 self.backups(uuid)
1558 }
1559
1560 pub fn backups(&self, uuid: &str) -> Result<Vec<String>> {
1561 let mut stmt = self
1562 .conn
1563 .prepare("SELECT url FROM streams WHERE uuid=?1 ORDER BY rowid")?;
1564 Ok(stmt
1565 .query_map([uuid], |r| r.get(0))?
1566 .collect::<rusqlite::Result<_>>()?)
1567 }
1568
1569 pub fn save_recording(&self, recording: &Recording) -> Result<()> {
1570 self.conn.execute(
1571 "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",
1572 params![
1573 recording.id,
1574 recording.status,
1575 serde_json::to_string(recording)?,
1576 recording.recovery_pending
1577 ],
1578 )?;
1579 Ok(())
1580 }
1581
1582 pub fn search_count(&self, filter: &Filter) -> Result<usize> {
1583 let (conditions, args, source) = self.conditions(filter);
1584 Ok(self
1585 .conn
1586 .prepare_cached(&format!("SELECT count(*) FROM {source} WHERE {conditions}"))?
1587 .query_row(params_from_iter(args), |r| r.get(0))?)
1588 }
1589
1590 pub fn recordings(&self, limit: usize) -> Result<Vec<Recording>> {
1591 self.recordings_page(limit, 0)
1592 }
1593
1594 pub fn recordings_count(&self) -> Result<usize> {
1595 Ok(self
1596 .conn
1597 .query_row("SELECT count(*) FROM recordings", [], |r| r.get(0))?)
1598 }
1599
1600 pub fn recording(&self, id: &str) -> Result<Recording> {
1601 let row = self
1602 .conn
1603 .query_row(
1604 "SELECT json,recovery_pending FROM recordings WHERE id=?1",
1605 [id],
1606 |r| Ok((r.get(0)?, r.get(1)?)),
1607 )
1608 .optional()?
1609 .context(DomainError::new(ErrorCode::RecordingNotFound))?;
1610 Self::read_recording(row)
1611 }
1612
1613 pub fn remove_recording_index(&self, id: &str) -> Result<()> {
1614 self.conn
1615 .execute("DELETE FROM recordings WHERE id=?1", [id])?;
1616 Ok(())
1617 }
1618
1619 pub fn recordings_page(&self, limit: usize, offset: usize) -> Result<Vec<Recording>> {
1620 let mut stmt = self.conn.prepare_cached(&format!("SELECT json,recovery_pending FROM recordings ORDER BY {RECORDING_ORDER} LIMIT ?1 OFFSET ?2"))?;
1621 let rows = stmt.query_map(
1622 params![
1623 limit.clamp(1, 1000) as i64,
1624 offset.min(i64::MAX as usize) as i64
1625 ],
1626 |r| Ok((r.get::<_, String>(0)?, r.get::<_, bool>(1)?)),
1627 )?;
1628 rows.map(|row| Self::read_recording(row?)).collect()
1629 }
1630
1631 fn read_recording((json, recovery_pending): (String, bool)) -> Result<Recording> {
1632 let mut record: Recording = serde_json::from_str(&json)?;
1633 record.recovery_pending = recovery_pending;
1634 Ok(record)
1635 }
1636
1637 pub fn unfinished_recordings(&self) -> Result<Vec<Recording>> {
1638 let mut stmt = self
1639 .conn
1640 .prepare("SELECT json,recovery_pending FROM recordings WHERE status IN ('recording','finalizing') OR recovery_pending=1")?;
1641 let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, bool>(1)?)))?;
1642 rows.map(|row| Self::read_recording(row?)).collect()
1643 }
1644}
1645
1646#[cfg(test)]
1647mod tests {
1648 use super::*;
1649
1650 #[test]
1651 fn rollback_diagnostics_preserve_a_newer_sync_report() -> Result<()> {
1652 let dir = tempfile::tempdir()?;
1653 let db = dir.path().join("radio.db");
1654 let store = Store::open(&db)?;
1655 store.record_rolled_back_sync(None, "first failure")?;
1656 let previous = store.meta("last_sync_attempt")?;
1657 assert_eq!(previous.as_deref(), Some("first failure"));
1658 let other = Store::open(&db)?;
1659 other.set_meta("last_sync_attempt", "newer attempt")?;
1660 store.record_rolled_back_sync(previous.as_deref(), "late failure")?;
1661 assert_eq!(
1662 store.meta("last_sync_attempt")?.as_deref(),
1663 Some("newer attempt")
1664 );
1665 Ok(())
1666 }
1667
1668 #[test]
1669 fn recording_order_index_migrates_without_losing_old_or_malformed_entries() {
1670 let dir = tempfile::tempdir().unwrap();
1671 let path = dir.path().join("radio.db");
1672 let store = Store::open(&path).unwrap();
1673 for (id, at) in [
1674 ("a", "2026-01-02"),
1675 ("b", "2026-01-02"),
1676 ("old", "2026-01-01"),
1677 ] {
1678 store
1679 .save_recording(&Recording {
1680 id: id.into(),
1681 stationuuid: "station".into(),
1682 station_name: "Station".into(),
1683 track: None,
1684 source_url_resolved: "http://localhost/live".into(),
1685 started_at: at.into(),
1686 stopped_at: None,
1687 media_duration_ms: Some(1000),
1688 codec: "mp3".into(),
1689 container: "mp3".into(),
1690 path: id.into(),
1691 final_path: None,
1692 size_bytes: 1,
1693 status: "complete".into(),
1694 error: None,
1695 reconnects: 0,
1696 recovery_pending: false,
1697 })
1698 .unwrap();
1699 }
1700 crate::test_support::strip_podcast_episode_order(&store.conn);
1701 store
1702 .conn
1703 .execute_batch(
1704 "DROP INDEX recording_started; PRAGMA user_version=7;
1705 INSERT INTO recordings(id,status,json) VALUES ('broken','complete','invalid');",
1706 )
1707 .unwrap();
1708 drop(store);
1709 let store = Store::open(&path).unwrap();
1710 assert_eq!(store.recordings_count().unwrap(), 4);
1711 let page = store.recordings_page(2, 0).unwrap();
1712 assert_eq!(
1713 page.iter().map(|r| r.id.as_str()).collect::<Vec<_>>(),
1714 ["b", "a"]
1715 );
1716 assert_eq!(store.recordings_page(1, 2).unwrap()[0].id, "old");
1717 assert!(store.recordings_page(1, 3).is_err());
1718 let plan: Vec<String> = store.conn.prepare(&format!(
1719 "EXPLAIN QUERY PLAN SELECT json,recovery_pending FROM recordings ORDER BY {RECORDING_ORDER} LIMIT 100"
1720 )).unwrap().query_map([], |r| r.get(3)).unwrap().collect::<rusqlite::Result<_>>().unwrap();
1721 assert!(plan.iter().any(|line| line.contains("recording_started")));
1722 assert!(!plan.iter().any(|line| line.contains("TEMP B-TREE")));
1723 }
1724
1725 #[test]
1726 fn territory_queries_union_indexed_country_and_trigram_candidates() {
1727 let dir = tempfile::tempdir().unwrap();
1728 let mut store = Store::open(&dir.path().join("radio.db")).unwrap();
1729 let rows: Vec<_> = (0..100)
1730 .map(|i| Station {
1731 stationuuid: uuid::Uuid::new_v4().to_string(),
1732 name: match i {
1733 1 => "爱尔兰音乐".into(),
1734 2 => "爱尔兰广播".into(),
1735 _ => format!("catalog station {i}"),
1736 },
1737 countrycode: if i == 0 || i == 2 { "IE" } else { "FR" }.into(),
1738 clickcount: i,
1739 active: true,
1740 ..Station::default()
1741 })
1742 .collect();
1743 store.bootstrap(&rows, || false).unwrap();
1744 let filter = Filter {
1745 query: " 爱尔兰 ".into(),
1746 limit: 100,
1747 ..Filter::default()
1748 };
1749 let actual: Vec<_> = store
1750 .search(&filter)
1751 .unwrap()
1752 .into_iter()
1753 .map(|row| row.stationuuid)
1754 .collect();
1755 assert_eq!(actual, [2, 1, 0].map(|i| rows[i].stationuuid.clone()));
1756 assert_eq!(store.search_count(&filter).unwrap(), 3);
1757 let (conditions, args, source) = store.conditions(&filter);
1758 let plan: Vec<String> = store
1759 .conn
1760 .prepare(&format!(
1761 "EXPLAIN QUERY PLAN SELECT s.rowid FROM {source} WHERE {conditions}"
1762 ))
1763 .unwrap()
1764 .query_map(params_from_iter(args), |r| r.get(3))
1765 .unwrap()
1766 .collect::<rusqlite::Result<_>>()
1767 .unwrap();
1768 for index in [
1769 "SEARCH s USING INTEGER PRIMARY KEY (rowid=?)",
1770 "station_search VIRTUAL TABLE INDEX",
1771 "station_country (country=?)",
1772 ] {
1773 assert!(plan.iter().any(|step| step.contains(index)), "{plan:?}");
1774 }
1775 }
1776
1777 #[test]
1778 fn search_statistics_collection_allows_a_concurrent_writer() {
1779 use std::sync::{
1780 Arc,
1781 atomic::{AtomicBool, Ordering},
1782 };
1783
1784 let dir = tempfile::tempdir().unwrap();
1785 let path = dir.path().join("radio.db");
1786 let mut store = Store::open(&path).unwrap();
1787 let rows: Vec<_> = (0..256)
1788 .map(|i| Station {
1789 stationuuid: uuid::Uuid::new_v4().to_string(),
1790 name: format!("station {i:05} jazz"),
1791 active: true,
1792 ..Station::default()
1793 })
1794 .collect();
1795 store.bootstrap(&rows, || false).unwrap();
1796 let writer = Connection::open(&path).unwrap();
1797 writer.busy_timeout(std::time::Duration::ZERO).unwrap();
1798 let attempted = Arc::new(AtomicBool::new(false));
1799 let succeeded = Arc::new(AtomicBool::new(false));
1800 let (attempt, success) = (attempted.clone(), succeeded.clone());
1801 store
1802 .conn
1803 .progress_handler(
1804 1000,
1805 Some(move || {
1806 if !attempt.swap(true, Ordering::SeqCst) {
1807 success.store(
1808 writer
1809 .execute("INSERT INTO meta VALUES ('concurrent','write')", [])
1810 .is_ok(),
1811 Ordering::SeqCst,
1812 );
1813 }
1814 false
1815 }),
1816 )
1817 .unwrap();
1818 store.refresh_search_stats().unwrap();
1819 store
1820 .conn
1821 .progress_handler(0, None::<fn() -> bool>)
1822 .unwrap();
1823 assert!(attempted.load(Ordering::SeqCst));
1824 assert!(succeeded.load(Ordering::SeqCst));
1825 let actual: usize = store
1826 .conn
1827 .query_row(
1828 "SELECT n FROM station_search_stats WHERE term=''",
1829 [],
1830 |r| r.get(0),
1831 )
1832 .unwrap();
1833 assert_eq!(actual, rows.len());
1834 let differences: usize = store
1835 .conn
1836 .query_row(
1837 "SELECT count(*) FROM (
1838 SELECT term,doc FROM station_search_terms
1839 EXCEPT SELECT term,n FROM station_search_stats WHERE term<>'')",
1840 [],
1841 |r| r.get(0),
1842 )
1843 .unwrap();
1844 assert_eq!(differences, 0);
1845 }
1846
1847 #[test]
1848 fn failed_statistics_refresh_preserves_hints_and_successful_publication() {
1849 for sync in [false, true] {
1850 let dir = tempfile::tempdir().unwrap();
1851 let mut store = Store::open(&dir.path().join("radio.db")).unwrap();
1852 let row = |name: &str| Station {
1853 stationuuid: uuid::Uuid::new_v4().to_string(),
1854 name: name.into(),
1855 tags: name.into(),
1856 active: true,
1857 ..Station::default()
1858 };
1859 store.bootstrap(&[row("originalneedle")], || false).unwrap();
1860 let stats = || {
1861 store
1862 .conn
1863 .prepare("SELECT term,n FROM station_search_stats ORDER BY term")
1864 .unwrap()
1865 .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))
1866 .unwrap()
1867 .collect::<rusqlite::Result<Vec<_>>>()
1868 .unwrap()
1869 };
1870 let before = stats();
1871 store
1872 .conn
1873 .execute_batch(
1874 "CREATE TRIGGER reject_stats BEFORE INSERT ON station_search_stats
1875 BEGIN SELECT RAISE(ABORT,'statistics unavailable'); END;",
1876 )
1877 .unwrap();
1878 let replacement = row("replacementneedle");
1879 if sync {
1880 store.begin_sync().unwrap();
1881 store.stage(&[replacement]).unwrap();
1882 assert_eq!(store.finish_sync().unwrap(), 1);
1883 assert!(store.meta("last_sync").unwrap().is_some());
1884 } else {
1885 assert_eq!(store.bootstrap(&[replacement], || false).unwrap(), 1);
1886 }
1887 assert_eq!(
1888 store
1889 .search_count(&Filter {
1890 query: "replacementneedle".into(),
1891 ..Filter::default()
1892 })
1893 .unwrap(),
1894 1
1895 );
1896 assert_eq!(
1897 store
1898 .facets(crate::model::FacetKind::Tag, "replacement")
1899 .unwrap()[0]
1900 .count,
1901 1
1902 );
1903 let after: Vec<_> = store
1904 .conn
1905 .prepare("SELECT term,n FROM station_search_stats ORDER BY term")
1906 .unwrap()
1907 .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))
1908 .unwrap()
1909 .collect::<rusqlite::Result<_>>()
1910 .unwrap();
1911 assert_eq!(after, before);
1912 }
1913 }
1914
1915 #[test]
1916 fn connection_revision_distinguishes_local_and_external_activity() -> Result<()> {
1917 let dir = tempfile::tempdir()?;
1918 let path = dir.path().join("radio.db");
1919 let one = Store::open(&path)?;
1920 let two = Store::open(&path)?;
1921 let before = one.revision()?;
1922 one.set_meta("diagnostic", "first")?;
1923 let local = one.revision()?;
1924 assert_eq!(before.0, local.0);
1925 assert!(local.1 > before.1);
1926 two.set_meta("diagnostic", "second")?;
1927 let external = one.revision()?;
1928 assert_ne!(external.0, local.0);
1929 assert_eq!(external.1, local.1);
1930 Ok(())
1931 }
1932
1933 #[test]
1934 fn read_snapshot_pins_revision_before_a_concurrent_commit() {
1935 let dir = tempfile::tempdir().unwrap();
1936 let path = dir.path().join("radio.db");
1937 let writer = Store::open(&path).unwrap();
1938 let reader = Store::open_reader(&path).unwrap();
1939 let revision = reader
1940 .read_snapshot(|store| {
1941 let revision = store.list_revision(&Filter::default())?;
1942 writer.upsert(&Station {
1943 stationuuid: uuid::Uuid::new_v4().to_string(),
1944 name: "new row".into(),
1945 active: true,
1946 ..Station::default()
1947 })?;
1948 assert_eq!(store.list_revision(&Filter::default())?, revision);
1949 assert_eq!(store.count()?, 0);
1950 Ok(revision)
1951 })
1952 .unwrap();
1953 assert_ne!(reader.list_revision(&Filter::default()).unwrap(), revision);
1954 assert_eq!(reader.count().unwrap(), 1);
1955 }
1956
1957 #[test]
1958 fn cancellation_before_sync_commit_rolls_back_all_derived_data() {
1959 let dir = tempfile::tempdir().unwrap();
1960 let mut store = Store::open(&dir.path().join("radio.db")).unwrap();
1961 let row = |name: &str, tag: &str| Station {
1962 stationuuid: uuid::Uuid::new_v4().to_string(),
1963 name: name.into(),
1964 tags: tag.into(),
1965 active: true,
1966 ..Station::default()
1967 };
1968 store.upsert(&row("originalneedle", "originaltag")).unwrap();
1969 store.begin_sync().unwrap();
1970 store
1971 .stage(&[row("replacementneedle", "replacementtag")])
1972 .unwrap();
1973 assert!(
1974 store
1975 .finish_sync_cancellable(|| true, |_, _| Ok(None))
1976 .is_err()
1977 );
1978 assert_eq!(store.count().unwrap(), 1);
1979 for (query, expected) in [("originalneedle", 1), ("replacementneedle", 0)] {
1980 assert_eq!(
1981 store
1982 .search_count(&Filter {
1983 query: query.into(),
1984 ..Filter::default()
1985 })
1986 .unwrap(),
1987 expected
1988 );
1989 }
1990 assert_eq!(
1991 store.facets(crate::model::FacetKind::Tag, "").unwrap()[0].value,
1992 "originaltag"
1993 );
1994 assert!(store.meta("last_sync").unwrap().is_none());
1995 }
1996
1997 #[test]
1998 fn sync_writes_only_changed_stations_and_facet_memberships() {
1999 let dir = tempfile::tempdir().unwrap();
2000 let mut store = Store::open(&dir.path().join("radio.db")).unwrap();
2001 let row = |name: &str| Station {
2002 stationuuid: uuid::Uuid::new_v4().to_string(),
2003 name: name.into(),
2004 tags: "jazz,jazz".into(),
2005 language: "english,en".into(),
2006 countrycode: "US".into(),
2007 active: true,
2008 ..Station::default()
2009 };
2010 let unchanged = row("unchanged");
2011 let mut changed = row("changed");
2012 let removed = row("removed");
2013 let mut revived = row("revived");
2014 revived.active = false;
2015 let mut custom = row("custom");
2016 custom.custom = true;
2017 for station in [&unchanged, &changed, &removed, &revived, &custom] {
2018 store.upsert(station).unwrap();
2019 }
2020 store
2021 .conn
2022 .execute_batch(
2023 "CREATE TABLE station_writes(uuid TEXT);
2024 CREATE TRIGGER audit_station_writes AFTER UPDATE ON stations
2025 BEGIN INSERT INTO station_writes VALUES(new.uuid); END;",
2026 )
2027 .unwrap();
2028 changed.tags = "rock,rock".into();
2029 changed.countrycode = "FR".into();
2030 revived.active = true;
2031 let mut collision = custom.clone();
2032 collision.custom = false;
2033 collision.tags = "wrong".into();
2034 let incoming = [unchanged.clone(), changed, revived, collision, row("new")];
2035 store.begin_sync().unwrap();
2036 store.stage(&incoming).unwrap();
2037 store.finish_sync().unwrap();
2038 let writes: Vec<String> = store
2039 .conn
2040 .prepare("SELECT uuid FROM station_writes")
2041 .unwrap()
2042 .query_map([], |r| r.get(0))
2043 .unwrap()
2044 .collect::<rusqlite::Result<_>>()
2045 .unwrap();
2046 assert_eq!(writes.len(), 3);
2047 assert!(!writes.contains(&unchanged.stationuuid));
2048 assert!(!writes.contains(&custom.stationuuid));
2049 assert!(!store.station(&removed.stationuuid).unwrap().active);
2050 assert_eq!(
2051 store.station(&custom.stationuuid).unwrap().tags,
2052 "jazz,jazz"
2053 );
2054 let facets = || {
2055 store
2056 .conn
2057 .prepare("SELECT kind,value,n FROM facets_cache ORDER BY kind,value")
2058 .unwrap()
2059 .query_map([], |r| {
2060 Ok((
2061 r.get::<_, u8>(0)?,
2062 r.get::<_, String>(1)?,
2063 r.get::<_, i64>(2)?,
2064 ))
2065 })
2066 .unwrap()
2067 .collect::<rusqlite::Result<Vec<_>>>()
2068 .unwrap()
2069 };
2070 let delta_counts = facets();
2071 facets::rebuild(&store.conn).unwrap();
2072 assert_eq!(facets(), delta_counts);
2073 let geo_revision = store.geo_revision().unwrap();
2074 store.begin_sync().unwrap();
2075 store.stage(&incoming).unwrap();
2076 let before = store.conn.total_changes();
2077 store.finish_sync().unwrap();
2078 assert_eq!(store.conn.total_changes() - before, 1);
2081 assert_eq!(store.geo_revision().unwrap(), geo_revision);
2082 }
2083}