Reading results
This page covers getting rows out of RasterizedDB in .NET: the data reader, the two result formats and when to pick each, which .NET type each SQL type reads as, and how NULLs, numbers, JSON, timestamps and bytes behave.
Reading rows
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();
await using var command = connection.CreateCommand(
"SELECT id, email, created_at, balance FROM accounts WHERE country = @country ORDER BY id");
command.Parameters.Add("country", "BG");
await using var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
long id = reader.GetInt64(0);
string email = reader.GetString(1);
DateTime createdAt = reader.GetDateTime(2); // UTC for a timestamptz column
decimal? balance = reader.GetFieldValue<decimal?>(3); // null for a NULL cell
Console.WriteLine($"{id} {email} {createdAt:O} {balance}");
}The whole answer has arrived by the time ExecuteReaderAsync returns, so Read/ReadAsync never wait on the network. Cells are decoded from the answer's bytes only when a getter asks for them.
The two result formats
The server can answer a statement in two forms. Pick one per connection string (Result Format=Binary) or per command (command.ResultFormat = RasterizedDbResultFormat.Binary).
Text (the default) | Binary | |
|---|---|---|
| statements per command | any number, with NextResult() between results | exactly one |
column names, GetOrdinal, reader["name"] | yes, sent with the answer | yes, asked of the server once per distinct statement text and cached; ?column? when the server cannot describe the statement |
column types (GetDataTypeName, GetDataTypeOid) | the PostgreSQL type of each column | the type of each cell; GetDataTypeOid is 0 |
| cells | PostgreSQL's text form, parsed when read | the engine's typed binary values, decoded in place |
| server path | the PostgreSQL-compatible path | the native path; a repeated statement text is answered from a parse the server learned |
command.Cancel() from another thread | always | only with command.Cancelable = true |
Use Binary for statements you run often and read by position or by known name. Use Text for statements with several parts, ad hoc SQL, and code that inspects result columns it did not choose. Both formats read every type in the mapping table below the same way.
RasterizedDbResultFormat.Default on a command means "the connection string's setting".
Getting values
| getter | notes |
|---|---|
GetInt16, GetInt32, GetInt64, GetByte | A wider getter reads a narrower column (GetInt64 on an integer). A narrower getter on a value that does not fit throws InvalidCastException. |
GetFloat, GetDouble, GetDecimal | Numbers convert between each other; see NUMERIC. |
GetBoolean, GetString, GetChar, GetGuid | GetString works on any column and gives its text form. |
GetDateTime, GetDateTimeOffset, GetDateOnly, GetTimeOnly | See Dates and times. |
GetTimeSpan, GetInterval | interval columns. |
GetBytes, GetStream, GetFieldValue<byte[]> | bytea columns. |
GetChars, GetTextReader | Text columns. |
GetFieldValue<T> | Any type in the table below, nullable value types, arrays (T[], List<T>), enums, Int128, BigInteger, JsonDocument, JsonElement, RasterizedDbInterval. |
GetValue, reader[i], reader["name"], GetValues | The column's default .NET type (the table below), boxed. |
GetRawSpan(i) | The cell's bytes as they arrived, without a copy: UTF-8 for text and for every cell of the text format. Valid until the reader moves on. |
Every type can also be read from text, so a column selected as col::text, and every cell of the text format, reads back as its own type: GetInt64 on the text '42' gives 42.
A getter that cannot convert a cell throws InvalidCastException naming the column.
Reading by name works in both formats. GetOrdinal looks for an exact match first, then ignores case.
SQL to .NET type mapping
The default type is what GetValue returns and what GetFieldType reports.
| SQL type | default .NET type | also readable as |
|---|---|---|
boolean | bool | string |
smallint | short | int, long, byte, decimal, double |
integer | int | long, short (when it fits), decimal, double |
bigint | long | int (when it fits), decimal, double |
real | float | double, decimal |
double precision | double | float, decimal |
numeric | decimal; a string holding the exact digits when the value does not fit decimal | double, string, integers (when whole) |
text, character varying, character | string | char (a single character) |
uuid | Guid | string |
bytea | byte[] | ReadOnlyMemory<byte>, Stream |
timestamp with time zone | DateTime, Kind Utc | DateTimeOffset, DateOnly, TimeOnly |
timestamp without time zone | DateTime, Kind Unspecified | DateTimeOffset, DateOnly, TimeOnly |
date | DateOnly | DateTime (midnight) |
time | TimeOnly | |
interval | TimeSpan; RasterizedDbInterval when it holds months | RasterizedDbInterval always |
json, jsonb | string (the JSON text) | JsonDocument, JsonElement |
inet | string | |
arrays (integer[], text[], …) | in the text format, a typed array for boolean, integer, floating-point, numeric, uuid and text arrays (int?[], string[], …) and a string for other array types; in the binary format, string[] | GetFieldValue<T[]> or GetFieldValue<List<T>> for any element type above |
In the text format, oid columns read as uint, and columns of types not in this table read as string.
Integer columns of an enum type in your code read with GetFieldValue<MyEnum>(); a text cell holding the enum's name reads too.
NULLs
| how you read a NULL cell | result |
|---|---|
IsDBNull(i) | true |
GetValue(i), reader[i], GetFieldValue<object>(i) | DBNull.Value |
GetFieldValue<int?>(i), or any other nullable value type | null |
GetInt32(i), GetString(i), GetFieldValue<string>(i) and the other typed getters | InvalidCastException |
So check IsDBNull first, or read nullable value-type columns with GetFieldValue<T?>. A reference type such as string has no nullable form to ask for, so check IsDBNull for those:
string? nickname = reader.IsDBNull(2) ? null : reader.GetString(2);
int? age = reader.GetFieldValue<int?>(3);ExecuteScalarAsync returns DBNull.Value for a NULL cell and null when there is no row at all.
NUMERIC and decimal
A numeric value reads as decimal when it fits exactly: at most 28 digits after the point, and a magnitude a decimal can hold. Trailing zeros after the point are dropped if needed to fit. A value that cannot be held exactly is not rounded:
GetDecimalandGetFieldValue<decimal>throwInvalidCastException.GetValuereturns the exact digits as astringinstead.GetStringalways gives the exact digits.GetDoublegives the nearestdouble.
Write decimal parameters for numeric columns; they are sent as exact literals.
JSON and JSONB
A json or jsonb column reads as its JSON text with GetString, or parsed with GetFieldValue<JsonDocument>() or GetFieldValue<JsonElement>():
using System.Text.Json;
await using var command = connection.CreateCommand("SELECT settings FROM users WHERE id = @id");
command.Parameters.Add("id", 7L);
await using var reader = await command.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
using var settings = reader.GetFieldValue<JsonDocument>(0);
Console.WriteLine(settings.RootElement.GetProperty("theme").GetString());
}To write JSON, pass a string, JsonDocument, JsonElement or JsonNode parameter; each is sent as its JSON text.
If a read fails with "this is a stored JSONB document, not JSON text", select the column as col::text. What the server stores as JSON is described in JSON.
Dates and times
Reading:
- A
timestamp with time zoneis an instant and comes back as a UTCDateTime(KindUtc). - A
timestamp without time zoneis a wall-clock time and comes back withKindUnspecified. GetDateTimeOffseton a binary-format cell gives offset zero. In the text format it keeps the offset the server wrote.- A
timeof24:00:00, which SQL allows, is not aTimeOnlyand throws. - Values outside years 1 to 9999 cannot be a
DateTimeand throw.
Writing (as parameters):
- A
DateTimewithKindUtcorLocal, and anyDateTimeOffset, is sent as an instant in UTC. Use these fortimestamp with time zonecolumns. - A
DateTimewithKindUnspecifiedis sent with no zone, which atimestamp without time zonecolumn takes as written.
Keep timestamp with time zone columns paired with UTC DateTimes (or DateTimeOffset) in your code, and wall-clock columns with Unspecified ones.
Intervals
An interval keeps months, days and microseconds apart, because a month is not a fixed number of days. One without months reads as a TimeSpan. One with months has no fixed length: GetTimeSpan throws, and GetInterval (or GetFieldValue<RasterizedDbInterval>) gives the parts:
RasterizedDbInterval interval = reader.GetInterval(0);
Console.WriteLine($"{interval.Months} months, {interval.Days} days, {interval.Microseconds} µs");RasterizedDbInterval.FromTimeSpan(span) and interval.ToTimeSpan() convert, and ToString() gives its SQL text form.
Bytes
bytea reads as byte[] with GetFieldValue<byte[]>, in chunks with GetBytes, or as a read-only Stream with GetStream. GetString on a bytea gives PostgreSQL's hex form (\x0102ff).
byte[] avatar = reader.GetFieldValue<byte[]>(0);Write byte[] (or ReadOnlyMemory<byte>) parameters; they are sent as hex literals.
Arrays
await using var command = connection.CreateCommand("SELECT tags, scores FROM posts WHERE id = @id");
command.Parameters.Add("id", 1L);
await using var reader = await command.ExecuteReaderAsync();
await reader.ReadAsync();
string[] tags = reader.GetFieldValue<string[]>(0);
List<int> scores = reader.GetFieldValue<List<int>>(1);Read an array whose elements may be NULL with a nullable element type (int?[]); a NULL element read as a non-nullable type throws. A multi-dimensional array cannot be read directly: select it as col::text. Pass a T[] or List<T> parameter to write an array.
Column information
| member | gives |
|---|---|
FieldCount | Columns in the current result. |
GetName(i) | The column's name (?column? in the binary format when the server cannot describe the statement). |
GetFieldType(i) | The default .NET type. In the binary format, types belong to cells, so this reports the type of the current row's cell (or the first row's before Read), and object when that cell is NULL. |
GetDataTypeName(i) | The SQL type name, such as bigint or timestamp with time zone. |
GetDataTypeOid(i) | The PostgreSQL type OID in the text format; 0 in the binary format. |
GetColumnSchema(), GetSchemaTable() | Name, ordinal, .NET type and SQL type name per column. |
HasRows | Whether the current result has rows. |
RecordsAffected, RowsAffected | Rows the command's writes changed, or -1. RowsAffected is a long. In the binary format a statement that returns rows reports -1. |
DataTable.Load(reader) works in both formats.
For the database's tables and columns, connection.GetSchema("Tables") and connection.GetSchema("Columns", ["orders"]) return DataTables read from information_schema.
Limits
- Results are not streamed: the whole answer is in memory before the first row is read, and must fit
Max Message Size(8 MiB unless raised in the connection string). A larger answer fails and closes the connection. - In the binary format a column's type is known per cell, not per column.
- In the binary format, column names cost one extra request per distinct statement text, the first time a name is asked for.
- Arrays in the binary format read as
string[]fromGetValue; ask for the element type withGetFieldValue<T[]>.