prolly-store-postgres 0.3.0

PostgreSQL store adapter for prolly-map.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
#![doc = include_str!("../README.md")]

pub use prolly::{
    RemoteBatchOp, RemoteManifestUpdate, RemoteNamedRoot, RemoteProllyStore, RemoteRootCondition,
    RemoteRootWrite, RemoteStoreBackend, RemoteTransactionConflict, RemoteTransactionUpdate,
};

/// Postgres adapter entry point.
pub mod postgres {
    use sqlx::{PgPool, Row};

    use crate::{
        RemoteBatchOp, RemoteManifestUpdate, RemoteNamedRoot, RemoteRootCondition, RemoteRootWrite,
        RemoteStoreBackend, RemoteTransactionConflict, RemoteTransactionUpdate,
    };

    /// Store adapter for PostgreSQL-backed prolly nodes and roots.
    pub type PostgresStore = crate::RemoteProllyStore<PostgresBackend>;

    /// SQLx-backed PostgreSQL backend.
    #[derive(Clone, Debug)]
    pub struct PostgresBackend {
        pool: PgPool,
    }

    impl PostgresBackend {
        /// Create a backend from an existing SQLx pool.
        pub fn new(pool: PgPool) -> Self {
            Self { pool }
        }

        /// Connect to PostgreSQL using `database_url`.
        pub async fn connect(database_url: &str) -> Result<Self, sqlx::Error> {
            Ok(Self::new(PgPool::connect(database_url).await?))
        }

        /// Borrow the underlying pool.
        pub fn pool(&self) -> &PgPool {
            &self.pool
        }

        /// Create the required tables if they do not already exist.
        pub async fn initialize_schema(&self) -> Result<(), sqlx::Error> {
            execute_statements(&self.pool, POSTGRES_SCHEMA).await
        }
    }

    impl RemoteStoreBackend for PostgresBackend {
        type Error = sqlx::Error;

        async fn get_node(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
            sqlx::query("SELECT node FROM prolly_nodes WHERE cid = $1")
                .bind(key)
                .fetch_optional(&self.pool)
                .await?
                .map(|row| row.try_get("node"))
                .transpose()
        }

        async fn put_node(&self, key: &[u8], value: &[u8]) -> Result<(), Self::Error> {
            sqlx::query(
                "\
                INSERT INTO prolly_nodes (cid, node) VALUES ($1, $2) \
                ON CONFLICT(cid) DO UPDATE SET node = excluded.node",
            )
            .bind(key)
            .bind(value)
            .execute(&self.pool)
            .await?;
            Ok(())
        }

        async fn delete_node(&self, key: &[u8]) -> Result<(), Self::Error> {
            sqlx::query("DELETE FROM prolly_nodes WHERE cid = $1")
                .bind(key)
                .execute(&self.pool)
                .await?;
            Ok(())
        }

        async fn batch_nodes(&self, ops: &[RemoteBatchOp<'_>]) -> Result<(), Self::Error> {
            let mut tx = self.pool.begin().await?;
            for op in ops {
                match op {
                    RemoteBatchOp::Upsert { key, value } => {
                        sqlx::query(
                            "\
                            INSERT INTO prolly_nodes (cid, node) VALUES ($1, $2) \
                            ON CONFLICT(cid) DO UPDATE SET node = excluded.node",
                        )
                        .bind(*key)
                        .bind(*value)
                        .execute(&mut *tx)
                        .await?;
                    }
                    RemoteBatchOp::Delete { key } => {
                        sqlx::query("DELETE FROM prolly_nodes WHERE cid = $1")
                            .bind(*key)
                            .execute(&mut *tx)
                            .await?;
                    }
                }
            }
            tx.commit().await
        }

        async fn batch_get_nodes_ordered(
            &self,
            keys: &[&[u8]],
        ) -> Result<Vec<Option<Vec<u8>>>, Self::Error> {
            let mut values = Vec::with_capacity(keys.len());
            for key in keys {
                values.push(self.get_node(key).await?);
            }
            Ok(values)
        }

        async fn batch_put_nodes(&self, entries: &[(&[u8], &[u8])]) -> Result<(), Self::Error> {
            let mut tx = self.pool.begin().await?;
            for (key, value) in entries {
                sqlx::query(
                    "\
                    INSERT INTO prolly_nodes (cid, node) VALUES ($1, $2) \
                    ON CONFLICT(cid) DO UPDATE SET node = excluded.node",
                )
                .bind(*key)
                .bind(*value)
                .execute(&mut *tx)
                .await?;
            }
            tx.commit().await
        }

        async fn list_node_cids(&self) -> Result<Vec<Vec<u8>>, Self::Error> {
            let rows = sqlx::query("SELECT cid FROM prolly_nodes ORDER BY cid")
                .fetch_all(&self.pool)
                .await?;
            rows.into_iter().map(|row| row.try_get("cid")).collect()
        }

        fn prefers_batch_reads(&self) -> bool {
            true
        }

        fn supports_hints(&self) -> bool {
            true
        }

        async fn get_hint(
            &self,
            namespace: &[u8],
            key: &[u8],
        ) -> Result<Option<Vec<u8>>, Self::Error> {
            sqlx::query("SELECT value FROM prolly_hints WHERE namespace = $1 AND key = $2")
                .bind(namespace)
                .bind(key)
                .fetch_optional(&self.pool)
                .await?
                .map(|row| row.try_get("value"))
                .transpose()
        }

        async fn put_hint(
            &self,
            namespace: &[u8],
            key: &[u8],
            value: &[u8],
        ) -> Result<(), Self::Error> {
            sqlx::query(
                "\
                INSERT INTO prolly_hints (namespace, key, value) VALUES ($1, $2, $3) \
                ON CONFLICT(namespace, key) DO UPDATE SET value = excluded.value",
            )
            .bind(namespace)
            .bind(key)
            .bind(value)
            .execute(&self.pool)
            .await?;
            Ok(())
        }

        async fn batch_put_nodes_with_hint(
            &self,
            entries: &[(&[u8], &[u8])],
            namespace: &[u8],
            key: &[u8],
            value: &[u8],
        ) -> Result<(), Self::Error> {
            let mut tx = self.pool.begin().await?;
            for (key, value) in entries {
                sqlx::query(
                    "\
                    INSERT INTO prolly_nodes (cid, node) VALUES ($1, $2) \
                    ON CONFLICT(cid) DO UPDATE SET node = excluded.node",
                )
                .bind(*key)
                .bind(*value)
                .execute(&mut *tx)
                .await?;
            }
            sqlx::query(
                "\
                INSERT INTO prolly_hints (namespace, key, value) VALUES ($1, $2, $3) \
                ON CONFLICT(namespace, key) DO UPDATE SET value = excluded.value",
            )
            .bind(namespace)
            .bind(key)
            .bind(value)
            .execute(&mut *tx)
            .await?;
            tx.commit().await
        }

        async fn get_root_manifest(&self, name: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
            sqlx::query("SELECT manifest FROM prolly_roots WHERE name = $1")
                .bind(name)
                .fetch_optional(&self.pool)
                .await?
                .map(|row| row.try_get("manifest"))
                .transpose()
        }

        async fn put_root_manifest(&self, name: &[u8], manifest: &[u8]) -> Result<(), Self::Error> {
            sqlx::query(
                "\
                INSERT INTO prolly_roots (name, manifest) VALUES ($1, $2) \
                ON CONFLICT(name) DO UPDATE SET manifest = excluded.manifest",
            )
            .bind(name)
            .bind(manifest)
            .execute(&self.pool)
            .await?;
            Ok(())
        }

        async fn delete_root_manifest(&self, name: &[u8]) -> Result<(), Self::Error> {
            sqlx::query("DELETE FROM prolly_roots WHERE name = $1")
                .bind(name)
                .execute(&self.pool)
                .await?;
            Ok(())
        }

        async fn compare_and_swap_root_manifest(
            &self,
            name: &[u8],
            expected: Option<&[u8]>,
            new: Option<&[u8]>,
        ) -> Result<RemoteManifestUpdate, Self::Error> {
            let mut tx = self.pool.begin().await?;
            sqlx::query("LOCK TABLE prolly_roots IN SHARE ROW EXCLUSIVE MODE")
                .execute(&mut *tx)
                .await?;

            let current = sqlx::query("SELECT manifest FROM prolly_roots WHERE name = $1")
                .bind(name)
                .fetch_optional(&mut *tx)
                .await?
                .map(|row| row.try_get("manifest"))
                .transpose()?;
            if current.as_deref() != expected {
                tx.rollback().await?;
                return Ok(RemoteManifestUpdate::Conflict { current });
            }

            match new {
                Some(manifest) => {
                    sqlx::query(
                        "\
                        INSERT INTO prolly_roots (name, manifest) VALUES ($1, $2) \
                        ON CONFLICT(name) DO UPDATE SET manifest = excluded.manifest",
                    )
                    .bind(name)
                    .bind(manifest)
                    .execute(&mut *tx)
                    .await?;
                }
                None => {
                    sqlx::query("DELETE FROM prolly_roots WHERE name = $1")
                        .bind(name)
                        .execute(&mut *tx)
                        .await?;
                }
            }

            tx.commit().await?;
            Ok(RemoteManifestUpdate::Applied)
        }

        async fn list_root_manifests(&self) -> Result<Vec<RemoteNamedRoot>, Self::Error> {
            let rows = sqlx::query("SELECT name, manifest FROM prolly_roots ORDER BY name")
                .fetch_all(&self.pool)
                .await?;
            rows.into_iter()
                .map(|row| {
                    Ok(RemoteNamedRoot::new(
                        row.try_get("name")?,
                        row.try_get("manifest")?,
                    ))
                })
                .collect()
        }

        fn supports_transactions(&self) -> bool {
            true
        }

        async fn commit_transaction(
            &self,
            node_writes: &[RemoteBatchOp<'_>],
            root_conditions: &[RemoteRootCondition],
            root_writes: &[RemoteRootWrite],
        ) -> Result<RemoteTransactionUpdate, Self::Error> {
            let mut tx = self.pool.begin().await?;
            sqlx::query("LOCK TABLE prolly_roots IN SHARE ROW EXCLUSIVE MODE")
                .execute(&mut *tx)
                .await?;

            for condition in root_conditions {
                let current = sqlx::query("SELECT manifest FROM prolly_roots WHERE name = $1")
                    .bind(&condition.name)
                    .fetch_optional(&mut *tx)
                    .await?
                    .map(|row| row.try_get("manifest"))
                    .transpose()?;
                if current != condition.expected {
                    tx.rollback().await?;
                    return Ok(RemoteTransactionUpdate::Conflict(
                        RemoteTransactionConflict::new(
                            condition.name.clone(),
                            condition.expected.clone(),
                            current,
                        ),
                    ));
                }
            }

            for write in node_writes {
                match write {
                    RemoteBatchOp::Upsert { key, value } => {
                        sqlx::query(
                            "\
                            INSERT INTO prolly_nodes (cid, node) VALUES ($1, $2) \
                            ON CONFLICT(cid) DO UPDATE SET node = excluded.node",
                        )
                        .bind(*key)
                        .bind(*value)
                        .execute(&mut *tx)
                        .await?;
                    }
                    RemoteBatchOp::Delete { key } => {
                        sqlx::query("DELETE FROM prolly_nodes WHERE cid = $1")
                            .bind(*key)
                            .execute(&mut *tx)
                            .await?;
                    }
                }
            }

            for write in root_writes {
                match write {
                    RemoteRootWrite::Put { name, manifest } => {
                        sqlx::query(
                            "\
                            INSERT INTO prolly_roots (name, manifest) VALUES ($1, $2) \
                            ON CONFLICT(name) DO UPDATE SET manifest = excluded.manifest",
                        )
                        .bind(name)
                        .bind(manifest)
                        .execute(&mut *tx)
                        .await?;
                    }
                    RemoteRootWrite::Delete { name } => {
                        sqlx::query("DELETE FROM prolly_roots WHERE name = $1")
                            .bind(name)
                            .execute(&mut *tx)
                            .await?;
                    }
                }
            }

            tx.commit().await?;
            Ok(RemoteTransactionUpdate::Applied)
        }
    }

    async fn execute_statements(pool: &PgPool, sql: &str) -> Result<(), sqlx::Error> {
        for statement in sql
            .split(';')
            .map(str::trim)
            .filter(|stmt| !stmt.is_empty())
        {
            sqlx::query(statement).execute(pool).await?;
        }
        Ok(())
    }

    /// Minimal table layout for PostgreSQL implementations.
    pub const POSTGRES_SCHEMA: &str = "\
CREATE TABLE IF NOT EXISTS prolly_nodes (
  cid bytea PRIMARY KEY,
  node bytea NOT NULL
);
CREATE TABLE IF NOT EXISTS prolly_hints (
  namespace bytea NOT NULL,
  key bytea NOT NULL,
  value bytea NOT NULL,
  PRIMARY KEY(namespace, key)
);
CREATE TABLE IF NOT EXISTS prolly_roots (
  name bytea PRIMARY KEY,
  manifest bytea NOT NULL
);";
}

pub use postgres::*;