Skip to main content

smriti/db/
geonames.rs

1//! GeoNames database access helpers.
2
3use std::fs::File;
4use std::io::{BufRead, BufReader};
5use std::path::Path;
6use std::path::PathBuf;
7
8use rusqlite::{Connection, OpenFlags};
9
10/// Resolve GeoNames DB path.
11///
12/// Searches the same candidate roots as the rest of bootstrap (asset
13/// install dir, $SMRITI_ASSET_DIR / legacy $PHOTOVAULT_ASSET_DIR,
14/// executable dir, project root, /usr/lib/smriti, /usr/lib/photovault)
15/// plus the CWD-relative `data/`.
16pub fn geonames_db_path() -> PathBuf {
17    let mut first_existing = None;
18    // 1. Walk every bootstrap-known asset root.
19    for root in candidate_geonames_roots() {
20        let p = root.join("data").join("geonames.db");
21        if p.exists() {
22            if geonames_db_is_current(&p) {
23                return p;
24            }
25            first_existing.get_or_insert(p);
26        }
27    }
28    // 2. Last-resort: CWD-relative literal "data/geonames.db".
29    let cwd = PathBuf::from("data").join("geonames.db");
30    if cwd.exists() {
31        if geonames_db_is_current(&cwd) {
32            return cwd;
33        }
34        first_existing.get_or_insert(cwd);
35    }
36    if let Some(existing) = first_existing {
37        return existing;
38    }
39    // 3. Fallback path that may not exist; caller checks.
40    crate::bootstrap::default_asset_install_dir()
41        .join("data")
42        .join("geonames.db")
43}
44
45/// Candidate root directories under which `data/geonames.db` may live.
46/// Mirrors `bootstrap::candidate_asset_roots` but inlined here to avoid
47/// pulling that helper into a public surface.
48fn candidate_geonames_roots() -> Vec<PathBuf> {
49    let mut roots = Vec::new();
50    roots.push(crate::bootstrap::default_asset_install_dir());
51    if let Ok(from_env) = std::env::var("SMRITI_ASSET_DIR") {
52        roots.push(PathBuf::from(from_env));
53    }
54    if let Ok(from_env) = std::env::var("PHOTOVAULT_ASSET_DIR") {
55        roots.push(PathBuf::from(from_env));
56    }
57    if let Ok(exe) = std::env::current_exe() {
58        if let Some(dir) = exe.parent() {
59            roots.push(dir.to_path_buf());
60            // Debian install layout (smriti primary, legacy photovault fallback)
61            roots.push(dir.join("..").join("lib").join("smriti"));
62            roots.push(dir.join("..").join("lib").join("photovault"));
63            // target/debug/<binary> → walk up to workspace root
64            roots.push(dir.join("..").join(".."));
65            roots.push(dir.join("..").join("..").join(".."));
66        }
67    }
68    let cwd = crate::bootstrap::project_root();
69    // `cargo tauri dev` typically sets CWD to src-tauri/. Walk up so the
70    // dev tree's data/ directory is reachable.
71    if let Some(parent) = cwd.parent() {
72        roots.push(parent.to_path_buf());
73        if let Some(grand) = parent.parent() {
74            roots.push(grand.to_path_buf());
75        }
76    }
77    roots.push(cwd);
78    roots.push(PathBuf::from("/usr/lib/smriti"));
79    roots.push(PathBuf::from("/usr/lib/photovault"));
80    roots
81}
82
83/// Check if bundled GeoNames DB exists.
84pub fn geonames_db_exists() -> bool {
85    geonames_schema_is_current()
86}
87
88/// Returns `true` when the on-disk geonames.db matches the current
89/// schema. False if the file is missing OR built against an older
90/// layout. Callers (asset setup, the geocoder) should rebuild when
91/// this returns false.
92pub fn geonames_schema_is_current() -> bool {
93    let path = geonames_db_path();
94    geonames_db_is_current(&path)
95}
96
97/// Validate a specific GeoNames database without creating or mutating it.
98pub fn geonames_db_is_current(path: &Path) -> bool {
99    if !path.exists() {
100        return false;
101    }
102    let Ok(conn) = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY) else {
103        return false;
104    };
105    // Probe both the v2 column and the data. A zero-byte, interrupted,
106    // or schema-only database must not make asset setup report success.
107    conn.query_row(
108        "SELECT COUNT(*) FROM cities WHERE feature_code IS NOT NULL",
109        [],
110        |row| row.get::<_, i64>(0),
111    )
112    .is_ok_and(|count| count > 1_000)
113}
114
115pub fn build_geonames_db(project_root: &Path) -> Result<(), String> {
116    let data_dir = project_root.join("data");
117    let countries_path = data_dir.join("country_codes.txt");
118    let cities_path = data_dir.join("cities1000.txt");
119    // Building and lookup have different semantics. Always put the output
120    // beside the supplied sources; setup scripts and release packaging use
121    // this exact contract.
122    let db_path = data_dir.join("geonames.db");
123
124    std::fs::create_dir_all(&data_dir).map_err(|e| format!("Failed to create db dir: {}", e))?;
125
126    // Build beside the destination and only replace the live DB after a
127    // successful commit. Interrupted setup leaves the previous DB intact.
128    let temp_path = data_dir.join(format!("geonames.db.tmp-{}", std::process::id()));
129    if temp_path.exists() {
130        std::fs::remove_file(&temp_path)
131            .map_err(|e| format!("Failed removing stale GeoNames temp DB: {}", e))?;
132    }
133
134    if let Err(error) = build_geonames_db_file(&countries_path, &cities_path, &temp_path) {
135        let _ = std::fs::remove_file(&temp_path);
136        return Err(error);
137    }
138    if !geonames_db_is_current(&temp_path) {
139        let _ = std::fs::remove_file(&temp_path);
140        return Err(
141            "Built GeoNames database failed validation; source data may be incomplete".to_string(),
142        );
143    }
144
145    let backup_path = data_dir.join(format!("geonames.db.backup-{}", std::process::id()));
146    if backup_path.exists() {
147        std::fs::remove_file(&backup_path)
148            .map_err(|e| format!("Failed removing stale GeoNames backup: {}", e))?;
149    }
150    let had_existing = db_path.exists();
151    if had_existing {
152        std::fs::rename(&db_path, &backup_path)
153            .map_err(|e| format!("Failed backing up old GeoNames DB: {}", e))?;
154    }
155    if let Err(error) = std::fs::rename(&temp_path, &db_path) {
156        if had_existing {
157            let _ = std::fs::rename(&backup_path, &db_path);
158        }
159        return Err(format!("Failed installing rebuilt GeoNames DB: {}", error));
160    }
161    if had_existing {
162        let _ = std::fs::remove_file(&backup_path);
163    }
164
165    Ok(())
166}
167
168fn build_geonames_db_file(
169    countries_path: &Path,
170    cities_path: &Path,
171    db_path: &Path,
172) -> Result<(), String> {
173    let mut conn = Connection::open(db_path).map_err(|e| format!("Failed to open DB: {}", e))?;
174
175    conn.execute_batch(
176        r#"
177        CREATE TABLE IF NOT EXISTS cities (
178            id INTEGER PRIMARY KEY,
179            name TEXT NOT NULL,
180            ascii_name TEXT NOT NULL,
181            latitude REAL NOT NULL,
182            longitude REAL NOT NULL,
183            country_code TEXT NOT NULL,
184            country_name TEXT NOT NULL,
185            population INTEGER,
186            feature_code TEXT,
187            timezone TEXT
188        );
189
190        CREATE TABLE IF NOT EXISTS countries (
191            code TEXT PRIMARY KEY,
192            name TEXT NOT NULL
193        );
194
195        CREATE INDEX IF NOT EXISTS idx_cities_coords ON cities(latitude, longitude);
196        CREATE INDEX IF NOT EXISTS idx_cities_feature ON cities(feature_code);
197        "#,
198    )
199    .map_err(|e| format!("Failed creating schema: {}", e))?;
200
201    let tx = conn
202        .transaction()
203        .map_err(|e| format!("Failed starting transaction: {}", e))?;
204
205    let countries = std::fs::read_to_string(countries_path)
206        .map_err(|e| format!("Failed reading {}: {}", countries_path.display(), e))?;
207    for line in countries.lines() {
208        let parts: Vec<&str> = line.split('\t').collect();
209        if parts.len() >= 2 {
210            // Windows PowerShell 5's `Set-Content -Encoding UTF8` prefixes
211            // the first code with a BOM. Strip it or all Andorran city rows
212            // fail their country lookup during the Windows setup path.
213            let country_code = parts[0].trim_start_matches('\u{feff}');
214            if country_code.starts_with('#') {
215                continue;
216            }
217            // Accept compact `code<TAB>name` input and raw GeoNames
218            // countryInfo.txt input produced by older packaging jobs.
219            let country_name = if parts.len() >= 5 { parts[4] } else { parts[1] };
220            tx.execute(
221                "INSERT OR IGNORE INTO countries (code, name) VALUES (?1, ?2)",
222                [country_code, country_name],
223            )
224            .map_err(|e| format!("Failed inserting country: {}", e))?;
225        }
226    }
227
228    let file = File::open(cities_path)
229        .map_err(|e| format!("Failed opening {}: {}", cities_path.display(), e))?;
230    let reader = BufReader::new(file);
231    let mut stmt = tx
232        .prepare(
233            r#"
234            INSERT OR IGNORE INTO cities
235                (id, name, ascii_name, latitude, longitude, country_code, country_name, population, feature_code, timezone)
236            VALUES
237                (?1, ?2, ?3, ?4, ?5, ?6, COALESCE((SELECT name FROM countries WHERE code = ?6), ?6), ?7, ?8, ?9)
238            "#,
239        )
240        .map_err(|e| format!("Failed preparing statement: {}", e))?;
241
242    for line in reader.lines() {
243        let line = line.map_err(|e| format!("Failed reading cities line: {}", e))?;
244        let parts: Vec<&str> = line.split('\t').collect();
245        // cities1000.txt columns (tab-separated):
246        //   0=id 1=name 2=ascii_name 3=alt_names 4=lat 5=lng
247        //   6=feature_class 7=feature_code 8=country_code 9=cc2
248        //   10..13=admin codes 14=population 15=elevation 16=dem
249        //   17=timezone 18=mod_date
250        if parts.len() >= 18 {
251            let id: i64 = parts[0].parse().unwrap_or(0);
252            let name = parts[1];
253            let ascii_name = parts[2];
254            let lat: f64 = parts[4].parse().unwrap_or(0.0);
255            let lon: f64 = parts[5].parse().unwrap_or(0.0);
256            let country_code = parts[8];
257            let population: i64 = parts[14].parse().unwrap_or(0);
258            let feature_code = parts[7];
259            let timezone = parts[17];
260
261            stmt.execute(rusqlite::params![
262                id,
263                name,
264                ascii_name,
265                lat,
266                lon,
267                country_code,
268                population,
269                feature_code,
270                timezone
271            ])
272            .map_err(|e| format!("Failed inserting city row: {}", e))?;
273        }
274    }
275
276    drop(stmt);
277    tx.commit()
278        .map_err(|e| format!("Failed committing GeoNames DB: {}", e))?;
279
280    Ok(())
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    #[test]
288    fn builder_writes_beside_sources_and_accepts_raw_country_info() {
289        let temp = tempfile::tempdir().expect("tempdir");
290        let data = temp.path().join("data");
291        std::fs::create_dir_all(&data).expect("data dir");
292        std::fs::write(
293            data.join("country_codes.txt"),
294            "\u{feff}ZZ\tZZZ\t999\tZZ\tTest Country\n",
295        )
296        .expect("countries");
297
298        let mut cities = String::new();
299        for id in 1..=1_001 {
300            cities.push_str(&format!(
301                "{id}\tCity {id}\tCity {id}\t\t1.0\t2.0\tP\tPPL\tZZ\t\t\t\t\t\t{id}\t\t\tUTC\t2026-01-01\n"
302            ));
303        }
304        std::fs::write(data.join("cities1000.txt"), cities).expect("cities");
305
306        build_geonames_db(temp.path()).expect("build");
307
308        let db = data.join("geonames.db");
309        assert!(db.exists());
310        assert!(!temp.path().join("geonames.db").exists());
311        let conn = Connection::open(db).expect("open built db");
312        let country: String = conn
313            .query_row("SELECT country_name FROM cities WHERE id = 1", [], |row| {
314                row.get(0)
315            })
316            .expect("country name");
317        assert_eq!(country, "Test Country");
318    }
319}