DatabaseManager class final

Opens and keeps the database connections, runs transactions (nested ones as savepoints) and after-commit callbacks, and hands out query builders. DB is its facade.

Constructors

DatabaseManager(DatabaseConfig config, {Logger? logger, Map<String, DatabaseDriverFactory> drivers = const {}})
A manager for config's connections; drivers beyond SQLite and PostgreSQL are registered through withDatabaseDriver.

Properties

config → DatabaseConfig
The connections it manages.
final
hashCode → int
The hash code for this object.
no setterinherited
hasOpenConnections → bool
Whether any connection has been opened.
no setter
inTransaction → bool
Whether the current zone is inside a transaction on the default connection of this manager.
no setter
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited
totalQueryDuration → Duration
Time spent in queries by the current request, job or command (the isolate's total outside a scope).
no setter
transactionDepth → int
Current savepoint depth (0 outside, 1 in the outer transaction).
no setter

Methods

afterCommit(FutureOr<void> callback()) → Future<void>
Runs callback once the active transaction (and its savepoints) commits; a rollback discards it. Outside a transaction it runs now.
captureQueries<T>(FutureOr<T> body()) → Future<(T, List<QueryExecuted>)>
Runs body and returns its result with every query it ran, in this zone (nested calls each see their own queries): for tests that assert eager loading removed an N+1.
closeAll({Duration timeout = closeTimeout}) → Future<void>
Closes every open connection, each within timeout: a driver that throws or takes longer (a pool waiting for an abandoned transaction) is logged and left behind, and the others are still closed. The first error is rethrown once all were tried; a timeout is only logged.
connection([String? name]) → Future<DatabaseDriver>
Returns the (lazily connected) driver for name or the default connection.
dialectOf([String? name]) → SqlDialect
Dialect of name (or the default connection) without connecting.
executor([String? name]) → Future<QueryExecutor>
The active transaction executor of the current zone, or the connection. While anything listens (listeners, captures, duration handlers) it is wrapped to report each query.
forConnection(String name, ConnectionConfig connection) → DatabaseManager
A separate manager whose only (and default) connection is connection under name, with this manager's registered drivers: for tools that reach a database outside the configuration (dartisan db:transfer). Close it with closeAll.
forgetListeners() → void
Removes every query listener.
grammarFor([String? name]) → QueryGrammar
Query grammar for name (or the default connection).
insertGetId(String sql, [Object? bindings = const <Object?>[], String? connection]) → Future<Object?>
Runs a raw insert and returns the generated id.
inTransactionOn([String? connection]) → bool
Whether the current zone is inside a transaction on connection (the default connection when null).
listen(void listener(QueryExecuted event)) → void Function()
Calls listener after every query (DB::listen). Listeners run synchronously on the query's isolate; keep them cheap.
listenTransactions(void listener(TransactionEvent event)) → void Function()
Calls listener when a transaction or savepoint begins, commits and rolls back, synchronously; keep it cheap. Register it once; the returned function removes it.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
notifications(String channel, {String? connection}) → Future<Stream<String>?>
Payloads sent with notify on channel, when the connection delivers notifications (PostgreSQL's LISTEN); null otherwise, so callers poll instead. The stream holds a connection of its own until its listener cancels.
notify(String channel, [String payload = '', String? connection]) → Future<void>
Wakes the notifications listeners of channel, on every machine connected to the database (PostgreSQL's NOTIFY; inside a transaction it is sent at commit). Nothing on databases without notifications.
raw(String sql, [List<Object?> bindings = const []]) → RawExpression
A raw SQL expression (never bound; use ? for embedded bindings).
rollbackAfter<T>(Future<T> body(), {String? connection}) → Future<T>
Runs body in a transaction that is always rolled back (Laravel RefreshDatabase). Application transactions inside become savepoints and their after-commit callbacks fire when they "commit", as they would without the wrapper.
select(String sql, [Object? bindings = const <Object?>[], String? connection]) → Future<List<Map<String, Object?>>>
Runs a raw query. bindings may be a List (? placeholders) or a Map (:name placeholders); see SqlBindings.
statement(String sql, [Object? bindings = const <Object?>[], String? connection]) → Future<int>
Runs a raw statement and returns the affected row count.
table(String table, {String? connection}) → QueryBuilder
Starts a fluent query on table.
toString() → String
A string representation of this object.
inherited
transaction<T>(Future<T> body(), {String? connection, int attempts = 1, Duration? timeout}) → Future<T>
Runs body in a transaction on connection (default when null). Nested calls create a savepoint that is released or rolled back with the nested callback. With attempts > 1, deadlocks and serialization failures retry the whole transaction, after a short random wait.
whenQueryingForLongerThan(Duration threshold, void handler(QueryExecuted event)) → void Function()
Calls handler once the queries of the current request, job or command have taken more than threshold in total (Laravel's DB::whenQueryingForLongerThan), once per scope. Register it once; the returned function removes it.

Operators

operator ==(Object other) → bool
The equality operator.
inherited

Static Methods

retryDelay(Duration previous, Random random) → Duration
The next wait of a retry, decorrelated jitter: anywhere from the base to three times previous. Fifty isolates that collided do not collide again on the same microsecond.

Constants

afterCommitKey → const Object
Zone key holding the after-commit callbacks of the active transaction.
baselineKey → const Object
Zone key marking the callbacks list of a test baseline transaction.
closeTimeout → const Duration
How long closeAll waits for one connection by default.
depthKey → const Symbol
Zone key tracking the savepoint depth of the active transaction.
retryBaseDelay → const Duration
The shortest wait before retrying a transaction that hit a deadlock.
retryMaxDelay → const Duration
The longest wait between retries.
transactionKey → const Symbol
Zone key under which the active transaction executor is stored.