hyperdb-api 0.6.0

Pure Rust API for Hyper database
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
417
418
419
420
421
422
// Copyright (c) 2026, Salesforce, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! Async key-value store — the [`AsyncConnection`] twin of [`KvStore`](crate::KvStore).

use crate::async_connection::AsyncConnection;
use crate::error::{Error, Result};
use crate::kv_store::{kv_create_table_sql, kv_target_prefix, validate_kv_name, KV_TABLE};

/// A handle to one named key-value store over an [`AsyncConnection`].
///
/// The async twin of [`KvStore`](crate::KvStore); see it for semantics. Open
/// one with [`AsyncConnection::kv_store`].
///
/// # Examples
///
/// ```no_run
/// use hyperdb_api::{AsyncConnection, CreateMode, Result};
///
/// async fn demo(conn: &AsyncConnection) -> Result<()> {
///     let kv = conn.kv_store("settings").await?;
///     kv.set("theme", "dark").await?;
///     assert_eq!(kv.get("theme").await?, Some("dark".to_string()));
///     Ok(())
/// }
/// ```
#[derive(Debug)]
pub struct AsyncKvStore<'conn> {
    connection: &'conn AsyncConnection,
    store_name: String,
    table_ref: String,
}

impl<'conn> AsyncKvStore<'conn> {
    /// Opens a handle to `name`, creating `KV_TABLE` if needed.
    async fn open(
        connection: &'conn AsyncConnection,
        name: &str,
        table_ref: String,
    ) -> Result<Self> {
        validate_kv_name(name, "store name")?;
        connection
            .execute_command(&kv_create_table_sql(&table_ref))
            .await?;
        Ok(AsyncKvStore {
            connection,
            store_name: name.to_string(),
            table_ref,
        })
    }

    /// Opens a handle to a store in the default location.
    pub(crate) async fn new(connection: &'conn AsyncConnection, name: &str) -> Result<Self> {
        Self::open(connection, name, KV_TABLE.to_string()).await
    }

    /// Async twin of [`KvStore::with_target`](crate::KvStore::with_target).
    ///
    /// Crate-internal low-level constructor behind
    /// [`AsyncConnection::kv_store_in`](crate::AsyncConnection::kv_store_in).
    /// `target` is interpolated into SQL — the caller must supply a pre-escaped,
    /// SQL-safe qualifier (public callers go through `kv_store_in`, which
    /// escapes for them).
    pub(crate) async fn with_target(
        connection: &'conn AsyncConnection,
        name: &str,
        target: &str,
    ) -> Result<Self> {
        Self::open(connection, name, format!("{target}.{KV_TABLE}")).await
    }

    /// Returns this store's validated name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.store_name
    }

    /// Returns the value for `key`, or `None` if absent or NULL.
    ///
    /// # Errors
    ///
    /// See [`KvStore::get`](crate::KvStore::get).
    pub async fn get(&self, key: &str) -> Result<Option<String>> {
        validate_kv_name(key, "key")?;
        let sql = format!(
            "SELECT value FROM {} WHERE store_name = $1 AND key = $2",
            self.table_ref
        );
        // Bind store_name/key as `&str` params (never interpolated) — uniform
        // `&str` element types coerce cleanly to `&[&dyn ToSqlParam]`.
        let row = self
            .connection
            .query_params(&sql, &[&self.store_name.as_str(), &key])
            .await?
            .first_row()
            .await?;
        Ok(row.and_then(|r| r.get::<String>(0)))
    }

    /// Sets `key` to `value` (upsert).
    ///
    /// # Errors
    ///
    /// See [`KvStore::set`](crate::KvStore::set).
    pub async fn set(&self, key: &str, value: &str) -> Result<()> {
        validate_kv_name(key, "key")?;
        self.upsert(key, value).await
    }

    /// UPDATE-then-conditional-INSERT upsert. Assumes `key` is validated.
    ///
    /// Mirrors [`KvStore::upsert`](crate::KvStore); the conditional INSERT uses
    /// distinct placeholders (`$4`/`$5`) so it is unambiguous under the
    /// extended-query protocol.
    async fn upsert(&self, key: &str, value: &str) -> Result<()> {
        let updated = self
            .connection
            .command_params(
                &format!(
                    "UPDATE {} SET value = $3 WHERE store_name = $1 AND key = $2",
                    self.table_ref
                ),
                &[&self.store_name.as_str(), &key, &value],
            )
            .await?;
        if updated == 0 {
            self.connection
                .command_params(
                    &format!(
                        "INSERT INTO {t} (store_name, key, value) \
                         SELECT $1, $2, $3 \
                         WHERE NOT EXISTS (SELECT 1 FROM {t} WHERE store_name = $4 AND key = $5)",
                        t = self.table_ref
                    ),
                    &[
                        &self.store_name.as_str(),
                        &key,
                        &value,
                        &self.store_name.as_str(),
                        &key,
                    ],
                )
                .await?;
        }
        Ok(())
    }

    /// Deserializes the JSON value for `key` into `T`; `None` if absent.
    ///
    /// # Errors
    ///
    /// See [`KvStore::get_as`](crate::KvStore::get_as).
    pub async fn get_as<T: serde::de::DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
        match self.get(key).await? {
            Some(json) => serde_json::from_str(&json)
                .map(Some)
                .map_err(|e| Error::serialization(e.to_string())),
            None => Ok(None),
        }
    }

    /// Serializes `value` to JSON and stores it under `key` (upsert).
    ///
    /// # Errors
    ///
    /// See [`KvStore::set_as`](crate::KvStore::set_as).
    pub async fn set_as<T: serde::Serialize>(&self, key: &str, value: &T) -> Result<()> {
        validate_kv_name(key, "key")?;
        let json = serde_json::to_string(value).map_err(|e| Error::serialization(e.to_string()))?;
        self.upsert(key, &json).await
    }

    /// Deletes `key`; returns `true` if a row was removed.
    ///
    /// # Errors
    ///
    /// See [`KvStore::delete`](crate::KvStore::delete).
    pub async fn delete(&self, key: &str) -> Result<bool> {
        validate_kv_name(key, "key")?;
        let affected = self
            .connection
            .command_params(
                &format!(
                    "DELETE FROM {} WHERE store_name = $1 AND key = $2",
                    self.table_ref
                ),
                &[&self.store_name.as_str(), &key],
            )
            .await?;
        Ok(affected > 0)
    }

    /// Returns whether `key` is present.
    ///
    /// # Errors
    ///
    /// See [`KvStore::exists`](crate::KvStore::exists).
    pub async fn exists(&self, key: &str) -> Result<bool> {
        validate_kv_name(key, "key")?;
        let sql = format!(
            "SELECT 1 FROM {} WHERE store_name = $1 AND key = $2 LIMIT 1",
            self.table_ref
        );
        Ok(self
            .connection
            .query_params(&sql, &[&self.store_name.as_str(), &key])
            .await?
            .first_row()
            .await?
            .is_some())
    }

    /// Returns the number of keys in this store.
    ///
    /// # Errors
    ///
    /// See [`KvStore::size`](crate::KvStore::size).
    pub async fn size(&self) -> Result<i64> {
        let sql = format!(
            "SELECT COUNT(*) FROM {} WHERE store_name = $1",
            self.table_ref
        );
        // `scalar()` errors on zero rows, but COUNT(*) always returns exactly
        // one non-NULL row, so `unwrap_or(0)` is unreachable-but-defensive.
        Ok(self
            .connection
            .query_params(&sql, &[&self.store_name.as_str()])
            .await?
            .scalar::<i64>()
            .await?
            .unwrap_or(0))
    }

    /// Returns this store's keys, sorted ascending.
    ///
    /// # Errors
    ///
    /// See [`KvStore::keys`](crate::KvStore::keys).
    pub async fn keys(&self) -> Result<Vec<String>> {
        let sql = format!(
            "SELECT key FROM {} WHERE store_name = $1 ORDER BY key ASC",
            self.table_ref
        );
        let mut result = self
            .connection
            .query_params(&sql, &[&self.store_name.as_str()])
            .await?;
        let mut keys = Vec::new();
        while let Some(chunk) = result.next_chunk().await? {
            for row in &chunk {
                if let Some(k) = row.get::<String>(0) {
                    keys.push(k);
                }
            }
        }
        Ok(keys)
    }

    /// Deletes every key in this store; returns the number removed.
    ///
    /// The shared backing table survives; only this store's rows are removed.
    ///
    /// # Errors
    ///
    /// See [`KvStore::clear`](crate::KvStore::clear).
    pub async fn clear(&self) -> Result<u64> {
        self.connection
            .command_params(
                &format!("DELETE FROM {} WHERE store_name = $1", self.table_ref),
                &[&self.store_name.as_str()],
            )
            .await
    }

    /// Removes and returns the lowest-ordered pair, or `None` if empty.
    ///
    /// The peek and delete run in one transaction, so they apply atomically —
    /// either both commit, or neither does (on error the transaction is rolled
    /// back). A SQL-NULL value is returned as an empty string.
    ///
    /// # Errors
    ///
    /// See [`KvStore::pop`](crate::KvStore::pop).
    pub async fn pop(&self) -> Result<Option<(String, String)>> {
        self.connection.begin_transaction_raw().await?;
        let result = self.pop_inner().await;
        match &result {
            Ok(_) => self.connection.commit_raw().await?,
            Err(_) => {
                // Best-effort rollback; preserve the original error.
                let _ = self.connection.rollback_raw().await;
            }
        }
        result
    }

    /// Transaction body for [`pop`](Self::pop).
    async fn pop_inner(&self) -> Result<Option<(String, String)>> {
        let select = format!(
            "SELECT key, value FROM {} WHERE store_name = $1 ORDER BY key ASC LIMIT 1",
            self.table_ref
        );
        // `first_row()` consumes the `AsyncRowset`, releasing its statement
        // guard on the shared connection BEFORE the DELETE runs — the two
        // statements never overlap on the connection.
        let Some(row) = self
            .connection
            .query_params(&select, &[&self.store_name.as_str()])
            .await?
            .first_row()
            .await?
        else {
            return Ok(None);
        };
        let key: String = row
            .get::<String>(0)
            .ok_or_else(|| Error::internal("kv pop: key column was unexpectedly NULL"))?;
        let value: String = row.get::<String>(1).unwrap_or_default();
        self.connection
            .command_params(
                &format!(
                    "DELETE FROM {} WHERE store_name = $1 AND key = $2",
                    self.table_ref
                ),
                &[&self.store_name.as_str(), &key.as_str()],
            )
            .await?;
        Ok(Some((key, value)))
    }

    /// Upserts every `(key, value)` pair in one transaction.
    ///
    /// All keys are validated before the transaction opens, so an invalid key
    /// aborts the whole batch without writing anything.
    ///
    /// # Errors
    ///
    /// See [`KvStore::set_batch`](crate::KvStore::set_batch).
    pub async fn set_batch(&self, entries: &[(&str, &str)]) -> Result<()> {
        for (key, _) in entries {
            validate_kv_name(key, "key")?;
        }
        self.connection.begin_transaction_raw().await?;
        let mut inner: Result<()> = Ok(());
        for (key, value) in entries {
            if let Err(e) = self.upsert(key, value).await {
                inner = Err(e);
                break;
            }
        }
        match &inner {
            Ok(()) => self.connection.commit_raw().await?,
            Err(_) => {
                let _ = self.connection.rollback_raw().await;
            }
        }
        inner
    }
}

impl AsyncConnection {
    /// Opens a handle to a named KV store, creating the table if needed.
    ///
    /// # Errors
    ///
    /// See [`Connection::kv_store`](crate::Connection::kv_store).
    pub async fn kv_store(&self, name: &str) -> Result<AsyncKvStore<'_>> {
        AsyncKvStore::new(self, name).await
    }

    /// Async twin of [`Connection::kv_store_in`](crate::Connection::kv_store_in).
    ///
    /// # Errors
    ///
    /// See [`Connection::kv_store_in`](crate::Connection::kv_store_in).
    pub async fn kv_store_in(&self, database: &str, name: &str) -> Result<AsyncKvStore<'_>> {
        AsyncKvStore::with_target(self, name, &kv_target_prefix(database)?).await
    }

    /// Lists the names of every KV store that currently holds at least one key.
    ///
    /// # Errors
    ///
    /// See [`Connection::kv_list_stores`](crate::Connection::kv_list_stores).
    pub async fn kv_list_stores(&self) -> Result<Vec<String>> {
        self.kv_list_stores_impl(KV_TABLE).await
    }

    /// Async twin of
    /// [`Connection::kv_list_stores_in`](crate::Connection::kv_list_stores_in).
    ///
    /// # Errors
    ///
    /// See [`Connection::kv_list_stores_in`](crate::Connection::kv_list_stores_in).
    pub async fn kv_list_stores_in(&self, database: &str) -> Result<Vec<String>> {
        let table_ref = format!("{}.{KV_TABLE}", kv_target_prefix(database)?);
        self.kv_list_stores_impl(&table_ref).await
    }

    /// Shared body for [`kv_list_stores`](Self::kv_list_stores) /
    /// [`kv_list_stores_in`](Self::kv_list_stores_in): the async twin of the sync
    /// `kv_list_stores_impl`. Factored out so the default and location-aware
    /// paths cannot drift.
    async fn kv_list_stores_impl(&self, table_ref: &str) -> Result<Vec<String>> {
        self.execute_command(&kv_create_table_sql(table_ref))
            .await?;
        let mut result = self
            .execute_query(&format!(
                "SELECT DISTINCT store_name FROM {table_ref} ORDER BY store_name ASC"
            ))
            .await?;
        let mut names = Vec::new();
        while let Some(chunk) = result.next_chunk().await? {
            for row in &chunk {
                if let Some(name) = row.get::<String>(0) {
                    names.push(name);
                }
            }
        }
        Ok(names)
    }
}