Skip to main content

martin_core/tiles/postgres/
features.rs

1//! Tile features read one row per feature
2
3use std::ops::Range;
4
5use compact_str::CompactString;
6use deadpool_postgres::tokio_postgres::Row;
7use martin_tilegen::plan::{ColumnDef, ValueKind};
8use mlt_core::PropValue;
9use mlt_core::geo_types::Geometry;
10use serde_json::Value;
11
12use crate::tiles::postgres::PostgresError::{PostgresError as PgError, UnsupportedPropertyType};
13use crate::tiles::postgres::{PostgresResult, parse_tile_wkb};
14
15/// One feature of a tile, in tile coordinate space.
16#[derive(Debug, Clone, PartialEq)]
17pub struct PostgresFeature {
18    /// The feature id, when the source has an id column that held a non-negative value.
19    pub id: Option<u64>,
20    /// The geometry, already clipped and projected into tile space.
21    pub geometry: Geometry<i32>,
22    /// One M ordinate per vertex of [`Self::geometry`], when the source geometry is measured.
23    pub m_values: Option<Vec<f64>>,
24    /// The property columns, in the order the query selected them.
25    pub properties: Vec<(CompactString, PostgresProperty)>,
26}
27
28/// One property column's value for one feature.
29#[derive(Debug, Clone, PartialEq)]
30pub enum PostgresProperty {
31    /// A value of a type a tile column holds.
32    Value(PropValue),
33    /// A `jsonb` document, whose shape the tile format decides how to keep.
34    Json(Option<Value>),
35}
36
37impl From<PropValue> for PostgresProperty {
38    fn from(value: PropValue) -> Self {
39        Self::Value(value)
40    }
41}
42
43/// Everything one tile's worth of rows makes up: a single layer of features.
44#[derive(Debug, Clone, PartialEq)]
45pub struct PostgresTileFeatures {
46    /// The name of the layer the features belong to.
47    pub layer_name: String,
48    /// The tile extent the geometries are expressed in.
49    pub extent: u32,
50    /// The features, in the order the rows arrived.
51    pub features: Vec<PostgresFeature>,
52}
53
54/// A `PostgreSQL` column type that reaches a tile as a typed property.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub(super) enum PropType {
57    Bool,
58    Int16,
59    Int32,
60    Int64,
61    Float,
62    Double,
63    Text,
64    Json,
65}
66
67impl PropType {
68    /// The type a column of this `PostgreSQL` type holds, or `None` for one that needs a cast.
69    fn of(pg_type: &str) -> Option<Self> {
70        Some(match pg_type {
71            "bool" => Self::Bool,
72            "int2" => Self::Int16,
73            "int4" => Self::Int32,
74            "int8" => Self::Int64,
75            "float4" => Self::Float,
76            "float8" => Self::Double,
77            "text" | "varchar" | "bpchar" | "name" => Self::Text,
78            "jsonb" => Self::Json,
79            _ => return None,
80        })
81    }
82
83    /// The type the row's column `idx` reaches a tile as.
84    pub(super) fn of_column(row: &Row, idx: usize) -> PostgresResult<Self> {
85        let column = &row.columns()[idx];
86        Self::of(column.type_().name()).ok_or_else(|| UnsupportedPropertyType {
87            column: column.name().to_owned(),
88            pg_type: column.type_().name().to_owned(),
89        })
90    }
91
92    /// The types of the row's `columns`, the same for every row of one query.
93    pub(super) fn of_columns(row: &Row, columns: Range<usize>) -> PostgresResult<Vec<Self>> {
94        columns.map(|idx| Self::of_column(row, idx)).collect()
95    }
96
97    /// The row's value in column `idx`, read as this type.
98    pub(super) fn read(self, row: &Row, idx: usize, context: &'static str) -> PostgresResult<PostgresProperty> {
99        let read = |e| PgError(e, context);
100        Ok(PostgresProperty::Value(match self {
101            Self::Json => return Ok(PostgresProperty::Json(row.try_get(idx).map_err(read)?)),
102            Self::Bool => PropValue::Bool(row.try_get(idx).map_err(read)?),
103            Self::Int16 => PropValue::I64(row.try_get::<_, Option<i16>>(idx).map_err(read)?.map(i64::from)),
104            Self::Int32 => PropValue::I64(row.try_get::<_, Option<i32>>(idx).map_err(read)?.map(i64::from)),
105            Self::Int64 => PropValue::I64(row.try_get(idx).map_err(read)?),
106            Self::Float => PropValue::F32(row.try_get(idx).map_err(read)?),
107            Self::Double => PropValue::F64(row.try_get(idx).map_err(read)?),
108            Self::Text => PropValue::Str(
109                row.try_get::<_, Option<&str>>(idx)
110                    .map_err(read)?
111                    .map(CompactString::from),
112            ),
113        }))
114    }
115}
116
117/// A scanned column of this `PostgreSQL` type, as a plan sees it.
118#[must_use]
119pub fn column_def(column: String, pg_type: &str) -> ColumnDef {
120    let kind = match PropType::of(pg_type) {
121        Some(PropType::Json) => return ColumnDef::Keys(column),
122        Some(PropType::Text) if matches!(pg_type, "bpchar" | "name") => None,
123        Some(PropType::Bool) => Some(ValueKind::Bool),
124        Some(PropType::Int16 | PropType::Int32 | PropType::Int64) => Some(ValueKind::Int),
125        Some(PropType::Float | PropType::Double) => Some(ValueKind::Float),
126        Some(PropType::Text) | None => Some(ValueKind::String),
127    };
128    ColumnDef::Value(column, kind)
129}
130
131/// Whether a column of this `PostgreSQL` type reaches a tile as a typed property.
132#[must_use]
133pub fn is_typed_property(pg_type: &str) -> bool {
134    PropType::of(pg_type).is_some()
135}
136
137/// Decodes the rows of one tile query into features.
138pub(crate) fn features_from_rows(rows: &[Row], has_id_column: bool) -> PostgresResult<Vec<PostgresFeature>> {
139    let first_property = 1 + usize::from(has_id_column);
140    let types = match rows.first() {
141        Some(row) => PropType::of_columns(row, first_property..row.columns().len())?,
142        None => Vec::new(),
143    };
144    let mut features = Vec::with_capacity(rows.len());
145    for row in rows {
146        let wkb: Option<&[u8]> = row
147            .try_get(0)
148            .map_err(|e| PgError(e, "reading a tile feature's geometry"))?;
149        let Some(wkb) = wkb else {
150            continue;
151        };
152        let (geometry, m_values) = parse_tile_wkb(wkb)?;
153        let id = if has_id_column { feature_id(row)? } else { None };
154        let mut properties = Vec::with_capacity(types.len());
155        for (idx, prop_type) in (first_property..).zip(&types) {
156            properties.push((
157                CompactString::new(row.columns()[idx].name()),
158                prop_type.read(row, idx, "reading a tile property")?,
159            ));
160        }
161        features.push(PostgresFeature {
162            id,
163            geometry,
164            m_values,
165            properties,
166        });
167    }
168    Ok(features)
169}
170
171/// The feature id in the row's second column, following `ST_AsMVT`.
172pub(super) fn feature_id(row: &Row) -> PostgresResult<Option<u64>> {
173    let column = &row.columns()[1];
174    let value = PropType::of_column(row, 1)?.read(row, 1, "reading a tile feature's id")?;
175    let PostgresProperty::Value(PropValue::I64(value)) = value else {
176        return Err(UnsupportedPropertyType {
177            column: column.name().to_owned(),
178            pg_type: column.type_().name().to_owned(),
179        });
180    };
181    Ok(value.and_then(|v| u64::try_from(v).ok()))
182}