Key/value cache from Rust
The server has a built-in, Redis-compatible key/value cache, and rasterizeddb_client gives you a typed API for it: plain values, typed maps under a key prefix, closure queries, #[derive(Model)] structs stored as hashes, and a read-through cache in front of your ORM tables. Use it for sessions, counters, rate limits, leases and cached rows when you would rather not run a separate Redis next to the database.
The client talks to the cache over its ordinary native connection, as KV … statements. You do not need the server's Redis port, and nothing extra to install.
Before you start
On the server
Nothing needs to be turned on. The key/value cache is part of the standard server build, allocates nothing until first used, and answers KV statements on every SQL connection whether or not the Redis port (--kv-port) is open.
Each database has a store of its own. The client uses the store of the database it is connected to (see Connecting for choosing one).
What you may want to set on the server, all described in Key/value cache:
--kv-max-memoryand--kv-eviction, to bound the store's memory and decide what goes when it is full.--kv-persist, to keep the store across restarts. Without it the store is a cache and starts empty after a restart.--kv-port, only if other programs should reach the same store with a Redis client.
In your project
[dependencies]
rasterizeddb_client = "1.1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }#[derive(Model)] (needed for models as hashes and the read-through cache) comes with the default derive feature. For JSON values with KvJson, add the serde_json feature and serde:
[dependencies]
rasterizeddb_client = { version = "1.1", features = ["serde_json"] }
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }use rasterizeddb_client::prelude::*; brings in Client, Options, Result, Model, ModelExt, ModelQuery and the KvKey and KvValue traits. The other key/value types live in rasterizeddb_client::kv (Kv, KvMap, KvQuery, KvRepo, KvJson) and rasterizeddb_client::orm (Cached, CACHE_PREFIX).
Typed values
client.kv() returns a Kv handle. set_as and get_as store and read one value of any supported type at a key:
use std::time::Duration;
use rasterizeddb_client::prelude::*;
#[tokio::main]
async fn main() -> rasterizeddb_client::Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let kv = client.kv();
kv.set_as("visits", &41i32, None).await?;
let visits: Option<i32> = kv.get_as::<i32>("visits").await?;
println!("visits = {visits:?}");
// Expires after ten minutes.
kv.set_as("banner", &"Spring sale".to_string(), Some(Duration::from_secs(600))).await?;
println!("banner = {:?}", kv.get_as::<String>("banner").await?);
Ok(())
}visits = Some(41)
banner = Some("Spring sale")get_as returns None for a key that does not exist (or has expired). A key is any type the client can send as a parameter, here a &str. Kv is Copy, so pass it around freely.
Typed maps
A KvMap<K, V> keeps values of one type under one key prefix. client.kv().map::<K, V>("sessions") stores each entry at sessions:<key>, so maps with different prefixes never collide and other tools see readable keys.
use std::time::Duration;
use rasterizeddb_client::prelude::*;
#[tokio::main]
async fn main() -> rasterizeddb_client::Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let names = client.kv().map::<i64, String>("user_name");
names.set(&7, &"Ada".to_string()).await?;
names.set_with_ttl(&8, &"Grace".to_string(), Duration::from_secs(3600)).await?;
println!("{:?}", names.get(&7).await?);
println!("{:?}", names.get_many(&[&7, &8, &9]).await?);
println!("contains 9: {}", names.contains(&9).await?);
names.remove(&7).await?;
Ok(())
}Some("Ada")
[Some("Ada"), Some("Grace"), None]
contains 9: falseclient.kv().map::<K, V>("") (an empty prefix) is the whole keyspace, with no prefix added.
Key and value types
Keys and values are stored as their text form, the same text the server would print for that value, so a Redis client reading the same store sees 42, t, 2026-11-27 10:15:00 and so on.
| Type | As a key | As a value | Stored as |
|---|---|---|---|
String | yes | yes | the text itself |
i16, i32, i64, u64, i128 | yes | yes | decimal digits |
f32, f64 | yes | yes | Rust's shortest round-trip form (0.1, 1.0); NaN, Infinity, -Infinity |
bool | yes | yes | t or f |
Vec<u8> | yes | yes | the bytes unchanged |
Uuid, Timestamp, Date, Time, Interval, Numeric | yes | yes | their usual text form |
#[derive(SqlEnum)] enums | yes | yes | the variant's name, in snake case unless renamed |
arrays (Vec<i64>, Vec<String>, …) | yes | yes | array text, {1,-2} |
KvJson<T> (feature serde_json) | no | yes | T's JSON |
Any type that implements both ToSql and FromSql works as a value, and any ToSql type works as a key: these are blanket implementations of KvValue and KvKey. A NULL (None in an Option) is neither a key nor a value: storing one fails with Error::Param. Delete the key instead.
A KvMap key type must be sized: use KvMap<String, _> and pass &"key".to_string(), not a &str.
JSON values
Wrap any serde type in KvJson to store it as JSON (feature serde_json):
use std::time::Duration;
use rasterizeddb_client::kv::KvJson;
use rasterizeddb_client::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Cart {
items: Vec<String>,
total_cents: i64,
}
#[tokio::main]
async fn main() -> rasterizeddb_client::Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let carts = client.kv().map::<i64, KvJson<Cart>>("cart");
let cart = Cart { items: vec!["tea".into(), "scones".into()], total_cents: 1250 };
carts.set_with_ttl(&7, &KvJson(cart), Duration::from_secs(1800)).await?;
if let Some(KvJson(cart)) = carts.get(&7).await? {
println!("{} items, {} cents", cart.items.len(), cart.total_cents);
}
Ok(())
}2 items, 1250 centsA stored value that is not valid JSON for T fails the read with Error::Column.
TTLs and expiry
A key with a TTL is removed by the server when its time runs out; reads after that see None.
| Call | What it does |
|---|---|
set_with_ttl(&key, &value, ttl) / kv.set_as(key, &value, Some(ttl)) | Store the value and its TTL in one command. |
set_if_absent(&key, &value, Some(ttl)) | Store only if the key is absent, with a TTL. |
expire(&key, ttl) | Give an existing key a TTL. Returns false if there was no key. |
ttl(&key) | Time left. None for a key with no TTL, and also for a missing key. |
kv.persist(key_bytes) | Remove a key's TTL (byte-level Kv only). |
TTLs are sent in whole milliseconds; anything under 1 ms becomes 1 ms. A plain set (no TTL) on a key that had one replaces the value and drops the TTL, as Redis's SET does.
Counters and atomic operations
Each command is atomic on its key on the server, so many clients can bump the same counter without losing updates:
use rasterizeddb_client::prelude::*;
#[tokio::main]
async fn main() -> rasterizeddb_client::Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let hits = client.kv().map::<String, i64>("hits");
for path in ["/", "/api/a", "/api/b", "/api/b"] {
hits.incr_by(&path.to_string(), 1).await?;
}
println!("/api/b: {:?}", hits.get(&"/api/b".to_string()).await?);
Ok(())
}/api/b: Some(2)incr_by starts from 0 when the key is absent and returns the new value. by may be negative. The value at the key must be an integer, or the server refuses it (Error::Server, Redis's ERR value is not an integer or out of range).
The atomic single-command operations are:
| Operation | Call |
|---|---|
| Add to an integer | KvMap::incr_by, Kv::incr_by |
| Add to a hash field's integer | Kv::hincr_by |
| Add to a sorted-set score | Kv::zincr_by |
| Set only if absent (a lock or lease) | KvMap::set_if_absent, Kv::set_if_absent |
| Set many keys at once | Kv::set_many (MSET) |
| Pop from a list | Kv::lpop, Kv::rpop |
Two separate calls are never atomic together. The client's connection has no MULTI/EXEC; for a group of commands that must apply together, use a Redis client on the server's Redis port.
Queries
map.query() (or client.kv().query::<K, V>() for the whole keyspace) builds a query over a map's entries. Key patterns are matched on the server; the closures run in your process.
use rasterizeddb_client::prelude::*;
#[tokio::main]
async fn main() -> rasterizeddb_client::Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let hits = client.kv().map::<String, i64>("hits");
// Keys starting with /api/, matched on the server; values tested here.
let busy: Vec<(String, i64)> = hits
.query()
.prefix("/api/")
.filter(|path, n| *n > 100 && !path.ends_with("/health"))
.limit(50)
.all()
.await?;
println!("{busy:?}");
// By key only: values are read only for keys that pass.
let found: Vec<(String, i32)> = client
.kv()
.query::<String, i32>()
.filter_keys(|key| key == "visits")
.all()
.await?;
println!("{found:?}");
// Remove every matching entry.
let removed = hits.query().pattern("/tmp/*").delete().await?;
println!("removed {removed}");
Ok(())
}How a query narrows:
| Step | Where it runs | What it does |
|---|---|---|
prefix("/api/") | server | Only keys (after the map's prefix) starting with this text. *, ?, [, ] and \ in it are taken literally. |
pattern("user:*:cart") | server | Only keys (after the map's prefix) matching a glob: * any run, ? one byte, [abc] one of. Replaces prefix, and the other way round. |
filter_keys(|k| …) | client | Only keys for which the closure holds, before any value is read. |
filter(|k, v| …) | client | Only entries for which the closure holds. Every value the steps above let through is read. |
limit(n) | client | At most n entries, in scan order (which is no particular order). |
lenient() | client | Skip keys or values that do not read as K or V, instead of failing. |
Then run it with all(), keys(), values(), first(), count() or delete(). A query's key type must also be a value type (K: KvKey + KvValue), because keys are read back as K.
A query reads keys with SCAN and values with MGET in batches of 500. It sees every key that existed for the whole scan, but it is not a snapshot: keys written or removed while it runs may or may not appear. A key holding a hash, list or set rather than a plain value is usually skipped, but when it is the only key in a batch the server answers WRONGTYPE and the query fails, so keep such keys out of a query's prefix. The cache has no index on values, so a value filter reads every value the key steps let through; keep hot paths on direct get calls.
Without lenient(), a key or value that does not read as the query's types fails the query with Error::Unsupported naming the key. This matters for whole-keyspace queries over a store that holds other kinds of entries.
Models as hashes
client.kv().repo::<M>() stores a #[derive(Model)] struct as a hash: one hash field per column, under the key <table>:<primary key>. It is the same struct the ORM maps, so a row can live in a table, in the cache, or both.
use std::time::Duration;
use rasterizeddb_client::prelude::*;
#[derive(Model, Debug, Clone)]
#[rdb(table = "sessions")]
struct Session {
#[rdb(primary_key)]
token: Uuid,
user_id: i64,
roles: Vec<String>,
seen: Timestamp,
}
#[tokio::main]
async fn main() -> rasterizeddb_client::Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let sessions = client.kv().repo::<Session>();
let s = Session {
token: Uuid::new_v4()?,
user_id: 7,
roles: vec!["staff".into()],
seen: Timestamp::now(),
};
sessions.save_with_ttl(&s, Duration::from_secs(3600)).await?;
let again: Option<Session> = sessions.get(&[&s.token]).await?;
println!("found: {}", again.is_some());
let theirs: Vec<Session> = sessions.filter(|x| x.user_id == 7).await?;
println!("user 7 has {} session(s)", theirs.len());
sessions.delete(&s).await?;
Ok(())
}found: true
user 7 has 1 session(s)How rows are stored:
- The key is the table name (the struct's name in snake case unless
#[rdb(table = "…")]says otherwise), then each primary-key column's text form, joined by:. A:or\inside a key value is escaped with\, so("a:b", "c")and("a", "b:c")are different keys.with_prefix("…")uses another prefix than the table name. - Each non-NULL column is a hash field named after the column. A NULL column has no field;
saveremoves it if an earlier save wrote one. - Primary-key values are passed in key-column order:
get(&[&tenant_id, &order_id])for a composite key. Passing the wrong number of values fails withError::Param. - The model must have a
#[rdb(primary_key)]field, and no key column may be NULL. Aserialkey is stored as given, so assign it before saving. - A stored hash missing a field for a non-
Optioncolumn (written by another version of the struct, or by hand) fails the read withError::Columnnaming the column. Extra fields are ignored.
all(), filter() and find() scan every key under the prefix and read each hash with its own command, one round trip per stored row. They suit small sets and admin tasks.
Read-through cache for models
client.cached::<M>(ttl) (or M::cached(&client, ttl)) puts the cache in front of a model's table. find answers from the cache when the row is there; on a miss it reads the table and stores the row for ttl. Writes through the same handle run the ORM's statement and then remove the row's cache entry, so the next read sees the change.
use std::time::Duration;
use rasterizeddb_client::prelude::*;
#[derive(Model, Debug, Clone)]
#[rdb(table = "profiles")]
struct Profile {
#[rdb(primary_key)]
id: i64,
name: String,
}
#[tokio::main]
async fn main() -> rasterizeddb_client::Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let profiles = client.cached::<Profile>(Duration::from_secs(30));
if let Some(mut p) = profiles.find(7i64).await? { // read from the table, then cached
let _again = profiles.find(7i64).await?; // answered by the cache
p.name = "Ada Lovelace".into();
profiles.update(&p).await?; // UPDATE, then the entry removed
}
Ok(())
}Cached takes the ORM's single-row writes: insert, update, upsert, delete, force_delete and restore, each the ORM call of the same name followed by removing the row's entry. find_by_key(&[&a, &b]) reads a row with a composite key.
What to know:
- Staleness is bounded by the TTL, and only by it. A write that does not go through this handle (another process, plain SQL, a bulk
query().update(), a PostgreSQL client) leaves the cached row as it was until its TTL runs out. So can a read racing a write: a reader that read the table just before the write and stores the row just after the write removed the entry puts the old row back. Choose the TTL as the staleness you accept. - Each entry is written with its TTL in one command, so no entry is ever left without one.
- A row that does not exist is not cached; the next
findreads the table again. Rowsfinddoes not return (such as soft-deleted ones) are not cached either. - Entries are tagged with the model's column names and types. After you change the struct's columns, an older entry reads as a miss and is overwritten.
- Entries live at
rdb_orm:<table>:<primary key>(CACHE_PREFIXis"rdb_orm");with_prefix("…")replacesrdb_orm:<table>. The value is a compact binary record, not a hash, so it is meant to be read throughCachedonly. Cachedtakes aClient, not a transaction: the cache is outside every transaction.
Invalidation
When a row changes outside the handle, remove its entry yourself:
use std::time::Duration;
use rasterizeddb_client::prelude::*;
#[derive(Model, Debug, Clone)]
#[rdb(table = "profiles")]
struct Profile {
#[rdb(primary_key)]
id: i64,
name: String,
}
#[tokio::main]
async fn main() -> rasterizeddb_client::Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let profiles = client.cached::<Profile>(Duration::from_secs(30));
client.exec("UPDATE profiles SET name = $1 WHERE id = $2", params!["Grace", 8i64]).await?;
profiles.invalidate_key(&[&8i64]).await?;
// Every cached profile at once, after a bulk change.
let removed = client.kv().map::<String, Vec<u8>>("rdb_orm:profiles").clear().await?;
println!("dropped {removed} cached profile(s)");
Ok(())
}invalidate(&row) does the same from a model value. Both return whether there was an entry to remove.
If a write through Cached commits but removing its entry then fails, the call returns Error::Unsupported saying so. The write is in the table; the cache serves the old row until its TTL runs out.
Caching patterns
Read-through for any value
For values that are not model rows, read the cache, and on a miss compute the value and store it with a TTL:
use std::time::Duration;
use rasterizeddb_client::prelude::*;
async fn order_count(client: &Client, day: &str) -> rasterizeddb_client::Result<i64> {
let counts = client.kv().map::<String, i64>("daily_orders");
let key = day.to_string();
if let Some(total) = counts.get(&key).await? {
return Ok(total);
}
let total: i64 = client
.fetch_scalar("SELECT COUNT(*) FROM orders WHERE day = $1", params![key])
.await?;
counts.set_with_ttl(&key, &total, Duration::from_secs(300)).await?;
Ok(total)
}
#[tokio::main]
async fn main() -> rasterizeddb_client::Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
println!("{}", order_count(&client, "2026-11-27").await?);
Ok(())
}Invalidate by calling counts.remove(&key) wherever the underlying data changes, or let the TTL bound the staleness.
A lock or lease
set_if_absent with a TTL lets exactly one caller win until the TTL runs out, even if that caller crashes:
use std::time::Duration;
use rasterizeddb_client::prelude::*;
#[tokio::main]
async fn main() -> rasterizeddb_client::Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let leases = client.kv().map::<String, Uuid>("lease");
let job = "nightly-report".to_string();
let me = Uuid::new_v4()?;
if leases.set_if_absent(&job, &me, Some(Duration::from_secs(300))).await? {
// ... do the work ...
// Release only if the lease is still ours (two commands, not atomic).
if leases.get(&job).await? == Some(me) {
leases.remove(&job).await?;
}
} else {
println!("another worker holds the lease");
}
Ok(())
}Make the TTL longer than the work. The check-then-remove at the end is two commands; if the lease expires between them, another worker's lease can be removed.
A fixed-window rate limit
use std::time::Duration;
use rasterizeddb_client::prelude::*;
async fn allow(client: &Client, user_id: i64) -> rasterizeddb_client::Result<bool> {
let window = client.kv().map::<i64, i64>("rate");
let n = window.incr_by(&user_id, 1).await?;
if n == 1 {
window.expire(&user_id, Duration::from_secs(60)).await?;
}
Ok(n <= 100)
}
#[tokio::main]
async fn main() -> rasterizeddb_client::Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
println!("allowed: {}", allow(&client, 7).await?);
Ok(())
}The increment and the expire are two commands. If the process stops between them, the counter has no TTL; check window.ttl(&user_id) and set one if you need to be strict.
Byte-level commands
Kv also has the common Redis commands on byte strings, for data that is not text or for structures the typed layers do not cover (lists, sets, sorted sets). Every argument is sent as hex and values come back as bytes, so any byte string is a key or a value.
use rasterizeddb_client::prelude::*;
#[tokio::main]
async fn main() -> rasterizeddb_client::Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let kv = client.kv();
// A leaderboard.
kv.zadd("board".as_bytes(), &[(1500.0, "ada".as_bytes()), (1320.0, "bob".as_bytes())]).await?;
for (member, score) in kv.zrange("board".as_bytes(), 0, 9, true).await? {
println!("{} {score}", String::from_utf8_lossy(&member));
}
// A hash.
kv.hset("user:7".as_bytes(), &[("name".as_bytes(), "Ada".as_bytes()), ("plan".as_bytes(), "pro".as_bytes())]).await?;
let plan = kv.hget("user:7".as_bytes(), "plan".as_bytes()).await?;
println!("plan = {:?}", plan.map(|v| String::from_utf8_lossy(&v).into_owned()));
// Any other command: the rows come back as the server answers them.
kv.rpush("recent".as_bytes(), &["a".as_bytes(), "b".as_bytes(), "c".as_bytes()]).await?;
kv.command("LTRIM", &["recent".as_bytes(), "0".as_bytes(), "1".as_bytes()]).await?;
let rows = kv.command("DBSIZE", &[]).await?;
if let Some(row) = rows.get(0) {
let keys: i64 = row.get(0)?;
println!("{keys} keys");
}
Ok(())
}command(name, args) sends any command the server supports (see the command list in Key/value cache). The name must be letters, digits and _ only. Value columns come back as bytea; integers, scores and a scan's cursor keep their types. Commands that need a connection of their own (MULTI, SUBSCRIBE, SELECT, AUTH, …) are refused by the server.
Inside a transaction
Kv::new(&tx) gives the same commands on a transaction's connection, and kv.map(…) and kv.repo() work on it too. The cache is not part of any SQL transaction: a command takes effect at once, and a rollback does not undo it. Write to the cache after the transaction commits when the two must agree.
use rasterizeddb_client::kv::Kv;
use rasterizeddb_client::prelude::*;
#[tokio::main]
async fn main() -> rasterizeddb_client::Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let tx = client.begin().await?;
tx.exec("UPDATE profiles SET name = $1 WHERE id = $2", params!["Grace", 8i64]).await?;
tx.commit().await?;
// After the commit, so a rollback cannot leave the cache ahead of the table.
Kv::new(&client).map::<i64, String>("profile_name").remove(&8).await?;
Ok(())
}Using it with client-side sharding
With a sharding router, router.kv_for(key), router.cached::<M>(ttl) and router.kv_repo::<M>() place each entry on the shard its row lives on. See Sharding.
Reference
Client
| Call | What it does |
|---|---|
client.kv() | The Kv handle for the connected database's store. |
client.cached::<M>(ttl) | A read-through Cached<M> keeping each row for ttl. Also M::cached(&client, ttl). |
Kv (typed calls)
| Call | What it does |
|---|---|
Kv::new(&executor) | The same commands on any executor: a Client or a Transaction. |
get_as::<T>(key) | The value at key read as T, or None. |
set_as(key, &value, ttl: Option<Duration>) | Store a typed value, with an optional TTL. |
map::<K, V>(prefix) | A KvMap under prefix:; "" for the whole keyspace. |
query::<K, V>() | A KvQuery over the whole keyspace. |
repo::<M>() | A KvRepo storing model M as hashes under <table>:. |
Kv (byte-level calls)
Keys, values, fields and members are &[u8]; lists of them are &[&[u8]].
| Call | Command | Returns |
|---|---|---|
command(name, args) | any | Rows, value columns as bytea |
get(key) | GET | Option<Vec<u8>> |
set(key, value, ttl) | SET … [PX ms] | () |
set_if_absent(key, value, ttl) | SET … NX [PX ms] | bool: whether it was set |
get_many(keys) | MGET | Vec<Option<Vec<u8>>>, in order |
set_many(&[(key, value)]) | MSET | () |
del(keys) | DEL | i64: keys removed |
exists(key) | EXISTS | bool |
incr_by(key, by) | INCRBY | i64: the new value |
expire(key, ttl) | PEXPIRE | bool: whether the key existed |
persist(key) | PERSIST | bool: whether it had a TTL to remove |
ttl(key) | PTTL | Option<Duration>: None for no TTL or no key |
keys(pattern) | SCAN … MATCH | Vec<Vec<u8>>: every matching key |
hset(key, &[(field, value)]) | HSET | i64: fields that were new |
hget(key, field) | HGET | Option<Vec<u8>> |
hgetall(key) | HGETALL | Vec<(Vec<u8>, Vec<u8>)>; empty for no key |
hdel(key, fields) | HDEL | i64: fields removed |
hincr_by(key, field, by) | HINCRBY | i64: the new value |
rpush(key, values) / lpush(key, values) | RPUSH / LPUSH | i64: the list's length after |
lpop(key) / rpop(key) | LPOP / RPOP | Option<Vec<u8>> |
lrange(key, start, stop) | LRANGE | Vec<Vec<u8>>; negative counts from the end, 0, -1 is all |
llen(key) | LLEN | i64; 0 for no list |
sadd(key, members) | SADD | i64: members that were new |
srem(key, members) | SREM | i64: members removed |
sismember(key, member) | SISMEMBER | bool |
smembers(key) | SMEMBERS | Vec<Vec<u8>> |
scard(key) | SCARD | i64 |
zadd(key, &[(score, member)]) | ZADD | i64: members that were new |
zscore(key, member) | ZSCORE | Option<f64> |
zrange(key, start, stop, rev) | ZRANGE … [REV] WITHSCORES | Vec<(Vec<u8>, f64)>, by rank; rev for highest first |
zrem(key, members) | ZREM | i64: members removed |
zincr_by(key, member, by) | ZINCRBY | f64: the new score |
del, get_many, set_many, hset and hdel with an empty list send nothing and return the empty result.
KvMap<K, V>
| Call | What it does |
|---|---|
get(&key) | The value, or None. |
set(&key, &value) | Store with no TTL. |
set_with_ttl(&key, &value, ttl) | Store, expiring after ttl. |
set_if_absent(&key, &value, ttl: Option<Duration>) | Store only if absent; whether it was stored. |
remove(&key) | Delete; whether there was a value. |
contains(&key) | Whether the key has a value. |
expire(&key, ttl) | Set a TTL; whether the key existed. |
ttl(&key) | Time left; None without a TTL or a value. |
get_many(&[&key, …]) | Each key's value, None for missing ones, in one command. |
incr_by(&key, by) | Add to an integer counter, from 0; the new value. |
full_key(&key) | The full stored key, prefix:key, as bytes. |
raw_keys() | Every key's suffix after prefix:, as bytes. |
clear() | Remove every key under the prefix; the number removed. Refused for an empty prefix. |
query() | A KvQuery over this map's entries. |
KvQuery<K, V>
| Call | What it does |
|---|---|
prefix(text) | Keys starting with text (after the map's prefix), on the server. |
pattern(glob) | Keys matching a glob (after the map's prefix), on the server. |
filter_keys(closure) | Keys for which Fn(&K) -> bool holds, before values are read. |
filter(closure) | Entries for which Fn(&K, &V) -> bool holds. |
limit(n) | At most n entries. |
lenient() | Skip entries that do not read as K/V instead of failing. |
all() | The matching (K, V) entries. |
keys() | The matching keys; reads no values unless there is a filter. |
values() | The matching values. |
first() | The first matching entry in scan order, or None. |
count() | How many entries match. |
delete() | Remove the matching entries; how many were removed. Refused with no prefix, pattern or filter on the whole keyspace. |
KvRepo<M>
| Call | What it does |
|---|---|
with_prefix(prefix) | Use another key prefix than the table name. |
save(&row) | Store the row's columns as a hash. |
save_with_ttl(&row, ttl) | Store it, then set a TTL on the whole hash. |
get(&[&key, …]) | The row with that primary key, or None. |
exists(&[&key, …]) | Whether that row is stored. |
delete(&row) | Remove the row's hash; whether there was one. |
delete_key(&[&key, …]) | The same, by primary key. |
expire(&row, ttl) | Set a TTL on the row's hash; whether it was stored. |
key_for(&[&key, …]) | The hash key for that primary key, as bytes. |
all() | Every stored row of this model. |
filter(closure) | Every stored row for which Fn(&M) -> bool holds. |
find(closure) | The first stored row, in scan order, for which it holds. |
Cached<M>
| Call | What it does |
|---|---|
find(key) | The row with that single-column primary key: from the cache, or read from the table and cached. |
find_by_key(&[&key, …]) | The same for a composite key, in key-column order. |
insert(&row), update(&row), upsert(&row), restore(&row) | The ORM write, then the row's entry removed; returns the stored row. |
delete(&row), force_delete(&row) | The ORM delete, then the entry removed; whether a row was deleted. |
invalidate(&row) | Remove the row's entry; whether there was one. |
invalidate_key(&[&key, …]) | The same, by primary key. |
with_prefix(prefix) | Another key prefix than rdb_orm:<table>. |
ttl() | The TTL entries are stored with. |
key_for(&[&key, …]) | The cache key for that primary key, as bytes. |
Traits and helpers
| Item | What it is |
|---|---|
KvKey | A key: key_bytes() gives its text form. Implemented for every ToSql type. |
KvValue | A value: encode() and decode(bytes). Implemented for every type that is ToSql and FromSql, and for KvJson<T>. Implement it yourself for your own encoding. |
KvJson<T> | A serde type stored as JSON (feature serde_json). |
kv::text_form(¶m) | A parameter's stored text form as bytes; None for a NULL. |
kv::push_text_form(&mut out, ¶m) | The same, appended to out; false for a NULL. |
orm::CACHE_PREFIX | "rdb_orm", the read-through cache's key prefix. |
Errors
Key/value calls fail with the client's ordinary Error (see Errors):
| Error | When |
|---|---|
Error::Server | The server refused the command: a wrong type for the key (WRONGTYPE …), a non-integer under incr_by, a full store under --kv-eviction noeviction (OOM command not allowed …), an administrative command without a superuser role, or a command SQL cannot run (MULTI, SUBSCRIBE, …). |
Error::Column | A stored value does not read as the type asked for (get, get_as, KvMap::get), or a stored hash is missing a non-NULL column of the model. |
Error::Param | A NULL key or value, the wrong number of primary-key values, a NULL primary-key column, or a command name that is not letters, digits and _. |
Error::Unsupported | clear() on the whole keyspace, delete() with nothing to narrow it, a query entry that does not read as K/V (without lenient()), a model with no primary key, or a scan that never finishes. From Cached: the server's key/value cache refused a call, or a write committed but its entry could not be removed. |
Error::Transport | The connection failed. A command may or may not have run. |
Limits
- No two commands are atomic together.
KvRepo::save(a hash write, then removing NULL fields),save_with_ttl(then a TTL) and the check-then-act patterns above are separate commands. There is noMULTI/EXECon the client's connection; use a Redis client on the server's Redis port for that. - The cache is not transactional. A
KVcommand sent on a transaction's connection takes effect at once and survives a rollback. - Queries,
keys,raw_keys,clear,KvRepo::all/filter/findread bySCAN: complete, but not a snapshot. There is no index on values or on hash fields; filters read every candidate.KvReposcans read one hash per round trip. - A scan that has not finished after a million rounds of 500 keys stops with an error.
ttl()cannot tell a key with no TTL from a missing key; usecontains/existsfor that.- TTLs have millisecond resolution.
- The read-through cache only sees writes made through its own handle. Anything else is visible after the TTL, or after you invalidate the entry.
- The store is a cache: without
--kv-persiston the server it is empty after a restart, and with--kv-max-memoryand an eviction policy keys can disappear at any time. Code that reads the cache must handle a miss. - The client reaches the store of the database it is connected to. Other databases' stores need a connection to those databases.