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:
BlockingConnectionruns 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.Connectionis 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 ArrowRecordBatches viaConnection::fetch_all_record_batchandConnection::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 aPoolBackend. - 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/AsyncWriteread 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
tracingis never named. A unit struct (not()) so alet _span = obs_span!(…);binding does not trip theclippy::let_unit_value/unused_unitlints. - obs_
warn - Off-build: a no-op; argument expressions are not evaluated and
tracingis never named. - params
- Build a positional bind list from a heterogeneous set of
ToSqlvalues.
Structs§
- Access
Token - A database access token used in place of a password — an OCI IAM database
token or an OAuth2 token. Its
Debugoutput is redacted so the secret never leaks into logs, error messages, or panic output. Set it withConnectOptions::with_access_token. - Auth
Capabilities - Queryable authentication capability metadata for this build.
- Batch
- Execute-many builder for array DML.
- Batch
Error - One row-level error collected by
Batch::collect_errors. - Batch
Outcome - Result of an
execute_manyoperation. - Blocking
Connection - Synchronous facade over
Connection. - Blocking
Rows - Blocking lazy result-set facade returned by
BlockingConnection::queryandBlockingConnection::query_with. - Cancel
Handle - Clob
Reader - 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.
- Collection
Element - Element type metadata for an Oracle collection type (VARRAY / nested table),
from
ALL_COLL_TYPES. - Column
Shape - 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.
- Connect
Options - Everything needed to open a connection: where to connect, who to
authenticate as, and the
ClientIdentitythe database will record. - Connection
- A live asynchronous connection to an Oracle Database session.
- Dbms
Output - Captured
DBMS_OUTPUT, bounded by the caller’s line/char limits. Returned byConnection::read_dbms_output. - Decoded
Object - A decoded Oracle ADT value. For an object type the scalar attributes are in
attributes; for a collection type the elements are inelements. Each value is decoded with the same rules as a normal column. Returned bydecode_object. - Execute
- Execute builder for DML, DDL, and PL/SQL operations that use at most one bind row.
- Execute
Outcome - Result of an
Executeoperation. - Executemany
Manager - Drives the per-batch row windowing of an
executemanycall: 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_chunkappends at the running byte cursor. - Object
Attribute - A scalar attribute of an Oracle ADT/object type (from the data dictionary).
- Object
Type - Metadata for an Oracle ADT/object type, fetched from the data dictionary by
Connection::describe_object_type. A type is either an object (carryingattributes) or a collection (carryingcollection_element). - OutBinds
- OUT and IN/OUT bind values returned by
Connection::execute. - Owned
RowStream - A
Streamof owned query rows that owns itsConnectionand returns it when drained. Constructed withConnection::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).
- Registration
Outcome - Result of a
register_queryoperation. - Returning
Rows - Per-bind rows returned by DML
RETURNING INTO. - Routine
Call - A driver-native call to a PL/SQL stored procedure or function (GH#13).
- Routine
Outcome - The OUT and function-RETURN values produced by a
RoutineCall. - Row
- One owned query row.
- Rows
- Lazy result-set facade returned by
Connection::queryandConnection::query_with. - Shape
Observation - Outcome of observing a freshly-described shape for a SQL statement.
- Statement
Shape Cache - 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. - Token
Private Key - The RSA private key (PKCS#8 PEM) an OCI IAM database token is bound to, used
to sign the proof-of-possession header. Like
AccessTokenitsDebugis redacted so the key never leaks into logs, errors, or panics. Set it withConnectOptions::with_access_token_and_keyorConnectOptions::with_token_source_and_key. - Typed
Row - A borrowed view of one row of a
QueryResultthat converts cells to typed Rust values. Obtain it withQueryResultExt::typed_row. - Unsupported
Auth Mode - Structured unsupported-authentication diagnostic.
- Wallet
Resolution - The outcome of wallet-file precedence resolution in a wallet directory.
Enums§
- Auth
Mode - A known authentication mode selected by the caller.
- Auth
Mode Kind - Stable classifier for the thin driver’s authentication modes.
- Auth
Mode Support - Whether a known authentication mode is implemented by this thin driver.
- Batch
Rows - Bind rows for
Connection::execute_many. Each innerVec<BindValue>is one execution of the statement. - Bind
Error - Why a bind payload could not be matched to a SQL statement before the wire round trip.
- Connection
Disposition - Whether the connection that produced an error can be reused.
- Conversion
Error - Why a typed
FromSqlconversion could not be performed. - Error
- Error
Kind - Stable top-level error bucket for
Error::kind. - Executemany
Manager Error - Error returned when constructing an
ExecutemanyManagerwith 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 (TypeErrorfor a zero batch size,RuntimeErrorfor a row count that overflows the wire’s 32-bit field). - Notification
Outcome - 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.
- Pipeline
Request - One operation in a pipelined batch (
Connection::run_pipeline). - Retry
Hint - Conservative retry guidance for caller-proven idempotent operations.
- Scroll
- Scroll target for
Rows::scroll. - Sessionless
Error - Client-API misuse of the sessionless transaction API, mirroring the
reference
ERR_SESSIONLESS_*errors (impl/oracledb/errors.py:338-340). - Token
Source Error - Failure classes a
TokenSourcemay report. - Wallet
File - 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§
- Column
Index - Resolve an owned
Rowcolumn 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
QueryValueinto a concrete Rust type. - Into
Binds - 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 singleToSqltype, and forVec<BindValue>(the raw form). - Query
Result Ext - Typed accessors layered onto
QueryResultso 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
BindValuefor a placeholder bind. - Token
Source - A pluggable source of OCI IAM / OAuth2 database access tokens.
Functions§
- bind_
rows_ need_ iterative_ plsql - Whether an
executemanyoverbind_rowsmust 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 validationcrate::Connection::execute_manyperforms at execute time. - check_
positional_ binds - Pre-flight the positional bind COUNT for
statementagainst the number of values a caller intends to supply, with no database round trip. ReturnsBindError::PositionalCountMismatchwhen they differ. This is precisely the checkcrate::Connection::executeruns 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
statementdeclares, counted with the driver’s real SQL tokenizer — placeholders inside string/quoted literals,--//* */comments andq'…'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 fromConnection::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 lastfetch_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
sqlcontaining the 1-based characteroffset(the position Oracle reports for a parse error), with a^under that character, beneathheadline. - resolve_
wallet - Resolve which wallet file in
dirwins the precedence chain and report theWalletResolutionoutcome, without exposing the parsed key material.
Type Aliases§
- BoxFuture
- A boxed,
Sendfuture — the return type ofTokenSource::get_token. - Cursor
- A REF CURSOR handle returned in a row or implicit result set.
- Result