diff --git a/.cirrus.yml b/.cirrus.yml deleted file mode 100644 index 84651caf..00000000 --- a/.cirrus.yml +++ /dev/null @@ -1,20 +0,0 @@ -# Run tasks with the dart SDK installed by default -container: - dockerfile: tool/Dockerfile - memory: 12G - cpu: 4 - -task: - pub_cache: - folder: $HOME/.pub-cache - environment: - CODECOV_TOKEN: ENCRYPTED[6322a159d9b7692b999d13fa2bc7981c8b61ecb1ac18ae076864f1355ee9b65088b2bf9d97d7860196e58bf1db5708af] - dart_version_script: dart --version - pub_get_script: tool/pub_get.sh - analyze_script: tool/analyze.sh - test_moor_script: tool/test_moor.sh - test_sqlparser_script: tool/test_sqlparser.sh - misc_integration_test_script: tool/misc_integration_test.sh - # We just get too many timeouts for moor_generator in the CI runner -# test_moor_generator_script: tool/test_generator.sh - format_coverage_script: tool/upload_coverage.sh \ No newline at end of file diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 00000000..5048820e --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,116 @@ +name: CI + +on: [push, pull_request] + +env: + PUB_ENVIRONMENT: bot.github + +jobs: + moor: + name: "moor package" + runs-on: ubuntu-20.04 + + steps: + # setup + - uses: actions/checkout@v2 + - uses: cedx/setup-dart@v2 + with: + release-channel: beta + - run: sudo apt-get install -y libsqlite3-dev + name: Install sqlite3 for tests + - run: dart pub upgrade + working-directory: moor + # analysis + - run: dart format -o none --set-exit-if-changed moor/ + name: dartfmt + - run: dart analyze --fatal-infos --fatal-warnings + working-directory: moor/ + # build, test and upload coverage + - run: dart run build_runner build --delete-conflicting-outputs + working-directory: moor + - run: dart --no-sound-null-safety --null-assertions test #-x background_isolate --coverage=coverage + working-directory: moor +# - uses: actions/upload-artifact@v2 +# with: +# name: moor-coverage-data +# path: | +# moor/coverage/ +# moor/.dart_tool/package_config.json +# retention-days: 1 + + moor_generator: + runs-on: ubuntu-20.04 + steps: + # setup + - uses: actions/checkout@v2 + - uses: cedx/setup-dart@v2 + with: + release-channel: beta + - run: dart pub upgrade + working-directory: moor_generator + # analysis + - run: dart format -o none --set-exit-if-changed moor_generator/ + name: dartfmt + - run: dart analyze --fatal-infos --fatal-warnings + working-directory: moor_generator/ + + sqlparser: + runs-on: ubuntu-20.04 + steps: + # setup + - uses: actions/checkout@v2 + - uses: cedx/setup-dart@v2 + - run: sudo apt-get install -y libsqlite3-dev + name: Install sqlite3 for tests + - run: dart pub upgrade + working-directory: sqlparser + # analysis + - run: dart format -o none --set-exit-if-changed sqlparser/ + name: dartfmt + - run: dart analyze --fatal-infos --fatal-warnings + working-directory: sqlparser/ + # tests and coverage + - run: dart test #--coverage=coverage + working-directory: sqlparser +# - uses: actions/upload-artifact@v2 +# with: +# name: sqlparser-coverage-data +# path: | +# sqlparser/coverage/ +# sqlparser/.dart_tool/package_config.json +# retention-days: 1 + + misc_integration_tests: + name: "Integration tests" + runs-on: ubuntu-20.04 + steps: + - uses: actions/checkout@v2 + - uses: cedx/setup-dart@v2 + with: + release-channel: beta + - run: sudo apt-get install -y libsqlite3-dev + name: Install sqlite3 for tests + - run: tool/misc_integration_test.sh + +# upload_coverage: +# runs-on: ubuntu-20.04 +# needs: [moor, sqlparser] +# steps: +# - uses: actions/checkout@v2 +# - uses: cedx/setup-dart@v2 +# - run: dart pub upgrade +# name: "Setup coverage processor" +# working-directory: extras/coverage_formatting +# - uses: actions/download-artifact@v2 +# with: +# name: moor-coverage-data +# path: moor/ +# - uses: actions/download-artifact@v2 +# with: +# name: sqlparser-coverage-data +# path: sqlparser/ +# - run: dart run extras/coverage_formatting/bin/coverage.dart +# name: "Format coverage from raw data" +# - uses: codecov/codecov-action@v1 +# with: +# file: lcov.info diff --git a/.gitignore b/.gitignore index 14b5448e..e08463f4 100644 --- a/.gitignore +++ b/.gitignore @@ -8,5 +8,6 @@ pubspec.lock .dart_tool/ benchmark_results.json +.flutter-plugins .flutter-plugins-dependencies flutter_export_environment.sh \ No newline at end of file diff --git a/analysis_options.yaml b/analysis_options.yaml index a2996adc..98d91963 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -13,6 +13,7 @@ analyzer: # Will be analyzed anyway, nobody knows why ¯\_(ツ)_/¯. We're only analyzing lib/ and test/ as a workaround - ".dart_tool/build/entrypoint/build.dart" - "tool/**" + - "**/*.mocks.dart" # this should always include all rules. Those we don't use are commented out linter: diff --git a/extras/benchmarks/pubspec.yaml b/extras/benchmarks/pubspec.yaml index 568209e3..80192935 100644 --- a/extras/benchmarks/pubspec.yaml +++ b/extras/benchmarks/pubspec.yaml @@ -1,6 +1,9 @@ name: benchmarks description: Runs simple and complex benchmarks to measure performance of moor and moor_ffi +environment: + sdk: '>=2.6.0 <3.0.0' + dependencies: moor: sqlite3: ^0.1.3 diff --git a/extras/coverage_formatting/bin/coverage.dart b/extras/coverage_formatting/bin/coverage.dart index 2d6d0b88..4b15de29 100644 --- a/extras/coverage_formatting/bin/coverage.dart +++ b/extras/coverage_formatting/bin/coverage.dart @@ -31,7 +31,8 @@ Future runForProject(String projectName) async { final hitmap = await parseCoverage(files, 1); final resolver = MoorResolver( - projectRoot: projectName, packagesPath: p.join(projectName, '.packages')); + projectRoot: projectName, + packagesPath: p.join(projectName, '.dart_tool', 'package_config.json')); final output = await LcovFormatter(resolver, reportOn: [p.join(projectName, 'lib')]) diff --git a/extras/coverage_formatting/pubspec.yaml b/extras/coverage_formatting/pubspec.yaml index 02650cb9..f2fee0e2 100644 --- a/extras/coverage_formatting/pubspec.yaml +++ b/extras/coverage_formatting/pubspec.yaml @@ -2,6 +2,9 @@ name: coverage_formatting publish_to: none description: Tool used for the CI to format VM coverage jsons to LCOV files +environment: + sdk: '>=2.6.0 <3.0.0' + dependencies: coverage: '^0.14.0' path: ^1.6.4 \ No newline at end of file diff --git a/extras/encryption/lib/encrypted_moor.dart b/extras/encryption/lib/encrypted_moor.dart index e65a75b8..e697065d 100644 --- a/extras/encryption/lib/encrypted_moor.dart +++ b/extras/encryption/lib/encrypted_moor.dart @@ -6,7 +6,6 @@ library encrypted_moor; import 'dart:async'; import 'dart:io'; -import 'package:meta/meta.dart'; import 'package:path/path.dart'; import 'package:moor/moor.dart'; import 'package:moor/backends.dart'; @@ -19,21 +18,25 @@ typedef DatabaseCreator = FutureOr Function(File file); class _SqfliteDelegate extends DatabaseDelegate with _SqfliteExecutor { @override - s.Database db; + late s.Database db; + bool _isOpen = false; final bool inDbFolder; final String path; - final String password; + final String? password; bool singleInstance; - final DatabaseCreator creator; + final DatabaseCreator? creator; - _SqfliteDelegate(this.inDbFolder, this.path, - {this.singleInstance, this.creator, this.password}) { - singleInstance ??= true; - } + _SqfliteDelegate( + this.inDbFolder, + this.path, { + this.singleInstance = true, + this.creator, + this.password, + }); - DbVersionDelegate _delegate; + DbVersionDelegate? _delegate; @override DbVersionDelegate get versionDelegate { return _delegate ??= _SqfliteVersionDelegate(db); @@ -44,7 +47,7 @@ class _SqfliteDelegate extends DatabaseDelegate with _SqfliteExecutor { _SqfliteTransactionDelegate(this); @override - bool get isOpen => db != null; + bool get isOpen => _isOpen; @override Future open(QueryExecutorUser user) async { @@ -57,7 +60,7 @@ class _SqfliteDelegate extends DatabaseDelegate with _SqfliteExecutor { final file = File(resolvedPath); if (creator != null && !await file.exists()) { - await creator(file); + await creator!(file); } db = await s.openDatabase( @@ -65,6 +68,7 @@ class _SqfliteDelegate extends DatabaseDelegate with _SqfliteExecutor { password: password, singleInstance: singleInstance, ); + _isOpen = true; } @override @@ -98,7 +102,6 @@ class _SqfliteTransactionDelegate extends SupportedTransactionDelegate { @override void startTransaction(Future Function(QueryDelegate) run) { delegate.db.transaction((transaction) async { - assert(transaction != null); final executor = _SqfliteTransactionExecutor(transaction); await run(executor); }).catchError((_) { @@ -131,23 +134,23 @@ mixin _SqfliteExecutor on QueryDelegate { } @override - Future runCustom(String statement, List args) { + Future runCustom(String statement, List args) { return db.execute(statement, args); } @override - Future runInsert(String statement, List args) { + Future runInsert(String statement, List args) { return db.rawInsert(statement, args); } @override - Future runSelect(String statement, List args) async { + Future runSelect(String statement, List args) async { final result = await db.rawQuery(statement, args); return QueryResult.fromRows(result); } @override - Future runUpdate(String statement, List args) { + Future runUpdate(String statement, List args) { return db.rawUpdate(statement, args); } } @@ -165,11 +168,11 @@ class EncryptedExecutor extends DelegatedDatabase { /// [MigrationStrategy.onCreate] callback because it hasn't been created by /// moor. EncryptedExecutor( - {@required String path, - @required String password, - bool logStatements, - bool singleInstance, - DatabaseCreator creator}) + {required String path, + required String password, + bool? logStatements, + bool singleInstance = true, + DatabaseCreator? creator}) : super( _SqfliteDelegate(false, path, singleInstance: singleInstance, @@ -189,11 +192,11 @@ class EncryptedExecutor extends DelegatedDatabase { /// [MigrationStrategy.onCreate] callback because it hasn't been created by /// moor. EncryptedExecutor.inDatabaseFolder( - {@required String path, - @required String password, - bool logStatements, - bool singleInstance, - DatabaseCreator creator}) + {required String path, + required String password, + bool? logStatements, + bool singleInstance = true, + DatabaseCreator? creator}) : super( _SqfliteDelegate(true, path, singleInstance: singleInstance, @@ -212,8 +215,8 @@ class EncryptedExecutor extends DelegatedDatabase { /// /// Note that this returns null until the moor database has been opened. /// A moor database is opened lazily when the first query runs. - s.Database get sqfliteDb { + s.Database? get sqfliteDb { final sqfliteDelegate = delegate as _SqfliteDelegate; - return sqfliteDelegate.db; + return sqfliteDelegate.isOpen ? sqfliteDelegate.db : null; } } diff --git a/extras/encryption/pubspec.yaml b/extras/encryption/pubspec.yaml index 644db6a3..96a2f4bd 100644 --- a/extras/encryption/pubspec.yaml +++ b/extras/encryption/pubspec.yaml @@ -4,11 +4,11 @@ version: 1.0.0 author: Simon Binder environment: - sdk: '>=2.4.0 <3.0.0' + sdk: '>=2.12.0-0 <3.0.0' dependencies: moor: ^3.0.0 - sqflite_sqlcipher: ^1.0.0+6 + sqflite_sqlcipher: ^2.0.0-nullsafety dependency_overrides: moor: diff --git a/extras/integration_tests/ffi_on_flutter/pubspec.yaml b/extras/integration_tests/ffi_on_flutter/pubspec.yaml index 1fc87152..3c9e7017 100644 --- a/extras/integration_tests/ffi_on_flutter/pubspec.yaml +++ b/extras/integration_tests/ffi_on_flutter/pubspec.yaml @@ -2,6 +2,8 @@ name: flutter_db description: Moor integration tests running on sqflite version: 1.0.0+1 +publish_to: none + environment: sdk: ">=2.1.0 <3.0.0" flutter: ">=1.12.0" diff --git a/extras/integration_tests/vm/pubspec.yaml b/extras/integration_tests/vm/pubspec.yaml index 94a87991..c2f9a7fe 100644 --- a/extras/integration_tests/vm/pubspec.yaml +++ b/extras/integration_tests/vm/pubspec.yaml @@ -16,4 +16,4 @@ dev_dependencies: dependency_overrides: moor: - path: ../../../moor + path: ../../../moor \ No newline at end of file diff --git a/extras/with_built_value/pubspec.yaml b/extras/with_built_value/pubspec.yaml index fcd328c2..4a30110a 100644 --- a/extras/with_built_value/pubspec.yaml +++ b/extras/with_built_value/pubspec.yaml @@ -23,4 +23,5 @@ dependency_overrides: path: ../../sqlparser # todo: Remove after built_value supports analyzer ^0.40 - analyzer: 0.40.4 \ No newline at end of file + analyzer: 0.40.4 + convert: ^3.0.0-nullsafety \ No newline at end of file diff --git a/moor/CHANGELOG.md b/moor/CHANGELOG.md index ad595bda..af7d06a8 100644 --- a/moor/CHANGELOG.md +++ b/moor/CHANGELOG.md @@ -1,5 +1,8 @@ -## unreleased +## unreleased (breaking - 4.0) +- __Breaking__: Changed the `args` parameter in `QueryExecutor` methods to `List` +- __Breaking__: Removed the second type parameter from `TypedResult.read` +- Support null safety - Changed the sql representation of text types from `VARCHAR` to `TEXT` - Added extensions for `isNull` and `isNotNull` - Support creating a `VmDatabase` from a raw sqlite3 `Database` via `VmDatabase.opened` diff --git a/moor/README.md b/moor/README.md index 1a62b3b4..3c6bdc15 100644 --- a/moor/README.md +++ b/moor/README.md @@ -1,3 +1,4 @@ + # Moor Moor is a reactive persistence library for Flutter and Dart, built ontop of sqlite. diff --git a/moor/analysis_options.yaml b/moor/analysis_options.yaml index 94cfa8af..50b3175f 100644 --- a/moor/analysis_options.yaml +++ b/moor/analysis_options.yaml @@ -7,4 +7,5 @@ analyzer: exclude: - "example_web/**" - "example/**" - - "**/*.g.dart" \ No newline at end of file + - "**/*.g.dart" + - "**/*.mocks.dart" diff --git a/moor/dart_test.yaml b/moor/dart_test.yaml index 02c6febb..c11d0b9e 100644 --- a/moor/dart_test.yaml +++ b/moor/dart_test.yaml @@ -1,5 +1,6 @@ tags: integration: + background_isolate: platforms: - vm diff --git a/moor/example/example.g.dart b/moor/example/example.g.dart index 91925823..b2b4b3bf 100644 --- a/moor/example/example.g.dart +++ b/moor/example/example.g.dart @@ -9,15 +9,15 @@ part of 'example.dart'; // ignore_for_file: unnecessary_brace_in_string_interps, unnecessary_this class Category extends DataClass implements Insertable { final int id; - final String description; - Category({@required this.id, this.description}); + final String? description; + Category({required this.id, this.description}); factory Category.fromData(Map data, GeneratedDatabase db, - {String prefix}) { + {String? prefix}) { final effectivePrefix = prefix ?? ''; final intType = db.typeSystem.forDartType(); final stringType = db.typeSystem.forDartType(); return Category( - id: intType.mapFromDatabaseResponse(data['${effectivePrefix}id']), + id: intType.mapFromDatabaseResponse(data['${effectivePrefix}id'])!, description: stringType .mapFromDatabaseResponse(data['${effectivePrefix}description']), ); @@ -25,18 +25,16 @@ class Category extends DataClass implements Insertable { @override Map toColumns(bool nullToAbsent) { final map = {}; - if (!nullToAbsent || id != null) { - map['id'] = Variable(id); - } + map['id'] = Variable(id); if (!nullToAbsent || description != null) { - map['description'] = Variable(description); + map['description'] = Variable(description); } return map; } CategoriesCompanion toCompanion(bool nullToAbsent) { return CategoriesCompanion( - id: id == null && nullToAbsent ? const Value.absent() : Value(id), + id: Value(id), description: description == null && nullToAbsent ? const Value.absent() : Value(description), @@ -44,29 +42,29 @@ class Category extends DataClass implements Insertable { } factory Category.fromJson(Map json, - {ValueSerializer serializer}) { + {ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return Category( id: serializer.fromJson(json['id']), - description: serializer.fromJson(json['description']), + description: serializer.fromJson(json['description']), ); } factory Category.fromJsonString(String encodedJson, - {ValueSerializer serializer}) => + {ValueSerializer? serializer}) => Category.fromJson( DataClass.parseJson(encodedJson) as Map, serializer: serializer); @override - Map toJson({ValueSerializer serializer}) { + Map toJson({ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return { 'id': serializer.toJson(id), - 'description': serializer.toJson(description), + 'description': serializer.toJson(description), }; } Category copyWith( - {int id, Value description = const Value.absent()}) => + {int? id, Value description = const Value.absent()}) => Category( id: id ?? this.id, description: description.present ? description.value : this.description, @@ -92,7 +90,7 @@ class Category extends DataClass implements Insertable { class CategoriesCompanion extends UpdateCompanion { final Value id; - final Value description; + final Value description; const CategoriesCompanion({ this.id = const Value.absent(), this.description = const Value.absent(), @@ -102,8 +100,8 @@ class CategoriesCompanion extends UpdateCompanion { this.description = const Value.absent(), }); static Insertable custom({ - Expression id, - Expression description, + Expression? id, + Expression? description, }) { return RawValuesInsertable({ if (id != null) 'id': id, @@ -111,7 +109,7 @@ class CategoriesCompanion extends UpdateCompanion { }); } - CategoriesCompanion copyWith({Value id, Value description}) { + CategoriesCompanion copyWith({Value? id, Value? description}) { return CategoriesCompanion( id: id ?? this.id, description: description ?? this.description, @@ -125,7 +123,7 @@ class CategoriesCompanion extends UpdateCompanion { map['id'] = Variable(id.value); } if (description.present) { - map['description'] = Variable(description.value); + map['description'] = Variable(description.value); } return map; } @@ -143,12 +141,11 @@ class CategoriesCompanion extends UpdateCompanion { class $CategoriesTable extends Categories with TableInfo<$CategoriesTable, Category> { final GeneratedDatabase _db; - final String _alias; + final String? _alias; $CategoriesTable(this._db, [this._alias]); final VerificationMeta _idMeta = const VerificationMeta('id'); - GeneratedIntColumn _id; @override - GeneratedIntColumn get id => _id ??= _constructId(); + late final GeneratedIntColumn id = _constructId(); GeneratedIntColumn _constructId() { return GeneratedIntColumn('id', $tableName, false, hasAutoIncrement: true, declaredAsPrimaryKey: true); @@ -156,10 +153,8 @@ class $CategoriesTable extends Categories final VerificationMeta _descriptionMeta = const VerificationMeta('description'); - GeneratedTextColumn _description; @override - GeneratedTextColumn get description => - _description ??= _constructDescription(); + late final GeneratedTextColumn description = _constructDescription(); GeneratedTextColumn _constructDescription() { return GeneratedTextColumn( 'description', @@ -182,13 +177,13 @@ class $CategoriesTable extends Categories final context = VerificationContext(); final data = instance.toColumns(true); if (data.containsKey('id')) { - context.handle(_idMeta, id.isAcceptableOrUnknown(data['id'], _idMeta)); + context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); } if (data.containsKey('description')) { context.handle( _descriptionMeta, description.isAcceptableOrUnknown( - data['description'], _descriptionMeta)); + data['description']!, _descriptionMeta)); } return context; } @@ -196,7 +191,7 @@ class $CategoriesTable extends Categories @override Set get $primaryKey => {id}; @override - Category map(Map data, {String tablePrefix}) { + Category map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; return Category.fromData(data, _db, prefix: effectivePrefix); } @@ -211,23 +206,23 @@ class Recipe extends DataClass implements Insertable { final int id; final String title; final String instructions; - final int category; + final int? category; Recipe( - {@required this.id, - @required this.title, - @required this.instructions, + {required this.id, + required this.title, + required this.instructions, this.category}); factory Recipe.fromData(Map data, GeneratedDatabase db, - {String prefix}) { + {String? prefix}) { final effectivePrefix = prefix ?? ''; final intType = db.typeSystem.forDartType(); final stringType = db.typeSystem.forDartType(); return Recipe( - id: intType.mapFromDatabaseResponse(data['${effectivePrefix}id']), + id: intType.mapFromDatabaseResponse(data['${effectivePrefix}id'])!, title: - stringType.mapFromDatabaseResponse(data['${effectivePrefix}title']), + stringType.mapFromDatabaseResponse(data['${effectivePrefix}title'])!, instructions: stringType - .mapFromDatabaseResponse(data['${effectivePrefix}instructions']), + .mapFromDatabaseResponse(data['${effectivePrefix}instructions'])!, category: intType.mapFromDatabaseResponse(data['${effectivePrefix}category']), ); @@ -235,29 +230,20 @@ class Recipe extends DataClass implements Insertable { @override Map toColumns(bool nullToAbsent) { final map = {}; - if (!nullToAbsent || id != null) { - map['id'] = Variable(id); - } - if (!nullToAbsent || title != null) { - map['title'] = Variable(title); - } - if (!nullToAbsent || instructions != null) { - map['instructions'] = Variable(instructions); - } + map['id'] = Variable(id); + map['title'] = Variable(title); + map['instructions'] = Variable(instructions); if (!nullToAbsent || category != null) { - map['category'] = Variable(category); + map['category'] = Variable(category); } return map; } RecipesCompanion toCompanion(bool nullToAbsent) { return RecipesCompanion( - id: id == null && nullToAbsent ? const Value.absent() : Value(id), - title: - title == null && nullToAbsent ? const Value.absent() : Value(title), - instructions: instructions == null && nullToAbsent - ? const Value.absent() - : Value(instructions), + id: Value(id), + title: Value(title), + instructions: Value(instructions), category: category == null && nullToAbsent ? const Value.absent() : Value(category), @@ -265,35 +251,35 @@ class Recipe extends DataClass implements Insertable { } factory Recipe.fromJson(Map json, - {ValueSerializer serializer}) { + {ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return Recipe( id: serializer.fromJson(json['id']), title: serializer.fromJson(json['title']), instructions: serializer.fromJson(json['instructions']), - category: serializer.fromJson(json['category']), + category: serializer.fromJson(json['category']), ); } factory Recipe.fromJsonString(String encodedJson, - {ValueSerializer serializer}) => + {ValueSerializer? serializer}) => Recipe.fromJson(DataClass.parseJson(encodedJson) as Map, serializer: serializer); @override - Map toJson({ValueSerializer serializer}) { + Map toJson({ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return { 'id': serializer.toJson(id), 'title': serializer.toJson(title), 'instructions': serializer.toJson(instructions), - 'category': serializer.toJson(category), + 'category': serializer.toJson(category), }; } Recipe copyWith( - {int id, - String title, - String instructions, - Value category = const Value.absent()}) => + {int? id, + String? title, + String? instructions, + Value category = const Value.absent()}) => Recipe( id: id ?? this.id, title: title ?? this.title, @@ -328,7 +314,7 @@ class RecipesCompanion extends UpdateCompanion { final Value id; final Value title; final Value instructions; - final Value category; + final Value category; const RecipesCompanion({ this.id = const Value.absent(), this.title = const Value.absent(), @@ -337,16 +323,16 @@ class RecipesCompanion extends UpdateCompanion { }); RecipesCompanion.insert({ this.id = const Value.absent(), - @required String title, - @required String instructions, + required String title, + required String instructions, this.category = const Value.absent(), }) : title = Value(title), instructions = Value(instructions); static Insertable custom({ - Expression id, - Expression title, - Expression instructions, - Expression category, + Expression? id, + Expression? title, + Expression? instructions, + Expression? category, }) { return RawValuesInsertable({ if (id != null) 'id': id, @@ -357,10 +343,10 @@ class RecipesCompanion extends UpdateCompanion { } RecipesCompanion copyWith( - {Value id, - Value title, - Value instructions, - Value category}) { + {Value? id, + Value? title, + Value? instructions, + Value? category}) { return RecipesCompanion( id: id ?? this.id, title: title ?? this.title, @@ -382,7 +368,7 @@ class RecipesCompanion extends UpdateCompanion { map['instructions'] = Variable(instructions.value); } if (category.present) { - map['category'] = Variable(category.value); + map['category'] = Variable(category.value); } return map; } @@ -401,31 +387,27 @@ class RecipesCompanion extends UpdateCompanion { class $RecipesTable extends Recipes with TableInfo<$RecipesTable, Recipe> { final GeneratedDatabase _db; - final String _alias; + final String? _alias; $RecipesTable(this._db, [this._alias]); final VerificationMeta _idMeta = const VerificationMeta('id'); - GeneratedIntColumn _id; @override - GeneratedIntColumn get id => _id ??= _constructId(); + late final GeneratedIntColumn id = _constructId(); GeneratedIntColumn _constructId() { return GeneratedIntColumn('id', $tableName, false, hasAutoIncrement: true, declaredAsPrimaryKey: true); } final VerificationMeta _titleMeta = const VerificationMeta('title'); - GeneratedTextColumn _title; @override - GeneratedTextColumn get title => _title ??= _constructTitle(); + late final GeneratedTextColumn title = _constructTitle(); GeneratedTextColumn _constructTitle() { return GeneratedTextColumn('title', $tableName, false, maxTextLength: 16); } final VerificationMeta _instructionsMeta = const VerificationMeta('instructions'); - GeneratedTextColumn _instructions; @override - GeneratedTextColumn get instructions => - _instructions ??= _constructInstructions(); + late final GeneratedTextColumn instructions = _constructInstructions(); GeneratedTextColumn _constructInstructions() { return GeneratedTextColumn( 'instructions', @@ -435,9 +417,8 @@ class $RecipesTable extends Recipes with TableInfo<$RecipesTable, Recipe> { } final VerificationMeta _categoryMeta = const VerificationMeta('category'); - GeneratedIntColumn _category; @override - GeneratedIntColumn get category => _category ??= _constructCategory(); + late final GeneratedIntColumn category = _constructCategory(); GeneratedIntColumn _constructCategory() { return GeneratedIntColumn( 'category', @@ -460,11 +441,11 @@ class $RecipesTable extends Recipes with TableInfo<$RecipesTable, Recipe> { final context = VerificationContext(); final data = instance.toColumns(true); if (data.containsKey('id')) { - context.handle(_idMeta, id.isAcceptableOrUnknown(data['id'], _idMeta)); + context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); } if (data.containsKey('title')) { context.handle( - _titleMeta, title.isAcceptableOrUnknown(data['title'], _titleMeta)); + _titleMeta, title.isAcceptableOrUnknown(data['title']!, _titleMeta)); } else if (isInserting) { context.missing(_titleMeta); } @@ -472,13 +453,13 @@ class $RecipesTable extends Recipes with TableInfo<$RecipesTable, Recipe> { context.handle( _instructionsMeta, instructions.isAcceptableOrUnknown( - data['instructions'], _instructionsMeta)); + data['instructions']!, _instructionsMeta)); } else if (isInserting) { context.missing(_instructionsMeta); } if (data.containsKey('category')) { context.handle(_categoryMeta, - category.isAcceptableOrUnknown(data['category'], _categoryMeta)); + category.isAcceptableOrUnknown(data['category']!, _categoryMeta)); } return context; } @@ -486,7 +467,7 @@ class $RecipesTable extends Recipes with TableInfo<$RecipesTable, Recipe> { @override Set get $primaryKey => {id}; @override - Recipe map(Map data, {String tablePrefix}) { + Recipe map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; return Recipe.fromData(data, _db, prefix: effectivePrefix); } @@ -502,46 +483,38 @@ class Ingredient extends DataClass implements Insertable { final String name; final int caloriesPer100g; Ingredient( - {@required this.id, @required this.name, @required this.caloriesPer100g}); + {required this.id, required this.name, required this.caloriesPer100g}); factory Ingredient.fromData(Map data, GeneratedDatabase db, - {String prefix}) { + {String? prefix}) { final effectivePrefix = prefix ?? ''; final intType = db.typeSystem.forDartType(); final stringType = db.typeSystem.forDartType(); return Ingredient( - id: intType.mapFromDatabaseResponse(data['${effectivePrefix}id']), - name: stringType.mapFromDatabaseResponse(data['${effectivePrefix}name']), + id: intType.mapFromDatabaseResponse(data['${effectivePrefix}id'])!, + name: stringType.mapFromDatabaseResponse(data['${effectivePrefix}name'])!, caloriesPer100g: - intType.mapFromDatabaseResponse(data['${effectivePrefix}calories']), + intType.mapFromDatabaseResponse(data['${effectivePrefix}calories'])!, ); } @override Map toColumns(bool nullToAbsent) { final map = {}; - if (!nullToAbsent || id != null) { - map['id'] = Variable(id); - } - if (!nullToAbsent || name != null) { - map['name'] = Variable(name); - } - if (!nullToAbsent || caloriesPer100g != null) { - map['calories'] = Variable(caloriesPer100g); - } + map['id'] = Variable(id); + map['name'] = Variable(name); + map['calories'] = Variable(caloriesPer100g); return map; } IngredientsCompanion toCompanion(bool nullToAbsent) { return IngredientsCompanion( - id: id == null && nullToAbsent ? const Value.absent() : Value(id), - name: name == null && nullToAbsent ? const Value.absent() : Value(name), - caloriesPer100g: caloriesPer100g == null && nullToAbsent - ? const Value.absent() - : Value(caloriesPer100g), + id: Value(id), + name: Value(name), + caloriesPer100g: Value(caloriesPer100g), ); } factory Ingredient.fromJson(Map json, - {ValueSerializer serializer}) { + {ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return Ingredient( id: serializer.fromJson(json['id']), @@ -550,12 +523,12 @@ class Ingredient extends DataClass implements Insertable { ); } factory Ingredient.fromJsonString(String encodedJson, - {ValueSerializer serializer}) => + {ValueSerializer? serializer}) => Ingredient.fromJson( DataClass.parseJson(encodedJson) as Map, serializer: serializer); @override - Map toJson({ValueSerializer serializer}) { + Map toJson({ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return { 'id': serializer.toJson(id), @@ -564,7 +537,8 @@ class Ingredient extends DataClass implements Insertable { }; } - Ingredient copyWith({int id, String name, int caloriesPer100g}) => Ingredient( + Ingredient copyWith({int? id, String? name, int? caloriesPer100g}) => + Ingredient( id: id ?? this.id, name: name ?? this.name, caloriesPer100g: caloriesPer100g ?? this.caloriesPer100g, @@ -602,14 +576,14 @@ class IngredientsCompanion extends UpdateCompanion { }); IngredientsCompanion.insert({ this.id = const Value.absent(), - @required String name, - @required int caloriesPer100g, - }) : name = Value(name), + required String name, + required int caloriesPer100g, + }) : name = Value(name), caloriesPer100g = Value(caloriesPer100g); static Insertable custom({ - Expression id, - Expression name, - Expression caloriesPer100g, + Expression? id, + Expression? name, + Expression? caloriesPer100g, }) { return RawValuesInsertable({ if (id != null) 'id': id, @@ -619,7 +593,7 @@ class IngredientsCompanion extends UpdateCompanion { } IngredientsCompanion copyWith( - {Value id, Value name, Value caloriesPer100g}) { + {Value? id, Value? name, Value? caloriesPer100g}) { return IngredientsCompanion( id: id ?? this.id, name: name ?? this.name, @@ -656,21 +630,19 @@ class IngredientsCompanion extends UpdateCompanion { class $IngredientsTable extends Ingredients with TableInfo<$IngredientsTable, Ingredient> { final GeneratedDatabase _db; - final String _alias; + final String? _alias; $IngredientsTable(this._db, [this._alias]); final VerificationMeta _idMeta = const VerificationMeta('id'); - GeneratedIntColumn _id; @override - GeneratedIntColumn get id => _id ??= _constructId(); + late final GeneratedIntColumn id = _constructId(); GeneratedIntColumn _constructId() { return GeneratedIntColumn('id', $tableName, false, hasAutoIncrement: true, declaredAsPrimaryKey: true); } final VerificationMeta _nameMeta = const VerificationMeta('name'); - GeneratedTextColumn _name; @override - GeneratedTextColumn get name => _name ??= _constructName(); + late final GeneratedTextColumn name = _constructName(); GeneratedTextColumn _constructName() { return GeneratedTextColumn( 'name', @@ -681,10 +653,8 @@ class $IngredientsTable extends Ingredients final VerificationMeta _caloriesPer100gMeta = const VerificationMeta('caloriesPer100g'); - GeneratedIntColumn _caloriesPer100g; @override - GeneratedIntColumn get caloriesPer100g => - _caloriesPer100g ??= _constructCaloriesPer100g(); + late final GeneratedIntColumn caloriesPer100g = _constructCaloriesPer100g(); GeneratedIntColumn _constructCaloriesPer100g() { return GeneratedIntColumn( 'calories', @@ -707,11 +677,11 @@ class $IngredientsTable extends Ingredients final context = VerificationContext(); final data = instance.toColumns(true); if (data.containsKey('id')) { - context.handle(_idMeta, id.isAcceptableOrUnknown(data['id'], _idMeta)); + context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); } if (data.containsKey('name')) { context.handle( - _nameMeta, name.isAcceptableOrUnknown(data['name'], _nameMeta)); + _nameMeta, name.isAcceptableOrUnknown(data['name']!, _nameMeta)); } else if (isInserting) { context.missing(_nameMeta); } @@ -719,7 +689,7 @@ class $IngredientsTable extends Ingredients context.handle( _caloriesPer100gMeta, caloriesPer100g.isAcceptableOrUnknown( - data['calories'], _caloriesPer100gMeta)); + data['calories']!, _caloriesPer100gMeta)); } else if (isInserting) { context.missing(_caloriesPer100gMeta); } @@ -729,7 +699,7 @@ class $IngredientsTable extends Ingredients @override Set get $primaryKey => {id}; @override - Ingredient map(Map data, {String tablePrefix}) { + Ingredient map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; return Ingredient.fromData(data, _db, prefix: effectivePrefix); } @@ -746,52 +716,42 @@ class IngredientInRecipe extends DataClass final int ingredient; final int amountInGrams; IngredientInRecipe( - {@required this.recipe, - @required this.ingredient, - @required this.amountInGrams}); + {required this.recipe, + required this.ingredient, + required this.amountInGrams}); factory IngredientInRecipe.fromData( Map data, GeneratedDatabase db, - {String prefix}) { + {String? prefix}) { final effectivePrefix = prefix ?? ''; final intType = db.typeSystem.forDartType(); return IngredientInRecipe( - recipe: intType.mapFromDatabaseResponse(data['${effectivePrefix}recipe']), - ingredient: - intType.mapFromDatabaseResponse(data['${effectivePrefix}ingredient']), + recipe: + intType.mapFromDatabaseResponse(data['${effectivePrefix}recipe'])!, + ingredient: intType + .mapFromDatabaseResponse(data['${effectivePrefix}ingredient'])!, amountInGrams: - intType.mapFromDatabaseResponse(data['${effectivePrefix}amount']), + intType.mapFromDatabaseResponse(data['${effectivePrefix}amount'])!, ); } @override Map toColumns(bool nullToAbsent) { final map = {}; - if (!nullToAbsent || recipe != null) { - map['recipe'] = Variable(recipe); - } - if (!nullToAbsent || ingredient != null) { - map['ingredient'] = Variable(ingredient); - } - if (!nullToAbsent || amountInGrams != null) { - map['amount'] = Variable(amountInGrams); - } + map['recipe'] = Variable(recipe); + map['ingredient'] = Variable(ingredient); + map['amount'] = Variable(amountInGrams); return map; } IngredientInRecipesCompanion toCompanion(bool nullToAbsent) { return IngredientInRecipesCompanion( - recipe: - recipe == null && nullToAbsent ? const Value.absent() : Value(recipe), - ingredient: ingredient == null && nullToAbsent - ? const Value.absent() - : Value(ingredient), - amountInGrams: amountInGrams == null && nullToAbsent - ? const Value.absent() - : Value(amountInGrams), + recipe: Value(recipe), + ingredient: Value(ingredient), + amountInGrams: Value(amountInGrams), ); } factory IngredientInRecipe.fromJson(Map json, - {ValueSerializer serializer}) { + {ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return IngredientInRecipe( recipe: serializer.fromJson(json['recipe']), @@ -800,12 +760,12 @@ class IngredientInRecipe extends DataClass ); } factory IngredientInRecipe.fromJsonString(String encodedJson, - {ValueSerializer serializer}) => + {ValueSerializer? serializer}) => IngredientInRecipe.fromJson( DataClass.parseJson(encodedJson) as Map, serializer: serializer); @override - Map toJson({ValueSerializer serializer}) { + Map toJson({ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return { 'recipe': serializer.toJson(recipe), @@ -815,7 +775,7 @@ class IngredientInRecipe extends DataClass } IngredientInRecipe copyWith( - {int recipe, int ingredient, int amountInGrams}) => + {int? recipe, int? ingredient, int? amountInGrams}) => IngredientInRecipe( recipe: recipe ?? this.recipe, ingredient: ingredient ?? this.ingredient, @@ -853,16 +813,16 @@ class IngredientInRecipesCompanion extends UpdateCompanion { this.amountInGrams = const Value.absent(), }); IngredientInRecipesCompanion.insert({ - @required int recipe, - @required int ingredient, - @required int amountInGrams, - }) : recipe = Value(recipe), + required int recipe, + required int ingredient, + required int amountInGrams, + }) : recipe = Value(recipe), ingredient = Value(ingredient), amountInGrams = Value(amountInGrams); static Insertable custom({ - Expression recipe, - Expression ingredient, - Expression amountInGrams, + Expression? recipe, + Expression? ingredient, + Expression? amountInGrams, }) { return RawValuesInsertable({ if (recipe != null) 'recipe': recipe, @@ -872,7 +832,7 @@ class IngredientInRecipesCompanion extends UpdateCompanion { } IngredientInRecipesCompanion copyWith( - {Value recipe, Value ingredient, Value amountInGrams}) { + {Value? recipe, Value? ingredient, Value? amountInGrams}) { return IngredientInRecipesCompanion( recipe: recipe ?? this.recipe, ingredient: ingredient ?? this.ingredient, @@ -909,12 +869,11 @@ class IngredientInRecipesCompanion extends UpdateCompanion { class $IngredientInRecipesTable extends IngredientInRecipes with TableInfo<$IngredientInRecipesTable, IngredientInRecipe> { final GeneratedDatabase _db; - final String _alias; + final String? _alias; $IngredientInRecipesTable(this._db, [this._alias]); final VerificationMeta _recipeMeta = const VerificationMeta('recipe'); - GeneratedIntColumn _recipe; @override - GeneratedIntColumn get recipe => _recipe ??= _constructRecipe(); + late final GeneratedIntColumn recipe = _constructRecipe(); GeneratedIntColumn _constructRecipe() { return GeneratedIntColumn( 'recipe', @@ -924,9 +883,8 @@ class $IngredientInRecipesTable extends IngredientInRecipes } final VerificationMeta _ingredientMeta = const VerificationMeta('ingredient'); - GeneratedIntColumn _ingredient; @override - GeneratedIntColumn get ingredient => _ingredient ??= _constructIngredient(); + late final GeneratedIntColumn ingredient = _constructIngredient(); GeneratedIntColumn _constructIngredient() { return GeneratedIntColumn( 'ingredient', @@ -937,10 +895,8 @@ class $IngredientInRecipesTable extends IngredientInRecipes final VerificationMeta _amountInGramsMeta = const VerificationMeta('amountInGrams'); - GeneratedIntColumn _amountInGrams; @override - GeneratedIntColumn get amountInGrams => - _amountInGrams ??= _constructAmountInGrams(); + late final GeneratedIntColumn amountInGrams = _constructAmountInGrams(); GeneratedIntColumn _constructAmountInGrams() { return GeneratedIntColumn( 'amount', @@ -964,7 +920,7 @@ class $IngredientInRecipesTable extends IngredientInRecipes final data = instance.toColumns(true); if (data.containsKey('recipe')) { context.handle(_recipeMeta, - recipe.isAcceptableOrUnknown(data['recipe'], _recipeMeta)); + recipe.isAcceptableOrUnknown(data['recipe']!, _recipeMeta)); } else if (isInserting) { context.missing(_recipeMeta); } @@ -972,7 +928,7 @@ class $IngredientInRecipesTable extends IngredientInRecipes context.handle( _ingredientMeta, ingredient.isAcceptableOrUnknown( - data['ingredient'], _ingredientMeta)); + data['ingredient']!, _ingredientMeta)); } else if (isInserting) { context.missing(_ingredientMeta); } @@ -980,7 +936,7 @@ class $IngredientInRecipesTable extends IngredientInRecipes context.handle( _amountInGramsMeta, amountInGrams.isAcceptableOrUnknown( - data['amount'], _amountInGramsMeta)); + data['amount']!, _amountInGramsMeta)); } else if (isInserting) { context.missing(_amountInGramsMeta); } @@ -990,7 +946,7 @@ class $IngredientInRecipesTable extends IngredientInRecipes @override Set get $primaryKey => {recipe, ingredient}; @override - IngredientInRecipe map(Map data, {String tablePrefix}) { + IngredientInRecipe map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; return IngredientInRecipe.fromData(data, _db, prefix: effectivePrefix); } @@ -1004,15 +960,11 @@ class $IngredientInRecipesTable extends IngredientInRecipes abstract class _$Database extends GeneratedDatabase { _$Database(QueryExecutor e) : super(SqlTypeSystem.defaultInstance, e); _$Database.connect(DatabaseConnection c) : super.connect(c); - $CategoriesTable _categories; - $CategoriesTable get categories => _categories ??= $CategoriesTable(this); - $RecipesTable _recipes; - $RecipesTable get recipes => _recipes ??= $RecipesTable(this); - $IngredientsTable _ingredients; - $IngredientsTable get ingredients => _ingredients ??= $IngredientsTable(this); - $IngredientInRecipesTable _ingredientInRecipes; - $IngredientInRecipesTable get ingredientInRecipes => - _ingredientInRecipes ??= $IngredientInRecipesTable(this); + late final $CategoriesTable categories = $CategoriesTable(this); + late final $RecipesTable recipes = $RecipesTable(this); + late final $IngredientsTable ingredients = $IngredientsTable(this); + late final $IngredientInRecipesTable ingredientInRecipes = + $IngredientInRecipesTable(this); Selectable totalWeight() { return customSelect( 'SELECT r.title, SUM(ir.amount) AS total_weight\n FROM recipes r\n INNER JOIN recipe_ingredients ir ON ir.recipe = r.id\n GROUP BY r.id', @@ -1037,9 +989,9 @@ class TotalWeightResult extends CustomResultSet { final String title; final int totalWeight; TotalWeightResult({ - @required QueryRow row, - this.title, - this.totalWeight, + required QueryRow row, + required this.title, + required this.totalWeight, }) : super(row); @override int get hashCode => $mrjf($mrjc(title.hashCode, totalWeight.hashCode)); diff --git a/moor/lib/extensions/json1.dart b/moor/lib/extensions/json1.dart index 123ff8e8..502a7509 100644 --- a/moor/lib/extensions/json1.dart +++ b/moor/lib/extensions/json1.dart @@ -12,7 +12,7 @@ import 'package:meta/meta.dart'; import '../moor.dart'; /// Defines extensions on string expressions to support the json1 api from Dart. -extension JsonExtensions on Expression { +extension JsonExtensions on Expression { /// Assuming that this string is a json array, returns the length of this json /// array. /// @@ -28,7 +28,7 @@ extension JsonExtensions on Expression { /// /// See also: /// - the [sqlite documentation for this function](https://www.sqlite.org/json1.html#the_json_array_length_function) - Expression jsonArrayLength([String path]) { + Expression jsonArrayLength([String? path]) { return FunctionCallExpression('json_array_length', [ this, if (path != null) Variable.withString(path), diff --git a/moor/lib/extensions/moor_ffi.dart b/moor/lib/extensions/moor_ffi.dart index b78ab64e..5d9f9253 100644 --- a/moor/lib/extensions/moor_ffi.dart +++ b/moor/lib/extensions/moor_ffi.dart @@ -11,7 +11,7 @@ import 'package:moor/moor.dart'; /// instead of `NaN`. /// /// This function is only available when using `moor_ffi`. -Expression sqlPow(Expression base, Expression exponent) { +Expression sqlPow(Expression base, Expression exponent) { return FunctionCallExpression('pow', [base, exponent]); } @@ -21,7 +21,7 @@ Expression sqlPow(Expression base, Expression exponent) { /// of `NaN` for negative values. /// /// This function is only available when using `moor_ffi`. -Expression sqlSqrt(Expression value) { +Expression sqlSqrt(Expression value) { return FunctionCallExpression('sqrt', [value]); } @@ -30,7 +30,7 @@ Expression sqlSqrt(Expression value) { /// This function is equivalent to [sin]. /// /// This function is only available when using `moor_ffi`. -Expression sqlSin(Expression value) { +Expression sqlSin(Expression value) { return FunctionCallExpression('sin', [value]); } @@ -39,7 +39,7 @@ Expression sqlSin(Expression value) { /// This function is equivalent to [sin]. /// /// This function is only available when using `moor_ffi`. -Expression sqlCos(Expression value) { +Expression sqlCos(Expression value) { return FunctionCallExpression('cos', [value]); } @@ -48,7 +48,7 @@ Expression sqlCos(Expression value) { /// This function is equivalent to [tan]. /// /// This function is only available when using `moor_ffi`. -Expression sqlTan(Expression value) { +Expression sqlTan(Expression value) { return FunctionCallExpression('tan', [value]); } @@ -58,7 +58,7 @@ Expression sqlTan(Expression value) { /// instead of `NaN`. /// /// This function is only available when using `moor_ffi`. -Expression sqlAsin(Expression value) { +Expression sqlAsin(Expression value) { return FunctionCallExpression('asin', [value]); } @@ -68,7 +68,7 @@ Expression sqlAsin(Expression value) { /// instead of `NaN`. /// /// This function is only available when using `moor_ffi`. -Expression sqlAcos(Expression value) { +Expression sqlAcos(Expression value) { return FunctionCallExpression('acos', [value]); } @@ -78,13 +78,13 @@ Expression sqlAcos(Expression value) { /// instead of `NaN`. /// /// This function is only available when using `moor_ffi`. -Expression sqlAtan(Expression value) { +Expression sqlAtan(Expression value) { return FunctionCallExpression('atan', [value]); } /// Adds functionality to string expressions that only work when using /// `moor_ffi`. -extension MoorFfiSpecificStringExtensions on Expression { +extension MoorFfiSpecificStringExtensions on Expression { /// Version of `contains` that allows controlling case sensitivity better. /// /// The default `contains` method uses sqlite's `LIKE`, which is case- @@ -102,7 +102,7 @@ extension MoorFfiSpecificStringExtensions on Expression { /// /// Note that this is only available when using `moor_ffi` version 0.6.0 or /// greater. - Expression containsCase(String substring, + Expression containsCase(String substring, {bool caseSensitive = false}) { return FunctionCallExpression('moor_contains', [ this, diff --git a/moor/lib/src/dsl/columns.dart b/moor/lib/src/dsl/columns.dart index feb300fd..bb026dfd 100644 --- a/moor/lib/src/dsl/columns.dart +++ b/moor/lib/src/dsl/columns.dart @@ -8,24 +8,24 @@ abstract class Column extends Expression { } /// A column that stores int values. -abstract class IntColumn extends Column {} +abstract class IntColumn extends Column {} /// A column that stores boolean values. Booleans will be stored as an integer /// that can either be 0 (false) or 1 (true). -abstract class BoolColumn extends Column {} +abstract class BoolColumn extends Column {} /// A column that stores text. -abstract class TextColumn extends Column {} +abstract class TextColumn extends Column {} /// A column that stores a [DateTime]. Times will be stored as unix timestamp /// and will thus have a second accuracy. -abstract class DateTimeColumn extends Column {} +abstract class DateTimeColumn extends Column {} /// A column that stores arbitrary blobs of data as a [Uint8List]. -abstract class BlobColumn extends Column {} +abstract class BlobColumn extends Column {} /// A column that stores floating point numeric values. -abstract class RealColumn extends Column {} +abstract class RealColumn extends Column {} /// A column builder is used to specify which columns should appear in a table. /// All of the methods defined in this class and its subclasses are not meant to @@ -173,7 +173,8 @@ class ColumnBuilder, /// Tells the generator to build an [IntColumn]. See the docs at [ColumnBuilder] /// for details. -class IntColumnBuilder extends ColumnBuilder { +class IntColumnBuilder + extends ColumnBuilder { /// Enables auto-increment for this column, which will also make this column /// the primary key of the table. /// @@ -185,35 +186,37 @@ class IntColumnBuilder extends ColumnBuilder { /// Tells the generator to build an [BoolColumn]. See the docs at /// [ColumnBuilder] for details. class BoolColumnBuilder - extends ColumnBuilder {} + extends ColumnBuilder {} /// Tells the generator to build an [BlobColumn]. See the docs at /// [ColumnBuilder] for details. class BlobColumnBuilder - extends ColumnBuilder {} + extends ColumnBuilder {} /// Tells the generator to build an [RealColumn]. See the docs at /// [ColumnBuilder] for details. class RealColumnBuilder - extends ColumnBuilder {} + extends ColumnBuilder {} /// Tells the generator to build an [TextColumn]. See the docs at /// [ColumnBuilder] for details. class TextColumnBuilder - extends ColumnBuilder { + extends ColumnBuilder { /// Puts a constraint on the minimum and maximum length of text that can be - /// stored in this column (will be validated whenever this column is updated - /// or a value is inserted). If [min] is not null and one tries to write a - /// string so that [String.length] is smaller than [min], the query will throw - /// an exception when executed and no data will be written. The same applies - /// for [max]. - TextColumnBuilder withLength({int min, int max}) => _isGenerated(); + /// stored in this column. + /// + /// Both [min] and [max] are inclusive. This constraint will be validated in + /// Dart, it doesn't have an impact on the database schema. If [min] is not + /// null and one tries to write a string which [String.length] is + /// _strictly less_ than [min], an exception will be thrown. Similarly, you + /// can't insert strings with a length _strictly greater_ than [max]. + TextColumnBuilder withLength({int? min, int? max}) => _isGenerated(); } /// Tells the generator to build an [DateTimeColumn]. See the docs at /// [ColumnBuilder] for details. class DateTimeColumnBuilder - extends ColumnBuilder {} + extends ColumnBuilder {} /// Annotation to use on column getters inside of a [Table] to define the name /// of the column in the json used by [DataClass.toJson]. diff --git a/moor/lib/src/dsl/dsl.dart b/moor/lib/src/dsl/dsl.dart index f5ae4a2f..8031e4bf 100644 --- a/moor/lib/src/dsl/dsl.dart +++ b/moor/lib/src/dsl/dsl.dart @@ -30,7 +30,7 @@ part 'table.dart'; /// ); /// } /// ``` -Null /* = Never */ _isGenerated() { +Never _isGenerated() { throw UnsupportedError( 'This method should not be called at runtime. Are you sure you re-ran the ' 'builder after changing your tables or databases?', diff --git a/moor/lib/src/dsl/table.dart b/moor/lib/src/dsl/table.dart index 677df8ff..c24da559 100644 --- a/moor/lib/src/dsl/table.dart +++ b/moor/lib/src/dsl/table.dart @@ -15,7 +15,7 @@ abstract class Table { /// valid, whereas `@override final String tableName = 'my_table';` or /// `@override String get tableName => createMyTableName();` is not. @visibleForOverriding - String get tableName => null; + String? get tableName => null; /// Whether to append a `WITHOUT ROWID` clause in the `CREATE TABLE` /// statement. This is intended to be used by generated code only. @@ -45,7 +45,7 @@ abstract class Table { /// As an auto-incremented `IntColumn` is recognized by moor to be the /// primary key, doing so will result in an exception thrown at runtime. @visibleForOverriding - Set get primaryKey => null; + Set? get primaryKey => null; /// Custom table constraints that should be added to the table. /// diff --git a/moor/lib/src/ffi/moor_ffi_functions.dart b/moor/lib/src/ffi/moor_ffi_functions.dart index 9c2c9db8..0a2971da 100644 --- a/moor/lib/src/ffi/moor_ffi_functions.dart +++ b/moor/lib/src/ffi/moor_ffi_functions.dart @@ -96,12 +96,12 @@ extension EnableMoorFunctions on Database { deterministic: true, directOnly: false, argumentCount: const AllowedArgumentCount(0), - function: (List args) => DateTime.now().millisecondsSinceEpoch, + function: (List args) => DateTime.now().millisecondsSinceEpoch, ); } } -num _pow(List args) { +num? _pow(List args) { final first = args[0]; final second = args[1]; @@ -109,7 +109,7 @@ num _pow(List args) { return null; } - return pow(first as num, second as num); + return pow(first, second); } /// Base implementation for a sqlite function that takes one numerical argument @@ -117,8 +117,8 @@ num _pow(List args) { /// /// When not called with a number, returns will null. Otherwise, returns with /// [calculation]. -num Function(List) _unaryNumFunction(num Function(num) calculation) { - return (List args) { +num? Function(List) _unaryNumFunction(num Function(num) calculation) { + return (List args) { // sqlite will ensure that this is only called with one argument final value = args[0]; if (value is num) { @@ -129,7 +129,7 @@ num Function(List) _unaryNumFunction(num Function(num) calculation) { }; } -bool _regexpImpl(List args) { +bool? _regexpImpl(List args) { var multiLine = false; var caseSensitive = true; var unicode = false; @@ -165,7 +165,7 @@ bool _regexpImpl(List args) { RegExp regex; try { regex = RegExp( - firstParam as String, + firstParam, multiLine: multiLine, caseSensitive: caseSensitive, unicode: unicode, @@ -175,7 +175,7 @@ bool _regexpImpl(List args) { throw 'Invalid regex'; } - return regex.hasMatch(secondParam as String); + return regex.hasMatch(secondParam); } bool _containsImpl(List args) { @@ -193,12 +193,9 @@ bool _containsImpl(List args) { final caseSensitive = argCount == 3 && args[2] == 1; - final firstAsString = first as String; - final secondAsString = second as String; - final result = caseSensitive - ? firstAsString.contains(secondAsString) - : firstAsString.toLowerCase().contains(secondAsString.toLowerCase()); + ? first.contains(second) + : first.toLowerCase().contains(second.toLowerCase()); return result; } diff --git a/moor/lib/src/ffi/vm_database.dart b/moor/lib/src/ffi/vm_database.dart index 85f41b76..4b0c21b7 100644 --- a/moor/lib/src/ffi/vm_database.dart +++ b/moor/lib/src/ffi/vm_database.dart @@ -32,14 +32,15 @@ class VmDatabase extends DelegatedDatabase { /// SQLCipher implementations. /// {@endtemplate} factory VmDatabase(File file, - {bool logStatements = false, DatabaseSetup setup}) { + {bool logStatements = false, DatabaseSetup? setup}) { return VmDatabase._(_VmDelegate(file, setup), logStatements); } /// Creates an in-memory database won't persist its changes on disk. /// /// {@macro moor_vm_database_factory} - factory VmDatabase.memory({bool logStatements = false, DatabaseSetup setup}) { + factory VmDatabase.memory( + {bool logStatements = false, DatabaseSetup? setup}) { return VmDatabase._(_VmDelegate(null, setup), logStatements); } @@ -51,7 +52,7 @@ class VmDatabase extends DelegatedDatabase { /// /// {@macro moor_vm_database_factory} factory VmDatabase.opened(Database database, - {bool logStatements = false, DatabaseSetup setup}) { + {bool logStatements = false, DatabaseSetup? setup}) { return VmDatabase._(_VmDelegate._opened(database, setup), logStatements); } @@ -106,11 +107,11 @@ class VmDatabase extends DelegatedDatabase { } class _VmDelegate extends DatabaseDelegate { - Database _db; + late Database _db; bool _isOpen = false; - final File file; - final DatabaseSetup setup; + final File? file; + final DatabaseSetup? setup; _VmDelegate(this.file, this.setup); @@ -122,14 +123,14 @@ class _VmDelegate extends DatabaseDelegate { TransactionDelegate get transactionDelegate => const NoTransactionDelegate(); @override - DbVersionDelegate versionDelegate; + late DbVersionDelegate versionDelegate; @override Future get isOpen => Future.value(_isOpen); @override Future open(QueryExecutorUser user) async { - if (_db == null) { + if (!_isOpen) { _createDatabase(); } _initializeDatabase(); @@ -138,7 +139,9 @@ class _VmDelegate extends DatabaseDelegate { } void _createDatabase() { - assert(_db == null); + assert(!_isOpen); + + final file = this.file; if (file != null) { // Create the parent directory if it doesn't exist. sqlite will emit // confusing misuse warnings otherwise @@ -156,9 +159,7 @@ class _VmDelegate extends DatabaseDelegate { void _initializeDatabase() { _db.useMoorVersions(); - if (setup != null) { - setup(_db); - } + setup?.call(_db); versionDelegate = _VmVersionDelegate(_db); } @@ -181,7 +182,7 @@ class _VmDelegate extends DatabaseDelegate { return Future.value(); } - Future _runWithArgs(String statement, List args) async { + Future _runWithArgs(String statement, List args) async { if (args.isEmpty) { _db.execute(statement); } else { @@ -192,24 +193,24 @@ class _VmDelegate extends DatabaseDelegate { } @override - Future runCustom(String statement, List args) async { + Future runCustom(String statement, List args) async { await _runWithArgs(statement, args); } @override - Future runInsert(String statement, List args) async { + Future runInsert(String statement, List args) async { await _runWithArgs(statement, args); return _db.lastInsertRowId; } @override - Future runUpdate(String statement, List args) async { + Future runUpdate(String statement, List args) async { await _runWithArgs(statement, args); return _db.getUpdatedRows(); } @override - Future runSelect(String statement, List args) async { + Future runSelect(String statement, List args) async { final stmt = _db.prepare(statement); final result = stmt.select(args); stmt.dispose(); diff --git a/moor/lib/src/runtime/api/batch.dart b/moor/lib/src/runtime/api/batch.dart index 1ac942f0..4f00c795 100644 --- a/moor/lib/src/runtime/api/batch.dart +++ b/moor/lib/src/runtime/api/batch.dart @@ -38,7 +38,7 @@ class Batch { /// - [InsertStatement.insert], which would be used outside a [Batch]. void insert( TableInfo table, Insertable row, - {InsertMode mode, DoUpdate onConflict}) { + {InsertMode? mode, DoUpdate? onConflict}) { _addUpdate(table, UpdateKind.insert); final actualMode = mode ?? InsertMode.insert; final context = InsertStatement(_engine, table) @@ -60,7 +60,7 @@ class Batch { /// support it. For details and examples, see [InsertStatement.insert]. void insertAll( TableInfo table, List> rows, - {InsertMode mode, DoUpdate onConflict}) { + {InsertMode? mode, DoUpdate? onConflict}) { for (final row in rows) { insert(table, row, mode: mode, onConflict: onConflict); } @@ -82,7 +82,7 @@ class Batch { /// [UpdateStatement.write] or the [documentation with examples](https://moor.simonbinder.eu/docs/getting-started/writing_queries/#updates-and-deletes) void update( TableInfo table, Insertable row, - {Expression Function(T table) where}) { + {Expression Function(T table)? where}) { _addUpdate(table, UpdateKind.update); final stmt = UpdateStatement(_engine, table); if (where != null) stmt.where(where); @@ -148,8 +148,8 @@ class Batch { /// See also: /// - [QueryEngine.customStatement], the equivalent method outside of /// batches. - void customStatement(String sql, [List args]) { - _addSqlAndArguments(sql, args); + void customStatement(String sql, [List? args]) { + _addSqlAndArguments(sql, args ?? const []); } void _addContext(GenerationContext ctx) { @@ -171,17 +171,17 @@ class Batch { await _engine.executor.ensureOpen(_engine.attachedDatabase); if (_startTransaction) { - TransactionExecutor transaction; + TransactionExecutor? transaction; try { transaction = _engine.executor.beginTransaction(); - await transaction.ensureOpen(null); + await transaction.ensureOpen(_engine.attachedDatabase); await _runWith(transaction); await transaction.send(); } catch (e) { - await transaction.rollback(); + await transaction?.rollback(); rethrow; } } else { diff --git a/moor/lib/src/runtime/api/connection.dart b/moor/lib/src/runtime/api/connection.dart index 2567d81d..5f246228 100644 --- a/moor/lib/src/runtime/api/connection.dart +++ b/moor/lib/src/runtime/api/connection.dart @@ -52,12 +52,10 @@ class DatabaseConnection { return connection; } - final future = connection as Future; - return DatabaseConnection( SqlTypeSystem.defaultInstance, - LazyDatabase(() async => (await future).executor), - DelayedStreamQueryStore(future.then((conn) => conn.streamQueries)), + LazyDatabase(() async => (await connection).executor), + DelayedStreamQueryStore(connection.then((conn) => conn.streamQueries)), ); } @@ -89,16 +87,16 @@ abstract class DatabaseConnectionUser { /// 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}) + {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}) + {SqlTypeSystem? typeSystem, + QueryExecutor? executor, + StreamQueryStore? streamQueries}) : connection = DatabaseConnection( typeSystem ?? other.connection.typeSystem, executor ?? other.connection.executor, diff --git a/moor/lib/src/runtime/api/db_base.dart b/moor/lib/src/runtime/api/db_base.dart index 26c7e7d7..260fef25 100644 --- a/moor/lib/src/runtime/api/db_base.dart +++ b/moor/lib/src/runtime/api/db_base.dart @@ -30,7 +30,7 @@ abstract class GeneratedDatabase extends DatabaseConnectionUser /// changes in your schema, you'll need a custom migration strategy to create /// the new tables or change the columns. MigrationStrategy get migration => MigrationStrategy(); - MigrationStrategy _cachedMigration; + MigrationStrategy? _cachedMigration; MigrationStrategy get _resolvedMigration => _cachedMigration ??= migration; /// The collection of update rules contains information on how updates on @@ -58,7 +58,7 @@ abstract class GeneratedDatabase extends DatabaseConnectionUser /// Used by generated code GeneratedDatabase(SqlTypeSystem types, QueryExecutor executor, - {StreamQueryStore streamStore}) + {StreamQueryStore? streamStore}) : super(types, executor, streamQueries: streamStore) { assert(_handleInstantiated()); } @@ -75,7 +75,9 @@ abstract class GeneratedDatabase extends DatabaseConnectionUser _openedDbCount[runtimeType] = 1; return true; } - final count = ++_openedDbCount[runtimeType]; + + final count = + _openedDbCount[runtimeType] = _openedDbCount[runtimeType]! + 1; if (count > 1) { // ignore: avoid_print print( @@ -117,7 +119,7 @@ abstract class GeneratedDatabase extends DatabaseConnectionUser } else if (details.hadUpgrade) { final migrator = createMigrator(); await _resolvedMigration.onUpgrade( - migrator, details.versionBefore, details.versionNow); + migrator, details.versionBefore!, details.versionNow); } await _resolvedMigration.beforeOpen?.call(details); @@ -131,7 +133,7 @@ abstract class GeneratedDatabase extends DatabaseConnectionUser assert(() { if (_openedDbCount[runtimeType] != null) { - _openedDbCount[runtimeType]--; + _openedDbCount[runtimeType] = _openedDbCount[runtimeType]! - 1; } return true; }()); diff --git a/moor/lib/src/runtime/api/query_engine.dart b/moor/lib/src/runtime/api/query_engine.dart index 12a5f857..7cebdea5 100644 --- a/moor/lib/src/runtime/api/query_engine.dart +++ b/moor/lib/src/runtime/api/query_engine.dart @@ -47,7 +47,7 @@ mixin QueryEngine on DatabaseConnectionUser { // 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; + return (resolved as QueryEngine?) ?? this; } } @@ -201,8 +201,8 @@ mixin QueryEngine on DatabaseConnectionUser { Future customUpdate( String query, { List variables = const [], - Set updates, - UpdateKind updateKind, + Set? updates, + UpdateKind? updateKind, }) async { return _customWrite( query, @@ -221,7 +221,7 @@ mixin QueryEngine on DatabaseConnectionUser { /// [updates] parameter. Query-streams running on any of these tables will /// then be re-run. Future customInsert(String query, - {List variables = const [], Set updates}) { + {List variables = const [], Set? updates}) { return _customWrite( query, variables, @@ -239,8 +239,8 @@ mixin QueryEngine on DatabaseConnectionUser { Future _customWrite( String query, List variables, - Set updates, - UpdateKind updateKind, + Set? updates, + UpdateKind? updateKind, _CustomWriter writer, ) async { final engine = _resolvedEngine; @@ -273,7 +273,6 @@ mixin QueryEngine on DatabaseConnectionUser { Selectable customSelect(String query, {List variables = const [], Set readsFrom = const {}}) { - readsFrom ??= {}; return CustomSelectStatement(query, variables, readsFrom, _resolvedEngine); } @@ -294,7 +293,7 @@ mixin QueryEngine on DatabaseConnectionUser { } /// Executes the custom sql [statement] on the database. - Future customStatement(String statement, [List args]) { + Future customStatement(String statement, [List? args]) { final engine = _resolvedEngine; return engine.doWhenOpened((executor) { @@ -408,7 +407,7 @@ mixin QueryEngine on DatabaseConnectionUser { /// Will be used by generated code to resolve inline Dart components in sql. @protected - GenerationContext $write(Component component, {bool hasMultipleTables}) { + GenerationContext $write(Component component, {bool? hasMultipleTables}) { final context = GenerationContext.fromDb(this); if (hasMultipleTables != null) { context.hasMultipleTables = hasMultipleTables; diff --git a/moor/lib/src/runtime/api/stream_updates.dart b/moor/lib/src/runtime/api/stream_updates.dart index cb51c516..39a8ebd9 100644 --- a/moor/lib/src/runtime/api/stream_updates.dart +++ b/moor/lib/src/runtime/api/stream_updates.dart @@ -60,8 +60,7 @@ class WritePropagation extends UpdateRule { final List result; /// Default constructor. See [WritePropagation] for details. - const WritePropagation({@required this.on, @required this.result}) - : super._(); + const WritePropagation({required this.on, required this.result}) : super._(); } /// Classifies a [TableUpdate] by what kind of write happened - an insert, an @@ -83,7 +82,7 @@ class TableUpdate { /// What kind of update was applied to the [table]. /// /// Can be null, which indicates that the update is not known. - final UpdateKind /*?*/ kind; + final UpdateKind? kind; /// Name of the table that was updated. final String table; @@ -93,7 +92,7 @@ class TableUpdate { /// Creates a [TableUpdate] instance based on a [TableInfo] instead of the raw /// name. - factory TableUpdate.onTable(TableInfo table, {UpdateKind kind}) { + factory TableUpdate.onTable(TableInfo table, {UpdateKind? kind}) { return TableUpdate(table.actualTableName, kind: kind); } @@ -131,14 +130,14 @@ abstract class TableUpdateQuery { /// The optional [limitUpdateKind] parameter can be used to limit the updates /// to a certain kind. const factory TableUpdateQuery.onTableName(String table, - {UpdateKind limitUpdateKind}) = SpecificUpdateQuery; + {UpdateKind? limitUpdateKind}) = SpecificUpdateQuery; /// A query that listens for all updates on a specific [table]. /// /// The optional [limitUpdateKind] parameter can be used to limit the updates /// to a certain kind. factory TableUpdateQuery.onTable(TableInfo table, - {UpdateKind limitUpdateKind}) { + {UpdateKind? limitUpdateKind}) { return TableUpdateQuery.onTableName( table.actualTableName, limitUpdateKind: limitUpdateKind, diff --git a/moor/lib/src/runtime/data_class.dart b/moor/lib/src/runtime/data_class.dart index 50730fb7..251223a1 100644 --- a/moor/lib/src/runtime/data_class.dart +++ b/moor/lib/src/runtime/data_class.dart @@ -32,13 +32,13 @@ abstract class DataClass { /// [json]. The [serializer] can be used to configure how individual values /// will be encoded. By default, [MoorRuntimeOptions.defaultSerializer] will /// be used. See [ValueSerializer.defaults] for details. - Map toJson({ValueSerializer serializer}); + Map toJson({ValueSerializer? serializer}); /// Converts this object into a json representation. The [serializer] can be /// used to configure how individual values will be encoded. By default, /// [MoorRuntimeOptions.defaultSerializer] will be used. See /// [ValueSerializer.defaults] for details. - String toJsonString({ValueSerializer serializer}) { + String toJsonString({ValueSerializer? serializer}) { return json.encode(toJson(serializer: serializer)); } @@ -73,11 +73,7 @@ abstract class UpdateCompanion implements Insertable { if (identical(this, other)) return true; if (other is! UpdateCompanion) return false; - return _mapEquality.equals( - // ignore: test_types_in_equals - (other as UpdateCompanion).toColumns(false), - toColumns(false), - ); + return _mapEquality.equals(other.toColumns(false), toColumns(false)); } } @@ -111,16 +107,20 @@ class Value { /// inserted or updated. final bool present; + final T? _value; + /// If this value is [present], contains the value to update or insert. - final T value; + T get value => _value as T; /// Create a (present) value by wrapping the [value] provided. - const Value(this.value) : present = true; + const Value(T value) + : _value = value, + present = true; /// Create an absent value that will not be written into the database, the /// default value or null will be used instead. const Value.absent() - : value = null, + : _value = null, present = false; @override @@ -164,20 +164,22 @@ class _DefaultValueSerializer extends ValueSerializer { @override T fromJson(dynamic json) { if (json == null) { - return null; + return null as T; } - if (T == DateTime) { + final _typeList = []; + + if (_typeList is List) { return DateTime.fromMillisecondsSinceEpoch(json as int) as T; } - if (T == double && json is int) { + if (_typeList is List && json is int) { return json.toDouble() as T; } // blobs are encoded as a regular json array, so we manually convert that to // a Uint8List - if (T == Uint8List && json is! Uint8List) { + if (_typeList is List && json is! Uint8List) { final asList = (json as List).cast(); return Uint8List.fromList(asList) as T; } diff --git a/moor/lib/src/runtime/data_verification.dart b/moor/lib/src/runtime/data_verification.dart index 48f5b496..e072f377 100644 --- a/moor/lib/src/runtime/data_verification.dart +++ b/moor/lib/src/runtime/data_verification.dart @@ -18,7 +18,7 @@ class VerificationResult { /// If not [success]-ful, contains a human readable description of what went /// wrong. - final String message; + final String? message; /// Used internally by moor const VerificationResult(this.success, this.message); diff --git a/moor/lib/src/runtime/exceptions.dart b/moor/lib/src/runtime/exceptions.dart index 4f6b9a33..8697c62c 100644 --- a/moor/lib/src/runtime/exceptions.dart +++ b/moor/lib/src/runtime/exceptions.dart @@ -23,14 +23,14 @@ class MoorWrappedException implements Exception { final String message; /// The underlying exception caught by moor - final dynamic cause; + final Object? cause; /// The original stacktrace when caught by moor - final StackTrace trace; + final StackTrace? trace; /// Creates a new [MoorWrappedException] to provide additional details about /// an underlying error from the database. - MoorWrappedException({this.message, this.cause, this.trace}); + MoorWrappedException({required this.message, this.cause, this.trace}); @override String toString() { diff --git a/moor/lib/src/runtime/executor/connection_pool.dart b/moor/lib/src/runtime/executor/connection_pool.dart index 3ddadb68..f6f71852 100644 --- a/moor/lib/src/runtime/executor/connection_pool.dart +++ b/moor/lib/src/runtime/executor/connection_pool.dart @@ -1,4 +1,3 @@ -import 'package:meta/meta.dart'; import 'package:moor/backends.dart'; import 'package:moor/moor.dart'; @@ -10,7 +9,7 @@ abstract class MultiExecutor extends QueryExecutor { /// with [write]. Select statements outside of a transaction are executed on /// [read]. factory MultiExecutor( - {@required QueryExecutor read, @required QueryExecutor write}) { + {required QueryExecutor read, required QueryExecutor write}) { return _MultiExecutorImpl(read, write); } @@ -44,28 +43,28 @@ class _MultiExecutorImpl extends MultiExecutor { } @override - Future runCustom(String statement, [List args]) async { + Future runCustom(String statement, [List? args]) async { await _writes.runCustom(statement, args); } @override - Future runDelete(String statement, List args) async { + Future runDelete(String statement, List args) async { return await _writes.runDelete(statement, args); } @override - Future runInsert(String statement, List args) async { + Future runInsert(String statement, List args) async { return await _writes.runInsert(statement, args); } @override - Future>> runSelect( - String statement, List args) async { + Future>> runSelect( + String statement, List args) async { return await _reads.runSelect(statement, args); } @override - Future runUpdate(String statement, List args) async { + Future runUpdate(String statement, List args) async { return await _writes.runUpdate(statement, args); } diff --git a/moor/lib/src/runtime/executor/delayed_stream_queries.dart b/moor/lib/src/runtime/executor/delayed_stream_queries.dart index 37dfd3a6..4d3f76ce 100644 --- a/moor/lib/src/runtime/executor/delayed_stream_queries.dart +++ b/moor/lib/src/runtime/executor/delayed_stream_queries.dart @@ -7,8 +7,8 @@ import 'stream_queries.dart'; /// This class is internal and should not be exposed to moor users. It's used /// through a delayed database connection. class DelayedStreamQueryStore implements StreamQueryStore { - Future _delegate; - StreamQueryStore _resolved; + late Future _delegate; + StreamQueryStore? _resolved; /// Creates a [StreamQueryStore] that will work after [delegate] is /// available. diff --git a/moor/lib/src/runtime/executor/executor.dart b/moor/lib/src/runtime/executor/executor.dart index 9ab31e15..2f511e57 100644 --- a/moor/lib/src/runtime/executor/executor.dart +++ b/moor/lib/src/runtime/executor/executor.dart @@ -23,23 +23,23 @@ abstract class QueryExecutor { /// Runs a select statement with the given variables and returns the raw /// results. - Future>> runSelect( - String statement, List args); + Future>> runSelect( + String statement, List args); /// Runs an insert statement with the given variables. Returns the row id or /// the auto_increment id of the inserted row. - Future runInsert(String statement, List args); + Future runInsert(String statement, List args); /// Runs an update statement with the given variables and returns how many /// rows where affected. - Future runUpdate(String statement, List args); + Future runUpdate(String statement, List args); /// Runs an delete statement and returns how many rows where affected. - Future runDelete(String statement, List args); + Future runDelete(String statement, List args); /// Runs a custom SQL statement without any variables. The result of that /// statement will be ignored. - Future runCustom(String statement, [List args]); + Future runCustom(String statement, [List? args]); /// Prepares and runs [statements]. /// @@ -119,7 +119,7 @@ class ArgumentsForBatchedStatement { final int statementIndex; /// Bound arguments for the referenced statement. - final List arguments; + final List arguments; /// Used internally by moor. ArgumentsForBatchedStatement(this.statementIndex, this.arguments); diff --git a/moor/lib/src/runtime/executor/helpers/delegates.dart b/moor/lib/src/runtime/executor/helpers/delegates.dart index fb30cb44..4c340de8 100644 --- a/moor/lib/src/runtime/executor/helpers/delegates.dart +++ b/moor/lib/src/runtime/executor/helpers/delegates.dart @@ -76,7 +76,7 @@ abstract class QueryDelegate { /// /// If the statement can't be executed, an exception should be thrown. See /// the class documentation of [DatabaseDelegate] on what types are supported. - Future runSelect(String statement, List args); + Future runSelect(String statement, List args); /// Prepares and executes the [statement] with the variables bound to [args]. /// The statement will either be an `UPDATE` or `DELETE` statement. @@ -84,7 +84,7 @@ abstract class QueryDelegate { /// If the statement completes successfully, the amount of changed rows should /// be returned, or `0` if no rows where updated. Should throw if the /// statement can't be executed. - Future runUpdate(String statement, List args); + Future runUpdate(String statement, List args); /// Prepares and executes the [statement] with the variables bound to [args]. /// The statement will be an `INSERT` statement. @@ -92,11 +92,11 @@ abstract class QueryDelegate { /// If the statement completes successfully, the insert id of the row can be /// returned. If that information is not available, `null` can be returned. /// The method should throw if the statement can't be executed. - Future runInsert(String statement, List args); + Future runInsert(String statement, List args); /// Runs a custom [statement] with the given [args]. Ignores all results, but /// throws when the statement can't be executed. - Future runCustom(String statement, List args); + Future runCustom(String statement, List args); /// Runs multiple [statements] without having to prepare the same statement /// multiple times. diff --git a/moor/lib/src/runtime/executor/helpers/engines.dart b/moor/lib/src/runtime/executor/helpers/engines.dart index b8cd3813..c76bc06d 100644 --- a/moor/lib/src/runtime/executor/helpers/engines.dart +++ b/moor/lib/src/runtime/executor/helpers/engines.dart @@ -26,15 +26,15 @@ mixin _ExecutorWithQueryDelegate on QueryExecutor { } } - void _log(String sql, List args) { + void _log(String sql, List args) { if (logStatements) { print('Moor: Sent $sql with args $args'); } } @override - Future>> runSelect( - String statement, List args) async { + Future>> runSelect( + String statement, List args) async { assert(_ensureOpenCalled); final result = await _synchronized(() { _log(statement, args); @@ -44,7 +44,7 @@ mixin _ExecutorWithQueryDelegate on QueryExecutor { } @override - Future runUpdate(String statement, List args) { + Future runUpdate(String statement, List args) { assert(_ensureOpenCalled); return _synchronized(() { _log(statement, args); @@ -53,7 +53,7 @@ mixin _ExecutorWithQueryDelegate on QueryExecutor { } @override - Future runDelete(String statement, List args) { + Future runDelete(String statement, List args) { assert(_ensureOpenCalled); return _synchronized(() { _log(statement, args); @@ -62,7 +62,7 @@ mixin _ExecutorWithQueryDelegate on QueryExecutor { } @override - Future runInsert(String statement, List args) { + Future runInsert(String statement, List args) { assert(_ensureOpenCalled); return _synchronized(() { _log(statement, args); @@ -71,7 +71,7 @@ mixin _ExecutorWithQueryDelegate on QueryExecutor { } @override - Future runCustom(String statement, [List args]) { + Future runCustom(String statement, [List? args]) { assert(_ensureOpenCalled); return _synchronized(() { final resolvedArgs = args ?? const []; @@ -97,7 +97,7 @@ class _TransactionExecutor extends TransactionExecutor final DelegatedDatabase _db; @override - QueryDelegate impl; + late QueryDelegate impl; @override bool get isSequential => _db.isSequential; @@ -106,10 +106,10 @@ class _TransactionExecutor extends TransactionExecutor bool get logStatements => _db.logStatements; final Completer _sendCalled = Completer(); - Completer _openingCompleter; + Completer? _openingCompleter; - String _sendOnCommit; - String _sendOnRollback; + String? _sendOnCommit; + String? _sendOnRollback; Future get completed => _sendCalled.future; bool _sendFakeErrorOnRollback = false; @@ -133,7 +133,7 @@ class _TransactionExecutor extends TransactionExecutor _ensureOpenCalled = true; if (_openingCompleter != null) { - return await _openingCompleter.future; + return await _openingCompleter!.future; } _openingCompleter = Completer(); @@ -178,7 +178,7 @@ class _TransactionExecutor extends TransactionExecutor } await transactionStarted.future; - _openingCompleter.complete(true); + _openingCompleter!.complete(true); return true; } @@ -188,7 +188,7 @@ class _TransactionExecutor extends TransactionExecutor if (_openingCompleter == null) return; if (_sendOnCommit != null) { - await runCustom(_sendOnCommit, const []); + await runCustom(_sendOnCommit!, const []); _db.delegate.isInTransaction = false; } @@ -202,7 +202,7 @@ class _TransactionExecutor extends TransactionExecutor if (_openingCompleter == null) return; if (_sendOnRollback != null) { - await runCustom(_sendOnRollback, const []); + await runCustom(_sendOnRollback!, const []); _db.delegate.isInTransaction = false; } @@ -238,10 +238,8 @@ class DelegatedDatabase extends QueryExecutor with _ExecutorWithQueryDelegate { /// Constructs a delegated database by providing the [delegate]. DelegatedDatabase(this.delegate, - {this.logStatements, this.isSequential = false}) { - // not using default value because it's commonly set to null - logStatements ??= false; - } + {bool? logStatements, this.isSequential = false}) + : logStatements = logStatements ?? false; @override Future ensureOpen(QueryExecutorUser user) { @@ -260,7 +258,7 @@ class DelegatedDatabase extends QueryExecutor with _ExecutorWithQueryDelegate { Future _runMigrations(QueryExecutorUser user) async { final versionDelegate = delegate.versionDelegate; - int oldVersion; + int? oldVersion; final currentVersion = user.schemaVersion; if (versionDelegate is NoVersionDelegate) { diff --git a/moor/lib/src/runtime/executor/helpers/results.dart b/moor/lib/src/runtime/executor/helpers/results.dart index 165217b7..3ded3ec9 100644 --- a/moor/lib/src/runtime/executor/helpers/results.dart +++ b/moor/lib/src/runtime/executor/helpers/results.dart @@ -5,17 +5,17 @@ class QueryResult { /// The data returned by the select statement. Each list represents a row, /// which has the data in the same order as [columnNames]. - final List> rows; + final List> rows; - Map _columnIndexes; + final Map _columnIndexes; /// Constructs a [QueryResult] by specifying the order of column names in /// [columnNames] and the associated data in [rows]. - QueryResult(this.columnNames, this.rows) { - _columnIndexes = { - for (var column in columnNames) column: columnNames.lastIndexOf(column) - }; - } + QueryResult(this.columnNames, this.rows) + : _columnIndexes = { + for (var column in columnNames) + column: columnNames.lastIndexOf(column) + }; /// Converts the [rows] into [columnNames] and raw data [QueryResult.rows]. /// We assume that each map in [rows] has the same keys. @@ -38,7 +38,7 @@ class QueryResult { Iterable> get asMap { return rows.map((row) { return { - for (var column in columnNames) column: row[_columnIndexes[column]], + for (var column in columnNames) column: row[_columnIndexes[column]!], }; }); } diff --git a/moor/lib/src/runtime/executor/stream_queries.dart b/moor/lib/src/runtime/executor/stream_queries.dart index 36a81d76..7155af8f 100644 --- a/moor/lib/src/runtime/executor/stream_queries.dart +++ b/moor/lib/src/runtime/executor/stream_queries.dart @@ -2,7 +2,6 @@ import 'dart:async'; import 'dart:collection'; import 'package:collection/collection.dart'; -import 'package:meta/meta.dart'; import 'package:moor/moor.dart'; import 'package:moor/src/utils/start_with_value_transformer.dart'; import 'package:pedantic/pedantic.dart'; @@ -22,13 +21,13 @@ class QueryStreamFetcher { /// Key that can be used to check whether two fetchers will yield the same /// result when operating on the same data. - final StreamKey key; + final StreamKey? key; /// Function that asynchronously fetches the latest set of data. final Future Function() fetchData; QueryStreamFetcher( - {@required this.readsFrom, this.key, @required this.fetchData}); + {required this.readsFrom, this.key, required this.fetchData}); } /// Key that uniquely identifies a select statement. If two keys created from @@ -67,7 +66,7 @@ class StreamKey { /// updates them when needed. class StreamQueryStore { final Map _activeKeyStreams = {}; - final HashSet _keysPendingRemoval = HashSet(); + final HashSet _keysPendingRemoval = HashSet(); bool _isShuttingDown = false; // we track pending timers since Flutter throws an exception when timers @@ -185,17 +184,15 @@ class QueryStream { final QueryStreamFetcher _fetcher; final StreamQueryStore _store; - StreamController _controller; - StreamSubscription _tablesChangedSubscription; + late final StreamController _controller = StreamController.broadcast( + onListen: _onListen, + onCancel: _onCancel, + ); + StreamSubscription? _tablesChangedSubscription; - T _lastData; + T? _lastData; Stream get stream { - _controller ??= StreamController.broadcast( - onListen: _onListen, - onCancel: _onCancel, - ); - return _controller.stream.transform(StartWithValueTransformer(_cachedData)); } @@ -205,7 +202,7 @@ class QueryStream { /// Called when we have a new listener, makes the stream query behave similar /// to an `BehaviorSubject` from rxdart. - T _cachedData() => _lastData; + T? _cachedData() => _lastData; void _onListen() { _store.markAsOpened(this); @@ -282,7 +279,7 @@ class MultipleUpdateQuery extends TableUpdateQuery { } class SpecificUpdateQuery extends TableUpdateQuery { - final UpdateKind limitUpdateKind; + final UpdateKind? limitUpdateKind; final String table; const SpecificUpdateQuery(this.table, {this.limitUpdateKind}); diff --git a/moor/lib/src/runtime/isolate/client.dart b/moor/lib/src/runtime/isolate/client.dart index 208f9760..c4c0fcb8 100644 --- a/moor/lib/src/runtime/isolate/client.dart +++ b/moor/lib/src/runtime/isolate/client.dart @@ -3,20 +3,18 @@ part of 'moor_isolate.dart'; class _MoorClient { final IsolateCommunication _channel; final SqlTypeSystem typeSystem; - _IsolateStreamQueryStore _streamStore; - DatabaseConnection _connection; + late final _IsolateStreamQueryStore _streamStore = + _IsolateStreamQueryStore(this); + late final DatabaseConnection _connection = DatabaseConnection( + typeSystem, + _IsolateQueryExecutor(this), + _streamStore, + ); - QueryExecutorUser _connectedDb; + late QueryExecutorUser _connectedDb; _MoorClient(this._channel, this.typeSystem) { - _streamStore = _IsolateStreamQueryStore(this); - - _connection = DatabaseConnection( - typeSystem, - _IsolateQueryExecutor(this), - _streamStore, - ); _channel.setRequestHandler(_handleRequest); } @@ -44,7 +42,7 @@ class _MoorClient { abstract class _BaseExecutor extends QueryExecutor { final _MoorClient client; - int _executorId; + int? _executorId; _BaseExecutor(this.client, [this._executorId]); @@ -54,13 +52,14 @@ abstract class _BaseExecutor extends QueryExecutor { .request(_ExecuteBatchedStatement(statements, _executorId)); } - Future _runRequest(_StatementMethod method, String sql, List args) { + Future _runRequest( + _StatementMethod method, String sql, List? args) { return client._channel .request(_ExecuteQuery(method, sql, args ?? const [], _executorId)); } @override - Future runCustom(String statement, [List args]) { + Future runCustom(String statement, [List? args]) { return _runRequest( _StatementMethod.custom, statement, @@ -69,31 +68,32 @@ abstract class _BaseExecutor extends QueryExecutor { } @override - Future runDelete(String statement, List args) { + Future runDelete(String statement, List args) { return _runRequest(_StatementMethod.deleteOrUpdate, statement, args); } @override - Future runUpdate(String statement, List args) { + Future runUpdate(String statement, List args) { return _runRequest(_StatementMethod.deleteOrUpdate, statement, args); } @override - Future runInsert(String statement, List args) { + Future runInsert(String statement, List args) { return _runRequest(_StatementMethod.insert, statement, args); } @override - Future>> runSelect(String statement, List args) { + Future>> runSelect( + String statement, List args) { return _runRequest(_StatementMethod.select, statement, args); } } class _IsolateQueryExecutor extends _BaseExecutor { - _IsolateQueryExecutor(_MoorClient client, [int executorId]) + _IsolateQueryExecutor(_MoorClient client, [int? executorId]) : super(client, executorId); - Completer _setSchemaVersion; + Completer? _setSchemaVersion; @override TransactionExecutor beginTransaction() { @@ -104,7 +104,7 @@ class _IsolateQueryExecutor extends _BaseExecutor { Future ensureOpen(QueryExecutorUser user) async { client._connectedDb = user; if (_setSchemaVersion != null) { - await _setSchemaVersion.future; + await _setSchemaVersion!.future; _setSchemaVersion = null; } return client._channel @@ -123,17 +123,18 @@ class _IsolateQueryExecutor extends _BaseExecutor { class _TransactionIsolateExecutor extends _BaseExecutor implements TransactionExecutor { - final int _outerExecutorId; + final int? _outerExecutorId; _TransactionIsolateExecutor(_MoorClient client, this._outerExecutorId) : super(client); - Completer _pendingOpen; + Completer? _pendingOpen; bool _done = false; - // nested transactions aren't supported @override - TransactionExecutor beginTransaction() => null; + TransactionExecutor beginTransaction() { + throw UnsupportedError('Nested transactions'); + } @override Future ensureOpen(_) { @@ -143,8 +144,8 @@ class _TransactionIsolateExecutor extends _BaseExecutor 'somewhere?', ); - _pendingOpen ??= Completer()..complete(_openAtServer()); - return _pendingOpen.future; + final completer = _pendingOpen ??= Completer()..complete(_openAtServer()); + return completer.future; } Future _openAtServer() async { diff --git a/moor/lib/src/runtime/isolate/communication.dart b/moor/lib/src/runtime/isolate/communication.dart index bd450407..b7cefe65 100644 --- a/moor/lib/src/runtime/isolate/communication.dart +++ b/moor/lib/src/runtime/isolate/communication.dart @@ -19,7 +19,7 @@ class IsolateCommunication { /// primitive objects. final MessageCodec messageCodec; - StreamSubscription _inputSubscription; + StreamSubscription? _inputSubscription; // note that there are two IsolateCommunication instances in each connection, // and each of them has an independent _currentRequestId field! @@ -102,7 +102,7 @@ class IsolateCommunication { if (completer != null) { if (msg is _ErrorResponse) { final trace = msg.stackTrace != null - ? StackTrace.fromString(msg.stackTrace) + ? StackTrace.fromString(msg.stackTrace!) : null; completer.completeError(msg.error, trace); @@ -146,7 +146,7 @@ class IsolateCommunication { } /// Sends an erroneous response for a [Request]. - void respondError(Request request, dynamic error, [StackTrace trace]) { + void respondError(Request request, dynamic error, [StackTrace? trace]) { // sending a message while closed will throw, so don't even try. if (isClosed) return; @@ -390,9 +390,9 @@ class _Response implements IsolateMessage { class _ErrorResponse extends _Response { static const _tag = 6; - final String stackTrace; + final String? stackTrace; - dynamic get error => response; + Object get error => response as Object; _ErrorResponse(int requestId, dynamic error, [this.stackTrace]) : super(requestId, error); diff --git a/moor/lib/src/runtime/isolate/protocol.dart b/moor/lib/src/runtime/isolate/protocol.dart index 8d91438d..4eadb8b0 100644 --- a/moor/lib/src/runtime/isolate/protocol.dart +++ b/moor/lib/src/runtime/isolate/protocol.dart @@ -63,7 +63,7 @@ class _MoorCodec extends MessageCodec { for (final update in payload.updates) [ update.table, - update.kind.index, + update.kind?.index, ] ]; } else if (payload is SqlTypeSystem) { @@ -80,7 +80,7 @@ class _MoorCodec extends MessageCodec { if (encoded == null || encoded is bool) return encoded; int tag; - List fullMessage; + List? fullMessage; if (encoded is int) { tag = encoded; @@ -89,7 +89,8 @@ class _MoorCodec extends MessageCodec { tag = fullMessage[0] as int; } - int readInt(int index) => fullMessage[index] as int; + int readInt(int index) => fullMessage![index] as int; + int? readNullableInt(int index) => fullMessage![index] as int?; switch (tag) { case _tag_NoArgsRequest_getTypeSystem: @@ -98,12 +99,12 @@ class _MoorCodec extends MessageCodec { return _NoArgsRequest.terminateAll; case _tag_ExecuteQuery: final method = _StatementMethod.values[readInt(1)]; - final sql = fullMessage[2] as String; + final sql = fullMessage![2] as String; final args = (fullMessage[3] as List).map(_decodeDbValue).toList(); - final executorId = fullMessage[4] as int /*?*/; + final executorId = readNullableInt(4); return _ExecuteQuery(method, sql, args, executorId); case _tag_ExecuteBatchedStatement: - final sql = (fullMessage[1] as List).cast(); + final sql = (fullMessage![1] as List).cast(); final args = []; for (var i = 2; i < fullMessage.length - 1; i++) { @@ -118,19 +119,19 @@ class _MoorCodec extends MessageCodec { BatchedStatements(sql, args), executorId); case _tag_RunTransactionAction: final control = _TransactionControl.values[readInt(1)]; - return _RunTransactionAction(control, readInt(2)); + return _RunTransactionAction(control, readNullableInt(2)); case _tag_EnsureOpen: - return _EnsureOpen(readInt(1), readInt(2)); + return _EnsureOpen(readInt(1), readNullableInt(2)); case _tag_RunBeforeOpen: return _RunBeforeOpen( - OpeningDetails(readInt(1), readInt(2)), + OpeningDetails(readNullableInt(1), readInt(2)), readInt(3), ); case _tag_DefaultSqlTypeSystem: return SqlTypeSystem.defaultInstance; case _tag_NotifyTablesUpdated: final updates = []; - for (var i = 1; i < fullMessage.length; i++) { + for (var i = 1; i < fullMessage!.length; i++) { final encodedUpdate = fullMessage[i] as List; updates.add( TableUpdate(encodedUpdate[0] as String, @@ -186,7 +187,7 @@ class _ExecuteQuery { final _StatementMethod method; final String sql; final List args; - final int executorId; + final int? executorId; _ExecuteQuery(this.method, this.sql, this.args, [this.executorId]); @@ -202,7 +203,7 @@ class _ExecuteQuery { /// Sent from the client to run [BatchedStatements] class _ExecuteBatchedStatement { final BatchedStatements stmts; - final int executorId; + final int? executorId; _ExecuteBatchedStatement(this.stmts, [this.executorId]); } @@ -219,7 +220,7 @@ enum _TransactionControl { /// Sent from the client to commit or rollback a transaction class _RunTransactionAction { final _TransactionControl control; - final int executorId; + final int? executorId; _RunTransactionAction(this.control, this.executorId); @@ -233,7 +234,7 @@ class _RunTransactionAction { /// database connection, using the [schemaVersion]. class _EnsureOpen { final int schemaVersion; - final int executorId; + final int? executorId; _EnsureOpen(this.schemaVersion, this.executorId); diff --git a/moor/lib/src/runtime/isolate/server.dart b/moor/lib/src/runtime/isolate/server.dart index 6429d65e..3753e22f 100644 --- a/moor/lib/src/runtime/isolate/server.dart +++ b/moor/lib/src/runtime/isolate/server.dart @@ -3,7 +3,7 @@ part of 'moor_isolate.dart'; class _MoorServer { final Server server; - DatabaseConnection connection; + final DatabaseConnection connection; final Map _managedExecutors = {}; int _currentExecutorId = 0; @@ -19,20 +19,20 @@ class _MoorServer { final StreamController _backlogUpdated = StreamController.broadcast(sync: true); - _IsolateDelegatedUser _dbUser; + late final _IsolateDelegatedUser _dbUser = _IsolateDelegatedUser(this); SendPort get portToOpenConnection => server.portToOpenConnection; - _MoorServer(DatabaseOpener opener) : server = Server(const _MoorCodec()) { + _MoorServer(DatabaseOpener opener) + : connection = opener(), + server = Server(const _MoorCodec()) { server.openedConnections.listen((connection) { connection.setRequestHandler(_handleRequest); }); - connection = opener(); - _dbUser = _IsolateDelegatedUser(this); } /// Returns the first connected client, or null if no client is connected. - IsolateCommunication get firstClient { + IsolateCommunication? get firstClient { final channels = server.currentChannels; return channels.isEmpty ? null : channels.first; } @@ -74,8 +74,8 @@ class _MoorServer { return await executor.ensureOpen(_dbUser); } - Future _runQuery( - _StatementMethod method, String sql, List args, int transactionId) async { + Future _runQuery(_StatementMethod method, String sql, + List args, int? transactionId) async { final executor = await _loadExecutor(transactionId); switch (method) { @@ -88,23 +88,21 @@ class _MoorServer { case _StatementMethod.select: return executor.runSelect(sql, args); } - - throw AssertionError("Unknown _StatementMethod, this can't happen."); } - Future _runBatched(BatchedStatements stmts, int transactionId) async { + Future _runBatched(BatchedStatements stmts, int? transactionId) async { final executor = await _loadExecutor(transactionId); await executor.runBatched(stmts); } - Future _loadExecutor(int transactionId) async { + Future _loadExecutor(int? transactionId) async { await _waitForTurn(transactionId); return transactionId != null - ? _managedExecutors[transactionId] + ? _managedExecutors[transactionId]! : connection.executor; } - Future _spawnTransaction(int executor) async { + Future _spawnTransaction(int? executor) async { final transaction = (await _loadExecutor(executor)).beginTransaction(); final id = _putExecutor(transaction, beforeCurrent: true); @@ -126,7 +124,7 @@ class _MoorServer { } Future _transactionControl( - _TransactionControl action, int executorId) async { + _TransactionControl action, int? executorId) async { if (action == _TransactionControl.begin) { return await _spawnTransaction(executorId); } @@ -142,21 +140,19 @@ class _MoorServer { ); } - final transaction = executor as TransactionExecutor; - try { switch (action) { case _TransactionControl.commit: - await transaction.send(); + await executor.send(); break; case _TransactionControl.rollback: - await transaction.rollback(); + await executor.rollback(); break; default: assert(false, 'Unknown TransactionControl'); } } finally { - _releaseExecutor(executorId); + _releaseExecutor(executorId!); } } @@ -166,7 +162,7 @@ class _MoorServer { _notifyActiveExecutorUpdated(); } - Future _waitForTurn(int transactionId) { + Future _waitForTurn(int? transactionId) { bool idIsActive() { if (transactionId == null) { return _executorBacklog.isEmpty; @@ -202,7 +198,7 @@ class _IsolateDelegatedUser implements QueryExecutorUser { QueryExecutor executor, OpeningDetails details) async { final id = server._putExecutor(executor, beforeCurrent: true); try { - await server.firstClient.request(_RunBeforeOpen(details, id)); + await server.firstClient!.request(_RunBeforeOpen(details, id)); } finally { server._releaseExecutor(id); } diff --git a/moor/lib/src/runtime/query_builder/components/group_by.dart b/moor/lib/src/runtime/query_builder/components/group_by.dart index 8f6a28c5..217bece7 100644 --- a/moor/lib/src/runtime/query_builder/components/group_by.dart +++ b/moor/lib/src/runtime/query_builder/components/group_by.dart @@ -6,7 +6,7 @@ class GroupBy extends Component { final List groupBy; /// Optional, a having clause to exclude some groups. - final Expression /*?*/ having; + final Expression? having; GroupBy._(this.groupBy, this.having); @@ -17,7 +17,7 @@ class GroupBy extends Component { if (having != null) { context.buffer.write(' HAVING '); - having.writeInto(context); + having!.writeInto(context); } } } diff --git a/moor/lib/src/runtime/query_builder/components/join.dart b/moor/lib/src/runtime/query_builder/components/join.dart index a215e5c1..57d822aa 100644 --- a/moor/lib/src/runtime/query_builder/components/join.dart +++ b/moor/lib/src/runtime/query_builder/components/join.dart @@ -31,7 +31,7 @@ class Join extends Component { /// For joins that aren't [_JoinType.cross], contains an additional predicate /// that must be matched for the join. - final Expression on; + final Expression? on; /// Whether [table] should appear in the result set (defaults to true). /// @@ -41,7 +41,7 @@ class Join extends Component { /// Constructs a [Join] by providing the relevant fields. [on] is optional for /// [_JoinType.cross]. - Join._(this.type, this.table, this.on, {bool includeInResult}) + Join._(this.type, this.table, this.on, {bool? includeInResult}) : includeInResult = includeInResult ?? true; @override @@ -53,7 +53,7 @@ class Join extends Component { if (type != _JoinType.cross) { context.buffer.write(' ON '); - on.writeInto(context); + on!.writeInto(context); } } } @@ -71,7 +71,7 @@ class Join extends Component { /// - http://www.sqlitetutorial.net/sqlite-inner-join/ Join innerJoin( TableInfo other, Expression on, - {bool useColumns}) { + {bool? useColumns}) { return Join._(_JoinType.inner, other, on, includeInResult: useColumns); } @@ -85,7 +85,7 @@ Join innerJoin( /// - http://www.sqlitetutorial.net/sqlite-left-join/ Join leftOuterJoin( TableInfo other, Expression on, - {bool useColumns}) { + {bool? useColumns}) { return Join._(_JoinType.leftOuter, other, on, includeInResult: useColumns); } @@ -97,6 +97,6 @@ Join leftOuterJoin( /// See also: /// - https://moor.simonbinder.eu/docs/advanced-features/joins/#joins /// - http://www.sqlitetutorial.net/sqlite-cross-join/ -Join crossJoin(TableInfo other, {bool useColumns}) { +Join crossJoin(TableInfo other, {bool? useColumns}) { return Join._(_JoinType.cross, other, null, includeInResult: useColumns); } diff --git a/moor/lib/src/runtime/query_builder/components/limit.dart b/moor/lib/src/runtime/query_builder/components/limit.dart index 71316b62..f287c0df 100644 --- a/moor/lib/src/runtime/query_builder/components/limit.dart +++ b/moor/lib/src/runtime/query_builder/components/limit.dart @@ -7,7 +7,7 @@ class Limit extends Component { /// When the offset is non null, the first offset rows will be skipped an not /// included in the result. - final int offset; + final int? offset; /// Construct a limit clause from the [amount] of rows to include an a /// nullable [offset]. diff --git a/moor/lib/src/runtime/query_builder/components/order_by.dart b/moor/lib/src/runtime/query_builder/components/order_by.dart index 3e61d6b5..b64f5073 100644 --- a/moor/lib/src/runtime/query_builder/components/order_by.dart +++ b/moor/lib/src/runtime/query_builder/components/order_by.dart @@ -25,7 +25,7 @@ class OrderingTerm extends Component { /// Creates an ordering term by the [expression] and the [mode] (defaults to /// ascending). - OrderingTerm({@required this.expression, this.mode = OrderingMode.asc}); + OrderingTerm({required this.expression, this.mode = OrderingMode.asc}); /// Creates an ordering term that sorts for ascending values of [expression]. factory OrderingTerm.asc(Expression expression) { diff --git a/moor/lib/src/runtime/query_builder/components/where.dart b/moor/lib/src/runtime/query_builder/components/where.dart index ddb87f13..ee5991c2 100644 --- a/moor/lib/src/runtime/query_builder/components/where.dart +++ b/moor/lib/src/runtime/query_builder/components/where.dart @@ -4,7 +4,7 @@ part of '../query_builder.dart'; class Where extends Component { /// The expression that determines whether a given row should be included in /// the result. - final Expression predicate; + final Expression predicate; /// Construct a [Where] clause from its [predicate]. Where(this.predicate); diff --git a/moor/lib/src/runtime/query_builder/expressions/aggregate.dart b/moor/lib/src/runtime/query_builder/expressions/aggregate.dart index 388b6e7b..8f7eb0e0 100644 --- a/moor/lib/src/runtime/query_builder/expressions/aggregate.dart +++ b/moor/lib/src/runtime/query_builder/expressions/aggregate.dart @@ -1,8 +1,5 @@ part of '../query_builder.dart'; -// todo: We should have a detailed article on group-by clauses and aggregate -// expressions on the website - /// Returns the amount of rows in the current group matching the optional /// [filter]. /// @@ -12,7 +9,7 @@ part of '../query_builder.dart'; /// /// This is equivalent to the `COUNT(*) FILTER (WHERE filter)` sql function. The /// filter will be omitted if null. -Expression countAll({Expression filter}) { +Expression countAll({Expression? filter}) { return _AggregateExpression('COUNT', const _StarFunctionParameter(), filter: filter); } @@ -27,7 +24,7 @@ extension BaseAggregate
on Expression
{ /// counted twice. An optional [filter] can be used to only include values /// matching the filter. Note that [filter] is only available from sqlite /// 3.30 and most devices will use an older sqlite version. - Expression count({bool distinct, Expression filter}) { + Expression count({bool? distinct, Expression? filter}) { return _AggregateExpression('COUNT', this, filter: filter, distinct: distinct); } @@ -52,19 +49,19 @@ extension BaseAggregate
on Expression
{ } /// Provides aggregate functions that are available for numeric expressions. -extension ArithmeticAggregates
on Expression
{ +extension ArithmeticAggregates
on Expression { /// Return the average of all non-null values in this group. - Expression avg() => _AggregateExpression('AVG', this); + Expression avg() => _AggregateExpression('AVG', this); /// Return the maximum of all non-null values in this group. /// /// If there are no non-null values in the group, returns null. - Expression
max() => _AggregateExpression('MAX', this); + Expression max() => _AggregateExpression('MAX', this); /// Return the minimum of all non-null values in this group. /// /// If there are no non-null values in the group, returns null. - Expression
min() => _AggregateExpression('MIN', this); + Expression min() => _AggregateExpression('MIN', this); /// Calculate the sum of all non-null values in the group. /// @@ -74,13 +71,13 @@ extension ArithmeticAggregates
on Expression
{ /// /// See also [total], which behaves similarly but returns a floating point /// value and doesn't throw an overflow exception. - Expression
sum() => _AggregateExpression('SUM', this); + Expression sum() => _AggregateExpression('SUM', this); /// Calculate the sum of all non-null values in the group. /// /// If all values in the group are null, [total] returns `0.0`. This function /// uses floating-point values internally. - Expression total() => _AggregateExpression('TOTAL', this); + Expression total() => _AggregateExpression('TOTAL', this); } class _AggregateExpression extends Expression { @@ -88,10 +85,10 @@ class _AggregateExpression extends Expression { final bool distinct; final FunctionParameter parameter; - final Where /*?*/ filter; + final Where? filter; _AggregateExpression(this.functionName, this.parameter, - {Expression filter, bool distinct}) + {Expression? filter, bool? distinct}) : filter = filter != null ? Where(filter) : null, distinct = distinct ?? false; @@ -111,7 +108,7 @@ class _AggregateExpression extends Expression { if (filter != null) { context.buffer.write(' FILTER ('); - filter.writeInto(context); + filter!.writeInto(context); context.buffer.write(')'); } } diff --git a/moor/lib/src/runtime/query_builder/expressions/algebra.dart b/moor/lib/src/runtime/query_builder/expressions/algebra.dart index f36477cf..334d5946 100644 --- a/moor/lib/src/runtime/query_builder/expressions/algebra.dart +++ b/moor/lib/src/runtime/query_builder/expressions/algebra.dart @@ -1,7 +1,7 @@ part of '../query_builder.dart'; /// Defines the `-`, `*` and `/` operators on sql expressions that support it. -extension ArithmeticExpr
on Expression
{ +extension ArithmeticExpr
on Expression
{ /// Performs an addition (`this` + [other]) in sql. Expression
operator +(Expression
other) { return _BaseInfixOperator(this, '+', other, diff --git a/moor/lib/src/runtime/query_builder/expressions/bools.dart b/moor/lib/src/runtime/query_builder/expressions/bools.dart index 9ca625ec..a54f3394 100644 --- a/moor/lib/src/runtime/query_builder/expressions/bools.dart +++ b/moor/lib/src/runtime/query_builder/expressions/bools.dart @@ -1,24 +1,24 @@ part of '../query_builder.dart'; /// Defines operations on boolean values. -extension BooleanExpressionOperators on Expression { +extension BooleanExpressionOperators on Expression { /// Negates this boolean expression. The returned expression is true if /// `this` is false, and vice versa. - Expression not() => _NotExpression(this); + Expression not() => _NotExpression(this); /// Returns an expression that is true iff both `this` and [other] are true. - Expression operator &(Expression other) { + Expression operator &(Expression other) { return _BaseInfixOperator(this, 'AND', other, precedence: Precedence.and); } /// Returns an expression that is true if `this` or [other] are true. - Expression operator |(Expression other) { + Expression operator |(Expression other) { return _BaseInfixOperator(this, 'OR', other, precedence: Precedence.or); } } -class _NotExpression extends Expression { - final Expression inner; +class _NotExpression extends Expression { + final Expression inner; _NotExpression(this.inner); diff --git a/moor/lib/src/runtime/query_builder/expressions/comparable.dart b/moor/lib/src/runtime/query_builder/expressions/comparable.dart index 70d88ce3..8d80b39f 100644 --- a/moor/lib/src/runtime/query_builder/expressions/comparable.dart +++ b/moor/lib/src/runtime/query_builder/expressions/comparable.dart @@ -1,7 +1,7 @@ part of '../query_builder.dart'; /// Defines extension functions to express comparisons in sql -extension ComparableExpr
> on Expression
{ +extension ComparableExpr
?> on Expression
{ /// Returns an expression that is true if this expression is strictly bigger /// than the other expression. Expression isBiggerThan(Expression
other) { @@ -84,9 +84,9 @@ class _BetweenExpression extends Expression { final Expression higher; _BetweenExpression( - {@required this.target, - @required this.lower, - @required this.higher, + {required this.target, + required this.lower, + required this.higher, this.not = false}); @override diff --git a/moor/lib/src/runtime/query_builder/expressions/datetimes.dart b/moor/lib/src/runtime/query_builder/expressions/datetimes.dart index d458b71c..caed9873 100644 --- a/moor/lib/src/runtime/query_builder/expressions/datetimes.dart +++ b/moor/lib/src/runtime/query_builder/expressions/datetimes.dart @@ -19,27 +19,27 @@ class _CustomDateTimeExpression extends CustomExpression { /// Provides expressions to extract information from date time values, or to /// calculate the difference between datetimes. -extension DateTimeExpressions on Expression { +extension DateTimeExpressions on Expression { /// Extracts the (UTC) year from `this` datetime expression. - Expression get year => _StrftimeSingleFieldExpression('%Y', this); + Expression get year => _StrftimeSingleFieldExpression('%Y', this); /// Extracts the (UTC) month from `this` datetime expression. - Expression get month => _StrftimeSingleFieldExpression('%m', this); + Expression get month => _StrftimeSingleFieldExpression('%m', this); /// Extracts the (UTC) day from `this` datetime expression. - Expression get day => _StrftimeSingleFieldExpression('%d', this); + Expression get day => _StrftimeSingleFieldExpression('%d', this); /// Extracts the (UTC) hour from `this` datetime expression. - Expression get hour => _StrftimeSingleFieldExpression('%H', this); + Expression get hour => _StrftimeSingleFieldExpression('%H', this); /// Extracts the (UTC) minute from `this` datetime expression. - Expression get minute => _StrftimeSingleFieldExpression('%M', this); + Expression get minute => _StrftimeSingleFieldExpression('%M', this); /// Extracts the (UTC) second from `this` datetime expression. - Expression get second => _StrftimeSingleFieldExpression('%S', this); + Expression get second => _StrftimeSingleFieldExpression('%S', this); /// Formats this datetime in the format `year-month-day`. - Expression get date { + Expression get date { return FunctionCallExpression( 'DATE', [this, const Constant('unixepoch')], @@ -68,9 +68,9 @@ extension DateTimeExpressions on Expression { /// Expression that extracts components out of a date time by using the builtin /// sqlite function "strftime" and casting the result to an integer. -class _StrftimeSingleFieldExpression extends Expression { +class _StrftimeSingleFieldExpression extends Expression { final String format; - final Expression date; + final Expression date; _StrftimeSingleFieldExpression(this.format, this.date); diff --git a/moor/lib/src/runtime/query_builder/expressions/expression.dart b/moor/lib/src/runtime/query_builder/expressions/expression.dart index 1562b803..e2a0ae0b 100644 --- a/moor/lib/src/runtime/query_builder/expressions/expression.dart +++ b/moor/lib/src/runtime/query_builder/expressions/expression.dart @@ -264,7 +264,7 @@ class _Comparison extends _InfixOperator { final _ComparisonOperator op; @override - String get operator => _operatorNames[op]; + String get operator => _operatorNames[op]!; @override Precedence get precedence { diff --git a/moor/lib/src/runtime/query_builder/expressions/null_check.dart b/moor/lib/src/runtime/query_builder/expressions/null_check.dart index b6928d1a..af429900 100644 --- a/moor/lib/src/runtime/query_builder/expressions/null_check.dart +++ b/moor/lib/src/runtime/query_builder/expressions/null_check.dart @@ -1,8 +1,5 @@ part of '../query_builder.dart'; -// we're not using extensions for this because I'm not sure if / how this could -// look together with NNBD in the future - /// Expression that is true if the inner expression resolves to a null value. @Deprecated('Use isNull through the SqlIsNull extension') Expression isNull(Expression inner) => _NullCheck(inner, true); diff --git a/moor/lib/src/runtime/query_builder/expressions/text.dart b/moor/lib/src/runtime/query_builder/expressions/text.dart index 604f5bc1..1adaf110 100644 --- a/moor/lib/src/runtime/query_builder/expressions/text.dart +++ b/moor/lib/src/runtime/query_builder/expressions/text.dart @@ -1,11 +1,11 @@ part of '../query_builder.dart'; /// Defines methods that operate on a column storing [String] values. -extension StringExpressionOperators on Expression { +extension StringExpressionOperators on Expression { /// Whether this column matches the given pattern. For details on what patters /// are valid and how they are interpreted, check out /// [this tutorial](http://www.sqlitetutorial.net/sqlite-like/). - Expression like(String regex) { + Expression like(String regex) { return _LikeOperator(this, Variable.withString(regex)); } @@ -16,7 +16,7 @@ extension StringExpressionOperators on Expression { /// /// Note that this function is only available when using `moor_ffi`. If you /// need to support the web or `moor_flutter`, consider using [like] instead. - Expression regexp( + Expression regexp( String regex, { bool multiLine = false, bool caseSensitive = true, @@ -62,7 +62,7 @@ extension StringExpressionOperators on Expression { /// Note that this is case-insensitive for the English alphabet only. /// /// This is equivalent to calling [like] with `%%`. - Expression contains(String substring) { + Expression contains(String substring) { return like('%$substring%'); } @@ -73,7 +73,7 @@ extension StringExpressionOperators on Expression { } /// Performs a string concatenation in sql by appending [other] to `this`. - Expression operator +(Expression other) { + Expression operator +(Expression other) { return _BaseInfixOperator(this, '||', other, precedence: Precedence.stringConcatenation); } @@ -102,19 +102,19 @@ extension StringExpressionOperators on Expression { /// /// See also: /// - https://www.w3resource.com/sqlite/core-functions-length.php - Expression get length { + Expression get length { return FunctionCallExpression('LENGTH', [this]); } } /// A `text LIKE pattern` expression that will be true if the first expression /// matches the pattern given by the second expression. -class _LikeOperator extends Expression { +class _LikeOperator extends Expression { /// The target expression that will be tested - final Expression target; + final Expression target; /// The regex-like expression to test the [target] against. - final Expression regex; + final Expression regex; /// The operator to use when matching. Defaults to `LIKE`. final String operator; diff --git a/moor/lib/src/runtime/query_builder/generation_context.dart b/moor/lib/src/runtime/query_builder/generation_context.dart index 3d598aa1..a63e73d6 100644 --- a/moor/lib/src/runtime/query_builder/generation_context.dart +++ b/moor/lib/src/runtime/query_builder/generation_context.dart @@ -16,7 +16,7 @@ class GenerationContext { final SqlDialect dialect; /// The actual [QueryEngine] that's going to execute the generated query. - final QueryEngine executor; + final QueryEngine? executor; final List _boundVariables = []; @@ -40,8 +40,9 @@ class GenerationContext { /// Constructs a [GenerationContext] by copying the relevant fields from the /// database. GenerationContext.fromDb(this.executor) - : typeSystem = executor.typeSystem, - dialect = executor.executor?.dialect ?? SqlDialect.sqlite; + : typeSystem = executor?.typeSystem ?? SqlTypeSystem.defaultInstance, + // ignore: invalid_null_aware_operator, (doesn't seem to actually work) + dialect = executor?.executor?.dialect ?? SqlDialect.sqlite; /// Constructs a custom [GenerationContext] by setting the fields manually. /// See [GenerationContext.fromDb] for a more convenient factory. diff --git a/moor/lib/src/runtime/query_builder/migration.dart b/moor/lib/src/runtime/query_builder/migration.dart index 410f8cb9..ab49f3d7 100644 --- a/moor/lib/src/runtime/query_builder/migration.dart +++ b/moor/lib/src/runtime/query_builder/migration.dart @@ -35,7 +35,7 @@ class MigrationStrategy { /// and all migrations ran), but before any other queries will be sent. This /// makes it a suitable place to populate data after the database has been /// created or set sqlite `PRAGMAS` that you need. - final OnBeforeOpen /*?*/ beforeOpen; + final OnBeforeOpen? beforeOpen; /// Construct a migration strategy from the provided [onCreate] and /// [onUpgrade] methods. @@ -121,7 +121,7 @@ class Migrator { @experimental Future alterTable(TableMigration migration) async { final foreignKeysEnabled = - (await _db.customSelect('PRAGMA foreign_keys').getSingle()) + (await _db.customSelect('PRAGMA foreign_keys').getSingle())! .readBool('foreign_keys'); if (foreignKeysEnabled) { @@ -251,7 +251,7 @@ class Migrator { // as table constraint if it has already been written on a primary key // column, even though that column appears in table.$primaryKey because we // need to know all primary keys for the update(table).replace(row) API - final hasPrimaryKey = table.$primaryKey?.isNotEmpty ?? false; + final hasPrimaryKey = table.$primaryKey.isNotEmpty; final dontWritePk = dslTable.dontWriteConstraints || hasAutoIncrement; if (hasPrimaryKey && !dontWritePk) { context.buffer.write(', PRIMARY KEY ('); @@ -266,7 +266,7 @@ class Migrator { context.buffer.write(')'); } - final constraints = dslTable.customConstraints ?? []; + final constraints = dslTable.customConstraints; for (var i = 0; i < constraints.length; i++) { context.buffer..write(', ')..write(constraints[i]); @@ -369,11 +369,11 @@ class Migrator { /// Executes the custom query. @Deprecated('Use customStatement in the database class') - Future issueCustomQuery(String sql, [List args]) { + Future issueCustomQuery(String sql, [List? args]) { return _issueCustomQuery(sql, args); } - Future _issueCustomQuery(String sql, [List args]) { + Future _issueCustomQuery(String sql, [List? args]) { return _db.customStatement(sql, args); } } @@ -383,7 +383,7 @@ class Migrator { class OpeningDetails { /// The schema version before the database has been opened, or `null` if the /// database has just been created. - final int versionBefore; + final int? versionBefore; /// The schema version after running migrations. final int versionNow; @@ -395,7 +395,9 @@ class OpeningDetails { bool get hadUpgrade => !wasCreated && versionBefore != versionNow; /// Used internally by moor when opening a database. - const OpeningDetails(this.versionBefore, this.versionNow); + const OpeningDetails(this.versionBefore, this.versionNow) + // Should use null instead of 0 for consistency + : assert(versionBefore != 0); } /// Extension providing the [destructiveFallback] strategy. diff --git a/moor/lib/src/runtime/query_builder/schema/columns.dart b/moor/lib/src/runtime/query_builder/schema/columns.dart index e7733a7f..bef9187b 100644 --- a/moor/lib/src/runtime/query_builder/schema/columns.dart +++ b/moor/lib/src/runtime/query_builder/schema/columns.dart @@ -21,11 +21,11 @@ abstract class GeneratedColumn extends Column { /// If custom constraints have been specified for this column via /// [ColumnBuilder.customConstraint], these are kept here. Otherwise, this /// field is going to be null. - final String $customConstraints; + final String? $customConstraints; /// The default expression to be used during inserts when no value has been /// specified. Can be null if no default value is set. - final Expression defaultValue; + final Expression? defaultValue; /// A function that yields a default column for inserts if no value has been /// set. This is different to [defaultValue] since the function is written in @@ -33,7 +33,7 @@ abstract class GeneratedColumn extends Column { /// [defaultValue] and [clientDefault] are non-null. /// /// See also: [ColumnBuilder.clientDefault]. - T Function() clientDefault; + T Function()? clientDefault; /// Used by generated code. GeneratedColumn(this.$name, this.tableName, this.$nullable, @@ -48,6 +48,7 @@ abstract class GeneratedColumn extends Column { if ($customConstraints == null) { into.buffer.write($nullable ? ' NULL' : ' NOT NULL'); + final defaultValue = this.defaultValue; if (defaultValue != null) { into.buffer.write(' DEFAULT '); @@ -137,18 +138,18 @@ abstract class GeneratedColumn extends Column { } Variable _evaluateClientDefault() { - return Variable(clientDefault()); + return Variable(clientDefault!()); } } /// Implementation for [TextColumn]. -class GeneratedTextColumn extends GeneratedColumn +class GeneratedTextColumn extends GeneratedColumn implements TextColumn { /// Optional. The minimum text length. - final int minTextLength; + final int? minTextLength; /// Optional. The maximum text length. - final int maxTextLength; + final int? maxTextLength; /// Used by generated code. GeneratedTextColumn( @@ -157,8 +158,8 @@ class GeneratedTextColumn extends GeneratedColumn bool nullable, { this.minTextLength, this.maxTextLength, - String $customConstraints, - Expression defaultValue, + String? $customConstraints, + Expression? defaultValue, }) : super(name, tableName, nullable, $customConstraints: $customConstraints, defaultValue: defaultValue); @@ -166,16 +167,16 @@ class GeneratedTextColumn extends GeneratedColumn final String typeName = 'TEXT'; @override - VerificationResult isAcceptableValue(String value, VerificationMeta meta) { + VerificationResult isAcceptableValue(String? value, VerificationMeta meta) { // handle nullability check in common column if (value == null) return super.isAcceptableValue(null, meta); final length = value.length; - if (minTextLength != null && minTextLength > length) { + if (minTextLength != null && minTextLength! > length) { return VerificationResult.failure( 'Must at least be $minTextLength characters long.'); } - if (maxTextLength != null && maxTextLength < length) { + if (maxTextLength != null && maxTextLength! < length) { return VerificationResult.failure( 'Must at most be $maxTextLength characters long.'); } @@ -185,10 +186,10 @@ class GeneratedTextColumn extends GeneratedColumn } /// Implementation for [BoolColumn]. -class GeneratedBoolColumn extends GeneratedColumn implements BoolColumn { +class GeneratedBoolColumn extends GeneratedColumn implements BoolColumn { /// Used by generated code GeneratedBoolColumn(String name, String tableName, bool nullable, - {String $customConstraints, Expression defaultValue}) + {String? $customConstraints, Expression? defaultValue}) : super(name, tableName, nullable, $customConstraints: $customConstraints, defaultValue: defaultValue); @@ -202,7 +203,7 @@ class GeneratedBoolColumn extends GeneratedColumn implements BoolColumn { } /// Implementation for [IntColumn] -class GeneratedIntColumn extends GeneratedColumn implements IntColumn { +class GeneratedIntColumn extends GeneratedColumn implements IntColumn { /// Whether this column was declared to be a primary key via a column /// constraint. The only way to do this in Dart is with /// [IntColumnBuilder.autoIncrement]. In `.moor` files, declaring a column @@ -226,8 +227,8 @@ class GeneratedIntColumn extends GeneratedColumn implements IntColumn { bool nullable, { this.declaredAsPrimaryKey = false, this.hasAutoIncrement = false, - String $customConstraints, - Expression defaultValue, + String? $customConstraints, + Expression? defaultValue, }) : super(name, tableName, nullable, $customConstraints: $customConstraints, defaultValue: defaultValue); @@ -248,15 +249,15 @@ class GeneratedIntColumn extends GeneratedColumn implements IntColumn { } /// Implementation for [DateTimeColumn]. -class GeneratedDateTimeColumn extends GeneratedColumn +class GeneratedDateTimeColumn extends GeneratedColumn implements DateTimeColumn { /// Used by generated code. GeneratedDateTimeColumn( String $name, String tableName, bool $nullable, { - String $customConstraints, - Expression defaultValue, + String? $customConstraints, + Expression? defaultValue, }) : super($name, tableName, $nullable, $customConstraints: $customConstraints, defaultValue: defaultValue); @@ -265,11 +266,11 @@ class GeneratedDateTimeColumn extends GeneratedColumn } /// Implementation for [BlobColumn] -class GeneratedBlobColumn extends GeneratedColumn +class GeneratedBlobColumn extends GeneratedColumn implements BlobColumn { /// Used by generated code. GeneratedBlobColumn(String $name, String tableName, bool $nullable, - {String $customConstraints, Expression defaultValue}) + {String? $customConstraints, Expression? defaultValue}) : super($name, tableName, $nullable, $customConstraints: $customConstraints, defaultValue: defaultValue); @@ -278,15 +279,15 @@ class GeneratedBlobColumn extends GeneratedColumn } /// Implementation for [RealColumn] -class GeneratedRealColumn extends GeneratedColumn +class GeneratedRealColumn extends GeneratedColumn implements RealColumn { /// Used by generated code GeneratedRealColumn( String $name, String tableName, bool $nullable, { - Expression defaultValue, - String $customConstraints, + Expression? defaultValue, + String? $customConstraints, }) : super($name, tableName, $nullable, defaultValue: defaultValue, $customConstraints: $customConstraints); diff --git a/moor/lib/src/runtime/query_builder/schema/table_info.dart b/moor/lib/src/runtime/query_builder/schema/table_info.dart index 1fce4fd4..9f710c69 100644 --- a/moor/lib/src/runtime/query_builder/schema/table_info.dart +++ b/moor/lib/src/runtime/query_builder/schema/table_info.dart @@ -9,12 +9,12 @@ mixin TableInfo on Table /// [TableInfo] and [TableDsl] and can thus just return their instance. TableDsl get asDslTable; - /// The primary key of this table. Can be null or empty if no custom primary - /// key has been specified. + /// The primary key of this table. Can be empty if no custom primary key has + /// been specified. /// /// Additional to the [Table.primaryKey] columns declared by an user, this /// also contains auto-increment integers, which are primary key by default. - Set get $primaryKey => null; + Set get $primaryKey => const {}; // ensure the primaryKey getter is consistent with $primaryKey, which can // contain additional columns. @@ -35,7 +35,7 @@ mixin TableInfo on Table /// All columns defined in this table. List get $columns; - Map _columnsByName; + Map? _columnsByName; /// Gets all [$columns] in this table, indexed by their (non-escaped) name. Map get columnsByName { @@ -54,7 +54,7 @@ mixin TableInfo on Table } /// Maps the given row returned by the database into the fitting data class. - D map(Map data, {String tablePrefix}); + D map(Map data, {String? tablePrefix}); /// Converts a [companion] to the real model class, [D]. /// @@ -120,13 +120,13 @@ extension TableInfoUtils } /// Like [map], but from a [row] instead of the low-level map. - D mapFromRow(QueryRow row, {String tablePrefix}) { + D mapFromRow(QueryRow row, {String? tablePrefix}) { return map(row.data, tablePrefix: tablePrefix); } /// Like [mapFromRow], but returns null if a non-nullable column of this table /// is null in [row]. - D /*?*/ mapFromRowOrNull(QueryRow row, {String tablePrefix}) { + D? mapFromRowOrNull(QueryRow row, {String? tablePrefix}) { final resolvedPrefix = tablePrefix == null ? '' : '$tablePrefix.'; final notInRow = $columns @@ -153,7 +153,7 @@ extension TableInfoUtils /// `'c2': 'bar'` in [alias]. D mapFromRowWithAlias(QueryRow row, Map alias) { return map({ - for (final entry in row.data.entries) alias[entry.key]: entry.value, + for (final entry in row.data.entries) alias[entry.key]!: entry.value, }); } } diff --git a/moor/lib/src/runtime/query_builder/statements/delete.dart b/moor/lib/src/runtime/query_builder/statements/delete.dart index d7bc49b8..d9fbf2fb 100644 --- a/moor/lib/src/runtime/query_builder/statements/delete.dart +++ b/moor/lib/src/runtime/query_builder/statements/delete.dart @@ -36,7 +36,7 @@ class DeleteStatement extends Query Future go() async { final ctx = constructQuery(); - return ctx.executor.doWhenOpened((e) async { + return ctx.executor!.doWhenOpened((e) async { final rows = await e.runDelete(ctx.sql, ctx.boundVariables); if (rows > 0) { diff --git a/moor/lib/src/runtime/query_builder/statements/insert.dart b/moor/lib/src/runtime/query_builder/statements/insert.dart index 1eb692a9..5f8b9f14 100644 --- a/moor/lib/src/runtime/query_builder/statements/insert.dart +++ b/moor/lib/src/runtime/query_builder/statements/insert.dart @@ -60,8 +60,8 @@ class InsertStatement { /// Still, the future will always complete with an error if the insert fails. Future insert( Insertable entity, { - InsertMode mode, - DoUpdate onConflict, + InsertMode? mode, + DoUpdate? onConflict, }) async { final ctx = createContext(entity, mode ?? InsertMode.insert, onConflict: onConflict); @@ -94,7 +94,7 @@ class InsertStatement { /// /// This method is used internally by moor. Consider using [insert] instead. GenerationContext createContext(Insertable entry, InsertMode mode, - {DoUpdate onConflict}) { + {DoUpdate? onConflict}) { _validateIntegrity(entry); final rawValues = entry.toColumns(true); @@ -105,7 +105,7 @@ class InsertStatement { final columnName = column.$name; if (rawValues.containsKey(columnName)) { - map[columnName] = rawValues[columnName]; + map[columnName] = rawValues[columnName]!; } else { if (column.clientDefault != null) { map[columnName] = column._evaluateClientDefault(); @@ -165,6 +165,12 @@ class InsertStatement { ctx.buffer.write(' ON CONFLICT('); final conflictTarget = onConflict.target ?? table.$primaryKey.toList(); + + if (conflictTarget.isEmpty) { + throw ArgumentError( + 'Table has no primary key, so a conflict target is needed.'); + } + var first = true; for (final target in conflictTarget) { if (!first) ctx.buffer.write(', '); @@ -190,7 +196,7 @@ class InsertStatement { return ctx; } - void _validateIntegrity(Insertable d) { + void _validateIntegrity(Insertable? d) { if (d == null) { throw InvalidDataException( 'Cannot write null row into ${table.$tableName}'); @@ -254,7 +260,7 @@ class DoUpdate { /// specifies the uniqueness constraint that will trigger the upsert. /// /// By default, the primary key of the table will be used. - final List /*?*/ target; + final List? target; /// For an example, see [InsertStatement.insert]. DoUpdate(Insertable Function(T old) update, {this.target}) diff --git a/moor/lib/src/runtime/query_builder/statements/query.dart b/moor/lib/src/runtime/query_builder/statements/query.dart index 4bd98307..d0b65f02 100644 --- a/moor/lib/src/runtime/query_builder/statements/query.dart +++ b/moor/lib/src/runtime/query_builder/statements/query.dart @@ -16,17 +16,17 @@ abstract class Query { /// The `WHERE` clause for this statement @protected - Where whereExpr; + Where? whereExpr; /// The `ORDER BY` clause for this statement @protected - OrderBy orderByExpr; + OrderBy? orderByExpr; /// The `LIMIT` clause for this statement. @protected - Limit limitExpr; + Limit? limitExpr; - GroupBy _groupBy; + GroupBy? _groupBy; /// Subclasses must override this and write the part of the statement that /// comes before the where and limit expression.. @@ -44,7 +44,7 @@ abstract class Query { // whether we need to insert a space before writing the next component var needsWhitespace = false; - void writeWithSpace(Component /*?*/ component) { + void writeWithSpace(Component? component) { if (component == null) return; if (needsWhitespace) ctx.writeWhitespace(); @@ -96,7 +96,7 @@ abstract class Selectable { /// one row, for instance because you used `limit(1)` or you know the `where` /// clause will only allow one row. /// {@endtemplate} - Future getSingle() async { + Future getSingle() async { final list = await get(); final iterator = list.iterator; @@ -119,7 +119,7 @@ abstract class Selectable { /// will be added to the stream instead. /// /// {@macro moor_single_query_expl} - Stream watchSingle() { + Stream watchSingle() { return watch().transform(singleElements()); } @@ -182,7 +182,7 @@ mixin SingleTableQueryMixin if (whereExpr == null) { whereExpr = Where(predicate); } else { - whereExpr = Where(whereExpr.predicate & predicate); + whereExpr = Where(whereExpr!.predicate & predicate); } } @@ -190,7 +190,7 @@ mixin SingleTableQueryMixin /// [d] will be matched. void whereSamePrimaryKey(Insertable d) { assert( - table.$primaryKey != null && table.$primaryKey.isNotEmpty, + table.$primaryKey.isNotEmpty, 'When using Query.whereSamePrimaryKey, which is also called from ' 'DeleteStatement.delete and UpdateStatement.replace, the affected table' 'must have a primary key. You can either specify a primary implicitly ' @@ -212,10 +212,10 @@ mixin SingleTableQueryMixin final primaryKeyValues = Map.fromEntries(updatedFields.entries .where((entry) => primaryKeyColumns.containsKey(entry.key))) .map((columnName, value) { - return MapEntry(primaryKeyColumns[columnName], value); + return MapEntry(primaryKeyColumns[columnName]!, value); }); - Expression predicate; + Expression? predicate; for (final entry in primaryKeyValues.entries) { final comparison = _Comparison(entry.key, _ComparisonOperator.equal, entry.value); @@ -227,7 +227,7 @@ mixin SingleTableQueryMixin } } - whereExpr = Where(predicate); + whereExpr = Where(predicate!); } } @@ -236,7 +236,7 @@ mixin LimitContainerMixin on Query { /// Limits the amount of rows returned by capping them at [limit]. If [offset] /// is provided as well, the first [offset] rows will be skipped and not /// included in the result. - void limit(int limit, {int offset}) { + void limit(int limit, {int? offset}) { limitExpr = Limit(limit, offset); } } diff --git a/moor/lib/src/runtime/query_builder/statements/select/custom_select.dart b/moor/lib/src/runtime/query_builder/statements/select/custom_select.dart index 04491f1a..883f578d 100644 --- a/moor/lib/src/runtime/query_builder/statements/select/custom_select.dart +++ b/moor/lib/src/runtime/query_builder/statements/select/custom_select.dart @@ -73,11 +73,11 @@ class QueryRow { /// Reads an arbitrary value from the row and maps it to a fitting dart type. /// The dart type [T] must be supported by the type system of the database - /// used (mostly contains booleans, strings, integers and dates). + /// used (mostly contains booleans, strings, numbers and dates). T read(String key) { final type = _db.typeSystem.forDartType(); - return type.mapFromDatabaseResponse(data[key]); + return type.mapFromDatabaseResponse(data[key]) as T; } /// Reads a bool from the column named [key]. diff --git a/moor/lib/src/runtime/query_builder/statements/select/select.dart b/moor/lib/src/runtime/query_builder/statements/select/select.dart index a8cd514b..0fc53246 100644 --- a/moor/lib/src/runtime/query_builder/statements/select/select.dart +++ b/moor/lib/src/runtime/query_builder/statements/select/select.dart @@ -36,7 +36,7 @@ class SimpleSelectStatement } Future> _getWithQuery(GenerationContext ctx) async { - final results = await ctx.executor.doWhenOpened((e) async { + final results = await ctx.executor!.doWhenOpened((e) async { return await e.runSelect(ctx.sql, ctx.boundVariables); }); return results.map(table.map).toList(); @@ -69,10 +69,10 @@ class SimpleSelectStatement final statement = JoinedSelectStatement(database, table, joins, distinct); if (whereExpr != null) { - statement.where(whereExpr.predicate); + statement.where(whereExpr!.predicate); } if (orderByExpr != null) { - statement.orderBy(orderByExpr.terms); + statement.orderBy(orderByExpr!.terms); } if (limitExpr != null) { statement.limitExpr = limitExpr; @@ -129,7 +129,7 @@ class TypedResult { TypedResult(this._parsedData, this.rawData, [this._parsedExpressions]); final Map _parsedData; - final Map _parsedExpressions; + final Map? _parsedExpressions; /// The raw data contained in this row. final QueryRow rawData; @@ -142,10 +142,10 @@ class TypedResult { /// Reads a single column from an [expr]. The expression must have been added /// as a column, for instance via [JoinedSelectStatement.addColumns]. /// - /// To access the underlying columns directly, use - D read>(Expression expr) { + /// To access the underlying columns directly, use [rawData]. + D? read(Expression expr) { if (_parsedExpressions != null) { - return _parsedExpressions[expr] as D; + return _parsedExpressions![expr] as D; } return null; } diff --git a/moor/lib/src/runtime/query_builder/statements/select/select_with_join.dart b/moor/lib/src/runtime/query_builder/statements/select/select_with_join.dart index 86fa897b..21db5d3a 100644 --- a/moor/lib/src/runtime/query_builder/statements/select/select_with_join.dart +++ b/moor/lib/src/runtime/query_builder/statements/select/select_with_join.dart @@ -109,11 +109,11 @@ class JoinedSelectStatement /// ]) /// ..where(todos.name.like("%Important") & categories.name.equals("Work")); /// ``` - void where(Expression predicate) { + void where(Expression predicate) { if (whereExpr == null) { whereExpr = Where(predicate); } else { - whereExpr = Where(whereExpr.predicate & predicate); + whereExpr = Where(whereExpr!.predicate & predicate); } } @@ -165,7 +165,7 @@ class JoinedSelectStatement /// Groups the result by values in [expressions]. /// /// An optional [having] attribute can be set to exclude certain groups. - void groupBy(Iterable expressions, {Expression having}) { + void groupBy(Iterable expressions, {Expression? having}) { _groupBy = GroupBy._(expressions.toList(), having); } @@ -188,7 +188,7 @@ class JoinedSelectStatement } Future> _getWithQuery(GenerationContext ctx) async { - final results = await ctx.executor.doWhenOpened((e) async { + final results = await ctx.executor!.doWhenOpened((e) async { try { return await e.runSelect(ctx.sql, ctx.boundVariables); } catch (e, s) { diff --git a/moor/lib/src/runtime/query_builder/statements/update.dart b/moor/lib/src/runtime/query_builder/statements/update.dart index 65b0c3fe..9f2bc5fa 100644 --- a/moor/lib/src/runtime/query_builder/statements/update.dart +++ b/moor/lib/src/runtime/query_builder/statements/update.dart @@ -7,7 +7,7 @@ class UpdateStatement extends Query UpdateStatement(QueryEngine database, TableInfo table) : super(database, table); - Map _updatedFields; + late Map _updatedFields; @override void writeStartPart(GenerationContext ctx) { @@ -31,7 +31,7 @@ class UpdateStatement extends Query Future _performQuery() async { final ctx = constructQuery(); - final rows = await ctx.executor.doWhenOpened((e) async { + final rows = await ctx.executor!.doWhenOpened((e) async { return await e.runUpdate(ctx.sql, ctx.boundVariables); }); @@ -123,7 +123,7 @@ class UpdateStatement extends Query // if a default value exists and no value is set, apply the default if (column.defaultValue != null && !_updatedFields.containsKey(column.$name)) { - _updatedFields[column.$name] = column.defaultValue; + _updatedFields[column.$name] = column.defaultValue!; } } diff --git a/moor/lib/src/runtime/types/custom_type.dart b/moor/lib/src/runtime/types/custom_type.dart index 470fbbf4..a75bd08b 100644 --- a/moor/lib/src/runtime/types/custom_type.dart +++ b/moor/lib/src/runtime/types/custom_type.dart @@ -13,12 +13,11 @@ abstract class TypeConverter { const TypeConverter(); /// Map a value from an object in Dart into something that will be understood - /// by the database. Be aware that [value] is nullable. - S mapToSql(D value); + /// by the database. + S? mapToSql(D? value); - /// Maps a column from the database back to Dart. Be aware that [fromDb] is - /// nullable. - D mapToDart(S fromDb); + /// Maps a column from the database back to Dart. + D? mapToDart(S? fromDb); } /// Implementation for an enum to int converter that uses the index of the enum @@ -31,12 +30,12 @@ class EnumIndexConverter extends TypeConverter { const EnumIndexConverter(this.values); @override - T mapToDart(int fromDb) { + T? mapToDart(int? fromDb) { return fromDb == null ? null : values[fromDb]; } @override - int mapToSql(T value) { + int? mapToSql(T? value) { return (value as dynamic)?.index as int; } } diff --git a/moor/lib/src/runtime/types/sql_types.dart b/moor/lib/src/runtime/types/sql_types.dart index 839ccee3..8f198e91 100644 --- a/moor/lib/src/runtime/types/sql_types.dart +++ b/moor/lib/src/runtime/types/sql_types.dart @@ -1,5 +1,6 @@ import 'dart:typed_data'; +// ignore: import_of_legacy_library_into_null_safe import 'package:convert/convert.dart'; import 'package:moor/moor.dart'; @@ -17,14 +18,14 @@ abstract class SqlType { /// Maps the [content] to a value that we can send together with a prepared /// statement to represent the given value. - dynamic mapToSqlVariable(T content); + dynamic mapToSqlVariable(T? content); /// Maps the given content to a sql literal that can be included in the query /// string. - String mapToSqlConstant(T content); + String? mapToSqlConstant(T? content); /// Maps the response from sql back to a readable dart type. - T mapFromDatabaseResponse(dynamic response); + T? mapFromDatabaseResponse(dynamic response); } /// A mapper for boolean values in sql. Booleans are represented as integers, @@ -37,14 +38,14 @@ class BoolType extends SqlType { String get sqlName => 'INTEGER'; @override - bool mapFromDatabaseResponse(dynamic response) { + bool? mapFromDatabaseResponse(dynamic response) { // ignore: avoid_returning_null if (response == null) return null; return response != 0; } @override - String mapToSqlConstant(bool content) { + String mapToSqlConstant(bool? content) { if (content == null) { return 'NULL'; } @@ -52,7 +53,7 @@ class BoolType extends SqlType { } @override - int mapToSqlVariable(bool content) { + int? mapToSqlVariable(bool? content) { if (content == null) { // ignore: avoid_returning_null return null; @@ -70,10 +71,12 @@ class StringType extends SqlType { String get sqlName => 'TEXT'; @override - String mapFromDatabaseResponse(dynamic response) => response?.toString(); + String? mapFromDatabaseResponse(dynamic response) => response?.toString(); @override - String mapToSqlConstant(String content) { + String mapToSqlConstant(String? content) { + if (content == null) return 'NULL'; + // From the sqlite docs: (https://www.sqlite.org/lang_expr.html) // A string constant is formed by enclosing the string in single quotes ('). // A single quote within the string can be encoded by putting two single @@ -84,7 +87,7 @@ class StringType extends SqlType { } @override - String mapToSqlVariable(String content) => content; + String? mapToSqlVariable(String? content) => content; } /// Maps [int] values from and to sql @@ -96,16 +99,16 @@ class IntType extends SqlType { String get sqlName => 'INTEGER'; @override - int mapFromDatabaseResponse(dynamic response) { - if (response == null || response is int /*?*/) return response as int /*?*/; + int? mapFromDatabaseResponse(dynamic response) { + if (response == null || response is int?) return response as int?; return int.parse(response.toString()); } @override - String mapToSqlConstant(int content) => content?.toString() ?? 'NULL'; + String mapToSqlConstant(int? content) => content?.toString() ?? 'NULL'; @override - int mapToSqlVariable(int content) { + int? mapToSqlVariable(int? content) { return content; } } @@ -119,7 +122,7 @@ class DateTimeType extends SqlType { String get sqlName => 'INTEGER'; @override - DateTime mapFromDatabaseResponse(dynamic response) { + DateTime? mapFromDatabaseResponse(dynamic response) { if (response == null) return null; final unixSeconds = response as int; @@ -128,14 +131,14 @@ class DateTimeType extends SqlType { } @override - String mapToSqlConstant(DateTime content) { + String mapToSqlConstant(DateTime? content) { if (content == null) return 'NULL'; return (content.millisecondsSinceEpoch ~/ 1000).toString(); } @override - int mapToSqlVariable(DateTime content) { + int? mapToSqlVariable(DateTime? content) { // ignore: avoid_returning_null if (content == null) return null; @@ -152,17 +155,20 @@ class BlobType extends SqlType { String get sqlName => 'BLOB'; @override - Uint8List mapFromDatabaseResponse(dynamic response) => response as Uint8List; + Uint8List? mapFromDatabaseResponse(dynamic response) { + return response as Uint8List?; + } @override - String mapToSqlConstant(Uint8List content) { + String mapToSqlConstant(Uint8List? content) { + if (content == null) return 'NULL'; // BLOB literals are string literals containing hexadecimal data and // preceded by a single "x" or "X" character. Example: X'53514C697465' return "x'${hex.encode(content)}'"; } @override - Uint8List mapToSqlVariable(Uint8List content) => content; + Uint8List? mapToSqlVariable(Uint8List? content) => content; } /// Maps [double] values from and to sql @@ -174,12 +180,12 @@ class RealType extends SqlType { String get sqlName => 'REAL'; @override - double mapFromDatabaseResponse(dynamic response) { - return (response as num)?.toDouble(); + double? mapFromDatabaseResponse(dynamic response) { + return (response as num?)?.toDouble(); } @override - String mapToSqlConstant(num content) { + String mapToSqlConstant(num? content) { if (content == null) { return 'NULL'; } @@ -187,5 +193,5 @@ class RealType extends SqlType { } @override - num mapToSqlVariable(num content) => content; + num? mapToSqlVariable(num? content) => content; } diff --git a/moor/lib/src/runtime/types/type_system.dart b/moor/lib/src/runtime/types/type_system.dart index c0b7460c..61de819f 100644 --- a/moor/lib/src/runtime/types/type_system.dart +++ b/moor/lib/src/runtime/types/type_system.dart @@ -20,7 +20,7 @@ class SqlTypeSystem { RealType(), ]); - /// Constant field of [SqlTypeSystem.withDefaults()]. This field exists as a + /// Constant field of [SqlTypeSystem.withDefaults]. This field exists as a /// workaround for an analyzer bug: https://dartbug.com/38658 /// /// Used internally by generated code. diff --git a/moor/lib/src/utils/lazy_database.dart b/moor/lib/src/utils/lazy_database.dart index eff046ec..c86ddf7e 100644 --- a/moor/lib/src/utils/lazy_database.dart +++ b/moor/lib/src/utils/lazy_database.dart @@ -9,8 +9,10 @@ typedef DatabaseOpener = FutureOr Function(); /// A special database executor that delegates work to another [QueryExecutor]. /// The other executor is lazily opened by a [DatabaseOpener]. class LazyDatabase extends QueryExecutor { - QueryExecutor _delegate; - Completer _openDelegate; + late QueryExecutor _delegate; + bool _delegateAvailable = false; + + Completer? _openDelegate; /// The function that will open the database when this [LazyDatabase] gets /// opened for the first time. @@ -21,17 +23,18 @@ class LazyDatabase extends QueryExecutor { LazyDatabase(this.opener); Future _awaitOpened() { - if (_delegate != null) { + if (_delegateAvailable) { return Future.value(); } else if (_openDelegate != null) { - return _openDelegate.future; + return _openDelegate!.future; } else { - _openDelegate = Completer(); + final delegate = _openDelegate = Completer(); Future.value(opener()).then((database) { _delegate = database; - _openDelegate.complete(); + _delegateAvailable = true; + delegate.complete(); }); - return _openDelegate.future; + return delegate.future; } } @@ -48,28 +51,30 @@ class LazyDatabase extends QueryExecutor { _delegate.runBatched(statements); @override - Future runCustom(String statement, [List args]) => + Future runCustom(String statement, [List? args]) => _delegate.runCustom(statement, args); @override - Future runDelete(String statement, List args) => + Future runDelete(String statement, List args) => _delegate.runDelete(statement, args); @override - Future runInsert(String statement, List args) => + Future runInsert(String statement, List args) => _delegate.runInsert(statement, args); @override - Future>> runSelect(String statement, List args) => - _delegate.runSelect(statement, args); + Future>> runSelect( + String statement, List args) { + return _delegate.runSelect(statement, args); + } @override - Future runUpdate(String statement, List args) => + Future runUpdate(String statement, List args) => _delegate.runUpdate(statement, args); @override Future close() { - if (_delegate != null) { + if (_delegateAvailable) { return _delegate.close(); } else { return Future.value(); diff --git a/moor/lib/src/utils/single_transformer.dart b/moor/lib/src/utils/single_transformer.dart index 2468dbb8..d487289d 100644 --- a/moor/lib/src/utils/single_transformer.dart +++ b/moor/lib/src/utils/single_transformer.dart @@ -2,7 +2,7 @@ import 'dart:async'; /// Transforms a stream of lists into a stream of single elements, assuming /// that each list is a singleton. -StreamTransformer, T> singleElements() { +StreamTransformer, T?> singleElements() { return StreamTransformer.fromHandlers(handleData: (data, sink) { try { if (data.isEmpty) { diff --git a/moor/lib/src/utils/start_with_value_transformer.dart b/moor/lib/src/utils/start_with_value_transformer.dart index 7772cb2a..f0407ae9 100644 --- a/moor/lib/src/utils/start_with_value_transformer.dart +++ b/moor/lib/src/utils/start_with_value_transformer.dart @@ -2,7 +2,7 @@ import 'dart:async'; /// Signature of a function that returns the latest current value of a /// [StartWithValueTransformer]. -typedef LatestValue = T Function(); +typedef LatestValue = T? Function(); /// Lightweight implementation that turns a [StreamController] into a behavior /// subject (we try to avoid depending on rxdart because of its size). @@ -29,8 +29,8 @@ class _StartWithValueStream extends Stream { bool get isBroadcast => _inner.isBroadcast; @override - StreamSubscription listen(void Function(T event) onData, - {Function onError, void Function() onDone, bool cancelOnError}) { + StreamSubscription listen(void Function(T event)? onData, + {Function? onError, void Function()? onDone, bool? cancelOnError}) { final data = _value(); return _StartWithValueSubscription(_inner, data, onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); @@ -38,32 +38,33 @@ class _StartWithValueStream extends Stream { } class _StartWithValueSubscription extends StreamSubscription { - StreamSubscription _inner; - final T initialData; + late final StreamSubscription _inner; + final T? initialData; bool needsInitialData = true; - void Function(T data) _onData; + void Function(T data)? _onData; _StartWithValueSubscription( Stream innerStream, this.initialData, this._onData, - {Function onError, void Function() onDone, bool cancelOnError}) { + {Function? onError, void Function()? onDone, bool? cancelOnError}) { _inner = innerStream.listen(_wrappedDataCallback(_onData), onError: onError, onDone: onDone, cancelOnError: cancelOnError); // Dart's stream contract specifies that listeners are only notified // after the .listen() code completes. So, we add the initial data in // a later microtask. - if (initialData != null) { + final data = initialData; + if (data != null) { scheduleMicrotask(() { if (needsInitialData) { - _onData?.call(initialData); + _onData?.call(data); needsInitialData = false; } }); } } - void Function(T data) _wrappedDataCallback(void Function(T data) onData) { + void Function(T data) _wrappedDataCallback(void Function(T data)? onData) { return (event) { needsInitialData = false; onData?.call(event); @@ -71,7 +72,7 @@ class _StartWithValueSubscription extends StreamSubscription { } @override - Future asFuture([E futureValue]) => _inner.asFuture(); + Future asFuture([E? futureValue]) => _inner.asFuture(futureValue); @override Future cancel() { @@ -83,20 +84,20 @@ class _StartWithValueSubscription extends StreamSubscription { bool get isPaused => _inner.isPaused; @override - void onData(void Function(T data) handleData) { + void onData(void Function(T data)? handleData) { _onData = handleData; _inner.onData(_wrappedDataCallback(handleData)); } @override - void onDone(void Function() handleDone) => _inner.onDone(handleDone); + void onDone(void Function()? handleDone) => _inner.onDone(handleDone); @override - void onError(Function handleError) => _inner.onError(handleError); + void onError(Function? handleError) => _inner.onError(handleError); @override - void pause([Future resumeSignal]) { + void pause([Future? resumeSignal]) { needsInitialData = false; _inner.pause(resumeSignal); } diff --git a/moor/lib/src/web/sql_js.dart b/moor/lib/src/web/sql_js.dart index 9466f1ef..36773e25 100644 --- a/moor/lib/src/web/sql_js.dart +++ b/moor/lib/src/web/sql_js.dart @@ -7,12 +7,12 @@ import 'dart:typed_data'; // This way, projects using moor can run on flutter as long as they don't import // this file. -Completer _moduleCompleter; +Completer? _moduleCompleter; /// Calls the `initSqlJs` function from the native sql.js library. Future initSqlJs() { if (_moduleCompleter != null) { - return _moduleCompleter.future; + return _moduleCompleter!.future; } _moduleCompleter = Completer(); @@ -26,7 +26,7 @@ Future initSqlJs() { (context.callMethod('initSqlJs') as JsObject) .callMethod('then', [_handleModuleResolved]); - return _moduleCompleter.future; + return _moduleCompleter!.future; } // We're extracting this into its own method so that we don't have to call @@ -34,7 +34,7 @@ Future initSqlJs() { // todo figure out why dart2js generates invalid js when wrapping this in // allowInterop void _handleModuleResolved(dynamic module) { - _moduleCompleter.complete(SqlJsModule._(module as JsObject)); + _moduleCompleter!.complete(SqlJsModule._(module as JsObject)); } /// `sql.js` module from the underlying library @@ -43,7 +43,7 @@ class SqlJsModule { SqlJsModule._(this._obj); /// Constructs a new [SqlJsDatabase], optionally from the [data] blob. - SqlJsDatabase createDatabase([Uint8List data]) { + SqlJsDatabase createDatabase([Uint8List? data]) { final dbObj = _createInternally(data); assert(() { // set the window.db variable to make debugging easier @@ -54,7 +54,7 @@ class SqlJsModule { return SqlJsDatabase._(dbObj); } - JsObject _createInternally(Uint8List data) { + JsObject _createInternally(Uint8List? data) { final constructor = _obj['Database'] as JsFunction; if (data != null) { diff --git a/moor/lib/src/web/storage.dart b/moor/lib/src/web/storage.dart index 5fd9fa9b..f4f8b642 100644 --- a/moor/lib/src/web/storage.dart +++ b/moor/lib/src/web/storage.dart @@ -13,7 +13,7 @@ abstract class MoorWebStorage { /// Restore the last database version that was saved with [store]. /// /// If no saved data was found, returns null. - Future restore(); + Future restore(); /// Store the entire database. Future store(Uint8List data); @@ -72,8 +72,8 @@ abstract class MoorWebStorage { } abstract class _CustomSchemaVersionSave implements MoorWebStorage { - int /*?*/ get schemaVersion; - set schemaVersion(int value); + int? get schemaVersion; + set schemaVersion(int? value); } String _persistenceKeyForLocalStorage(String name) { @@ -84,7 +84,7 @@ String _legacyVersionKeyForLocalStorage(String name) { return 'moor_db_version_$name'; } -Uint8List /*?*/ _restoreLocalStorage(String name) { +Uint8List? _restoreLocalStorage(String name) { final raw = window.localStorage[_persistenceKeyForLocalStorage(name)]; if (raw != null) { return bin2str.decode(raw); @@ -101,7 +101,7 @@ class _LocalStorageImpl implements MoorWebStorage, _CustomSchemaVersionSave { const _LocalStorageImpl(this.name); @override - int get schemaVersion { + int? get schemaVersion { final versionStr = window.localStorage[_versionKey]; // ignore: avoid_returning_null if (versionStr == null) return null; @@ -110,8 +110,14 @@ class _LocalStorageImpl implements MoorWebStorage, _CustomSchemaVersionSave { } @override - set schemaVersion(int value) { - window.localStorage[_versionKey] = value.toString(); + set schemaVersion(int? value) { + final key = _versionKey; + + if (value == null) { + window.localStorage.remove(key); + } else { + window.localStorage[_versionKey] = value.toString(); + } } @override @@ -121,7 +127,7 @@ class _LocalStorageImpl implements MoorWebStorage, _CustomSchemaVersionSave { Future open() => Future.value(); @override - Future restore() async { + Future restore() async { return _restoreLocalStorage(name); } @@ -141,7 +147,7 @@ class _IndexedDbStorage implements MoorWebStorage { final bool migrateFromLocalStorage; final bool inWebWorker; - Database _database; + late Database _database; _IndexedDbStorage(this.name, {this.migrateFromLocalStorage = true, this.inWebWorker = false}); @@ -153,7 +159,7 @@ class _IndexedDbStorage implements MoorWebStorage { final indexedDb = inWebWorker ? WorkerGlobalScope.instance.indexedDB : window.indexedDB; - _database = await indexedDb.open( + _database = await indexedDb!.open( _objectStoreName, version: 1, onUpgradeNeeded: (event) { @@ -188,12 +194,12 @@ class _IndexedDbStorage implements MoorWebStorage { } @override - Future restore() async { + Future restore() async { final transaction = _database.transactionStore(_objectStoreName, 'readonly'); final store = transaction.objectStore(_objectStoreName); - final result = await store.getObject(name) as Blob /*?*/; + final result = await store.getObject(name) as Blob?; if (result == null) return null; final reader = FileReader(); diff --git a/moor/lib/src/web/web_db.dart b/moor/lib/src/web/web_db.dart index 40149a9e..1734eecd 100644 --- a/moor/lib/src/web/web_db.dart +++ b/moor/lib/src/web/web_db.dart @@ -13,7 +13,7 @@ class WebDatabase extends DelegatedDatabase { /// [name] can be used to identify multiple databases. The optional /// [initializer] can be used to initialize the database if it doesn't exist. WebDatabase(String name, - {bool logStatements = false, CreateWebDatabase initializer}) + {bool logStatements = false, CreateWebDatabase? initializer}) : super(_WebDelegate(MoorWebStorage(name), initializer), logStatements: logStatements, isSequential: true); @@ -23,15 +23,17 @@ class WebDatabase extends DelegatedDatabase { /// constructor of [MoorWebStorage] will use local storage for that, but an /// IndexedDB-based implementation is available via. WebDatabase.withStorage(MoorWebStorage storage, - {bool logStatements = false, CreateWebDatabase initializer}) + {bool logStatements = false, CreateWebDatabase? initializer}) : super(_WebDelegate(storage, initializer), logStatements: logStatements, isSequential: true); } class _WebDelegate extends DatabaseDelegate { final MoorWebStorage storage; - final CreateWebDatabase initializer; - SqlJsDatabase _db; + final CreateWebDatabase? initializer; + + late SqlJsDatabase _db; + bool _isOpen = false; bool _inTransaction = false; @@ -56,13 +58,13 @@ class _WebDelegate extends DatabaseDelegate { @override DbVersionDelegate get versionDelegate => _versionDelegate ??= _WebVersionDelegate(this); - DbVersionDelegate _versionDelegate; + DbVersionDelegate? _versionDelegate; @override - bool get isOpen => _db != null; + bool get isOpen => _isOpen; @override - Future open([QueryExecutorUser db]) async { + Future open(QueryExecutorUser db) async { final dbVersion = db.schemaVersion; assert(dbVersion >= 1, 'Database schema version needs to be at least 1'); @@ -72,11 +74,15 @@ class _WebDelegate extends DatabaseDelegate { var restored = await storage.restore(); if (restored == null && initializer != null) { - restored = await initializer(); - await storage.store(restored); + restored = await initializer?.call(); + + if (restored != null) { + await storage.store(restored); + } } _db = module.createDatabase(restored); + _isOpen = true; } @override @@ -100,13 +106,13 @@ class _WebDelegate extends DatabaseDelegate { } @override - Future runCustom(String statement, List args) { + Future runCustom(String statement, List args) { _db.runWithArgs(statement, args); return Future.value(); } @override - Future runInsert(String statement, List args) async { + Future runInsert(String statement, List args) async { _db.runWithArgs(statement, args); final insertId = _db.lastInsertId(); await _handlePotentialUpdate(); @@ -114,11 +120,11 @@ class _WebDelegate extends DatabaseDelegate { } @override - Future runSelect(String statement, List args) { + Future runSelect(String statement, List args) { // todo at least for stream queries we should cache prepared statements. final stmt = _db.prepare(statement)..executeWith(args); - List columnNames; + List? columnNames; final rows = >[]; while (stmt.step()) { @@ -133,7 +139,7 @@ class _WebDelegate extends DatabaseDelegate { } @override - Future runUpdate(String statement, List args) { + Future runUpdate(String statement, List args) { _db.runWithArgs(statement, args); return _handlePotentialUpdate(); } @@ -141,7 +147,10 @@ class _WebDelegate extends DatabaseDelegate { @override Future close() async { await _storeDb(); - _db?.close(); + if (_isOpen) { + _db.close(); + } + await storage.close(); } @@ -181,7 +190,7 @@ class _WebVersionDelegate extends DynamicVersionDelegate { @override Future get schemaVersion async { final storage = delegate.storage; - int version; + int? version; if (storage is _CustomSchemaVersionSave) { version = storage.schemaVersion; } diff --git a/moor/pubspec.yaml b/moor/pubspec.yaml index 796daeef..41d64544 100644 --- a/moor/pubspec.yaml +++ b/moor/pubspec.yaml @@ -6,27 +6,50 @@ homepage: https://moor.simonbinder.eu/ issue_tracker: https://github.com/simolus3/moor/issues environment: - sdk: '>=2.6.0 <3.0.0' + sdk: '>=2.12.0-0 <3.0.0' dependencies: - meta: ^1.1.8 - convert: ^2.1.1 - collection: ^1.0.0 - synchronized: ^2.1.0 - pedantic: ^1.0.0 - sqlite3: ^0.1.6 + meta: ^1.3.0-nullsafety.6 + # We'd prefer convert ^3.0.0 for nullsafety, (we have a dependency_override) for that, but large chunks of the Dart + # ecosystem don't support version 3.0.0 yet, we support older versions for compatibility. + convert: ">=2.1.1 <4.0.0" + collection: ^1.15.0-nullsafety.5 + synchronized: ^3.0.0-nullsafety + pedantic: ^1.10.0-nullsafety.3 + sqlite3: ^0.1.9-nullsafety dev_dependencies: + analyzer: ^0.40.6 + build_test: ^1.3.0 + build_runner_core: ^6.1.0 moor_generator: ^3.2.0 uuid: ^2.0.0 path: ^1.6.4 - build_runner: '^1.10.1' - test: ^1.9.0 - mockito: ^4.1.0 + build_runner: '^1.10.4' + test: ^1.16.0-nullsafety + mockito: ^4.1.3 rxdart: ^0.24.0 # used to test compatibility with stream queries dependency_overrides: moor_generator: path: ../moor_generator sqlparser: - path: ../sqlparser \ No newline at end of file + path: ../sqlparser + + # Remove after https://github.com/dart-lang/mockito/issues/297 is fixed + mockito: + git: + url: https://github.com/simolus3/mockito.git + ref: generate-inheritance + + uuid: + git: + url: https://github.com/simolus3/dart-uuid.git + ref: null-safety + + crypto: + git: + url: https://github.com/dart-lang/crypto.git + ref: "3.0" + + convert: ^3.0.0-nullsafety \ No newline at end of file diff --git a/moor/test/batch_test.dart b/moor/test/batch_test.dart index 847ea503..495388d3 100644 --- a/moor/test/batch_test.dart +++ b/moor/test/batch_test.dart @@ -1,3 +1,5 @@ +//@dart=2.9 +import 'package:mockito/mockito.dart'; import 'package:moor/moor.dart'; import 'package:test/test.dart'; diff --git a/moor/test/columns/datetime_test.dart b/moor/test/columns/datetime_test.dart index 15273d62..98e33d01 100644 --- a/moor/test/columns/datetime_test.dart +++ b/moor/test/columns/datetime_test.dart @@ -2,12 +2,12 @@ import 'package:moor/moor.dart'; import 'package:test/test.dart'; void main() { - final nullable = GeneratedDateTimeColumn('name', null, true); - final nonNull = GeneratedDateTimeColumn('name', null, false); + final nullable = GeneratedDateTimeColumn('name', 'table', true); + final nonNull = GeneratedDateTimeColumn('name', 'table', false); test('should write column definition', () { - final nonNullQuery = GenerationContext(null, null); - final nullableQuery = GenerationContext(null, null); + final nonNullQuery = GenerationContext.fromDb(null); + final nullableQuery = GenerationContext.fromDb(null); nonNull.writeColumnDefinition(nonNullQuery); nullable.writeColumnDefinition(nullableQuery); @@ -16,7 +16,7 @@ void main() { }); test('can compare', () { - final ctx = GenerationContext(null, null); + final ctx = GenerationContext.fromDb(null); nonNull.isSmallerThan(currentDateAndTime).writeInto(ctx); expect(ctx.sql, "name < strftime('%s', CURRENT_TIMESTAMP)"); diff --git a/moor/test/columns/int_column_test.dart b/moor/test/columns/int_column_test.dart index 129f8b7d..9f19267f 100644 --- a/moor/test/columns/int_column_test.dart +++ b/moor/test/columns/int_column_test.dart @@ -1,3 +1,4 @@ +//@dart=2.9 import 'package:test/test.dart'; import 'package:moor/moor.dart'; @@ -13,7 +14,7 @@ void main() { hasAutoIncrement: true, ); - final context = GenerationContext.fromDb(TodoDb(null)); + final context = GenerationContext.fromDb(TodoDb()); column.writeColumnDefinition(context); expect( @@ -29,7 +30,7 @@ void main() { hasAutoIncrement: false, ); - final context = GenerationContext.fromDb(TodoDb(null)); + final context = GenerationContext.fromDb(TodoDb()); column.writeColumnDefinition(context); expect(context.sql, equals('foo INTEGER NOT NULL PRIMARY KEY')); diff --git a/moor/test/custom_queries_test.dart b/moor/test/custom_queries_test.dart index c3ad2d1c..5736defc 100644 --- a/moor/test/custom_queries_test.dart +++ b/moor/test/custom_queries_test.dart @@ -1,3 +1,5 @@ +//@dart=2.9 +import 'package:mockito/mockito.dart'; import 'package:moor/moor.dart'; import 'package:test/test.dart'; diff --git a/moor/test/data/tables/converter.dart b/moor/test/data/tables/converter.dart index bebf07eb..bed86f60 100644 --- a/moor/test/data/tables/converter.dart +++ b/moor/test/data/tables/converter.dart @@ -10,14 +10,14 @@ class SyncTypeConverter extends TypeConverter { const SyncTypeConverter(); @override - SyncType mapToDart(int fromDb) { + SyncType? mapToDart(int? fromDb) { if (fromDb == null) return null; return SyncType.values[fromDb]; } @override - int mapToSql(SyncType value) { + int? mapToSql(SyncType? value) { return value?.index; } } diff --git a/moor/test/data/tables/custom_tables.g.dart b/moor/test/data/tables/custom_tables.g.dart index 525b2bdc..a1538148 100644 --- a/moor/test/data/tables/custom_tables.g.dart +++ b/moor/test/data/tables/custom_tables.g.dart @@ -9,22 +9,22 @@ part of 'custom_tables.dart'; // ignore_for_file: unnecessary_brace_in_string_interps, unnecessary_this class Config extends DataClass implements Insertable { final String configKey; - final String configValue; - final SyncType syncState; - final SyncType syncStateImplicit; + final String? configValue; + final SyncType? syncState; + final SyncType? syncStateImplicit; Config( - {@required this.configKey, + {required this.configKey, this.configValue, this.syncState, this.syncStateImplicit}); factory Config.fromData(Map data, GeneratedDatabase db, - {String prefix}) { + {String? prefix}) { final effectivePrefix = prefix ?? ''; final stringType = db.typeSystem.forDartType(); final intType = db.typeSystem.forDartType(); return Config( configKey: stringType - .mapFromDatabaseResponse(data['${effectivePrefix}config_key']), + .mapFromDatabaseResponse(data['${effectivePrefix}config_key'])!, configValue: stringType .mapFromDatabaseResponse(data['${effectivePrefix}config_value']), syncState: ConfigTable.$converter0.mapToDart(intType @@ -37,29 +37,25 @@ class Config extends DataClass implements Insertable { @override Map toColumns(bool nullToAbsent) { final map = {}; - if (!nullToAbsent || configKey != null) { - map['config_key'] = Variable(configKey); - } + map['config_key'] = Variable(configKey); if (!nullToAbsent || configValue != null) { - map['config_value'] = Variable(configValue); + map['config_value'] = Variable(configValue); } if (!nullToAbsent || syncState != null) { final converter = ConfigTable.$converter0; - map['sync_state'] = Variable(converter.mapToSql(syncState)); + map['sync_state'] = Variable(converter.mapToSql(syncState)); } if (!nullToAbsent || syncStateImplicit != null) { final converter = ConfigTable.$converter1; map['sync_state_implicit'] = - Variable(converter.mapToSql(syncStateImplicit)); + Variable(converter.mapToSql(syncStateImplicit)); } return map; } ConfigCompanion toCompanion(bool nullToAbsent) { return ConfigCompanion( - configKey: configKey == null && nullToAbsent - ? const Value.absent() - : Value(configKey), + configKey: Value(configKey), configValue: configValue == null && nullToAbsent ? const Value.absent() : Value(configValue), @@ -73,36 +69,36 @@ class Config extends DataClass implements Insertable { } factory Config.fromJson(Map json, - {ValueSerializer serializer}) { + {ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return Config( configKey: serializer.fromJson(json['config_key']), - configValue: serializer.fromJson(json['config_value']), - syncState: serializer.fromJson(json['sync_state']), + configValue: serializer.fromJson(json['config_value']), + syncState: serializer.fromJson(json['sync_state']), syncStateImplicit: - serializer.fromJson(json['sync_state_implicit']), + serializer.fromJson(json['sync_state_implicit']), ); } factory Config.fromJsonString(String encodedJson, - {ValueSerializer serializer}) => + {ValueSerializer? serializer}) => Config.fromJson(DataClass.parseJson(encodedJson) as Map, serializer: serializer); @override - Map toJson({ValueSerializer serializer}) { + Map toJson({ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return { 'config_key': serializer.toJson(configKey), - 'config_value': serializer.toJson(configValue), - 'sync_state': serializer.toJson(syncState), - 'sync_state_implicit': serializer.toJson(syncStateImplicit), + 'config_value': serializer.toJson(configValue), + 'sync_state': serializer.toJson(syncState), + 'sync_state_implicit': serializer.toJson(syncStateImplicit), }; } Config copyWith( - {String configKey, - Value configValue = const Value.absent(), - Value syncState = const Value.absent(), - Value syncStateImplicit = const Value.absent()}) => + {String? configKey, + Value configValue = const Value.absent(), + Value syncState = const Value.absent(), + Value syncStateImplicit = const Value.absent()}) => Config( configKey: configKey ?? this.configKey, configValue: configValue.present ? configValue.value : this.configValue, @@ -139,9 +135,9 @@ class Config extends DataClass implements Insertable { class ConfigCompanion extends UpdateCompanion { final Value configKey; - final Value configValue; - final Value syncState; - final Value syncStateImplicit; + final Value configValue; + final Value syncState; + final Value syncStateImplicit; const ConfigCompanion({ this.configKey = const Value.absent(), this.configValue = const Value.absent(), @@ -149,16 +145,16 @@ class ConfigCompanion extends UpdateCompanion { this.syncStateImplicit = const Value.absent(), }); ConfigCompanion.insert({ - @required String configKey, + required String configKey, this.configValue = const Value.absent(), this.syncState = const Value.absent(), this.syncStateImplicit = const Value.absent(), }) : configKey = Value(configKey); static Insertable custom({ - Expression configKey, - Expression configValue, - Expression syncState, - Expression syncStateImplicit, + Expression? configKey, + Expression? configValue, + Expression? syncState, + Expression? syncStateImplicit, }) { return RawValuesInsertable({ if (configKey != null) 'config_key': configKey, @@ -169,10 +165,10 @@ class ConfigCompanion extends UpdateCompanion { } ConfigCompanion copyWith( - {Value configKey, - Value configValue, - Value syncState, - Value syncStateImplicit}) { + {Value? configKey, + Value? configValue, + Value? syncState, + Value? syncStateImplicit}) { return ConfigCompanion( configKey: configKey ?? this.configKey, configValue: configValue ?? this.configValue, @@ -188,16 +184,16 @@ class ConfigCompanion extends UpdateCompanion { map['config_key'] = Variable(configKey.value); } if (configValue.present) { - map['config_value'] = Variable(configValue.value); + map['config_value'] = Variable(configValue.value); } if (syncState.present) { final converter = ConfigTable.$converter0; - map['sync_state'] = Variable(converter.mapToSql(syncState.value)); + map['sync_state'] = Variable(converter.mapToSql(syncState.value)); } if (syncStateImplicit.present) { final converter = ConfigTable.$converter1; map['sync_state_implicit'] = - Variable(converter.mapToSql(syncStateImplicit.value)); + Variable(converter.mapToSql(syncStateImplicit.value)); } return map; } @@ -216,11 +212,10 @@ class ConfigCompanion extends UpdateCompanion { class ConfigTable extends Table with TableInfo { final GeneratedDatabase _db; - final String _alias; + final String? _alias; ConfigTable(this._db, [this._alias]); final VerificationMeta _configKeyMeta = const VerificationMeta('configKey'); - GeneratedTextColumn _configKey; - GeneratedTextColumn get configKey => _configKey ??= _constructConfigKey(); + late final GeneratedTextColumn configKey = _constructConfigKey(); GeneratedTextColumn _constructConfigKey() { return GeneratedTextColumn('config_key', $tableName, false, $customConstraints: 'not null primary key'); @@ -228,17 +223,14 @@ class ConfigTable extends Table with TableInfo { final VerificationMeta _configValueMeta = const VerificationMeta('configValue'); - GeneratedTextColumn _configValue; - GeneratedTextColumn get configValue => - _configValue ??= _constructConfigValue(); + late final GeneratedTextColumn configValue = _constructConfigValue(); GeneratedTextColumn _constructConfigValue() { return GeneratedTextColumn('config_value', $tableName, true, $customConstraints: ''); } final VerificationMeta _syncStateMeta = const VerificationMeta('syncState'); - GeneratedIntColumn _syncState; - GeneratedIntColumn get syncState => _syncState ??= _constructSyncState(); + late final GeneratedIntColumn syncState = _constructSyncState(); GeneratedIntColumn _constructSyncState() { return GeneratedIntColumn('sync_state', $tableName, true, $customConstraints: ''); @@ -246,9 +238,8 @@ class ConfigTable extends Table with TableInfo { final VerificationMeta _syncStateImplicitMeta = const VerificationMeta('syncStateImplicit'); - GeneratedIntColumn _syncStateImplicit; - GeneratedIntColumn get syncStateImplicit => - _syncStateImplicit ??= _constructSyncStateImplicit(); + late final GeneratedIntColumn syncStateImplicit = + _constructSyncStateImplicit(); GeneratedIntColumn _constructSyncStateImplicit() { return GeneratedIntColumn('sync_state_implicit', $tableName, true, $customConstraints: ''); @@ -270,7 +261,7 @@ class ConfigTable extends Table with TableInfo { final data = instance.toColumns(true); if (data.containsKey('config_key')) { context.handle(_configKeyMeta, - configKey.isAcceptableOrUnknown(data['config_key'], _configKeyMeta)); + configKey.isAcceptableOrUnknown(data['config_key']!, _configKeyMeta)); } else if (isInserting) { context.missing(_configKeyMeta); } @@ -278,7 +269,7 @@ class ConfigTable extends Table with TableInfo { context.handle( _configValueMeta, configValue.isAcceptableOrUnknown( - data['config_value'], _configValueMeta)); + data['config_value']!, _configValueMeta)); } context.handle(_syncStateMeta, const VerificationResult.success()); context.handle(_syncStateImplicitMeta, const VerificationResult.success()); @@ -288,7 +279,7 @@ class ConfigTable extends Table with TableInfo { @override Set get $primaryKey => {configKey}; @override - Config map(Map data, {String tablePrefix}) { + Config map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; return Config.fromData(data, _db, prefix: effectivePrefix); } @@ -298,19 +289,19 @@ class ConfigTable extends Table with TableInfo { return ConfigTable(_db, alias); } - static TypeConverter $converter0 = const SyncTypeConverter(); - static TypeConverter $converter1 = + static TypeConverter $converter0 = const SyncTypeConverter(); + static TypeConverter $converter1 = const EnumIndexConverter(SyncType.values); @override bool get dontWriteConstraints => true; } class WithDefault extends DataClass implements Insertable { - final String a; - final int b; + final String? a; + final int? b; WithDefault({this.a, this.b}); factory WithDefault.fromData(Map data, GeneratedDatabase db, - {String prefix}) { + {String? prefix}) { final effectivePrefix = prefix ?? ''; final stringType = db.typeSystem.forDartType(); final intType = db.typeSystem.forDartType(); @@ -323,10 +314,10 @@ class WithDefault extends DataClass implements Insertable { Map toColumns(bool nullToAbsent) { final map = {}; if (!nullToAbsent || a != null) { - map['a'] = Variable(a); + map['a'] = Variable(a); } if (!nullToAbsent || b != null) { - map['b'] = Variable(b); + map['b'] = Variable(b); } return map; } @@ -339,30 +330,30 @@ class WithDefault extends DataClass implements Insertable { } factory WithDefault.fromJson(Map json, - {ValueSerializer serializer}) { + {ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return WithDefault( - a: serializer.fromJson(json['a']), - b: serializer.fromJson(json['b']), + a: serializer.fromJson(json['a']), + b: serializer.fromJson(json['b']), ); } factory WithDefault.fromJsonString(String encodedJson, - {ValueSerializer serializer}) => + {ValueSerializer? serializer}) => WithDefault.fromJson( DataClass.parseJson(encodedJson) as Map, serializer: serializer); @override - Map toJson({ValueSerializer serializer}) { + Map toJson({ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return { - 'a': serializer.toJson(a), - 'b': serializer.toJson(b), + 'a': serializer.toJson(a), + 'b': serializer.toJson(b), }; } WithDefault copyWith( - {Value a = const Value.absent(), - Value b = const Value.absent()}) => + {Value a = const Value.absent(), + Value b = const Value.absent()}) => WithDefault( a: a.present ? a.value : this.a, b: b.present ? b.value : this.b, @@ -385,8 +376,8 @@ class WithDefault extends DataClass implements Insertable { } class WithDefaultsCompanion extends UpdateCompanion { - final Value a; - final Value b; + final Value a; + final Value b; const WithDefaultsCompanion({ this.a = const Value.absent(), this.b = const Value.absent(), @@ -396,8 +387,8 @@ class WithDefaultsCompanion extends UpdateCompanion { this.b = const Value.absent(), }); static Insertable custom({ - Expression a, - Expression b, + Expression? a, + Expression? b, }) { return RawValuesInsertable({ if (a != null) 'a': a, @@ -405,7 +396,7 @@ class WithDefaultsCompanion extends UpdateCompanion { }); } - WithDefaultsCompanion copyWith({Value a, Value b}) { + WithDefaultsCompanion copyWith({Value? a, Value? b}) { return WithDefaultsCompanion( a: a ?? this.a, b: b ?? this.b, @@ -416,10 +407,10 @@ class WithDefaultsCompanion extends UpdateCompanion { Map toColumns(bool nullToAbsent) { final map = {}; if (a.present) { - map['a'] = Variable(a.value); + map['a'] = Variable(a.value); } if (b.present) { - map['b'] = Variable(b.value); + map['b'] = Variable(b.value); } return map; } @@ -436,11 +427,10 @@ class WithDefaultsCompanion extends UpdateCompanion { class WithDefaults extends Table with TableInfo { final GeneratedDatabase _db; - final String _alias; + final String? _alias; WithDefaults(this._db, [this._alias]); final VerificationMeta _aMeta = const VerificationMeta('a'); - GeneratedTextColumn _a; - GeneratedTextColumn get a => _a ??= _constructA(); + late final GeneratedTextColumn a = _constructA(); GeneratedTextColumn _constructA() { return GeneratedTextColumn('a', $tableName, true, $customConstraints: 'DEFAULT \'something\'', @@ -448,8 +438,7 @@ class WithDefaults extends Table with TableInfo { } final VerificationMeta _bMeta = const VerificationMeta('b'); - GeneratedIntColumn _b; - GeneratedIntColumn get b => _b ??= _constructB(); + late final GeneratedIntColumn b = _constructB(); GeneratedIntColumn _constructB() { return GeneratedIntColumn('b', $tableName, true, $customConstraints: 'UNIQUE'); @@ -469,10 +458,10 @@ class WithDefaults extends Table with TableInfo { final context = VerificationContext(); final data = instance.toColumns(true); if (data.containsKey('a')) { - context.handle(_aMeta, a.isAcceptableOrUnknown(data['a'], _aMeta)); + context.handle(_aMeta, a.isAcceptableOrUnknown(data['a']!, _aMeta)); } if (data.containsKey('b')) { - context.handle(_bMeta, b.isAcceptableOrUnknown(data['b'], _bMeta)); + context.handle(_bMeta, b.isAcceptableOrUnknown(data['b']!, _bMeta)); } return context; } @@ -480,7 +469,7 @@ class WithDefaults extends Table with TableInfo { @override Set get $primaryKey => {}; @override - WithDefault map(Map data, {String tablePrefix}) { + WithDefault map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; return WithDefault.fromData(data, _db, prefix: effectivePrefix); } @@ -496,53 +485,49 @@ class WithDefaults extends Table with TableInfo { class NoId extends DataClass implements Insertable { final Uint8List payload; - NoId({@required this.payload}); + NoId({required this.payload}); factory NoId.fromData(Map data, GeneratedDatabase db, - {String prefix}) { + {String? prefix}) { final effectivePrefix = prefix ?? ''; final uint8ListType = db.typeSystem.forDartType(); return NoId( payload: uint8ListType - .mapFromDatabaseResponse(data['${effectivePrefix}payload']), + .mapFromDatabaseResponse(data['${effectivePrefix}payload'])!, ); } @override Map toColumns(bool nullToAbsent) { final map = {}; - if (!nullToAbsent || payload != null) { - map['payload'] = Variable(payload); - } + map['payload'] = Variable(payload); return map; } NoIdsCompanion toCompanion(bool nullToAbsent) { return NoIdsCompanion( - payload: payload == null && nullToAbsent - ? const Value.absent() - : Value(payload), + payload: Value(payload), ); } factory NoId.fromJson(Map json, - {ValueSerializer serializer}) { + {ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return NoId( payload: serializer.fromJson(json['payload']), ); } factory NoId.fromJsonString(String encodedJson, - {ValueSerializer serializer}) => + {ValueSerializer? serializer}) => NoId.fromJson(DataClass.parseJson(encodedJson) as Map, serializer: serializer); @override - Map toJson({ValueSerializer serializer}) { + Map toJson({ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return { 'payload': serializer.toJson(payload), }; } - NoId copyWith({Uint8List payload}) => NoId( + NoId copyWith({Uint8List? payload}) => NoId( payload: payload ?? this.payload, ); @override @@ -565,17 +550,17 @@ class NoIdsCompanion extends UpdateCompanion { this.payload = const Value.absent(), }); NoIdsCompanion.insert({ - @required Uint8List payload, + required Uint8List payload, }) : payload = Value(payload); static Insertable custom({ - Expression payload, + Expression? payload, }) { return RawValuesInsertable({ if (payload != null) 'payload': payload, }); } - NoIdsCompanion copyWith({Value payload}) { + NoIdsCompanion copyWith({Value? payload}) { return NoIdsCompanion( payload: payload ?? this.payload, ); @@ -601,11 +586,10 @@ class NoIdsCompanion extends UpdateCompanion { class NoIds extends Table with TableInfo { final GeneratedDatabase _db; - final String _alias; + final String? _alias; NoIds(this._db, [this._alias]); final VerificationMeta _payloadMeta = const VerificationMeta('payload'); - GeneratedBlobColumn _payload; - GeneratedBlobColumn get payload => _payload ??= _constructPayload(); + late final GeneratedBlobColumn payload = _constructPayload(); GeneratedBlobColumn _constructPayload() { return GeneratedBlobColumn('payload', $tableName, false, $customConstraints: 'NOT NULL PRIMARY KEY'); @@ -626,7 +610,7 @@ class NoIds extends Table with TableInfo { final data = instance.toColumns(true); if (data.containsKey('payload')) { context.handle(_payloadMeta, - payload.isAcceptableOrUnknown(data['payload'], _payloadMeta)); + payload.isAcceptableOrUnknown(data['payload']!, _payloadMeta)); } else if (isInserting) { context.missing(_payloadMeta); } @@ -636,7 +620,7 @@ class NoIds extends Table with TableInfo { @override Set get $primaryKey => {payload}; @override - NoId map(Map data, {String tablePrefix}) { + NoId map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; return NoId.fromData(data, _db, prefix: effectivePrefix); } @@ -653,20 +637,20 @@ class NoIds extends Table with TableInfo { } class WithConstraint extends DataClass implements Insertable { - final String a; + final String? a; final int b; - final double c; - WithConstraint({this.a, @required this.b, this.c}); + final double? c; + WithConstraint({this.a, required this.b, this.c}); factory WithConstraint.fromData( Map data, GeneratedDatabase db, - {String prefix}) { + {String? prefix}) { final effectivePrefix = prefix ?? ''; final stringType = db.typeSystem.forDartType(); final intType = db.typeSystem.forDartType(); final doubleType = db.typeSystem.forDartType(); return WithConstraint( a: stringType.mapFromDatabaseResponse(data['${effectivePrefix}a']), - b: intType.mapFromDatabaseResponse(data['${effectivePrefix}b']), + b: intType.mapFromDatabaseResponse(data['${effectivePrefix}b'])!, c: doubleType.mapFromDatabaseResponse(data['${effectivePrefix}c']), ); } @@ -674,13 +658,11 @@ class WithConstraint extends DataClass implements Insertable { Map toColumns(bool nullToAbsent) { final map = {}; if (!nullToAbsent || a != null) { - map['a'] = Variable(a); - } - if (!nullToAbsent || b != null) { - map['b'] = Variable(b); + map['a'] = Variable(a); } + map['b'] = Variable(b); if (!nullToAbsent || c != null) { - map['c'] = Variable(c); + map['c'] = Variable(c); } return map; } @@ -688,39 +670,39 @@ class WithConstraint extends DataClass implements Insertable { WithConstraintsCompanion toCompanion(bool nullToAbsent) { return WithConstraintsCompanion( a: a == null && nullToAbsent ? const Value.absent() : Value(a), - b: b == null && nullToAbsent ? const Value.absent() : Value(b), + b: Value(b), c: c == null && nullToAbsent ? const Value.absent() : Value(c), ); } factory WithConstraint.fromJson(Map json, - {ValueSerializer serializer}) { + {ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return WithConstraint( - a: serializer.fromJson(json['a']), + a: serializer.fromJson(json['a']), b: serializer.fromJson(json['b']), - c: serializer.fromJson(json['c']), + c: serializer.fromJson(json['c']), ); } factory WithConstraint.fromJsonString(String encodedJson, - {ValueSerializer serializer}) => + {ValueSerializer? serializer}) => WithConstraint.fromJson( DataClass.parseJson(encodedJson) as Map, serializer: serializer); @override - Map toJson({ValueSerializer serializer}) { + Map toJson({ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return { - 'a': serializer.toJson(a), + 'a': serializer.toJson(a), 'b': serializer.toJson(b), - 'c': serializer.toJson(c), + 'c': serializer.toJson(c), }; } WithConstraint copyWith( - {Value a = const Value.absent(), - int b, - Value c = const Value.absent()}) => + {Value a = const Value.absent(), + int? b, + Value c = const Value.absent()}) => WithConstraint( a: a.present ? a.value : this.a, b: b ?? this.b, @@ -748,9 +730,9 @@ class WithConstraint extends DataClass implements Insertable { } class WithConstraintsCompanion extends UpdateCompanion { - final Value a; + final Value a; final Value b; - final Value c; + final Value c; const WithConstraintsCompanion({ this.a = const Value.absent(), this.b = const Value.absent(), @@ -758,13 +740,13 @@ class WithConstraintsCompanion extends UpdateCompanion { }); WithConstraintsCompanion.insert({ this.a = const Value.absent(), - @required int b, + required int b, this.c = const Value.absent(), }) : b = Value(b); static Insertable custom({ - Expression a, - Expression b, - Expression c, + Expression? a, + Expression? b, + Expression? c, }) { return RawValuesInsertable({ if (a != null) 'a': a, @@ -774,7 +756,7 @@ class WithConstraintsCompanion extends UpdateCompanion { } WithConstraintsCompanion copyWith( - {Value a, Value b, Value c}) { + {Value? a, Value? b, Value? c}) { return WithConstraintsCompanion( a: a ?? this.a, b: b ?? this.b, @@ -786,13 +768,13 @@ class WithConstraintsCompanion extends UpdateCompanion { Map toColumns(bool nullToAbsent) { final map = {}; if (a.present) { - map['a'] = Variable(a.value); + map['a'] = Variable(a.value); } if (b.present) { map['b'] = Variable(b.value); } if (c.present) { - map['c'] = Variable(c.value); + map['c'] = Variable(c.value); } return map; } @@ -811,26 +793,23 @@ class WithConstraintsCompanion extends UpdateCompanion { class WithConstraints extends Table with TableInfo { final GeneratedDatabase _db; - final String _alias; + final String? _alias; WithConstraints(this._db, [this._alias]); final VerificationMeta _aMeta = const VerificationMeta('a'); - GeneratedTextColumn _a; - GeneratedTextColumn get a => _a ??= _constructA(); + late final GeneratedTextColumn a = _constructA(); GeneratedTextColumn _constructA() { return GeneratedTextColumn('a', $tableName, true, $customConstraints: ''); } final VerificationMeta _bMeta = const VerificationMeta('b'); - GeneratedIntColumn _b; - GeneratedIntColumn get b => _b ??= _constructB(); + late final GeneratedIntColumn b = _constructB(); GeneratedIntColumn _constructB() { return GeneratedIntColumn('b', $tableName, false, $customConstraints: 'NOT NULL'); } final VerificationMeta _cMeta = const VerificationMeta('c'); - GeneratedRealColumn _c; - GeneratedRealColumn get c => _c ??= _constructC(); + late final GeneratedRealColumn c = _constructC(); GeneratedRealColumn _constructC() { return GeneratedRealColumn('c', $tableName, true, $customConstraints: ''); } @@ -849,15 +828,15 @@ class WithConstraints extends Table final context = VerificationContext(); final data = instance.toColumns(true); if (data.containsKey('a')) { - context.handle(_aMeta, a.isAcceptableOrUnknown(data['a'], _aMeta)); + context.handle(_aMeta, a.isAcceptableOrUnknown(data['a']!, _aMeta)); } if (data.containsKey('b')) { - context.handle(_bMeta, b.isAcceptableOrUnknown(data['b'], _bMeta)); + context.handle(_bMeta, b.isAcceptableOrUnknown(data['b']!, _bMeta)); } else if (isInserting) { context.missing(_bMeta); } if (data.containsKey('c')) { - context.handle(_cMeta, c.isAcceptableOrUnknown(data['c'], _cMeta)); + context.handle(_cMeta, c.isAcceptableOrUnknown(data['c']!, _cMeta)); } return context; } @@ -865,7 +844,7 @@ class WithConstraints extends Table @override Set get $primaryKey => {}; @override - WithConstraint map(Map data, {String tablePrefix}) { + WithConstraint map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; return WithConstraint.fromData(data, _db, prefix: effectivePrefix); } @@ -884,20 +863,21 @@ class WithConstraints extends Table class MytableData extends DataClass implements Insertable { final int someid; - final String sometext; - final bool isInserting; - final DateTime somedate; + final String? sometext; + final bool? isInserting; + final DateTime? somedate; MytableData( - {@required this.someid, this.sometext, this.isInserting, this.somedate}); + {required this.someid, this.sometext, this.isInserting, this.somedate}); factory MytableData.fromData(Map data, GeneratedDatabase db, - {String prefix}) { + {String? prefix}) { final effectivePrefix = prefix ?? ''; final intType = db.typeSystem.forDartType(); final stringType = db.typeSystem.forDartType(); final boolType = db.typeSystem.forDartType(); final dateTimeType = db.typeSystem.forDartType(); return MytableData( - someid: intType.mapFromDatabaseResponse(data['${effectivePrefix}someid']), + someid: + intType.mapFromDatabaseResponse(data['${effectivePrefix}someid'])!, sometext: stringType .mapFromDatabaseResponse(data['${effectivePrefix}sometext']), isInserting: boolType @@ -909,25 +889,22 @@ class MytableData extends DataClass implements Insertable { @override Map toColumns(bool nullToAbsent) { final map = {}; - if (!nullToAbsent || someid != null) { - map['someid'] = Variable(someid); - } + map['someid'] = Variable(someid); if (!nullToAbsent || sometext != null) { - map['sometext'] = Variable(sometext); + map['sometext'] = Variable(sometext); } if (!nullToAbsent || isInserting != null) { - map['is_inserting'] = Variable(isInserting); + map['is_inserting'] = Variable(isInserting); } if (!nullToAbsent || somedate != null) { - map['somedate'] = Variable(somedate); + map['somedate'] = Variable(somedate); } return map; } MytableCompanion toCompanion(bool nullToAbsent) { return MytableCompanion( - someid: - someid == null && nullToAbsent ? const Value.absent() : Value(someid), + someid: Value(someid), sometext: sometext == null && nullToAbsent ? const Value.absent() : Value(sometext), @@ -941,36 +918,36 @@ class MytableData extends DataClass implements Insertable { } factory MytableData.fromJson(Map json, - {ValueSerializer serializer}) { + {ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return MytableData( someid: serializer.fromJson(json['someid']), - sometext: serializer.fromJson(json['sometext']), - isInserting: serializer.fromJson(json['is_inserting']), - somedate: serializer.fromJson(json['somedate']), + sometext: serializer.fromJson(json['sometext']), + isInserting: serializer.fromJson(json['is_inserting']), + somedate: serializer.fromJson(json['somedate']), ); } factory MytableData.fromJsonString(String encodedJson, - {ValueSerializer serializer}) => + {ValueSerializer? serializer}) => MytableData.fromJson( DataClass.parseJson(encodedJson) as Map, serializer: serializer); @override - Map toJson({ValueSerializer serializer}) { + Map toJson({ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return { 'someid': serializer.toJson(someid), - 'sometext': serializer.toJson(sometext), - 'is_inserting': serializer.toJson(isInserting), - 'somedate': serializer.toJson(somedate), + 'sometext': serializer.toJson(sometext), + 'is_inserting': serializer.toJson(isInserting), + 'somedate': serializer.toJson(somedate), }; } MytableData copyWith( - {int someid, - Value sometext = const Value.absent(), - Value isInserting = const Value.absent(), - Value somedate = const Value.absent()}) => + {int? someid, + Value sometext = const Value.absent(), + Value isInserting = const Value.absent(), + Value somedate = const Value.absent()}) => MytableData( someid: someid ?? this.someid, sometext: sometext.present ? sometext.value : this.sometext, @@ -1005,9 +982,9 @@ class MytableData extends DataClass implements Insertable { class MytableCompanion extends UpdateCompanion { final Value someid; - final Value sometext; - final Value isInserting; - final Value somedate; + final Value sometext; + final Value isInserting; + final Value somedate; const MytableCompanion({ this.someid = const Value.absent(), this.sometext = const Value.absent(), @@ -1021,10 +998,10 @@ class MytableCompanion extends UpdateCompanion { this.somedate = const Value.absent(), }); static Insertable custom({ - Expression someid, - Expression sometext, - Expression isInserting, - Expression somedate, + Expression? someid, + Expression? sometext, + Expression? isInserting, + Expression? somedate, }) { return RawValuesInsertable({ if (someid != null) 'someid': someid, @@ -1035,10 +1012,10 @@ class MytableCompanion extends UpdateCompanion { } MytableCompanion copyWith( - {Value someid, - Value sometext, - Value isInserting, - Value somedate}) { + {Value? someid, + Value? sometext, + Value? isInserting, + Value? somedate}) { return MytableCompanion( someid: someid ?? this.someid, sometext: sometext ?? this.sometext, @@ -1054,13 +1031,13 @@ class MytableCompanion extends UpdateCompanion { map['someid'] = Variable(someid.value); } if (sometext.present) { - map['sometext'] = Variable(sometext.value); + map['sometext'] = Variable(sometext.value); } if (isInserting.present) { - map['is_inserting'] = Variable(isInserting.value); + map['is_inserting'] = Variable(isInserting.value); } if (somedate.present) { - map['somedate'] = Variable(somedate.value); + map['somedate'] = Variable(somedate.value); } return map; } @@ -1079,19 +1056,17 @@ class MytableCompanion extends UpdateCompanion { class Mytable extends Table with TableInfo { final GeneratedDatabase _db; - final String _alias; + final String? _alias; Mytable(this._db, [this._alias]); final VerificationMeta _someidMeta = const VerificationMeta('someid'); - GeneratedIntColumn _someid; - GeneratedIntColumn get someid => _someid ??= _constructSomeid(); + late final GeneratedIntColumn someid = _constructSomeid(); GeneratedIntColumn _constructSomeid() { return GeneratedIntColumn('someid', $tableName, false, declaredAsPrimaryKey: true, $customConstraints: 'NOT NULL PRIMARY KEY'); } final VerificationMeta _sometextMeta = const VerificationMeta('sometext'); - GeneratedTextColumn _sometext; - GeneratedTextColumn get sometext => _sometext ??= _constructSometext(); + late final GeneratedTextColumn sometext = _constructSometext(); GeneratedTextColumn _constructSometext() { return GeneratedTextColumn('sometext', $tableName, true, $customConstraints: ''); @@ -1099,17 +1074,14 @@ class Mytable extends Table with TableInfo { final VerificationMeta _isInsertingMeta = const VerificationMeta('isInserting'); - GeneratedBoolColumn _isInserting; - GeneratedBoolColumn get isInserting => - _isInserting ??= _constructIsInserting(); + late final GeneratedBoolColumn isInserting = _constructIsInserting(); GeneratedBoolColumn _constructIsInserting() { return GeneratedBoolColumn('is_inserting', $tableName, true, $customConstraints: ''); } final VerificationMeta _somedateMeta = const VerificationMeta('somedate'); - GeneratedDateTimeColumn _somedate; - GeneratedDateTimeColumn get somedate => _somedate ??= _constructSomedate(); + late final GeneratedDateTimeColumn somedate = _constructSomedate(); GeneratedDateTimeColumn _constructSomedate() { return GeneratedDateTimeColumn('somedate', $tableName, true, $customConstraints: ''); @@ -1131,22 +1103,22 @@ class Mytable extends Table with TableInfo { final data = instance.toColumns(true); if (data.containsKey('someid')) { context.handle(_someidMeta, - someid.isAcceptableOrUnknown(data['someid'], _someidMeta)); + someid.isAcceptableOrUnknown(data['someid']!, _someidMeta)); } if (data.containsKey('sometext')) { context.handle(_sometextMeta, - sometext.isAcceptableOrUnknown(data['sometext'], _sometextMeta)); + sometext.isAcceptableOrUnknown(data['sometext']!, _sometextMeta)); } if (data.containsKey('is_inserting')) { context.handle( _isInsertingMeta, this .isInserting - .isAcceptableOrUnknown(data['is_inserting'], _isInsertingMeta)); + .isAcceptableOrUnknown(data['is_inserting']!, _isInsertingMeta)); } if (data.containsKey('somedate')) { context.handle(_somedateMeta, - somedate.isAcceptableOrUnknown(data['somedate'], _somedateMeta)); + somedate.isAcceptableOrUnknown(data['somedate']!, _somedateMeta)); } return context; } @@ -1154,7 +1126,7 @@ class Mytable extends Table with TableInfo { @override Set get $primaryKey => {someid}; @override - MytableData map(Map data, {String tablePrefix}) { + MytableData map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; return MytableData.fromData(data, _db, prefix: effectivePrefix); } @@ -1172,46 +1144,38 @@ class EMail extends DataClass implements Insertable { final String sender; final String title; final String body; - EMail({@required this.sender, @required this.title, @required this.body}); + EMail({required this.sender, required this.title, required this.body}); factory EMail.fromData(Map data, GeneratedDatabase db, - {String prefix}) { + {String? prefix}) { final effectivePrefix = prefix ?? ''; final stringType = db.typeSystem.forDartType(); return EMail( sender: - stringType.mapFromDatabaseResponse(data['${effectivePrefix}sender']), + stringType.mapFromDatabaseResponse(data['${effectivePrefix}sender'])!, title: - stringType.mapFromDatabaseResponse(data['${effectivePrefix}title']), - body: stringType.mapFromDatabaseResponse(data['${effectivePrefix}body']), + stringType.mapFromDatabaseResponse(data['${effectivePrefix}title'])!, + body: stringType.mapFromDatabaseResponse(data['${effectivePrefix}body'])!, ); } @override Map toColumns(bool nullToAbsent) { final map = {}; - if (!nullToAbsent || sender != null) { - map['sender'] = Variable(sender); - } - if (!nullToAbsent || title != null) { - map['title'] = Variable(title); - } - if (!nullToAbsent || body != null) { - map['body'] = Variable(body); - } + map['sender'] = Variable(sender); + map['title'] = Variable(title); + map['body'] = Variable(body); return map; } EmailCompanion toCompanion(bool nullToAbsent) { return EmailCompanion( - sender: - sender == null && nullToAbsent ? const Value.absent() : Value(sender), - title: - title == null && nullToAbsent ? const Value.absent() : Value(title), - body: body == null && nullToAbsent ? const Value.absent() : Value(body), + sender: Value(sender), + title: Value(title), + body: Value(body), ); } factory EMail.fromJson(Map json, - {ValueSerializer serializer}) { + {ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return EMail( sender: serializer.fromJson(json['sender']), @@ -1220,11 +1184,11 @@ class EMail extends DataClass implements Insertable { ); } factory EMail.fromJsonString(String encodedJson, - {ValueSerializer serializer}) => + {ValueSerializer? serializer}) => EMail.fromJson(DataClass.parseJson(encodedJson) as Map, serializer: serializer); @override - Map toJson({ValueSerializer serializer}) { + Map toJson({ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return { 'sender': serializer.toJson(sender), @@ -1233,7 +1197,7 @@ class EMail extends DataClass implements Insertable { }; } - EMail copyWith({String sender, String title, String body}) => EMail( + EMail copyWith({String? sender, String? title, String? body}) => EMail( sender: sender ?? this.sender, title: title ?? this.title, body: body ?? this.body, @@ -1270,16 +1234,16 @@ class EmailCompanion extends UpdateCompanion { this.body = const Value.absent(), }); EmailCompanion.insert({ - @required String sender, - @required String title, - @required String body, - }) : sender = Value(sender), + required String sender, + required String title, + required String body, + }) : sender = Value(sender), title = Value(title), body = Value(body); static Insertable custom({ - Expression sender, - Expression title, - Expression body, + Expression? sender, + Expression? title, + Expression? body, }) { return RawValuesInsertable({ if (sender != null) 'sender': sender, @@ -1289,7 +1253,7 @@ class EmailCompanion extends UpdateCompanion { } EmailCompanion copyWith( - {Value sender, Value title, Value body}) { + {Value? sender, Value? title, Value? body}) { return EmailCompanion( sender: sender ?? this.sender, title: title ?? this.title, @@ -1326,27 +1290,24 @@ class EmailCompanion extends UpdateCompanion { class Email extends Table with TableInfo, VirtualTableInfo { final GeneratedDatabase _db; - final String _alias; + final String? _alias; Email(this._db, [this._alias]); final VerificationMeta _senderMeta = const VerificationMeta('sender'); - GeneratedTextColumn _sender; - GeneratedTextColumn get sender => _sender ??= _constructSender(); + late final GeneratedTextColumn sender = _constructSender(); GeneratedTextColumn _constructSender() { return GeneratedTextColumn('sender', $tableName, false, $customConstraints: ''); } final VerificationMeta _titleMeta = const VerificationMeta('title'); - GeneratedTextColumn _title; - GeneratedTextColumn get title => _title ??= _constructTitle(); + late final GeneratedTextColumn title = _constructTitle(); GeneratedTextColumn _constructTitle() { return GeneratedTextColumn('title', $tableName, false, $customConstraints: ''); } final VerificationMeta _bodyMeta = const VerificationMeta('body'); - GeneratedTextColumn _body; - GeneratedTextColumn get body => _body ??= _constructBody(); + late final GeneratedTextColumn body = _constructBody(); GeneratedTextColumn _constructBody() { return GeneratedTextColumn('body', $tableName, false, $customConstraints: ''); @@ -1367,19 +1328,19 @@ class Email extends Table final data = instance.toColumns(true); if (data.containsKey('sender')) { context.handle(_senderMeta, - sender.isAcceptableOrUnknown(data['sender'], _senderMeta)); + sender.isAcceptableOrUnknown(data['sender']!, _senderMeta)); } else if (isInserting) { context.missing(_senderMeta); } if (data.containsKey('title')) { context.handle( - _titleMeta, title.isAcceptableOrUnknown(data['title'], _titleMeta)); + _titleMeta, title.isAcceptableOrUnknown(data['title']!, _titleMeta)); } else if (isInserting) { context.missing(_titleMeta); } if (data.containsKey('body')) { context.handle( - _bodyMeta, body.isAcceptableOrUnknown(data['body'], _bodyMeta)); + _bodyMeta, body.isAcceptableOrUnknown(data['body']!, _bodyMeta)); } else if (isInserting) { context.missing(_bodyMeta); } @@ -1389,7 +1350,7 @@ class Email extends Table @override Set get $primaryKey => {}; @override - EMail map(Map data, {String tablePrefix}) { + EMail map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; return EMail.fromData(data, _db, prefix: effectivePrefix); } @@ -1408,44 +1369,36 @@ class Email extends Table class WeirdData extends DataClass implements Insertable { final int sqlClass; final String textColumn; - WeirdData({@required this.sqlClass, @required this.textColumn}); + WeirdData({required this.sqlClass, required this.textColumn}); factory WeirdData.fromData(Map data, GeneratedDatabase db, - {String prefix}) { + {String? prefix}) { final effectivePrefix = prefix ?? ''; final intType = db.typeSystem.forDartType(); final stringType = db.typeSystem.forDartType(); return WeirdData( sqlClass: - intType.mapFromDatabaseResponse(data['${effectivePrefix}class']), + intType.mapFromDatabaseResponse(data['${effectivePrefix}class'])!, textColumn: - stringType.mapFromDatabaseResponse(data['${effectivePrefix}text']), + stringType.mapFromDatabaseResponse(data['${effectivePrefix}text'])!, ); } @override Map toColumns(bool nullToAbsent) { final map = {}; - if (!nullToAbsent || sqlClass != null) { - map['class'] = Variable(sqlClass); - } - if (!nullToAbsent || textColumn != null) { - map['text'] = Variable(textColumn); - } + map['class'] = Variable(sqlClass); + map['text'] = Variable(textColumn); return map; } WeirdTableCompanion toCompanion(bool nullToAbsent) { return WeirdTableCompanion( - sqlClass: sqlClass == null && nullToAbsent - ? const Value.absent() - : Value(sqlClass), - textColumn: textColumn == null && nullToAbsent - ? const Value.absent() - : Value(textColumn), + sqlClass: Value(sqlClass), + textColumn: Value(textColumn), ); } factory WeirdData.fromJson(Map json, - {ValueSerializer serializer}) { + {ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return WeirdData( sqlClass: serializer.fromJson(json['class']), @@ -1453,12 +1406,12 @@ class WeirdData extends DataClass implements Insertable { ); } factory WeirdData.fromJsonString(String encodedJson, - {ValueSerializer serializer}) => + {ValueSerializer? serializer}) => WeirdData.fromJson( DataClass.parseJson(encodedJson) as Map, serializer: serializer); @override - Map toJson({ValueSerializer serializer}) { + Map toJson({ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return { 'class': serializer.toJson(sqlClass), @@ -1466,7 +1419,7 @@ class WeirdData extends DataClass implements Insertable { }; } - WeirdData copyWith({int sqlClass, String textColumn}) => WeirdData( + WeirdData copyWith({int? sqlClass, String? textColumn}) => WeirdData( sqlClass: sqlClass ?? this.sqlClass, textColumn: textColumn ?? this.textColumn, ); @@ -1497,13 +1450,13 @@ class WeirdTableCompanion extends UpdateCompanion { this.textColumn = const Value.absent(), }); WeirdTableCompanion.insert({ - @required int sqlClass, - @required String textColumn, - }) : sqlClass = Value(sqlClass), + required int sqlClass, + required String textColumn, + }) : sqlClass = Value(sqlClass), textColumn = Value(textColumn); static Insertable custom({ - Expression sqlClass, - Expression textColumn, + Expression? sqlClass, + Expression? textColumn, }) { return RawValuesInsertable({ if (sqlClass != null) 'class': sqlClass, @@ -1512,7 +1465,7 @@ class WeirdTableCompanion extends UpdateCompanion { } WeirdTableCompanion copyWith( - {Value sqlClass, Value textColumn}) { + {Value? sqlClass, Value? textColumn}) { return WeirdTableCompanion( sqlClass: sqlClass ?? this.sqlClass, textColumn: textColumn ?? this.textColumn, @@ -1543,19 +1496,17 @@ class WeirdTableCompanion extends UpdateCompanion { class WeirdTable extends Table with TableInfo { final GeneratedDatabase _db; - final String _alias; + final String? _alias; WeirdTable(this._db, [this._alias]); final VerificationMeta _sqlClassMeta = const VerificationMeta('sqlClass'); - GeneratedIntColumn _sqlClass; - GeneratedIntColumn get sqlClass => _sqlClass ??= _constructSqlClass(); + late final GeneratedIntColumn sqlClass = _constructSqlClass(); GeneratedIntColumn _constructSqlClass() { return GeneratedIntColumn('class', $tableName, false, $customConstraints: 'NOT NULL'); } final VerificationMeta _textColumnMeta = const VerificationMeta('textColumn'); - GeneratedTextColumn _textColumn; - GeneratedTextColumn get textColumn => _textColumn ??= _constructTextColumn(); + late final GeneratedTextColumn textColumn = _constructTextColumn(); GeneratedTextColumn _constructTextColumn() { return GeneratedTextColumn('text', $tableName, false, $customConstraints: 'NOT NULL'); @@ -1576,13 +1527,13 @@ class WeirdTable extends Table with TableInfo { final data = instance.toColumns(true); if (data.containsKey('class')) { context.handle(_sqlClassMeta, - sqlClass.isAcceptableOrUnknown(data['class'], _sqlClassMeta)); + sqlClass.isAcceptableOrUnknown(data['class']!, _sqlClassMeta)); } else if (isInserting) { context.missing(_sqlClassMeta); } if (data.containsKey('text')) { context.handle(_textColumnMeta, - textColumn.isAcceptableOrUnknown(data['text'], _textColumnMeta)); + textColumn.isAcceptableOrUnknown(data['text']!, _textColumnMeta)); } else if (isInserting) { context.missing(_textColumnMeta); } @@ -1592,7 +1543,7 @@ class WeirdTable extends Table with TableInfo { @override Set get $primaryKey => {}; @override - WeirdData map(Map data, {String tablePrefix}) { + WeirdData map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; return WeirdData.fromData(data, _db, prefix: effectivePrefix); } @@ -1609,33 +1560,23 @@ class WeirdTable extends Table with TableInfo { abstract class _$CustomTablesDb extends GeneratedDatabase { _$CustomTablesDb(QueryExecutor e) : super(SqlTypeSystem.defaultInstance, e); _$CustomTablesDb.connect(DatabaseConnection c) : super.connect(c); - ConfigTable _config; - ConfigTable get config => _config ??= ConfigTable(this); - Index _valueIdx; - Index get valueIdx => _valueIdx ??= Index('value_idx', + late final ConfigTable config = ConfigTable(this); + late final Index valueIdx = Index('value_idx', 'CREATE INDEX IF NOT EXISTS value_idx ON config (config_value);'); - WithDefaults _withDefaults; - WithDefaults get withDefaults => _withDefaults ??= WithDefaults(this); - Trigger _myTrigger; - Trigger get myTrigger => _myTrigger ??= Trigger( + late final WithDefaults withDefaults = WithDefaults(this); + late final Trigger myTrigger = Trigger( 'CREATE TRIGGER my_trigger AFTER INSERT ON config BEGIN\n INSERT INTO with_defaults VALUES (new.config_key, LENGTH(new.config_value));\nEND;', 'my_trigger'); - NoIds _noIds; - NoIds get noIds => _noIds ??= NoIds(this); - WithConstraints _withConstraints; - WithConstraints get withConstraints => - _withConstraints ??= WithConstraints(this); - Mytable _mytable; - Mytable get mytable => _mytable ??= Mytable(this); - Email _email; - Email get email => _email ??= Email(this); - WeirdTable _weirdTable; - WeirdTable get weirdTable => _weirdTable ??= WeirdTable(this); + late final NoIds noIds = NoIds(this); + late final WithConstraints withConstraints = WithConstraints(this); + late final Mytable mytable = Mytable(this); + late final Email email = Email(this); + late final WeirdTable weirdTable = WeirdTable(this); Selectable readConfig(String var1) { return customSelect( 'SELECT\n config_key AS ck,\n config_value as cf,\n sync_state AS cs1,\n sync_state_implicit AS cs2\nFROM config WHERE config_key = ?', variables: [ - Variable.withString(var1) + Variable(var1) ], readsFrom: { config @@ -1648,7 +1589,7 @@ abstract class _$CustomTablesDb extends GeneratedDatabase { } Selectable readMultiple(List var1, - {@required OrderBy clause}) { + {required OrderBy clause}) { var $arrayStartIndex = 1; final expandedvar1 = $expandVar($arrayStartIndex, var1.length); $arrayStartIndex += var1.length; @@ -1657,7 +1598,7 @@ abstract class _$CustomTablesDb extends GeneratedDatabase { return customSelect( 'SELECT * FROM config WHERE config_key IN ($expandedvar1) ORDER BY ${generatedclause.sql}', variables: [ - for (var $ in var1) Variable.withString($), + for (var $ in var1) Variable($), ...generatedclause.introducedVariables ], readsFrom: { @@ -1673,16 +1614,16 @@ abstract class _$CustomTablesDb extends GeneratedDatabase { readsFrom: {config}).map(config.mapFromRow); } - Selectable typeConverterVar(SyncType var1, List var2) { + Selectable typeConverterVar(SyncType? var1, List var2) { var $arrayStartIndex = 2; final expandedvar2 = $expandVar($arrayStartIndex, var2.length); $arrayStartIndex += var2.length; return customSelect( 'SELECT config_key FROM config WHERE sync_state = ? OR sync_state_implicit IN ($expandedvar2)', variables: [ - Variable.withInt(ConfigTable.$converter0.mapToSql(var1)), + Variable(ConfigTable.$converter0.mapToSql(var1)!), for (var $ in var2) - Variable.withInt(ConfigTable.$converter1.mapToSql($)) + Variable(ConfigTable.$converter1.mapToSql($)!) ], readsFrom: { config @@ -1715,7 +1656,7 @@ abstract class _$CustomTablesDb extends GeneratedDatabase { }); } - Selectable multiple({@required Expression predicate}) { + Selectable multiple({required Expression predicate}) { final generatedpredicate = $write(predicate, hasMultipleTables: true); return customSelect( 'SELECT d.*, "c"."a" AS "nested_0.a", "c"."b" AS "nested_0.b", "c"."c" AS "nested_0.c" FROM with_constraints c\n INNER JOIN with_defaults d\n ON d.a = c.a AND d.b = c.b\n WHERE ${generatedpredicate.sql}', @@ -1730,14 +1671,14 @@ abstract class _$CustomTablesDb extends GeneratedDatabase { }); } - Selectable searchEmails({@required String term}) { + Selectable searchEmails({required String term}) { return customSelect( 'SELECT * FROM email WHERE email MATCH :term ORDER BY rank', - variables: [Variable.withString(term)], + variables: [Variable(term)], readsFrom: {email}).map(email.mapFromRow); } - Selectable readRowId({@required Expression expr}) { + Selectable readRowId({required Expression expr}) { final generatedexpr = $write(expr); return customSelect( 'SELECT oid, * FROM config WHERE _rowid_ = ${generatedexpr.sql}', @@ -1762,10 +1703,10 @@ abstract class _$CustomTablesDb extends GeneratedDatabase { readsFrom: {}).map((QueryRow row) => row.readInt('x')); } - Future writeConfig({@required String key, @required String value}) { + Future writeConfig({required String key, required String value}) { return customInsert( 'REPLACE INTO config (config_key, config_value) VALUES (:key, :value)', - variables: [Variable.withString(key), Variable.withString(value)], + variables: [Variable(key), Variable(value)], updates: {config}, ); } @@ -1802,10 +1743,10 @@ abstract class _$CustomTablesDb extends GeneratedDatabase { class JsonResult extends CustomResultSet { final String key; - final String value; + final String? value; JsonResult({ - @required QueryRow row, - this.key, + required QueryRow row, + required this.key, this.value, }) : super(row); @override @@ -1827,11 +1768,11 @@ class JsonResult extends CustomResultSet { } class MultipleResult extends CustomResultSet { - final String a; - final int b; - final WithConstraint c; + final String? a; + final int? b; + final WithConstraint? c; MultipleResult({ - @required QueryRow row, + required QueryRow row, this.a, this.b, this.c, @@ -1859,13 +1800,13 @@ class MultipleResult extends CustomResultSet { class ReadRowIdResult extends CustomResultSet { final int rowid; final String configKey; - final String configValue; - final SyncType syncState; - final SyncType syncStateImplicit; + final String? configValue; + final SyncType? syncState; + final SyncType? syncStateImplicit; ReadRowIdResult({ - @required QueryRow row, - this.rowid, - this.configKey, + required QueryRow row, + required this.rowid, + required this.configKey, this.configValue, this.syncState, this.syncStateImplicit, diff --git a/moor/test/data/tables/todos.dart b/moor/test/data/tables/todos.dart index 405e0a27..05e100ff 100644 --- a/moor/test/data/tables/todos.dart +++ b/moor/test/data/tables/todos.dart @@ -1,6 +1,9 @@ import 'package:moor/moor.dart'; +// ignore: import_of_legacy_library_into_null_safe import 'package:uuid/uuid.dart'; +import '../utils/null_executor.dart'; + part 'todos.g.dart'; mixin AutoIncrement on Table { @@ -80,12 +83,12 @@ class MyCustomObject { class CustomConverter extends TypeConverter { const CustomConverter(); @override - MyCustomObject mapToDart(String fromDb) { + MyCustomObject? mapToDart(String? fromDb) { return fromDb == null ? null : MyCustomObject(fromDb); } @override - String mapToSql(MyCustomObject value) { + String? mapToSql(MyCustomObject? value) { return value?.data; } } @@ -111,7 +114,7 @@ class CustomConverter extends TypeConverter { }, ) class TodoDb extends _$TodoDb { - TodoDb(QueryExecutor e) : super(e) { + TodoDb([QueryExecutor? e]) : super(e ?? const NullExecutor()) { moorRuntimeOptions.dontWarnAboutMultipleDatabases = true; } TodoDb.connect(DatabaseConnection connection) : super.connect(connection) { diff --git a/moor/test/data/tables/todos.g.dart b/moor/test/data/tables/todos.g.dart index 14df2562..c0a8d705 100644 --- a/moor/test/data/tables/todos.g.dart +++ b/moor/test/data/tables/todos.g.dart @@ -9,28 +9,28 @@ part of 'todos.dart'; // ignore_for_file: unnecessary_brace_in_string_interps, unnecessary_this class TodoEntry extends DataClass implements Insertable { final int id; - final String title; + final String? title; final String content; - final DateTime targetDate; - final int category; + final DateTime? targetDate; + final int? category; TodoEntry( - {@required this.id, + {required this.id, this.title, - @required this.content, + required this.content, this.targetDate, this.category}); factory TodoEntry.fromData(Map data, GeneratedDatabase db, - {String prefix}) { + {String? prefix}) { final effectivePrefix = prefix ?? ''; final intType = db.typeSystem.forDartType(); final stringType = db.typeSystem.forDartType(); final dateTimeType = db.typeSystem.forDartType(); return TodoEntry( - id: intType.mapFromDatabaseResponse(data['${effectivePrefix}id']), + id: intType.mapFromDatabaseResponse(data['${effectivePrefix}id'])!, title: stringType.mapFromDatabaseResponse(data['${effectivePrefix}title']), - content: - stringType.mapFromDatabaseResponse(data['${effectivePrefix}content']), + content: stringType + .mapFromDatabaseResponse(data['${effectivePrefix}content'])!, targetDate: dateTimeType .mapFromDatabaseResponse(data['${effectivePrefix}target_date']), category: @@ -40,32 +40,26 @@ class TodoEntry extends DataClass implements Insertable { @override Map toColumns(bool nullToAbsent) { final map = {}; - if (!nullToAbsent || id != null) { - map['id'] = Variable(id); - } + map['id'] = Variable(id); if (!nullToAbsent || title != null) { - map['title'] = Variable(title); - } - if (!nullToAbsent || content != null) { - map['content'] = Variable(content); + map['title'] = Variable(title); } + map['content'] = Variable(content); if (!nullToAbsent || targetDate != null) { - map['target_date'] = Variable(targetDate); + map['target_date'] = Variable(targetDate); } if (!nullToAbsent || category != null) { - map['category'] = Variable(category); + map['category'] = Variable(category); } return map; } TodosTableCompanion toCompanion(bool nullToAbsent) { return TodosTableCompanion( - id: id == null && nullToAbsent ? const Value.absent() : Value(id), + id: Value(id), title: title == null && nullToAbsent ? const Value.absent() : Value(title), - content: content == null && nullToAbsent - ? const Value.absent() - : Value(content), + content: Value(content), targetDate: targetDate == null && nullToAbsent ? const Value.absent() : Value(targetDate), @@ -76,39 +70,39 @@ class TodoEntry extends DataClass implements Insertable { } factory TodoEntry.fromJson(Map json, - {ValueSerializer serializer}) { + {ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return TodoEntry( id: serializer.fromJson(json['id']), - title: serializer.fromJson(json['title']), + title: serializer.fromJson(json['title']), content: serializer.fromJson(json['content']), - targetDate: serializer.fromJson(json['target_date']), - category: serializer.fromJson(json['category']), + targetDate: serializer.fromJson(json['target_date']), + category: serializer.fromJson(json['category']), ); } factory TodoEntry.fromJsonString(String encodedJson, - {ValueSerializer serializer}) => + {ValueSerializer? serializer}) => TodoEntry.fromJson( DataClass.parseJson(encodedJson) as Map, serializer: serializer); @override - Map toJson({ValueSerializer serializer}) { + Map toJson({ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return { 'id': serializer.toJson(id), - 'title': serializer.toJson(title), + 'title': serializer.toJson(title), 'content': serializer.toJson(content), - 'target_date': serializer.toJson(targetDate), - 'category': serializer.toJson(category), + 'target_date': serializer.toJson(targetDate), + 'category': serializer.toJson(category), }; } TodoEntry copyWith( - {int id, - Value title = const Value.absent(), - String content, - Value targetDate = const Value.absent(), - Value category = const Value.absent()}) => + {int? id, + Value title = const Value.absent(), + String? content, + Value targetDate = const Value.absent(), + Value category = const Value.absent()}) => TodoEntry( id: id ?? this.id, title: title.present ? title.value : this.title, @@ -148,10 +142,10 @@ class TodoEntry extends DataClass implements Insertable { class TodosTableCompanion extends UpdateCompanion { final Value id; - final Value title; + final Value title; final Value content; - final Value targetDate; - final Value category; + final Value targetDate; + final Value category; const TodosTableCompanion({ this.id = const Value.absent(), this.title = const Value.absent(), @@ -162,16 +156,16 @@ class TodosTableCompanion extends UpdateCompanion { TodosTableCompanion.insert({ this.id = const Value.absent(), this.title = const Value.absent(), - @required String content, + required String content, this.targetDate = const Value.absent(), this.category = const Value.absent(), }) : content = Value(content); static Insertable custom({ - Expression id, - Expression title, - Expression content, - Expression targetDate, - Expression category, + Expression? id, + Expression? title, + Expression? content, + Expression? targetDate, + Expression? category, }) { return RawValuesInsertable({ if (id != null) 'id': id, @@ -183,11 +177,11 @@ class TodosTableCompanion extends UpdateCompanion { } TodosTableCompanion copyWith( - {Value id, - Value title, - Value content, - Value targetDate, - Value category}) { + {Value? id, + Value? title, + Value? content, + Value? targetDate, + Value? category}) { return TodosTableCompanion( id: id ?? this.id, title: title ?? this.title, @@ -204,16 +198,16 @@ class TodosTableCompanion extends UpdateCompanion { map['id'] = Variable(id.value); } if (title.present) { - map['title'] = Variable(title.value); + map['title'] = Variable(title.value); } if (content.present) { map['content'] = Variable(content.value); } if (targetDate.present) { - map['target_date'] = Variable(targetDate.value); + map['target_date'] = Variable(targetDate.value); } if (category.present) { - map['category'] = Variable(category.value); + map['category'] = Variable(category.value); } return map; } @@ -234,30 +228,27 @@ class TodosTableCompanion extends UpdateCompanion { class $TodosTableTable extends TodosTable with TableInfo<$TodosTableTable, TodoEntry> { final GeneratedDatabase _db; - final String _alias; + final String? _alias; $TodosTableTable(this._db, [this._alias]); final VerificationMeta _idMeta = const VerificationMeta('id'); - GeneratedIntColumn _id; @override - GeneratedIntColumn get id => _id ??= _constructId(); + late final GeneratedIntColumn id = _constructId(); GeneratedIntColumn _constructId() { return GeneratedIntColumn('id', $tableName, false, hasAutoIncrement: true, declaredAsPrimaryKey: true); } final VerificationMeta _titleMeta = const VerificationMeta('title'); - GeneratedTextColumn _title; @override - GeneratedTextColumn get title => _title ??= _constructTitle(); + late final GeneratedTextColumn title = _constructTitle(); GeneratedTextColumn _constructTitle() { return GeneratedTextColumn('title', $tableName, true, minTextLength: 4, maxTextLength: 16); } final VerificationMeta _contentMeta = const VerificationMeta('content'); - GeneratedTextColumn _content; @override - GeneratedTextColumn get content => _content ??= _constructContent(); + late final GeneratedTextColumn content = _constructContent(); GeneratedTextColumn _constructContent() { return GeneratedTextColumn( 'content', @@ -267,10 +258,8 @@ class $TodosTableTable extends TodosTable } final VerificationMeta _targetDateMeta = const VerificationMeta('targetDate'); - GeneratedDateTimeColumn _targetDate; @override - GeneratedDateTimeColumn get targetDate => - _targetDate ??= _constructTargetDate(); + late final GeneratedDateTimeColumn targetDate = _constructTargetDate(); GeneratedDateTimeColumn _constructTargetDate() { return GeneratedDateTimeColumn( 'target_date', @@ -280,9 +269,8 @@ class $TodosTableTable extends TodosTable } final VerificationMeta _categoryMeta = const VerificationMeta('category'); - GeneratedIntColumn _category; @override - GeneratedIntColumn get category => _category ??= _constructCategory(); + late final GeneratedIntColumn category = _constructCategory(); GeneratedIntColumn _constructCategory() { return GeneratedIntColumn( 'category', @@ -306,15 +294,15 @@ class $TodosTableTable extends TodosTable final context = VerificationContext(); final data = instance.toColumns(true); if (data.containsKey('id')) { - context.handle(_idMeta, id.isAcceptableOrUnknown(data['id'], _idMeta)); + context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); } if (data.containsKey('title')) { context.handle( - _titleMeta, title.isAcceptableOrUnknown(data['title'], _titleMeta)); + _titleMeta, title.isAcceptableOrUnknown(data['title']!, _titleMeta)); } if (data.containsKey('content')) { context.handle(_contentMeta, - content.isAcceptableOrUnknown(data['content'], _contentMeta)); + content.isAcceptableOrUnknown(data['content']!, _contentMeta)); } else if (isInserting) { context.missing(_contentMeta); } @@ -322,11 +310,11 @@ class $TodosTableTable extends TodosTable context.handle( _targetDateMeta, targetDate.isAcceptableOrUnknown( - data['target_date'], _targetDateMeta)); + data['target_date']!, _targetDateMeta)); } if (data.containsKey('category')) { context.handle(_categoryMeta, - category.isAcceptableOrUnknown(data['category'], _categoryMeta)); + category.isAcceptableOrUnknown(data['category']!, _categoryMeta)); } return context; } @@ -334,7 +322,7 @@ class $TodosTableTable extends TodosTable @override Set get $primaryKey => {id}; @override - TodoEntry map(Map data, {String tablePrefix}) { + TodoEntry map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; return TodoEntry.fromData(data, _db, prefix: effectivePrefix); } @@ -350,50 +338,42 @@ class Category extends DataClass implements Insertable { final String description; final CategoryPriority priority; Category( - {@required this.id, @required this.description, @required this.priority}); + {required this.id, required this.description, required this.priority}); factory Category.fromData(Map data, GeneratedDatabase db, - {String prefix}) { + {String? prefix}) { final effectivePrefix = prefix ?? ''; final intType = db.typeSystem.forDartType(); final stringType = db.typeSystem.forDartType(); return Category( - id: intType.mapFromDatabaseResponse(data['${effectivePrefix}id']), + id: intType.mapFromDatabaseResponse(data['${effectivePrefix}id'])!, description: - stringType.mapFromDatabaseResponse(data['${effectivePrefix}desc']), + stringType.mapFromDatabaseResponse(data['${effectivePrefix}desc'])!, priority: $CategoriesTable.$converter0.mapToDart( - intType.mapFromDatabaseResponse(data['${effectivePrefix}priority'])), + intType.mapFromDatabaseResponse(data['${effectivePrefix}priority']))!, ); } @override Map toColumns(bool nullToAbsent) { final map = {}; - if (!nullToAbsent || id != null) { - map['id'] = Variable(id); - } - if (!nullToAbsent || description != null) { - map['desc'] = Variable(description); - } - if (!nullToAbsent || priority != null) { + map['id'] = Variable(id); + map['desc'] = Variable(description); + { final converter = $CategoriesTable.$converter0; - map['priority'] = Variable(converter.mapToSql(priority)); + map['priority'] = Variable(converter.mapToSql(priority)!); } return map; } CategoriesCompanion toCompanion(bool nullToAbsent) { return CategoriesCompanion( - id: id == null && nullToAbsent ? const Value.absent() : Value(id), - description: description == null && nullToAbsent - ? const Value.absent() - : Value(description), - priority: priority == null && nullToAbsent - ? const Value.absent() - : Value(priority), + id: Value(id), + description: Value(description), + priority: Value(priority), ); } factory Category.fromJson(Map json, - {ValueSerializer serializer}) { + {ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return Category( id: serializer.fromJson(json['id']), @@ -402,12 +382,12 @@ class Category extends DataClass implements Insertable { ); } factory Category.fromJsonString(String encodedJson, - {ValueSerializer serializer}) => + {ValueSerializer? serializer}) => Category.fromJson( DataClass.parseJson(encodedJson) as Map, serializer: serializer); @override - Map toJson({ValueSerializer serializer}) { + Map toJson({ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return { 'id': serializer.toJson(id), @@ -416,7 +396,8 @@ class Category extends DataClass implements Insertable { }; } - Category copyWith({int id, String description, CategoryPriority priority}) => + Category copyWith( + {int? id, String? description, CategoryPriority? priority}) => Category( id: id ?? this.id, description: description ?? this.description, @@ -455,13 +436,13 @@ class CategoriesCompanion extends UpdateCompanion { }); CategoriesCompanion.insert({ this.id = const Value.absent(), - @required String description, + required String description, this.priority = const Value.absent(), }) : description = Value(description); static Insertable custom({ - Expression id, - Expression description, - Expression priority, + Expression? id, + Expression? description, + Expression? priority, }) { return RawValuesInsertable({ if (id != null) 'id': id, @@ -471,9 +452,9 @@ class CategoriesCompanion extends UpdateCompanion { } CategoriesCompanion copyWith( - {Value id, - Value description, - Value priority}) { + {Value? id, + Value? description, + Value? priority}) { return CategoriesCompanion( id: id ?? this.id, description: description ?? this.description, @@ -492,7 +473,7 @@ class CategoriesCompanion extends UpdateCompanion { } if (priority.present) { final converter = $CategoriesTable.$converter0; - map['priority'] = Variable(converter.mapToSql(priority.value)); + map['priority'] = Variable(converter.mapToSql(priority.value)!); } return map; } @@ -511,12 +492,11 @@ class CategoriesCompanion extends UpdateCompanion { class $CategoriesTable extends Categories with TableInfo<$CategoriesTable, Category> { final GeneratedDatabase _db; - final String _alias; + final String? _alias; $CategoriesTable(this._db, [this._alias]); final VerificationMeta _idMeta = const VerificationMeta('id'); - GeneratedIntColumn _id; @override - GeneratedIntColumn get id => _id ??= _constructId(); + late final GeneratedIntColumn id = _constructId(); GeneratedIntColumn _constructId() { return GeneratedIntColumn('id', $tableName, false, hasAutoIncrement: true, declaredAsPrimaryKey: true); @@ -524,19 +504,16 @@ class $CategoriesTable extends Categories final VerificationMeta _descriptionMeta = const VerificationMeta('description'); - GeneratedTextColumn _description; @override - GeneratedTextColumn get description => - _description ??= _constructDescription(); + late final GeneratedTextColumn description = _constructDescription(); GeneratedTextColumn _constructDescription() { return GeneratedTextColumn('desc', $tableName, false, $customConstraints: 'NOT NULL UNIQUE'); } final VerificationMeta _priorityMeta = const VerificationMeta('priority'); - GeneratedIntColumn _priority; @override - GeneratedIntColumn get priority => _priority ??= _constructPriority(); + late final GeneratedIntColumn priority = _constructPriority(); GeneratedIntColumn _constructPriority() { return GeneratedIntColumn('priority', $tableName, false, defaultValue: const Constant(0)); @@ -556,11 +533,11 @@ class $CategoriesTable extends Categories final context = VerificationContext(); final data = instance.toColumns(true); if (data.containsKey('id')) { - context.handle(_idMeta, id.isAcceptableOrUnknown(data['id'], _idMeta)); + context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); } if (data.containsKey('desc')) { context.handle(_descriptionMeta, - description.isAcceptableOrUnknown(data['desc'], _descriptionMeta)); + description.isAcceptableOrUnknown(data['desc']!, _descriptionMeta)); } else if (isInserting) { context.missing(_descriptionMeta); } @@ -571,7 +548,7 @@ class $CategoriesTable extends Categories @override Set get $primaryKey => {id}; @override - Category map(Map data, {String tablePrefix}) { + Category map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; return Category.fromData(data, _db, prefix: effectivePrefix); } @@ -581,7 +558,7 @@ class $CategoriesTable extends Categories return $CategoriesTable(_db, alias); } - static TypeConverter $converter0 = + static TypeConverter $converter0 = const EnumIndexConverter(CategoryPriority.values); } @@ -592,13 +569,13 @@ class User extends DataClass implements Insertable { final Uint8List profilePicture; final DateTime creationTime; User( - {@required this.id, - @required this.name, - @required this.isAwesome, - @required this.profilePicture, - @required this.creationTime}); + {required this.id, + required this.name, + required this.isAwesome, + required this.profilePicture, + required this.creationTime}); factory User.fromData(Map data, GeneratedDatabase db, - {String prefix}) { + {String? prefix}) { final effectivePrefix = prefix ?? ''; final intType = db.typeSystem.forDartType(); final stringType = db.typeSystem.forDartType(); @@ -606,55 +583,39 @@ class User extends DataClass implements Insertable { final uint8ListType = db.typeSystem.forDartType(); final dateTimeType = db.typeSystem.forDartType(); return User( - id: intType.mapFromDatabaseResponse(data['${effectivePrefix}id']), - name: stringType.mapFromDatabaseResponse(data['${effectivePrefix}name']), + id: intType.mapFromDatabaseResponse(data['${effectivePrefix}id'])!, + name: stringType.mapFromDatabaseResponse(data['${effectivePrefix}name'])!, isAwesome: boolType - .mapFromDatabaseResponse(data['${effectivePrefix}is_awesome']), + .mapFromDatabaseResponse(data['${effectivePrefix}is_awesome'])!, profilePicture: uint8ListType - .mapFromDatabaseResponse(data['${effectivePrefix}profile_picture']), + .mapFromDatabaseResponse(data['${effectivePrefix}profile_picture'])!, creationTime: dateTimeType - .mapFromDatabaseResponse(data['${effectivePrefix}creation_time']), + .mapFromDatabaseResponse(data['${effectivePrefix}creation_time'])!, ); } @override Map toColumns(bool nullToAbsent) { final map = {}; - if (!nullToAbsent || id != null) { - map['id'] = Variable(id); - } - if (!nullToAbsent || name != null) { - map['name'] = Variable(name); - } - if (!nullToAbsent || isAwesome != null) { - map['is_awesome'] = Variable(isAwesome); - } - if (!nullToAbsent || profilePicture != null) { - map['profile_picture'] = Variable(profilePicture); - } - if (!nullToAbsent || creationTime != null) { - map['creation_time'] = Variable(creationTime); - } + map['id'] = Variable(id); + map['name'] = Variable(name); + map['is_awesome'] = Variable(isAwesome); + map['profile_picture'] = Variable(profilePicture); + map['creation_time'] = Variable(creationTime); return map; } UsersCompanion toCompanion(bool nullToAbsent) { return UsersCompanion( - id: id == null && nullToAbsent ? const Value.absent() : Value(id), - name: name == null && nullToAbsent ? const Value.absent() : Value(name), - isAwesome: isAwesome == null && nullToAbsent - ? const Value.absent() - : Value(isAwesome), - profilePicture: profilePicture == null && nullToAbsent - ? const Value.absent() - : Value(profilePicture), - creationTime: creationTime == null && nullToAbsent - ? const Value.absent() - : Value(creationTime), + id: Value(id), + name: Value(name), + isAwesome: Value(isAwesome), + profilePicture: Value(profilePicture), + creationTime: Value(creationTime), ); } factory User.fromJson(Map json, - {ValueSerializer serializer}) { + {ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return User( id: serializer.fromJson(json['id']), @@ -665,11 +626,11 @@ class User extends DataClass implements Insertable { ); } factory User.fromJsonString(String encodedJson, - {ValueSerializer serializer}) => + {ValueSerializer? serializer}) => User.fromJson(DataClass.parseJson(encodedJson) as Map, serializer: serializer); @override - Map toJson({ValueSerializer serializer}) { + Map toJson({ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return { 'id': serializer.toJson(id), @@ -681,11 +642,11 @@ class User extends DataClass implements Insertable { } User copyWith( - {int id, - String name, - bool isAwesome, - Uint8List profilePicture, - DateTime creationTime}) => + {int? id, + String? name, + bool? isAwesome, + Uint8List? profilePicture, + DateTime? creationTime}) => User( id: id ?? this.id, name: name ?? this.name, @@ -738,18 +699,18 @@ class UsersCompanion extends UpdateCompanion { }); UsersCompanion.insert({ this.id = const Value.absent(), - @required String name, + required String name, this.isAwesome = const Value.absent(), - @required Uint8List profilePicture, + required Uint8List profilePicture, this.creationTime = const Value.absent(), }) : name = Value(name), profilePicture = Value(profilePicture); static Insertable custom({ - Expression id, - Expression name, - Expression isAwesome, - Expression profilePicture, - Expression creationTime, + Expression? id, + Expression? name, + Expression? isAwesome, + Expression? profilePicture, + Expression? creationTime, }) { return RawValuesInsertable({ if (id != null) 'id': id, @@ -761,11 +722,11 @@ class UsersCompanion extends UpdateCompanion { } UsersCompanion copyWith( - {Value id, - Value name, - Value isAwesome, - Value profilePicture, - Value creationTime}) { + {Value? id, + Value? name, + Value? isAwesome, + Value? profilePicture, + Value? creationTime}) { return UsersCompanion( id: id ?? this.id, name: name ?? this.name, @@ -811,30 +772,27 @@ class UsersCompanion extends UpdateCompanion { class $UsersTable extends Users with TableInfo<$UsersTable, User> { final GeneratedDatabase _db; - final String _alias; + final String? _alias; $UsersTable(this._db, [this._alias]); final VerificationMeta _idMeta = const VerificationMeta('id'); - GeneratedIntColumn _id; @override - GeneratedIntColumn get id => _id ??= _constructId(); + late final GeneratedIntColumn id = _constructId(); GeneratedIntColumn _constructId() { return GeneratedIntColumn('id', $tableName, false, hasAutoIncrement: true, declaredAsPrimaryKey: true); } final VerificationMeta _nameMeta = const VerificationMeta('name'); - GeneratedTextColumn _name; @override - GeneratedTextColumn get name => _name ??= _constructName(); + late final GeneratedTextColumn name = _constructName(); GeneratedTextColumn _constructName() { return GeneratedTextColumn('name', $tableName, false, minTextLength: 6, maxTextLength: 32); } final VerificationMeta _isAwesomeMeta = const VerificationMeta('isAwesome'); - GeneratedBoolColumn _isAwesome; @override - GeneratedBoolColumn get isAwesome => _isAwesome ??= _constructIsAwesome(); + late final GeneratedBoolColumn isAwesome = _constructIsAwesome(); GeneratedBoolColumn _constructIsAwesome() { return GeneratedBoolColumn('is_awesome', $tableName, false, defaultValue: const Constant(true)); @@ -842,10 +800,8 @@ class $UsersTable extends Users with TableInfo<$UsersTable, User> { final VerificationMeta _profilePictureMeta = const VerificationMeta('profilePicture'); - GeneratedBlobColumn _profilePicture; @override - GeneratedBlobColumn get profilePicture => - _profilePicture ??= _constructProfilePicture(); + late final GeneratedBlobColumn profilePicture = _constructProfilePicture(); GeneratedBlobColumn _constructProfilePicture() { return GeneratedBlobColumn( 'profile_picture', @@ -856,10 +812,8 @@ class $UsersTable extends Users with TableInfo<$UsersTable, User> { final VerificationMeta _creationTimeMeta = const VerificationMeta('creationTime'); - GeneratedDateTimeColumn _creationTime; @override - GeneratedDateTimeColumn get creationTime => - _creationTime ??= _constructCreationTime(); + late final GeneratedDateTimeColumn creationTime = _constructCreationTime(); GeneratedDateTimeColumn _constructCreationTime() { return GeneratedDateTimeColumn('creation_time', $tableName, false, defaultValue: currentDateAndTime); @@ -880,23 +834,23 @@ class $UsersTable extends Users with TableInfo<$UsersTable, User> { final context = VerificationContext(); final data = instance.toColumns(true); if (data.containsKey('id')) { - context.handle(_idMeta, id.isAcceptableOrUnknown(data['id'], _idMeta)); + context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); } if (data.containsKey('name')) { context.handle( - _nameMeta, name.isAcceptableOrUnknown(data['name'], _nameMeta)); + _nameMeta, name.isAcceptableOrUnknown(data['name']!, _nameMeta)); } else if (isInserting) { context.missing(_nameMeta); } if (data.containsKey('is_awesome')) { context.handle(_isAwesomeMeta, - isAwesome.isAcceptableOrUnknown(data['is_awesome'], _isAwesomeMeta)); + isAwesome.isAcceptableOrUnknown(data['is_awesome']!, _isAwesomeMeta)); } if (data.containsKey('profile_picture')) { context.handle( _profilePictureMeta, profilePicture.isAcceptableOrUnknown( - data['profile_picture'], _profilePictureMeta)); + data['profile_picture']!, _profilePictureMeta)); } else if (isInserting) { context.missing(_profilePictureMeta); } @@ -904,7 +858,7 @@ class $UsersTable extends Users with TableInfo<$UsersTable, User> { context.handle( _creationTimeMeta, creationTime.isAcceptableOrUnknown( - data['creation_time'], _creationTimeMeta)); + data['creation_time']!, _creationTimeMeta)); } return context; } @@ -912,7 +866,7 @@ class $UsersTable extends Users with TableInfo<$UsersTable, User> { @override Set get $primaryKey => {id}; @override - User map(Map data, {String tablePrefix}) { + User map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; return User.fromData(data, _db, prefix: effectivePrefix); } @@ -926,37 +880,33 @@ class $UsersTable extends Users with TableInfo<$UsersTable, User> { class SharedTodo extends DataClass implements Insertable { final int todo; final int user; - SharedTodo({@required this.todo, @required this.user}); + SharedTodo({required this.todo, required this.user}); factory SharedTodo.fromData(Map data, GeneratedDatabase db, - {String prefix}) { + {String? prefix}) { final effectivePrefix = prefix ?? ''; final intType = db.typeSystem.forDartType(); return SharedTodo( - todo: intType.mapFromDatabaseResponse(data['${effectivePrefix}todo']), - user: intType.mapFromDatabaseResponse(data['${effectivePrefix}user']), + todo: intType.mapFromDatabaseResponse(data['${effectivePrefix}todo'])!, + user: intType.mapFromDatabaseResponse(data['${effectivePrefix}user'])!, ); } @override Map toColumns(bool nullToAbsent) { final map = {}; - if (!nullToAbsent || todo != null) { - map['todo'] = Variable(todo); - } - if (!nullToAbsent || user != null) { - map['user'] = Variable(user); - } + map['todo'] = Variable(todo); + map['user'] = Variable(user); return map; } SharedTodosCompanion toCompanion(bool nullToAbsent) { return SharedTodosCompanion( - todo: todo == null && nullToAbsent ? const Value.absent() : Value(todo), - user: user == null && nullToAbsent ? const Value.absent() : Value(user), + todo: Value(todo), + user: Value(user), ); } factory SharedTodo.fromJson(Map json, - {ValueSerializer serializer}) { + {ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return SharedTodo( todo: serializer.fromJson(json['todo']), @@ -964,12 +914,12 @@ class SharedTodo extends DataClass implements Insertable { ); } factory SharedTodo.fromJsonString(String encodedJson, - {ValueSerializer serializer}) => + {ValueSerializer? serializer}) => SharedTodo.fromJson( DataClass.parseJson(encodedJson) as Map, serializer: serializer); @override - Map toJson({ValueSerializer serializer}) { + Map toJson({ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return { 'todo': serializer.toJson(todo), @@ -977,7 +927,7 @@ class SharedTodo extends DataClass implements Insertable { }; } - SharedTodo copyWith({int todo, int user}) => SharedTodo( + SharedTodo copyWith({int? todo, int? user}) => SharedTodo( todo: todo ?? this.todo, user: user ?? this.user, ); @@ -1008,13 +958,13 @@ class SharedTodosCompanion extends UpdateCompanion { this.user = const Value.absent(), }); SharedTodosCompanion.insert({ - @required int todo, - @required int user, - }) : todo = Value(todo), + required int todo, + required int user, + }) : todo = Value(todo), user = Value(user); static Insertable custom({ - Expression todo, - Expression user, + Expression? todo, + Expression? user, }) { return RawValuesInsertable({ if (todo != null) 'todo': todo, @@ -1022,7 +972,7 @@ class SharedTodosCompanion extends UpdateCompanion { }); } - SharedTodosCompanion copyWith({Value todo, Value user}) { + SharedTodosCompanion copyWith({Value? todo, Value? user}) { return SharedTodosCompanion( todo: todo ?? this.todo, user: user ?? this.user, @@ -1054,12 +1004,11 @@ class SharedTodosCompanion extends UpdateCompanion { class $SharedTodosTable extends SharedTodos with TableInfo<$SharedTodosTable, SharedTodo> { final GeneratedDatabase _db; - final String _alias; + final String? _alias; $SharedTodosTable(this._db, [this._alias]); final VerificationMeta _todoMeta = const VerificationMeta('todo'); - GeneratedIntColumn _todo; @override - GeneratedIntColumn get todo => _todo ??= _constructTodo(); + late final GeneratedIntColumn todo = _constructTodo(); GeneratedIntColumn _constructTodo() { return GeneratedIntColumn( 'todo', @@ -1069,9 +1018,8 @@ class $SharedTodosTable extends SharedTodos } final VerificationMeta _userMeta = const VerificationMeta('user'); - GeneratedIntColumn _user; @override - GeneratedIntColumn get user => _user ??= _constructUser(); + late final GeneratedIntColumn user = _constructUser(); GeneratedIntColumn _constructUser() { return GeneratedIntColumn( 'user', @@ -1095,13 +1043,13 @@ class $SharedTodosTable extends SharedTodos final data = instance.toColumns(true); if (data.containsKey('todo')) { context.handle( - _todoMeta, todo.isAcceptableOrUnknown(data['todo'], _todoMeta)); + _todoMeta, todo.isAcceptableOrUnknown(data['todo']!, _todoMeta)); } else if (isInserting) { context.missing(_todoMeta); } if (data.containsKey('user')) { context.handle( - _userMeta, user.isAcceptableOrUnknown(data['user'], _userMeta)); + _userMeta, user.isAcceptableOrUnknown(data['user']!, _userMeta)); } else if (isInserting) { context.missing(_userMeta); } @@ -1111,7 +1059,7 @@ class $SharedTodosTable extends SharedTodos @override Set get $primaryKey => {todo, user}; @override - SharedTodo map(Map data, {String tablePrefix}) { + SharedTodo map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; return SharedTodo.fromData(data, _db, prefix: effectivePrefix); } @@ -1128,56 +1076,47 @@ class TableWithoutPKData extends DataClass final double someFloat; final MyCustomObject custom; TableWithoutPKData( - {@required this.notReallyAnId, - @required this.someFloat, - @required this.custom}); + {required this.notReallyAnId, + required this.someFloat, + required this.custom}); factory TableWithoutPKData.fromData( Map data, GeneratedDatabase db, - {String prefix}) { + {String? prefix}) { final effectivePrefix = prefix ?? ''; final intType = db.typeSystem.forDartType(); final doubleType = db.typeSystem.forDartType(); final stringType = db.typeSystem.forDartType(); return TableWithoutPKData( notReallyAnId: intType - .mapFromDatabaseResponse(data['${effectivePrefix}not_really_an_id']), + .mapFromDatabaseResponse(data['${effectivePrefix}not_really_an_id'])!, someFloat: doubleType - .mapFromDatabaseResponse(data['${effectivePrefix}some_float']), - custom: $TableWithoutPKTable.$converter0.mapToDart( - stringType.mapFromDatabaseResponse(data['${effectivePrefix}custom'])), + .mapFromDatabaseResponse(data['${effectivePrefix}some_float'])!, + custom: $TableWithoutPKTable.$converter0.mapToDart(stringType + .mapFromDatabaseResponse(data['${effectivePrefix}custom']))!, ); } @override Map toColumns(bool nullToAbsent) { final map = {}; - if (!nullToAbsent || notReallyAnId != null) { - map['not_really_an_id'] = Variable(notReallyAnId); - } - if (!nullToAbsent || someFloat != null) { - map['some_float'] = Variable(someFloat); - } - if (!nullToAbsent || custom != null) { + map['not_really_an_id'] = Variable(notReallyAnId); + map['some_float'] = Variable(someFloat); + { final converter = $TableWithoutPKTable.$converter0; - map['custom'] = Variable(converter.mapToSql(custom)); + map['custom'] = Variable(converter.mapToSql(custom)!); } return map; } TableWithoutPKCompanion toCompanion(bool nullToAbsent) { return TableWithoutPKCompanion( - notReallyAnId: notReallyAnId == null && nullToAbsent - ? const Value.absent() - : Value(notReallyAnId), - someFloat: someFloat == null && nullToAbsent - ? const Value.absent() - : Value(someFloat), - custom: - custom == null && nullToAbsent ? const Value.absent() : Value(custom), + notReallyAnId: Value(notReallyAnId), + someFloat: Value(someFloat), + custom: Value(custom), ); } factory TableWithoutPKData.fromJson(Map json, - {ValueSerializer serializer}) { + {ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return TableWithoutPKData( notReallyAnId: serializer.fromJson(json['notReallyAnId']), @@ -1186,12 +1125,12 @@ class TableWithoutPKData extends DataClass ); } factory TableWithoutPKData.fromJsonString(String encodedJson, - {ValueSerializer serializer}) => + {ValueSerializer? serializer}) => TableWithoutPKData.fromJson( DataClass.parseJson(encodedJson) as Map, serializer: serializer); @override - Map toJson({ValueSerializer serializer}) { + Map toJson({ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return { 'notReallyAnId': serializer.toJson(notReallyAnId), @@ -1201,7 +1140,7 @@ class TableWithoutPKData extends DataClass } TableWithoutPKData copyWith( - {int notReallyAnId, double someFloat, MyCustomObject custom}) => + {int? notReallyAnId, double? someFloat, MyCustomObject? custom}) => TableWithoutPKData( notReallyAnId: notReallyAnId ?? this.notReallyAnId, someFloat: someFloat ?? this.someFloat, @@ -1239,15 +1178,15 @@ class TableWithoutPKCompanion extends UpdateCompanion { this.custom = const Value.absent(), }); TableWithoutPKCompanion.insert({ - @required int notReallyAnId, - @required double someFloat, + required int notReallyAnId, + required double someFloat, this.custom = const Value.absent(), }) : notReallyAnId = Value(notReallyAnId), someFloat = Value(someFloat); static Insertable createCustom({ - Expression notReallyAnId, - Expression someFloat, - Expression custom, + Expression? notReallyAnId, + Expression? someFloat, + Expression? custom, }) { return RawValuesInsertable({ if (notReallyAnId != null) 'not_really_an_id': notReallyAnId, @@ -1257,9 +1196,9 @@ class TableWithoutPKCompanion extends UpdateCompanion { } TableWithoutPKCompanion copyWith( - {Value notReallyAnId, - Value someFloat, - Value custom}) { + {Value? notReallyAnId, + Value? someFloat, + Value? custom}) { return TableWithoutPKCompanion( notReallyAnId: notReallyAnId ?? this.notReallyAnId, someFloat: someFloat ?? this.someFloat, @@ -1278,7 +1217,7 @@ class TableWithoutPKCompanion extends UpdateCompanion { } if (custom.present) { final converter = $TableWithoutPKTable.$converter0; - map['custom'] = Variable(converter.mapToSql(custom.value)); + map['custom'] = Variable(converter.mapToSql(custom.value)!); } return map; } @@ -1297,14 +1236,12 @@ class TableWithoutPKCompanion extends UpdateCompanion { class $TableWithoutPKTable extends TableWithoutPK with TableInfo<$TableWithoutPKTable, TableWithoutPKData> { final GeneratedDatabase _db; - final String _alias; + final String? _alias; $TableWithoutPKTable(this._db, [this._alias]); final VerificationMeta _notReallyAnIdMeta = const VerificationMeta('notReallyAnId'); - GeneratedIntColumn _notReallyAnId; @override - GeneratedIntColumn get notReallyAnId => - _notReallyAnId ??= _constructNotReallyAnId(); + late final GeneratedIntColumn notReallyAnId = _constructNotReallyAnId(); GeneratedIntColumn _constructNotReallyAnId() { return GeneratedIntColumn( 'not_really_an_id', @@ -1314,9 +1251,8 @@ class $TableWithoutPKTable extends TableWithoutPK } final VerificationMeta _someFloatMeta = const VerificationMeta('someFloat'); - GeneratedRealColumn _someFloat; @override - GeneratedRealColumn get someFloat => _someFloat ??= _constructSomeFloat(); + late final GeneratedRealColumn someFloat = _constructSomeFloat(); GeneratedRealColumn _constructSomeFloat() { return GeneratedRealColumn( 'some_float', @@ -1326,9 +1262,8 @@ class $TableWithoutPKTable extends TableWithoutPK } final VerificationMeta _customMeta = const VerificationMeta('custom'); - GeneratedTextColumn _custom; @override - GeneratedTextColumn get custom => _custom ??= _constructCustom(); + late final GeneratedTextColumn custom = _constructCustom(); GeneratedTextColumn _constructCustom() { return GeneratedTextColumn( 'custom', @@ -1354,13 +1289,13 @@ class $TableWithoutPKTable extends TableWithoutPK context.handle( _notReallyAnIdMeta, notReallyAnId.isAcceptableOrUnknown( - data['not_really_an_id'], _notReallyAnIdMeta)); + data['not_really_an_id']!, _notReallyAnIdMeta)); } else if (isInserting) { context.missing(_notReallyAnIdMeta); } if (data.containsKey('some_float')) { context.handle(_someFloatMeta, - someFloat.isAcceptableOrUnknown(data['some_float'], _someFloatMeta)); + someFloat.isAcceptableOrUnknown(data['some_float']!, _someFloatMeta)); } else if (isInserting) { context.missing(_someFloatMeta); } @@ -1371,7 +1306,7 @@ class $TableWithoutPKTable extends TableWithoutPK @override Set get $primaryKey => {}; @override - TableWithoutPKData map(Map data, {String tablePrefix}) { + TableWithoutPKData map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; return TableWithoutPKData.fromData(data, _db, prefix: effectivePrefix); } @@ -1381,15 +1316,15 @@ class $TableWithoutPKTable extends TableWithoutPK return $TableWithoutPKTable(_db, alias); } - static TypeConverter $converter0 = + static TypeConverter $converter0 = const CustomConverter(); } class PureDefault extends DataClass implements Insertable { - final String txt; + final String? txt; PureDefault({this.txt}); factory PureDefault.fromData(Map data, GeneratedDatabase db, - {String prefix}) { + {String? prefix}) { final effectivePrefix = prefix ?? ''; final stringType = db.typeSystem.forDartType(); return PureDefault( @@ -1400,7 +1335,7 @@ class PureDefault extends DataClass implements Insertable { Map toColumns(bool nullToAbsent) { final map = {}; if (!nullToAbsent || txt != null) { - map['insert'] = Variable(txt); + map['insert'] = Variable(txt); } return map; } @@ -1412,26 +1347,26 @@ class PureDefault extends DataClass implements Insertable { } factory PureDefault.fromJson(Map json, - {ValueSerializer serializer}) { + {ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return PureDefault( - txt: serializer.fromJson(json['txt']), + txt: serializer.fromJson(json['txt']), ); } factory PureDefault.fromJsonString(String encodedJson, - {ValueSerializer serializer}) => + {ValueSerializer? serializer}) => PureDefault.fromJson( DataClass.parseJson(encodedJson) as Map, serializer: serializer); @override - Map toJson({ValueSerializer serializer}) { + Map toJson({ValueSerializer? serializer}) { serializer ??= moorRuntimeOptions.defaultSerializer; return { - 'txt': serializer.toJson(txt), + 'txt': serializer.toJson(txt), }; } - PureDefault copyWith({Value txt = const Value.absent()}) => + PureDefault copyWith({Value txt = const Value.absent()}) => PureDefault( txt: txt.present ? txt.value : this.txt, ); @@ -1449,7 +1384,7 @@ class PureDefault extends DataClass implements Insertable { } class PureDefaultsCompanion extends UpdateCompanion { - final Value txt; + final Value txt; const PureDefaultsCompanion({ this.txt = const Value.absent(), }); @@ -1457,14 +1392,14 @@ class PureDefaultsCompanion extends UpdateCompanion { this.txt = const Value.absent(), }); static Insertable custom({ - Expression txt, + Expression? txt, }) { return RawValuesInsertable({ if (txt != null) 'insert': txt, }); } - PureDefaultsCompanion copyWith({Value txt}) { + PureDefaultsCompanion copyWith({Value? txt}) { return PureDefaultsCompanion( txt: txt ?? this.txt, ); @@ -1474,7 +1409,7 @@ class PureDefaultsCompanion extends UpdateCompanion { Map toColumns(bool nullToAbsent) { final map = {}; if (txt.present) { - map['insert'] = Variable(txt.value); + map['insert'] = Variable(txt.value); } return map; } @@ -1491,12 +1426,11 @@ class PureDefaultsCompanion extends UpdateCompanion { class $PureDefaultsTable extends PureDefaults with TableInfo<$PureDefaultsTable, PureDefault> { final GeneratedDatabase _db; - final String _alias; + final String? _alias; $PureDefaultsTable(this._db, [this._alias]); final VerificationMeta _txtMeta = const VerificationMeta('txt'); - GeneratedTextColumn _txt; @override - GeneratedTextColumn get txt => _txt ??= _constructTxt(); + late final GeneratedTextColumn txt = _constructTxt(); GeneratedTextColumn _constructTxt() { return GeneratedTextColumn( 'insert', @@ -1520,7 +1454,7 @@ class $PureDefaultsTable extends PureDefaults final data = instance.toColumns(true); if (data.containsKey('insert')) { context.handle( - _txtMeta, txt.isAcceptableOrUnknown(data['insert'], _txtMeta)); + _txtMeta, txt.isAcceptableOrUnknown(data['insert']!, _txtMeta)); } return context; } @@ -1528,7 +1462,7 @@ class $PureDefaultsTable extends PureDefaults @override Set get $primaryKey => {txt}; @override - PureDefault map(Map data, {String tablePrefix}) { + PureDefault map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; return PureDefault.fromData(data, _db, prefix: effectivePrefix); } @@ -1542,22 +1476,13 @@ class $PureDefaultsTable extends PureDefaults abstract class _$TodoDb extends GeneratedDatabase { _$TodoDb(QueryExecutor e) : super(SqlTypeSystem.defaultInstance, e); _$TodoDb.connect(DatabaseConnection c) : super.connect(c); - $TodosTableTable _todosTable; - $TodosTableTable get todosTable => _todosTable ??= $TodosTableTable(this); - $CategoriesTable _categories; - $CategoriesTable get categories => _categories ??= $CategoriesTable(this); - $UsersTable _users; - $UsersTable get users => _users ??= $UsersTable(this); - $SharedTodosTable _sharedTodos; - $SharedTodosTable get sharedTodos => _sharedTodos ??= $SharedTodosTable(this); - $TableWithoutPKTable _tableWithoutPK; - $TableWithoutPKTable get tableWithoutPK => - _tableWithoutPK ??= $TableWithoutPKTable(this); - $PureDefaultsTable _pureDefaults; - $PureDefaultsTable get pureDefaults => - _pureDefaults ??= $PureDefaultsTable(this); - SomeDao _someDao; - SomeDao get someDao => _someDao ??= SomeDao(this as TodoDb); + late final $TodosTableTable todosTable = $TodosTableTable(this); + late final $CategoriesTable categories = $CategoriesTable(this); + late final $UsersTable users = $UsersTable(this); + late final $SharedTodosTable sharedTodos = $SharedTodosTable(this); + late final $TableWithoutPKTable tableWithoutPK = $TableWithoutPKTable(this); + late final $PureDefaultsTable pureDefaults = $PureDefaultsTable(this); + late final SomeDao someDao = SomeDao(this as TodoDb); Selectable allTodosWithCategory() { return customSelect( 'SELECT t.*, c.id as catId, c."desc" as catDesc FROM todos t INNER JOIN categories c ON c.id = t.category', @@ -1579,7 +1504,7 @@ abstract class _$TodoDb extends GeneratedDatabase { Future deleteTodoById(int var1) { return customUpdate( 'DELETE FROM todos WHERE id = ?', - variables: [Variable.withInt(var1)], + variables: [Variable(var1)], updates: {todosTable}, updateKind: UpdateKind.delete, ); @@ -1592,19 +1517,19 @@ abstract class _$TodoDb extends GeneratedDatabase { return customSelect( 'SELECT * FROM todos WHERE title = ?2 OR id IN ($expandedvar3) OR title = ?1', variables: [ - Variable.withString(var1), - Variable.withString(var2), - for (var $ in var3) Variable.withInt($) + Variable(var1), + Variable(var2), + for (var $ in var3) Variable($) ], readsFrom: { todosTable }).map(todosTable.mapFromRow); } - Selectable search({@required int id}) { + Selectable search({required int id}) { return customSelect( 'SELECT * FROM todos WHERE CASE WHEN -1 = :id THEN 1 ELSE id = :id END', - variables: [Variable.withInt(id)], + variables: [Variable(id)], readsFrom: {todosTable}).map(todosTable.mapFromRow); } @@ -1614,7 +1539,7 @@ abstract class _$TodoDb extends GeneratedDatabase { variables: [], readsFrom: {tableWithoutPK}) .map((QueryRow row) => $TableWithoutPKTable.$converter0 - .mapToDart(row.readString('custom'))); + .mapToDart(row.readString('custom'))!); } @override @@ -1632,21 +1557,21 @@ abstract class _$TodoDb extends GeneratedDatabase { class AllTodosWithCategoryResult extends CustomResultSet { final int id; - final String title; + final String? title; final String content; - final DateTime targetDate; - final int category; + final DateTime? targetDate; + final int? category; final int catId; final String catDesc; AllTodosWithCategoryResult({ - @required QueryRow row, - this.id, + required QueryRow row, + required this.id, this.title, - this.content, + required this.content, this.targetDate, this.category, - this.catId, - this.catDesc, + required this.catId, + required this.catDesc, }) : super(row); @override int get hashCode => $mrjf($mrjc( @@ -1693,10 +1618,10 @@ mixin _$SomeDaoMixin on DatabaseAccessor { $UsersTable get users => attachedDatabase.users; $SharedTodosTable get sharedTodos => attachedDatabase.sharedTodos; $TodosTableTable get todosTable => attachedDatabase.todosTable; - Selectable todosForUser({@required int user}) { + Selectable todosForUser({required int user}) { return customSelect( 'SELECT t.* FROM todos t INNER JOIN shared_todos st ON st.todo = t.id INNER JOIN users u ON u.id = st.user WHERE u.id = :user', - variables: [Variable.withInt(user)], + variables: [Variable(user)], readsFrom: {todosTable, sharedTodos, users}).map(todosTable.mapFromRow); } } diff --git a/moor/test/data/utils/expect_generated.dart b/moor/test/data/utils/expect_generated.dart index dc7309cd..47cb05f7 100644 --- a/moor/test/data/utils/expect_generated.dart +++ b/moor/test/data/utils/expect_generated.dart @@ -10,7 +10,7 @@ Matcher generates(dynamic sql, [dynamic variables]) { class _GeneratesSqlMatcher extends Matcher { final Matcher _matchSql; - final Matcher _matchVariables; + final Matcher? _matchVariables; _GeneratesSqlMatcher(this._matchSql, this._matchVariables); @@ -44,7 +44,7 @@ class _GeneratesSqlMatcher extends Matcher { mismatchDescription = mismatchDescription.add('generated variables $vars, which '); - mismatchDescription = _matchVariables.describeMismatch( + mismatchDescription = _matchVariables!.describeMismatch( vars, mismatchDescription, matchState['vars_match'] as Map, verbose); } return mismatchDescription; @@ -57,9 +57,8 @@ class _GeneratesSqlMatcher extends Matcher { return false; } - final component = item as Component; final ctx = GenerationContext(SqlTypeSystem.defaultInstance, null); - component.writeInto(ctx); + item.writeInto(ctx); var matches = true; @@ -72,7 +71,7 @@ class _GeneratesSqlMatcher extends Matcher { final argsMatchState = {}; if (_matchVariables != null && - !_matchVariables.matches(ctx.boundVariables, argsMatchState)) { + !_matchVariables!.matches(ctx.boundVariables, argsMatchState)) { matchState['vars'] = ctx.boundVariables; matchState['vars_match'] = argsMatchState; matches = false; diff --git a/moor/test/data/utils/mocks.dart b/moor/test/data/utils/mocks.dart index cde55309..719fd98f 100644 --- a/moor/test/data/utils/mocks.dart +++ b/moor/test/data/utils/mocks.dart @@ -1,18 +1,36 @@ import 'dart:async'; +// ignore: import_of_legacy_library_into_null_safe +import 'package:mockito/annotations.dart'; +// ignore: import_of_legacy_library_into_null_safe import 'package:mockito/mockito.dart'; import 'package:moor/moor.dart'; import 'package:moor/src/runtime/executor/stream_queries.dart'; -export 'package:mockito/mockito.dart'; +import 'mocks.mocks.dart'; +export 'mocks.mocks.dart'; -class MockExecutor extends Mock implements QueryExecutor { +@GenerateMocks( + [], + customMocks: [ + MockSpec(as: #MockExecutorInternal), + MockSpec(as: #MockTransactionsInternal), + MockSpec( + as: #MockStreamQueries, returnNullOnMissingStub: true) + ], +) +// ignore: unused_element +void _pleaseGenerateMocks() { + // needed so that mockito generates classes for us. +} + +class MockExecutor extends MockExecutorInternal { final MockTransactionExecutor transactions = MockTransactionExecutor(); - final OpeningDetails openingDetails; - - var _opened = false; + final OpeningDetails? openingDetails; + bool _opened = false; MockExecutor([this.openingDetails]) { + when(dialect).thenReturn(SqlDialect.sqlite); when(runSelect(any, any)).thenAnswer((_) { assert(_opened); return Future.value([]); @@ -33,6 +51,10 @@ class MockExecutor extends Mock implements QueryExecutor { assert(_opened); return Future.value(); }); + when(runBatched(any)).thenAnswer((_) { + assert(_opened); + return Future.value(); + }); when(beginTransaction()).thenAnswer((_) { assert(_opened); return transactions; @@ -42,7 +64,7 @@ class MockExecutor extends Mock implements QueryExecutor { if (!_opened && openingDetails != null) { _opened = true; await (i.positionalArguments.single as QueryExecutorUser) - .beforeOpen(this, openingDetails); + .beforeOpen(this, openingDetails!); } _opened = true; @@ -56,23 +78,24 @@ class MockExecutor extends Mock implements QueryExecutor { } } -class MockTransactionExecutor extends Mock implements TransactionExecutor { +class MockTransactionExecutor extends MockTransactionsInternal { MockTransactionExecutor() { + when(dialect).thenReturn(SqlDialect.sqlite); when(runSelect(any, any)).thenAnswer((_) => Future.value([])); when(runUpdate(any, any)).thenAnswer((_) => Future.value(0)); when(runDelete(any, any)).thenAnswer((_) => Future.value(0)); when(runInsert(any, any)).thenAnswer((_) => Future.value(0)); - when(ensureOpen(any)).thenAnswer((_) => Future.value()); + when(runCustom(any, any)).thenAnswer((_) => Future.value()); + when(runBatched(any)).thenAnswer((_) => Future.value()); + when(ensureOpen(any)).thenAnswer((_) => Future.value(true)); when(send()).thenAnswer((_) => Future.value(null)); when(rollback()).thenAnswer((_) => Future.value(null)); } } -class MockStreamQueries extends Mock implements StreamQueryStore {} - DatabaseConnection createConnection(QueryExecutor executor, - [StreamQueryStore streams]) { + [StreamQueryStore? streams]) { return DatabaseConnection( SqlTypeSystem.defaultInstance, executor, streams ?? StreamQueryStore()); } diff --git a/moor/test/data/utils/mocks.mocks.dart b/moor/test/data/utils/mocks.mocks.dart new file mode 100644 index 00000000..6d622cc5 --- /dev/null +++ b/moor/test/data/utils/mocks.mocks.dart @@ -0,0 +1,110 @@ +import 'package:mockito/mockito.dart' as _i1; +import 'package:moor/src/runtime/executor/executor.dart' as _i2; +import 'package:moor/src/runtime/query_builder/query_builder.dart' as _i3; +import 'dart:async' as _i4; +import 'package:moor/src/runtime/executor/stream_queries.dart' as _i5; +import 'package:moor/src/runtime/api/runtime_api.dart' as _i6; + +class _FakeTransactionExecutor extends _i1.Fake + implements _i2.TransactionExecutor {} + +/// A class which mocks [QueryExecutor]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockExecutorInternal extends _i1.Mock implements _i2.QueryExecutor { + MockExecutorInternal() { + _i1.throwOnMissingStub(this); + } + + _i3.SqlDialect get dialect => + super.noSuchMethod(Invocation.getter(#dialect), _i3.SqlDialect.sqlite); + _i4.Future ensureOpen(_i2.QueryExecutorUser? user) => + super.noSuchMethod( + Invocation.method(#ensureOpen, [user]), Future.value(false)); + _i4.Future>> runSelect( + String? statement, List? args) => + super.noSuchMethod(Invocation.method(#runSelect, [statement, args]), + Future.value(>[])); + _i4.Future runInsert(String? statement, List? args) => + super.noSuchMethod( + Invocation.method(#runInsert, [statement, args]), Future.value(0)); + _i4.Future runUpdate(String? statement, List? args) => + super.noSuchMethod( + Invocation.method(#runUpdate, [statement, args]), Future.value(0)); + _i4.Future runDelete(String? statement, List? args) => + super.noSuchMethod( + Invocation.method(#runDelete, [statement, args]), Future.value(0)); + _i4.Future runCustom(String? statement, [List? args]) => + super.noSuchMethod( + Invocation.method(#runCustom, [statement, args]), Future.value(null)); + _i4.Future runBatched(_i2.BatchedStatements? statements) => + super.noSuchMethod( + Invocation.method(#runBatched, [statements]), Future.value(null)); + _i2.TransactionExecutor beginTransaction() => super.noSuchMethod( + Invocation.method(#beginTransaction, []), _FakeTransactionExecutor()); + _i4.Future close() => + super.noSuchMethod(Invocation.method(#close, []), Future.value(null)); +} + +/// A class which mocks [TransactionExecutor]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockTransactionsInternal extends _i1.Mock + implements _i2.TransactionExecutor { + MockTransactionsInternal() { + _i1.throwOnMissingStub(this); + } + + _i4.Future send() => + super.noSuchMethod(Invocation.method(#send, []), Future.value(null)); + _i4.Future rollback() => + super.noSuchMethod(Invocation.method(#rollback, []), Future.value(null)); + _i4.Future ensureOpen(_i2.QueryExecutorUser? user) => + super.noSuchMethod( + Invocation.method(#ensureOpen, [user]), Future.value(false)); + _i4.Future>> runSelect( + String? statement, List? args) => + super.noSuchMethod(Invocation.method(#runSelect, [statement, args]), + Future.value(>[])); + _i4.Future runInsert(String? statement, List? args) => + super.noSuchMethod( + Invocation.method(#runInsert, [statement, args]), Future.value(0)); + _i4.Future runUpdate(String? statement, List? args) => + super.noSuchMethod( + Invocation.method(#runUpdate, [statement, args]), Future.value(0)); + _i4.Future runDelete(String? statement, List? args) => + super.noSuchMethod( + Invocation.method(#runDelete, [statement, args]), Future.value(0)); + _i4.Future runCustom(String? statement, [List? args]) => + super.noSuchMethod( + Invocation.method(#runCustom, [statement, args]), Future.value(null)); + _i4.Future runBatched(_i2.BatchedStatements? statements) => + super.noSuchMethod( + Invocation.method(#runBatched, [statements]), Future.value(null)); + _i2.TransactionExecutor beginTransaction() => super.noSuchMethod( + Invocation.method(#beginTransaction, []), _FakeTransactionExecutor()); + _i4.Future close() => + super.noSuchMethod(Invocation.method(#close, []), Future.value(null)); +} + +/// A class which mocks [StreamQueryStore]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockStreamQueries extends _i1.Mock implements _i5.StreamQueryStore { + _i4.Stream registerStream(_i5.QueryStreamFetcher? fetcher) => + super.noSuchMethod( + Invocation.method(#registerStream, [fetcher]), Stream.empty()); + _i4.Stream updatesForSync(_i6.TableUpdateQuery? query) => + super.noSuchMethod( + Invocation.method(#updatesForSync, [query]), Stream.empty()); + void handleTableUpdates(Set<_i6.TableUpdate>? updates) => + super.noSuchMethod(Invocation.method(#handleTableUpdates, [updates])); + void markAsClosed( + _i5.QueryStream? stream, dynamic Function()? whenRemoved) => + super.noSuchMethod( + Invocation.method(#markAsClosed, [stream, whenRemoved])); + void markAsOpened(_i5.QueryStream? stream) => + super.noSuchMethod(Invocation.method(#markAsOpened, [stream])); + _i4.Future close() => + super.noSuchMethod(Invocation.method(#close, []), Future.value(null)); +} diff --git a/moor/test/data/utils/null_executor.dart b/moor/test/data/utils/null_executor.dart new file mode 100644 index 00000000..10a353a4 --- /dev/null +++ b/moor/test/data/utils/null_executor.dart @@ -0,0 +1,52 @@ +import 'package:moor/backends.dart'; + +class NullExecutor implements QueryExecutor { + const NullExecutor(); + + @override + TransactionExecutor beginTransaction() { + throw UnsupportedError('beginTransaction'); + } + + @override + Future ensureOpen(QueryExecutorUser user) { + throw UnsupportedError('ensureOpen'); + } + + @override + Future runBatched(BatchedStatements statements) { + throw UnsupportedError('runBatched'); + } + + @override + Future runCustom(String statement, [List? args]) { + throw UnsupportedError('runCustom'); + } + + @override + Future runDelete(String statement, List args) { + throw UnsupportedError('runDelete'); + } + + @override + Future runInsert(String statement, List args) { + throw UnsupportedError('runInsert'); + } + + @override + Future>> runSelect( + String statement, List args) { + throw UnsupportedError('runSelect'); + } + + @override + Future runUpdate(String statement, List args) { + throw UnsupportedError('runUpdate'); + } + + @override + Future close() => Future.value(); + + @override + SqlDialect get dialect => SqlDialect.sqlite; +} diff --git a/moor/test/data_class_test.dart b/moor/test/data_class_test.dart index 54f2ee6b..6d94e863 100644 --- a/moor/test/data_class_test.dart +++ b/moor/test/data_class_test.dart @@ -1,3 +1,4 @@ +//@dart=2.9 import 'package:moor/moor.dart'; import 'package:test/test.dart'; @@ -19,13 +20,9 @@ void main() { }); test('can deserialize ints as doubles', () { - final entry = TableWithoutPKData.fromJson({ - 'notReallyAnId': 3, - 'someFloat': 4, - }); + const serializer = ValueSerializer.defaults(); - expect(entry, - TableWithoutPKData(notReallyAnId: 3, someFloat: 4, custom: null)); + expect(serializer.fromJson(3), 3.0); }); test('default serializer can be overridden globally', () { diff --git a/moor/test/database_test.dart b/moor/test/database_test.dart index fc7105bf..57c090b2 100644 --- a/moor/test/database_test.dart +++ b/moor/test/database_test.dart @@ -1,5 +1,7 @@ -import 'package:test/test.dart'; +//@dart=2.9 +import 'package:mockito/mockito.dart'; import 'package:moor/moor.dart'; +import 'package:test/test.dart'; import 'data/tables/todos.dart'; import 'data/utils/mocks.dart'; diff --git a/moor/test/delete_test.dart b/moor/test/delete_test.dart index 9e60c9bc..1f30786e 100644 --- a/moor/test/delete_test.dart +++ b/moor/test/delete_test.dart @@ -1,5 +1,7 @@ +//@dart=2.9 import 'dart:async'; +import 'package:mockito/mockito.dart'; import 'package:moor/moor.dart'; import 'package:test/test.dart'; diff --git a/moor/test/engines/connection_pool_integration_test.dart b/moor/test/engines/connection_pool_integration_test.dart index ebf324a9..89468e50 100644 --- a/moor/test/engines/connection_pool_integration_test.dart +++ b/moor/test/engines/connection_pool_integration_test.dart @@ -1,3 +1,4 @@ +//@dart=2.9 @TestOn('vm') import 'dart:io'; diff --git a/moor/test/engines/connection_pool_test.dart b/moor/test/engines/connection_pool_test.dart index b9baa8c9..556fc3a7 100644 --- a/moor/test/engines/connection_pool_test.dart +++ b/moor/test/engines/connection_pool_test.dart @@ -1,3 +1,5 @@ +//@dart=2.9 +import 'package:mockito/mockito.dart'; import 'package:moor/moor.dart'; import 'package:test/test.dart'; diff --git a/moor/test/engines/delegated_database_test.dart b/moor/test/engines/delegated_database_test.dart index f40548de..2845de01 100644 --- a/moor/test/engines/delegated_database_test.dart +++ b/moor/test/engines/delegated_database_test.dart @@ -1,3 +1,4 @@ +//@dart=2.9 import 'package:mockito/mockito.dart'; import 'package:moor/backends.dart'; import 'package:moor/moor.dart'; @@ -42,19 +43,20 @@ void main() { final db = DelegatedDatabase(delegate, isSequential: sequential); await db.ensureOpen(_FakeExecutorUser()); - expect(await db.runSelect(null, null), isEmpty); - expect(await db.runUpdate(null, null), 3); - expect(await db.runInsert(null, null), 4); - await db.runCustom(null); - await db.runBatched(null); + expect(await db.runSelect('select', const []), isEmpty); + expect(await db.runUpdate('update', const []), 3); + expect(await db.runInsert('insert', const []), 4); + await db.runCustom('custom'); + final batched = BatchedStatements([], []); + await db.runBatched(batched); verifyInOrder([ delegate.isOpen, - delegate.runSelect(null, null), - delegate.runUpdate(null, null), - delegate.runInsert(null, null), - delegate.runCustom(null, []), - delegate.runBatched(null), + delegate.runSelect('select', const []), + delegate.runUpdate('update', const []), + delegate.runInsert('insert', const []), + delegate.runCustom('custom', const []), + delegate.runBatched(batched), ]); }); } @@ -149,12 +151,12 @@ void main() { final transaction = db.beginTransaction(); await transaction.ensureOpen(_FakeExecutorUser()); - await transaction.runSelect(null, null); + await transaction.runSelect('SELECT 1;', const []); await transaction.send(); verifyInOrder([ delegate.runCustom('BEGIN TRANSACTION', []), - delegate.runSelect(null, null), + delegate.runSelect('SELECT 1;', const []), delegate.runCustom('COMMIT TRANSACTION', []), ]); }); diff --git a/moor/test/error_handling_test.dart b/moor/test/error_handling_test.dart index 4381d8e7..1699bc1d 100644 --- a/moor/test/error_handling_test.dart +++ b/moor/test/error_handling_test.dart @@ -1,3 +1,4 @@ +//@dart=2.9 import 'package:moor/moor.dart'; import 'package:test/test.dart'; diff --git a/moor/test/expressions/comparable_test.dart b/moor/test/expressions/comparable_test.dart index f4e1a7c4..7ebbd2a6 100644 --- a/moor/test/expressions/comparable_test.dart +++ b/moor/test/expressions/comparable_test.dart @@ -5,8 +5,8 @@ import '../data/tables/todos.dart'; import '../data/utils/expect_equality.dart'; void main() { - final expression = GeneratedIntColumn('col', null, false); - final db = TodoDb(null); + final expression = GeneratedIntColumn('col', 'table', false); + final db = TodoDb(); final comparisons = { expression.isSmallerThan: '<', @@ -23,7 +23,7 @@ void main() { }; group('can compare with other expressions', () { - final compare = GeneratedIntColumn('compare', null, false); + final compare = GeneratedIntColumn('compare', 'table', false); comparisons.forEach((fn, value) { test('for operator $value', () { @@ -53,8 +53,8 @@ void main() { group('between', () { test('other expressions', () { - final low = GeneratedIntColumn('low', null, false); - final high = GeneratedIntColumn('high', null, false); + final low = GeneratedIntColumn('low', 'table', false); + final high = GeneratedIntColumn('high', 'table', false); final ctx = GenerationContext.fromDb(db); expression.isBetween(low, high).writeInto(ctx); diff --git a/moor/test/expressions/constant_test.dart b/moor/test/expressions/constant_test.dart index fd673fc3..07cff1c7 100644 --- a/moor/test/expressions/constant_test.dart +++ b/moor/test/expressions/constant_test.dart @@ -1,3 +1,4 @@ +//@dart=2.9 import 'package:moor/moor.dart'; import 'package:test/test.dart'; @@ -31,7 +32,7 @@ void main() { } void testStringMapping(String dart, String expectedLiteral) { - final ctx = GenerationContext.fromDb(TodoDb(null)); + final ctx = GenerationContext.fromDb(TodoDb()); final constant = Constant(dart); constant.writeInto(ctx); diff --git a/moor/test/expressions/datetime_expression_test.dart b/moor/test/expressions/datetime_expression_test.dart index df94d4a3..c7f6aed5 100644 --- a/moor/test/expressions/datetime_expression_test.dart +++ b/moor/test/expressions/datetime_expression_test.dart @@ -1,3 +1,4 @@ +//@dart=2.9 import 'package:moor/moor.dart'; import 'package:test/test.dart'; @@ -7,7 +8,7 @@ import '../data/utils/expect_generated.dart'; typedef _Extractor = Expression Function(Expression d); void main() { - final column = GeneratedDateTimeColumn('val', null, false); + final column = GeneratedDateTimeColumn('val', 'table', false); group('extracting information via top-level method', () { final expectedResults = <_Extractor, String>{ diff --git a/moor/test/expressions/expressions_integration_test.dart b/moor/test/expressions/expressions_integration_test.dart index 8f354587..1a552dc5 100644 --- a/moor/test/expressions/expressions_integration_test.dart +++ b/moor/test/expressions/expressions_integration_test.dart @@ -1,3 +1,4 @@ +//@dart=2.9 @TestOn('vm') import 'package:moor/ffi.dart'; import 'package:moor/moor.dart'; diff --git a/moor/test/expressions/in_expression_test.dart b/moor/test/expressions/in_expression_test.dart index 00f82279..02f39b76 100644 --- a/moor/test/expressions/in_expression_test.dart +++ b/moor/test/expressions/in_expression_test.dart @@ -1,3 +1,4 @@ +//@dart=2.9 import 'package:test/test.dart'; import 'package:moor/moor.dart'; @@ -6,10 +7,10 @@ import '../data/utils/expect_generated.dart'; void main() { test('in expressions are generated', () { - final innerExpression = GeneratedTextColumn('name', null, true); + final innerExpression = GeneratedTextColumn('name', 'table', true); final isInExpression = innerExpression.isIn(['Max', 'Tobias']); - final context = GenerationContext.fromDb(TodoDb(null)); + final context = GenerationContext.fromDb(TodoDb()); isInExpression.writeInto(context); expect(context.sql, 'name IN (?, ?)'); @@ -17,7 +18,7 @@ void main() { }); test('not in expressions are generated', () { - final innerExpression = GeneratedTextColumn('name', null, true); + final innerExpression = GeneratedTextColumn('name', 'table', true); final isNotIn = innerExpression.isNotIn(['Max', 'Tobias']); expect(isNotIn, generates('name NOT IN (?, ?)', ['Max', 'Tobias'])); diff --git a/moor/test/expressions/null_check_test.dart b/moor/test/expressions/null_check_test.dart index 0e0fe332..8e516f8f 100644 --- a/moor/test/expressions/null_check_test.dart +++ b/moor/test/expressions/null_check_test.dart @@ -6,7 +6,7 @@ import '../data/utils/expect_equality.dart'; import '../data/utils/expect_generated.dart'; void main() { - final innerExpression = GeneratedTextColumn('name', null, true); + final innerExpression = GeneratedTextColumn('name', 'table', true); test('IS NULL expressions are generated', () { final oldFunction = moor.isNull(innerExpression); @@ -29,7 +29,7 @@ void main() { }); test('generates COALESCE expressions', () { - final expr = moor.coalesce([const Constant(null), const Constant(3)]); + final expr = moor.coalesce([const Constant(null), const Constant(3)]); expect(expr, generates('COALESCE(NULL, 3)')); }); diff --git a/moor/test/expressions/text_test.dart b/moor/test/expressions/text_test.dart index 60822e3f..ded9275b 100644 --- a/moor/test/expressions/text_test.dart +++ b/moor/test/expressions/text_test.dart @@ -5,8 +5,8 @@ import '../data/tables/todos.dart'; import '../data/utils/expect_generated.dart'; void main() { - final expression = GeneratedTextColumn('col', null, false); - final db = TodoDb(null); + final expression = GeneratedTextColumn('col', 'table', false); + final db = TodoDb(); test('generates like expressions', () { final ctx = GenerationContext.fromDb(db); diff --git a/moor/test/expressions/variable_test.dart b/moor/test/expressions/variable_test.dart index 187eb7fc..6ce21633 100644 --- a/moor/test/expressions/variable_test.dart +++ b/moor/test/expressions/variable_test.dart @@ -1,3 +1,4 @@ +//@dart=2.9 import 'package:test/test.dart'; import 'package:moor/moor.dart'; @@ -7,7 +8,7 @@ void main() { test('maps the variable to sql', () { final variable = Variable(DateTime.fromMillisecondsSinceEpoch(1551297563000)); - final ctx = GenerationContext.fromDb(TodoDb(null)); + final ctx = GenerationContext.fromDb(TodoDb()); variable.writeInto(ctx); @@ -16,8 +17,8 @@ void main() { }); test('writes null directly for null values', () { - final variable = Variable.withString(null); - final ctx = GenerationContext.fromDb(TodoDb(null)); + const variable = Variable(null); + final ctx = GenerationContext.fromDb(TodoDb()); variable.writeInto(ctx); diff --git a/moor/test/extensions/json1_integration_test.dart b/moor/test/extensions/json1_integration_test.dart index d171c4f5..16f2e71b 100644 --- a/moor/test/extensions/json1_integration_test.dart +++ b/moor/test/extensions/json1_integration_test.dart @@ -31,6 +31,6 @@ void main() { .equalsExp(Variable.withString('bar'))); final resultRow = await query.getSingle(); - expect(resultRow.read(arrayLengthExpr), 3); + expect(resultRow!.read(arrayLengthExpr), 3); }, tags: const ['integration']); } diff --git a/moor/test/extensions/moor_ffi_functions_test.dart b/moor/test/extensions/moor_ffi_functions_test.dart index 5b101cfa..d59ef650 100644 --- a/moor/test/extensions/moor_ffi_functions_test.dart +++ b/moor/test/extensions/moor_ffi_functions_test.dart @@ -8,8 +8,8 @@ import '../data/tables/todos.dart'; import '../data/utils/expect_generated.dart'; void main() { - final a = GeneratedRealColumn('a', null, false); - final b = GeneratedRealColumn('b', null, false); + final a = GeneratedRealColumn('a', 'table', false); + final b = GeneratedRealColumn('b', 'table', false); test('pow', () { expect(sqlPow(a, b), generates('pow(a, b)')); @@ -24,7 +24,7 @@ void main() { test('atan', () => expect(sqlAtan(a), generates('atan(a)'))); test('containsCase', () { - final c = GeneratedTextColumn('a', null, false); + final c = GeneratedTextColumn('a', 'table', false); expect(c.containsCase('foo'), generates('moor_contains(a, ?, 0)', ['foo'])); expect( @@ -38,11 +38,11 @@ void main() { // insert exactly one row so that we can evaluate expressions from Dart await db.into(db.pureDefaults).insert(PureDefaultsCompanion.insert()); - Future evaluate(Expression expr) async { + Future evaluate(Expression expr) async { final result = await (db.selectOnly(db.pureDefaults)..addColumns([expr])) .getSingle(); - return result.read(expr); + return result!.read(expr)!; } expect( @@ -58,7 +58,7 @@ void main() { }); group('regexp flags', () { - TodoDb db; + late TodoDb db; setUp(() async { db = TodoDb(VmDatabase.memory()); @@ -68,11 +68,11 @@ void main() { tearDown(() => db.close()); - Future evaluate(Expression expr) async { + Future evaluate(Expression expr) async { final result = await (db.selectOnly(db.pureDefaults)..addColumns([expr])) .getSingle(); - return result.read(expr); + return result!.read(expr)!; } test('multiLine', () { diff --git a/moor/test/ffi/moor_functions_test.dart b/moor/test/ffi/moor_functions_test.dart index 10902468..70781c16 100644 --- a/moor/test/ffi/moor_functions_test.dart +++ b/moor/test/ffi/moor_functions_test.dart @@ -6,7 +6,7 @@ import 'package:sqlite3/sqlite3.dart'; import 'package:test/test.dart'; void main() { - Database db; + late Database db; setUp(() => db = sqlite3.openInMemory()..useMoorVersions()); tearDown(() => db.dispose()); diff --git a/moor/test/ffi/setup_test.dart b/moor/test/ffi/setup_test.dart index 49cdaf65..59aa6537 100644 --- a/moor/test/ffi/setup_test.dart +++ b/moor/test/ffi/setup_test.dart @@ -19,7 +19,7 @@ void main() { final db = TodoDb(executor); final row = await db.customSelect('SELECT my_function() AS r;').getSingle(); - expect(row.readString('r'), 'hello from Dart'); + expect(row!.readString('r'), 'hello from Dart'); await db.close(); }); @@ -31,7 +31,7 @@ void main() { final db = TodoDb(executor); final row = await db.customSelect('SELECT my_function() AS r;').getSingle(); - expect(row.readString('r'), 'hello from Dart'); + expect(row!.readString('r'), 'hello from Dart'); await db.close(); }); diff --git a/moor/test/insert_test.dart b/moor/test/insert_test.dart index a0b9a046..be76f91d 100644 --- a/moor/test/insert_test.dart +++ b/moor/test/insert_test.dart @@ -1,3 +1,5 @@ +// ignore: import_of_legacy_library_into_null_safe +import 'package:mockito/mockito.dart'; import 'package:moor/moor.dart'; import 'package:test/test.dart'; @@ -5,9 +7,9 @@ import 'data/tables/todos.dart'; import 'data/utils/mocks.dart'; void main() { - TodoDb db; - MockExecutor executor; - MockStreamQueries streamQueries; + late TodoDb db; + late MockExecutor executor; + late MockStreamQueries streamQueries; setUp(() { executor = MockExecutor(); @@ -29,8 +31,10 @@ void main() { test('can insert floating point values', () async { // regression test for https://github.com/simolus3/moor/issues/30 - await db.into(db.tableWithoutPK).insert( - TableWithoutPKData(notReallyAnId: 42, someFloat: 3.1415, custom: null)); + await db.into(db.tableWithoutPK).insert(TableWithoutPKData( + notReallyAnId: 42, + someFloat: 3.1415, + custom: MyCustomObject('custom'))); verify(executor.runInsert( 'INSERT INTO table_without_p_k ' @@ -74,8 +78,8 @@ void main() { try { await db.into(db.todosTable).insert( const TodosTableCompanion( - // not declared as nullable in table definition - content: Value(null), + // has a min length of 4 + title: Value('s'), ), ); fail('inserting invalid data did not throw'); @@ -102,7 +106,7 @@ void main() { expect( () { final insert = TodosTableCompanion.insert(content: 'content'); - const update = TodosTableCompanion(content: Value(null)); + const update = TodosTableCompanion(title: Value('s')); return db .into(db.todosTable) .insert(insert, onConflict: DoUpdate((_) => update)); @@ -112,16 +116,6 @@ void main() { }); }); - test("doesn't allow writing null rows", () { - expect( - () { - return db.into(db.todosTable).insert(null); - }, - throwsA(const TypeMatcher().having( - (e) => e.message, 'message', contains('Cannot write null row'))), - ); - }); - test('reports auto-increment id', () { when(executor.runInsert(any, any)).thenAnswer((_) => Future.value(42)); diff --git a/moor/test/integration_tests/insert_integration_test.dart b/moor/test/integration_tests/insert_integration_test.dart index beb4d835..da9cd26e 100644 --- a/moor/test/integration_tests/insert_integration_test.dart +++ b/moor/test/integration_tests/insert_integration_test.dart @@ -1,6 +1,7 @@ +//@dart=2.9 +@TestOn('vm') import 'package:moor/moor.dart'; import 'package:moor/ffi.dart'; -@TestOn('vm') import 'package:test/test.dart'; import '../data/tables/todos.dart'; diff --git a/moor/test/integration_tests/migrations_integration_test.dart b/moor/test/integration_tests/migrations_integration_test.dart index db43e258..97e0cb2a 100644 --- a/moor/test/integration_tests/migrations_integration_test.dart +++ b/moor/test/integration_tests/migrations_integration_test.dart @@ -1,3 +1,4 @@ +//@dart=2.9 @TestOn('vm') import 'package:moor/ffi.dart'; import 'package:moor/moor.dart' hide isNull; diff --git a/moor/test/isolate_test.dart b/moor/test/isolate_test.dart index 339df16b..ce2d5718 100644 --- a/moor/test/isolate_test.dart +++ b/moor/test/isolate_test.dart @@ -1,3 +1,4 @@ +//@dart=2.9 @TestOn('vm') import 'dart:async'; import 'dart:isolate'; @@ -27,7 +28,7 @@ void main() { } _runTests(spawnBackground, true); - }); + }, tags: 'background_isolate'); test('stream queries across isolates', () async { // three isolates: @@ -58,7 +59,7 @@ void main() { writer.kill(); await expectation; await moorIsolate.shutdownAll(); - }); + }, tags: 'background_isolate'); test('errors propagate across isolates', () async { final isolate = await MoorIsolate.spawn(_backgroundConnection); @@ -77,7 +78,7 @@ void main() { await db.close(); await isolate.shutdownAll(); - }); + }, tags: 'background_isolate'); } void _runTests( diff --git a/moor/test/join_test.dart b/moor/test/join_test.dart index d4aa342b..93d13f86 100644 --- a/moor/test/join_test.dart +++ b/moor/test/join_test.dart @@ -1,3 +1,5 @@ +//@dart=2.9 +import 'package:mockito/mockito.dart'; import 'package:moor/moor.dart' hide isNull; import 'package:test/test.dart'; import 'data/tables/todos.dart'; diff --git a/moor/test/parsed_sql/moor_files_integration_test.dart b/moor/test/parsed_sql/moor_files_integration_test.dart index e7063ff1..733e8277 100644 --- a/moor/test/parsed_sql/moor_files_integration_test.dart +++ b/moor/test/parsed_sql/moor_files_integration_test.dart @@ -1,3 +1,5 @@ +//@dart=2.9 +import 'package:mockito/mockito.dart'; import 'package:moor/moor.dart'; import 'package:test/test.dart'; diff --git a/moor/test/schema_test.dart b/moor/test/schema_test.dart index 8af89639..f1db4be4 100644 --- a/moor/test/schema_test.dart +++ b/moor/test/schema_test.dart @@ -1,3 +1,5 @@ +//@dart=2.9 +import 'package:mockito/mockito.dart'; import 'package:moor/moor.dart'; import 'package:test/test.dart'; diff --git a/moor/test/select_test.dart b/moor/test/select_test.dart index 12b28ef1..76818b97 100644 --- a/moor/test/select_test.dart +++ b/moor/test/select_test.dart @@ -1,5 +1,7 @@ +//@dart=2.9 import 'dart:async'; +import 'package:mockito/mockito.dart'; import 'package:moor/moor.dart' hide isNull; import 'package:test/test.dart'; diff --git a/moor/test/serialization_test.dart b/moor/test/serialization_test.dart index dd34d9bf..f139e3de 100644 --- a/moor/test/serialization_test.dart +++ b/moor/test/serialization_test.dart @@ -7,24 +7,24 @@ final DateTime someDate = DateTime(2019, 06, 08); final TodoEntry someTodoEntry = TodoEntry( id: 3, - title: 'a title', - content: null, + title: null, + content: 'content', targetDate: someDate, category: 3, ); final Map regularSerialized = { 'id': 3, - 'title': 'a title', - 'content': null, + 'title': null, + 'content': 'content', 'target_date': someDate.millisecondsSinceEpoch, 'category': 3, }; final Map customSerialized = { 'id': 3, - 'title': 'a title', - 'content': 'set to null', + 'title': 'set to null', + 'content': 'content', 'target_date': someDate.toIso8601String(), 'category': 3, }; @@ -32,10 +32,10 @@ final Map customSerialized = { class CustomSerializer extends ValueSerializer { @override T fromJson(dynamic json) { - if (T == DateTime) { + if ([] is List) { return DateTime.parse(json.toString()) as T; } else if (json == 'set to null') { - return null; + return null as T; } else { return json as T; } @@ -43,8 +43,8 @@ class CustomSerializer extends ValueSerializer { @override dynamic toJson(T value) { - if (T == DateTime) { - return (value as DateTime).toIso8601String(); + if ([] is List) { + return (value as DateTime?)?.toIso8601String(); } else if (value == null) { return 'set to null'; } else { @@ -56,8 +56,8 @@ class CustomSerializer extends ValueSerializer { void main() { test('default serializer', () { const serializer = ValueSerializer.defaults(); - expect(serializer.toJson(null), null); - expect(serializer.fromJson(null), null); + expect(serializer.toJson(null), null); + expect(serializer.fromJson(null), null); }); group('serialization', () { diff --git a/moor/test/streams_test.dart b/moor/test/streams_test.dart index b448a3df..df774df2 100644 --- a/moor/test/streams_test.dart +++ b/moor/test/streams_test.dart @@ -1,4 +1,7 @@ +//@dart=2.9 import 'dart:async'; + +import 'package:mockito/mockito.dart'; import 'package:moor/moor.dart'; import 'package:moor/src/runtime/api/runtime_api.dart'; import 'package:moor/src/runtime/executor/stream_queries.dart'; @@ -86,7 +89,7 @@ void main() { await first.first; // subscribe to first stream, then drop subscription when(executor.runSelect(any, any)).thenAnswer((_) => Future.value([ - {'id': 1, 'description': 'd'} + {'id': 1, 'desc': 'd', 'priority': 0} ])); await db .into(db.categories) @@ -102,7 +105,7 @@ void main() { final subscription = first.listen((_) {}); when(executor.runSelect(any, any)).thenAnswer((_) => Future.value([ - {'id': 1, 'description': 'd'} + {'id': 1, 'desc': 'd', 'priority': 0} ])); await db .into(db.categories) diff --git a/moor/test/tables_test.dart b/moor/test/tables_test.dart index 66a9b52e..07a31f3e 100644 --- a/moor/test/tables_test.dart +++ b/moor/test/tables_test.dart @@ -1,3 +1,4 @@ +//@dart=2.9 import 'package:moor/moor.dart'; import 'package:test/test.dart'; @@ -35,23 +36,19 @@ void main() { }); test('can convert a companion to a row class', () { - const companion = UsersCompanion( + const companion = CategoriesCompanion( id: Value(3), - name: Value('hi'), - profilePicture: Value.absent(), - // false for https://github.com/simolus3/moor/issues/559 - isAwesome: Value(false), + description: Value('description'), + priority: Value(CategoryPriority.low), ); - final user = db.users.mapFromCompanion(companion); + final user = db.categories.mapFromCompanion(companion); expect( user, - User( + Category( id: 3, - name: 'hi', - profilePicture: null, - isAwesome: false, - creationTime: null, + description: 'description', + priority: CategoryPriority.low, ), ); }); diff --git a/moor/test/transactions_test.dart b/moor/test/transactions_test.dart index d3e1c8ca..8ac7fdd7 100644 --- a/moor/test/transactions_test.dart +++ b/moor/test/transactions_test.dart @@ -1,3 +1,4 @@ +//@dart=2.9 import 'dart:async'; @TestOn('!browser') // todo: Figure out why this doesn't run in js @@ -19,6 +20,7 @@ package:mockito/src/mock.dart 128:22 Mo */ import 'package:test/test.dart'; +import 'package:mockito/mockito.dart'; import 'package:moor/moor.dart'; import 'data/tables/todos.dart'; diff --git a/moor/test/update_test.dart b/moor/test/update_test.dart index ae85a62a..996a28e3 100644 --- a/moor/test/update_test.dart +++ b/moor/test/update_test.dart @@ -1,5 +1,7 @@ +//@dart=2.9 import 'dart:async'; +import 'package:mockito/mockito.dart'; import 'package:moor/moor.dart'; import 'package:test/test.dart'; @@ -39,22 +41,6 @@ void main() { 'UPDATE todos SET title = ? WHERE id < ?;', ['Changed title', 50])); }); - test('for data classes', () async { - await (db.update(db.users)..where((u) => u.id.equals(3))).write(User( - isAwesome: true, - // these fields shouldn't change - id: null, - name: null, - profilePicture: null, - creationTime: null, - )); - - verify(executor.runUpdate( - 'UPDATE users SET is_awesome = ? WHERE id = ?;', - [1, 3], - )); - }); - test('with escaped column names', () async { await db .update(db.pureDefaults) diff --git a/moor/test/utils/lazy_database_test.dart b/moor/test/utils/lazy_database_test.dart index d1f333f6..f7e7d273 100644 --- a/moor/test/utils/lazy_database_test.dart +++ b/moor/test/utils/lazy_database_test.dart @@ -1,3 +1,5 @@ +//@dart=2.9 +import 'package:mockito/mockito.dart'; import 'package:moor/moor.dart'; import 'package:pedantic/pedantic.dart'; import 'package:test/test.dart'; @@ -25,7 +27,8 @@ void main() { clearInteractions(inner); lazy.beginTransaction(); - await lazy.runBatched(null); + final batched = BatchedStatements([], []); + await lazy.runBatched(batched); await lazy.runCustom('custom_stmt'); await lazy.runDelete('delete_stmt', [1]); await lazy.runInsert('insert_stmt', [2]); @@ -33,7 +36,7 @@ void main() { await lazy.runUpdate('update_stmt', [4]); verifyInOrder([ - inner.runBatched(null), + inner.runBatched(batched), inner.runCustom('custom_stmt'), inner.runDelete('delete_stmt', [1]), inner.runInsert('insert_stmt', [2]), diff --git a/moor/tools/analyzer_plugin/bin/plugin.dart b/moor/tools/analyzer_plugin/bin/plugin.dart index 5885a20c..3807beb6 100644 --- a/moor/tools/analyzer_plugin/bin/plugin.dart +++ b/moor/tools/analyzer_plugin/bin/plugin.dart @@ -1,3 +1,5 @@ +//@dart=2.6 + import 'dart:convert'; import 'dart:isolate'; diff --git a/moor_flutter/lib/moor_flutter.dart b/moor_flutter/lib/moor_flutter.dart index 9c392480..f68ea20e 100644 --- a/moor_flutter/lib/moor_flutter.dart +++ b/moor_flutter/lib/moor_flutter.dart @@ -6,7 +6,6 @@ library moor_flutter; import 'dart:async'; import 'dart:io'; -import 'package:meta/meta.dart'; import 'package:path/path.dart'; import 'package:moor/moor.dart'; import 'package:moor/backends.dart'; @@ -21,20 +20,19 @@ typedef DatabaseCreator = FutureOr Function(File file); class _SqfliteDelegate extends DatabaseDelegate with _SqfliteExecutor { @override - s.Database db; + late s.Database db; + bool _isOpen = false; final bool inDbFolder; final String path; bool singleInstance; - final DatabaseCreator creator; + final DatabaseCreator? creator; _SqfliteDelegate(this.inDbFolder, this.path, - {this.singleInstance, this.creator}) { - singleInstance ??= true; - } + {this.singleInstance = true, this.creator}); - DbVersionDelegate _delegate; + DbVersionDelegate? _delegate; @override DbVersionDelegate get versionDelegate { return _delegate ??= _SqfliteVersionDelegate(db); @@ -45,20 +43,20 @@ class _SqfliteDelegate extends DatabaseDelegate with _SqfliteExecutor { _SqfliteTransactionDelegate(this); @override - bool get isOpen => db != null; + bool get isOpen => _isOpen; @override Future open(QueryExecutorUser user) async { String resolvedPath; if (inDbFolder) { - resolvedPath = join(await s.getDatabasesPath(), path); + resolvedPath = join((await s.getDatabasesPath())!, path); } else { resolvedPath = path; } final file = File(resolvedPath); if (creator != null && !await file.exists()) { - await creator(file); + await creator!(file); } // default value when no migration happened @@ -66,6 +64,7 @@ class _SqfliteDelegate extends DatabaseDelegate with _SqfliteExecutor { resolvedPath, singleInstance: singleInstance, ); + _isOpen = true; } @override @@ -131,23 +130,23 @@ mixin _SqfliteExecutor on QueryDelegate { } @override - Future runCustom(String statement, List args) { + Future runCustom(String statement, List args) { return db.execute(statement, args); } @override - Future runInsert(String statement, List args) { + Future runInsert(String statement, List args) { return db.rawInsert(statement, args); } @override - Future runSelect(String statement, List args) async { + Future runSelect(String statement, List args) async { final result = await db.rawQuery(statement, args); return QueryResult.fromRows(result); } @override - Future runUpdate(String statement, List args) { + Future runUpdate(String statement, List args) { return db.rawUpdate(statement, args); } } @@ -165,10 +164,10 @@ class FlutterQueryExecutor extends DelegatedDatabase { /// [MigrationStrategy.onCreate] callback because it hasn't been created by /// moor. FlutterQueryExecutor( - {@required String path, - bool logStatements, - bool singleInstance, - DatabaseCreator creator}) + {required String path, + bool? logStatements, + bool singleInstance = true, + DatabaseCreator? creator}) : super( _SqfliteDelegate(false, path, singleInstance: singleInstance, creator: creator), @@ -186,10 +185,10 @@ class FlutterQueryExecutor extends DelegatedDatabase { /// [MigrationStrategy.onCreate] callback because it hasn't been created by /// moor. FlutterQueryExecutor.inDatabaseFolder( - {@required String path, - bool logStatements, - bool singleInstance, - DatabaseCreator creator}) + {required String path, + bool? logStatements, + bool singleInstance = true, + DatabaseCreator? creator}) : super( _SqfliteDelegate(true, path, singleInstance: singleInstance, creator: creator), @@ -206,8 +205,8 @@ class FlutterQueryExecutor extends DelegatedDatabase { /// /// Note that this returns null until the moor database has been opened. /// A moor database is opened lazily when the first query runs. - s.Database get sqfliteDb { + s.Database? get sqfliteDb { final sqfliteDelegate = delegate as _SqfliteDelegate; - return sqfliteDelegate.db; + return sqfliteDelegate.isOpen ? sqfliteDelegate.db : null; } } diff --git a/moor_flutter/pubspec.lock b/moor_flutter/pubspec.lock index 26f998f9..90a0bb0e 100644 --- a/moor_flutter/pubspec.lock +++ b/moor_flutter/pubspec.lock @@ -7,42 +7,42 @@ packages: name: async url: "https://pub.dartlang.org" source: hosted - version: "2.5.0-nullsafety.1" + version: "2.5.0-nullsafety.3" boolean_selector: dependency: transitive description: name: boolean_selector url: "https://pub.dartlang.org" source: hosted - version: "2.1.0-nullsafety.1" + version: "2.1.0-nullsafety.3" characters: dependency: transitive description: name: characters url: "https://pub.dartlang.org" source: hosted - version: "1.1.0-nullsafety.3" + version: "1.1.0-nullsafety.5" charcode: dependency: transitive description: name: charcode url: "https://pub.dartlang.org" source: hosted - version: "1.2.0-nullsafety.1" + version: "1.2.0-nullsafety.3" clock: dependency: transitive description: name: clock url: "https://pub.dartlang.org" source: hosted - version: "1.1.0-nullsafety.1" + version: "1.1.0-nullsafety.3" collection: dependency: transitive description: name: collection url: "https://pub.dartlang.org" source: hosted - version: "1.15.0-nullsafety.3" + version: "1.15.0-nullsafety.5" convert: dependency: transitive description: @@ -56,7 +56,14 @@ packages: name: fake_async url: "https://pub.dartlang.org" source: hosted - version: "1.2.0-nullsafety.1" + version: "1.2.0-nullsafety.3" + ffi: + dependency: transitive + description: + name: ffi + url: "https://pub.dartlang.org" + source: hosted + version: "0.2.0-nullsafety.1" flutter: dependency: "direct main" description: flutter @@ -73,35 +80,35 @@ packages: name: matcher url: "https://pub.dartlang.org" source: hosted - version: "0.12.10-nullsafety.1" + version: "0.12.10-nullsafety.3" meta: - dependency: "direct main" + dependency: transitive description: name: meta url: "https://pub.dartlang.org" source: hosted - version: "1.3.0-nullsafety.4" + version: "1.3.0-nullsafety.6" moor: dependency: "direct main" description: - name: moor - url: "https://pub.dartlang.org" - source: hosted - version: "3.0.0" + path: "../moor" + relative: true + source: path + version: "3.5.0-dev" path: dependency: "direct main" description: name: path url: "https://pub.dartlang.org" source: hosted - version: "1.8.0-nullsafety.1" + version: "1.8.0-nullsafety.3" pedantic: dependency: transitive description: name: pedantic url: "https://pub.dartlang.org" source: hosted - version: "1.9.0" + version: "1.10.0-nullsafety.3" sky_engine: dependency: transitive description: flutter @@ -113,77 +120,84 @@ packages: name: source_span url: "https://pub.dartlang.org" source: hosted - version: "1.8.0-nullsafety.2" + version: "1.8.0-nullsafety.4" sqflite: dependency: "direct main" description: name: sqflite url: "https://pub.dartlang.org" source: hosted - version: "1.3.0" + version: "2.0.0-nullsafety.2" sqflite_common: dependency: transitive description: name: sqflite_common url: "https://pub.dartlang.org" source: hosted - version: "1.0.0+1" + version: "2.0.0-nullsafety.2" + sqlite3: + dependency: transitive + description: + name: sqlite3 + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.9-nullsafety.0" stack_trace: dependency: transitive description: name: stack_trace url: "https://pub.dartlang.org" source: hosted - version: "1.10.0-nullsafety.2" + version: "1.10.0-nullsafety.6" stream_channel: dependency: transitive description: name: stream_channel url: "https://pub.dartlang.org" source: hosted - version: "2.1.0-nullsafety.1" + version: "2.1.0-nullsafety.3" string_scanner: dependency: transitive description: name: string_scanner url: "https://pub.dartlang.org" source: hosted - version: "1.1.0-nullsafety.1" + version: "1.1.0-nullsafety.3" synchronized: dependency: transitive description: name: synchronized url: "https://pub.dartlang.org" source: hosted - version: "2.2.0" + version: "3.0.0-nullsafety.1" term_glyph: dependency: transitive description: name: term_glyph url: "https://pub.dartlang.org" source: hosted - version: "1.2.0-nullsafety.1" + version: "1.2.0-nullsafety.3" test_api: dependency: transitive description: name: test_api url: "https://pub.dartlang.org" source: hosted - version: "0.2.19-nullsafety.2" + version: "0.2.19-nullsafety.6" typed_data: dependency: transitive description: name: typed_data url: "https://pub.dartlang.org" source: hosted - version: "1.3.0-nullsafety.3" + version: "1.3.0-nullsafety.5" vector_math: dependency: transitive description: name: vector_math url: "https://pub.dartlang.org" source: hosted - version: "2.1.0-nullsafety.3" + version: "2.1.0-nullsafety.5" sdks: - dart: ">=2.10.0-110 <=2.11.0-213.1.beta" - flutter: ">=1.10.1 <2.0.0" + dart: ">=2.12.0-29 <3.0.0" + flutter: ">=1.24.0-10 <2.0.0" diff --git a/moor_flutter/pubspec.yaml b/moor_flutter/pubspec.yaml index b7bab9f3..37bff2b7 100644 --- a/moor_flutter/pubspec.yaml +++ b/moor_flutter/pubspec.yaml @@ -1,18 +1,17 @@ name: moor_flutter description: Flutter implementation of moor, a safe and reactive persistence library for Dart applications -version: 3.1.0 +version: 4.0.0-nullsafety repository: https://github.com/simolus3/moor homepage: https://moor.simonbinder.eu/ issue_tracker: https://github.com/simolus3/moor/issues environment: - sdk: ">=2.0.0 <3.0.0" + sdk: '>=2.12.0-0 <3.0.0' dependencies: moor: ^3.0.0 - sqflite: ^1.1.6+5 - meta: ^1.0.0 - path: ^1.0.0 + sqflite: '>=2.0.0-nullsafety <3.0.0' + path: '>1.8.0-nullsafety <2.0.0' flutter: sdk: flutter @@ -20,9 +19,9 @@ dev_dependencies: flutter_test: sdk: flutter -#dependency_overrides: -# moor: -# path: ../moor +dependency_overrides: + moor: + path: ../moor # For information on the generic Dart part of this file, see the # following page: https://www.dartlang.org/tools/pub/pubspec diff --git a/moor_generator/lib/src/analyzer/dart/column_parser.dart b/moor_generator/lib/src/analyzer/dart/column_parser.dart index 3efa8d7e..62160e8a 100644 --- a/moor_generator/lib/src/analyzer/dart/column_parser.dart +++ b/moor_generator/lib/src/analyzer/dart/column_parser.dart @@ -199,7 +199,7 @@ class ColumnParser { final enumType = remainingExpr.typeArgumentTypes[0]; try { - converter = UsedTypeConverter.forEnumColumn(enumType); + converter = UsedTypeConverter.forEnumColumn(enumType, nullable); } on InvalidTypeForEnumConverterException catch (e) { base.step.errors.report(ErrorInDartCode( message: e.errorDescription, diff --git a/moor_generator/lib/src/analyzer/moor/create_table_reader.dart b/moor_generator/lib/src/analyzer/moor/create_table_reader.dart index 4bc3f653..1368679a 100644 --- a/moor_generator/lib/src/analyzer/moor/create_table_reader.dart +++ b/moor_generator/lib/src/analyzer/moor/create_table_reader.dart @@ -69,7 +69,8 @@ class CreateTableReader { )); } else { try { - converter = UsedTypeConverter.forEnumColumn(dartType); + converter = + UsedTypeConverter.forEnumColumn(dartType, column.type.nullable); } on InvalidTypeForEnumConverterException catch (e) { step.reportError(ErrorInMoorFile( message: e.errorDescription, diff --git a/moor_generator/lib/src/model/types.dart b/moor_generator/lib/src/model/types.dart index 71bf08e7..f4624a87 100644 --- a/moor_generator/lib/src/model/types.dart +++ b/moor_generator/lib/src/model/types.dart @@ -18,13 +18,22 @@ abstract class HasType { extension OperationOnTypes on HasType { /// the Dart type of this column that can be handled by moors type mapping. - /// Basically the same as [dartTypeCode], minus custom types. + /// Basically the same as [dartTypeCode], minus custom types and nullability. String get variableTypeName => dartTypeNames[type]; /// The class inside the moor library that represents the same sql type as /// this column. String get sqlTypeName => sqlTypes[type]; + /// The moor Dart type that matches the type of this column. + /// + /// This is the same as [dartTypeCode] but without custom types. + String variableTypeCode( + [GenerationOptions options = const GenerationOptions()]) { + final hasSuffix = nullable && options.nnbd; + return hasSuffix ? '$variableTypeName?' : variableTypeName; + } + /// The dart type that matches the values of this column. For instance, if a /// table has declared an `IntColumn`, the matching dart type name would be /// [int]. @@ -33,8 +42,7 @@ extension OperationOnTypes on HasType { return typeConverter.mappedType?.codeString(options); } - final hasSuffix = nullable && options.nnbd; - return hasSuffix ? '$variableTypeName?' : variableTypeName; + return variableTypeCode(options); } } diff --git a/moor_generator/lib/src/model/used_type_converter.dart b/moor_generator/lib/src/model/used_type_converter.dart index 0f5368b0..ec81e277 100644 --- a/moor_generator/lib/src/model/used_type_converter.dart +++ b/moor_generator/lib/src/model/used_type_converter.dart @@ -1,4 +1,5 @@ import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:meta/meta.dart'; import 'package:moor_generator/src/model/table.dart'; @@ -36,7 +37,7 @@ class UsedTypeConverter { @required this.sqlType, }); - factory UsedTypeConverter.forEnumColumn(DartType enumType) { + factory UsedTypeConverter.forEnumColumn(DartType enumType, bool nullable) { if (enumType.element is! ClassElement) { throw InvalidTypeForEnumConverterException('Not a class', enumType); } @@ -50,7 +51,10 @@ class UsedTypeConverter { return UsedTypeConverter( expression: 'const EnumIndexConverter<$className>($className.values)', - mappedType: enumType, + mappedType: creatingClass.instantiate( + typeArguments: const [], + nullabilitySuffix: + nullable ? NullabilitySuffix.question : NullabilitySuffix.none), sqlType: ColumnType.integer, ); } diff --git a/moor_generator/lib/src/writer/queries/query_writer.dart b/moor_generator/lib/src/writer/queries/query_writer.dart index 464836e8..913cfb3f 100644 --- a/moor_generator/lib/src/writer/queries/query_writer.dart +++ b/moor_generator/lib/src/writer/queries/query_writer.dart @@ -84,7 +84,8 @@ class QueryWriter { void _writeMappingLambda() { if (_select.resultSet.singleColumn) { final column = _select.resultSet.columns.single; - _buffer.write('(QueryRow row) => ${readingCode(column)}'); + _buffer.write('(QueryRow row) => ' + '${readingCode(column, scope.generationOptions)}'); } else if (_select.resultSet.matchingTable != null) { // note that, even if the result set has a matching table, we can't just // use the mapFromRow() function of that table - the column names might @@ -118,7 +119,8 @@ class QueryWriter { for (final column in _select.resultSet.columns) { final fieldName = _select.resultSet.dartNameFor(column); - _buffer.write('$fieldName: ${readingCode(column)},'); + _buffer.write( + '$fieldName: ${readingCode(column, scope.generationOptions)},'); } for (final nested in _select.resultSet.nestedResults) { final prefix = _select.resultSet.nestedPrefixFor(nested); @@ -137,15 +139,18 @@ class QueryWriter { /// Returns Dart code that, given a variable of type `QueryRow` named `row` /// in the same scope, reads the [column] from that row and brings it into a /// suitable type. - static String readingCode(ResultColumn column) { + static String readingCode(ResultColumn column, GenerationOptions options) { final readMethod = readFromMethods[column.type]; final dartLiteral = asDartLiteral(column.name); var code = 'row.$readMethod($dartLiteral)'; if (column.typeConverter != null) { + final needsAssert = !column.nullable && options.nnbd; + final converter = column.typeConverter; code = '${_converter(converter)}.mapToDart($code)'; + if (needsAssert) code += '!'; } return code; } @@ -400,17 +405,24 @@ class QueryWriter { if (element is FoundVariable) { // Variables without type converters are written as: - // `Variable.withInt(x)`. When there's a type converter, we instead use - // `Variable.withInt(typeConverter.mapToSql(x))`. + // `Variable(x)`. When there's a type converter, we instead use + // `Variable(typeConverter.mapToSql(x))`. // Finally, if we're dealing with a list, we use a collection for to // write all the variables sequentially. String constructVar(String dartExpr) { - final buffer = StringBuffer(createVariable[element.type])..write('('); + final type = element.variableTypeCode(scope.generationOptions); + final buffer = StringBuffer('Variable<$type>('); if (element.typeConverter != null) { // Apply the converter buffer.write( '${_converter(element.typeConverter)}.mapToSql($dartExpr)'); + + final needsNullAssertion = + !element.nullable && scope.generationOptions.nnbd; + if (needsNullAssertion) { + buffer.write('!'); + } } else { buffer.write(dartExpr); } diff --git a/moor_generator/lib/src/writer/queries/result_set_writer.dart b/moor_generator/lib/src/writer/queries/result_set_writer.dart index 0617492d..6738e9f1 100644 --- a/moor_generator/lib/src/writer/queries/result_set_writer.dart +++ b/moor_generator/lib/src/writer/queries/result_set_writer.dart @@ -13,6 +13,7 @@ class ResultSetWriter { void write() { final className = query.resultClassName; final fieldNames = []; + final nonNullableFields = {}; final into = scope.leaf(); final resultSet = query.resultSet; @@ -34,25 +35,33 @@ class ResultSetWriter { into.write('$modifier $runtimeType $name\n;'); fieldNames.add(name); + if (!column.nullable) nonNullableFields.add(name); } for (final nested in resultSet.nestedResults) { final typeName = nested.table.dartTypeName; final fieldName = nested.dartFieldName; - into.write('$modifier $typeName $fieldName;\n'); + if (scope.generationOptions.nnbd) { + into.write('$modifier $typeName? $fieldName;\n'); + } else { + into.write('$modifier $typeName $fieldName;\n'); + } fieldNames.add(fieldName); } // write the constructor if (scope.options.rawResultSetData) { - into.write('$className({@required QueryRow row,'); + into.write('$className({${scope.required} QueryRow row,'); } else { into.write('$className({'); } for (final column in fieldNames) { + if (nonNullableFields.contains(column)) { + into..write(scope.required)..write(' '); + } into.write('this.$column,'); } diff --git a/moor_generator/lib/src/writer/tables/data_class_writer.dart b/moor_generator/lib/src/writer/tables/data_class_writer.dart index f9fce0d2..10286e41 100644 --- a/moor_generator/lib/src/writer/tables/data_class_writer.dart +++ b/moor_generator/lib/src/writer/tables/data_class_writer.dart @@ -109,7 +109,11 @@ class DataClassWriter { loadType = '$loaded.mapToDart($loadType)'; } - _buffer.write('$getter: $loadType,'); + if (!column.nullable && scope.generationOptions.nnbd) { + _buffer.write('$getter: $loadType!,'); + } else { + _buffer.write('$getter: $loadType,'); + } } _buffer.write(');}\n'); @@ -217,18 +221,32 @@ class DataClassWriter { ..write('final map = {};'); for (final column in table.columns) { - _buffer.write('if (!nullToAbsent || ${column.dartGetterName} != null) {'); + // We include all columns that are not null. If nullToAbsent is false, we + // also include null columns. When generating NNBD code, we can include + // non-nullable columns without an additional null check. + final needsNullCheck = column.nullable || !scope.generationOptions.nnbd; + final needsScope = needsNullCheck || column.typeConverter != null; + if (needsNullCheck) { + _buffer.write('if (!nullToAbsent || ${column.dartGetterName} != null)'); + } + if (needsScope) _buffer.write('{'); + + final typeName = column.variableTypeCode(scope.generationOptions); final mapSetter = 'map[${asDartLiteral(column.name.name)}] = ' - 'Variable<${column.variableTypeName}>'; + 'Variable<$typeName>'; if (column.typeConverter != null) { // apply type converter before writing the variable final converter = column.typeConverter; final fieldName = '${table.tableInfoName}.${converter.fieldName}'; + final assertNotNull = !column.nullable && scope.generationOptions.nnbd; + _buffer ..write('final converter = $fieldName;\n') ..write(mapSetter) - ..write('(converter.mapToSql(${column.dartGetterName}));'); + ..write('(converter.mapToSql(${column.dartGetterName})'); + if (assertNotNull) _buffer.write('!'); + _buffer.write(');'); } else { // no type converter. Write variable directly _buffer @@ -238,7 +256,8 @@ class DataClassWriter { ..write(');'); } - _buffer.write('}'); + // This one closes the optional if from before. + if (needsScope) _buffer.write('}'); } _buffer.write('return map; \n}\n'); @@ -256,13 +275,17 @@ class DataClassWriter { for (final column in table.columns) { final dartName = column.dartGetterName; - _buffer - ..write(dartName) - ..write(': ') - ..write(dartName) - ..write(' == null && nullToAbsent ? const Value.absent() : Value (') - ..write(dartName) - ..write('),'); + _buffer..write(dartName)..write(': '); + + final needsNullCheck = column.nullable || !scope.generationOptions.nnbd; + if (needsNullCheck) { + _buffer + ..write(dartName) + ..write(' == null && nullToAbsent ? const Value.absent() : '); + // We'll write the non-null case afterwards + } + + _buffer..write('Value (')..write(dartName)..write('),'); } _buffer.writeln(');\n}'); diff --git a/moor_generator/lib/src/writer/tables/table_writer.dart b/moor_generator/lib/src/writer/tables/table_writer.dart index 4fb82321..3012f1a5 100644 --- a/moor_generator/lib/src/writer/tables/table_writer.dart +++ b/moor_generator/lib/src/writer/tables/table_writer.dart @@ -210,6 +210,8 @@ class TableWriter { const locals = {'instance', 'isInserting', 'context', 'data'}; + final nonNullAssert = scope.generationOptions.nnbd ? '!' : ''; + for (final column in table.columns) { final getterName = column.thisIfNeeded(locals); final metaName = _fieldNameForColumnMeta(column); @@ -228,7 +230,7 @@ class TableWriter { ..write('context.handle(' '$metaName, ' '$getterName.isAcceptableOrUnknown(' - 'data[$columnNameString], $metaName));') + 'data[$columnNameString]$nonNullAssert, $metaName));') ..write('}'); if (table.isColumnRequiredForInsert(column)) { diff --git a/moor_generator/lib/src/writer/tables/update_companion_writer.dart b/moor_generator/lib/src/writer/tables/update_companion_writer.dart index 9afc5cef..04e17034 100644 --- a/moor_generator/lib/src/writer/tables/update_companion_writer.dart +++ b/moor_generator/lib/src/writer/tables/update_companion_writer.dart @@ -111,7 +111,8 @@ class UpdateCompanionWriter { ..write('({'); for (final column in table.columns) { - final type = scope.nullableType('Expression<${column.variableTypeName}>'); + final typeName = column.dartTypeCode(scope.generationOptions); + final type = scope.nullableType('Expression<$typeName>'); _buffer.write('$type ${column.dartGetterName}, \n'); } @@ -160,14 +161,15 @@ class UpdateCompanionWriter { '(bool nullToAbsent) {\n') ..write('final map = {};'); - const locals = {'map', 'nullToAbsent'}; + const locals = {'map', 'nullToAbsent', 'converter'}; for (final column in table.columns) { final getterName = column.thisIfNeeded(locals); _buffer.write('if ($getterName.present) {'); + final typeName = column.variableTypeCode(scope.generationOptions); final mapSetter = 'map[${asDartLiteral(column.name.name)}] = ' - 'Variable<${column.variableTypeName}>'; + 'Variable<$typeName>'; if (column.typeConverter != null) { // apply type converter before writing the variable @@ -176,7 +178,12 @@ class UpdateCompanionWriter { _buffer ..write('final converter = $fieldName;\n') ..write(mapSetter) - ..write('(converter.mapToSql($getterName.value));'); + ..write('(converter.mapToSql($getterName.value)'); + + if (!column.nullable && scope.generationOptions.nnbd) { + _buffer.write('!'); + } + _buffer.write(');'); } else { // no type converter. Write variable directly _buffer diff --git a/moor_generator/pubspec.yaml b/moor_generator/pubspec.yaml index 8fdc9735..6866c246 100644 --- a/moor_generator/pubspec.yaml +++ b/moor_generator/pubspec.yaml @@ -51,4 +51,4 @@ dependency_overrides: sqlparser: path: ../sqlparser moor: - path: ../moor + path: ../moor \ No newline at end of file diff --git a/sqlparser/test/scanner/recognizes_all_tokens_test.dart b/sqlparser/test/scanner/recognizes_all_tokens_test.dart index 68fd24ff..fdd80f43 100644 --- a/sqlparser/test/scanner/recognizes_all_tokens_test.dart +++ b/sqlparser/test/scanner/recognizes_all_tokens_test.dart @@ -21,6 +21,9 @@ void main() { try { library = open.openSqlite(); + + // Some platforms have sqlite3, but no sqlite3_keyword_count + library.lookup('sqlite3_keyword_count'); } on dynamic { skip = 'sqlite3 is not available in test environment'; } diff --git a/tool/Dockerfile b/tool/Dockerfile deleted file mode 100644 index 110bc63a..00000000 --- a/tool/Dockerfile +++ /dev/null @@ -1,17 +0,0 @@ -FROM ubuntu:rolling - -RUN apt-get update && apt-get install -y --no-install-recommends apt-transport-https wget gnupg2 ca-certificates curl git - -# Setup for Dart -RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - -RUN wget -qO- https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_stable.list > /etc/apt/sources.list.d/dart_stable.list -ENV PATH="/usr/lib/dart/bin:${PATH}" - -# Setup for Google Chrome -RUN echo 'deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main' | tee /etc/apt/sources.list.d/google-chrome.list - -#RUN apt-get update && apt-get install -y --no-install-recommends -q libsqlite3-dev google-chrome-stable firefox dart -RUN apt-get update && apt-get install -y --no-install-recommends -q libsqlite3-dev dart - -# We ocassionally have to change this file to manually trigger rebuilds in the CI. Particularly, after a new Dart SDK -# version is out. Prefer to use Dart 2.10 or above. \ No newline at end of file diff --git a/tool/analyze.sh b/tool/analyze.sh deleted file mode 100755 index 463ba648..00000000 --- a/tool/analyze.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env bash - -EXIT_CODE=0 - -cd moor -echo $(pwd) -dart format -o none --set-exit-if-changed . || EXIT_CODE=$? -dart analyze --fatal-infos --fatal-warnings || EXIT_CODE=$? -cd .. - -# todo we don't analyze this subproject because Flutter isn't installed in the CI -#cd moor_flutter -#echo $(pwd) -#dartfmt -n --set-exit-if-changed . || EXIT_CODE=$? -#dartanalyzer --options analysis_options.yaml --fatal-infos --fatal-warnings lib/ || EXIT_CODE=$? -#cd .. - -#cd moor_ffi -#echo $(pwd) -#dartfmt -n --set-exit-if-changed . || EXIT_CODE=$? -#dartanalyzer --options analysis_options.yaml --fatal-infos --fatal-warnings lib/ test/ || EXIT_CODE=$? -#cd .. - -cd moor_generator -echo $(pwd) -dart format -o none --set-exit-if-changed . || EXIT_CODE=$? -dart analyze --fatal-infos --fatal-warnings || EXIT_CODE=$? -cd .. - -cd sqlparser -echo $(pwd) -dart format -o none --set-exit-if-changed . || EXIT_CODE=$? -dart analyze --fatal-infos --fatal-warnings || EXIT_CODE=$? - -exit $EXIT_CODE \ No newline at end of file diff --git a/tool/misc_integration_test.sh b/tool/misc_integration_test.sh index f4bd3bf7..15d538ef 100755 --- a/tool/misc_integration_test.sh +++ b/tool/misc_integration_test.sh @@ -4,14 +4,14 @@ EXIT_CODE=0 pushd extras/integration_tests/vm echo "Running integration tests with moor_ffi & VM" -pub upgrade -pub run test || EXIT_CODE=$? +dart pub upgrade +dart test || EXIT_CODE=$? popd pushd extras/with_built_value echo "Running build runner in with_built_value" -pub upgrade -pub run build_runner build --delete-conflicting-outputs || EXIT_CODE=$? +dart pub upgrade +dart run build_runner build --delete-conflicting-outputs || EXIT_CODE=$? popd exit $EXIT_CODE \ No newline at end of file diff --git a/tool/pub_get.sh b/tool/pub_get.sh deleted file mode 100755 index dfa7b5b2..00000000 --- a/tool/pub_get.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env bash - -cd moor -echo $(pwd) -pub upgrade -cd .. - -#cd moor_flutter -#echo $(pwd) -#flutter packages upgrade -#cd .. - -cd moor_generator -echo $(pwd) -pub upgrade -cd .. - -cd sqlparser -echo $(pwd) -pub upgrade -cd .. - -#cd moor_ffi -#echo $(pwd) -#flutter packages upgrade -#cd .. \ No newline at end of file diff --git a/tool/test_generator.sh b/tool/test_generator.sh deleted file mode 100755 index 9ce7024b..00000000 --- a/tool/test_generator.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env bash - -cd moor_generator - -# todo figure out why analyzer tests don't run on the CI (it throws an internal error) -pub run test --exclude-tags analyzer \ No newline at end of file diff --git a/tool/test_moor.sh b/tool/test_moor.sh deleted file mode 100755 index c269bfd9..00000000 --- a/tool/test_moor.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env bash - -EXIT_CODE=0 - -cd moor || exit 1 -pub run build_runner build --delete-conflicting-outputs - -pub run test --coverage=coverage || EXIT_CODE=$? - -# Testing on the web doesn't work on CI (we're running into out-of-memory issues even with 12G of RAM) -#if [ $EXIT_CODE -eq 0 ] -# then pub run test -P browsers || EXIT_CODE=$? -#fi - -exit $EXIT_CODE \ No newline at end of file diff --git a/tool/test_sqlparser.sh b/tool/test_sqlparser.sh deleted file mode 100755 index 44376ee9..00000000 --- a/tool/test_sqlparser.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env bash - -cd sqlparser -pub run test --coverage=coverage \ No newline at end of file diff --git a/tool/travis.sh b/tool/travis.sh deleted file mode 100755 index 28639138..00000000 --- a/tool/travis.sh +++ /dev/null @@ -1,51 +0,0 @@ -#!/bin/bash -# Created with package:mono_repo v1.2.1 -# We don't use travis, but this let's us run mono_repo presubmit locally - -if [ -z "$PKG" ]; then - echo -e '\033[31mPKG environment variable must be set!\033[0m' - exit 1 -fi - -if [ "$#" == "0" ]; then - echo -e '\033[31mAt least one task argument must be provided!\033[0m' - exit 1 -fi - -pushd $PKG -pub upgrade || exit $? - -EXIT_CODE=0 - -while (( "$#" )); do - TASK=$1 - case $TASK in - command) echo - echo -e '\033[1mTASK: command\033[22m' - echo -e 'pub run build_runner build -v --delete-conflicting-outputs' - pub run build_runner build -v --delete-conflicting-outputs || EXIT_CODE=$? - ;; - dartanalyzer) echo - echo -e '\033[1mTASK: dartanalyzer\033[22m' - echo -e 'dartanalyzer --fatal-infos --fatal-warnings lib/ test/' - dartanalyzer --fatal-infos --fatal-warnings lib/ test/ || EXIT_CODE=$? - ;; - dartfmt) echo - echo -e '\033[1mTASK: dartfmt\033[22m' - echo -e 'dartfmt -n --set-exit-if-changed .' - dartfmt -n --set-exit-if-changed . || EXIT_CODE=$? - ;; - test) echo - echo -e '\033[1mTASK: test\033[22m' - echo -e 'pub run test' - pub run test || EXIT_CODE=$? - ;; - *) echo -e "\033[31mNot expecting TASK '${TASK}'. Error!\033[0m" - EXIT_CODE=1 - ;; - esac - - shift -done - -exit $EXIT_CODE diff --git a/tool/upload_coverage.sh b/tool/upload_coverage.sh deleted file mode 100755 index 0f232032..00000000 --- a/tool/upload_coverage.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env bash - -pushd extras/coverage_formatting -pub upgrade --no-precompile -popd - -dart extras/coverage_formatting/bin/coverage.dart - -bash <(curl -s https://codecov.io/bash) -f lcov.info