Remove QueryEngine mixin

This commit is contained in:
Simon Binder 2021-01-03 17:04:33 +01:00
parent db72da0f07
commit 603c9a20cc
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
19 changed files with 121 additions and 174 deletions

View File

@ -2,6 +2,7 @@
- __Breaking__: `getSingle()` and `watchSingle()` are now non-nullable and throw for empty results.
Use `getSingleOrNull()` and `watchSingleOrNull()` for the old behavior.
- __Breaking__: Removed `QueryEngine`, its methods have been moved to `DatabaseConnectionUser`
- __Breaking__: Changed the `args` parameter in `QueryExecutor` methods to `List<Object?>`
- __Breaking__: Removed the second type parameter from `TypedResult.read`
- __Breaking__: `MoorWebStorage.indexedDbIfSupported` now returns a future

View File

@ -12,7 +12,6 @@ export 'package:moor/src/runtime/query_builder/query_builder.dart';
export 'package:moor/src/runtime/executor/connection_pool.dart';
export 'package:moor/src/runtime/executor/executor.dart';
export 'package:moor/src/runtime/executor/transactions.dart';
export 'package:moor/src/runtime/custom_result_set.dart';
export 'package:moor/src/runtime/data_verification.dart';
export 'package:moor/src/runtime/data_class.dart';

View File

@ -7,7 +7,7 @@ part of 'dsl.dart';
/// run the build runner using (flutter packages) pub run build_runner build.
/// Moor will have generated a class that has the same name as your database
/// class, but with `_$` as a prefix. You can now extend that class and provide
/// a [QueryEngine] to use moor:
/// a [QueryExecutor] to use moor:
/// ```dart
/// class MyDatabase extends _$MyDatabase { // _$MyDatabase was generated
/// MyDatabase():

View File

@ -8,14 +8,14 @@ class Batch {
final Map<String, int> _sqlToIndex = {};
final List<ArgumentsForBatchedStatement> _createdArguments = [];
final QueryEngine _engine;
final DatabaseConnectionUser _user;
/// Whether we should start a transaction when completing.
final bool _startTransaction;
final Set<TableUpdate> _createdUpdates = {};
Batch._(this._engine, this._startTransaction);
Batch._(this._user, this._startTransaction);
void _addUpdate(TableInfo table, UpdateKind kind) {
_createdUpdates.add(TableUpdate.onTable(table, kind: kind));
@ -41,7 +41,7 @@ class Batch {
{InsertMode? mode, DoUpdate<T, D>? onConflict}) {
_addUpdate(table, UpdateKind.insert);
final actualMode = mode ?? InsertMode.insert;
final context = InsertStatement<Table, D>(_engine, table)
final context = InsertStatement<Table, D>(_user, table)
.createContext(row, actualMode, onConflict: onConflict);
_addContext(context);
}
@ -84,7 +84,7 @@ class Batch {
TableInfo<T, D> table, Insertable<D> row,
{Expression<bool?> Function(T table)? where}) {
_addUpdate(table, UpdateKind.update);
final stmt = UpdateStatement(_engine, table);
final stmt = UpdateStatement(_user, table);
if (where != null) stmt.where(where);
stmt.write(row, dontExecute: true);
@ -103,8 +103,7 @@ class Batch {
Insertable<D> row,
) {
_addUpdate(table, UpdateKind.update);
final stmt = UpdateStatement(_engine, table)
..replace(row, dontExecute: true);
final stmt = UpdateStatement(_user, table)..replace(row, dontExecute: true);
_addContext(stmt.constructQuery());
}
@ -119,23 +118,23 @@ class Batch {
/// Deletes [row] from the [table] when this batch is executed.
///
/// See also:
/// - [QueryEngine.delete]
/// - [DatabaseConnectionUser.delete]
/// - [DeleteStatement.delete]
void delete<T extends Table, D extends DataClass>(
TableInfo<T, D> table, Insertable<D> row) {
_addUpdate(table, UpdateKind.delete);
final stmt = DeleteStatement(_engine, table)..whereSamePrimaryKey(row);
final stmt = DeleteStatement(_user, table)..whereSamePrimaryKey(row);
_addContext(stmt.constructQuery());
}
/// Deletes all rows from [table] matching the provided [filter].
///
/// See also:
/// - [QueryEngine.delete]
/// - [DatabaseConnectionUser.delete]
void deleteWhere<T extends Table, D extends DataClass>(
TableInfo<T, D> table, Expression<bool?> Function(T tbl) filter) {
_addUpdate(table, UpdateKind.delete);
final stmt = DeleteStatement(_engine, table)..where(filter);
final stmt = DeleteStatement(_user, table)..where(filter);
_addContext(stmt.constructQuery());
}
@ -146,8 +145,8 @@ class Batch {
/// inspect the return value of individual statements.
///
/// See also:
/// - [QueryEngine.customStatement], the equivalent method outside of
/// batches.
/// - [DatabaseConnectionUser.customStatement], the equivalent method outside
/// of batches.
void customStatement(String sql, [List<dynamic>? args]) {
_addSqlAndArguments(sql, args ?? const []);
}
@ -168,14 +167,14 @@ class Batch {
}
Future<void> _commit() async {
await _engine.executor.ensureOpen(_engine.attachedDatabase);
await _user.executor.ensureOpen(_user.attachedDatabase);
if (_startTransaction) {
TransactionExecutor? transaction;
try {
transaction = _engine.executor.beginTransaction();
await transaction.ensureOpen(_engine.attachedDatabase);
transaction = _user.executor.beginTransaction();
await transaction.ensureOpen(_user.attachedDatabase);
await _runWith(transaction);
@ -185,10 +184,10 @@ class Batch {
rethrow;
}
} else {
await _runWith(_engine.executor);
await _runWith(_user.executor);
}
_engine.notifyUpdates(_createdUpdates);
_user.notifyUpdates(_createdUpdates);
}
Future<void> _runWith(QueryExecutor executor) {

View File

@ -65,69 +65,3 @@ class DatabaseConnection {
return DatabaseConnection(typeSystem, executor, streamQueries);
}
}
/// Manages a [DatabaseConnection] to send queries to the database.
abstract class DatabaseConnectionUser {
/// The database connection used by this [DatabaseConnectionUser].
@protected
final DatabaseConnection connection;
/// The type system to use with this database. The type system is responsible
/// for mapping Dart objects into sql expressions and vice-versa.
SqlTypeSystem get typeSystem => connection.typeSystem;
/// The executor to use when queries are executed.
QueryExecutor get executor => connection.executor;
/// Manages active streams from select statements.
@visibleForTesting
@protected
StreamQueryStore get streamQueries => connection.streamQueries;
/// Constructs a database connection user, which is responsible to store query
/// streams, wrap the underlying executor and perform type mapping.
DatabaseConnectionUser(SqlTypeSystem typeSystem, QueryExecutor executor,
{StreamQueryStore? streamQueries})
: connection = DatabaseConnection(
typeSystem, executor, streamQueries ?? StreamQueryStore());
/// Creates another [DatabaseConnectionUser] by referencing the implementation
/// from the [other] user.
DatabaseConnectionUser.delegate(DatabaseConnectionUser other,
{SqlTypeSystem? typeSystem,
QueryExecutor? executor,
StreamQueryStore? streamQueries})
: connection = DatabaseConnection(
typeSystem ?? other.connection.typeSystem,
executor ?? other.connection.executor,
streamQueries ?? other.connection.streamQueries,
);
/// Constructs a [DatabaseConnectionUser] that will use the provided
/// [DatabaseConnection].
DatabaseConnectionUser.fromConnection(this.connection);
/// Creates and auto-updating stream from the given select statement. This
/// method should not be used directly.
Stream<T> createStream<T>(QueryStreamFetcher<T> stmt) =>
streamQueries.registerStream(stmt);
/// Creates a copy of the table with an alias so that it can be used in the
/// same query more than once.
///
/// Example which uses the same table (here: points) more than once to
/// differentiate between the start and end point of a route:
/// ```
/// var source = alias(points, 'source');
/// var destination = alias(points, 'dest');
///
/// select(routes).join([
/// innerJoin(source, routes.startPoint.equalsExp(source.id)),
/// innerJoin(destination, routes.startPoint.equalsExp(destination.id)),
/// ]);
/// ```
T alias<T extends Table, D extends DataClass>(
TableInfo<T, D> table, String alias) {
return table.createAlias(alias).asDslTable;
}
}

View File

@ -5,50 +5,77 @@ const _zoneRootUserKey = #DatabaseConnectionUser;
typedef _CustomWriter<T> = Future<T> Function(
QueryExecutor e, String sql, List<dynamic> vars);
/// Mixin for a [DatabaseConnectionUser]. Provides an API to execute both
/// high-level and custom queries and fetch their results.
mixin QueryEngine on DatabaseConnectionUser {
/// Whether this connection user is "top level", e.g. there is no parent
/// connection user. We consider a [GeneratedDatabase] and a
/// [DatabaseAccessor] to be top-level, while a [Transaction] or a
/// [BeforeOpenRunner] aren't.
///
/// If any query method is called on a [topLevel] database user, we check if
/// it could instead be delegated to a child executor. For instance, consider
/// this code, assuming its part of a subclass of [GeneratedDatabase]:
/// ```dart
/// void example() {
/// transaction((t) async {
/// await update(table).write(/*...*/)
/// });
/// }
/// ```
/// Here, the `update` method would be called on the [GeneratedDatabase]
/// although it is very likely that the user meant to call it on the
/// [Transaction] t. We can detect this by calling the function passed to
/// `transaction` in a forked [Zone].
/// Manages a [DatabaseConnection] to send queries to the database.
abstract class DatabaseConnectionUser {
/// The database connection used by this [DatabaseConnectionUser].
@protected
bool get topLevel => false;
final DatabaseConnection connection;
/// The database that this query engine is attached to.
/// The database class that this user is attached to.
@visibleForOverriding
GeneratedDatabase get attachedDatabase;
/// We can detect when a user called methods on the wrong [QueryEngine]
/// (e.g. calling [QueryEngine.into] in a transaction, where
/// [QueryEngine.into] should have been called instead). See the documentation
/// of [topLevel] on how this works.
QueryEngine get _resolvedEngine {
if (!topLevel) {
// called directly in a transaction / other child callback, so use this
// instance directly
return this;
} else {
// if an overridden executor has been specified for this zone (this will
// happen for transactions), use that one.
final resolved = Zone.current[_zoneRootUserKey];
return (resolved as QueryEngine?) ?? this;
}
/// The type system to use with this database. The type system is responsible
/// for mapping Dart objects into sql expressions and vice-versa.
SqlTypeSystem get typeSystem => connection.typeSystem;
/// The executor to use when queries are executed.
QueryExecutor get executor => connection.executor;
/// Manages active streams from select statements.
@visibleForTesting
@protected
StreamQueryStore get streamQueries => connection.streamQueries;
/// Constructs a database connection user, which is responsible to store query
/// streams, wrap the underlying executor and perform type mapping.
DatabaseConnectionUser(SqlTypeSystem typeSystem, QueryExecutor executor,
{StreamQueryStore? streamQueries})
: connection = DatabaseConnection(
typeSystem, executor, streamQueries ?? StreamQueryStore());
/// Creates another [DatabaseConnectionUser] by referencing the implementation
/// from the [other] user.
DatabaseConnectionUser.delegate(DatabaseConnectionUser other,
{SqlTypeSystem? typeSystem,
QueryExecutor? executor,
StreamQueryStore? streamQueries})
: connection = DatabaseConnection(
typeSystem ?? other.connection.typeSystem,
executor ?? other.connection.executor,
streamQueries ?? other.connection.streamQueries,
);
/// Constructs a [DatabaseConnectionUser] that will use the provided
/// [DatabaseConnection].
DatabaseConnectionUser.fromConnection(this.connection);
/// Creates and auto-updating stream from the given select statement. This
/// method should not be used directly.
Stream<T> createStream<T>(QueryStreamFetcher<T> stmt) =>
streamQueries.registerStream(stmt);
/// Creates a copy of the table with an alias so that it can be used in the
/// same query more than once.
///
/// Example which uses the same table (here: points) more than once to
/// differentiate between the start and end point of a route:
/// ```
/// var source = alias(points, 'source');
/// var destination = alias(points, 'dest');
///
/// select(routes).join([
/// innerJoin(source, routes.startPoint.equalsExp(source.id)),
/// innerJoin(destination, routes.startPoint.equalsExp(destination.id)),
/// ]);
/// ```
T alias<T extends Table, D extends DataClass>(
TableInfo<T, D> table, String alias) {
return table.createAlias(alias).asDslTable;
}
DatabaseConnectionUser get _resolvedEngine {
return (Zone.current[_zoneRootUserKey] as DatabaseConnectionUser?) ?? this;
}
/// Marks the tables as updated. This method will be called internally
@ -335,7 +362,7 @@ mixin QueryEngine on DatabaseConnectionUser {
final transactionExecutor = executor.beginTransaction();
final transaction = Transaction(this, transactionExecutor);
return _runEngineZoned(transaction, () async {
return _runConnectionZoned(transaction, () async {
var success = false;
try {
final result = await action();
@ -396,13 +423,11 @@ mixin QueryEngine on DatabaseConnectionUser {
}
/// Runs [calculation] in a forked [Zone] that has its [_resolvedEngine] set
/// to the [engine].
///
/// For details, see the documentation at [topLevel].
/// to the [user].
@protected
Future<T> _runEngineZoned<T>(
QueryEngine engine, Future<T> Function() calculation) {
return runZoned(calculation, zoneValues: {_zoneRootUserKey: engine});
Future<T> _runConnectionZoned<T>(
DatabaseConnectionUser user, Future<T> Function() calculation) {
return runZoned(calculation, zoneValues: {_zoneRootUserKey: user});
}
/// Will be used by generated code to resolve inline Dart components in sql.

View File

@ -8,10 +8,7 @@ part of 'runtime_api.dart';
/// For details on how to write a dao, see [UseDao].
/// [T] should be the associated database class you wrote.
abstract class DatabaseAccessor<T extends GeneratedDatabase>
extends DatabaseConnectionUser with QueryEngine {
@override
final bool topLevel = true;
extends DatabaseConnectionUser {
/// The main database instance for this dao
@override
final T attachedDatabase;

View File

@ -11,11 +11,7 @@ Map<Type, int> _openedDbCount = {};
/// A base class for all generated databases.
abstract class GeneratedDatabase extends DatabaseConnectionUser
with QueryEngine
implements QueryExecutorUser {
@override
bool get topLevel => true;
@override
GeneratedDatabase get attachedDatabase => this;
@ -112,7 +108,7 @@ abstract class GeneratedDatabase extends DatabaseConnectionUser
@override
@nonVirtual
Future<void> beforeOpen(QueryExecutor executor, OpeningDetails details) {
return _runEngineZoned(BeforeOpenRunner(this, executor), () async {
return _runConnectionZoned(BeforeOpenRunner(this, executor), () async {
if (details.wasCreated) {
final migrator = createMigrator();
await _resolvedMigration.onCreate(migrator);

View File

@ -4,12 +4,13 @@ import 'package:meta/meta.dart';
import 'package:moor/moor.dart';
import 'package:moor/src/runtime/executor/delayed_stream_queries.dart';
import 'package:moor/src/runtime/executor/stream_queries.dart';
import 'package:moor/src/runtime/executor/transactions.dart';
part 'batch.dart';
part 'connection.dart';
part 'connection_user.dart';
part 'db_base.dart';
part 'dao_base.dart';
part 'query_engine.dart';
part 'stream_updates.dart';
/// Defines additional runtime behavior for moor. Changing the fields of this

View File

@ -152,7 +152,7 @@ abstract class SupportedTransactionDelegate extends TransactionDelegate {
/// Constant constructor on superclass
const SupportedTransactionDelegate();
/// Start a transaction, which we assume implements [QueryEngine], and call
/// Start a transaction, which we assume implements [QueryDelegate], and call
/// [run] with the transaction.
///
/// If [run] completes with an error, rollback. Otherwise, commit.

View File

@ -1,15 +1,11 @@
import 'package:meta/meta.dart';
import 'package:moor/moor.dart';
import 'package:moor/src/runtime/executor/stream_queries.dart';
/// Runs multiple statements transactionally.
///
/// Moor users should use [QueryEngine.transaction] to use this api.
@Deprecated(
"This class will be private in moor 4. If you're using this class directly, "
'please describe your usage in https://github.com/simolus3/moor/issues/810.',
)
class Transaction extends DatabaseConnectionUser with QueryEngine {
final QueryEngine _parent;
@internal
class Transaction extends DatabaseConnectionUser {
final DatabaseConnectionUser _parent;
@override
GeneratedDatabase get attachedDatabase => _parent.attachedDatabase;
@ -91,18 +87,15 @@ class _TransactionStreamStore extends StreamQueryStore {
///
/// To use this api, moor users should use the [MigrationStrategy.beforeOpen]
/// parameter inside the [GeneratedDatabase.migration] getter.
@Deprecated(
"This class will be private in moor 4. If you're using this class directly, "
'please describe your usage in https://github.com/simolus3/moor/issues/810.',
)
class BeforeOpenRunner extends DatabaseConnectionUser with QueryEngine {
final QueryEngine _parent;
@internal
class BeforeOpenRunner extends DatabaseConnectionUser {
final DatabaseConnectionUser _parent;
@override
GeneratedDatabase get attachedDatabase => _parent.attachedDatabase;
/// Creates a [BeforeOpenRunner] from a [QueryEngine] and the special
/// [executor] running the queries.
/// Creates a [BeforeOpenRunner] from a [DatabaseConnectionUser] and the
/// special [executor] running the queries.
BeforeOpenRunner(this._parent, QueryExecutor executor)
: super.delegate(_parent, executor: executor);
}

View File

@ -15,8 +15,9 @@ class GenerationContext {
/// The [SqlDialect] that should be respected when generating the query.
final SqlDialect dialect;
/// The actual [QueryEngine] that's going to execute the generated query.
final QueryEngine? executor;
/// The actual [DatabaseConnectionUser] that's going to execute the generated
/// query.
final DatabaseConnectionUser? executor;
final List<dynamic> _boundVariables = [];

View File

@ -3,8 +3,9 @@ part of '../query_builder.dart';
/// A `DELETE` statement in sql
class DeleteStatement<T extends Table, D extends DataClass> extends Query<T, D>
with SingleTableQueryMixin<T, D> {
/// This constructor should be called by [QueryEngine.delete] for you.
DeleteStatement(QueryEngine database, TableInfo<T, D> table)
/// This constructor should be called by [DatabaseConnectionUser.delete] for
/// you.
DeleteStatement(DatabaseConnectionUser database, TableInfo<T, D> table)
: super(database, table);
@override

View File

@ -4,7 +4,7 @@ part of '../query_builder.dart';
class InsertStatement<T extends Table, D extends DataClass> {
/// The database to use then executing this statement
@protected
final QueryEngine database;
final DatabaseConnectionUser database;
/// The table we're inserting into
@protected

View File

@ -5,13 +5,13 @@ part of '../query_builder.dart';
abstract class Query<T extends Table, D extends DataClass> {
/// The database this statement should be sent to.
@protected
QueryEngine database;
DatabaseConnectionUser database;
/// The (main) table this query operates on.
TableInfo<T, D> table;
/// Used internally by moor. Users should use the appropriate methods on
/// [QueryEngine] instead.
/// [DatabaseConnectionUser] instead.
Query(this.database, this.table);
/// The `WHERE` clause for this statement
@ -205,7 +205,7 @@ mixin SingleTableQueryMixin<T extends Table, D extends DataClass>
/// - The docs on [expressions](https://moor.simonbinder.eu/docs/getting-started/expressions/),
/// which explains how to express most SQL expressions in Dart.
/// If you want to remove duplicate rows from a query, use the `distinct`
/// parameter on [QueryEngine.select].
/// parameter on [DatabaseConnectionUser.select].
void where(Expression<bool?> Function(T tbl) filter) {
final predicate = filter(table.asDslTable);

View File

@ -14,7 +14,7 @@ class CustomSelectStatement with Selectable<QueryRow> {
/// The variables for the prepared statement, in the order they appear in
/// [query]. Variables are denoted using a question mark in the query.
final List<Variable> variables;
final QueryEngine _db;
final DatabaseConnectionUser _db;
/// Constructs a new custom select statement for the query, the variables,
/// the affected tables and the database.
@ -65,7 +65,7 @@ class QueryRow {
/// it's stored in the database. To read a value, use any of the [read]
/// methods.
final Map<String, dynamic> data;
final QueryEngine _db;
final DatabaseConnectionUser _db;
/// Construct a row from the raw data and the query engine that maps the raw
/// response to appropriate dart types.

View File

@ -12,9 +12,9 @@ class SimpleSelectStatement<T extends Table, D extends DataClass>
/// `SELECT DISTINCT` statement in sql). Defaults to false.
final bool distinct;
/// Used internally by moor, users will want to call [QueryEngine.select]
/// instead.
SimpleSelectStatement(QueryEngine database, TableInfo<T, D> table,
/// Used internally by moor, users will want to call
/// [DatabaseConnectionUser.select] instead.
SimpleSelectStatement(DatabaseConnectionUser database, TableInfo<T, D> table,
{this.distinct = false})
: super(database, table);

View File

@ -9,8 +9,8 @@ class JoinedSelectStatement<FirstT extends Table, FirstD extends DataClass>
with LimitContainerMixin, Selectable<TypedResult> {
/// Used internally by moor, users should use [SimpleSelectStatement.join]
/// instead.
JoinedSelectStatement(
QueryEngine database, TableInfo<FirstT, FirstD> table, this._joins,
JoinedSelectStatement(DatabaseConnectionUser database,
TableInfo<FirstT, FirstD> table, this._joins,
[this.distinct = false, this._includeMainTableInResult = true])
: super(database, table);

View File

@ -4,7 +4,7 @@ part of '../query_builder.dart';
class UpdateStatement<T extends Table, D extends DataClass> extends Query<T, D>
with SingleTableQueryMixin<T, D> {
/// Used internally by moor, construct an update statement
UpdateStatement(QueryEngine database, TableInfo<T, D> table)
UpdateStatement(DatabaseConnectionUser database, TableInfo<T, D> table)
: super(database, table);
late Map<String, Expression> _updatedFields;