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::error::Error;
4use std::io::Write as _;
5use std::thread::{self, JoinHandle};
6
7use crossbeam_channel::{Receiver, Sender, bounded};
8use osmflow::Timestamp;
9use postgres::types::{FromSql, Type};
10use postgres::{CopyInWriter, GenericClient};
11
12use crate::SyncError;
13use crate::copy::{HEADER, Rows, TRAILER};
14pub(crate) use crate::tls::connect;
15use crate::varint::unpack_ids;
16
17/// The format of the `osm` schema this crate reads and writes.
18pub(crate) const SCHEMA_VERSION: i32 = 3;
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    /// The layout of `osm.nodes` and `osm.ways`.
34    pub tables: TableLayout,
35}
36
37/// How `osm.nodes` and `osm.ways` store their rows: chosen by the import, kept by every update.
38///
39/// SQL reads `osm.nodes` and `osm.ways` with `geom` as a PostGIS geometry and `nodes` as an `int8[]` in either
40/// layout. When packed, the tables are `osm.nodes_packed` and `osm.ways_packed`, and `osm.nodes` and `osm.ways` are
41/// views over them that decode `geom` with `osm.geom(geom)` and `nodes` with `osm.node_ids(nodes)`. `osm.geom` is
42/// inlined, so an index on `osm.ways_packed (osm.geom(geom))` serves queries on the view `osm.ways`; when plain, the
43/// index is on `osm.ways (geom)`.
44///
45/// It displays and parses as `packed` or `plain`, its name in `osm.state`.
46#[derive(
47    Debug,
48    Clone,
49    Copy,
50    Default,
51    PartialEq,
52    Eq,
53    Hash,
54    strum::AsRefStr,
55    strum::Display,
56    strum::EnumString,
57    strum::VariantNames,
58)]
59#[strum(serialize_all = "lowercase")]
60pub enum TableLayout {
61    /// Compact tables, read through the views `osm.nodes` and `osm.ways`. `geom` is TWKB with OSM's 7 decimal digits
62    /// in a `bytea`, which PostGIS reads exactly as the locations were written: 11.5 MB against 48.3 MB of WKB in the
63    /// District of Columbia. A way's `nodes` is a `bytea` of its node IDs, each as the step from the
64    /// one before (the first from 0), zigzag-encoded and written as an LEB128 varint: 6.0 MB against 25.9 MB as an
65    /// `int8[]` in the District of Columbia, 17.6 MB against 86.7 MB in New York City (PostgreSQL 18 in Docker on a
66    /// laptop). `osm.node_ids` decodes about 1.3 µs per node, 9.1 s for all ways of New York City against 0.28 s for
67    /// reading an `int8[]`, so bulk readers should read `osm.ways_packed` and decode the bytes with [`NodeIds`].
68    #[default]
69    Packed,
70    /// PostGIS's `geometry` with SRID 4326, stored as WKB, and `nodes` as an `int8[]`, in the tables `osm.nodes` and
71    /// `osm.ways`: read without decoding.
72    Plain,
73}
74
75/// The SQL of a [`TableLayout`], for `schema.sql`.
76pub(crate) struct LayoutSql {
77    /// The column type of a point.
78    pub(crate) point: &'static str,
79    /// The column type of a line string.
80    pub(crate) line: &'static str,
81    /// The column type of a way's node IDs.
82    pub(crate) ids: &'static str,
83    /// What goes after the tables: `osm.geom`, `osm.node_ids` and the views `osm.nodes` and `osm.ways` over the
84    /// packed tables; nothing when plain.
85    pub(crate) after: String,
86}
87
88impl TableLayout {
89    /// The column types, and the functions and views, with PostGIS in schema `postgis`.
90    ///
91    /// The body of `osm.geom` names PostGIS's schema: Postgres reads it again where it inlines it, and builds indexes
92    /// with only `pg_catalog` in the search path.
93    pub(crate) fn sql(self, postgis: &str) -> LayoutSql {
94        let s = format!("\"{}\"", postgis.replace('"', "\"\""));
95        match self {
96            Self::Packed => {
97                let view = |t: Table| {
98                    let columns = t
99                        .columns()
100                        .split(", ")
101                        .map(|c| match (t, c) {
102                            (Table::Ways, "nodes") => "osm.node_ids(nodes) AS nodes",
103                            (_, "geom") => "osm.geom(geom) AS geom",
104                            _ => c,
105                        })
106                        .collect::<Vec<_>>()
107                        .join(", ");
108                    format!(
109                        "CREATE VIEW {} AS SELECT {columns} FROM {};",
110                        <&str>::from(t),
111                        t.name(self)
112                    )
113                };
114                LayoutSql {
115                    point: "bytea",
116                    line: "bytea",
117                    ids: "bytea",
118                    after: format!(
119                        "CREATE FUNCTION osm.geom(g bytea) RETURNS {s}.geometry LANGUAGE sql IMMUTABLE PARALLEL SAFE \
120                         AS $$ SELECT {s}.ST_SetSRID({s}.ST_GeomFromTWKB(g), 4326) $$;\n{}\n{}\n{}",
121                        include_str!("node_ids.sql"),
122                        view(Table::Nodes),
123                        view(Table::Ways)
124                    ),
125                }
126            }
127            Self::Plain => LayoutSql {
128                point: "geometry(Point, 4326)",
129                line: "geometry(LineString, 4326)",
130                ids: "int8[]",
131                after: String::new(),
132            },
133        }
134    }
135}
136
137/// A way's node IDs from its `nodes` column, in either layout: a packed `bytea` (`osm.ways_packed`, decoded here, far
138/// faster than `osm.node_ids` in SQL) or an `int8[]` (`osm.ways`). With binary `COPY`, declare the column's type as it
139/// is: `bytea` when the table is packed, `int8[]` otherwise.
140///
141/// ```
142/// use osmflow_sync::NodeIds;
143/// use postgres::types::{FromSql, Type};
144///
145/// // Steps 100, +1, -2, +300, each zigzagged and written as a varint
146/// let ids = NodeIds::from_sql(&Type::BYTEA, &[0xc8, 0x01, 0x02, 0x03, 0xd8, 0x04]).unwrap();
147/// assert_eq!(ids.0, [100, 101, 99, 399]);
148/// ```
149#[derive(Debug, Clone, Default, PartialEq, Eq)]
150pub struct NodeIds(pub Vec<i64>);
151
152impl<'a> FromSql<'a> for NodeIds {
153    fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<Self, Box<dyn Error + Sync + Send>> {
154        if *ty == Type::BYTEA {
155            Ok(Self(unpack_ids(raw)))
156        } else {
157            Vec::from_sql(ty, raw).map(Self)
158        }
159    }
160
161    fn accepts(ty: &Type) -> bool {
162        *ty == Type::BYTEA || *ty == Type::INT8_ARRAY
163    }
164}
165
166impl DbState {
167    /// Reads the state row; an error if there is no imported database.
168    pub(crate) fn read(client: &mut impl GenericClient) -> Result<Self, SyncError> {
169        let exists: bool = client
170            .query_one("SELECT to_regclass('osm.state') IS NOT NULL", &[])?
171            .get(0);
172        if !exists {
173            return Err(SyncError::state(
174                "the database has no osm schema: import a PBF file first",
175            ));
176        }
177        let row = client
178            .query_opt(
179                "SELECT id, version, rev, url, sequence, (extract(epoch FROM timestamp) * 1000)::int8, tables \
180                 FROM osm.state",
181                &[],
182            )?
183            .ok_or_else(|| SyncError::state("the import did not finish: run it again, replacing the osm schema"))?;
184        let version: i32 = row.get(1);
185        if version != SCHEMA_VERSION {
186            return Err(SyncError::state(format!(
187                "the osm schema has format {version}, but this osmflow-sync reads {SCHEMA_VERSION}: import again, \
188                 replacing the osm schema"
189            )));
190        }
191        Ok(Self {
192            id: row.get(0),
193            rev: row.get::<_, i32>(2).into(),
194            url: row.get(3),
195            sequence: row.get(4),
196            timestamp: row.get::<_, Option<i64>>(5).map(Timestamp::from_millis),
197            tables: {
198                let name: &str = row.get(6);
199                name.parse().map_err(|_| {
200                    SyncError::state(format!("unknown table layout {name:?} in osm.state"))
201                })?
202            },
203        })
204    }
205}
206
207/// A table rows are copied into. `<&str>::from` gives the name SQL users read, `osm.nodes`; [`Table::name`] the table
208/// that stores the rows.
209#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)]
210#[strum(serialize_all = "lowercase", prefix = "osm.")]
211pub(crate) enum Table {
212    Nodes,
213    Ways,
214    Relations,
215}
216
217impl Table {
218    /// The table that stores the rows in `layout`: when packed, `osm.nodes_packed` and `osm.ways_packed`, as
219    /// `osm.nodes` and `osm.ways` are views.
220    pub(crate) fn name(self, layout: TableLayout) -> &'static str {
221        match (self, layout) {
222            (Self::Nodes, TableLayout::Packed) => "osm.nodes_packed",
223            (Self::Ways, TableLayout::Packed) => "osm.ways_packed",
224            _ => self.into(),
225        }
226    }
227
228    /// The table's columns, in the order rows are encoded, as a list for SQL: `id` first, then the rest after `, `.
229    pub(crate) fn columns(self) -> &'static str {
230        match self {
231            Self::Nodes => "id, changeset, ts, version, rev, tags, geom",
232            Self::Ways => "id, changeset, ts, version, minor, rev, tags, nodes, geom",
233            Self::Relations => {
234                "id, changeset, ts, version, rev, tags, member_types, member_ids, member_roles"
235            }
236        }
237    }
238}
239
240/// Copies `rows` into `table` (a name, with its columns in the rows' order) in one `COPY`.
241pub(crate) fn copy(
242    client: &mut impl GenericClient,
243    table: &str,
244    columns: &str,
245    rows: &Rows,
246) -> Result<(), SyncError> {
247    let mut w = copy_in(client, table, columns)?;
248    w.write_all(&rows.buf)?;
249    copy_end(w)
250}
251
252/// Starts a binary `COPY` into `table`'s `columns`: rows are written to it, then [`copy_end`] ends it.
253fn copy_in<'a>(
254    client: &'a mut impl GenericClient,
255    table: &str,
256    columns: &str,
257) -> Result<CopyInWriter<'a>, SyncError> {
258    let mut w = client.copy_in(&format!(
259        "COPY {table} ({columns}) FROM STDIN (FORMAT binary)"
260    ))?;
261    w.write_all(HEADER)?;
262    Ok(w)
263}
264
265fn copy_end(mut w: CopyInWriter<'_>) -> Result<(), SyncError> {
266    w.write_all(TRAILER)?;
267    w.finish()?;
268    Ok(())
269}
270
271/// Copies rows into the tables on several connections at once, each with a `COPY` per table it is sent rows of.
272pub(crate) struct Writers {
273    tx: Sender<(Table, Vec<u8>)>,
274    threads: Vec<JoinHandle<Result<(), SyncError>>>,
275}
276
277impl Writers {
278    pub(crate) fn start(
279        url: &str,
280        connections: usize,
281        layout: TableLayout,
282    ) -> Result<Self, SyncError> {
283        let (tx, rx) = bounded(connections * 4);
284        let threads = (0..connections.max(1))
285            .map(|i| {
286                let (url, rx) = (url.to_owned(), rx.clone());
287                thread::Builder::new()
288                    .name(format!("osmflow-copy-{i}"))
289                    .spawn(move || write(&url, &rx, layout))
290            })
291            .collect::<Result<_, _>>()?;
292        Ok(Self { tx, threads })
293    }
294
295    /// Hands rows to a connection; false if the connections stopped, as after an error, which
296    /// [`finish`](Self::finish) returns.
297    pub(crate) fn send(&self, table: Table, rows: Rows) -> bool {
298        rows.buf.is_empty() || self.tx.send((table, rows.buf)).is_ok()
299    }
300
301    /// Ends every `COPY`, and returns the first error.
302    pub(crate) fn finish(self) -> Result<(), SyncError> {
303        drop(self.tx);
304        let mut result = Ok(());
305        for t in self.threads {
306            let r = t
307                .join()
308                .unwrap_or_else(|_| Err(SyncError::state("a COPY thread panicked")));
309            result = result.and(r);
310        }
311        result
312    }
313}
314
315/// One connection's work: a `COPY` for each run of rows of one table.
316fn write(url: &str, rx: &Receiver<(Table, Vec<u8>)>, layout: TableLayout) -> Result<(), SyncError> {
317    let mut client = connect(url)?;
318    client.batch_execute("SET synchronous_commit = off; SET default_toast_compression = lz4")?;
319    let mut next = rx.recv().ok();
320    while let Some((table, buf)) = next {
321        let mut w = copy_in(&mut client, table.name(layout), table.columns())?;
322        w.write_all(&buf)?;
323        loop {
324            next = rx.recv().ok();
325            match &next {
326                Some((t, buf)) if *t == table => w.write_all(buf)?,
327                _ => break,
328            }
329        }
330        copy_end(w)?;
331    }
332    Ok(())
333}