OrmConnection class
Represents a fully materialized ORM connection that exposes helpers, metadata, and instrumentation hooks.
Observability
OrmConnection provides a unified observability system inspired by Laravel's Connection class. The primary method for observing database operations is listen, which receives QueryExecuted events after every query.
// Register a query listener (like Laravel's listen)
connection.listen((event) {
print('Query: ${event.sql} took ${event.time}ms');
});
// Listen for specific event types
connection.onEvent<TransactionBeginning>((event) {
print('Transaction started');
});
connection.onEvent<TransactionCommitted>((event) {
print('Transaction committed');
});
Query Logging
Built-in query logging accumulates QueryLogEntry objects for debugging:
connection.enableQueryLog();
// ... execute queries ...
for (final entry in connection.queryLog) {
print('${entry.sql} (${entry.duration.inMilliseconds}ms)');
}
connection.flushQueryLog(); // Clear entries
Duration Handlers
Monitor cumulative query time with whenQueryingForLongerThan:
connection.whenQueryingForLongerThan(
Duration(seconds: 2),
(connection, event) {
logger.warning('Slow queries detected: ${connection.totalQueryDuration}ms total');
},
);
- Implemented types
Constructors
- OrmConnection({required ConnectionConfig config, required DriverAdapter driver, required ModelRegistry registry, ValueCodecRegistry? codecRegistry, ScopeRegistry? scopeRegistry, QueryContext? context})
Properties
- codecRegistry → ValueCodecRegistry
-
Codec registry scoped to the current connection.
no setteroverride
- config → ConnectionConfig
-
Configuration describing the logical connection.
final
- context → QueryContext
-
Underlying QueryContext for advanced operations.
no setter
- database → String?
-
Optional database/catalog identifier.
no setter
- driver → DriverAdapter
-
Database adapter backing this resolver.
no setteroverride
- hashCode → int
-
The hash code for this object.
no setterinherited
- loggingQueries → bool
-
Whether query logging is enabled.
no setter
- name → String
-
Connection name convenience accessor.
no setter
-
options
→ Map<
String, Object?> -
no setter
- pretending → bool
-
Current pretend-mode flag.
no setter
-
queryLog
→ List<
QueryLogEntry> -
Immutable view of recorded query log entries.
no setter
- registry → ModelRegistry
-
Registry of model definitions available to this resolver.
no setteroverride
- role → ConnectionRole
-
no setter
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- tablePrefix → String
-
Table prefix metadata.
no setter
Methods
-
allowQueryDurationHandlersToRunAgain(
) → void - Allows duration handlers registered via whenQueryingForLongerThan to run again.
-
attachDefaultContextualLogger(
{Logger? logger, String? logFilePath}) → void - Attaches the default contextual logger for query events.
-
beforeExecuting(
ExecutingStatementCallback callback) → void Function() - Registers a callback invoked before any SQL is dispatched.
-
describeMutation(
MutationPlan plan) → StatementPreview -
Provides the statement preview for a write
plan.override -
describeQuery(
QueryPlan plan) → StatementPreview -
Provides the statement preview for a read
plan.override -
disableQueryLog(
{bool clear = false}) → void - Disables query logging and optionally clears existing entries.
-
enableQueryLog(
{bool includeParameters = true, bool clear = true}) → void - Enables query logging for this connection.
-
ensureLedgerInitialized(
{String? tableName}) → Future< void> - Ensures the migrations ledger table exists for this connection.
-
ensureSchemaReady(
{required MigrationRunner runner, bool applyPendingMigrations = true}) → Future< MigrationReport> -
Ensures pending migrations are applied using
runner. -
flushQueryLog(
) → void - Clears all accumulated query log entries.
-
listen(
void callback(QueryExecuted event)) → void Function() - Registers a listener for QueryExecuted events (like Laravel's listen).
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
onEvent<
T extends ConnectionEvent> (void callback(T event)) → void Function() - Registers a listener for specific connection event types.
-
pretend(
FutureOr< void> action()) → Future<List< QueryLogEntry> > -
Runs
actionwith pretend mode enabled and returns the captured SQL. -
query<
T extends OrmEntity> () → Query< T> - Creates a typed query builder.
-
queryAs<
T extends OrmEntity> ({String? table, String? schema, String? alias}) → Query< T> -
Builds a query for
Tusing an alternate table/schema/alias. -
queryFromDefinition<
T extends OrmEntity> (ModelDefinition< T> definition, {String? table, String? schema, String? alias}) → Query<T> - Queries using a specific model definition, optionally overriding table/schema.
-
repository<
T extends OrmEntity> () → Repository< T> -
Returns a repository for
T. -
runMutation(
MutationPlan plan) → Future< MutationResult> -
Executes a write
planand returns the driver result.override -
runSelect(
QueryPlan plan) → Future< List< Map< >String, Object?> > -
Executes a read
planand returns the raw rows.override -
table(
String table, {String? as, String? schema, List< String> ? scopes, List<AdHocColumn> columns = const []}) → Query<AdHocRow> - Builds a query against an arbitrary table name.
-
toString(
) → String -
A string representation of this object.
inherited
-
totalQueryDuration(
) → double - Returns the total time spent executing queries in milliseconds.
-
transaction<
R> (Future< R> callback()) → Future<R> -
Executes
callbackwithin a transaction boundary. -
whenQueryingForLongerThan(
Duration threshold, void handler(OrmConnection connection, QueryExecuted event)) → void Function() -
Registers a callback when cumulative query time exceeds
threshold.
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited
Static Methods
-
fromManager(
String name, {ConnectionRole role = ConnectionRole.primary, ConnectionManager? manager}) → OrmConnection