geolith 0.2.0

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
Documentation
//! `MBTiles` output format writer.
//!
//! Writes tiles to an `MBTiles` SQLite database using the standard 3-table schema:
//! `metadata`, `tiles`, and `tile_index`. WAL journal mode is enabled for
//! concurrent read access during writes.
//!
//! # `MBTiles` Spec
//!
//! `MBTiles` uses TMS y-axis convention (inverted from slippy map / XYZ):
//! `tms_y = (1 << zoom) - 1 - y`
//!
//! Standard schema (no tile deduplication — maximum tile server compatibility):
//! ```sql
//! CREATE TABLE metadata (name TEXT, value TEXT);
//! CREATE TABLE tiles (
//!     zoom_level INTEGER,
//!     tile_column INTEGER,
//!     tile_row INTEGER,
//!     tile_data BLOB
//! );
//! CREATE UNIQUE INDEX tile_index ON tiles (zoom_level, tile_column, tile_row);
//! ```
//!
//! # References
//!
//! - <https://github.com/mapbox/mbtiles-spec/blob/master/1.3/spec.md>

use rusqlite::{Connection, params};

use crate::error::{GeolithError, Result};
use crate::geometry::mercator::TileCoord;
use crate::output::format::OutputFormat;

/// Number of tiles to batch in a single SQLite transaction.
const BATCH_SIZE: usize = 1000;

/// `MBTiles` output format writer.
///
/// Writes tiles to a SQLite database using the standard `MBTiles` 3-table schema.
/// Uses WAL journal mode for concurrent reads during writes.
///
/// # Standard Schema
///
/// Does NOT implement the `tile_data` + `tile_shallow` dedup view pattern.
/// Uses the canonical 3-table spec for maximum tile server compatibility
/// (tileserver-gl, martin, mbtiles-spec tools all expect this schema).
pub struct MbtilesOutput {
    conn: Connection,
    pending: Vec<(u8, u32, u32, Vec<u8>)>, // (zoom, x, tms_y, data)
    tiles_written: u64,
}

impl MbtilesOutput {
    /// Creates a new `MBTiles` database at the given path.
    ///
    /// Initializes the standard 3-table schema and enables WAL mode.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be created or the schema cannot
    /// be initialized.
    pub fn create(path: &std::path::Path) -> Result<Self> {
        let conn = Connection::open(path).map_err(GeolithError::Sqlite)?;

        // Enable WAL mode for concurrent reads during writes
        conn.execute_batch("PRAGMA journal_mode=WAL;")
            .map_err(GeolithError::Sqlite)?;

        // Optimize for bulk writes
        conn.execute_batch(
            "PRAGMA synchronous=NORMAL;
             PRAGMA page_size=65536;
             PRAGMA cache_size=-65536;",
        )
        .map_err(GeolithError::Sqlite)?;

        // Create standard MBTiles schema
        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,
        })
    }

    /// Returns the number of tiles written so far.
    #[must_use]
    pub const fn tiles_written(&self) -> u64 {
        self.tiles_written
    }

    /// Flushes pending tiles to the database in a single transaction.
    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(())
    }

    /// Converts slippy map y to TMS y (inverted y-axis).
    ///
    /// `MBTiles` uses TMS convention: `tms_y = (1 << zoom) - 1 - y`
    #[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<()> {
        // Flush any remaining pending tiles
        self.flush_pending()?;

        // Write metadata entries
        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)?;

            // Write standard MBTiles metadata fields from JSON
            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");

        // Verify tile count via SQLite
        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");

        // Write tile at z=2, x=1, y=0 (slippy map)
        // TMS y = 2^2 - 1 - 0 = 3
        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() {
        // z=1: 2^1 - 1 - y
        assert_eq!(MbtilesOutput::to_tms_y(0, 1), 1);
        assert_eq!(MbtilesOutput::to_tms_y(1, 1), 0);
    }

    #[test]
    fn tms_y_flip_z0() {
        // z=0: only one tile, y=0 → tms_y=0
        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");

        // Write more than BATCH_SIZE tiles to trigger auto-flush
        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);
    }
}