martin_core/tiles/postgres/
scan.rs1use bytes::{Bytes, BytesMut};
4use deadpool_postgres::Object;
5use deadpool_postgres::tokio_postgres::types::ToSql;
6use deadpool_postgres::tokio_postgres::{Client, Row, ToStatement};
7use futures::TryStreamExt as _;
8use martin_tilegen::props::{KeyId, KeyInterner, Prop, SourceStr};
9use martin_tilegen::source::{Crs, FeatureBatch, Geometry, SourceError, SourceFeature, SourceResult};
10use mlt_core::PropValue;
11
12use super::features::{PropType, feature_id};
13use super::mlt_encoder::st_asmvt_properties;
14use super::{PostgresError, PostgresPool, PostgresProperty};
15
16const BATCH_FEATURES: usize = 1024;
17const ARENA_BYTES: usize = 256 << 10;
18
19#[derive(Clone, Debug)]
22pub struct ScanLayout {
23 pub table: u16,
25 pub crs: Crs,
27 pub has_id: bool,
29 pub properties: usize,
31}
32
33impl ScanLayout {
34 fn first_property(&self) -> usize {
36 1 + usize::from(self.has_id)
37 }
38}
39
40impl From<PostgresError> for SourceError {
41 fn from(err: PostgresError) -> Self {
42 Self::Other(Box::new(err))
43 }
44}
45
46pub async fn open_scan_connection(pool: &PostgresPool) -> Result<Object, PostgresError> {
53 open_scan_transaction(pool, None).await
54}
55
56pub async fn open_scan_connections(pool: &PostgresPool, count: usize) -> Result<Vec<Object>, PostgresError> {
62 let first = open_scan_transaction(pool, None).await?;
63 if count <= 1 {
64 return Ok(vec![first]);
65 }
66 let snapshot = export_snapshot(&first).await?;
67 let mut conns = Vec::with_capacity(count);
68 conns.push(first);
69 for _ in 1..count {
70 conns.push(open_scan_transaction(pool, Some(&snapshot)).await?);
71 }
72 Ok(conns)
73}
74
75pub async fn export_snapshot(conn: &Client) -> Result<String, PostgresError> {
81 Ok(conn
82 .query_one("SELECT pg_export_snapshot()", &[])
83 .await
84 .map_err(|e| PostgresError::PostgresError(e, "exporting the scan snapshot"))?
85 .get(0))
86}
87
88pub async fn open_snapshot_connection(pool: &PostgresPool, snapshot: &str) -> Result<Object, PostgresError> {
94 open_scan_transaction(pool, Some(snapshot)).await
95}
96
97async fn open_scan_transaction(pool: &PostgresPool, snapshot: Option<&str>) -> Result<Object, PostgresError> {
98 let conn = pool.get().await?;
99 let import = snapshot.map_or_else(String::new, |id| {
100 format!("SET TRANSACTION SNAPSHOT '{}'; ", id.replace('\'', "''"))
101 });
102 conn.batch_execute(&format!(
103 "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY; {import}\
104 SET LOCAL max_parallel_workers_per_gather = 0; \
105 SET LOCAL synchronize_seqscans = off; \
106 SET LOCAL statement_timeout = 0; \
107 SET LOCAL idle_in_transaction_session_timeout = 0;"
108 ))
109 .await
110 .map_err(|e| PostgresError::PostgresError(e, "opening the scan transaction"))?;
111 Ok(conn)
112}
113
114pub async fn heap_blocks(conn: &Client, schema: &str, table: &str) -> Result<Option<u32>, PostgresError> {
121 let row = conn
122 .query_opt(
123 "SELECT pg_relation_size(c.oid) / current_setting('block_size')::bigint \
124 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
125 WHERE n.nspname = $1 AND c.relname = $2 AND c.relkind IN ('r', 'm') \
126 AND current_setting('server_version_num')::int >= 140000",
127 &[&schema, &table],
128 )
129 .await
130 .map_err(|e| PostgresError::PostgresError(e, "reading a table's heap size"))?;
131 Ok(row.map(|row| u32::try_from(row.get::<_, i64>(0)).unwrap_or(u32::MAX)))
132}
133
134pub async fn estimated_rows(conn: &Client, sql: &str) -> Result<Option<u64>, PostgresError> {
140 let lines = conn
141 .query(&format!("EXPLAIN {sql}"), &[])
142 .await
143 .map_err(|e| PostgresError::PostgresError(e, "planning a scan"))?;
144 let Some(top) = lines.first() else {
145 return Ok(None);
146 };
147 let plan: &str = top.get(0);
148 Ok(plan
149 .split_once(" rows=")
150 .and_then(|(_, rest)| rest.split(' ').next())
151 .and_then(|rows| rows.parse().ok()))
152}
153
154pub async fn scan_features<T: ?Sized + ToStatement>(
161 conn: &Client,
162 query: &T,
163 params: &[&(dyn ToSql + Sync)],
164 layout: &ScanLayout,
165 partition: u32,
166 keys: &KeyInterner,
167 mut emit: impl FnMut(FeatureBatch) -> SourceResult<()>,
168) -> SourceResult<()> {
169 let rows = conn
170 .query_raw(query, params.iter().copied())
171 .await
172 .map_err(|e| PostgresError::PostgresError(e, "starting a scan"))?;
173 let mut rows = std::pin::pin!(rows);
174 let mut batch = new_batch(layout, partition, 0);
175 let mut next_row = 0u64;
176 let mut arena = BatchBufferArena::default();
177 let mut types = Vec::new();
178 while let Some(row) = rows
179 .try_next()
180 .await
181 .map_err(|e| PostgresError::PostgresError(e, "reading a scan"))?
182 {
183 if next_row == 0 {
184 let first = layout.first_property();
185 types = PropType::of_columns(&row, first..first + layout.properties)?;
186 }
187 next_row += 1;
188 batch.features.push(feature(&row, layout, &types, keys, &mut arena)?);
189 if batch.features.len() == BATCH_FEATURES {
190 emit(std::mem::replace(&mut batch, new_batch(layout, partition, next_row)))?;
191 }
192 }
193 if !batch.features.is_empty() {
194 emit(batch)?;
195 }
196 Ok(())
197}
198
199fn new_batch(layout: &ScanLayout, partition: u32, first_row: u64) -> FeatureBatch {
200 FeatureBatch {
201 table: layout.table,
202 partition,
203 first_row,
204 crs: layout.crs,
205 features: Vec::with_capacity(BATCH_FEATURES),
206 }
207}
208
209fn feature(
210 row: &Row,
211 layout: &ScanLayout,
212 types: &[PropType],
213 keys: &KeyInterner,
214 arena: &mut BatchBufferArena,
215) -> SourceResult<SourceFeature> {
216 let wkb: Option<&[u8]> = row
217 .try_get(0)
218 .map_err(|e| PostgresError::PostgresError(e, "reading a scanned geometry"))?;
219 let geometry = Geometry::Wkb(arena.bytes(wkb.unwrap_or_default()));
220
221 let id = if layout.has_id { feature_id(row)? } else { None };
222 let mut props = Vec::with_capacity(layout.properties);
223 for ((pos, idx), &prop_type) in (0u32..).zip(layout.first_property()..).zip(types) {
224 if prop_type == PropType::Text {
225 let text: Option<&str> = row
226 .try_get(idx)
227 .map_err(|e| PostgresError::PostgresError(e, "reading a scanned property"))?;
228 if let Some(text) = text {
229 props.push((KeyId::new(pos), Prop::Str(arena.str(text))));
230 }
231 continue;
232 }
233 match prop_type.read(row, idx, "reading a scanned property")? {
234 PostgresProperty::Value(value) => {
235 if let Some(value) = prop(value) {
236 props.push((KeyId::new(pos), value));
237 }
238 }
239 PostgresProperty::Json(document) => {
240 for (name, value) in st_asmvt_properties(document) {
241 if let Some(value) = prop(value) {
242 props.push((keys.intern(&name), value));
243 }
244 }
245 }
246 }
247 }
248 Ok(SourceFeature { id, geometry, props })
249}
250
251#[derive(Default)]
253struct BatchBufferArena(BytesMut);
254
255impl BatchBufferArena {
256 fn bytes(&mut self, bytes: &[u8]) -> Bytes {
258 if self.0.capacity() < bytes.len() {
259 self.0.reserve(bytes.len().max(ARENA_BYTES));
260 }
261 self.0.extend_from_slice(bytes);
262 self.0.split().freeze()
263 }
264
265 fn str(&mut self, text: &str) -> SourceStr {
267 SourceStr::try_from(self.bytes(text.as_bytes())).expect("copied from a str")
268 }
269}
270
271fn prop(value: PropValue) -> Option<Prop<SourceStr>> {
272 Some(match value {
273 PropValue::Bool(v) => Prop::Bool(v?),
274 PropValue::I8(v) => Prop::I64(v?.into()),
275 PropValue::U8(v) => Prop::I64(v?.into()),
276 PropValue::I32(v) => Prop::I64(v?.into()),
277 PropValue::U32(v) => Prop::I64(v?.into()),
278 PropValue::I64(v) => Prop::I64(v?),
279 PropValue::U64(v) => {
280 let v = v?;
281 i64::try_from(v).map_or_else(|_too_large| Prop::Str(v.to_string().into()), Prop::I64)
282 }
283 PropValue::F32(v) => Prop::F32(v?),
284 PropValue::F64(v) => Prop::F64(v?),
285 PropValue::Str(v) => Prop::Str(v?.into_string().into()),
286 })
287}