diff --git a/drift/CHANGELOG.md b/drift/CHANGELOG.md index a6ddd65a..7be8c247 100644 --- a/drift/CHANGELOG.md +++ b/drift/CHANGELOG.md @@ -12,6 +12,8 @@ - Improve stack traces for errors happening on drift isolates (which includes usages of `NativeDatabase.createInBackground`). - Don't cache `EXPLAIN` statements, avoiding schema locks. +- Deprecate `Value.ofNullable` in favor of `Value.absentIfNull`, which is more + explicit about its behavior and allows nullable types too. - Migrate `WasmDatabase` to `dart:js_interop` and `package:web`. ## 2.15.0 diff --git a/drift/lib/src/runtime/data_class.dart b/drift/lib/src/runtime/data_class.dart index 78d90dae..106ec3db 100644 --- a/drift/lib/src/runtime/data_class.dart +++ b/drift/lib/src/runtime/data_class.dart @@ -158,6 +158,7 @@ class Value { /// This constructor should only be used when [T] is not nullable. If [T] were /// nullable, there wouldn't be a clear interpretation for a `null` [value]. /// See the overall documentation on [Value] for details. + @Deprecated('Use Value.absentIfNull instead') const Value.ofNullable(T? value) : assert( value != null || null is! T, @@ -167,6 +168,15 @@ class Value { _value = value, present = value != null; + /// Create a value that is absent if [value] is `null` and [present] if it's + /// not. + /// + /// The functionality is equiavalent to the following: + /// `x != null ? Value(x) : Value.absent()`. + const Value.absentIfNull(T? value) + : _value = value, + present = value != null; + @override String toString() => present ? 'Value($value)' : 'Value.absent()'; diff --git a/drift/test/database/data_class_test.dart b/drift/test/database/data_class_test.dart index e3784421..05afec45 100644 --- a/drift/test/database/data_class_test.dart +++ b/drift/test/database/data_class_test.dart @@ -105,15 +105,16 @@ void main() { expect(entry.toCompanion(true), const PureDefaultsCompanion()); }); - test('nullable values cannot be used with nullOrAbsent', () { + test('utilities to wrap nullable values', () { expect( - // ignore: prefer_const_constructors + // ignore: prefer_const_constructors, deprecated_member_use_from_same_package () => Value.ofNullable(null), throwsA(isA())); - expect(const Value.ofNullable(null).present, isFalse); - expect(const Value.ofNullable(12).present, isTrue); - expect(const Value.ofNullable(23).present, isTrue); + expect(const Value.absentIfNull(null).present, isFalse); + expect(const Value.absentIfNull(null).present, isFalse); + expect(const Value.absentIfNull(12).present, isTrue); + expect(const Value.absentIfNull(23).present, isTrue); }); test('companions support hash and equals', () {