1use std::error::Error;
4use std::io::Write as _;
5use std::thread::{self, JoinHandle};
6
7use crossbeam_channel::{Receiver, Sender, bounded};
8use osmflow::Timestamp;
9use postgres::types::{FromSql, Type};
10use postgres::{CopyInWriter, GenericClient};
11
12use crate::SyncError;
13use crate::copy::{HEADER, Rows, TRAILER};
14pub(crate) use crate::tls::connect;
15use crate::varint::unpack_ids;
16
17pub(crate) const SCHEMA_VERSION: i32 = 3;
19
20#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct DbState {
23 pub id: i64,
25 pub rev: i64,
27 pub url: Option<String>,
29 pub sequence: i64,
31 pub timestamp: Option<Timestamp>,
33 pub tables: TableLayout,
35}
36
37#[derive(
47 Debug,
48 Clone,
49 Copy,
50 Default,
51 PartialEq,
52 Eq,
53 Hash,
54 strum::AsRefStr,
55 strum::Display,
56 strum::EnumString,
57 strum::VariantNames,
58)]
59#[strum(serialize_all = "lowercase")]
60pub enum TableLayout {
61 #[default]
69 Packed,
70 Plain,
73}
74
75pub(crate) struct LayoutSql {
77 pub(crate) point: &'static str,
79 pub(crate) line: &'static str,
81 pub(crate) ids: &'static str,
83 pub(crate) after: String,
86}
87
88impl TableLayout {
89 pub(crate) fn sql(self, postgis: &str) -> LayoutSql {
94 let s = format!("\"{}\"", postgis.replace('"', "\"\""));
95 match self {
96 Self::Packed => {
97 let view = |t: Table| {
98 let columns = t
99 .columns()
100 .split(", ")
101 .map(|c| match (t, c) {
102 (Table::Ways, "nodes") => "osm.node_ids(nodes) AS nodes",
103 (_, "geom") => "osm.geom(geom) AS geom",
104 _ => c,
105 })
106 .collect::<Vec<_>>()
107 .join(", ");
108 format!(
109 "CREATE VIEW {} AS SELECT {columns} FROM {};",
110 <&str>::from(t),
111 t.name(self)
112 )
113 };
114 LayoutSql {
115 point: "bytea",
116 line: "bytea",
117 ids: "bytea",
118 after: format!(
119 "CREATE FUNCTION osm.geom(g bytea) RETURNS {s}.geometry LANGUAGE sql IMMUTABLE PARALLEL SAFE \
120 AS $$ SELECT {s}.ST_SetSRID({s}.ST_GeomFromTWKB(g), 4326) $$;\n{}\n{}\n{}",
121 include_str!("node_ids.sql"),
122 view(Table::Nodes),
123 view(Table::Ways)
124 ),
125 }
126 }
127 Self::Plain => LayoutSql {
128 point: "geometry(Point, 4326)",
129 line: "geometry(LineString, 4326)",
130 ids: "int8[]",
131 after: String::new(),
132 },
133 }
134 }
135}
136
137#[derive(Debug, Clone, Default, PartialEq, Eq)]
150pub struct NodeIds(pub Vec<i64>);
151
152impl<'a> FromSql<'a> for NodeIds {
153 fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<Self, Box<dyn Error + Sync + Send>> {
154 if *ty == Type::BYTEA {
155 Ok(Self(unpack_ids(raw)))
156 } else {
157 Vec::from_sql(ty, raw).map(Self)
158 }
159 }
160
161 fn accepts(ty: &Type) -> bool {
162 *ty == Type::BYTEA || *ty == Type::INT8_ARRAY
163 }
164}
165
166impl DbState {
167 pub(crate) fn read(client: &mut impl GenericClient) -> Result<Self, SyncError> {
169 let exists: bool = client
170 .query_one("SELECT to_regclass('osm.state') IS NOT NULL", &[])?
171 .get(0);
172 if !exists {
173 return Err(SyncError::state(
174 "the database has no osm schema: import a PBF file first",
175 ));
176 }
177 let row = client
178 .query_opt(
179 "SELECT id, version, rev, url, sequence, (extract(epoch FROM timestamp) * 1000)::int8, tables \
180 FROM osm.state",
181 &[],
182 )?
183 .ok_or_else(|| SyncError::state("the import did not finish: run it again, replacing the osm schema"))?;
184 let version: i32 = row.get(1);
185 if version != SCHEMA_VERSION {
186 return Err(SyncError::state(format!(
187 "the osm schema has format {version}, but this osmflow-sync reads {SCHEMA_VERSION}: import again, \
188 replacing the osm schema"
189 )));
190 }
191 Ok(Self {
192 id: row.get(0),
193 rev: row.get::<_, i32>(2).into(),
194 url: row.get(3),
195 sequence: row.get(4),
196 timestamp: row.get::<_, Option<i64>>(5).map(Timestamp::from_millis),
197 tables: {
198 let name: &str = row.get(6);
199 name.parse().map_err(|_| {
200 SyncError::state(format!("unknown table layout {name:?} in osm.state"))
201 })?
202 },
203 })
204 }
205}
206
207#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)]
210#[strum(serialize_all = "lowercase", prefix = "osm.")]
211pub(crate) enum Table {
212 Nodes,
213 Ways,
214 Relations,
215}
216
217impl Table {
218 pub(crate) fn name(self, layout: TableLayout) -> &'static str {
221 match (self, layout) {
222 (Self::Nodes, TableLayout::Packed) => "osm.nodes_packed",
223 (Self::Ways, TableLayout::Packed) => "osm.ways_packed",
224 _ => self.into(),
225 }
226 }
227
228 pub(crate) fn columns(self) -> &'static str {
230 match self {
231 Self::Nodes => "id, changeset, ts, version, rev, tags, geom",
232 Self::Ways => "id, changeset, ts, version, minor, rev, tags, nodes, geom",
233 Self::Relations => {
234 "id, changeset, ts, version, rev, tags, member_types, member_ids, member_roles"
235 }
236 }
237 }
238}
239
240pub(crate) fn copy(
242 client: &mut impl GenericClient,
243 table: &str,
244 columns: &str,
245 rows: &Rows,
246) -> Result<(), SyncError> {
247 let mut w = copy_in(client, table, columns)?;
248 w.write_all(&rows.buf)?;
249 copy_end(w)
250}
251
252fn copy_in<'a>(
254 client: &'a mut impl GenericClient,
255 table: &str,
256 columns: &str,
257) -> Result<CopyInWriter<'a>, SyncError> {
258 let mut w = client.copy_in(&format!(
259 "COPY {table} ({columns}) FROM STDIN (FORMAT binary)"
260 ))?;
261 w.write_all(HEADER)?;
262 Ok(w)
263}
264
265fn copy_end(mut w: CopyInWriter<'_>) -> Result<(), SyncError> {
266 w.write_all(TRAILER)?;
267 w.finish()?;
268 Ok(())
269}
270
271pub(crate) struct Writers {
273 tx: Sender<(Table, Vec<u8>)>,
274 threads: Vec<JoinHandle<Result<(), SyncError>>>,
275}
276
277impl Writers {
278 pub(crate) fn start(
279 url: &str,
280 connections: usize,
281 layout: TableLayout,
282 ) -> Result<Self, SyncError> {
283 let (tx, rx) = bounded(connections * 4);
284 let threads = (0..connections.max(1))
285 .map(|i| {
286 let (url, rx) = (url.to_owned(), rx.clone());
287 thread::Builder::new()
288 .name(format!("osmflow-copy-{i}"))
289 .spawn(move || write(&url, &rx, layout))
290 })
291 .collect::<Result<_, _>>()?;
292 Ok(Self { tx, threads })
293 }
294
295 pub(crate) fn send(&self, table: Table, rows: Rows) -> bool {
298 rows.buf.is_empty() || self.tx.send((table, rows.buf)).is_ok()
299 }
300
301 pub(crate) fn finish(self) -> Result<(), SyncError> {
303 drop(self.tx);
304 let mut result = Ok(());
305 for t in self.threads {
306 let r = t
307 .join()
308 .unwrap_or_else(|_| Err(SyncError::state("a COPY thread panicked")));
309 result = result.and(r);
310 }
311 result
312 }
313}
314
315fn write(url: &str, rx: &Receiver<(Table, Vec<u8>)>, layout: TableLayout) -> Result<(), SyncError> {
317 let mut client = connect(url)?;
318 client.batch_execute("SET synchronous_commit = off; SET default_toast_compression = lz4")?;
319 let mut next = rx.recv().ok();
320 while let Some((table, buf)) = next {
321 let mut w = copy_in(&mut client, table.name(layout), table.columns())?;
322 w.write_all(&buf)?;
323 loop {
324 next = rx.recv().ok();
325 match &next {
326 Some((t, buf)) if *t == table => w.write_all(buf)?,
327 _ => break,
328 }
329 }
330 copy_end(w)?;
331 }
332 Ok(())
333}