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 ;:
Host=db.example.com;Port=61170;Username=app;Password=secret;Database=shopKeywords 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) | default | what it does |
|---|---|---|
Host (Server, Data Source, DataSource, Address) | none | The 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. |
Port | 61170 | The native listener's TCP port (the server's --rdb-port). |
Socket (Unix Socket, UnixSocket) | none | The 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 database | The database the connection works in. See Choosing a database. |
Username (User Name, User, User Id, UserId, UID) | none | The role to log in as. |
Password (PWD) | none | The role's password, for a SCRAM-SHA-256 login. A data source reports its connection string without it. |
Login | Auto | How to log in: Auto, Password, Trust or Peer. See Logging in. |
Role | none | On a Trust login, the role the connection's statements run as. |
Trust (Server Trust) | AcceptAny | Whether the server's TLS certificate is checked: AcceptAny, WebPki, RootCa or Pinned. See TLS. |
Root Certificate (RootCertificate) | none | A PEM file holding the certificate authority that Trust=RootCa trusts. |
Certificate Fingerprint (CertificateFingerprint) | none | For Trust=Pinned: the server certificate's SHA-256 fingerprint in hex. Several may be given, separated by commas. |
Client Certificate (ClientCertificate) | none | A PEM certificate to present to a server that asks for one. |
Client Key (ClientKey) | none | The PEM private key for Client Certificate. Leave it out when the certificate file holds the key too. |
Tls Engine (TlsEngine) | Auto | Which TLS implementation to use: Auto, Platform or Managed. See TLS engines. |
Result Format (ResultFormat) | Text | How rows are asked for: Text or Binary. See the two result formats. |
Timeout (Connect Timeout, Connection Timeout) | 15 | Seconds to open and log in a connection, and to wait for a free pooled connection. 0 waits indefinitely. |
Command Timeout (CommandTimeout) | 30 | Seconds a statement may wait for its answer. 0 waits indefinitely. See Timeouts. |
Pooling | true | Whether connections are pooled. Accepts true/false, yes/no, on/off, 1/0. |
Maximum Pool Size (Max Pool Size, MaxPoolSize) | 100 | The most connections the pool opens. At least 1. |
Minimum Pool Size (Min Pool Size, MinPoolSize) | 0 | How 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) | 300 | Seconds an unused pooled connection is kept before it is closed. |
Keepalive (Keep Alive) | 10 | Seconds between pings of an unused pooled connection, so the server does not close it. 0 sends none. |
Idle Reconnect (IdleReconnect) | 20 | A 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. |
Notices | true | Whether connections ask the server to send notices (RAISE NOTICE, warnings). See Notices. |
Application Name (ApplicationName) | none | Accepted 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:
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
Login | what happens | needs |
|---|---|---|
Auto (default) | Password when the connection string has a Password, otherwise Trust. | |
Password | A SCRAM-SHA-256 exchange, bound to the TLS connection it runs on. | Username and Password |
Trust | No exchange at all. | A listener that asks for none (the server's --rdb-auth trust, or a socket under --rdb-socket-auth trust) |
Peer | The 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:
Host=db.example.com;Username=app;Password=secretA trust login over a local socket, running as the role app:
Socket=/run/rdb/rdb.sock;Role=appRules worth knowing:
Login=Passwordwithout bothUsernameandPasswordis an error before anything is sent.- On a
Trustlogin,Usernamewithout aPasswordis taken as the role, the same asRole. Roleis only forTrustlogins. A password or peer login names its role withUsername; givingRoleas 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=Trustif 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:
Trust | the certificate is accepted when | use it for |
|---|---|---|
AcceptAny (default) | always | a server on your own machine or a network you control |
WebPki | it chains to a root the operating system trusts, and is issued for Host | a server with a certificate from a public authority |
RootCa | it chains to the authority in Root Certificate, and is issued for Host | a server with a certificate from your own authority |
Pinned | its SHA-256 fingerprint is one of those in Certificate Fingerprint | exactly 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:
Host=db.internal;Username=app;Password=secret;Trust=RootCa;Root Certificate=/etc/rdb/ca.pemA pinned certificate. Print the fingerprint with OpenSSL; the colons it writes, spaces, upper or lower case, and a leading SHA256= are all accepted:
openssl x509 -in server.pem -noout -fingerprint -sha256Host=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:9CTo 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 Engine | behaviour |
|---|---|
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. |
Platform | Always SslStream. A password login then fails on platforms where the binding cannot be read. |
Managed | Always 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:
rasterizeddb --location ./rdb-data --rdb-socket /run/rdb/rdb.sock --rdb-socket-auth peerand connect with any of these forms:
Socket=/run/rdb/rdb.sock
Host=unix:/run/rdb/rdb.sock
Host=/run/rdb/rdb.sockOn 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,600unless set). Trustother thanAcceptAny, andClient Certificate, are errors: there is no certificate to check or present.--rdb-socket-authdecides the login:peerpairs withLogin=Peer,trustwithLogin=Trust(or aRole),scram-sha-256with 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.
Host=db.example.com;Username=app;Password=secret;Database=shopA 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
RasterizedDbDataSourceowns its pool. ARasterizedDbConnectioncreated from a connection string alone shares one pool with every other connection made from exactly the same string. - When the pool is full,
Openwaits for a connection to be returned, up toTimeoutseconds, and then fails with an error that namesMaximum 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
Keepaliveseconds, and closes those unused forConnection Idle Lifetime, keeping at leastMinimum 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 Reconnectseconds (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'scurrval. - 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
RasterizedDbExceptionwhoseKindisTransactionLost. 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:
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:
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:
{
"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:
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 Nameis accepted and ignored.Minimum Pool Sizekeeps connections, it does not open them in advance.- A connection's database cannot change while it is open.