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