Skip to main content

radio_cli/store/
geo.rs

1use super::*;
2use crate::geo::{GeoBounds, GeoFilter, WORLD_WIDTH};
3
4pub(super) const SORT_THRESHOLD: usize = 4096;
5
6pub(super) fn migrate(conn: &Connection) -> Result<()> {
7    conn.execute_batch(
8        "ALTER TABLE stations ADD COLUMN geo_x INTEGER;
9        ALTER TABLE stations ADD COLUMN geo_y INTEGER;
10        CREATE INDEX station_geo ON stations(geo_x,geo_y,country,bitrate,custom) WHERE active=1 AND geo_x IS NOT NULL;
11        INSERT INTO meta(key,value) VALUES ('geo_revision','1');",
12    )?;
13    let mut read = conn.prepare("SELECT rowid,json FROM stations WHERE json_extract(json,'$.geo_lat') IS NOT NULL AND json_extract(json,'$.geo_long') IS NOT NULL")?;
14    let mut write = conn.prepare("UPDATE stations SET geo_x=?2,geo_y=?3 WHERE rowid=?1")?;
15    for row in read.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)))? {
16        let (id, json) = row?;
17        let s: Station = serde_json::from_str(&json)?;
18        if let Some((x, y)) = crate::geo::coordinates(s.geo_lat, s.geo_long) {
19            write.execute(params![id, x, y])?;
20        }
21    }
22    Ok(())
23}
24pub(super) fn changed(conn: &Connection) -> Result<()> {
25    conn.execute(
26        "UPDATE meta SET value=CAST(value AS INTEGER)+1 WHERE key='geo_revision'",
27        [],
28    )?;
29    Ok(())
30}
31pub(super) fn predicate(b: GeoBounds, args: &mut Vec<Value>) -> String {
32    args.extend([b.y.into(), (b.y + b.height).into()]);
33    let mut sql = "s.geo_x IS NOT NULL AND s.geo_y>=? AND s.geo_y<?".to_owned();
34    if b.width < WORLD_WIDTH {
35        args.push(b.x.into());
36        let right = b.x + b.width;
37        if right == WORLD_WIDTH {
38            sql.push_str(" AND s.geo_x>=?");
39        } else {
40            args.push((right % WORLD_WIDTH).into());
41            sql.push_str(if right < WORLD_WIDTH {
42                " AND (s.geo_x>=? AND s.geo_x<?)"
43            } else {
44                " AND (s.geo_x>=? OR s.geo_x<?)"
45            });
46        }
47    }
48    sql
49}
50pub(super) fn plain(f: &Filter) -> bool {
51    f.query.trim().is_empty()
52        && f.country.is_none()
53        && f.language.is_none()
54        && f.tag.is_none()
55        && f.min_bitrate == 0
56        && !f.custom
57        && !f.favorites
58        && !f.history
59}
60impl Store {
61    pub fn geo_revision(&self) -> Result<u64> {
62        Ok(self.conn.query_row(
63            "SELECT CAST(value AS INTEGER) FROM meta WHERE key='geo_revision'",
64            [],
65            |r| r.get(0),
66        )?)
67    }
68    /// Stream compact coordinates into a bounded grid; never retain the atlas.
69    pub fn geo_counts(
70        &self,
71        filter: &Filter,
72        bounds: GeoBounds,
73        columns: usize,
74        rows: usize,
75        mut cancelled: impl FnMut() -> bool,
76    ) -> Result<Vec<u32>> {
77        anyhow::ensure!(
78            (1..=320).contains(&columns) && (1..=80).contains(&rows),
79            "invalid map size"
80        );
81        let mut f = filter.clone();
82        f.geo = Some(GeoFilter::Cell(bounds));
83        let plain = plain(&f);
84        let (conditions, args, source) = if plain {
85            let mut args = vec![];
86            (
87                format!("s.active=1 AND {}", predicate(bounds, &mut args)),
88                args,
89                "stations s INDEXED BY station_geo",
90            )
91        } else {
92            self.conditions(&f)
93        };
94        let mut stmt = self.conn.prepare_cached(&format!(
95            "SELECT s.geo_x,s.geo_y FROM {source} WHERE {conditions}"
96        ))?;
97        let mut points = stmt.query(params_from_iter(args))?;
98        let mut grid = vec![0u32; columns * rows];
99        let mut n = 0usize;
100        while let Some(row) = points.next()? {
101            if n.is_multiple_of(1024) && cancelled() {
102                bail!(DomainError::new(ErrorCode::Cancelled));
103            }
104            n += 1;
105            if let Some((x, y)) = bounds.project(row.get(0)?, row.get(1)?, columns, rows) {
106                grid[y * columns + x] = grid[y * columns + x].saturating_add(1);
107            }
108        }
109        Ok(grid)
110    }
111    pub fn geo_missing_countries(&self, filter: &Filter) -> Result<Vec<crate::model::Facet>> {
112        let mut f = filter.clone();
113        f.geo = Some(GeoFilter::Missing);
114        f.country = None;
115        let (conditions, args, source) = self.conditions(&f);
116        let mut stmt = self.conn.prepare_cached(&format!(
117            "SELECT s.country,count(*) FROM {source} WHERE {conditions} \
118             GROUP BY s.country ORDER BY s.country LIMIT 1000"
119        ))?;
120        Ok(stmt
121            .query_map(params_from_iter(args), |r| {
122                Ok(crate::model::Facet {
123                    value: r.get(0)?,
124                    count: r.get(1)?,
125                })
126            })?
127            .collect::<rusqlite::Result<_>>()?)
128    }
129}