odbc_fast library
Enterprise-grade ODBC data platform for Dart with a Rust native engine.
This library provides a high-performance ODBC interface with:
- Clean Architecture design
- Native Rust engine for performance
- Connection pooling
- Streaming queries
- Async API for non-blocking operations
- Automatic reconnect on connection-lost (configurable attempts/backoff)
- Savepoints (nested transactions)
Quick Start
import 'package:odbc_fast/core/di/service_locator.dart';
import 'package:odbc_fast/odbc_fast.dart';
void main() async {
final locator = ServiceLocator()..initialize();
final service = locator.syncService;
await service.initialize();
final connResult = await service.connect('MyDSN');
await connResult.fold((connection) async {
await service.executeQuery(
'SELECT * FROM users',
connectionId: connection.id,
);
await service.disconnect(connection.id);
}, (error) {
print('Error: $error');
});
locator.shutdown();
}
Async API (Recommended for Flutter)
For non-blocking operations, use the async API:
final locator = ServiceLocator();
locator.initialize(useAsync: true);
final asyncService = locator.asyncService;
await asyncService.initialize();
final connResult = await asyncService.connect('MyDSN');
// ... use asyncService for all operations
locator.shutdown(); // Call on app exit
See README.md for more details.
Classes
- AppLogger
- Centralized logger for ODBC Fast
- AsyncNativeOdbcConnection
- Non-blocking wrapper around ODBC using a long-lived worker isolate.
- BulkColumnSpec
- Specification for a column in a bulk insert operation.
- BulkInsertBuilder
- Builder for creating bulk insert data buffers.
- BulkTimestamp
- Represents a timestamp value for bulk insert operations.
- CatalogQuery
- Wrapper for database catalog queries.
- Connection
- Represents an active ODBC database connection.
- ConnectionOptions
- Options for connection establishment and statement execution.
- ConnectionPool
- Wrapper for connection pool operations.
- ConnectionStringBuilder
- Fluent builder for ODBC connection strings.
- DatabaseEngineIds
-
Canonical engine identifier returned by the Rust layer
(
engine::core::ENGINE_*). Stable across releases. - Db2Builder
- Builder preconfigured for IBM Db2 (NEW v3.0).
- DbmsInfo
-
Live DBMS introspection (NEW in v2.1). Populated by
odbc_get_connection_dbms_infoonce the connection is open. - DirectedMultiItem
- One item from a multi-result directed response.
- DirectedParam
-
A parameter with an explicit ParamDirection for API surfaces that
prepare the contract for
OUTPUT/INOUT(native engine support is still being rolled in — seedoc/notes/TYPE_MAPPING.md§3.1). - DirectedResultItem
- A result-set item (cursor) from a directed multi-result response.
- DirectedRowCountItem
- A row-count item (DML) from a directed multi-result response.
- DriverCapabilities
- Typed driver capabilities parsed from native JSON payload.
- ForeignKeyInfo
- Metadata for a foreign key reference.
- IndexInfo
- Metadata for an index column.
- IOdbcRepository
- Repository interface for ODBC database operations.
- IOdbcService
- Interface for ODBC service operations.
- ITelemetryRepository
- Repository interface for telemetry operations.
- ITelemetryService
- Simplified interface for telemetry service operations.
- MariaDbBuilder
- Builder preconfigured for MariaDB (NEW v3.0).
- Metric
- Represents a metric value collected during operations.
- MySqlBuilder
- Builder preconfigured for MySQL.
- NamedParameterParser
- Parser and extractor for named parameters in SQL.
- NativeOdbcConnection
- Native ODBC connection implementation using FFI bindings.
- OdbcConnectionBackend
- Backend interface for low-level ODBC operations.
- OdbcDriverCapabilities
- Typed wrapper for native driver capabilities FFI.
- OdbcDriverFeatures
- Typed wrapper for the v3.0 capability FFIs.
- OdbcMetrics
- Performance and operational metrics for the ODBC engine.
- OdbcPoolFactory
- Typed wrapper for the v3.0 pool-creation FFI with options support.
- OdbcRepositoryImpl
- Implementation of IOdbcRepository using native ODBC connection.
- OdbcService
- High-level ODBC service that provides simplified API for database operations.
- OdbcTelemetryAttributes
- Attributes for ODBC-specific telemetry.
- OpenTelemetryFFI
- OpenTelemetry FFI wrapper backed by the native ODBC engine library.
- ParamValue
- Base class for parameter values in prepared statements.
- ParamValueBinary
- Represents a binary parameter value.
- ParamValueDecimal
- Represents a decimal/numeric parameter value as a string.
- ParamValueInt32
- Represents a 32-bit integer parameter value.
- ParamValueInt64
- Represents a 64-bit integer parameter value.
- ParamValueNull
- Represents a NULL parameter value.
- ParamValueRefCursorOut
-
Placeholder for Oracle
SYS_REFCURSOR(and similar)OUTparameters on the DRT1 wire. Payload length is always zero; materialized row sets use the nativeRC1\0trailer. Engine bind is not yet available for all drivers (seeTYPE_MAPPING§3.1.1). - ParamValueString
- Represents a string parameter value.
- PoolOptions
-
Optional eviction/timeout knobs for a connection pool created via
odbc_pool_create_with_options(NEW v3.0). - PoolState
- Current state of a connection pool.
- PostgreSqlBuilder
- Builder preconfigured for PostgreSQL.
- PreparedStatement
- Wrapper for prepared statement operations.
- PreparedStatementConfig
- Configuration for prepared statement cache.
- PreparedStatementMetrics
- Metrics for prepared statement cache.
- PrimaryKeyInfo
- Metadata for a primary key column.
- QueryResult
- Represents the result of a SQL query execution.
- QueryResultMulti
- Represents a full multi-result response preserving item order.
- QueryResultMultiItem
- One item in a multi-result response.
- RetryHelper
- Helper for retrying operations with exponential backoff.
- RetryOptions
- Configuration for automatic retry with exponential backoff.
- ServiceLocator
- Dependency injection container for ODBC Fast services.
- SessionOptions
-
Per-driver session initialization options. Mirror of the Rust
SessionOptionsstruct — every field is optional;null/empty means "do not touch this setting". - SimpleTelemetryService
- Simplified telemetry service for ODBC operations.
- SnowflakeBuilder
- Builder preconfigured for Snowflake (NEW v3.0).
- Span
- Represents a telemetry span - a segment of work with timing.
- SqlDataType
- Explicit SQL data types for optional typed parameter API.
- SqliteBuilder
- Builder preconfigured for SQLite (NEW v3.0).
- SqlServerBuilder
- Builder preconfigured for SQL Server.
- SqlTypedValue
- Explicitly typed parameter value.
- StatementOptions
- Options for a single prepared statement execution.
- TelemetryBatch
- Represents a batch of telemetry data to be exported.
- TelemetryBuffer
- In-memory buffer for batching telemetry data before export.
- TelemetryEvent
- Telemetry event for logging significant occurrences.
- TelemetryFailureRecord
- Record of a telemetry export failure for fallback tracking.
- TelemetryRepositoryImpl
- Implementation of ITelemetryRepository using OpenTelemetry FFI with buffering.
- Trace
- Represents a telemetry trace for a single operation.
- TransactionHandle
- Convenience wrapper around an active transaction.
- XaTransactionHandle
- Lightweight Dart wrapper around a native XA transaction id.
- Xid
- X/Open XA global transaction identifier.
Enums
- AsyncErrorCode
- Error codes for async operations that cross isolate boundaries.
- BulkColumnType
- Column data types for bulk insert operations.
- DatabaseType
- Logical database family. Use DatabaseType.fromEngineId when you have a canonical engine id from the native layer (preferred); fall back to DatabaseType.fromDriverName only for legacy callers that only have the raw driver name.
- DmlVerb
- DML category used by OdbcDriverFeatures.appendReturningClause to position the dialect-specific OUTPUT/RETURNING clause.
- ErrorCategory
- Error category for decision-making (retry, abort, reconnect, etc.)
- IsolationLevel
- Transaction isolation levels for database transactions.
- ParamDirection
-
Declares how a parameter is bound to a statement. Used by
DirectedParamfor API contracts that will align with future native OUTPUT /INOUT/REF CURSORwork (seedoc/notes/TYPE_MAPPING.md). - SavepointDialect
-
SQL dialect used to emit
SAVEPOINTstatements within a transaction. - TelemetrySeverity
- Severity levels for telemetry events.
- TransactionAccessMode
- Whether a transaction is allowed to mutate state.
- XaState
-
Lifecycle states of an XA transaction branch — mirror of
engine::xa_transaction::XaState(Rust).
Constants
- columnarV2Magic → const int
-
Wire constants for the columnar v2 result layout (row-major v1 remains
default). Emitter/parser integration is not wired; see
doc/notes/columnar_protocol_sketch.mdand the Rustcolumnar-v2feature. - defaultInitialResultBufferBytes → const int
- Default initial result buffer size in bytes (64 KB) when not set per connection.
- defaultMaxReconnectAttempts → const int
- Default maximum number of reconnect attempts when ConnectionOptions.autoReconnectOnConnectionLost is true.
- defaultMaxResultBufferBytes → const int
- Default maximum result buffer size in bytes (16 MB).
- defaultReconnectBackoff → const Duration
- Default delay between reconnect attempts when ConnectionOptions.autoReconnectOnConnectionLost is true.
-
drt1MagicBytes
→ const List<
int> -
Little-endian DRT1 magic (Rust:
odbc_enginecratebound_parammodule). - kDirectedParamErrorPrefix → const String
-
Stable error prefix, aligned with
output_aware_params/ nativeValidationError(TYPE_MAPPING §3.1).
Functions
-
deserializeParamValue(
Uint8List data, {int offset = 0}) → ({int consumed, ParamValue value}) -
Deserialises a single ParamValue from
datastarting atoffset(mirrorsParamValue::deserializein the Rust engine). Returns the value and the number of bytes consumed. -
deserializeParamValues(
Uint8List data) → List< ParamValue> - Deserialises every ParamValue in a legacy buffer (concatenated encodings, no DRT1 header).
-
isLikelyColumnarV2Header(
Uint8List data) → bool -
Returns whether
datais long enough to carry the sketch header and starts with the v2 magic (little-endian). -
paramValuesFromDirected(
List< DirectedParam> params) → List<ParamValue> -
Converts DirectedParam rows to a legacy v0 binary ParamValue list
(concatenated tags, all treated as
INPUTon the wire). -
paramValuesFromObjects(
List< Object?> params) → List<ParamValue> -
Converts a list of objects to
ParamValueinstances. -
serializeDirectedParams(
List< DirectedParam> params) → Uint8List -
Serialises DirectedParam values to a DRT1 buffer:
DRT1+ u32 count and repeated(u8 direction)(ParamValue wire). PreferIOdbcService.executeQueryDirectedParamsorIOdbcRepository.executeQueryParamBufferwith this buffer. Engine mapping: ParamDirectioninput= 0,output= 1,inOut= 2. -
serializeParams(
List< ParamValue> params) → Uint8List - Serializes a list of parameter values to binary format.
-
toParamValue(
Object? value) → ParamValue -
Converts a single object to a
ParamValueinstance. -
typedParam(
SqlDataType type, Object? value) → SqlTypedValue - Convenience helper to create SqlTypedValue instances.
-
validateDirectedOutInOut(
ParamDirection direction, ParamValue pv) → void -
Client-side checks for DRT1
OUT/INOUTthat the native engine will reject; fails fast with the same slugs asoutput_aware_params.rs.
Exceptions / Errors
- AsyncError
- Sendable error type that can cross isolate boundaries.
- BulkPartialFailureError
- Bulk insert split into chunks failed mid-way.
- CancelledError
- Operation cancelled by the caller (cooperative cancellation). Distinct from a driver error: the request was successfully aborted.
- ConnectionError
- Error during database connection establishment or maintenance.
- EnvironmentNotInitializedError
- Error indicating the ODBC environment was not properly initialized.
- MalformedPayloadError
- Wire-format payload is malformed (truncated, length mismatch, invalid tag). Always indicates a protocol bug in the caller — NOT retryable.
- NoMoreResultsError
-
SQLMoreResultsreports there are no further result sets. Informational: producers may stop iterating without treating it as failure. - OdbcError
- Base class for all ODBC-related errors.
- ParameterMissingException
- Thrown when named parameters are provided incomplete.
- QueryError
- Error during SQL query execution.
- ResourceLimitReachedError
- Resource limit reached (too many handles, payload too large, queue full). Generally NOT retryable without backoff.
- RollbackFailedError
- Rollback failed during cleanup. Carries the original failure so callers can decide between retry and connection destruction.
- TelemetryBufferException
- Error when telemetry buffer operations fail.
- TelemetryException
- Base exception for all telemetry errors.
- TelemetryExportException
- Error when telemetry export fails.
- TelemetryInitializationException
- Error when telemetry initialization fails.
- TelemetryShutdownException
- Error when telemetry shutdown fails.
- UnsupportedFeatureError
- Error indicating requested capability is not supported by current runtime.
- ValidationError
- Error indicating invalid input or parameters.
- WorkerCrashedError
- A worker thread (streaming/async pipeline) crashed or disconnected without sending end-of-stream. Indicates a serious internal failure.