Skip to content

Commit

Permalink
Add Value.absentIfNull
Browse files Browse the repository at this point in the history
  • Loading branch information
simolus3 committed Feb 24, 2024
1 parent fe0df6d commit d1d2b7f
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 5 deletions.
2 changes: 2 additions & 0 deletions drift/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions drift/lib/src/runtime/data_class.dart
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ class Value<T> {
/// 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,
Expand All @@ -167,6 +168,15 @@ class Value<T> {
_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()';

Expand Down
11 changes: 6 additions & 5 deletions drift/test/database/data_class_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<int?>.ofNullable(null),
throwsA(isA<AssertionError>()));

expect(const Value<int>.ofNullable(null).present, isFalse);
expect(const Value<int?>.ofNullable(12).present, isTrue);
expect(const Value<int>.ofNullable(23).present, isTrue);
expect(const Value<int?>.absentIfNull(null).present, isFalse);
expect(const Value<int>.absentIfNull(null).present, isFalse);
expect(const Value<int?>.absentIfNull(12).present, isTrue);
expect(const Value<int>.absentIfNull(23).present, isTrue);
});

test('companions support hash and equals', () {
Expand Down

0 comments on commit d1d2b7f

Please sign in to comment.