DataSource class

A unified entry point for ORM operations that manages connections, model registration, and provides ergonomic access to queries and repositories.

Single Data Source Example

final ds = DataSource(DataSourceOptions(
  driver: SqliteDriverAdapter.file('app.sqlite'),
  entities: [UserOrmDefinition.definition, PostOrmDefinition.definition],
));

await ds.init();

// Query data
final users = await ds.query<User>().whereEquals('active', true).get();

// Use repository
final userRepo = ds.repo<User>();
await userRepo.insert(newUser);

// Transaction
await ds.transaction(() async {
  await ds.repo<User>().insert(user);
  await ds.repo<Post>().insert(post);
});

await ds.dispose();

Multi-Tenant Example

final mainDs = DataSource(DataSourceOptions(
  name: 'main',
  driver: SqliteDriverAdapter.file('main.sqlite'),
  entities: entities,
));

final analyticsDs = DataSource(DataSourceOptions(
  name: 'analytics',
  driver: SqliteDriverAdapter.file('analytics.sqlite'),
  entities: entities,
));

await mainDs.init();
await analyticsDs.init();

// Query specific data sources
final mainUsers = await mainDs.query<User>().get();
final analyticsUsers = await analyticsDs.query<User>().get();
Available extensions

Constructors

DataSource(DataSourceOptions options)
Creates a new data source with the given configuration options.
DataSource.fromConfig(OrmProjectConfig config, {ModelRegistry? registry, ScopeRegistry? scopeRegistry, Map<String, ValueCodec> codecs = const {}, Logger? logger})
Creates a DataSource from an OrmProjectConfig.
factory

Properties

codecRegistry ValueCodecRegistry
The underlying value codec registry.
no setter
connection OrmConnection
The underlying ORM connection.
no setter
context QueryContext
The underlying query context.
no setter
hashCode int
The hash code for this object.
no setterinherited
isInitialized bool
Whether this data source has been initialized.
no setter
logger → Logger?
The contextual logger attached for query logging, if any.
no setter
name String
The logical name of this data source connection.
no setter
options DataSourceOptions
The configuration options for this data source.
final
queryLog List<QueryLogEntry>
Returns the accumulated query log entries.
no setter
registry ModelRegistry
The underlying model registry.
no setter
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

beforeExecuting(ExecutingStatementCallback callback) → void Function()
Registers a callback invoked before any SQL is dispatched.
beginTransaction() Future<void>
Begins a new database transaction.
commit() Future<void>
Commits the active database transaction.
disableQueryLog({bool clear = false}) → void
Disables query logging.
dispose() Future<void>
Closes the data source connection and releases resources.
enableQueryLog({bool includeParameters = true, bool clear = true}) → void
Enables query logging for this data source.
flushQueryLog() → void
Clears all accumulated query log entries.
getRepository<T extends OrmEntity>() Repository<T>
Alias for repo. Returns a repository for the specified model type.
init() Future<void>
Initializes the data source by registering all entities and establishing the database connection.
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 action with pretend mode enabled and returns the captured SQL.
query<T extends OrmEntity>() Query<T>
Creates a typed query builder for the specified model type.
repo<T extends OrmEntity>() Repository<T>
Returns a repository for performing CRUD operations on the specified model type.
rollback() Future<void>
Rolls back the active database transaction.
seed(List<Seeder> seeders) Future<void>

Available on DataSource, provided by the DataSourceSeeding extension

Seed the database with the given seeders
setAsDefault() → void
Sets this DataSource as the default connection for Model static helpers.
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 the provided callback within a database transaction.
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

clearDefault() → void
Clears the default DataSource. Useful for testing.
getDefault() DataSource?
Returns the current default DataSource, or null if none is set.
setDefault(DataSource dataSource) → void
Sets a DataSource as the default for Model static helpers.