Errors
Every call in the Rust client returns rasterizeddb_client::Result<T>, which is std::result::Result<T, rasterizeddb_client::Error>. This page lists what Error can be, how to read a SQLSTATE from it, which errors are worth retrying, and the patterns that handle them.
The Error type
Error implements std::error::Error, Display and Debug, so ? works into Box<dyn std::error::Error>, anyhow::Error and the like. It is #[non_exhaustive]: a match on it needs a final _ arm.
| variant | meaning | did the statement run? |
|---|---|---|
Transport(…) | the connection failed: it could not be opened, it closed, or the answer did not come in time | unknown; nothing is sent again |
Server(String) | the server ran the statement, or tried to, and refused it; the text is the server's message | no (it failed) |
Protocol(String) | the server's answer could not be read | unknown |
Param(String) | a parameter could not be written: a $n with no value, text holding a NUL, a number that is not one | not sent |
Column { index, message } | a cell could not be read as the type asked for, or a row had another width than the type | yes; reading failed |
Unsupported(String) | refused before anything was sent: two statements in one text, transaction control written as SQL, an ORM call the model does not allow (a bulk update with no filter, restore without a soft-delete column…), a migration conflict | not sent |
RowCount { expected, got } | fetch_one, fetch_optional or fetch_scalar got another number of rows; also an ORM update of a row that is gone | yes |
TransactionLost { commit_outcome_unknown, message } | a transaction's connection failed, idled out, or was left unusable by a dropped statement future; the transaction is over | rolled back, unless commit_outcome_unknown |
Conflict(String) | an ORM write found the row at another version than the struct holds, or an update_many found a row gone; nothing was written | no |
Invalid(String) | a model's validate hook refused the row; nothing was sent | not sent |
Display prefixes the kind: server: …, transport: …, parameter: …, column 2: …, unsupported: …, conflict: …, invalid: …, expected exactly 1 row(s), the statement returned 0.
Client-side sharding adds six variants: ShardDown, MapStale, IdentityMismatch, FanOutPartial, CrossShard and NeedsRouteKey. They are described on Client-side sharding.
Checks
Rather than matching variants, ask the error a question:
| method | true when |
|---|---|
is_transport() | the connection failed (including a lost transaction): only then can a statement's fate be unknown |
is_connection_lost() | the connection closed or broke under the statement (the server restarted or dropped it), rather than timing out |
is_timeout() | nothing came back within Options::timeout on this side (or the 10 s a login has); the statement may still be running on the server |
is_server_timeout() | the server gave up on the statement at its request timeout without stopping it; whether a write took effect is unknown |
is_statement_timeout() | the server stopped the statement at its statement timeout (57014); nothing of it took effect and the connection goes on |
is_message_too_large() | the answer was bigger than Options::max_message_size; the statement ran, its answer was not read, and the connection was closed |
is_transaction_lost() | a transaction's connection was lost |
is_commit_outcome_unknown() | the connection failed while COMMIT was in flight: it may or may not have committed |
may_predate_database_selection() | connect named a database and the server may be too old to select one over the native protocol |
is_serialization_failure() | SQLSTATE 40001 |
is_deadlock() | SQLSTATE 40P01 |
is_retryable() | 40001 or 40P01: running the whole transaction again may succeed |
is_unique_violation() | the server refused a write for breaking a unique or primary key |
is_conflict() | Error::Conflict |
is_invalid() | Error::Invalid |
is_no_rows() | Error::RowCount with no rows: fetch_one found nothing |
| accessor | returns |
|---|---|
server_message() | Option<&str>: the server's message, for Error::Server |
sqlstate() | Option<&str>: the five-character SQLSTATE, when the error carries one |
SQLSTATE codes
The native protocol has no separate field for an error code. What sqlstate() can read depends on where the statement ran:
- Inside a transaction, the server ends every error message with
(SQLSTATE xxxxx), andsqlstate()returns that code. - A statement stopped at the statement timeout carries
57014in or out of a transaction. - A simple query (
simple_query, aSimpleSession) carries its SQLSTATE. - Other statements sent on a
Clientmostly carry no code, andsqlstate()isNone. Use the message-based checks (is_unique_violation()) or run the statement in a transaction when your code must branch on the code.
Codes you will meet most often:
| code | meaning |
|---|---|
23505 | unique or primary key broken |
25P02 | the transaction had already failed; roll it back |
25006 | a write in a read-only transaction |
25001 | a statement that cannot run inside a transaction (CREATE DATABASE) |
40001 | serialization failure: retry the transaction |
40P01 | deadlock victim: retry the transaction |
55P03 | a lock wait passed lock_timeout |
57014 | statement timeout |
What to retry
| error | retry? |
|---|---|
is_retryable() (40001, 40P01) | yes, the whole transaction, from its first statement. client.transaction(…) does it for you. |
is_conflict() | after reading the row again and reapplying your change |
is_statement_timeout() | only after making the statement cheaper, or raising the timeout (Connecting) |
is_transport(), is_timeout(), is_server_timeout() | only if the statement is safe to run twice: it may already have run. A read, or a write keyed so a second run changes nothing (INSERT … ON CONFLICT DO NOTHING, UPDATE … SET x = 5), is safe. The next statement reconnects by itself. |
is_commit_outcome_unknown() | never blindly: check the data first |
is_message_too_large() | with a smaller read (LIMIT, keyset pages), or a larger max_message_size |
Server (other), Param, Unsupported, Column, Invalid | no: the same call fails the same way |
The client itself never sends a statement twice.
Patterns
A unique key taken, as a normal outcome:
use rasterizeddb_client::prelude::*;
async fn sign_up(client: &Client, email: &str) -> Result<bool> {
match client.exec("INSERT INTO users (email) VALUES ($1)", params![email]).await {
Ok(_) => Ok(true),
Err(e) if e.is_unique_violation() => Ok(false), // already registered
Err(e) => Err(e),
}
}No row, as None, without fetch_optional:
use rasterizeddb_client::prelude::*;
async fn price_of(client: &Client, id: i64) -> Result<Option<Numeric>> {
match client.fetch_scalar("SELECT price FROM items WHERE id = $1", params![id]).await {
Ok(price) => Ok(Some(price)),
Err(e) if e.is_no_rows() => Ok(None),
Err(e) => Err(e),
}
}A retry loop for a write that is safe to repeat, around a flaky network (tokio::time::sleep needs tokio's time feature):
use rasterizeddb_client::prelude::*;
use std::time::Duration;
async fn mark_paid(client: &Client, invoice: i64) -> Result<()> {
let mut attempt = 0;
loop {
match client.exec("UPDATE invoices SET paid = true WHERE id = $1", params![invoice]).await {
Ok(_) => return Ok(()),
Err(e) if e.is_transport() && attempt < 3 => {
attempt += 1;
tokio::time::sleep(Duration::from_millis(200 * attempt)).await;
}
Err(e) => return Err(e),
}
}
}Branching on a SQLSTATE inside a transaction:
use rasterizeddb_client::prelude::*;
async fn try_lock(client: &Client, id: i64) -> Result<bool> {
let tx = client.begin().await?;
tx.run("SET lock_timeout = '2s'").await?;
match tx.fetch_optional::<(i64,)>("SELECT id FROM job WHERE id = $1 FOR UPDATE", params![id]).await {
Ok(_) => {
tx.commit().await?;
Ok(true)
}
Err(e) if e.sqlstate() == Some("55P03") => {
tx.rollback().await?;
Ok(false) // someone else holds it
}
Err(e) => Err(e),
}
}An error in an application error type:
use rasterizeddb_client::Error as DbError;
#[derive(Debug)]
enum AppError {
NotFound,
Busy,
Db(DbError),
}
impl From<DbError> for AppError {
fn from(e: DbError) -> Self {
if e.is_no_rows() {
AppError::NotFound
} else if e.is_retryable() || e.is_statement_timeout() {
AppError::Busy
} else {
AppError::Db(e)
}
}
}Limits
- Outside a transaction and outside the simple-query form, most server errors carry no SQLSTATE;
is_unique_violation()reads the message instead. - The inner value of
Error::Transportis the transport crate's error type, which this crate does not re-export. Use theis_…checks rather than matching on it. - After a transport error the client cannot tell whether the statement ran. Design writes to be safe to repeat when you retry them.