Skip to main content

osmflow_sync/
db.rs

1//! The database side: connections, the state row, and writing rows with binary `COPY` on several connections.
2
3use std::io::Write as _;
4use std::thread::{self, JoinHandle};
5
6use crossbeam_channel::{Receiver, Sender, bounded};
7use osmflow::Timestamp;
8use postgres::{CopyInWriter, GenericClient};
9
10use crate::SyncError;
11use crate::copy::{HEADER, Rows, TRAILER};
12pub(crate) use crate::tls::connect;
13
14/// The format of the `osm` schema this crate reads and writes.
15pub(crate) const SCHEMA_VERSION: i32 = 2;
16
17/// Where the database is in its replication stream, from `osm.state`.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct DbState {
20    /// A random number made by the import, which the node file and the reverse index carry too.
21    pub id: i64,
22    /// The last revision: 1 after the import, one more after each update batch.
23    pub rev: i64,
24    /// The replication stream's base URL, if known.
25    pub url: Option<String>,
26    /// The last sequence of the stream applied.
27    pub sequence: i64,
28    /// The time of that sequence's state.
29    pub timestamp: Option<Timestamp>,
30    /// How `osm.nodes` and `osm.ways` store their geometries.
31    pub geometry: GeometryFormat,
32}
33
34/// How `osm.nodes` and `osm.ways` store their geometries: chosen by the import, kept by every update.
35///
36/// SQL reads either the same way through `osm.geom(geom)`, which the import creates for the format: it decodes TWKB,
37/// or gives the geometry as it is. It is inlined, so an index on `osm.geom(geom)` serves both.
38///
39/// It displays and parses as `twkb` or `wkb`, its name in `osm.state`.
40#[derive(
41    Debug,
42    Clone,
43    Copy,
44    Default,
45    PartialEq,
46    Eq,
47    Hash,
48    strum::AsRefStr,
49    strum::Display,
50    strum::EnumString,
51    strum::VariantNames,
52)]
53#[strum(serialize_all = "lowercase")]
54pub enum GeometryFormat {
55    /// TWKB with OSM's 7 decimal digits in a `bytea`, which PostGIS reads exactly as the locations were written:
56    /// about a quarter of the size of a line's WKB.
57    #[default]
58    Twkb,
59    /// PostGIS's `geometry` with SRID 4326, stored as WKB: read without decoding.
60    Wkb,
61}
62
63impl GeometryFormat {
64    /// The column types of a point and a line string, and `osm.geom` for them, with PostGIS in schema `postgis`.
65    ///
66    /// The function's body names PostGIS's schema: Postgres reads it again where it inlines it, and builds indexes
67    /// with only `pg_catalog` in the search path.
68    pub(crate) fn sql(self, postgis: &str) -> (&'static str, &'static str, String) {
69        let s = format!("\"{}\"", postgis.replace('"', "\"\""));
70        match self {
71            Self::Twkb => (
72                "bytea",
73                "bytea",
74                format!(
75                    "CREATE FUNCTION osm.geom(g bytea) RETURNS {s}.geometry LANGUAGE sql IMMUTABLE PARALLEL SAFE \
76                     AS $$ SELECT {s}.ST_SetSRID({s}.ST_GeomFromTWKB(g), 4326) $$;"
77                ),
78            ),
79            Self::Wkb => (
80                "geometry(Point, 4326)",
81                "geometry(LineString, 4326)",
82                format!(
83                    "CREATE FUNCTION osm.geom(g {s}.geometry) RETURNS {s}.geometry LANGUAGE sql IMMUTABLE \
84                     PARALLEL SAFE AS $$ SELECT g $$;"
85                ),
86            ),
87        }
88    }
89}
90
91impl DbState {
92    /// Reads the state row; an error if there is no imported database.
93    pub(crate) fn read(client: &mut impl GenericClient) -> Result<Self, SyncError> {
94        let exists: bool = client
95            .query_one("SELECT to_regclass('osm.state') IS NOT NULL", &[])?
96            .get(0);
97        if !exists {
98            return Err(SyncError::state(
99                "the database has no osm schema: import a PBF file first",
100            ));
101        }
102        let row = client
103            .query_opt(
104                "SELECT id, version, rev, url, sequence, (extract(epoch FROM timestamp) * 1000)::int8, geometry \
105                 FROM osm.state",
106                &[],
107            )?
108            .ok_or_else(|| SyncError::state("the import did not finish: run it again, replacing the osm schema"))?;
109        let version: i32 = row.get(1);
110        if version != SCHEMA_VERSION {
111            return Err(SyncError::state(format!(
112                "the osm schema has format {version}, but this osmflow-sync reads {SCHEMA_VERSION}"
113            )));
114        }
115        Ok(Self {
116            id: row.get(0),
117            rev: row.get(2),
118            url: row.get(3),
119            sequence: row.get(4),
120            timestamp: row.get::<_, Option<i64>>(5).map(Timestamp::from_millis),
121            geometry: {
122                let name: &str = row.get(6);
123                name.parse().map_err(|_| {
124                    SyncError::state(format!("unknown geometry format {name:?} in osm.state"))
125                })?
126            },
127        })
128    }
129}
130
131/// A table rows are copied into, named as `osm.nodes`.
132#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display, strum::IntoStaticStr)]
133#[strum(serialize_all = "lowercase", prefix = "osm.")]
134pub(crate) enum Table {
135    Nodes,
136    Ways,
137    Relations,
138}
139
140impl Table {
141    /// The table's columns, in the order rows are encoded, as a list for SQL: `id` first, then the rest after `, `.
142    pub(crate) fn columns(self) -> &'static str {
143        match self {
144            Self::Nodes => "id, version, changeset, ts, rev, tags, geom",
145            Self::Ways => "id, version, changeset, ts, minor, rev, tags, nodes, geom",
146            Self::Relations => {
147                "id, version, changeset, ts, rev, tags, member_types, member_ids, member_roles"
148            }
149        }
150    }
151}
152
153/// Copies `rows` into `table` (a name, with its columns in the rows' order) in one `COPY`.
154pub(crate) fn copy(
155    client: &mut impl GenericClient,
156    table: &str,
157    columns: &str,
158    rows: &Rows,
159) -> Result<(), SyncError> {
160    let mut w = copy_in(client, table, columns)?;
161    w.write_all(&rows.buf)?;
162    copy_end(w)
163}
164
165/// Starts a binary `COPY` into `table`'s `columns`: rows are written to it, then [`copy_end`] ends it.
166fn copy_in<'a>(
167    client: &'a mut impl GenericClient,
168    table: &str,
169    columns: &str,
170) -> Result<CopyInWriter<'a>, SyncError> {
171    let mut w = client.copy_in(&format!(
172        "COPY {table} ({columns}) FROM STDIN (FORMAT binary)"
173    ))?;
174    w.write_all(HEADER)?;
175    Ok(w)
176}
177
178fn copy_end(mut w: CopyInWriter<'_>) -> Result<(), SyncError> {
179    w.write_all(TRAILER)?;
180    w.finish()?;
181    Ok(())
182}
183
184/// Copies rows into the tables on several connections at once, each with a `COPY` per table it is sent rows of.
185pub(crate) struct Writers {
186    tx: Sender<(Table, Vec<u8>)>,
187    threads: Vec<JoinHandle<Result<(), SyncError>>>,
188}
189
190impl Writers {
191    pub(crate) fn start(url: &str, connections: usize) -> Result<Self, SyncError> {
192        let (tx, rx) = bounded(connections * 4);
193        let threads = (0..connections.max(1))
194            .map(|i| {
195                let (url, rx) = (url.to_owned(), rx.clone());
196                thread::Builder::new()
197                    .name(format!("osmflow-copy-{i}"))
198                    .spawn(move || write(&url, &rx))
199            })
200            .collect::<Result<_, _>>()?;
201        Ok(Self { tx, threads })
202    }
203
204    /// Hands rows to a connection; false if the connections stopped, as after an error, which
205    /// [`finish`](Self::finish) returns.
206    pub(crate) fn send(&self, table: Table, rows: Rows) -> bool {
207        rows.buf.is_empty() || self.tx.send((table, rows.buf)).is_ok()
208    }
209
210    /// Ends every `COPY`, and returns the first error.
211    pub(crate) fn finish(self) -> Result<(), SyncError> {
212        drop(self.tx);
213        let mut result = Ok(());
214        for t in self.threads {
215            let r = t
216                .join()
217                .unwrap_or_else(|_| Err(SyncError::state("a COPY thread panicked")));
218            result = result.and(r);
219        }
220        result
221    }
222}
223
224/// One connection's work: a `COPY` for each run of rows of one table.
225fn write(url: &str, rx: &Receiver<(Table, Vec<u8>)>) -> Result<(), SyncError> {
226    let mut client = connect(url)?;
227    client.batch_execute("SET synchronous_commit = off; SET default_toast_compression = lz4")?;
228    let mut next = rx.recv().ok();
229    while let Some((table, buf)) = next {
230        let mut w = copy_in(&mut client, table.into(), table.columns())?;
231        w.write_all(&buf)?;
232        loop {
233            next = rx.recv().ok();
234            match &next {
235                Some((t, buf)) if *t == table => w.write_all(buf)?,
236                _ => break,
237            }
238        }
239        copy_end(w)?;
240    }
241    Ok(())
242}