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 = 1;
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}
34
35impl DbState {
36 pub(crate) fn read(client: &mut impl GenericClient) -> Result<Self, SyncError> {
38 let exists: bool = client
39 .query_one("SELECT to_regclass('osm.state') IS NOT NULL", &[])?
40 .get(0);
41 if !exists {
42 return Err(SyncError::state(
43 "the database has no osm schema: import a PBF file first",
44 ));
45 }
46 let row = client
47 .query_opt(
48 "SELECT id, version, rev, url, sequence, (extract(epoch FROM timestamp) * 1000)::int8 FROM osm.state",
49 &[],
50 )?
51 .ok_or_else(|| SyncError::state("the import did not finish: run it again, replacing the osm schema"))?;
52 let version: i32 = row.get(1);
53 if version != SCHEMA_VERSION {
54 return Err(SyncError::state(format!(
55 "the osm schema has format {version}, but this osmflow-sync reads {SCHEMA_VERSION}"
56 )));
57 }
58 Ok(Self {
59 id: row.get(0),
60 rev: row.get(2),
61 url: row.get(3),
62 sequence: row.get(4),
63 timestamp: row.get::<_, Option<i64>>(5).map(Timestamp::from_millis),
64 })
65 }
66}
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub(crate) enum Table {
71 Nodes,
72 Ways,
73 Relations,
74}
75
76impl Table {
77 pub(crate) fn name(self) -> &'static str {
78 match self {
79 Self::Nodes => "osm.nodes",
80 Self::Ways => "osm.ways",
81 Self::Relations => "osm.relations",
82 }
83 }
84
85 pub(crate) fn columns(self) -> &'static [&'static str] {
87 match self {
88 Self::Nodes => &["id", "version", "changeset", "ts", "rev", "tags", "geom"],
89 Self::Ways => &[
90 "id",
91 "version",
92 "changeset",
93 "ts",
94 "minor",
95 "rev",
96 "tags",
97 "nodes",
98 "geom",
99 ],
100 Self::Relations => &[
101 "id",
102 "version",
103 "changeset",
104 "ts",
105 "rev",
106 "tags",
107 "member_types",
108 "member_ids",
109 "member_roles",
110 ],
111 }
112 }
113}
114
115pub(crate) fn copy(
117 client: &mut impl GenericClient,
118 table: &str,
119 columns: &str,
120 rows: &Rows,
121) -> Result<(), SyncError> {
122 let mut w = copy_in(client, table, columns)?;
123 w.write_all(&rows.buf)?;
124 copy_end(w)
125}
126
127fn copy_in<'a>(
129 client: &'a mut impl GenericClient,
130 table: &str,
131 columns: &str,
132) -> Result<CopyInWriter<'a>, SyncError> {
133 let mut w = client.copy_in(&format!(
134 "COPY {table} ({columns}) FROM STDIN (FORMAT binary)"
135 ))?;
136 w.write_all(HEADER)?;
137 Ok(w)
138}
139
140fn copy_end(mut w: CopyInWriter<'_>) -> Result<(), SyncError> {
141 w.write_all(TRAILER)?;
142 w.finish()?;
143 Ok(())
144}
145
146pub(crate) struct Writers {
148 tx: Sender<(Table, Vec<u8>)>,
149 threads: Vec<JoinHandle<Result<(), SyncError>>>,
150}
151
152impl Writers {
153 pub(crate) fn start(url: &str, connections: usize) -> Result<Self, SyncError> {
154 let (tx, rx) = bounded(connections * 4);
155 let threads = (0..connections.max(1))
156 .map(|i| {
157 let (url, rx) = (url.to_owned(), rx.clone());
158 thread::Builder::new()
159 .name(format!("osmflow-copy-{i}"))
160 .spawn(move || write(&url, &rx))
161 })
162 .collect::<Result<_, _>>()?;
163 Ok(Self { tx, threads })
164 }
165
166 pub(crate) fn send(&self, table: Table, rows: Rows) -> bool {
169 rows.buf.is_empty() || self.tx.send((table, rows.buf)).is_ok()
170 }
171
172 pub(crate) fn finish(self) -> Result<(), SyncError> {
174 drop(self.tx);
175 let mut result = Ok(());
176 for t in self.threads {
177 let r = t
178 .join()
179 .unwrap_or_else(|_| Err(SyncError::state("a COPY thread panicked")));
180 result = result.and(r);
181 }
182 result
183 }
184}
185
186fn write(url: &str, rx: &Receiver<(Table, Vec<u8>)>) -> Result<(), SyncError> {
188 let mut client = connect(url)?;
189 client.batch_execute("SET synchronous_commit = off; SET default_toast_compression = lz4")?;
190 let mut next = rx.recv().ok();
191 while let Some((table, buf)) = next {
192 let mut w = copy_in(&mut client, table.name(), &table.columns().join(", "))?;
193 w.write_all(&buf)?;
194 loop {
195 next = rx.recv().ok();
196 match &next {
197 Some((t, buf)) if *t == table => w.write_all(buf)?,
198 _ => break,
199 }
200 }
201 copy_end(w)?;
202 }
203 Ok(())
204}