Add coalesce function (#780)

This commit is contained in:
Simon Binder 2020-08-21 20:59:55 +02:00
parent 0e631b98d2
commit 0bc6f1368b
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
5 changed files with 34 additions and 1 deletions

View File

@ -67,6 +67,15 @@ which takes any expression and returns a boolean expression. The expression retu
resolve to `true` if the inner expression resolves to null and `false` otherwise.
As you would expect, `isNotNull` works the other way around.
To use a fallback value when an expression evaluates to `null`, you can use the `coalesce`
function. It takes a list of expressions and evaluates to the first one that isn't `null`:
```dart
final category = coalesce([todos.category, const Constant(1)]);
```
This corresponds to the `??` operator in Dart.
## Date and Time
For columns and expressions that return a `DateTime`, you can use the
`year`, `month`, `day`, `hour`, `minute` and `second` getters to extract individual

View File

@ -3,7 +3,7 @@
- New `DatabaseConnection.delayed` constructor to synchronously obtain a database connection
that requires async setup. This can be useful when connecting to a `MoorIsolate`.
- `VmDatabase`: Create directory of database file to avoid misuse errors from sqlite3.
- Add `groupConcat` function to Dart api.
- Add `groupConcat` and `coalesce` functions to the Dart query builder.
## 3.3.1

View File

@ -10,6 +10,15 @@ Expression<bool> isNull(Expression inner) => _NullCheck(inner, true);
/// value.
Expression<bool> isNotNull(Expression inner) => _NullCheck(inner, false);
/// Evaluates to the first expression in [expressions] that's not null, or
/// null if all [expressions] evaluate to null.
Expression<T> coalesce<T>(List<Expression<T>> expressions) {
assert(expressions.length >= 2,
'coalesce must have at least 2 arguments, got ${expressions.length}');
return FunctionCallExpression<T>('COALESCE', expressions);
}
class _NullCheck extends Expression<bool> {
final Expression _inner;
final bool _isNull;

View File

@ -42,4 +42,12 @@ void main() {
expect(row.read(containsSql), isTrue);
});
test('coalesce', () async {
final expr = coalesce<int>([const Constant(null), const Constant(3)]);
final row = await (db.selectOnly(db.users)..addColumns([expr])).getSingle();
expect(row.read(expr), equals(3));
});
}

View File

@ -4,6 +4,7 @@ import 'package:test/test.dart';
import '../data/tables/todos.dart';
import '../data/utils/expect_equality.dart';
import '../data/utils/expect_generated.dart';
void main() {
final innerExpression = GeneratedTextColumn('name', null, true);
@ -27,4 +28,10 @@ void main() {
expectEquals(expr, moor.isNotNull(innerExpression));
});
test('generates COALESCE expressions', () {
final expr = moor.coalesce([const Constant<int>(null), const Constant(3)]);
expect(expr, generates('COALESCE(NULL, 3)'));
});
}