Add Expression.equalsNullable

This commit is contained in:
Simon Binder 2022-07-21 18:30:27 +02:00
parent c0da411db4
commit 4d9b505703
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
2 changed files with 29 additions and 0 deletions

View File

@ -49,9 +49,28 @@ abstract class Expression<D extends Object> implements FunctionParameter {
/// type. The [compare] value will be written
/// as a variable using prepared statements, so there is no risk of
/// an SQL-injection.
///
/// This method only supports comparing the value of the column to non-
/// nullable values and translates to a direct `=` comparison in SQL.
/// To compare this column to `null`, use [equalsNullable].
Expression<bool> equals(D compare) =>
_Comparison.equal(this, Variable<D>(compare));
/// Compares the value of this column to [compare] or `null`.
///
/// When [compare] is null, this generates an `IS NULL` expression in SQL.
/// For non-null values, an [equals] expression is generated.
/// This means that, for this method, two null values are considered equal.
/// This deviates from the usual notion in SQL that doesn't allow comparing
/// `NULL` values with equals.
Expression<bool> equalsNullable(D? compare) {
if (compare == null) {
return this.isNull();
} else {
return equals(compare);
}
}
/// Casts this expression to an expression of [D].
///
/// Calling [dartCast] will not affect the generated sql. In particular, it

View File

@ -111,4 +111,14 @@ void main() {
.runSelect(argThat(contains('ON categories._rowid_ = ?')), [3]));
});
});
test('equals', () {
const a = CustomExpression<int>('a', precedence: Precedence.primary);
const b = CustomExpression<int>('b', precedence: Precedence.primary);
expect(a.equals(3), generates('a = ?', [3]));
expect(a.equalsNullable(3), generates('a = ?', [3]));
expect(a.equalsNullable(null), generates('a IS NULL'));
expect(a.equalsExp(b), generates('a = b'));
});
}