Administration API
client.admin() gives you the server's administrative statements as typed Rust calls: key/value stores, table placement, indexes, partitions, roles, backups, configuration, statistics and replication. Use it when an application or a deployment tool sets up and inspects its own database, instead of building statement strings by hand.
Each call writes the statement the server reads, checks or quotes every value so that it cannot change the statement, sends it, and reads the answer into a struct. This page lists every call, the statement it sends and what it returns. What the statement then does on the server is described on the server pages linked from each section.
Before you start
Add the client and Tokio to Cargo.toml:
[dependencies]
rasterizeddb_client = "1.1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }Connect as usual (see Connecting) and call admin() on the client. Admin<'_> borrows the client, so it is cheap to make one per task or hold one for a block of calls:
use rasterizeddb_client::{Client, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let admin = client.admin();
for table in admin.tables().await? {
println!("{}: {} bytes on {}", table.name, table.total_bytes, table.storage);
}
Ok(())
}Everything on this page lives in the rasterizeddb_client::admin module: Admin, the definition builders (Store, Index, Role) and the result structs.
Who may run these calls
The server decides who may run each statement. Statements that administer the server (STORAGE …, BACKUP …, RESTORE …, SET CONFIG, REPLICATION …, CREATE ROLE/ALTER ROLE/DROP ROLE) and rdb_index_checkpoint need a superuser. The SHOW forms (stores, locations, stats, config, backups) only read state and need no superuser. Index, partition and vacuum calls are ordinary DDL and maintenance on your tables. A refused call returns Error::Server with the server's message (permission denied: … requires superuser).
Over TCP, log in with Login::password(user, password) as a superuser role. On a unix socket started with --rdb-socket-auth trust, a trust connection that names no role is not an administrator in a database that has roles: role statements, BACKUP, STORAGE, CREATE DATABASE and tables owned by other roles are refused, and it keeps only the tables it created itself and what PUBLIC is granted. A database with no roles at all is unchanged. To administer such a database over a trust socket, name a superuser role with Client::connect_as_role(addr, options, "role"). With a 1.0.1 server, a Login::Trust connection on such a socket was a superuser. See Connecting.
Errors and checks before sending
Values that the statement grammar cannot carry are refused before anything is sent, with Error::Param (a bad name or value) or Error::Unsupported (a combination the server has no statement for). A refusal never echoes a credential or password. Everything the server refuses is Error::Server. See Errors.
Store::to_sql() and Index::to_sql() return the exact statement a definition will send, which is useful for logging and tests. Store::to_sql() contains the credentials in clear text, so do not log it for a store that has them. The Debug output of Store and Role redacts credentials and passwords.
Key/value stores
A key/value store is a named place, an S3-compatible bucket or a directory on the server, that tables can be placed on. Define it once, then place or move tables onto it. The server side is described in Key/value storage.
Define a store
Store::s3(name, endpoint, bucket) or Store::directory(name, path) start a definition; the builder methods below add to it. A store name is letters, digits, _ and -, starting with a letter or _, at most 128 bytes.
| Builder | Sets | Server default |
|---|---|---|
Store::s3(name, endpoint, bucket) | An S3-compatible store: ENDPOINT, BUCKET | |
Store::directory(name, path) | A store in a directory on the server: PATH | |
.region(region) | REGION (S3) | us-east-1 |
.prefix(prefix) | PREFIX: the key prefix (S3) or subdirectory (directory) the store's data sits under | rdb |
.addressing(Addressing::Virtual | Addressing::Path) | ADDRESSING: https://bucket.endpoint/key or https://endpoint/bucket/key (MinIO and most self-hosted stores want Path) | virtual |
.credentials(access_key_id, secret_access_key) | The store's own key (S3 only). Without it the store signs with the server's AWS_* environment | environment |
.session_token(token) | A session token; needs .credentials(…) | |
.chunk_size(bytes) | CHUNK_SIZE: bytes per chunk object, a whole number of pages | 4 MiB |
.page_size(bytes) | PAGE_SIZE: bytes per page within a chunk | 64 KiB |
.cache_bytes(bytes) | CACHE_BYTES: the store's read cache | 256 MiB |
.spill_bytes(bytes) | SPILL_BYTES: unstored changes held in memory before they are written out | 8 MiB |
.compact_chunk_bytes(bytes) | COMPACT_CHUNK_BYTES | 1 MiB |
.chunk_fetch_pages(pages) | CHUNK_FETCH_PAGES | 4 |
.readahead_chunks(chunks) | READAHEAD_CHUNKS: chunks read ahead of a sequential scan | 2 |
.max_deltas(deltas) | MAX_DELTAS: change objects per chunk before it is compacted | 64 |
.flush_interval_ms(ms) | FLUSH_INTERVAL_MS | 200 |
.if_not_exists() | IF NOT EXISTS: succeed when the same store already exists |
The size builders take a plain byte count (.chunk_size(8 * 1024 * 1024)). What each tuning option does is in Tuning options.
.if_not_exists() makes the definition safe to run on every start of your application. Re-adding an identical store does nothing; re-adding a store of the same name with a different definition fails and names the fields that differ. Credentials given on this path are applied either way, which is how such a deployment rotates a key.
Credentials go to the server's secrets file, never to its store catalogue, and are redacted from the server log.
Store calls
| Call | Statement it sends | Returns |
|---|---|---|
add_store(&Store) | STORAGE ADD STORE [IF NOT EXISTS] <name> s3|dir WITH (…) | Vec<String>: the server's report, one line per row |
alter_store(name, &[(key, value), …]) | STORAGE ALTER STORE <name> SET key = 'value', … | Vec<String>: the report |
rotate_store_credentials(name, access_key_id, secret_access_key) | STORAGE ALTER STORE <name> SET ACCESS_KEY_ID = …, SECRET_ACCESS_KEY = … | Vec<String>: the report |
drop_store(name) | STORAGE DROP STORE <name> | Vec<String>: the report |
drop_store_if_exists(name) | SHOW STORAGE STORES, then STORAGE DROP STORE <name> if it is listed | bool: whether a store was dropped |
stores() | SHOW STORAGE STORES | Vec<StoreInfo> |
store(name) | SHOW STORAGE STORES, filtered to name | Option<StoreInfo> |
alter_storetakes the option names of the table above (CACHE_BYTES,ENDPOINT, …) as keys. A value may not contain a comma or the wordSET, whichALTER STOREcannot carry. The server refuses an address change (ENDPOINT,BUCKET,PREFIX,REGION,ADDRESSING,PATH) while tables are placed on the store, and a store the running server already has open keeps its settings and credentials until the server restarts. See Change, rotate and drop a store.drop_storeis refused while any table is placed on the store. It does not delete the store's objects.drop_store_if_existslooks first because the grammar has noIF EXISTS; two clients racing on it can still see an error.
StoreInfo is one row of SHOW STORAGE STORES:
| Field | Type | Meaning |
|---|---|---|
name | String | The store's name |
kind | String | dir, s3, or the name of a kind this server build cannot open |
endpoint | String | An S3 store's endpoint; a directory store's path |
region | String | An S3 store's region; empty for a directory store |
bucket | String | An S3 store's bucket; empty for a directory store |
prefix | String | The key prefix or subdirectory its data sits under |
addressing | String | path or virtual (S3 only) |
settings | String | Its tuning options, as the server prints them |
credentials | String | store when it has its own credentials, environment otherwise |
tables | i64 | Tables placed on it |
opened | bool | Whether the server has opened it (a table on it has been used) |
supported | bool | Whether this server build can open a store of its kind |
Adding a store does not contact it. A wrong endpoint or a rejected key shows up when the first table on it is used: check opened after creating that table.
Example: an S3 store set up on every start
use rasterizeddb_client::admin::{Addressing, Placement, Store};
use rasterizeddb_client::{Client, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let admin = client.admin();
let key_id = std::env::var("ARCHIVE_KEY_ID").expect("ARCHIVE_KEY_ID is set");
let secret = std::env::var("ARCHIVE_SECRET").expect("ARCHIVE_SECRET is set");
let report = admin
.add_store(
&Store::s3("archive", "https://s3.eu-central-1.amazonaws.com", "acme-rdb")
.region("eu-central-1")
.prefix("prod/archive")
.addressing(Addressing::Virtual)
.credentials(&key_id, &secret)
.if_not_exists(),
)
.await?;
for line in report {
println!("{line}");
}
// A local directory store, for scratch data.
admin
.add_store(&Store::directory("scratch", "/mnt/fast/kv").prefix("scratch").if_not_exists())
.await?;
// Pin a table to the store before creating it.
if !client.table_exists("events").await? {
admin.place_table("events", &Placement::kv("archive")).await?;
client
.run("CREATE TABLE events (id BIGINT NOT NULL, body TEXT, PRIMARY KEY (id))")
.await?;
}
// Tuning can change later.
admin.alter_store("archive", &[("CACHE_BYTES", "1GiB"), ("READAHEAD_CHUNKS", "4")]).await?;
if let Some(store) = admin.store("archive").await? {
println!("{}: {} table(s), opened = {}", store.name, store.tables, store.opened);
}
Ok(())
}Table placement
Placement says where a table's rows live:
| Value | Placement spec sent | Meaning |
|---|---|---|
Placement::Memory | 'memory:' | In memory only; gone at restart |
Placement::kv(store) | 'kv:<store>' | On a key/value store added with add_store |
Placement::directory(path) | '<path>' | In a directory on the server, which must be a storage location of the database |
| Call | Statement it sends | Returns |
|---|---|---|
place_table(table, &Placement) | STORAGE PLACE TABLE <table> AT <spec> | Vec<String>: the server's report |
move_table(table, &Placement) | STORAGE MOVE TABLE <table> TO <spec> | Vec<String>: the report, which says what the table gains or loses (write-ahead log, point-in-time backup) |
storage_locations() | SHOW STORAGE LOCATIONS | Vec<LocationInfo> |
storage_stats() | SHOW STORAGE STATS | Vec<Metric> |
place_table is for a table that does not exist yet; the server refuses it for one that does. Use move_table for an existing table: it copies the rows, switches the placement and deletes the originals, and statements on that table wait for it. Both take a table name of letters, digits, _ and - (no quoted names). See Storage pools and Key/value storage.
LocationInfo is one row of SHOW STORAGE LOCATIONS:
| Field | Type | Meaning |
|---|---|---|
location | String | The directory |
role | String | primary or backup |
weight | i64 | Its share of new tables under a weighted policy |
enabled | bool | Whether new tables may be placed in it |
is_database_directory | bool | Whether it is the database's own directory |
tables | i64 | Tables stored in it |
available_bytes | i64 | Free bytes on its filesystem |
total_bytes | i64 | Total bytes of its filesystem |
Example: move a table between backends
use rasterizeddb_client::admin::Placement;
use rasterizeddb_client::{Client, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let admin = client.admin();
for line in admin.move_table("old_events", &Placement::kv("archive")).await? {
println!("{line}");
}
admin.move_table("old_events", &Placement::directory("/mnt/nvme2/rasterizeddb")).await?;
for loc in admin.storage_locations().await? {
println!(
"{} ({}): {} table(s), {} of {} bytes free",
loc.location, loc.role, loc.tables, loc.available_bytes, loc.total_bytes
);
}
Ok(())
}Indexes
Index::on(table, &[columns]) starts an index definition over the columns, in order.
| Builder | Effect | Default |
|---|---|---|
Index::on(table, &[columns]) | An index on table over columns | |
.name(name) | The index's name | <table>_<columns>_idx, or <table>_<columns>_key when unique, columns joined by _ |
.using(IndexMethod) | How it is built | IndexMethod::BTree |
.unique() | A unique index, created as a UNIQUE constraint | |
.if_not_exists() | Succeed without doing anything when an index of this name exists | |
.index_name() | Returns the name the index will have | |
.to_sql() | Returns the statement create_index sends |
IndexMethod | Sent as | Use for |
|---|---|---|
BTree (default) | USING btree | Equality and ranges: =, <, BETWEEN, ORDER BY |
Hash | USING hash | Equality only, smaller and faster for it |
Gin | USING gin | A jsonb column, with the jsonb_ops operator class |
GinPathOps | USING gin (col jsonb_path_ops) | A jsonb column, with jsonb_path_ops |
| Call | Statement it sends | Returns |
|---|---|---|
create_index(&Index) | CREATE INDEX [IF NOT EXISTS] <name> ON <table> USING <method> (<columns>); for a unique one, ALTER TABLE <table> ADD CONSTRAINT [IF NOT EXISTS] <name> UNIQUE (<columns>) | () |
drop_index(name, if_exists) | DROP INDEX [IF EXISTS] <name> | () |
index_checkpoint(table) | SELECT rdb_index_checkpoint('<table>') | String: the server's report, "<clean> of <file sets> clean", then any file set that was not left clean |
- A unique index is always a B-tree;
.unique()with another method is refused withError::Unsupported. Because it is created as a constraint,drop_indexdoes not remove it: drop it withclient.run("ALTER TABLE users DROP CONSTRAINT users_email_key"). index_checkpointseals the table's indexes to disk now, so that a restart loads them instead of rebuilding them. It needs a superuser. See Indexes.
What each method is good for, partial and expression indexes, and full-text indexes are on Indexes; write those with client.run.
Example: indexes for a users table
use rasterizeddb_client::admin::{Index, IndexMethod};
use rasterizeddb_client::{Client, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let admin = client.admin();
if !client.table_exists("users").await? {
client
.run("CREATE TABLE users (id BIGINT NOT NULL, email TEXT, team TEXT, profile JSONB, PRIMARY KEY (id))")
.await?;
}
// ALTER TABLE users ADD CONSTRAINT IF NOT EXISTS users_email_key UNIQUE (email)
admin.create_index(&Index::on("users", &["email"]).unique().if_not_exists()).await?;
// CREATE INDEX IF NOT EXISTS users_team_idx ON users USING hash (team)
admin
.create_index(&Index::on("users", &["team"]).using(IndexMethod::Hash).if_not_exists())
.await?;
// CREATE INDEX IF NOT EXISTS users_profile_gin ON users USING gin (profile jsonb_path_ops)
admin
.create_index(
&Index::on("users", &["profile"])
.name("users_profile_gin")
.using(IndexMethod::GinPathOps)
.if_not_exists(),
)
.await?;
println!("{}", admin.index_checkpoint("users").await?);
admin.drop_index("users_team_idx", true).await?;
Ok(())
}Partitions
| Call | Statement it sends | Returns |
|---|---|---|
partition_by_hash(table, &[columns], partitions) | ALTER TABLE <table> PARTITION BY HASH (<columns>) [PARTITIONS <n>] | () |
partitions(table) | SHOW PARTITIONS <table> | Vec<PartitionInfo> |
partition_by_hash converts an existing plain table in place. The key has one to three columns (anything else is refused before sending); None for partitions takes the server's default of 64. The conversion rewrites every row while holding an exclusive lock on the table, cannot run inside a transaction, and needs the table to be in the database directory. To create a table partitioned from the start, use CREATE TABLE … PARTITION BY or the ORM. See Partitioning.
PartitionInfo is one row of SHOW PARTITIONS, in hash-range order:
| Field | Type | Meaning |
|---|---|---|
pid | i64 | The partition's id |
lo | String | The lower bound of its hash range, in hex |
hi | String | The upper bound of its hash range, in hex |
location | Option<String> | The directory or store holding its files |
state | String | materialized (it has files) or unmaterialized (no row written yet) |
row_slots | i64 | Row slots in use, including versions not yet vacuumed |
total_bytes | i64 | Its bytes on disk |
Example: convert a table and list its partitions
use rasterizeddb_client::{Client, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let admin = client.admin();
client
.run(
"CREATE TABLE orders (tenant_id BIGINT NOT NULL, id BIGINT NOT NULL, \
total NUMERIC(12,2), PRIMARY KEY (tenant_id, id))",
)
.await?;
admin.partition_by_hash("orders", &["tenant_id"], Some(16)).await?;
for p in admin.partitions("orders").await? {
println!("{:>3} {}..{} {} {} bytes", p.pid, p.lo, p.hi, p.state, p.total_bytes);
}
Ok(())
}Tables, columns and statistics
| Call | Statement it sends | Returns |
|---|---|---|
tables() | SHOW TABLES | Vec<TableInfo> |
columns(table) | DESCRIBE <table> | Vec<ColumnInfo>, dropped columns included |
vacuum(table, full) | VACUUM [FULL] [<table>]; None vacuums every table | u64: bytes reclaimed |
database_stats() | SHOW STATS | Vec<Metric> |
table_stats(table) | SHOW TABLE STATS <table> | Vec<Metric> |
vacuum(Some("t"), false) makes the space of dead rows reusable; full = true compacts the table and gives space back to the filesystem. See Maintenance.
TableInfo is one row of SHOW TABLES:
| Field | Type | Meaning |
|---|---|---|
name | String | The table's name |
storage | String | Where it is stored: file, memory, s3, kv-directory, … |
row_slots | i64 | Row slots in use: live rows and those vacuum has yet to reclaim |
columns | i64 | Columns, dropped ones included |
data_bytes | i64 | Bytes of row data |
pointer_bytes | i64 | Bytes of row pointers |
index_bytes | i64 | Bytes of index data |
total_bytes | i64 | All of the table's bytes |
reclaimable_bytes | i64 | Bytes vacuum could give back |
filters_ready | bool | Whether the filter index has caught up with the table |
immutable | bool | Whether the table is read-only |
primary_key | String | The primary key's columns, comma-separated; empty for none |
ColumnInfo is one row of DESCRIBE <table>:
| Field | Type | Meaning |
|---|---|---|
position | i64 | The column's position, from 1 |
name | String | The column's name |
data_type | String | The type as the engine names it: BIGINT, TEXT, NUMERIC(10,2), … |
size | i64 | Its stored width in bytes (0 for a variable-width type) |
offset | i64 | Its offset within a row, for a fixed-width column |
nullable | bool | Whether it may hold NULL |
unique | bool | Whether a unique constraint covers it alone |
primary_key | bool | Whether it is (part of) the primary key |
default | Option<String> | Its DEFAULT expression |
indexed | bool | Whether the filter index covers it |
zone_bounds | bool | Whether per-zone minimum and maximum are kept for it |
json_table | Option<String> | For a shredded JSON column, the table holding its keys |
dropped | bool | Whether it was dropped (a dropped column keeps its slot until a rewrite) |
Metric is one metric, value, detail row, the shape of every STATS and STATUS answer:
| Field | Type | Meaning |
|---|---|---|
metric | String | What is measured |
value | Option<String> | Its value, as text |
detail | Option<String> | What the value means, or where it came from |
Example: a space report
use rasterizeddb_client::{Client, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let admin = client.admin();
for t in admin.tables().await? {
println!(
"{:<20} {:>12} bytes, {:>10} reclaimable, key ({})",
t.name, t.total_bytes, t.reclaimable_bytes, t.primary_key
);
if t.reclaimable_bytes > 64 * 1024 * 1024 {
let freed = admin.vacuum(Some(&t.name), false).await?;
println!(" vacuum reclaimed {freed} bytes");
}
}
for c in admin.columns("users").await?.iter().filter(|c| !c.dropped) {
println!("{} {} nullable={} unique={}", c.name, c.data_type, c.nullable, c.unique);
}
for m in admin.table_stats("users").await? {
println!("{} = {}", m.metric, m.value.unwrap_or_default());
}
Ok(())
}Configuration
| Call | Statement it sends | Returns |
|---|---|---|
config() | SHOW CONFIG | Vec<ConfigEntry> |
set_config(key, value) | SET CONFIG <section.key> = <value> | String: the server's answer |
set_config takes the key as section.key ("wal.synchronous_commit"). The value is sent unquoted, so it is limited to letters, digits and . _ : - + /; anything else is refused before sending. A hot key changes at once and is saved for the next start, a key read at start-up is saved and shown under pending, and the per-database keys (replication.*, vacuum.enabled) change at once and are not saved. The full key list is in Configuration.
ConfigEntry is one row of SHOW CONFIG:
| Field | Type | Meaning |
|---|---|---|
section | String | The setting's section (wal, filter, vacuum, …) |
key | String | Its name within the section |
value | Option<String> | Its current value |
hot_reload | bool | Whether SET CONFIG changes it without a restart |
set_with | String | How to change it: a SET CONFIG statement or a flag |
help | String | What it does |
pending | Option<String> | A value saved for the next start, if one is waiting |
options | Option<String> | The values it takes, when they are a fixed list |
source | Option<String> | Where its value came from: command line, saved or default |
Example: change a setting and confirm it
use rasterizeddb_client::{Client, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let admin = client.admin();
println!("{}", admin.set_config("wal.synchronous_commit", "off").await?);
for e in admin.config().await?.iter().filter(|e| e.section == "wal") {
println!(
"{}.{} = {} (hot: {}, from: {}, pending: {})",
e.section,
e.key,
e.value.as_deref().unwrap_or("-"),
e.hot_reload,
e.source.as_deref().unwrap_or("-"),
e.pending.as_deref().unwrap_or("-"),
);
}
Ok(())
}Roles
Role::user(name) is a role that can log in (PostgreSQL's CREATE USER); Role::group(name) is one that cannot until given LOGIN. A role name may not be empty or contain whitespace or quotes.
| Builder | Clause |
|---|---|
Role::user(name) | LOGIN |
Role::group(name) | NOLOGIN |
.password(password) | PASSWORD '…'; the server stores a SCRAM-SHA-256 verifier, never the password |
.superuser() | SUPERUSER (otherwise NOSUPERUSER) |
| Call | Statement it sends | Returns |
|---|---|---|
create_role(&Role) | CREATE ROLE <name> LOGIN|NOLOGIN SUPERUSER|NOSUPERUSER [PASSWORD '…'] | () |
set_role_password(name, Some(password)) | ALTER ROLE <name> PASSWORD '…' | () |
set_role_password(name, None) | ALTER ROLE <name> PASSWORD NULL: removes the password | () |
drop_role(name, if_exists) | DROP ROLE [IF EXISTS] <name> | () |
Roles, logins and what each authentication mode does are described in Security.
Example: an application role
use rasterizeddb_client::admin::Role;
use rasterizeddb_client::{Client, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let admin = client.admin();
let password = std::env::var("APP_DB_PASSWORD").expect("APP_DB_PASSWORD is set");
admin.drop_role("app", true).await?;
admin.create_role(&Role::user("app").password(&password)).await?;
// Later: rotate it.
admin.set_role_password("app", Some("a-new-long-secret")).await?;
Ok(())
}More role attributes
These builder methods add attributes to a Role. They need rasterizeddb_client 1.1.0 and a 1.1.0 server, which reads the clauses.
| Builder | Clause |
|---|---|
.create_db() | CREATEDB: may create databases |
.create_role() | CREATEROLE: may create, alter and drop roles that are not superusers |
.bypass_rls() | BYPASSRLS: held to no row-level security policy (a superuser's to give) |
.connection_limit(n) | CONNECTION LIMIT n: at most n sessions at once; -1 for none |
.valid_until(timestamp) | VALID UNTIL '…': the password stops working after it (2027-01-01 00:00:00+00, or infinity) |
Changing and listing roles
| Call | Statement it sends | Returns |
|---|---|---|
alter_role(&Role) | ALTER ROLE <name> with every attribute the Role describes | () |
rename_role(from, to) | ALTER ROLE <from> RENAME TO <to>; an md5 password is cleared by it, a SCRAM one is kept | () |
set_role_setting(name, setting, Some(value)) | ALTER ROLE <name> SET <setting> = '<value>' | () |
set_role_setting(name, setting, None) | ALTER ROLE <name> RESET <setting> | () |
grant_role(role, member, admin) | GRANT <role> TO <member> [WITH ADMIN OPTION] | () |
revoke_role(role, member) | REVOKE <role> FROM <member> | () |
reassign_owned(from, to) | REASSIGN OWNED BY <from> TO <to>: what from owns becomes to's | () |
roles() | SELECT … FROM pg_catalog.pg_roles ORDER BY rolname | Vec<RoleInfo> |
alter_role writes every attribute, so build the Role with all of them as they should end up: Role::user("app") without .superuser() sends LOGIN NOSUPERUSER. The server keeps three settings per role, statement_timeout, lock_timeout and rdb.shape_change, and a PostgreSQL-protocol session of the role starts with them (set_role_setting("app", "statement_timeout", Some("5s"))).
RoleInfo is one role:
| Field | Type | Meaning |
|---|---|---|
name | String | Its name |
superuser | bool | SUPERUSER |
login | bool | LOGIN |
create_db | bool | CREATEDB |
create_role | bool | CREATEROLE |
bypass_rls | bool | BYPASSRLS |
connection_limit | i64 | -1 for no limit |
valid_until | Option<String> | When its password stops working, if ever |
config | Vec<String> | Its ALTER ROLE … SET values, as name=value |
Privileges
Grant describes privileges on objects, for grant (sent as GRANT) and revoke (sent as REVOKE):
| Builder | Effect |
|---|---|
Grant::privileges(&[…]) | These privileges: SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER, USAGE, EXECUTE, or ALL (upper-cased for you) |
Grant::columns(privilege, &[columns]) | One privilege on these columns only, SELECT (a, b); returns Result<Grant> |
.on_table(table) | ON TABLE <table> (a table or view) |
.on_tables(&[tables]) | ON TABLE a, b |
.on_all_tables() | ON ALL TABLES IN SCHEMA public: every table and view there is now |
.on_sequences(&[sequences]) | ON SEQUENCE … (USAGE, SELECT, UPDATE) |
.on_functions(&[functions]) | ON FUNCTION … (EXECUTE) |
.to(grantee) | Who receives it, or loses it; call again for more; "public" for every role |
.with_grant_option() | WITH GRANT OPTION on a grant: the grantees may pass it on |
.cascade() | CASCADE on a revoke: also take back what the grantees passed on |
.to_sql(grant) | Returns the GRANT (true) or REVOKE (false) statement |
A Grant needs an object, at least one privilege and at least one grantee; otherwise it is refused before sending.
| Call | Statement it sends | Returns |
|---|---|---|
grant(&Grant) | GRANT <privileges> ON <objects> TO <grantees> [WITH GRANT OPTION] | () |
revoke(&Grant) | REVOKE <privileges> ON <objects> FROM <grantees> [CASCADE] | () |
table_grants(table) | SELECT … FROM information_schema.table_privileges WHERE table_name = '<table>' | Vec<GrantInfo>, the owner's privileges included |
GrantInfo is one privilege on one table:
| Field | Type | Meaning |
|---|---|---|
grantor | String | Who granted it |
grantee | String | Who holds it; PUBLIC for every role |
table | String | The table or view |
privilege | String | SELECT, INSERT, … |
grantable | bool | Held with the grant option |
Example: a read-only group and an application role
use rasterizeddb_client::admin::{Grant, Role};
use rasterizeddb_client::{Client, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let admin = client.admin();
admin.create_role(&Role::group("readers")).await?;
admin.grant(&Grant::privileges(&["SELECT"]).on_all_tables().to("readers")).await?;
let password = std::env::var("APP_DB_PASSWORD").expect("APP_DB_PASSWORD is set");
admin
.create_role(&Role::user("app").password(&password).connection_limit(20))
.await?;
admin.grant_role("readers", "app", false).await?;
admin
.grant(&Grant::privileges(&["SELECT", "INSERT", "UPDATE"]).on_table("orders").to("app"))
.await?;
admin.set_role_setting("app", "statement_timeout", Some("5s")).await?;
for g in admin.table_grants("orders").await? {
println!("{} has {} on {} (grantable: {})", g.grantee, g.privilege, g.table, g.grantable);
}
for r in admin.roles().await? {
println!("{} login={} limit={} {:?}", r.name, r.login, r.connection_limit, r.config);
}
Ok(())
}Backups and restore
These calls drive the server's S3 backups. They need a server started with backups turned on; see Turn backups on. Otherwise each returns Error::Server.
| Call | Statement it sends | Returns |
|---|---|---|
backup_database() | BACKUP DATABASE: a snapshot to the configured destination | u64: compressed bytes written |
backup_wal() | BACKUP WAL: ships the write-ahead log written since the last shipment | u64: compressed bytes shipped |
backup_prune() | BACKUP PRUNE: removes backups past the retention policy | u64: objects removed |
backups() | SHOW BACKUPS | Vec<BackupInfo> |
backup_status() | SHOW BACKUP STATUS | Vec<Metric> |
restore(&RestoreTarget, to_dir) | RESTORE DATABASE … TO '<to_dir>' | RestoreReport |
restore rebuilds the database from the backups into a new directory, to_dir, which a server can then be started on. The running database is not touched, and the server refuses its own directory. Restoring in place is a start-up flag, not a statement; see Restore.
RestoreTarget | Sent as | Recovers to |
|---|---|---|
RestoreTarget::Latest | RESTORE DATABASE LATEST | The newest state the backups hold |
RestoreTarget::Snapshot(id) | RESTORE DATABASE FROM SNAPSHOT '<id>' | One snapshot, by the id backups() lists |
RestoreTarget::Lsn(lsn) | RESTORE DATABASE AT LSN <lsn> | A log position |
RestoreTarget::Time(t) | RESTORE DATABASE AT TIME '<t>' | A point in time, RFC 3339 (2026-11-16T12:00:00Z) |
BackupInfo is one row of SHOW BACKUPS:
| Field | Type | Meaning |
|---|---|---|
kind | String | snapshot or wal |
id | String | The backup's id, as RestoreTarget::Snapshot takes it |
created_at | String | When it was taken |
start_lsn | i64 | The first log position it covers |
end_lsn | i64 | The last log position it covers |
uncompressed_bytes | i64 | Its size before compression |
compressed_bytes | i64 | Its size as stored |
detail | Option<String> | Anything else the server reports about it |
RestoreReport says what a restore did:
| Field | Type | Meaning |
|---|---|---|
snapshot_id | String | The snapshot restored from |
target_dir | String | The directory the database was restored into |
recovered_to_lsn | String | The log position recovery reached |
files_restored | i64 | Files restored from the snapshot |
bytes_restored | i64 | Bytes restored from the snapshot |
segments_replayed | i64 | Log segments replayed on top of it |
records_applied | i64 | Log records applied |
records_discarded | i64 | Log records past the target, not applied |
Example: take a backup and test-restore it
use rasterizeddb_client::admin::RestoreTarget;
use rasterizeddb_client::{Client, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let admin = client.admin();
let written = admin.backup_database().await?;
println!("snapshot: {written} bytes compressed");
admin.backup_wal().await?;
for b in admin.backups().await? {
println!("{:<8} {} {} lsn {}..{}", b.kind, b.id, b.created_at, b.start_lsn, b.end_lsn);
}
let report = admin
.restore(&RestoreTarget::Time("2026-11-16T12:00:00Z".into()), "/srv/restore-test")
.await?;
println!(
"restored {} into {}: {} records applied, {} discarded, at {}",
report.snapshot_id,
report.target_dir,
report.records_applied,
report.records_discarded,
report.recovered_to_lsn
);
let removed = admin.backup_prune().await?;
println!("pruned {removed} object(s)");
Ok(())
}Replication
| Call | Statement it sends | Returns |
|---|---|---|
replication_stats() | SHOW REPLICATION STATS | Vec<Metric> |
replication_peers() | SHOW REPLICATION PEER STATUS | Vec<Record>, one per peer |
replication(statement) | REPLICATION <statement>, for the verbs not typed here | Vec<String>: the server's report lines |
Record is a row whose columns the client names but does not type. record.get("lag") returns the value of a column as Option<&Value>; record.columns and record.values hold them in order. The columns of a peer record are peer, address, remote_node, connected, paused, acked_seq, lag, queued, records_sent, batches_sent, dropped, codec, last_ratio, last_error and state.
replication sends its argument as written after REPLICATION , with no checking: pass only statements your own code writes ("PAUSE PEER 'berlin'", "CHECK"), never user input. The verbs are listed in Controlling replication from SQL.
Example: a peer status check
use rasterizeddb_client::{Client, Options, Result};
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let admin = client.admin();
for peer in admin.replication_peers().await? {
let show = |c: &str| peer.get(c).map(|v| v.to_string()).unwrap_or_default();
println!(
"{} at {}: connected={} lag={} last_error={}",
show("peer"),
show("address"),
show("connected"),
show("lag"),
show("last_error")
);
}
for line in admin.replication("PAUSE PEER 'berlin'").await? {
println!("{line}");
}
Ok(())
}Key/value cache
admin.kv() returns the same binary-safe key/value cache handle as client.kv(), for code that holds an Admin. See Key/value cache.
Limits
- Store names, table names in
place_table/move_table, store setting keys andset_configkeys must be letters, digits,_and-, starting with a letter or_. A table with a quoted name (spaces, mixed case meant literally) cannot be placed or moved with these calls; useclient.runwithSTORAGE PLACE TABLE/STORAGE MOVE TABLE. - A store value cannot contain both
'and", or a newline, tab or NUL. Analter_storevalue also cannot contain a comma orSET. - A
set_configvalue is limited to letters, digits and. _ : - + /. - Role names cannot contain whitespace or quotes.
drop_store_if_existschecks and then drops in two statements, not atomically.- A unique index made with
Index::unique()is a constraint:drop_indexdoes not drop it, and it cannot use a method other than B-tree. Partial, expression and full-text indexes have no builder; write them withclient.run. partition_by_hashconverts an existing table only, with a key of one to three columns.restorewrites to a new directory only; it cannot restore over the running database.replication(statement)and the rawclient.runare not checked; everything else is.- There is no typed call for storage locations and pools (
STORAGE ADD LOCATION,STORAGE SET, rebalancing), databases, branching, orBACKUP ROLLOVER. Send those withclient.run; see Storage pools, Databases and Backup and restore. - The role attribute, role management and privilege calls added in 1.1.0 need both a 1.1.0 client and a 1.1.0 server.