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