Add substrExpr to query builder

This commit is contained in:
Simon Binder 2024-02-24 12:12:05 +01:00
parent f9d5443a8e
commit fe0df6d69c
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
3 changed files with 31 additions and 3 deletions

View File

@ -137,10 +137,31 @@ extension StringExpressionOperators on Expression<String> {
/// and [length] can be negative to return a section of the string before
/// [start].
Expression<String> substr(int start, [int? length]) {
return substrExpr(
Constant(start), length != null ? Constant(length) : null);
}
/// Calls the [`substr`](https://sqlite.org/lang_corefunc.html#substr)
/// function with arbitrary expressions as arguments.
///
/// For instance, this call uses [substrExpr] to remove the last 5 characters
/// from a column. As this depends on its [StringExpressionOperators.length],
/// it needs to use expressions:
///
/// ```dart
/// update(table).write(TableCompanion.custom(
/// column: column.substrExpr(Variable(1), column.length - Variable(5))
/// ));
/// ```
///
/// When both [start] and [length] are Dart values (e.g. [Variable]s or
/// [Constant]s), consider using [substr] instead.
Expression<String> substrExpr(Expression<int> start,
[Expression<int>? length]) {
return FunctionCallExpression('SUBSTR', [
this,
Constant<int>(start),
if (length != null) Constant<int>(length),
start,
if (length != null) length,
]);
}
}

View File

@ -125,7 +125,11 @@ void main() {
});
test('substring', () {
expect(eval(Constant('hello world').substr(7)), completion('world'));
final input = Constant('hello world');
expect(eval(input.substr(7)), completion('world'));
expect(eval(input.substrExpr(Variable(1), input.length - Variable(6))),
completion('hello'));
});
});

View File

@ -52,5 +52,8 @@ void main() {
test('substr', () {
expect(expression.substr(10), generates('SUBSTR(col, 10)'));
expect(expression.substr(10, 2), generates('SUBSTR(col, 10, 2)'));
expect(expression.substrExpr(Variable(1), expression.length - Variable(5)),
generates('SUBSTR(col, ?, LENGTH(col) - ?)', [1, 5]));
});
}