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 / READING RESULTS

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

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();

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 commandany number, with NextResult() between resultsexactly one
column names, GetOrdinal, reader["name"]yes, sent with the answeryes, 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 columnthe type of each cell; GetDataTypeOid is 0
cellsPostgreSQL's text form, parsed when readthe engine's typed binary values, decoded in place
server paththe PostgreSQL-compatible paththe native path; a repeated statement text is answered from a parse the server learned
command.Cancel() from another threadalwaysonly 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

getternotes
GetInt16, GetInt32, GetInt64, GetByteA wider getter reads a narrower column (GetInt64 on an integer). A narrower getter on a value that does not fit throws InvalidCastException.
GetFloat, GetDouble, GetDecimalNumbers convert between each other; see NUMERIC.
GetBoolean, GetString, GetChar, GetGuidGetString works on any column and gives its text form.
GetDateTime, GetDateTimeOffset, GetDateOnly, GetTimeOnlySee Dates and times.
GetTimeSpan, GetIntervalinterval columns.
GetBytes, GetStream, GetFieldValue<byte[]>bytea columns.
GetChars, GetTextReaderText 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"], GetValuesThe 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 typedefault .NET typealso readable as
booleanboolstring
smallintshortint, long, byte, decimal, double
integerintlong, short (when it fits), decimal, double
bigintlongint (when it fits), decimal, double
realfloatdouble, decimal
double precisiondoublefloat, decimal
numericdecimal; a string holding the exact digits when the value does not fit decimaldouble, string, integers (when whole)
text, character varying, characterstringchar (a single character)
uuidGuidstring
byteabyte[]ReadOnlyMemory<byte>, Stream
timestamp with time zoneDateTime, Kind UtcDateTimeOffset, DateOnly, TimeOnly
timestamp without time zoneDateTime, Kind UnspecifiedDateTimeOffset, DateOnly, TimeOnly
dateDateOnlyDateTime (midnight)
timeTimeOnly
intervalTimeSpan; RasterizedDbInterval when it holds monthsRasterizedDbInterval always
json, jsonbstring (the JSON text)JsonDocument, JsonElement
inetstring
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 cellresult
IsDBNull(i)true
GetValue(i), reader[i], GetFieldValue<object>(i)DBNull.Value
GetFieldValue<int?>(i), or any other nullable value typenull
GetInt32(i), GetString(i), GetFieldValue<string>(i) and the other typed gettersInvalidCastException

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:

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

  • GetDecimal and GetFieldValue<decimal> throw InvalidCastException.
  • GetValue returns the exact digits as a string instead.
  • GetString always gives the exact digits.
  • GetDouble gives the nearest double.

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>():

csharp
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 zone is an instant and comes back as a UTC DateTime (Kind Utc).
  • A timestamp without time zone is a wall-clock time and comes back with Kind Unspecified.
  • GetDateTimeOffset on a binary-format cell gives offset zero. In the text format it keeps the offset the server wrote.
  • A time of 24:00:00, which SQL allows, is not a TimeOnly and throws.
  • Values outside years 1 to 9999 cannot be a DateTime and throw.

Writing (as parameters):

  • A DateTime with Kind Utc or Local, and any DateTimeOffset, is sent as an instant in UTC. Use these for timestamp with time zone columns.
  • A DateTime with Kind Unspecified is sent with no zone, which a timestamp without time zone column 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:

csharp
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).

csharp
byte[] avatar = reader.GetFieldValue<byte[]>(0);

Write byte[] (or ReadOnlyMemory<byte>) parameters; they are sent as hex literals.

Arrays

csharp
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

membergives
FieldCountColumns 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.
HasRowsWhether the current result has rows.
RecordsAffected, RowsAffectedRows 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[] from GetValue; ask for the element type with GetFieldValue<T[]>.
✓ page rendered in 205 µs axum + tera + htmx · no other javascript