Skip to main content

Database

Struct Database 

Source
pub struct Database { /* private fields */ }
Expand description

A Redis database, backed by a lazily-built connection pool.

Implementations§

Source§

impl Database

Source

pub const fn new(name: &'static str) -> Self

Declares a new Redis database.

This function is const so it can initialize a module-scope static. The connection pool is created on first use. Chain builder methods to configure options:

use encore::storage::redis::Database;

static SESSIONS: Database = Database::new("sessions");
static LEDGER: Database = Database::new("ledger").persistent();
Source

pub const fn named(name: &'static str) -> Self

References an existing Redis database by name. To declare a new database, use Database::new instead.

name must be a string literal so Encore can resolve it statically. Referenced databases take no configuration options; options are set where the database is declared.

Source

pub const fn persistent(self) -> Self

Marks the database as persistent so its data survives restarts and is never evicted. Without this option, the database behaves as a cache and entries may be evicted or lost on restart.

Must be called as part of the static declaration.

Source

pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self

Attaches a classification tag (key, value) to the database, such as .tag("data", "pii"), for policy evaluation.

Call once per tag with unique keys. Both key and value must be string literals of at most 63 characters (up to 32 tags per database). Keys may contain lowercase letters, digits, _, and -, must start with a letter, and cannot start with encore (reserved for Encore). Values use the same character set or may be empty.

Must be called as part of the static declaration.

use encore::storage::redis::Database;

static SESSIONS: Database = Database::new("sessions").tag("data", "pii");
Source

pub const fn write(&'static self) -> DatabaseRef

A handle to the database that can read and write.

const, so a handle can initialize a module-scope static.

Source

pub const fn read(&'static self) -> ReadOnlyDatabaseRef

A handle to the database that can only read. It reads from a read replica where the database has a read-only connection pool on one, and otherwise from the primary. Either way a command that writes is refused before it is sent. To always read from the primary server, use Database::read_primary.

Source

pub const fn read_primary(&'static self) -> ReadOnlyDatabaseRef

A handle to the database that can only read, and reads from the primary server even where there are read replicas. A command that writes is refused before it is sent.

Source§

impl Database

Source

pub fn generic(&self) -> Commands<'_>

Commands that work on a key of any type: expiry, deletion, renaming.

Source

pub fn string(&self) -> Commands<'_>

Commands on strings, which is what a plain value is.

Source

pub fn bitmap(&self) -> Commands<'_>

Commands on the bits of a string.

Source

pub fn hash(&self) -> Commands<'_>

Commands on hashes: a key holding fields, each with a value.

Source

pub fn list(&self) -> Commands<'_>

Commands on lists.

Source

pub fn set(&self) -> Commands<'_>

Commands on sets.

Source

pub fn sorted_set(&self) -> Commands<'_>

Commands on sorted sets: members ordered by a score.

Source

pub fn geo(&self) -> Commands<'_>

Commands on geospatial indexes.

Source

pub fn stream(&self) -> Commands<'_>

Commands on streams.

Source

pub fn hyperloglog(&self) -> Commands<'_>

Commands on HyperLogLogs: estimates of how many distinct elements were added.

Source

pub fn pubsub(&self) -> Commands<'_>

Publishing to channels, and subscribing to them.

Source

pub fn pipeline(&self) -> Pipeline<'_>

A batch of commands sent in one round trip. Not a transaction: other clients’ commands may run between them, and one failing does not stop the rest.

let mut pipe = SESSIONS.pipeline();
pipe.string().get("name:1");
pipe.string().get("name:2");
let (first, second): (Option<String>, Option<String>) = pipe.exec().await?;
Source

pub fn transaction(&self) -> Transaction<'_>

A transaction (MULTI/EXEC): the commands queued on it run together, with no other client’s in between, or not at all.

Nothing is sent until Transaction::exec, so a transaction is never left open across an .await.

let mut tx = LEDGER.transaction();
tx.string().incr("hits", 1);
tx.hash().hset("user:1", "seen", now);
let (hits, _): (i64, u64) = tx.exec().await?;
Source

pub async fn acquire(&self) -> Result<Connection, Error>

Takes a connection out of the pool, for what must run on one connection: watching keys, then a transaction that depends on them. It is returned to the pool when dropped.

Source

pub async fn watch<T>( &self, keys: impl ToRedisArgs, body: impl AsyncFnMut(&Connection, &mut WatchedTransaction<'_>) -> Result<T, Error>, ) -> Result<T, Error>

Runs body as an optimistic transaction watching keys.

Read values through the connection and queue writes on the transaction. Changes are applied atomically only if none of keys changed in the meantime; otherwise, body is retried.

let left: i64 = LEDGER
    .watch("balance", async |conn, tx| {
        let balance: i64 = conn.string().get("balance").await?;
        tx.string().set("balance", balance - 10);
        Ok(balance - 10)
    })
    .await?;
Source

pub fn script(&self, script: &'static Script) -> Invocation<'_>

A call to script, to give its keys and arguments and then Invocation::invoke.

Source

pub fn command(&self, name: &'static str) -> CommandInvocation<'_>

Builds an arbitrary Redis command by name (for example, "OBJECT").

name must be a string literal. Pass arguments in order using CommandInvocation::key and CommandInvocation::arg, then call CommandInvocation::invoke. See the module docs for validation rules.

Source

pub fn connection_string(&self) -> Result<String, Error>

Returns a Redis connection URL for use with external clients.

External clients connect directly without this SDK’s key prefix (see the module docs), so keys written there do not match the unprefixed names used by this SDK.

Auto Trait Implementations§

§

impl !Freeze for Database

§

impl !RefUnwindSafe for Database

§

impl !UnwindSafe for Database

§

impl Forget for Database

§

impl Move for Database

§

impl Send for Database
where &'static str: Send, OnceLock<Arc<Client>>: Send,

§

impl Sync for Database

§

impl Unpin for Database
where &'static str: Unpin, Align4<u32>: Unpin, Arc<Client>: Unpin,

§

impl UnsafeUnpin for Database
where &'static str: UnsafeUnpin, Align4<u32>: UnsafeUnpin, *const ArcInner<Client> is !null: UnsafeUnpin, PhantomData<ArcInner<Client>>: UnsafeUnpin, PhantomData<Arc<Client>>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T, U> ExactFrom<T> for U
where U: TryFrom<T>,

Source§

fn exact_from(value: T) -> U

Source§

impl<T, U> ExactInto<U> for T
where U: ExactFrom<T>,

Source§

fn exact_into(self) -> U

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

impl<T, U> OverflowingInto<U> for T
where U: OverflowingFrom<T>,

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T, U> RoundingInto<U> for T
where U: RoundingFrom<T>,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> SaturatingInto<U> for T
where U: SaturatingFrom<T>,

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T, U> WrappingInto<U> for T
where U: WrappingFrom<T>,

Source§

fn wrapping_into(self) -> U