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 / C# / .NET CLIENT / ADMINISTRATION FROM .NET

Administration from .NET

connection.Admin turns the server's administration statements into typed .NET calls: tables and columns, indexes, partitioning, roles and grants, configuration, storage stores and table placement, backups and replication. Use it for tooling, start-up checks and operations scripts written in C#, instead of building those statements as strings.

Using it

csharp
using RasterizedDb.Data;

await using var dataSource = new RasterizedDbDataSource("Host=127.0.0.1;Username=app;Password=change-me-now");
await using var connection = await dataSource.OpenConnectionAsync();
var admin = connection.Admin;

foreach (var table in await admin.TablesAsync())
{
    Console.WriteLine($"{table.Name}: {table.RowSlots} row slots, {table.TotalBytes} bytes");
}

await admin.CreateIndexAsync(new RasterizedDbIndex("users", "email").Unique().IfNotExists());
await admin.CreateRoleAsync(RasterizedDbRole.User("reporting").Password("change-me-too"));
await admin.GrantAsync(RasterizedDbGrant.Privileges("SELECT").OnAllTables().To("reporting"));

How it works:

  • connection.Admin is a lightweight value; take it whenever you need it. It runs each call as one statement on that connection, in the binary result format, so a call inside an open transaction is part of it.
  • Every method has an …Async form taking an optional CancellationToken, and a synchronous twin without the suffix (admin.Tables(), admin.CreateIndex(…)) that blocks the calling thread on its I/O.
  • Names you pass are checked or quoted before they go into the statement; a name that cannot be written safely throws ArgumentException before anything is sent. Table, column and index names are quoted only when they need it (mixed case, a keyword).
  • A refused statement throws RasterizedDbException, as any other statement does; see Errors.
  • The listing calls read the server's answer columns by position. They match the server version the driver was written for.

Privileges

The server decides who may run each statement; the driver adds no checks of its own.

statementswho may run them
Stores and table placement (STORAGE …), SET CONFIG, BACKUP …, RESTORE …, REPLICATION …a superuser
CREATE ROLE, ALTER ROLE, DROP ROLEa superuser; a role with CREATEROLE within the server's role rules; any role may change its own password
CREATE INDEX, DROP INDEX, ALTER TABLE … PARTITION BY, VACUUM, GRANT, REVOKE, REASSIGN OWNEDas the same SQL statement: the object's owner, or a role with the right grant
The SHOW … and DESCRIBE readsnot limited to superusers

On a connection with no login exchange (a trust listener), the role named with Role in the connection string is the one checked. Roles, ownership and grants are explained in Security.

Tables and columns

methodstatement sentreturns
TablesAsync()SHOW TABLESList<RasterizedDbTableInfo>
ColumnsAsync(table)DESCRIBE tableList<RasterizedDbColumnInfo>
TableStatsAsync(table)SHOW TABLE STATS tableList<RasterizedDbMetric>
DatabaseStatsAsync()SHOW STATSList<RasterizedDbMetric>
VacuumAsync(string? table = null, bool full = false)VACUUM [FULL] [table]long: the count the server reports
recordfields
RasterizedDbTableInfoName, Storage, RowSlots, Columns, DataBytes, PointerBytes, IndexBytes, TotalBytes, ReclaimableBytes, FiltersReady, Immutable, PrimaryKey
RasterizedDbColumnInfoPosition, Name, DataType, Size, Offset, Nullable, Unique, PrimaryKey, Default (null when none), Indexed, ZoneBounds, JsonTable (null when none), Dropped
RasterizedDbMetricMetric, Value (as text, null when none), Detail
csharp
var columns = await admin.ColumnsAsync("orders");
foreach (var column in columns.Where(c => !c.Dropped))
{
    Console.WriteLine($"{column.Position} {column.Name} {column.DataType}{(column.Nullable ? "" : " NOT NULL")}");
}

long reclaimed = await admin.VacuumAsync("orders");

What VACUUM and VACUUM FULL do is described in Maintenance.

Indexes

methodstatement sentreturns
CreateIndexAsync(RasterizedDbIndex index)CREATE INDEX …, or for a unique index ALTER TABLE … ADD CONSTRAINT … UNIQUE (…)nothing
DropIndexAsync(string name, bool ifExists = false)DROP INDEX [IF EXISTS] namenothing
IndexCheckpointAsync(table)SELECT rdb_index_checkpoint('table')string: the server's report. Writes the table's persistent indexes to disk now.

Build the index with RasterizedDbIndex:

csharp
// CREATE INDEX IF NOT EXISTS orders_customer_id_placed_at_idx ON orders USING btree (customer_id, placed_at)
await admin.CreateIndexAsync(new RasterizedDbIndex("orders", "customer_id", "placed_at").IfNotExists());

// ALTER TABLE users ADD CONSTRAINT users_email_key UNIQUE (email)
await admin.CreateIndexAsync(new RasterizedDbIndex("users", "email").Unique());

// CREATE INDEX docs_body_gin ON docs USING gin (body jsonb_path_ops)
await admin.CreateIndexAsync(new RasterizedDbIndex("docs", "body").Name("docs_body_gin").Using(RasterizedDbIndexMethod.GinPathOps));
RasterizedDbIndex membereffect
new RasterizedDbIndex(table, params string[] columns)At least one column.
.Name(name)The index name. Without it: <table>_<columns>_idx, or <table>_<columns>_key for a unique one. IndexName shows the name that will be used.
.Using(method)BTree (default), Hash, Gin, or GinPathOps (GIN with jsonb_path_ops).
.Unique()A UNIQUE constraint instead of an index. It takes no method; combining it with anything but BTree throws NotSupportedException.
.IfNotExists()Adds IF NOT EXISTS.
.ToSql()The statement, for logging or review.

Which index types the server has, and when each helps, is in Indexes.

Partitioning

methodstatement sentreturns
PartitionByHashAsync(table, IReadOnlyList<string> columns, int? partitions = null)ALTER TABLE table PARTITION BY HASH (columns) [PARTITIONS n]nothing
PartitionsAsync(table)SHOW PARTITIONS tableList<RasterizedDbPartitionInfo>: Pid, Lo, Hi, Location (null when none), State, RowSlots, TotalBytes

A hash partition key has one to three columns. Converting a table to a partitioned one cannot run inside a transaction. See Partitioning.

csharp
await admin.PartitionByHashAsync("events", ["tenant_id"], partitions: 16);

Roles and grants

methodstatement sent
CreateRoleAsync(RasterizedDbRole role)CREATE ROLE name with LOGIN or NOLOGIN, SUPERUSER or NOSUPERUSER, then [CREATEDB] [CREATEROLE] [BYPASSRLS] [CONNECTION LIMIT n] [VALID UNTIL '…'] [PASSWORD '…']
AlterRoleAsync(RasterizedDbRole role)ALTER ROLE name … with the same options
RenameRoleAsync(from, to)ALTER ROLE from RENAME TO to
SetRolePasswordAsync(name, string? password)ALTER ROLE name PASSWORD '…', or PASSWORD NULL to remove it
SetRoleSettingAsync(name, setting, string? value)ALTER ROLE name SET setting = '…', or RESET setting when value is null
DropRoleAsync(name, bool ifExists = false)DROP ROLE [IF EXISTS] name
GrantRoleAsync(role, member, bool withAdminOption = false)GRANT role TO member [WITH ADMIN OPTION]
RevokeRoleAsync(role, member)REVOKE role FROM member
GrantAsync(RasterizedDbGrant grant)GRANT … ON … TO … [WITH GRANT OPTION]
RevokeAsync(RasterizedDbGrant grant)REVOKE … ON … FROM … [CASCADE]
ReassignOwnedAsync(from, to)REASSIGN OWNED BY from TO to
RolesAsync()reads pg_catalog.pg_roles; returns List<RasterizedDbRoleInfo>
TableGrantsAsync(table)reads information_schema.table_privileges; returns List<RasterizedDbGrantInfo>

The statements that change something return nothing. Role names must not be empty and must not contain whitespace or quotes.

RasterizedDbRole

csharp
await admin.CreateRoleAsync(
    RasterizedDbRole.User("app")
        .Password(Environment.GetEnvironmentVariable("APP_DB_PASSWORD")!)
        .ConnectionLimit(50));

await admin.CreateRoleAsync(RasterizedDbRole.Group("readers"));
await admin.GrantRoleAsync("readers", "app");
membereffect
RasterizedDbRole.User(name)A role that may log in (LOGIN).
RasterizedDbRole.Group(name)A role that holds privileges for its members and cannot log in (NOLOGIN).
.Password(password)PASSWORD '…'. The server stores a verifier, not the password.
.Superuser()SUPERUSER.
.CreateDb(), .CreateRole(), .BypassRls()CREATEDB, CREATEROLE, BYPASSRLS.
.ConnectionLimit(n)CONNECTION LIMIT n.
.ValidUntil(timestamp)VALID UNTIL '…'.

The statement always states LOGIN or NOLOGIN, and SUPERUSER or NOSUPERUSER. So AlterRoleAsync with a role built without .Superuser() takes superuser away, and with Group(…) takes login away. The other options are only ever added. To change only a password, use SetRolePasswordAsync. A role's ToString() leaves the password out.

RasterizedDbGrant

csharp
// GRANT SELECT, INSERT ON TABLE orders TO app
await admin.GrantAsync(RasterizedDbGrant.Privileges("SELECT", "INSERT").OnTable("orders").To("app"));

// GRANT UPDATE (name, email) ON TABLE users TO support
await admin.GrantAsync(RasterizedDbGrant.Columns("UPDATE", "name", "email").OnTable("users").To("support"));

// REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC
await admin.RevokeAsync(RasterizedDbGrant.Privileges("ALL").OnAllTables().To("public"));
membereffect
RasterizedDbGrant.Privileges(params string[])Privileges by name (SELECT, INSERT, UPDATE, DELETE, ALL, …), upper-cased.
RasterizedDbGrant.Columns(privilege, params string[] columns)One privilege on some columns only.
.OnTable(params string[]), .OnSequences(…), .OnFunctions(…)What the grant is on.
.OnAllTables()Every table in the public schema.
.To(grantee)A grantee; call it once per grantee. "public" becomes PUBLIC.
.WithGrantOption()For a grant: WITH GRANT OPTION.
.Cascade()For a revoke: CASCADE.
.ToSql(bool grant)The statement, for review.

A grant needs an object, at least one privilege and at least one grantee.

recordfields
RasterizedDbRoleInfoName, Superuser, Login, CreateDb, CreateRole, BypassRls, ConnectionLimit, ValidUntil (null when none), Config (the role's settings)
RasterizedDbGrantInfoGrantor, Grantee, Table, Privilege, Grantable

Configuration

methodstatement sentreturns
ConfigAsync()SHOW CONFIGList<RasterizedDbConfigEntry>: Section, Key, Value, HotReload, SetWith, Help, Pending, Options, Source (the last four null when empty)
SetConfigAsync(key, value)SET CONFIG section.key = valuestring: what the server said about the change

key is section.key, each part letters, digits, _ and -. value may hold letters, digits and . _ : - + / only; anything else throws ArgumentException. HotReload says whether a change takes effect on the running server.

csharp
foreach (var entry in (await admin.ConfigAsync()).Where(e => e.HotReload))
{
    Console.WriteLine($"{entry.Section}.{entry.Key} = {entry.Value}");
}

Console.WriteLine(await admin.SetConfigAsync("query_stats.enabled", "off"));

Storage stores and table placement

A store is a place a table's data can live besides the data directory: an S3-compatible bucket or another directory. See Storage pools and Key/value storage.

methodstatement sentreturns
AddStoreAsync(RasterizedDbStore store)STORAGE ADD STORE [IF NOT EXISTS] name s3 WITH (…) (or dir for a directory store)List<string>: the server's reply lines
AlterStoreAsync(name, IEnumerable<KeyValuePair<string, string>> settings)STORAGE ALTER STORE name SET key = 'value', …the reply lines
RotateStoreCredentialsAsync(name, accessKeyId, secretAccessKey)ALTER STORE of the two credential settingsthe reply lines
DropStoreAsync(name)STORAGE DROP STORE namethe reply lines
DropStoreIfExistsAsync(name)SHOW STORAGE STORES, then the drop if it is there (two statements)bool: whether it existed
StoresAsync()SHOW STORAGE STORESList<RasterizedDbStoreInfo>
StoreAsync(name)SHOW STORAGE STORESthe one store, or null
PlaceTableAsync(table, RasterizedDbPlacement placement)STORAGE PLACE TABLE table AT …: where a table not created yet will livethe reply lines
MoveTableAsync(table, RasterizedDbPlacement placement)STORAGE MOVE TABLE table TO …: moves an existing tablethe reply lines
StorageLocationsAsync()SHOW STORAGE LOCATIONSList<RasterizedDbLocationInfo>
StorageStatsAsync()SHOW STORAGE STATSList<RasterizedDbMetric>
csharp
await admin.AddStoreAsync(
    RasterizedDbStore.S3("archive", "https://s3.eu-central-1.amazonaws.com", "acme-rdb-archive")
        .Region("eu-central-1")
        .Prefix("prod/")
        .Credentials(Environment.GetEnvironmentVariable("AWS_ACCESS_KEY_ID")!, Environment.GetEnvironmentVariable("AWS_SECRET_ACCESS_KEY")!)
        .IfNotExists());

await admin.MoveTableAsync("events_2024", RasterizedDbPlacement.Kv("archive"));
RasterizedDbStore membersetting
RasterizedDbStore.S3(name, endpoint, bucket)An S3 store: ENDPOINT, BUCKET.
RasterizedDbStore.Directory(name, path)A directory store: PATH. Takes no credentials.
.Region(r), .Prefix(p)REGION, PREFIX.
.PathAddressing(bool path = true)ADDRESSING path or virtual.
.Credentials(accessKeyId, secretAccessKey), .SessionToken(token)ACCESS_KEY_ID, SECRET_ACCESS_KEY, SESSION_TOKEN. A session token needs the other two.
.ChunkSize(bytes), .PageSize(bytes), .CacheBytes(bytes), .SpillBytes(bytes), .CompactChunkBytes(bytes), .ChunkFetchPages(n), .ReadaheadChunks(n), .MaxDeltas(n), .FlushIntervalMs(ms)CHUNK_SIZE, PAGE_SIZE, CACHE_BYTES, SPILL_BYTES, COMPACT_CHUNK_BYTES, CHUNK_FETCH_PAGES, READAHEAD_CHUNKS, MAX_DELTAS, FLUSH_INTERVAL_MS.
.Option(key, value)Any other setting by name.
.IfNotExists()IF NOT EXISTS.
.ToSql()The statement. Its ToString() leaves secrets out.
RasterizedDbPlacementwhere
RasterizedDbPlacement.Memoryin memory ('memory:')
RasterizedDbPlacement.Kv(store)a registered store ('kv:store')
RasterizedDbPlacement.Directory(path)a directory on the server

Store, setting and table names here are letters, digits, _ and -, starting with a letter or _. A setting's value may not contain a control character, nor both ' and "; for AlterStoreAsync also no , and no SET.

recordfields
RasterizedDbStoreInfoName, Kind, Endpoint, Region, Bucket, Prefix, Addressing, Settings, Credentials, Tables, Opened, Supported
RasterizedDbLocationInfoLocation, Role, Weight, Enabled, IsDatabaseDirectory, Tables, AvailableBytes, TotalBytes

Backups

methodstatement sentreturns
BackupDatabaseAsync()BACKUP DATABASElong: the count the server reports
BackupWalAsync()BACKUP WALlong
BackupPruneAsync()BACKUP PRUNElong
BackupsAsync()SHOW BACKUPSList<RasterizedDbBackupInfo>: Kind, Id, CreatedAt, StartLsn, EndLsn, UncompressedBytes, CompressedBytes, Detail
BackupStatusAsync()SHOW BACKUP STATUSList<RasterizedDbMetric>
RestoreAsync(RasterizedDbRestoreTarget target, string toDirectory)RESTORE DATABASE <target> TO 'directory'RasterizedDbRestoreReport: SnapshotId, TargetDirectory, RecoveredToLsn, FilesRestored, BytesRestored, SegmentsReplayed, RecordsApplied, RecordsDiscarded

toDirectory is a directory on the server's machine. The restore target is one of:

RasterizedDbRestoreTargettarget
RasterizedDbRestoreTarget.LatestLATEST
RasterizedDbRestoreTarget.Snapshot(id)FROM SNAPSHOT 'id'
RasterizedDbRestoreTarget.Lsn(ulong lsn)AT LSN n
RasterizedDbRestoreTarget.Time(string timestamp)AT TIME '…'
csharp
await admin.BackupDatabaseAsync();
var report = await admin.RestoreAsync(RasterizedDbRestoreTarget.Latest, "/var/lib/rdb-restore-test");
Console.WriteLine($"restored {report.FilesRestored} files to LSN {report.RecoveredToLsn}");

Where backups go and how to configure them is in Backup and restore.

Replication

methodstatement sentreturns
ReplicationStatsAsync()SHOW REPLICATION STATSList<RasterizedDbMetric>
ReplicationPeersAsync()SHOW REPLICATION PEER STATUSList<Dictionary<string, object?>>, one per peer, keyed by the names in RasterizedDbAdmin.ReplicationPeerColumns
ReplicationAsync(string statement)REPLICATION <statement>List<string>: the reply lines

ReplicationPeerColumns is peer, address, remote_node, connected, paused, acked_seq, lag, queued, records_sent, batches_sent, dropped, codec, last_ratio, last_error, state.

ReplicationAsync sends its text as written, after the word REPLICATION; never pass it text from outside your program. The statements themselves are in Replication.

csharp
foreach (var peer in await admin.ReplicationPeersAsync())
{
    Console.WriteLine($"{peer["peer"]}: connected={peer["connected"]} lag={peer["lag"]}");
}

Limits

  • One statement per call. The calls that take two statements (DropStoreIfExistsAsync) are not atomic.
  • The listing calls read the server's columns by position, so they need a server of the version the driver was written for.
  • AlterRoleAsync always restates LOGIN/NOLOGIN and SUPERUSER/NOSUPERUSER, and cannot remove CREATEDB, CREATEROLE, BYPASSRLS or a connection limit. Use connection.CreateCommand("ALTER ROLE …") for that.
  • ReplicationAsync is not checked or quoted.
  • Not covered by a typed call: databases, branches, schema objects, and other statements. Run them as SQL with a command.
✓ page rendered in 133 µs axum + tera + htmx · no other javascript