Expand description
§wasi-pg-client
A production-grade PostgreSQL client library for WASI Preview 2.
§Quick Start
use wasi_pg_client::{Connection, Config};
#[wstd::main]
async fn main() -> Result<(), wasi_pg_client::PgError> {
let config = Config::from_uri("postgresql://user:pass@localhost/mydb")?;
let mut conn = Connection::connect(&config).await?;
let result = conn.query("SELECT id, name FROM users").await?;
for row in result.iter() {
let id: i32 = row.get(0)?;
let name: String = row.get(1)?;
println!("{}: {}", id, name);
}
conn.close().await?;
Ok(())
}§Key Features
- Full PostgreSQL wire protocol v3 — simple and extended query protocols
- Parameterized queries — SQL injection prevention with
$1,$2syntax - Prepared statements — with automatic LRU caching
- Streaming results — O(1) memory for large queries via
RowStream - Parameterized streaming —
query_params_stream()for streaming with parameters - Transactions — RAII guards with automatic rollback on drop
- Savepoints — nested transaction scopes
- COPY protocol — bulk import/export with CSV and binary support
- LISTEN/NOTIFY — asynchronous pub/sub with timeout support
- TLS — via rustls (pure Rust, WASI-compatible)
- SCRAM-SHA-256 and MD5 authentication
- Connection pooling — via
wasi_pg_client::poolmodule withMutex-based thread safety - Automatic reconnection — with exponential backoff and session state rebuild
- Retry policies — for transient errors (serialization failures, deadlocks)
- Query cancellation — out-of-band via
CancelToken(with TLS support) - Runtime parameter setting —
set_param()with automatic re-application on reconnect - Structured logging — via
tracing - Compiles to
wasm32-wasip2and native targets
§Feature Flags
| Feature | Default | Description |
|---|---|---|
tls | ✅ | TLS support via rustls |
scram | ✅ | SCRAM-SHA-256 authentication |
md5-auth | ❌ | MD5 authentication (legacy) |
pool | ❌ | Connection pooling |
tracing | ✅ | Structured logging via tracing |
uuid | ❌ | UUID type support via uuid crate |
serde-json | ❌ | JSON type support via serde_json |
chrono | ❌ | chrono integration for date/time |
test-native | ❌ | Native transport for testing |
tokio-transport | ❌ | Tokio async TCP transport for native builds |
§WASI P2 Requirements
This library targets wasm32-wasip2. When running in wasmtime, use:
wasmtime run --wasi inherit-network --wasi inherit-env component.wasmThe getrandom crate must be configured with features = ["wasi"] for
cryptographic randomness (required for SCRAM auth and TLS).
§Tracing
When the tracing feature is enabled, the library emits structured events
at the following levels:
| Level | What gets logged |
|---|---|
| ERROR | Fatal errors: auth failed, TLS handshake failed, reconnection failed |
| WARN | Recoverable problems: connection broken, transaction rolled back, dirty connection discarded |
| INFO | Normal operations: connection established/closed, query completed |
| DEBUG | Detailed info: TCP connect, auth method, pool acquire/release, connection state |
| TRACE | Wire-level detail: every protocol message, full SQL |
⚠️ TRACE may expose sensitive data. Use only in development, never in production.
Re-exports§
pub use copy::BinaryCopyWriter;pub use copy::CopyFormat;pub use copy::CopyIn;pub use copy::CopyOut;pub use error::sqlstate;pub use error::retry;pub use error::Error;pub use error::PgError;pub use error::PgServerError;pub use error::PoolErrorVariant;pub use error::Result;pub use types::FromSql;pub use types::ToSql;pub use transport::AsyncTransport;pub use transport::TransportError;pub use transport::tls::SslMode;pub use transport::tls::TlsConfig;pub use transport::tls::TlsInfo;pub use reconnect::classify_error;pub use reconnect::ErrorClass;pub use reconnect::ReconnectConfig;pub use reconnect::RetryPolicy;pub use reconnect::StaleConfig;pub use reconnect::ConnectionHealth;pub use reconnect::SessionState;pub use protocol::types::FormatCode;pub use protocol::types::TransactionStatus;pub use protocol::FrontendMessage;
Modules§
- copy
- PostgreSQL COPY protocol — bulk data import / export.
- error
- Error types for the PostgreSQL client.
- prelude
- Common imports for working with wasi-pg-client.
- protocol
- PostgreSQL wire protocol codec (I/O-free, synchronous).
- reconnect
- Automatic reconnection, retry policies, and connection resilience.
- transport
- Transport layer for PostgreSQL client.
- types
- PostgreSQL type system: ToSql/FromSql, OID mapping, encoding.
Structs§
- Cancel
Token - A token that can be used to cancel a running query on a connection.
- Command
Tag - The command tag returned by PostgreSQL for a completed command
(e.g.
"SELECT 3","INSERT 0 1","UPDATE 4"). - Config
- Configuration for a PostgreSQL connection.
- Connection
- A connection to a PostgreSQL server.
- Cursor
- A cursor for fetching a large result set in batches.
- Cursor
Stream - A streaming cursor that yields rows one at a time from a portal.
- Execute
Result - Result for statements that do not return rows (INSERT, UPDATE, DELETE, DDL).
- Field
Description - Metadata describing a single column in a query result.
- Notice
- A notice (non-fatal warning) sent by the PostgreSQL server.
- Notification
- An asynchronous notification received from PostgreSQL.
- Pipeline
- A builder for pipelined extended-query operations.
- Prepared
Statement - A server-side prepared statement.
- Query
Result - Result of a query that returns rows.
- Row
- A single row from a query result.
- RowStream
- An async stream of rows from a query result.
- Savepoint
- A savepoint within an active transaction.
- Statement
Cache - A least-recently-used (LRU) cache for prepared statements.
- Transaction
- An active transaction guard.
- Transaction
Options - Options for beginning a transaction.
- Type
- A Postgres type.
Enums§
- Backend
Message - An enum representing Postgres backend messages.
- Config
Error - Errors that can occur when building or parsing a configuration.
- Connection
State - Internal state of a PostgreSQL connection.
- Isolation
Level - Isolation level for a PostgreSQL transaction.
- Pipeline
Result - The result of a single pipeline operation.
- Target
Session Attrs - Target session attributes for connection validation.
Functions§
- ensure_
random_ available - Runtime sanity check that
getrandomis properly configured for WASI P2.
Type Aliases§
- Config
Builder - Builder type alias for
Config. - Notice
Handler - A callback that is invoked whenever the server sends a
Notice. - Oid
- A Postgres OID.