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 pub keep_documents: bool,
34}
35
36impl ScanLayout {
37 fn first_property(&self) -> usize {
39 1 + usize::from(self.has_id)
40 }
41}
42
43impl From<PostgresError> for SourceError {
44 fn from(err: PostgresError) -> Self {
45 Self::Other(Box::new(err))
46 }
47}
48
49pub async fn open_scan_connection(pool: &PostgresPool) -> Result<Object, PostgresError> {
56 open_scan_transaction(pool, None).await
57}
58
59pub async fn open_scan_connections(pool: &PostgresPool, count: usize) -> Result<Vec<Object>, PostgresError> {
65 let first = open_scan_transaction(pool, None).await?;
66 if count <= 1 {
67 return Ok(vec![first]);
68 }
69 let snapshot = export_snapshot(&first).await?;
70 let mut conns = Vec::with_capacity(count);
71 conns.push(first);
72 for _ in 1..count {
73 conns.push(open_scan_transaction(pool, Some(&snapshot)).await?);
74 }
75 Ok(conns)
76}
77
78pub async fn export_snapshot(conn: &Client) -> Result<String, PostgresError> {
84 Ok(conn
85 .query_one("SELECT pg_export_snapshot()", &[])
86 .await
87 .map_err(|e| PostgresError::PostgresError(e, "exporting the scan snapshot"))?
88 .get(0))
89}
90
91pub async fn open_snapshot_connection(pool: &PostgresPool, snapshot: &str) -> Result<Object, PostgresError> {
97 open_scan_transaction(pool, Some(snapshot)).await
98}
99
100async fn open_scan_transaction(pool: &PostgresPool, snapshot: Option<&str>) -> Result<Object, PostgresError> {
101 let conn = pool.get().await?;
102 let import = snapshot.map_or_else(String::new, |id| {
103 format!("SET TRANSACTION SNAPSHOT '{}'; ", id.replace('\'', "''"))
104 });
105 conn.batch_execute(&format!(
106 "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY; {import}\
107 SET LOCAL max_parallel_workers_per_gather = 0; \
108 SET LOCAL synchronize_seqscans = off; \
109 SET LOCAL statement_timeout = 0; \
110 SET LOCAL idle_in_transaction_session_timeout = 0;"
111 ))
112 .await
113 .map_err(|e| PostgresError::PostgresError(e, "opening the scan transaction"))?;
114 Ok(conn)
115}
116
117pub async fn heap_blocks(conn: &Client, schema: &str, table: &str) -> Result<Option<u32>, PostgresError> {
124 let row = conn
125 .query_opt(
126 "SELECT pg_relation_size(c.oid) / current_setting('block_size')::bigint \
127 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
128 WHERE n.nspname = $1 AND c.relname = $2 AND c.relkind IN ('r', 'm') \
129 AND current_setting('server_version_num')::int >= 140000",
130 &[&schema, &table],
131 )
132 .await
133 .map_err(|e| PostgresError::PostgresError(e, "reading a table's heap size"))?;
134 Ok(row.map(|row| u32::try_from(row.get::<_, i64>(0)).unwrap_or(u32::MAX)))
135}
136
137pub async fn estimated_rows(conn: &Client, sql: &str) -> Result<Option<u64>, PostgresError> {
143 let lines = conn
144 .query(&format!("EXPLAIN {sql}"), &[])
145 .await
146 .map_err(|e| PostgresError::PostgresError(e, "planning a scan"))?;
147 let Some(top) = lines.first() else {
148 return Ok(None);
149 };
150 let plan: &str = top.get(0);
151 Ok(plan
152 .split_once(" rows=")
153 .and_then(|(_, rest)| rest.split(' ').next())
154 .and_then(|rows| rows.parse().ok()))
155}
156
157pub async fn scan_features<T: ?Sized + ToStatement>(
164 conn: &Client,
165 query: &T,
166 params: &[&(dyn ToSql + Sync)],
167 layout: &ScanLayout,
168 partition: u32,
169 keys: &KeyInterner,
170 mut emit: impl FnMut(FeatureBatch) -> SourceResult<()>,
171) -> SourceResult<()> {
172 let rows = conn
173 .query_raw(query, params.iter().copied())
174 .await
175 .map_err(|e| PostgresError::PostgresError(e, "starting a scan"))?;
176 let mut rows = std::pin::pin!(rows);
177 let mut batch = new_batch(layout, partition, 0);
178 let mut next_row = 0u64;
179 let mut arena = BatchBufferArena::default();
180 let mut types = Vec::new();
181 while let Some(row) = rows
182 .try_next()
183 .await
184 .map_err(|e| PostgresError::PostgresError(e, "reading a scan"))?
185 {
186 if next_row == 0 {
187 let first = layout.first_property();
188 types = PropType::of_columns(&row, first..first + layout.properties)?;
189 }
190 next_row += 1;
191 batch.features.push(feature(&row, layout, &types, keys, &mut arena)?);
192 if batch.features.len() == BATCH_FEATURES {
193 emit(std::mem::replace(&mut batch, new_batch(layout, partition, next_row)))?;
194 }
195 }
196 if !batch.features.is_empty() {
197 emit(batch)?;
198 }
199 Ok(())
200}
201
202fn new_batch(layout: &ScanLayout, partition: u32, first_row: u64) -> FeatureBatch {
203 FeatureBatch {
204 table: layout.table,
205 partition,
206 first_row,
207 crs: layout.crs,
208 features: Vec::with_capacity(BATCH_FEATURES),
209 }
210}
211
212fn feature(
213 row: &Row,
214 layout: &ScanLayout,
215 types: &[PropType],
216 keys: &KeyInterner,
217 arena: &mut BatchBufferArena,
218) -> SourceResult<SourceFeature> {
219 let wkb: Option<&[u8]> = row
220 .try_get(0)
221 .map_err(|e| PostgresError::PostgresError(e, "reading a scanned geometry"))?;
222 let geometry = Geometry::Wkb(arena.bytes(wkb.unwrap_or_default()));
223
224 let id = if layout.has_id { feature_id(row)? } else { None };
225 let mut props = Vec::with_capacity(layout.properties);
226 for ((pos, idx), &prop_type) in (0u32..).zip(layout.first_property()..).zip(types) {
227 if prop_type == PropType::Text {
228 let text: Option<&str> = row
229 .try_get(idx)
230 .map_err(|e| PostgresError::PostgresError(e, "reading a scanned property"))?;
231 if let Some(text) = text {
232 props.push((KeyId::new(pos), Prop::Str(arena.str(text))));
233 }
234 continue;
235 }
236 match prop_type.read(row, idx, "reading a scanned property")? {
237 PostgresProperty::Value(value) => {
238 if let Some(value) = prop(value) {
239 props.push((KeyId::new(pos), value));
240 }
241 }
242 #[cfg(feature = "unstable-mlt-v2")]
243 PostgresProperty::Json(document) if layout.keep_documents => {
244 if let Some(document) = document.filter(|document| !document.is_null()) {
245 props.push((KeyId::new(pos), Prop::Nested(arena.str(&document.to_string()))));
246 }
247 }
248 PostgresProperty::Json(document) => {
249 for (name, value) in st_asmvt_properties(document) {
250 if let Some(value) = prop(value) {
251 props.push((keys.intern(&name), value));
252 }
253 }
254 }
255 }
256 }
257 Ok(SourceFeature {
258 id,
259 geometry,
260 props,
261 relations: Vec::new(),
262 })
263}
264
265#[derive(Default)]
267struct BatchBufferArena(BytesMut);
268
269impl BatchBufferArena {
270 fn bytes(&mut self, bytes: &[u8]) -> Bytes {
272 if self.0.capacity() < bytes.len() {
273 self.0.reserve(bytes.len().max(ARENA_BYTES));
274 }
275 self.0.extend_from_slice(bytes);
276 self.0.split().freeze()
277 }
278
279 fn str(&mut self, text: &str) -> SourceStr {
281 SourceStr::try_from(self.bytes(text.as_bytes())).expect("copied from a str")
282 }
283}
284
285fn prop(value: PropValue) -> Option<Prop<SourceStr>> {
286 Some(match value {
287 PropValue::Bool(v) => Prop::Bool(v?),
288 PropValue::I8(v) => Prop::I64(v?.into()),
289 PropValue::U8(v) => Prop::I64(v?.into()),
290 PropValue::I32(v) => Prop::I64(v?.into()),
291 PropValue::U32(v) => Prop::I64(v?.into()),
292 PropValue::I64(v) => Prop::I64(v?),
293 PropValue::U64(v) => {
294 let v = v?;
295 i64::try_from(v).map_or_else(|_too_large| Prop::Str(v.to_string().into()), Prop::I64)
296 }
297 PropValue::F32(v) => Prop::F32(v?),
298 PropValue::F64(v) => Prop::F64(v?),
299 PropValue::Str(v) => Prop::Str(v?.into_string().into()),
300 })
301}