Skip to main content

Crate oracledb

Crate oracledb 

Source
Expand description

A pure-Rust, thin-mode driver for Oracle Database.

oracledb speaks the Oracle TNS/TTC wire protocol directly over TCP. It needs no Oracle Instant Client, no OCI libraries, and no C toolchain: add the crate, point it at a listener, and connect. The driver is a faithful port of the python-oracledb thin client, so its behavior tracks that reference implementation.

§Why thin mode

A traditional OCI-based client links a large native library and inherits whatever identity the OS hands it. Because this driver builds every packet itself, the application controls the full connection envelope, including the session identity the database records.

§Caller-set identity (the differentiator)

Every connection carries a ClientIdentity the caller supplies: program, machine, osuser, and terminal. The database stores those exact values in v$session. An OCI client reports the host process and OS user it happens to run as; here the application decides. This is invaluable for multi-tenant services and connection multiplexers that need each logical user attributed correctly in the DBA’s session views, audit trail, and resource-manager rules.

use oracledb::{BlockingConnection, ConnectOptions};
use oracledb::protocol::ClientIdentity;

// The identity the database will record for this session.
let identity = ClientIdentity::new(
    "billing-worker", // program
    "edge-pod-7",     // machine
    "tenant-42",      // osuser
    "shard-a",        // terminal
    "rust-oracledb",  // driver name
)?;

let options = ConnectOptions::new(
    "dbhost:1521/FREEPDB1", // EasyConnect string
    "app_user",
    "app_password",
    identity,
);

let mut conn = BlockingConnection::connect(options)?;

// Bind parameters positionally (:1, :2, ...) as a tuple.
let row = BlockingConnection::query_one(
    &mut conn,
    "select :1 + :2 from dual",
    (40, 2),
)?;

// Typed column access converts the Oracle NUMBER straight into an integer.
let sum: i64 = row.get(0)?;
assert_eq!(sum, 42);

BlockingConnection::close(conn)?;

§Choosing an API surface

Two equivalent surfaces are exposed:

  • BlockingConnection runs each operation on a private single-threaded runtime and blocks the calling thread. Use it from synchronous code; it is the simplest way to use the driver as a library.
  • Connection is the native asynchronous API. Every method takes an &Cx (the Asupersync request context) so the work participates in structured concurrency and cancellation. Use it inside an Asupersync runtime.

BlockingConnection is a thin shim over Connection: it owns a Connection and drives the async methods to completion.

§Working with values

Fetched cells are QueryValue, a sum type over every Oracle scalar (NUMBER carried as lossless text, VARCHAR2, DATE / TIMESTAMP, RAW, ROWID, BOOLEAN, BINARY_DOUBLE, VECTOR, JSON, LOB locators, object images, …). Convenience accessors (as_i64, as_text, as_f64, and friends) and QueryResult::cell cover the common cases without an explicit match.

Columns that stream their value through a client-side define (CLOB, BLOB, VECTOR, native JSON) come back from a plain Connection::execute_raw as describe-only metadata with a None cell, matching the wire protocol. Use Connection::define_and_fetch_rows_with_columns after opening the cursor when you need the first batch materialized explicitly.

§Optional features

  • arrow: fetch result sets directly into Apache Arrow RecordBatches via Connection::fetch_all_record_batch and Connection::fetch_record_batches.

§Connection pooling

The pool module provides async Pool and BlockingPool facades that mirror python-oracledb’s thin pool: free/busy lists, growth planning, getmode semantics, ping policy, idle timeout, and max lifetime. The pool is generic over a PoolBackend so the embedder supplies how a pooled connection is created, pinged, and closed.

Re-exports§

pub use oracledb_protocol as protocol;

Modules§

pool
Connection pool engine mirroring python-oracledb’s thin pool algebra (impl/thin/pool.pyx). The engine owns the pool state machine (free lists, busy list, growth planning, getmode semantics, ping policy, idle timeout, max lifetime) and a background worker thread that creates, pings and closes connections through a PoolBackend.
prelude
The everyday types and traits, for a single glob import.
retry
Idempotency-gated retry executor over the ORA error taxonomy (bead a4-r9a). Retry executor over the ORA error taxonomy, gated by operation idempotency.
transport
Connection transport: a plain TCP socket or a TLS (TCPS) stream, presented to the rest of the driver as AsyncRead/AsyncWrite read and write halves.

Macros§

obs_record
Off-build: a no-op; the value expression is not evaluated, the guard is ().
obs_span
Off-build: a zero-sized no-op guard; the field token-tree is discarded entirely, so none of the field expressions are evaluated and tracing is never named. A unit struct (not ()) so a let _span = obs_span!(…); binding does not trip the clippy::let_unit_value / unused_unit lints.
obs_warn
Off-build: a no-op; argument expressions are not evaluated and tracing is never named.
params
Build a positional bind list from a heterogeneous set of ToSql values.

Structs§

AccessToken
A database access token used in place of a password — an OCI IAM database token or an OAuth2 token. Its Debug output is redacted so the secret never leaks into logs, error messages, or panic output. Set it with ConnectOptions::with_access_token.
AuthCapabilities
Queryable authentication capability metadata for this build.
Batch
Execute-many builder for array DML.
BatchError
One row-level error collected by Batch::collect_errors.
BatchOutcome
Result of an execute_many operation.
BlockingConnection
Synchronous facade over Connection.
BlockingRows
Blocking lazy result-set facade returned by BlockingConnection::query and BlockingConnection::query_with.
CancelHandle
ClobReader
A lazy CLOB/NCLOB reader that decodes streamed character data. Chunk boundaries that split a multi-byte codepoint or a UTF-16 surrogate pair are stitched across reads, so the concatenated text is identical to a whole decode.
CollectionElement
Element type metadata for an Oracle collection type (VARRAY / nested table), from ALL_COLL_TYPES.
ColumnShape
A fingerprint of a query’s described result-column shape: the decode-relevant fields of every column, in select-list order. Equality means “decodes the same”; inequality means the server’s shape changed (typically a concurrent DDL) and any cached decode plan for that SQL is stale.
ConnectOptions
Everything needed to open a connection: where to connect, who to authenticate as, and the ClientIdentity the database will record.
Connection
A live asynchronous connection to an Oracle Database session.
DbmsOutput
Captured DBMS_OUTPUT, bounded by the caller’s line/char limits. Returned by Connection::read_dbms_output.
DecodedObject
A decoded Oracle ADT value. For an object type the scalar attributes are in attributes; for a collection type the elements are in elements. Each value is decoded with the same rules as a normal column. Returned by decode_object.
Execute
Execute builder for DML, DDL, and PL/SQL operations that use at most one bind row.
ExecuteOutcome
Result of an Execute operation.
ExecutemanyManager
Drives the per-batch row windowing of an executemany call: how many rows each server round trip carries and where in the bound-row buffer it starts.
LobReader
A lazy reader over a LOB locator. Pulls the LOB in chunk-unit batches on demand, tracking a 1-based cursor. Units are bytes for BLOB and characters for CLOB/NCLOB (Oracle LOB semantics).
LobWriter
A byte-oriented lazy writer over a (typically temporary) BLOB locator. Each write_chunk appends at the running byte cursor.
ObjectAttribute
A scalar attribute of an Oracle ADT/object type (from the data dictionary).
ObjectType
Metadata for an Oracle ADT/object type, fetched from the data dictionary by Connection::describe_object_type. A type is either an object (carrying attributes) or a collection (carrying collection_element).
OutBinds
OUT and IN/OUT bind values returned by Connection::execute.
OwnedRowStream
A Stream of owned query rows that owns its Connection and returns it when drained. Constructed with Connection::into_row_stream / Connection::into_query_stream.
Query
Query builder for the high-level row API.
Registration
Registered-query builder for Continuous Query Notification (CQN).
RegistrationOutcome
Result of a register_query operation.
ReturningRows
Per-bind rows returned by DML RETURNING INTO.
RoutineCall
A driver-native call to a PL/SQL stored procedure or function (GH#13).
RoutineOutcome
The OUT and function-RETURN values produced by a RoutineCall.
Row
One owned query row.
Rows
Lazy result-set facade returned by Connection::query and Connection::query_with.
ShapeObservation
Outcome of observing a freshly-described shape for a SQL statement.
StatementShapeCache
A cross-connection cache of statement result-column shapes, keyed by normalized SQL text, with DDL-invalidation self-heal. Share one instance across connections via crate::ConnectOptions::with_shared_statement_shape_cache.
TokenPrivateKey
The RSA private key (PKCS#8 PEM) an OCI IAM database token is bound to, used to sign the proof-of-possession header. Like AccessToken its Debug is redacted so the key never leaks into logs, errors, or panics. Set it with ConnectOptions::with_access_token_and_key or ConnectOptions::with_token_source_and_key.
TypedRow
A borrowed view of one row of a QueryResult that converts cells to typed Rust values. Obtain it with QueryResultExt::typed_row.
UnsupportedAuthMode
Structured unsupported-authentication diagnostic.
WalletResolution
The outcome of wallet-file precedence resolution in a wallet directory.

Enums§

AuthMode
A known authentication mode selected by the caller.
AuthModeKind
Stable classifier for the thin driver’s authentication modes.
AuthModeSupport
Whether a known authentication mode is implemented by this thin driver.
BatchRows
Bind rows for Connection::execute_many. Each inner Vec<BindValue> is one execution of the statement.
BindError
Why a bind payload could not be matched to a SQL statement before the wire round trip.
ConnectionDisposition
Whether the connection that produced an error can be reused.
ConversionError
Why a typed FromSql conversion could not be performed.
Error
ErrorKind
Stable top-level error bucket for Error::kind.
ExecutemanyManagerError
Error returned when constructing an ExecutemanyManager with invalid inputs. The two variants mirror the two distinct failure modes the reference batch-load manager rejects, so a Python adapter can raise the matching exception type (TypeError for a zero batch size, RuntimeError for a row count that overflows the wire’s 32-bit field).
NotificationOutcome
Outcome of Connection::recv_notification.
OutType
The Oracle type an OUT (or function-RETURN) placeholder expects, so the driver registers the bind with the right wire metadata before the call.
Params
Single-row bind payload for the operation-family APIs.
PipelineRequest
One operation in a pipelined batch (Connection::run_pipeline).
RetryHint
Conservative retry guidance for caller-proven idempotent operations.
Scroll
Scroll target for Rows::scroll.
SessionlessError
Client-API misuse of the sessionless transaction API, mirroring the reference ERR_SESSIONLESS_* errors (impl/oracledb/errors.py:338-340).
TokenSourceError
Failure classes a TokenSource may report.
WalletFile
Which wallet file in a wallet directory supplied the resolved TLS identity.

Constants§

VERSION
The version of this driver crate, supplied by Cargo at build time.

Traits§

ColumnIndex
Resolve an owned Row column by index or by case-insensitive column name.
FromRow
Map a fetched query row into a concrete Rust struct, with compile-time checked field types.
FromSql
Convert a fetched Oracle QueryValue into a concrete Rust type.
IntoBinds
A source of positional binds (:1, :2, …) for the ergonomic execute helpers. Implemented for tuples up to arity 12, for [T] / Vec<T> of a single ToSql type, and for Vec<BindValue> (the raw form).
QueryResultExt
Typed accessors layered onto QueryResult so callers can pull a cell out as a concrete Rust type by index or by column name.
ToSql
Convert a Rust value into an Oracle BindValue for a placeholder bind.
TokenSource
A pluggable source of OCI IAM / OAuth2 database access tokens.

Functions§

bind_rows_need_iterative_plsql
Whether an executemany over bind_rows must be driven one row at a time (iterative) rather than as a single batched array execute.
check_bind_rows
Pre-flight execute-many bind rows without a database round trip: the structural shape (rectangular rows — BindError::BatchRowWidthMismatch) and first-execute per-column type consistency (BindError::BatchColumnTypeMismatch). This mirrors the validation crate::Connection::execute_many performs at execute time.
check_positional_binds
Pre-flight the positional bind COUNT for statement against the number of values a caller intends to supply, with no database round trip. Returns BindError::PositionalCountMismatch when they differ. This is precisely the check crate::Connection::execute runs for positional binds, hoisted so it can be run early (e.g. in a test or before building the bind vector). DDL, which the driver never bind-count-validates, always passes.
declared_bind_count
The number of positional bind values a statement declares, counted with the driver’s real SQL tokenizer — placeholders inside string/quoted literals, --//* */ comments and q'…' quoted strings are ignored, and a repeated placeholder in plain SQL counts once per occurrence (PL/SQL coalesces duplicates), exactly as execution binds them.
decode_object
Decode a returned Oracle ADT object value (the payload of a QueryValue::Object) into its scalar attributes, using the type metadata from Connection::describe_object_type. Bounded by the object image length, so a malformed/huge image cannot cause unbounded work.
fetch_profile_arm
Profiling-only: arm or disarm fetch read/decode attribution for this process without setting an environment variable.
fetch_profile_read_decode_ns
Profiling-only: snapshot the cumulative (read_ns, decode_ns) split that the fetch paging loop has accumulated since the last fetch_profile_reset.
fetch_profile_reset
Profiling-only: zero the fetch read/decode attribution counters.
parse_user_and_proxy
Parse a username that may use the reference bracket form.
render_caret
Render a compiler-style caret diagnostic: the line of sql containing the 1-based character offset (the position Oracle reports for a parse error), with a ^ under that character, beneath headline.
resolve_wallet
Resolve which wallet file in dir wins the precedence chain and report the WalletResolution outcome, without exposing the parsed key material.

Type Aliases§

BoxFuture
A boxed, Send future — the return type of TokenSource::get_token.
Cursor
A REF CURSOR handle returned in a row or implicit result set.
Result

Derive Macros§

FromRow
Derive a FromRow implementation that maps a query row into a struct with compile-time-checked field types.