wilayah 0.3.0

Location lookup for Indonesian villages by GPS coordinates or name
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! Location lookup for Indonesian villages by GPS coordinates or name.
//!
//! Returns BMKG-compatible `adm4` administrative codes (e.g., `31.71.03.1001`)
//! for 82,689 villages across Indonesia, based on official Kemendagri
//! administrative codes with pre-computed village centroids from BIG (Badan
//! Informasi Geospasial) polygon boundaries.
//!
//! # Quick start
//!
//! ```
//! use wilayah;
//!
//! let conn = wilayah::open().expect("database");
//! let nearest = wilayah::find_nearest(&conn, -6.1647, 106.8453, 5).expect("query");
//! assert!(!nearest.is_empty());
//! ```
//!
//! # Data
//!
//! Sourced from the official Kemendagri (Ministry of Home Affairs) PDF
//! publication of all Indonesian villages, combined with village polygon
//! boundaries from BIG (Badan Informasi Geospasial) ArcGIS service. The data is
//! processed through a reproducible build pipeline to produce a SQLite database
//! with RTree spatial index and FTS5 full-text search. The database is embedded
//! into the binary at compile time via a build script.
//!
//! On first `cargo build`, the build script either downloads a pre-built
//! database from the GitHub Releases (default) or runs the full pipeline if
//! `WILAYAH_BUILD_PIPELINE=1` is set. Subsequent builds reuse the cached
//! database located at `data/locations.db`.
//!
//! To build from scratch, set `WILAYAH_BUILD_PIPELINE=1` and run:
//!
//! ```bash
//! cargo run --example build_db --features build-db
//! ```

#![deny(missing_docs)]

mod db;

#[cfg(feature = "build-db")]
#[allow(missing_docs)]
pub mod pipeline;

pub use db::{
    by_code, by_code_prefix, nearest, open_embedded, search, search_unique, LookupResult, Village,
};

/// Metadata about the embedded location database.
///
/// Returned by [`data_info()`]. Contains information about the data source,
/// the government decree it's based on, the number of villages, and when
/// the database was built.
#[derive(Debug, Clone)]
pub struct DataInfo {
    /// The upstream data source (e.g., `"official"`).
    pub source: &'static str,
    /// The government decree this data is based on
    /// (e.g., `"Kepmendagri No 300.2.2-2430 Tahun 2025"`).
    pub decree: &'static str,
    /// The number of villages in the database.
    pub village_count: u32,
    /// Unix timestamp (seconds since epoch) of when this database was built.
    pub build_date: u64,
}

/// Get the version of this crate.
///
/// Returns the `Cargo.toml` version string.
pub const fn version() -> &'static str {
    env!("CARGO_PKG_VERSION")
}

/// Get metadata about the embedded location database.
///
/// Returns source, decree, village count, and build timestamp information
/// compiled into the binary.
///
/// # Example
///
/// ```
/// let info = wilayah::data_info();
/// assert!(info.village_count > 80000);
/// assert!(info.build_date > 0);
/// ```
pub fn data_info() -> DataInfo {
    DataInfo {
        source: env!("WILAYAH_DATA_SOURCE"),
        decree: env!("WILAYAH_DATA_DECREE"),
        village_count: env!("WILAYAH_VILLAGE_COUNT").parse().unwrap_or(0),
        build_date: env!("WILAYAH_BUILD_DATE").parse().unwrap_or(0),
    }
}

/// Open the embedded database.
///
/// Loads the ~20 MB SQLite database from the compiled binary into memory using
/// SQLite's online backup API. The database contains village records with
/// spatial (RTree) and full-text (FTS5) indexes.
///
/// # Example
///
/// ```
/// let conn = wilayah::open()?;
/// # Ok::<_, rusqlite::Error>(())
/// ```
pub fn open() -> rusqlite::Result<rusqlite::Connection> {
    db::open_embedded()
}

/// Find the nearest villages to a given latitude/longitude.
///
/// Uses a SQLite RTree spatial index for fast bounding-box filtering, followed
/// by Haversine distance calculation to find the closest villages. The search
/// progressively expands the search radius until results are found or the full
/// globe has been searched.
///
/// # Arguments
///
/// * `conn` - Database connection from [`open()`]
/// * `lat` - Latitude (-90..90)
/// * `lon` - Longitude (-180..180)
/// * `limit` - Maximum number of results to return (clamped to 1..20)
///
/// # Example
///
/// ```
/// let conn = wilayah::open()?;
/// let results = wilayah::find_nearest(&conn, -6.1647, 106.8453, 5)?;
/// for v in results {
///     println!("{} ({:.1} km)", v.name, v.dist_km.unwrap());
/// }
/// # Ok::<_, rusqlite::Error>(())
/// ```
///
/// # Edge case: Papua coordinates
///
/// ```
/// let conn = wilayah::open()?;
/// let results = wilayah::find_nearest(&conn, -2.5, 140.0, 1)?;
/// assert!(!results.is_empty());
/// assert!(results[0].province.contains("Papua"));
/// # Ok::<_, rusqlite::Error>(())
/// ```
pub fn find_nearest(
    conn: &rusqlite::Connection,
    lat: f64,
    lon: f64,
    limit: usize,
) -> rusqlite::Result<Vec<Village>> {
    db::nearest(conn, lat, lon, limit)
}

/// Search for villages by name.
///
/// Uses FTS5 full-text search matching against village name, district, city,
/// and province. Supports partial matches and returns results ranked by BM25.
///
/// For disambiguation, include city or province in the query:
/// `find_by_name("kemayoran jakarta")` returns only villages in Jakarta.
///
/// # Arguments
///
/// * `conn` - Database connection from [`open()`]
/// * `query` - Search query (e.g., `"kemayoran"` or `"kemayoran jakarta"`)
/// * `limit` - Maximum number of results to return (clamped to 1..100)
///
/// # Example
///
/// ```
/// let conn = wilayah::open()?;
/// let results = wilayah::find_by_name(&conn, "kemayoran jakarta", 10)?;
/// for v in results {
///     println!("{} in {}, {}", v.name, v.district, v.province);
/// }
/// # Ok::<_, rusqlite::Error>(())
/// ```
pub fn find_by_name(
    conn: &rusqlite::Connection,
    query: &str,
    limit: usize,
) -> rusqlite::Result<Vec<Village>> {
    db::search(conn, query, limit)
}

/// Search for a unique village by name.
///
/// Returns [`LookupResult::Found`] if exactly one match exists,
/// [`LookupResult::Ambiguous`] with up to 20 candidates if multiple match,
/// or [`LookupResult::NotFound`] if no match exists.
///
/// This is useful for callers that need unambiguous results. For example,
/// a CLI tool can show an error with candidate list when the result is
/// ambiguous, rather than silently picking the wrong village.
///
/// # Arguments
///
/// * `conn` - Database connection from [`open()`]
/// * `query` - Search query (e.g., `"kemayoran"` or `"kemayoran jakarta"`)
///
/// # Example: exact match
///
/// ```
/// let conn = wilayah::open()?;
/// let result = wilayah::find_by_name_unique(&conn, "abadijaya")?;
/// if let wilayah::LookupResult::Found(v) = result {
///     println!("Found: {} in {}", v.name, v.city);
/// }
/// # Ok::<_, rusqlite::Error>(())
/// ```
///
/// # Example: ambiguous name
///
/// ```
/// let conn = wilayah::open()?;
/// // "sukamaju" exists in many villages across Indonesia
/// let result = wilayah::find_by_name_unique(&conn, "sukamaju")?;
/// assert!(matches!(result, wilayah::LookupResult::Ambiguous(_)));
/// # Ok::<_, rusqlite::Error>(())
/// ```
pub fn find_by_name_unique(
    conn: &rusqlite::Connection,
    query: &str,
) -> rusqlite::Result<LookupResult> {
    db::search_unique(conn, query)
}

/// Find a village by its BMKG-compatible administrative code.
///
/// Returns `None` if the code is not found in the database.
///
/// # Example
///
/// ```
/// let conn = wilayah::open()?;
/// let v = wilayah::find_by_code(&conn, "31.71.03.1001")?;
/// assert!(v.is_some());
/// # Ok::<_, rusqlite::Error>(())
/// ```
pub fn find_by_code(conn: &rusqlite::Connection, code: &str) -> rusqlite::Result<Option<Village>> {
    db::by_code(conn, code)
}

/// Find all villages matching an administrative code prefix.
///
/// Useful for listing all villages in a kecamatan (`"31.71.03"`),
/// kabupaten (`"31.71"`), or province (`"31"`). Returns villages
/// ordered by code, up to `limit` results.
///
/// # Arguments
///
/// * `conn` - Database connection from [`open()`]
/// * `prefix` - Code prefix (e.g., `"31.71.03"`, `"31.71"`, `"31"`)
/// * `limit` - Maximum number of results (clamped to 1..1000)
///
/// # Example
///
/// ```
/// let conn = wilayah::open()?;
/// let villages = wilayah::find_by_code_prefix(&conn, "31.71.03", 100)?;
/// assert!(!villages.is_empty());
/// for v in &villages {
///     assert!(v.code.starts_with("31.71.03"));
/// }
/// # Ok::<_, rusqlite::Error>(())
/// ```
pub fn find_by_code_prefix(
    conn: &rusqlite::Connection,
    prefix: &str,
    limit: usize,
) -> rusqlite::Result<Vec<Village>> {
    db::by_code_prefix(conn, prefix, limit)
}

/// Get the total number of villages in the database.
///
/// # Example
///
/// ```
/// let conn = wilayah::open()?;
/// let count = wilayah::village_count(&conn)?;
/// assert!(count > 80000);
/// # Ok::<_, rusqlite::Error>(())
/// ```
pub fn village_count(conn: &rusqlite::Connection) -> rusqlite::Result<i64> {
    conn.query_row("SELECT COUNT(*) FROM locations", [], |row| row.get(0))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_open_db() {
        let conn = open().expect("should open embedded database");
        let count = village_count(&conn).expect("should count villages");
        assert!(count > 80000, "expected >80k villages, got {count}");
    }

    #[test]
    fn test_data_info() {
        let info = data_info();
        assert!(info.village_count > 80000);
        assert!(info.build_date > 0);
        assert!(!info.source.is_empty());
        assert!(!info.decree.is_empty());
    }

    #[test]
    fn test_version() {
        assert_eq!(version(), "0.3.0");
    }

    #[test]
    fn test_nearest_jakarta() {
        let conn = open().unwrap();
        let results = find_nearest(&conn, -6.1647, 106.8453, 1).unwrap();
        assert_eq!(results.len(), 1);
        let v = &results[0];
        assert!(
            v.dist_km.unwrap() < 5.0,
            "should be within 5km of Jakarta center"
        );
        assert_eq!(
            v.city, "Kota Administrasi Jakarta Pusat",
            "expected Jakarta Pusat, got {}",
            v.city
        );
    }

    #[test]
    fn test_nearest_papua() {
        let conn = open().unwrap();
        let results = find_nearest(&conn, -2.5, 140.0, 1).unwrap();
        assert!(!results.is_empty());
        assert!(results[0].province.contains("Papua"));
    }

    #[test]
    fn test_search() {
        let conn = open().unwrap();
        let results = find_by_name(&conn, "kemayoran", 5).unwrap();
        assert!(!results.is_empty(), "should find Kemayoran");
        assert!(results
            .iter()
            .any(|v| v.name.to_lowercase().contains("kemayoran")));
    }

    #[test]
    fn test_search_qualified() {
        let conn = open().unwrap();
        let results = find_by_name(&conn, "kemayoran jakarta", 5).unwrap();
        assert!(!results.is_empty(), "should find Kemayoran Jakarta");
        assert!(results.iter().all(|v| v.city.contains("Jakarta")));
    }

    #[test]
    fn test_unique_found() {
        let conn = open().unwrap();
        let result = find_by_name_unique(&conn, "abadijaya").unwrap();
        assert!(
            matches!(result, LookupResult::Found(_)),
            "expected Found, got {:?}",
            result
        );
        if let LookupResult::Found(v) = result {
            assert_eq!(v.name, "Abadijaya");
        }
    }

    #[test]
    fn test_unique_ambiguous() {
        let conn = open().unwrap();
        let result = find_by_name_unique(&conn, "sukamaju").unwrap();
        assert!(
            matches!(result, LookupResult::Ambiguous(_)),
            "sukamaju should be ambiguous, got {:?}",
            result
        );
        if let LookupResult::Ambiguous(results) = result {
            assert!(results.len() > 1, "should have multiple matches");
        }
    }

    #[test]
    fn test_find_by_code() {
        let conn = open().unwrap();
        let v = find_by_code(&conn, "31.71.03.1001").unwrap();
        assert!(v.is_some(), "31.71.03.1001 should exist");
        let v = v.unwrap();
        assert_eq!(v.name, "Kemayoran");
        assert_eq!(v.district, "Kemayoran");
        assert_eq!(v.city, "Kota Administrasi Jakarta Pusat");
        assert_eq!(v.province, "Provinsi Daerah Khusus Ibukota Jakarta");
    }

    #[test]
    fn test_find_by_code_not_found() {
        let conn = open().unwrap();
        let v = find_by_code(&conn, "99.99.99.9999").unwrap();
        assert!(v.is_none());
    }

    #[test]
    fn test_find_by_code_prefix_kecamatan() {
        let conn = open().unwrap();
        let villages = find_by_code_prefix(&conn, "31.71.03", 100).unwrap();
        assert!(
            !villages.is_empty(),
            "should find villages in kecamatan 31.71.03"
        );
        assert!(villages.iter().all(|v| v.code.starts_with("31.71.03")));
        assert!(villages.iter().all(|v| v.district == "Kemayoran"));
    }

    #[test]
    fn test_find_by_code_prefix_kabupaten() {
        let conn = open().unwrap();
        let villages = find_by_code_prefix(&conn, "31.71", 500).unwrap();
        assert!(
            !villages.is_empty(),
            "should find villages in kabupaten 31.71"
        );
        assert!(villages.iter().all(|v| v.code.starts_with("31.71")));
    }

    #[test]
    fn test_find_by_code_prefix_not_found() {
        let conn = open().unwrap();
        let villages = find_by_code_prefix(&conn, "99.99.99", 100).unwrap();
        assert!(villages.is_empty());
    }

    #[test]
    fn test_unique_not_found() {
        let conn = open().unwrap();
        let result = find_by_name_unique(&conn, "zzzznonexistent").unwrap();
        assert!(
            matches!(result, LookupResult::NotFound),
            "should be not found, got {:?}",
            result
        );
    }
}