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 / CONNECTING FROM .NET

Connecting from .NET

This page is the reference for how RasterizedDb.Data reaches a server: the connection string, TLS, unix sockets, choosing a database, logging in, and the connection pool. Read it before you deploy, because the defaults suit a server on your own machine, not one across a network.

Connection strings

A connection string is a list of keyword=value pairs separated by ;:

text
Host=db.example.com;Port=61170;Username=app;Password=secret;Database=shop

Keywords are not case-sensitive, and most have aliases (Server for Host, User Id for Username, and so on). An unknown keyword is an error (ArgumentException), so a typo fails at once instead of being ignored. Values of the setting keywords below (Login, Trust, Tls Engine, Result Format) are not case-sensitive either, and spaces and hyphens in them are ignored (Root CA reads as RootCa).

Every keyword

keyword (aliases)defaultwhat it does
Host (Server, Data Source, DataSource, Address)noneThe server's host name or IP address. host:port is accepted when Port is not set. A value starting with unix: or / names a unix socket instead, as Socket does.
Port61170The native listener's TCP port (the server's --rdb-port).
Socket (Unix Socket, UnixSocket)noneThe path of the server's unix socket (the server's --rdb-socket), used instead of Host. See Unix sockets.
Database (Initial Catalog, DB)the server's default databaseThe database the connection works in. See Choosing a database.
Username (User Name, User, User Id, UserId, UID)noneThe role to log in as.
Password (PWD)noneThe role's password, for a SCRAM-SHA-256 login. A data source reports its connection string without it.
LoginAutoHow to log in: Auto, Password, Trust or Peer. See Logging in.
RolenoneOn a Trust login, the role the connection's statements run as.
Trust (Server Trust)AcceptAnyWhether the server's TLS certificate is checked: AcceptAny, WebPki, RootCa or Pinned. See TLS.
Root Certificate (RootCertificate)noneA PEM file holding the certificate authority that Trust=RootCa trusts.
Certificate Fingerprint (CertificateFingerprint)noneFor Trust=Pinned: the server certificate's SHA-256 fingerprint in hex. Several may be given, separated by commas.
Client Certificate (ClientCertificate)noneA PEM certificate to present to a server that asks for one.
Client Key (ClientKey)noneThe PEM private key for Client Certificate. Leave it out when the certificate file holds the key too.
Tls Engine (TlsEngine)AutoWhich TLS implementation to use: Auto, Platform or Managed. See TLS engines.
Result Format (ResultFormat)TextHow rows are asked for: Text or Binary. See the two result formats.
Timeout (Connect Timeout, Connection Timeout)15Seconds to open and log in a connection, and to wait for a free pooled connection. 0 waits indefinitely.
Command Timeout (CommandTimeout)30Seconds a statement may wait for its answer. 0 waits indefinitely. See Timeouts.
PoolingtrueWhether connections are pooled. Accepts true/false, yes/no, on/off, 1/0.
Maximum Pool Size (Max Pool Size, MaxPoolSize)100The most connections the pool opens. At least 1.
Minimum Pool Size (Min Pool Size, MinPoolSize)0How many idle connections the pool keeps even after their idle lifetime has passed. It does not open connections ahead of time.
Connection Idle Lifetime (ConnectionIdleLifetime)300Seconds an unused pooled connection is kept before it is closed.
Keepalive (Keep Alive)10Seconds between pings of an unused pooled connection, so the server does not close it. 0 sends none.
Idle Reconnect (IdleReconnect)20A connection that has been quiet this many seconds is replaced with a fresh one before the next statement is sent on it. 0 never does. See Idle connections.
Max Message Size (MaxMessageSize)8388608 (8 MiB)The largest answer, in bytes, the driver accepts. A larger one fails and closes the connection. At least 1024.
NoticestrueWhether connections ask the server to send notices (RAISE NOTICE, warnings). See Notices.
Application Name (ApplicationName)noneAccepted so connection strings written for other drivers parse. It is not sent to the server.

Building one in code

RasterizedDbConnectionStringBuilder has a typed property for each keyword, which avoids quoting mistakes:

csharp
using RasterizedDb.Data;

var builder = new RasterizedDbConnectionStringBuilder
{
    Host = "db.example.com",
    Username = "app",
    Password = Environment.GetEnvironmentVariable("RDB_PASSWORD"),
    Database = "shop",
    Trust = RasterizedDbTrust.RootCa,
    RootCertificate = "/etc/rdb/ca.pem",
    MaxPoolSize = 20,
};

await using var dataSource = new RasterizedDbDataSource(builder.ConnectionString);

The properties are Host, Port, Socket, Database, Username, Password, Login, Role, Trust, RootCertificate, CertificateFingerprint, ClientCertificate, ClientKey, TlsEngine, ResultFormat, Timeout, CommandTimeout, Pooling, MaxPoolSize, MinPoolSize, ConnectionIdleLifetime, Keepalive, IdleReconnect, MaxMessageSize, Notices and ApplicationName. Setting a property to null removes the keyword.

Logging in

Loginwhat happensneeds
Auto (default)Password when the connection string has a Password, otherwise Trust.
PasswordA SCRAM-SHA-256 exchange, bound to the TLS connection it runs on.Username and Password
TrustNo exchange at all.A listener that asks for none (the server's --rdb-auth trust, or a socket under --rdb-socket-auth trust)
PeerThe server reads which operating-system user is connecting from the unix socket itself, and lets in the role of that name. Username defaults to this process's user name.A unix socket under --rdb-socket-auth peer, and a role named after the operating-system user

A password login over TCP:

text
Host=db.example.com;Username=app;Password=secret

A trust login over a local socket, running as the role app:

text
Socket=/run/rdb/rdb.sock;Role=app

Rules worth knowing:

  • Login=Password without both Username and Password is an error before anything is sent.
  • On a Trust login, Username without a Password is taken as the role, the same as Role.
  • Role is only for Trust logins. A password or peer login names its role with Username; giving Role as well is an error.
  • A password login refuses a server that lets it in without the exchange: such a server never proved who it is. Use Login=Trust if that server is meant.
  • A trust connection that names no role is not an administrator in a database that has roles. Name the role it should run as.

The server side of logins (the --rdb-auth and --rdb-socket-auth flags, and creating roles) is covered in Security.

TLS

Over TCP the connection is always TLS 1.3; there is no unencrypted TCP mode. What the driver checks about the server's certificate is set by Trust:

Trustthe certificate is accepted whenuse it for
AcceptAny (default)alwaysa server on your own machine or a network you control
WebPkiit chains to a root the operating system trusts, and is issued for Hosta server with a certificate from a public authority
RootCait chains to the authority in Root Certificate, and is issued for Hosta server with a certificate from your own authority
Pinnedits SHA-256 fingerprint is one of those in Certificate Fingerprintexactly one known certificate

Over a network you do not control, do not keep Trust=AcceptAny. A password login is still safe from being replayed elsewhere, but whoever answers in the server's place reads every statement and row.

Certificate revocation is not checked in any mode.

Without --rdb-cert and --rdb-key, the server makes a new self-signed certificate every time it starts. Such a certificate can be encrypted to but never verified, and its fingerprint changes at every restart. To use WebPki, RootCa or Pinned, start the server with a certificate of its own; see Security.

A private authority:

text
Host=db.internal;Username=app;Password=secret;Trust=RootCa;Root Certificate=/etc/rdb/ca.pem

A pinned certificate. Print the fingerprint with OpenSSL; the colons it writes, spaces, upper or lower case, and a leading SHA256= are all accepted:

sh
openssl x509 -in server.pem -noout -fingerprint -sha256
text
Host=db.internal;Username=app;Password=secret;Trust=Pinned;Certificate Fingerprint=3F:A1:0C:7E:52:9B:44:D8:16:E2:6A:90:BB:31:CF:05:7D:68:E4:21:9A:C3:58:0F:B6:12:4D:EE:73:A9:01:9C

To roll a certificate over without downtime, list both the old and the new fingerprint, separated by a comma.

TLS engines

A password login signs over a value taken from the TLS session (its channel binding), which .NET's SslStream cannot hand out on every platform. Tls Engine decides how that is handled:

Tls Enginebehaviour
Auto (default)SslStream (the operating system's TLS) wherever it can, which is always for a login that needs no binding and on Linux for a password login. On other platforms a password login runs on a managed TLS implementation (BouncyCastle) instead.
PlatformAlways SslStream. A password login then fails on platforms where the binding cannot be read.
ManagedAlways the managed implementation. It cannot present a client certificate.

Client certificates

Client Certificate and Client Key present a certificate to a server that asks for one. Presenting one needs the platform's TLS, so on platforms other than Linux it cannot be combined with a password login; that combination is refused with an error. The standard rasterizeddb server has no option to ask clients for a certificate, so these keywords matter only for a server set up to do so.

Unix sockets

When the application runs on the same machine as the server, a unix socket skips TCP and TLS altogether. Start the server with a socket:

sh
rasterizeddb --location ./rdb-data --rdb-socket /run/rdb/rdb.sock --rdb-socket-auth peer

and connect with any of these forms:

text
Socket=/run/rdb/rdb.sock
Host=unix:/run/rdb/rdb.sock
Host=/run/rdb/rdb.sock

On a socket:

  • There is no TLS, and none is needed: who may connect is decided by the socket file's permissions (the server's --socket-mode, 600 unless set).
  • Trust other than AcceptAny, and Client Certificate, are errors: there is no certificate to check or present.
  • --rdb-socket-auth decides the login: peer pairs with Login=Peer, trust with Login=Trust (or a Role), scram-sha-256 with a password.
  • A socket path must be short: about 107 bytes on Linux.

With --rdb-tcp off the server serves the native protocol on the socket alone and opens no port.

Choosing a database

Database picks the database a connection works in. Leave it out to use the server's default database (postgres, unless the server was started with --pg-default-db). Creating databases is covered in Databases.

text
Host=db.example.com;Username=app;Password=secret;Database=shop

A connection's database is fixed once it is open. connection.ChangeDatabase("other") closes the connection and opens a new one to the other database. A connection made by a data source cannot change database at all; make a second data source for the other database.

Pooling

Pooling is on by default. Opening a connection takes an open, logged-in connection from the pool; closing or disposing it gives it back.

  • One pool per data source. A RasterizedDbDataSource owns its pool. A RasterizedDbConnection created from a connection string alone shares one pool with every other connection made from exactly the same string.
  • When the pool is full, Open waits for a connection to be returned, up to Timeout seconds, and then fails with an error that names Maximum Pool Size.
  • A connection goes back clean. If a transaction is still open when the connection is closed, the driver rolls it back before the connection returns to the pool.
  • Idle connections are kept alive. Every few seconds the pool pings connections that have been unused for Keepalive seconds, and closes those unused for Connection Idle Lifetime, keeping at least Minimum Pool Size.
  • Clearing. dataSource.Clear() closes a data source's idle connections; RasterizedDbDataSource.ClearAllPools() does it for every pool made from a connection string alone. Connections in use are closed when they are returned.

Pooling=false opens a new connection (TCP, TLS and login) for every Open and closes it on Close.

Idle connections

The server closes a native connection that has been quiet for its request timeout (--rdb-request-timeout, 30 seconds by default). The driver works around this so you rarely see it:

  • Pooled connections are pinged (Keepalive, every 10 seconds) while nobody uses them.
  • An open connection that has been quiet for Idle Reconnect seconds (20) is swapped for a fresh one before the next statement is sent on it, so no statement is sent to a connection the server may be closing. Anything that lived on the old connection is gone: temporary tables, a sequence's currval.
  • A connection is never swapped while a transaction is open on it. A transaction left quiet for 30 seconds is lost: the server rolls it back, and the next statement throws a RasterizedDbException whose Kind is TransactionLost. See Transactions.

Nothing is ever sent twice. A statement whose connection fails throws, because whether it ran is unknown.

Data sources

RasterizedDbDataSource is the .NET DbDataSource for RasterizedDB. Create one per connection string when the application starts and keep it until it stops:

csharp
using RasterizedDb.Data;

await using var dataSource = new RasterizedDbDataSource("Host=db.example.com;Username=app;Password=secret;Database=shop");

await using (var connection = await dataSource.OpenConnectionAsync())
{
    // statements that need a connection of their own: transactions, temporary tables
}

// a statement that commits on its own, with no connection to manage
await using var command = dataSource.CreateCommand("SELECT count(*) FROM orders");
var count = (long)(await command.ExecuteScalarAsync())!;

RasterizedDbDataSource.Create(connectionString) does the same as the constructor. A command made by dataSource.CreateCommand runs on one connection that all such commands share, with many statements in flight at once; see Commands without a connection.

Registering with dependency injection

The package has no IServiceCollection extension of its own. Register the data source as a singleton; the container disposes of it, and its pool, when the application stops:

csharp
using System.Data.Common;
using RasterizedDb.Data;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton(_ =>
    new RasterizedDbDataSource(builder.Configuration.GetConnectionString("Shop")!));
// For code that asks for the provider-neutral type:
builder.Services.AddSingleton<DbDataSource>(sp => sp.GetRequiredService<RasterizedDbDataSource>());

var app = builder.Build();

app.MapGet("/orders/count", async (RasterizedDbDataSource dataSource) =>
{
    await using var command = dataSource.CreateCommand("SELECT count(*) FROM orders");
    return (long)(await command.ExecuteScalarAsync())!;
});

app.Run();

with the connection string in appsettings.json:

json
{
  "ConnectionStrings": {
    "Shop": "Host=db.example.com;Username=app;Password=secret;Database=shop;Trust=RootCa;Root Certificate=/etc/rdb/ca.pem"
  }
}

For EF Core, pass the data source to UseRasterizedDb; see EF Core.

Provider factory

For code that discovers providers by name, register the factory once:

csharp
using System.Data.Common;
using RasterizedDb.Data;

DbProviderFactories.RegisterFactory("RasterizedDb.Data", RasterizedDbFactory.Instance);

The factory creates connections, commands, parameters, connection string builders, data sources and batches.

Limits

  • TLS revocation is not checked.
  • Over TCP there is no plain (unencrypted) mode; use a unix socket on the same machine.
  • Application Name is accepted and ignored.
  • Minimum Pool Size keeps connections, it does not open them in advance.
  • A connection's database cannot change while it is open.
✓ page rendered in 164 µs axum + tera + htmx · no other javascript