NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / RUST CLIENT / ADMINISTRATION API

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:

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:

rust
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.

BuilderSetsServer 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 underrdb
.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_* environmentenvironment
.session_token(token)A session token; needs .credentials(…)
.chunk_size(bytes)CHUNK_SIZE: bytes per chunk object, a whole number of pages4 MiB
.page_size(bytes)PAGE_SIZE: bytes per page within a chunk64 KiB
.cache_bytes(bytes)CACHE_BYTES: the store's read cache256 MiB
.spill_bytes(bytes)SPILL_BYTES: unstored changes held in memory before they are written out8 MiB
.compact_chunk_bytes(bytes)COMPACT_CHUNK_BYTES1 MiB
.chunk_fetch_pages(pages)CHUNK_FETCH_PAGES4
.readahead_chunks(chunks)READAHEAD_CHUNKS: chunks read ahead of a sequential scan2
.max_deltas(deltas)MAX_DELTAS: change objects per chunk before it is compacted64
.flush_interval_ms(ms)FLUSH_INTERVAL_MS200
.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

CallStatement it sendsReturns
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 listedbool: whether a store was dropped
stores()SHOW STORAGE STORESVec<StoreInfo>
store(name)SHOW STORAGE STORES, filtered to nameOption<StoreInfo>
  • alter_store takes the option names of the table above (CACHE_BYTES, ENDPOINT, …) as keys. A value may not contain a comma or the word SET, which ALTER STORE cannot 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_store is refused while any table is placed on the store. It does not delete the store's objects.
  • drop_store_if_exists looks first because the grammar has no IF EXISTS; two clients racing on it can still see an error.

StoreInfo is one row of SHOW STORAGE STORES:

FieldTypeMeaning
nameStringThe store's name
kindStringdir, s3, or the name of a kind this server build cannot open
endpointStringAn S3 store's endpoint; a directory store's path
regionStringAn S3 store's region; empty for a directory store
bucketStringAn S3 store's bucket; empty for a directory store
prefixStringThe key prefix or subdirectory its data sits under
addressingStringpath or virtual (S3 only)
settingsStringIts tuning options, as the server prints them
credentialsStringstore when it has its own credentials, environment otherwise
tablesi64Tables placed on it
openedboolWhether the server has opened it (a table on it has been used)
supportedboolWhether 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

rust
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:

ValuePlacement spec sentMeaning
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
CallStatement it sendsReturns
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 LOCATIONSVec<LocationInfo>
storage_stats()SHOW STORAGE STATSVec<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:

FieldTypeMeaning
locationStringThe directory
roleStringprimary or backup
weighti64Its share of new tables under a weighted policy
enabledboolWhether new tables may be placed in it
is_database_directoryboolWhether it is the database's own directory
tablesi64Tables stored in it
available_bytesi64Free bytes on its filesystem
total_bytesi64Total bytes of its filesystem

Example: move a table between backends

rust
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.

BuilderEffectDefault
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 builtIndexMethod::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
IndexMethodSent asUse for
BTree (default)USING btreeEquality and ranges: =, <, BETWEEN, ORDER BY
HashUSING hashEquality only, smaller and faster for it
GinUSING ginA jsonb column, with the jsonb_ops operator class
GinPathOpsUSING gin (col jsonb_path_ops)A jsonb column, with jsonb_path_ops
CallStatement it sendsReturns
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 with Error::Unsupported. Because it is created as a constraint, drop_index does not remove it: drop it with client.run("ALTER TABLE users DROP CONSTRAINT users_email_key").
  • index_checkpoint seals 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

rust
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

CallStatement it sendsReturns
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:

FieldTypeMeaning
pidi64The partition's id
loStringThe lower bound of its hash range, in hex
hiStringThe upper bound of its hash range, in hex
locationOption<String>The directory or store holding its files
stateStringmaterialized (it has files) or unmaterialized (no row written yet)
row_slotsi64Row slots in use, including versions not yet vacuumed
total_bytesi64Its bytes on disk

Example: convert a table and list its partitions

rust
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

CallStatement it sendsReturns
tables()SHOW TABLESVec<TableInfo>
columns(table)DESCRIBE <table>Vec<ColumnInfo>, dropped columns included
vacuum(table, full)VACUUM [FULL] [<table>]; None vacuums every tableu64: bytes reclaimed
database_stats()SHOW STATSVec<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:

FieldTypeMeaning
nameStringThe table's name
storageStringWhere it is stored: file, memory, s3, kv-directory, …
row_slotsi64Row slots in use: live rows and those vacuum has yet to reclaim
columnsi64Columns, dropped ones included
data_bytesi64Bytes of row data
pointer_bytesi64Bytes of row pointers
index_bytesi64Bytes of index data
total_bytesi64All of the table's bytes
reclaimable_bytesi64Bytes vacuum could give back
filters_readyboolWhether the filter index has caught up with the table
immutableboolWhether the table is read-only
primary_keyStringThe primary key's columns, comma-separated; empty for none

ColumnInfo is one row of DESCRIBE <table>:

FieldTypeMeaning
positioni64The column's position, from 1
nameStringThe column's name
data_typeStringThe type as the engine names it: BIGINT, TEXT, NUMERIC(10,2), …
sizei64Its stored width in bytes (0 for a variable-width type)
offseti64Its offset within a row, for a fixed-width column
nullableboolWhether it may hold NULL
uniqueboolWhether a unique constraint covers it alone
primary_keyboolWhether it is (part of) the primary key
defaultOption<String>Its DEFAULT expression
indexedboolWhether the filter index covers it
zone_boundsboolWhether per-zone minimum and maximum are kept for it
json_tableOption<String>For a shredded JSON column, the table holding its keys
droppedboolWhether 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:

FieldTypeMeaning
metricStringWhat is measured
valueOption<String>Its value, as text
detailOption<String>What the value means, or where it came from

Example: a space report

rust
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

CallStatement it sendsReturns
config()SHOW CONFIGVec<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:

FieldTypeMeaning
sectionStringThe setting's section (wal, filter, vacuum, …)
keyStringIts name within the section
valueOption<String>Its current value
hot_reloadboolWhether SET CONFIG changes it without a restart
set_withStringHow to change it: a SET CONFIG statement or a flag
helpStringWhat it does
pendingOption<String>A value saved for the next start, if one is waiting
optionsOption<String>The values it takes, when they are a fixed list
sourceOption<String>Where its value came from: command line, saved or default

Example: change a setting and confirm it

rust
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.

BuilderClause
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)
CallStatement it sendsReturns
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

rust
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.

BuilderClause
.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

CallStatement it sendsReturns
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 rolnameVec<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:

FieldTypeMeaning
nameStringIts name
superuserboolSUPERUSER
loginboolLOGIN
create_dbboolCREATEDB
create_roleboolCREATEROLE
bypass_rlsboolBYPASSRLS
connection_limiti64-1 for no limit
valid_untilOption<String>When its password stops working, if ever
configVec<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):

BuilderEffect
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.

CallStatement it sendsReturns
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:

FieldTypeMeaning
grantorStringWho granted it
granteeStringWho holds it; PUBLIC for every role
tableStringThe table or view
privilegeStringSELECT, INSERT, …
grantableboolHeld with the grant option

Example: a read-only group and an application role

rust
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.

CallStatement it sendsReturns
backup_database()BACKUP DATABASE: a snapshot to the configured destinationu64: compressed bytes written
backup_wal()BACKUP WAL: ships the write-ahead log written since the last shipmentu64: compressed bytes shipped
backup_prune()BACKUP PRUNE: removes backups past the retention policyu64: objects removed
backups()SHOW BACKUPSVec<BackupInfo>
backup_status()SHOW BACKUP STATUSVec<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.

RestoreTargetSent asRecovers to
RestoreTarget::LatestRESTORE DATABASE LATESTThe 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:

FieldTypeMeaning
kindStringsnapshot or wal
idStringThe backup's id, as RestoreTarget::Snapshot takes it
created_atStringWhen it was taken
start_lsni64The first log position it covers
end_lsni64The last log position it covers
uncompressed_bytesi64Its size before compression
compressed_bytesi64Its size as stored
detailOption<String>Anything else the server reports about it

RestoreReport says what a restore did:

FieldTypeMeaning
snapshot_idStringThe snapshot restored from
target_dirStringThe directory the database was restored into
recovered_to_lsnStringThe log position recovery reached
files_restoredi64Files restored from the snapshot
bytes_restoredi64Bytes restored from the snapshot
segments_replayedi64Log segments replayed on top of it
records_appliedi64Log records applied
records_discardedi64Log records past the target, not applied

Example: take a backup and test-restore it

rust
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

CallStatement it sendsReturns
replication_stats()SHOW REPLICATION STATSVec<Metric>
replication_peers()SHOW REPLICATION PEER STATUSVec<Record>, one per peer
replication(statement)REPLICATION <statement>, for the verbs not typed hereVec<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

rust
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 and set_config keys 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; use client.run with STORAGE PLACE TABLE/STORAGE MOVE TABLE.
  • A store value cannot contain both ' and ", or a newline, tab or NUL. An alter_store value also cannot contain a comma or SET.
  • A set_config value is limited to letters, digits and . _ : - + /.
  • Role names cannot contain whitespace or quotes.
  • drop_store_if_exists checks and then drops in two statements, not atomically.
  • A unique index made with Index::unique() is a constraint: drop_index does not drop it, and it cannot use a method other than B-tree. Partial, expression and full-text indexes have no builder; write them with client.run.
  • partition_by_hash converts an existing table only, with a key of one to three columns.
  • restore writes to a new directory only; it cannot restore over the running database.
  • replication(statement) and the raw client.run are not checked; everything else is.
  • There is no typed call for storage locations and pools (STORAGE ADD LOCATION, STORAGE SET, rebalancing), databases, branching, or BACKUP ROLLOVER. Send those with client.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.
✓ page rendered in 209 µs axum + tera + htmx · no other javascript