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::{Client, CopyInWriter, GenericClient, NoTls};
9
10use crate::SyncError;
11use crate::copy::{HEADER, Rows, TRAILER};
12
13/// The format of the `osm` schema this crate reads and writes.
14pub(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/// Where the database is in its replication stream, from `osm.state`.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct DbState {
23    /// A random number made by the import, which the node file and the reverse index carry too.
24    pub id: i64,
25    /// The last revision: 1 after the import, one more after each update batch.
26    pub rev: i64,
27    /// The replication stream's base URL, if known.
28    pub url: Option<String>,
29    /// The last sequence of the stream applied.
30    pub sequence: i64,
31    /// The time of that sequence's state.
32    pub timestamp: Option<Timestamp>,
33    /// How `osm.nodes` and `osm.ways` store their geometries.
34    pub geometry: GeometryFormat,
35}
36
37/// How `osm.nodes` and `osm.ways` store their geometries: chosen by the import, kept by every update.
38///
39/// SQL reads either the same way through `osm.geom(geom)`, which the import creates for the format: it decodes TWKB,
40/// or gives the geometry as it is. It is inlined, so an index on `osm.geom(geom)` serves both.
41///
42/// It displays and parses as `twkb` or `wkb`, its name in `osm.state`.
43#[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    /// TWKB with OSM's 7 decimal digits in a `bytea`, which PostGIS reads exactly as the locations were written:
59    /// about a quarter of the size of a line's WKB.
60    #[default]
61    Twkb,
62    /// PostGIS's `geometry` with SRID 4326, stored as WKB: read without decoding.
63    Wkb,
64}
65
66impl GeometryFormat {
67    /// The column types of a point and a line string, and `osm.geom` for them, with PostGIS in schema `postgis`.
68    ///
69    /// The function's body names PostGIS's schema: Postgres reads it again where it inlines it, and builds indexes
70    /// with only `pg_catalog` in the search path.
71    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    /// Reads the state row; an error if there is no imported database.
96    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/// A table rows are copied into, named as `osm.nodes`.
135#[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    /// The table's columns, in the order rows are encoded, as a list for SQL: `id` first, then the rest after `, `.
145    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
156/// Copies `rows` into `table` (a name, with its columns in the rows' order) in one `COPY`.
157pub(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
168/// Starts a binary `COPY` into `table`'s `columns`: rows are written to it, then [`copy_end`] ends it.
169fn 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
187/// Copies rows into the tables on several connections at once, each with a `COPY` per table it is sent rows of.
188pub(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    /// Hands rows to a connection; false if the connections stopped, as after an error, which
208    /// [`finish`](Self::finish) returns.
209    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    /// Ends every `COPY`, and returns the first error.
214    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
227/// One connection's work: a `COPY` for each run of rows of one table.
228fn 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}