Skip to main content

Crate wasi_pg_client

Crate wasi_pg_client 

Source
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, $2 syntax
  • Prepared statements — with automatic LRU caching
  • Streaming results — O(1) memory for large queries via RowStream
  • Parameterized streamingquery_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::pool module with Mutex-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 settingset_param() with automatic re-application on reconnect
  • Structured logging — via tracing
  • Compiles to wasm32-wasip2 and native targets

§Feature Flags

FeatureDefaultDescription
tlsTLS support via rustls
scramSCRAM-SHA-256 authentication
md5-authMD5 authentication (legacy)
poolConnection pooling
tracingStructured logging via tracing
uuidUUID type support via uuid crate
serde-jsonJSON type support via serde_json
chronochrono integration for date/time
test-nativeNative transport for testing
tokio-transportTokio 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.wasm

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

LevelWhat gets logged
ERRORFatal errors: auth failed, TLS handshake failed, reconnection failed
WARNRecoverable problems: connection broken, transaction rolled back, dirty connection discarded
INFONormal operations: connection established/closed, query completed
DEBUGDetailed info: TCP connect, auth method, pool acquire/release, connection state
TRACEWire-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§

CancelToken
A token that can be used to cancel a running query on a connection.
CommandTag
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.
CursorStream
A streaming cursor that yields rows one at a time from a portal.
ExecuteResult
Result for statements that do not return rows (INSERT, UPDATE, DELETE, DDL).
FieldDescription
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.
PreparedStatement
A server-side prepared statement.
QueryResult
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.
StatementCache
A least-recently-used (LRU) cache for prepared statements.
Transaction
An active transaction guard.
TransactionOptions
Options for beginning a transaction.
Type
A Postgres type.

Enums§

BackendMessage
An enum representing Postgres backend messages.
ConfigError
Errors that can occur when building or parsing a configuration.
ConnectionState
Internal state of a PostgreSQL connection.
IsolationLevel
Isolation level for a PostgreSQL transaction.
PipelineResult
The result of a single pipeline operation.
TargetSessionAttrs
Target session attributes for connection validation.

Functions§

ensure_random_available
Runtime sanity check that getrandom is properly configured for WASI P2.

Type Aliases§

ConfigBuilder
Builder type alias for Config.
NoticeHandler
A callback that is invoked whenever the server sends a Notice.
Oid
A Postgres OID.