From bf94057d1bd77ebc254f1307f9bb1b59b028c871 Mon Sep 17 00:00:00 2001 From: Simon Binder Date: Sun, 20 Oct 2019 11:39:24 +0200 Subject: [PATCH] Call doWhenOpened for customStatement (#199) --- moor/CHANGELOG.md | 4 ++++ moor/lib/src/runtime/database.dart | 6 +++++- moor/test/custom_queries_test.dart | 6 ++++++ moor/test/data/utils/mocks.dart | 4 ++++ 4 files changed, 19 insertions(+), 1 deletion(-) diff --git a/moor/CHANGELOG.md b/moor/CHANGELOG.md index 5e10adbf..5c35f229 100644 --- a/moor/CHANGELOG.md +++ b/moor/CHANGELOG.md @@ -1,3 +1,7 @@ +## unreleased + +- Fix crash when `customStatement` is the first operation used on a database ([#199](https://github.com/simolus3/moor/issues/199)) + ## 2.0.1 - Introduced `isBetween` and `isBetweenValues` methods for comparable expressions (int, double, datetime) diff --git a/moor/lib/src/runtime/database.dart b/moor/lib/src/runtime/database.dart index a12b8111..832ee2b5 100644 --- a/moor/lib/src/runtime/database.dart +++ b/moor/lib/src/runtime/database.dart @@ -270,7 +270,11 @@ mixin QueryEngine on DatabaseConnectionUser { @protected @visibleForTesting Future customStatement(String statement, [List args]) { - return _resolvedEngine.executor.runCustom(statement, args); + final engine = _resolvedEngine; + + return engine.executor.doWhenOpened((executor) { + return executor.runCustom(statement, args); + }); } /// Executes [action] in a transaction, which means that all its queries and diff --git a/moor/test/custom_queries_test.dart b/moor/test/custom_queries_test.dart index 516ddaec..787895d6 100644 --- a/moor/test/custom_queries_test.dart +++ b/moor/test/custom_queries_test.dart @@ -73,4 +73,10 @@ void main() { // shouldn't call stream queries - we didn't set the updates parameter verifyNever(streamQueries.handleTableUpdates(any)); }); + + test('custom statement', () async { + // regression test for https://github.com/simolus3/moor/issues/199 - the + // mock will throw when used before opening + expect(db.customStatement('UPDATE tbl SET a = b'), completes); + }); } diff --git a/moor/test/data/utils/mocks.dart b/moor/test/data/utils/mocks.dart index 2196cb28..c104c9e5 100644 --- a/moor/test/data/utils/mocks.dart +++ b/moor/test/data/utils/mocks.dart @@ -29,6 +29,10 @@ class MockExecutor extends Mock implements QueryExecutor { assert(_opened); return Future.value(0); }); + when(runCustom(any, any)).thenAnswer((_) { + assert(_opened); + return Future.value(0); + }); when(beginTransaction()).thenAnswer((_) { assert(_opened); return transactions;