1use std::io::Write as _;
4use std::thread::{self, JoinHandle};
5
6use crossbeam_channel::{Receiver, Sender, bounded};
7use osmflow::Timestamp;
8use postgres::{Client, CopyInWriter, GenericClient, NoTls};
9
10use crate::SyncError;
11use crate::copy::{HEADER, Rows, TRAILER};
12
13pub(crate) const SCHEMA_VERSION: i32 = 2;
15
16pub(crate) fn connect(url: &str) -> Result<Client, SyncError> {
17 Ok(Client::connect(url, NoTls)?)
18}
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 geometry: GeometryFormat,
35}
36
37#[derive(
44 Debug,
45 Clone,
46 Copy,
47 Default,
48 PartialEq,
49 Eq,
50 Hash,
51 strum::AsRefStr,
52 strum::Display,
53 strum::EnumString,
54 strum::VariantNames,
55)]
56#[strum(serialize_all = "lowercase")]
57pub enum GeometryFormat {
58 #[default]
61 Twkb,
62 Wkb,
64}
65
66impl GeometryFormat {
67 pub(crate) fn sql(self, postgis: &str) -> (&'static str, &'static str, String) {
72 let s = format!("\"{}\"", postgis.replace('"', "\"\""));
73 match self {
74 Self::Twkb => (
75 "bytea",
76 "bytea",
77 format!(
78 "CREATE FUNCTION osm.geom(g bytea) RETURNS {s}.geometry LANGUAGE sql IMMUTABLE PARALLEL SAFE \
79 AS $$ SELECT {s}.ST_SetSRID({s}.ST_GeomFromTWKB(g), 4326) $$;"
80 ),
81 ),
82 Self::Wkb => (
83 "geometry(Point, 4326)",
84 "geometry(LineString, 4326)",
85 format!(
86 "CREATE FUNCTION osm.geom(g {s}.geometry) RETURNS {s}.geometry LANGUAGE sql IMMUTABLE \
87 PARALLEL SAFE AS $$ SELECT g $$;"
88 ),
89 ),
90 }
91 }
92}
93
94impl DbState {
95 pub(crate) fn read(client: &mut impl GenericClient) -> Result<Self, SyncError> {
97 let exists: bool = client
98 .query_one("SELECT to_regclass('osm.state') IS NOT NULL", &[])?
99 .get(0);
100 if !exists {
101 return Err(SyncError::state(
102 "the database has no osm schema: import a PBF file first",
103 ));
104 }
105 let row = client
106 .query_opt(
107 "SELECT id, version, rev, url, sequence, (extract(epoch FROM timestamp) * 1000)::int8, geometry \
108 FROM osm.state",
109 &[],
110 )?
111 .ok_or_else(|| SyncError::state("the import did not finish: run it again, replacing the osm schema"))?;
112 let version: i32 = row.get(1);
113 if version != SCHEMA_VERSION {
114 return Err(SyncError::state(format!(
115 "the osm schema has format {version}, but this osmflow-sync reads {SCHEMA_VERSION}"
116 )));
117 }
118 Ok(Self {
119 id: row.get(0),
120 rev: row.get(2),
121 url: row.get(3),
122 sequence: row.get(4),
123 timestamp: row.get::<_, Option<i64>>(5).map(Timestamp::from_millis),
124 geometry: {
125 let name: &str = row.get(6);
126 name.parse().map_err(|_| {
127 SyncError::state(format!("unknown geometry format {name:?} in osm.state"))
128 })?
129 },
130 })
131 }
132}
133
134#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display, strum::IntoStaticStr)]
136#[strum(serialize_all = "lowercase", prefix = "osm.")]
137pub(crate) enum Table {
138 Nodes,
139 Ways,
140 Relations,
141}
142
143impl Table {
144 pub(crate) fn columns(self) -> &'static str {
146 match self {
147 Self::Nodes => "id, version, changeset, ts, rev, tags, geom",
148 Self::Ways => "id, version, changeset, ts, minor, rev, tags, nodes, geom",
149 Self::Relations => {
150 "id, version, changeset, ts, rev, tags, member_types, member_ids, member_roles"
151 }
152 }
153 }
154}
155
156pub(crate) fn copy(
158 client: &mut impl GenericClient,
159 table: &str,
160 columns: &str,
161 rows: &Rows,
162) -> Result<(), SyncError> {
163 let mut w = copy_in(client, table, columns)?;
164 w.write_all(&rows.buf)?;
165 copy_end(w)
166}
167
168fn copy_in<'a>(
170 client: &'a mut impl GenericClient,
171 table: &str,
172 columns: &str,
173) -> Result<CopyInWriter<'a>, SyncError> {
174 let mut w = client.copy_in(&format!(
175 "COPY {table} ({columns}) FROM STDIN (FORMAT binary)"
176 ))?;
177 w.write_all(HEADER)?;
178 Ok(w)
179}
180
181fn copy_end(mut w: CopyInWriter<'_>) -> Result<(), SyncError> {
182 w.write_all(TRAILER)?;
183 w.finish()?;
184 Ok(())
185}
186
187pub(crate) struct Writers {
189 tx: Sender<(Table, Vec<u8>)>,
190 threads: Vec<JoinHandle<Result<(), SyncError>>>,
191}
192
193impl Writers {
194 pub(crate) fn start(url: &str, connections: usize) -> Result<Self, SyncError> {
195 let (tx, rx) = bounded(connections * 4);
196 let threads = (0..connections.max(1))
197 .map(|i| {
198 let (url, rx) = (url.to_owned(), rx.clone());
199 thread::Builder::new()
200 .name(format!("osmflow-copy-{i}"))
201 .spawn(move || write(&url, &rx))
202 })
203 .collect::<Result<_, _>>()?;
204 Ok(Self { tx, threads })
205 }
206
207 pub(crate) fn send(&self, table: Table, rows: Rows) -> bool {
210 rows.buf.is_empty() || self.tx.send((table, rows.buf)).is_ok()
211 }
212
213 pub(crate) fn finish(self) -> Result<(), SyncError> {
215 drop(self.tx);
216 let mut result = Ok(());
217 for t in self.threads {
218 let r = t
219 .join()
220 .unwrap_or_else(|_| Err(SyncError::state("a COPY thread panicked")));
221 result = result.and(r);
222 }
223 result
224 }
225}
226
227fn write(url: &str, rx: &Receiver<(Table, Vec<u8>)>) -> Result<(), SyncError> {
229 let mut client = connect(url)?;
230 client.batch_execute("SET synchronous_commit = off; SET default_toast_compression = lz4")?;
231 let mut next = rx.recv().ok();
232 while let Some((table, buf)) = next {
233 let mut w = copy_in(&mut client, table.into(), table.columns())?;
234 w.write_all(&buf)?;
235 loop {
236 next = rx.recv().ok();
237 match &next {
238 Some((t, buf)) if *t == table => w.write_all(buf)?,
239 _ => break,
240 }
241 }
242 copy_end(w)?;
243 }
244 Ok(())
245}