core_crypto_keystore/traits/
entity.rs

1use std::borrow::Borrow;
2
3use async_trait::async_trait;
4
5use crate::{
6    CryptoKeystoreResult,
7    traits::{
8        EntityBase, KeyType, OwnedKeyType,
9        primary_key::{BorrowPrimaryKey, PrimaryKey},
10    },
11};
12
13/// Something which can be stored in our database.
14///
15/// It has a primary key, which uniquely identifies it.
16#[cfg_attr(target_family = "wasm", async_trait(?Send))]
17#[cfg_attr(not(target_family = "wasm"), async_trait)]
18pub trait Entity: EntityBase + PrimaryKey {
19    /// Get an entity by its primary key.
20    ///
21    /// For entites whose primary key has a distinct borrowed type, it is best to implement this as a direct
22    /// passthrough:
23    ///
24    /// ```rust,ignore
25    /// async fn get(conn: &mut Self::ConnectionType, key: &Self::PrimaryKey) -> CoreCryptoKeystoreResult<Option<Self>> {
26    ///     Self::get_borrowed(conn, key).await
27    /// }
28    /// ```
29    async fn get(conn: &mut Self::ConnectionType, key: &Self::PrimaryKey) -> CryptoKeystoreResult<Option<Self>>;
30
31    /// Count the number of entities of this type in the database.
32    async fn count(conn: &mut Self::ConnectionType) -> CryptoKeystoreResult<u32>;
33
34    /// Retrieve all entities of this type from the database.
35    async fn load_all(conn: &mut Self::ConnectionType) -> CryptoKeystoreResult<Vec<Self>>;
36}
37
38#[cfg_attr(target_family = "wasm", async_trait(?Send))]
39#[cfg_attr(not(target_family = "wasm"), async_trait)]
40pub trait EntityGetBorrowed: Entity + BorrowPrimaryKey {
41    /// Get an entity by a borrowed form of its primary key.
42    async fn get_borrowed(
43        conn: &mut Self::ConnectionType,
44        key: &Self::BorrowedPrimaryKey,
45    ) -> CryptoKeystoreResult<Option<Self>>
46    where
47        for<'pk> &'pk Self::BorrowedPrimaryKey: KeyType;
48}