Skip to main content

martin_core/tiles/postgres/
source.rs

1use std::collections::HashMap;
2
3use compact_str::CompactString;
4use deadpool_postgres::Object;
5use deadpool_postgres::tokio_postgres::types::{Json, ToSql, Type};
6use deadpool_postgres::tokio_postgres::{Row, Statement};
7use martin_tile_utils::{Encoding, TileCoord, TileData, TileGrid, TileInfo};
8use tilejson::TileJSON;
9use tracing::{debug, instrument};
10
11use crate::CacheZoomRange;
12use crate::tiles::postgres::PostgresError::{GetTileError, GetTileWithQueryError, PrepareQueryError};
13use crate::tiles::postgres::features::features_from_rows;
14use crate::tiles::postgres::pool::ActiveQueryGuard;
15use crate::tiles::postgres::utils::query_to_json;
16use crate::tiles::postgres::{
17    ActiveQueryRegistry, PostgresEngineInfo, PostgresError, PostgresPool, PostgresTileFeatures,
18};
19use crate::tiles::source::cap_zoom_range;
20use crate::tiles::{MartinCoreResult, Source, Tile, UrlQuery};
21
22#[derive(Clone, Debug)]
23/// `PostgreSQL` tile source that executes SQL queries to generate tiles.
24pub struct PostgresSource {
25    id: String,
26    tiler: PostgresTiler,
27    pool: PostgresPool,
28    tilejson: TileJSON,
29    tile_info: TileInfo,
30    cache_zoom: CacheZoomRange,
31    tile_grid: TileGrid,
32}
33
34/// What turns a source's rows into a tile.
35#[derive(Clone, Debug)]
36pub enum PostgresTiler {
37    /// A query that returns the tile itself: `ST_AsMVT` over a table, or a function.
38    Sql(PostgresSqlInfo),
39    /// A query that returns a table's features, which Martin's engine renders into its `layers`.
40    Engine(PostgresEngineInfo),
41}
42
43impl From<PostgresSqlInfo> for PostgresTiler {
44    fn from(info: PostgresSqlInfo) -> Self {
45        Self::Sql(info)
46    }
47}
48
49impl PostgresSource {
50    /// Creates a new `PostgreSQL` tile source.
51    #[must_use]
52    pub fn new(
53        id: String,
54        tiler: impl Into<PostgresTiler>,
55        mut tilejson: TileJSON,
56        pool: PostgresPool,
57        tile_info: TileInfo,
58        cache_zoom: CacheZoomRange,
59        tile_grid: TileGrid,
60    ) -> Self {
61        cap_zoom_range(&id, &mut tilejson);
62        Self {
63            id,
64            tiler: tiler.into(),
65            pool,
66            tilejson,
67            tile_info,
68            cache_zoom,
69            tile_grid,
70        }
71    }
72}
73
74impl PostgresSource {
75    /// The registry tracking this pool's in-flight queries, so a dropped request
76    /// can cancel the statement it started.
77    #[must_use]
78    pub fn active_query_registry(&self) -> ActiveQueryRegistry {
79        self.pool.active_query_registry().clone()
80    }
81
82    /// The features of a tile instead of its serialized bytes.
83    ///
84    /// `None` means this source has no row-per-feature form, which is every source but a table.
85    /// A caller that wants a tile format `PostGIS` does not produce itself can encode these
86    /// instead of taking an `ST_AsMVT` tile apart again.
87    ///
88    /// `keep_measures` asks for the M ordinates of polygons too, which `ST_AsMVTGeom` strips, at
89    /// the cost of a slower query. A caller whose format has nowhere to put them leaves it off.
90    pub async fn get_tile_features(
91        &self,
92        xyz: TileCoord,
93        url_query: Option<&UrlQuery>,
94        keep_measures: bool,
95    ) -> MartinCoreResult<Option<PostgresTileFeatures>> {
96        let Some(info) = self.sql_for(url_query) else {
97            return Ok(None);
98        };
99        let Some(row_query) = &info.row_query else {
100            return Ok(None);
101        };
102        let rows = self
103            .query_feature_rows(info, row_query, xyz, url_query, keep_measures)
104            .await?;
105        Ok(Some(PostgresTileFeatures {
106            layer_name: row_query.layer_name.clone(),
107            extent: row_query.extent,
108            features: features_from_rows(&rows, row_query.has_id_column)?,
109        }))
110    }
111}
112
113impl PostgresSource {
114    /// Every tile of the block a cache miss of `xyz` renders, `xyz` among them, or `None` when the
115    /// source does not prefetch.
116    pub async fn get_tile_block(&self, xyz: TileCoord) -> MartinCoreResult<Option<Vec<(TileCoord, Tile)>>> {
117        let PostgresTiler::Engine(engine) = &self.tiler else {
118            return Ok(None);
119        };
120        let Some(tiles) = engine.render_prefetch(&self.pool, &self.id, xyz).await? else {
121            return Ok(None);
122        };
123        Ok(Some(
124            tiles
125                .into_iter()
126                .map(|(coord, data)| (coord, Tile::new_hash_etag(data, self.tile_info)))
127                .collect(),
128        ))
129    }
130}
131
132impl Source for PostgresSource {
133    fn get_id(&self) -> &str {
134        &self.id
135    }
136
137    fn get_tilejson(&self) -> &TileJSON {
138        &self.tilejson
139    }
140
141    fn get_tile_info(&self) -> TileInfo {
142        self.tile_info
143    }
144
145    fn tile_grid(&self) -> &TileGrid {
146        &self.tile_grid
147    }
148
149    fn support_url_query(&self) -> bool {
150        self.sql().is_some_and(|info| info.use_url_query)
151    }
152
153    fn benefits_from_concurrent_scraping(&self) -> bool {
154        // pg does not parallelize queries well internally and having more requests in flight is thus beneficial
155        true
156    }
157
158    fn empty_tile_implies_empty_children(&self) -> bool {
159        self.sql().is_some_and(|info| info.empty_tile_implies_empty_children)
160    }
161
162    fn cache_zoom(&self) -> CacheZoomRange {
163        self.cache_zoom
164    }
165
166    async fn get_tile(&self, xyz: TileCoord, url_query: Option<&UrlQuery>) -> MartinCoreResult<TileData> {
167        let info = match &self.tiler {
168            PostgresTiler::Sql(info) => info.for_query(url_query),
169            PostgresTiler::Engine(engine) => {
170                return Ok(engine.render_tile(&self.pool, &self.id, xyz).await?);
171            }
172        };
173        Ok(self
174            .query_row(info, xyz, url_query)
175            .await?
176            .and_then(|row| row.get::<_, Option<Vec<u8>>>(0))
177            .map_or_default(TileData::from))
178    }
179
180    async fn get_tile_with_etag(&self, xyz: TileCoord, url_query: Option<&UrlQuery>) -> MartinCoreResult<Tile> {
181        let Some(info) = self.sql_for(url_query).filter(|info| info.has_etag_column) else {
182            let data = self.get_tile(xyz, url_query).await?;
183            let info = self.tile_info_for(&data);
184            return Ok(Tile::new_hash_etag(data, info));
185        };
186        let row = self.query_row(info, xyz, url_query).await?;
187        let data: TileData = row
188            .as_ref()
189            .and_then(|row| row.get::<_, Option<Vec<u8>>>(0))
190            .map_or_default(TileData::from);
191        let etag = row
192            .and_then(|row| row.get::<_, Option<String>>(1))
193            .map(CompactString::from);
194        let info = self.tile_info_for(&data);
195        match etag {
196            Some(etag) if !data.is_empty() && !etag.is_empty() => Ok(Tile::new_with_etag(data, info, etag)),
197            _ => Ok(Tile::new_hash_etag(data, info)),
198        }
199    }
200}
201
202impl PostgresSource {
203    /// The query returning a request's tile, by whether the request carries a query string.
204    /// `None` when the engine renders the tile.
205    fn sql_for(&self, url_query: Option<&UrlQuery>) -> Option<&PostgresSqlInfo> {
206        self.sql().map(|info| info.for_query(url_query))
207    }
208
209    /// The tile query, `None` when the engine renders the tiles.
210    fn sql(&self) -> Option<&PostgresSqlInfo> {
211        match &self.tiler {
212            PostgresTiler::Sql(info) => Some(info),
213            PostgresTiler::Engine(_) => None,
214        }
215    }
216
217    /// The declared tile info, with the encoding the bytes carry when the function compressed them.
218    fn tile_info_for(&self, data: &[u8]) -> TileInfo {
219        match Encoding::detect(data) {
220            Some(encoding) => TileInfo::new(self.tile_info.format, encoding),
221            None => self.tile_info,
222        }
223    }
224
225    /// Runs the tile query, returning the row when the query produced one.
226    #[instrument(
227        level = "debug",
228        skip_all,
229        fields(
230            source.id = %self.id,
231            tile.z = xyz.z(),
232            tile.x = xyz.x(),
233            tile.y = xyz.y(),
234        ),
235        err(Debug),
236    )]
237    async fn query_row(
238        &self,
239        info: &PostgresSqlInfo,
240        xyz: TileCoord,
241        url_query: Option<&UrlQuery>,
242    ) -> MartinCoreResult<Option<Row>> {
243        let query = self.tile_query(info, &info.sql_query, xyz, url_query).await?;
244        let row = query.conn.query_opt(&query.statement, &query.params()).await;
245        Ok(row.map_err(|e| self.run_error(e, xyz, url_query, info.use_url_query))?)
246    }
247
248    /// Runs the row-per-feature query, returning one row per feature of the tile.
249    #[instrument(
250        level = "debug",
251        skip_all,
252        fields(
253            source.id = %self.id,
254            tile.z = xyz.z(),
255            tile.x = xyz.x(),
256            tile.y = xyz.y(),
257        ),
258        err(Debug),
259    )]
260    async fn query_feature_rows(
261        &self,
262        info: &PostgresSqlInfo,
263        row_query: &PostgresRowQuery,
264        xyz: TileCoord,
265        url_query: Option<&UrlQuery>,
266        keep_measures: bool,
267    ) -> MartinCoreResult<Vec<Row>> {
268        let sql = if keep_measures {
269            &row_query.measured_sql_query
270        } else {
271            &row_query.sql_query
272        };
273        let query = self.tile_query(info, sql, xyz, url_query).await?;
274        let rows = query.conn.query(&query.statement, &query.params()).await;
275        Ok(rows.map_err(|e| self.run_error(e, xyz, url_query, info.use_url_query))?)
276    }
277
278    /// Prepares one of this source's tile queries and binds `xyz` and the query string to it.
279    ///
280    /// All of them take `z/x/y` and an optional query string, and differ only in what they
281    /// return, so every caller runs the statement itself.
282    async fn tile_query(
283        &self,
284        info: &PostgresSqlInfo,
285        sql: &str,
286        xyz: TileCoord,
287        url_query: Option<&UrlQuery>,
288    ) -> MartinCoreResult<TileQuery> {
289        let conn = self.pool.get().await?;
290        let guard = self.pool.active_query_registry().register(conn.cancel_token());
291
292        let param_types: &[Type] = if info.use_url_query {
293            &[Type::INT2, Type::INT8, Type::INT8, Type::JSON]
294        } else {
295            &[Type::INT2, Type::INT8, Type::INT8]
296        };
297        let statement = conn
298            .prepare_typed_cached(sql, param_types)
299            .await
300            .map_err(|e| PrepareQueryError {
301                source: e,
302                source_id: self.id.clone(),
303                signature: info.signature.clone(),
304                query: sql.to_owned(),
305            })?;
306
307        let url_query = if info.use_url_query {
308            let json = query_to_json(url_query);
309            debug!(sql = %sql, tile.coord = %xyz, url_query = ?json, "Running tile query");
310            Some(json)
311        } else {
312            debug!(sql = %sql, tile.coord = %xyz, "Running tile query");
313            None
314        };
315
316        Ok(TileQuery {
317            conn,
318            _cancel_guard: guard,
319            statement,
320            z: i16::from(xyz.z()),
321            x: i64::from(xyz.x()),
322            y: i64::from(xyz.y()),
323            url_query,
324        })
325    }
326
327    fn run_error(
328        &self,
329        e: deadpool_postgres::tokio_postgres::Error,
330        xyz: TileCoord,
331        url_query: Option<&UrlQuery>,
332        use_url_query: bool,
333    ) -> PostgresError {
334        if use_url_query {
335            GetTileWithQueryError(e, self.id.clone(), xyz, url_query.cloned())
336        } else {
337            GetTileError(e, self.id.clone(), xyz)
338        }
339    }
340}
341
342/// A prepared tile query with its parameters bound, ready to run on `conn`.
343///
344/// It holds the registry guard, so the statement stays cancellable for exactly as long as the
345/// query lives.
346struct TileQuery {
347    conn: Object,
348    _cancel_guard: ActiveQueryGuard,
349    statement: Statement,
350    z: i16,
351    x: i64,
352    y: i64,
353    url_query: Option<Json<HashMap<String, serde_json::Value>>>,
354}
355
356impl TileQuery {
357    fn params(&self) -> Vec<&(dyn ToSql + Sync)> {
358        let mut params: Vec<&(dyn ToSql + Sync)> = vec![&self.z, &self.x, &self.y];
359        if let Some(url_query) = &self.url_query {
360            params.push(url_query);
361        }
362        params
363    }
364}
365
366#[derive(Clone, Debug)]
367/// SQL query information for `PostgreSQL` tile sources.
368pub struct PostgresSqlInfo {
369    /// SQL query string.
370    pub sql_query: String,
371    /// Whether the query uses URL query parameters.
372    pub use_url_query: bool,
373    /// Whether an empty tile implies that all tiles below it are empty.
374    pub empty_tile_implies_empty_children: bool,
375    /// Signature of the query.
376    pub signature: String,
377    /// Whether the query's second column is the tile's `ETag`.
378    pub has_etag_column: bool,
379    /// The variant to run for a request without a query string, when the function has one.
380    pub queryless: Option<Box<Self>>,
381    /// The same tile as one row per feature, when the source can be read that way.
382    pub row_query: Option<PostgresRowQuery>,
383}
384
385/// The row-per-feature form of a tile query, and what its rows make up.
386///
387/// Unlike [`PostgresSqlInfo::sql_query`] this hands out the features themselves rather than an
388/// MVT blob, so a caller that wants another tile format does not have to take `ST_AsMVT`'s
389/// output apart again. Only table sources have one: a function source returns a blob built by
390/// user SQL, which has no row form.
391#[derive(Clone, Debug)]
392pub struct PostgresRowQuery {
393    /// SQL taking `$1/$2/$3` as `z/x/y` and returning one row per feature, the geometry first.
394    pub sql_query: String,
395    /// [`Self::sql_query`], but keeping the M ordinates of polygons, which `ST_AsMVTGeom` strips.
396    pub measured_sql_query: String,
397    /// Whether the second column is the feature id.
398    pub has_id_column: bool,
399    /// The name of the layer the features make up.
400    pub layer_name: String,
401    /// The tile extent the geometries are expressed in.
402    pub extent: u32,
403}
404
405impl PostgresSqlInfo {
406    /// Creates new SQL query information.
407    #[must_use]
408    pub const fn new(
409        query: String,
410        has_query_params: bool,
411        empty_tile_implies_empty_children: bool,
412        signature: String,
413        has_etag_column: bool,
414    ) -> Self {
415        Self {
416            sql_query: query,
417            use_url_query: has_query_params,
418            empty_tile_implies_empty_children,
419            signature,
420            has_etag_column,
421            queryless: None,
422            row_query: None,
423        }
424    }
425
426    /// This query with `queryless` answering the requests that carry no query string.
427    #[must_use]
428    pub fn with_queryless(mut self, queryless: Self) -> Self {
429        self.queryless = Some(Box::new(queryless));
430        self
431    }
432
433    /// This query with `row_query` as the row-per-feature form of the same tile.
434    #[must_use]
435    pub fn with_row_query(mut self, row_query: PostgresRowQuery) -> Self {
436        self.row_query = Some(row_query);
437        self
438    }
439
440    /// The query answering a request, by whether the request carries a query string.
441    fn for_query(&self, url_query: Option<&UrlQuery>) -> &Self {
442        match (&self.queryless, url_query) {
443            (Some(queryless), None) => queryless,
444            _ => self,
445        }
446    }
447}