mirror of https://github.com/AMT-Cheif/drift.git
Add substrExpr to query builder
This commit is contained in:
parent
f9d5443a8e
commit
fe0df6d69c
|
@ -137,10 +137,31 @@ extension StringExpressionOperators on Expression<String> {
|
||||||
/// and [length] can be negative to return a section of the string before
|
/// and [length] can be negative to return a section of the string before
|
||||||
/// [start].
|
/// [start].
|
||||||
Expression<String> substr(int start, [int? length]) {
|
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', [
|
return FunctionCallExpression('SUBSTR', [
|
||||||
this,
|
this,
|
||||||
Constant<int>(start),
|
start,
|
||||||
if (length != null) Constant<int>(length),
|
if (length != null) length,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -125,7 +125,11 @@ void main() {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('substring', () {
|
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'));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
@ -52,5 +52,8 @@ void main() {
|
||||||
test('substr', () {
|
test('substr', () {
|
||||||
expect(expression.substr(10), generates('SUBSTR(col, 10)'));
|
expect(expression.substr(10), generates('SUBSTR(col, 10)'));
|
||||||
expect(expression.substr(10, 2), generates('SUBSTR(col, 10, 2)'));
|
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]));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue