Types
This page lists which Rust types fill a $n parameter, which Rust types a column can be read as, and how NULL, exact decimals, JSON, points in time and arrays travel. It ends with how to add your own types.
Writing and reading in one table
A Rust type that implements ToSql can be a parameter (params![…]). One that implements FromSql can be read from a cell (row.get::<T>(i), a tuple element, a FromRow field). The last column is the type the ORM gives a field of that Rust type when it creates a table.
| Rust | written as | reads from | ORM column type |
|---|---|---|---|
bool | true, false | BOOLEAN | BOOLEAN |
i8, i16 | 5 | any integer column that fits | SMALLINT |
i32, u16 | 5 | any integer column that fits | INTEGER |
i64, u32, isize | 5, (-5) | any integer column that fits | BIGINT |
u64, usize | 5 | any integer column that fits | UBIGINT |
i128 | 5 | any integer column that fits | HUGEINT |
u8, u128 | (not a parameter) | any integer column that fits | |
f32 | 0.1::real | REAL; DOUBLE PRECISION when the value is exact as f32 | REAL |
f64 | 0.1, 'NaN' | DOUBLE PRECISION, REAL, integers | DOUBLE PRECISION |
Numeric | 12.50 | NUMERIC, DECIMAL, integers | NUMERIC |
&str, String, Cow<str> | 'it''s' | TEXT, VARCHAR, CHAR, JSON text | TEXT |
&[u8], Vec<u8>, [u8; N] | '\x00ff' | BYTEA | BYTEA |
Uuid | 'a0eebc99-…' | UUID | UUID |
Timestamp, std::time::SystemTime | '2026-11-16 12:00:00+00' | TIMESTAMPTZ, TIMESTAMP | TIMESTAMPTZ |
Date | '2026-11-16' | DATE | DATE |
Time | '13:05:09.25' | TIME | TIME |
Interval, std::time::Duration | '1 mons 2 days 3 microseconds' | INTERVAL | INTERVAL |
Json | '{"a":1}' | JSON, JSONB | JSONB |
Vec<T>, &[T], [T; N] | '{1,2,NULL}' | arrays | T[] |
Option<T> | NULL when None | any column; NULL is None | T, nullable |
Value | its variant | any column |
Numeric, Uuid, Timestamp, Date, Time, Interval, Json and Value are the crate's own types, all in the prelude. SystemTime and Duration are written as parameters; read them as Timestamp and Interval and convert (SystemTime::from(ts)).
Reading an integer into a narrower Rust integer that cannot hold the value is an error ("300 does not fit u8"), never a wrapped number.
Every non-text type also reads from text. A column selected as col::text reads back as its own type: "2026-01-02" as a Date, "12.50" as a Numeric, "{1,2,NULL}" as a Vec<Option<i64>>. This is the way out when a cell arrives in a form a type cannot read: the error message names the cast to use.
NULL and Option
Use Option<T> for every column that may be NULL. Reading a NULL into a type that is not an Option is an error (Error::Column), never a default value. As a parameter, None is written as NULL:
use rasterizeddb_client::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let nickname: Option<&str> = None;
client
.exec("INSERT INTO people (name, nickname) VALUES ($1, $2)", params!["Ada", nickname])
.await?;
let (name, nick): (String, Option<String>) = client
.fetch_one("SELECT name, nickname FROM people WHERE name = $1", params!["Ada"])
.await?;
assert_eq!((name.as_str(), nick), ("Ada", None));
Ok(())
}Comparing with a NULL parameter follows SQL: WHERE nickname = $1 with None matches nothing. Write IS NULL, or IS NOT DISTINCT FROM $1.
Exact decimals: Numeric
Numeric holds an exact decimal as its text (-12.3400, 1e-5, NaN), so nothing is lost on the way to the decimal type of your choice:
use rasterizeddb_client::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let price = Numeric::new("19.99")?; // Err for text that is not a number
client.exec("UPDATE items SET price = $1 WHERE id = $2", params![price, 7i64]).await?;
let stored: Numeric = client.fetch_scalar("SELECT price FROM items WHERE id = $1", params![7i64]).await?;
println!("{}", stored.as_str()); // "19.99" from a NUMERIC(10,2)
let from_int = Numeric::from(42i64); // From every integer type
let parsed: Numeric = "3.14".parse()?; // FromStr
println!("{from_int} {parsed}");
Ok(())
}on Numeric | does |
|---|---|
Numeric::new(text) | checks text is [+-]digits[.digits][e[+-]digits] or NaN; Err(Error::Param) otherwise |
as_str(), into_string() | the number's text |
From<i8…i128, u8…u128> | an integer as a Numeric |
FromStr, Display | parse and print |
A NUMERIC(p, s) column arrives with its scale (12.50). An aggregate the server types NUMERIC (a sum() over integers, avg()) reads as a Numeric too. A float column read as Numeric is refused, because a float is not exact; read it as f64.
To use a decimal crate, parse the text: stored.as_str().parse::<rust_decimal::Decimal>().
Floats
An f32 is written as 0.1::real. A bare 0.1 is a NUMERIC literal, which never equals the REAL 0.1 (that is 0.100000001490116…), so WHERE r = 0.1 would find nothing, as in PostgreSQL; the cast makes an f32 parameter equal a REAL column holding it. NaN and the infinities are written as 'NaN', 'Infinity' and '-Infinity'.
Text and bytes
&str borrows from the answer (no copy); String owns. A text value cannot hold a NUL byte: writing one is Error::Param. Bytes are written as a hex literal and read from BYTEA columns as Vec<u8> or &[u8].
JSON and JSONB
Json holds a JSON document's text. The server checks it on the way in.
use rasterizeddb_client::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let doc = Json::new(r#"{"theme":"dark","size":14}"#);
client.exec("INSERT INTO settings (user_id, doc) VALUES ($1, $2)", params![1i64, doc]).await?;
let back: Json = client.fetch_scalar("SELECT doc FROM settings WHERE user_id = $1", params![1i64]).await?;
println!("{}", back.as_str());
let theme: Option<String> = client
.fetch_scalar("SELECT doc ->> 'theme' FROM settings WHERE user_id = $1", params![1i64])
.await?;
println!("{theme:?}");
Ok(())
}A jsonb column arrives as its JSON text; read it as Json or String. If a cell arrives as a stored binary document instead, reading it is an error that says to select the column as col::text, never a garbled string.
With the serde_json feature:
| call | does |
|---|---|
Json::from_value(&value) | any Serialize value as Json |
json.parse::<T>() | the document as any DeserializeOwned type |
row.get::<serde_json::Value>(i) | a JSON column as a serde_json::Value |
#[rdb(json)] on a model or FromRow field | the field is stored as JSONB and (de)serialized with serde (The ORM) |
The server's JSON operators and functions are on JSON.
Points in time
| type | holds | build with |
|---|---|---|
Timestamp | microseconds since the Unix epoch (pub micros: i64) | Timestamp::now(), from_micros, from_unix_seconds, from_ymd_hms(y, m, d, h, min, s) (Option), From<SystemTime>, FromStr |
Date | days since 1970-01-01 | Date::from_ymd(y, m, d) (Option), from_unix_days, FromStr; read back with ymd(), unix_days() |
Time | microseconds since midnight | Time::from_hms_micro(h, m, s, us) (Option), Time::from_micros (Option), Time::MIDNIGHT, FromStr |
Interval | months, days, micros (all public) | Interval::new(months, days, micros), Interval::from_micros, From<Duration>, FromStr |
timestamp.date() and timestamp.time() give its UTC date and time of day. All four implement Display.
A Timestamp parameter is written in UTC with an explicit +00. A timestamptz column stores that instant whatever the server's time zone; a timestamp column stores the UTC wall-clock time (PostgreSQL drops the zone there).
use rasterizeddb_client::prelude::*;
use std::time::Duration;
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let due = Date::from_ymd(2026, 12, 1).expect("a real date");
let grace = Duration::from_secs(3 * 24 * 3600);
client
.exec(
"INSERT INTO invoices (id, issued, due, grace) VALUES ($1, $2, $3, $4)",
params![1i64, Timestamp::now(), due, grace],
)
.await?;
let (issued, grace): (Timestamp, Interval) = client
.fetch_one("SELECT issued, grace FROM invoices WHERE id = $1", params![1i64])
.await?;
println!("{issued} {} days", grace.days);
Ok(())
}With the chrono feature, DateTime<Tz> (written; read as DateTime<Utc>), NaiveDateTime, NaiveDate and NaiveTime are parameters and results too. A NaiveDateTime is taken as UTC. In a model, DateTime<Utc> is a TIMESTAMPTZ column and NaiveDateTime a TIMESTAMP one.
UUIDs
The crate's Uuid is 16 bytes (Uuid(pub [u8; 16])): Uuid::new_v4()? makes a random one, "…".parse::<Uuid>()? parses one, and Display prints the canonical form. With the uuid feature, uuid::Uuid works as a parameter, a result and a model field.
Arrays
A Vec<T>, &[T] or [T; N] is written as an array literal ('{1,2,NULL}'), for an array column or for = ANY($1):
use rasterizeddb_client::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::connect("unix:/run/rdb/rdb.sock", Options::default()).await?;
let tags = vec!["rust".to_string(), "db".to_string()];
client.exec("INSERT INTO posts (id, tags) VALUES ($1, $2)", params![1i64, tags]).await?;
let tags: Vec<String> = client.fetch_scalar("SELECT tags FROM posts WHERE id = $1", params![1i64]).await?;
let wanted = [1i64, 2, 3];
let found: Vec<(i64,)> = client.fetch_all("SELECT id FROM posts WHERE id = ANY($1)", params![wanted]).await?;
println!("{tags:?} {found:?}");
Ok(())
}Element types:
| direction | element types |
|---|---|
| written | bool, i8, i16, i32, i64, u16, u32, u64, f32, f64, String, &str, Uuid, Timestamp, Date, Time, Interval, Numeric, Json, Value; Option<…> of bool, i16, i32, i64, u64, f32, f64, String, &str, Uuid, Timestamp, Date, Numeric; and Vec<i16>, Vec<i32>, Vec<i64>, Vec<f64>, Vec<String> (two dimensions) |
read as Vec<…> | bool, i16, i32, i64, u32, u64, f32, f64, String, Uuid, Timestamp, Date, Time, Interval, Numeric, Json, Value; Option<…> of bool, i16, i32, i64, f64, String, Uuid, Timestamp, Date, Numeric; and Vec<i16>, Vec<i32>, Vec<i64>, Vec<f64>, Vec<String> |
Read an array that may hold NULLs as Vec<Option<T>>: reading a NULL element into Vec<T> is an error naming the element. Param::Array(ArrayRef::new(&values)) builds an array parameter from any slice of ToSql values.
Values of unknown type: Value
Value is for code that does not know a result's shape in advance. row.values() and Vec<Value> as a FromRow type read every cell into one:
| variant | for |
|---|---|
Null | SQL NULL |
Bool(bool) | BOOLEAN |
I16, I32, I64, U64, I128 | integers |
F32, F64 | floats |
Numeric(Numeric) | exact decimals |
Text(String) | text (a text cell that is not UTF-8 is Bytes) |
Bytes(Vec<u8>) | BYTEA |
Uuid, Timestamp, Date, Time, Interval, Json | those types |
Array(Vec<Value>) | arrays |
Value is also a parameter, has is_null(), as_str(), as_i64(), as_f64(), as_bool(), as_bytes() (each an Option), implements Display, and converts From the common Rust types. The enum is #[non_exhaustive]: end a match on it with _.
Enums as text: SqlEnum
#[derive(SqlEnum)] stores an enum of unit variants as text. It implements ToSql, FromSql (an unknown text is an error naming the variants) and the ORM's SqlType (TEXT), and adds as_sql_str():
use rasterizeddb_client::SqlEnum;
#[derive(SqlEnum, Debug, Clone, Copy, PartialEq)]
#[rdb(rename_all = "snake_case")]
enum Status {
Active,
#[rdb(rename = "on-hold")]
OnHold,
PastDue,
}
fn main() {
assert_eq!(Status::OnHold.as_sql_str(), "on-hold");
assert_eq!(Status::PastDue.as_sql_str(), "past_due");
}| attribute | on | values |
|---|---|---|
rename_all = "…" | the enum | snake_case (the default), SCREAMING_SNAKE_CASE, kebab-case, lowercase, UPPERCASE, PascalCase |
rename = "…" | a variant | the exact text stored |
Variants carrying data are refused at compile time. Renaming a variant changes what is stored: rows written before keep the old text, which then fails to read.
Your own types
Implement ToSql to make a type a parameter, and FromSql to read it from a cell. Both can build on an existing type:
use rasterizeddb_client::{FromSql, Param, ToSql};
#[derive(Debug, Clone, PartialEq)]
pub struct Email(String);
impl ToSql for Email {
fn to_param(&self) -> Param<'_> {
Param::Text(&self.0)
}
}
impl<'r> FromSql<'r> for Email {
fn from_sql(tag: u8, raw: &'r [u8]) -> std::result::Result<Self, String> {
let text = String::from_sql(tag, raw)?;
if text.contains('@') {
Ok(Email(text))
} else {
Err(format!("{text:?} is not an email address"))
}
}
}to_paramreturns aParamthat may borrow fromself; nothing is copied until the statement is written.from_sqlgets the cell's type tag and bytes, and returnsErr(message)for a cell it cannot read; the client adds which column. It is never called for NULL:Option<Email>works by itself.FromSql<'r>lets a type borrow from the answer, as&strdoes. A type that borrows nothing (likeEmail) isFromSqlOwnedautomatically, whichfetch_scalarand tuples need.ToSqlrequiresSync.
To use such a type as a model field, give the field its column type, and say it is read as text if the column's native form is not one from_sql reads:
use rasterizeddb_client::prelude::*;
// Email as defined above, with its ToSql and FromSql implementations.
#[derive(Model, Debug, Clone)]
struct Subscriber {
#[rdb(primary_key, serial)]
id: i64,
#[rdb(sql_type = "TEXT", unique)]
email: Email,
}#[rdb(text)] on a field selects the column as col::text and reads it with the type's FromSql. Alternatively implement rasterizeddb_client::orm::SqlType for the type (const SQL_TYPE: &'static str, and optionally NULLABLE and READ_AS_TEXT) so no attribute is needed. A whole-row type implements FromRow (fn from_row(row: &Row<'_>) -> Result<Self>), or derives it.
Limits
u8andu128read from integer columns but are not parameters; usei16ori128.Numericis text: arithmetic on it needs a decimal crate.- Array element types are the ones listed above; other element types are written through
Valueor read ascol::textand parsed. - The types of
jsonfields andserde_json::Valueneed theserde_jsonfeature;chronoanduuidtypes need their features.