use rusqlite::{Connection, params};
use crate::error::{GeolithError, Result};
use crate::geometry::mercator::TileCoord;
use crate::output::format::OutputFormat;
const BATCH_SIZE: usize = 1000;
pub struct MbtilesOutput {
conn: Connection,
pending: Vec<(u8, u32, u32, Vec<u8>)>, tiles_written: u64,
}
impl MbtilesOutput {
pub fn create(path: &std::path::Path) -> Result<Self> {
let conn = Connection::open(path).map_err(GeolithError::Sqlite)?;
conn.execute_batch("PRAGMA journal_mode=WAL;")
.map_err(GeolithError::Sqlite)?;
conn.execute_batch(
"PRAGMA synchronous=NORMAL;
PRAGMA page_size=65536;
PRAGMA cache_size=-65536;",
)
.map_err(GeolithError::Sqlite)?;
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS metadata (name TEXT, value TEXT);
CREATE TABLE IF NOT EXISTS tiles (
zoom_level INTEGER,
tile_column INTEGER,
tile_row INTEGER,
tile_data BLOB
);
CREATE UNIQUE INDEX IF NOT EXISTS tile_index
ON tiles (zoom_level, tile_column, tile_row);",
)
.map_err(GeolithError::Sqlite)?;
Ok(Self {
conn,
pending: Vec::with_capacity(BATCH_SIZE),
tiles_written: 0,
})
}
#[must_use]
pub const fn tiles_written(&self) -> u64 {
self.tiles_written
}
fn flush_pending(&mut self) -> Result<()> {
if self.pending.is_empty() {
return Ok(());
}
let tx = self.conn.transaction().map_err(GeolithError::Sqlite)?;
{
let mut stmt = tx
.prepare_cached(
"INSERT OR REPLACE INTO tiles
(zoom_level, tile_column, tile_row, tile_data)
VALUES (?1, ?2, ?3, ?4)",
)
.map_err(GeolithError::Sqlite)?;
for (zoom, x, tms_y, data) in &self.pending {
stmt.execute(params![zoom, x, tms_y, data])
.map_err(GeolithError::Sqlite)?;
}
}
tx.commit().map_err(GeolithError::Sqlite)?;
self.tiles_written += self.pending.len() as u64;
self.pending.clear();
Ok(())
}
#[inline]
#[must_use]
const fn to_tms_y(y: u32, zoom: u8) -> u32 {
let n = 1u32 << zoom;
n - 1 - y
}
}
impl OutputFormat for MbtilesOutput {
fn name(&self) -> &str {
"mbtiles"
}
fn write_tile(&mut self, tile: TileCoord, data: &[u8]) -> Result<()> {
let tms_y = Self::to_tms_y(tile.y, tile.z);
self.pending.push((tile.z, tile.x, tms_y, data.to_vec()));
if self.pending.len() >= BATCH_SIZE {
self.flush_pending()?;
}
Ok(())
}
fn finalize(&mut self, metadata: &serde_json::Value) -> Result<()> {
self.flush_pending()?;
let tx = self.conn.transaction().map_err(GeolithError::Sqlite)?;
{
let mut stmt = tx
.prepare_cached("INSERT OR REPLACE INTO metadata (name, value) VALUES (?1, ?2)")
.map_err(GeolithError::Sqlite)?;
if let Some(obj) = metadata.as_object() {
for (key, value) in obj {
let val_str = match value {
serde_json::Value::String(s) => s.clone(),
serde_json::Value::Number(n) => n.to_string(),
serde_json::Value::Bool(b) => b.to_string(),
other => other.to_string(),
};
stmt.execute(params![key, val_str])
.map_err(GeolithError::Sqlite)?;
}
}
}
tx.commit().map_err(GeolithError::Sqlite)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::geometry::mercator::TileCoord;
use tempfile::tempdir;
#[test]
fn mbtiles_output_name() {
let dir = tempdir().expect("tempdir");
let path = dir.path().join("test.mbtiles");
let output = MbtilesOutput::create(&path).expect("create");
assert_eq!(output.name(), "mbtiles");
}
#[test]
fn write_tiles_and_verify_count() {
let dir = tempdir().expect("tempdir");
let path = dir.path().join("test.mbtiles");
let mut output = MbtilesOutput::create(&path).expect("create");
let tile_data = b"fake-mvt-data";
for i in 0..10u32 {
output
.write_tile(TileCoord::new(3, i, 0), tile_data)
.expect("write tile");
}
let metadata = serde_json::json!({
"name": "test",
"format": "pbf",
"minzoom": "3",
"maxzoom": "3",
});
output.finalize(&metadata).expect("finalize");
let conn = Connection::open(&path).expect("open");
let count: i64 = conn
.query_row("SELECT COUNT(*) FROM tiles", [], |row| row.get(0))
.expect("count");
assert_eq!(count, 10);
}
#[test]
fn tms_y_flip_correct() {
let dir = tempdir().expect("tempdir");
let path = dir.path().join("test.mbtiles");
let mut output = MbtilesOutput::create(&path).expect("create");
output
.write_tile(TileCoord::new(2, 1, 0), b"data")
.expect("write");
output.finalize(&serde_json::json!({})).expect("finalize");
let conn = Connection::open(&path).expect("open");
let tms_y: i64 = conn
.query_row(
"SELECT tile_row FROM tiles WHERE zoom_level=2 AND tile_column=1",
[],
|row| row.get(0),
)
.expect("query");
assert_eq!(tms_y, 3, "TMS y should be 3 for slippy y=0 at z=2");
}
#[test]
fn tms_y_flip_z1() {
assert_eq!(MbtilesOutput::to_tms_y(0, 1), 1);
assert_eq!(MbtilesOutput::to_tms_y(1, 1), 0);
}
#[test]
fn tms_y_flip_z0() {
assert_eq!(MbtilesOutput::to_tms_y(0, 0), 0);
}
#[test]
fn metadata_written_correctly() {
let dir = tempdir().expect("tempdir");
let path = dir.path().join("test.mbtiles");
let mut output = MbtilesOutput::create(&path).expect("create");
let metadata = serde_json::json!({
"name": "my-tiles",
"format": "pbf",
"minzoom": "0",
"maxzoom": "15",
"bounds": "-180,-85,180,85",
});
output.finalize(&metadata).expect("finalize");
let conn = Connection::open(&path).expect("open");
let name: String = conn
.query_row("SELECT value FROM metadata WHERE name='name'", [], |row| {
row.get(0)
})
.expect("query name");
assert_eq!(name, "my-tiles");
let format: String = conn
.query_row(
"SELECT value FROM metadata WHERE name='format'",
[],
|row| row.get(0),
)
.expect("query format");
assert_eq!(format, "pbf");
}
#[test]
fn wal_mode_enabled() {
let dir = tempdir().expect("tempdir");
let path = dir.path().join("test.mbtiles");
let mut output = MbtilesOutput::create(&path).expect("create");
output.finalize(&serde_json::json!({})).expect("finalize");
let conn = Connection::open(&path).expect("open");
let mode: String = conn
.query_row("PRAGMA journal_mode", [], |row| row.get(0))
.expect("pragma");
assert_eq!(mode, "wal");
}
#[test]
fn batch_flush_on_large_write() {
let dir = tempdir().expect("tempdir");
let path = dir.path().join("test.mbtiles");
let mut output = MbtilesOutput::create(&path).expect("create");
for i in 0..(BATCH_SIZE + 100) as u32 {
let x = i % 1024;
let y = i / 1024;
output
.write_tile(TileCoord::new(10, x, y), b"data")
.expect("write");
}
output.finalize(&serde_json::json!({})).expect("finalize");
let conn = Connection::open(&path).expect("open");
let count: i64 = conn
.query_row("SELECT COUNT(*) FROM tiles", [], |row| row.get(0))
.expect("count");
assert_eq!(count, (BATCH_SIZE + 100) as i64);
}
}