Connect
Rust library
The nordbase crate for Rust: client, the sql! macro checked at compile time, the builder, Consistency, Document Databases and errors.
The nordbase crate wraps a proven async PostgreSQL driver on Tokio and the official MongoDB driver. It adds what NordBase needs: reading NORDBASE_URL, choosing a Region, Consistency and parameter-only SQL that is checked when your code compiles.
This page covers the parts of the Rust API that are fixed today. The rest is marked coming soon.
Install
cargo add nordbase
cargo add tokio --features fullCreate a client
use nordbase::Client;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let db = Client::from_env()?;
// ...
Ok(())
}Client::from_env() reads NORDBASE_URL, or the key file at NORDBASE_KEY_FILE when the URL is not set. On first use it picks the Region to serve Reads from, using NORDBASE_REGION or the fastest Endpoint. See Connection URL.
Create one client per process and share it. It holds a connection pool.
SQL with sql!
The sql! macro takes a string literal with {name} placeholders for variables in scope. At compile time it turns the literal into SQL text with $1…$n and a list of parameters, so a value never becomes SQL text:
use nordbase::{sql, Client};
let db = Client::from_env()?;
let customer_id: i64 = 1042;
let orders = db
.query(sql!(
"select id, total, status
from orders
where customer_id = {customer_id}
order by created_at desc
limit 20"
))
.await?;A query built at runtime, with format! or a String, does not compile where sql! is expected. The safe form is the only form that builds. See Safe SQL.
Coming soon to this page: the Rust forms of sql.id for names, sql.join for lists, nested fragments, and the two escape hatches. unsafe is a reserved word in Rust, so the raw-text function gets a different name there.
The builder
let latest = db
.from("orders")
.select("id, total, status")
.eq("customer_id", 1042)
.limit(20)
.await?;Rows are validated before sending against serde types, which nordbase gen types will write from your live Database. The Rust forms of ordering, in, or, inserts and upserts are coming soon. See The builder for what the builder does in every language.
Transactions
How a transaction behaves on NordBase is fixed:
- A transaction that contains a Write runs on the Primary as a whole.
- A transaction started read-only may use a Replica.
- On port 5432, session state lasts for one transaction: use
set local, notset.
The transaction API in the Rust library is coming soon. Until then, run a transaction with tokio-postgres or sqlx over the same NORDBASE_URL; the Router applies the same rules.
Consistency
Every client defaults to nearest: Reads come from the nearest healthy Instance. strong sends Reads to the Primary. After a Write, a client's own Reads go to the Primary for 2,000 ms by default.
The library lets you choose Consistency per client and per call. The Rust form of both options is coming soon. See Replicas and Consistency.
Document Databases
The NordBase Document client for Rust, with the operator-injection guard and op helpers, is coming soon. Until then, connect with the official mongodb crate and keep request data out of filters: deserialize requests into typed structs, so a field that should be a string can never arrive as an operator document.
use mongodb::{bson::{doc, Document}, Client};
let client = Client::with_uri_str(std::env::var("NORDBASE_URL")?).await?;
let orders = client.database("shop").collection::<Document>("orders");
let number: String = request.number; // typed, never a Document
let order = orders.find_one(doc! { "number": number }).await?;See Document Databases.
Errors
The library reports the same errors as every NordBase library:
| Error | When |
|---|---|
AuthenticationError | Wrong, revoked or expired Credential |
PermissionError | Not allowed by the Permission set |
ReadOnlyLockError | Storage is full; Writes are refused |
TooManyConnectionsError | Every connection your Plan allows is in use |
TimeoutError | A statement ran over 30 seconds on port 5432 |
ConnectionError | Unreachable after retries |
The Rust error type that carries them is coming soon. Reads and transactions that never reached the Database are retried for up to 30 seconds. A Write whose outcome is unknown is never retried. See Errors.