Skip to content

Commit

Permalink
Add substr to Dart query builder (#2555)
Browse files Browse the repository at this point in the history
  • Loading branch information
simolus3 committed Aug 10, 2023
1 parent fae8be0 commit f3e6ef2
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 0 deletions.
2 changes: 2 additions & 0 deletions drift/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
- Add support for subqueries in the Dart query builder.
- Add `isInExp` and `isNotInExp` to construct `IS IN` expressions with arbitrary
expressions.
- Add the `substr` extension on `Expression<String>` to call the sqlite3 function from
the Dart API.
- Add `isolateSetup` to `NativeDatabase.createInBackground()` to override libraries.

## 2.10.0
Expand Down
15 changes: 15 additions & 0 deletions drift/lib/src/runtime/query_builder/expressions/text.dart
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,21 @@ extension StringExpressionOperators on Expression<String> {
Expression<String> trimRight() {
return FunctionCallExpression('RTRIM', [this]);
}

/// Calls the [`substr`](https://sqlite.org/lang_corefunc.html#substr)
/// function on this string.
///
/// Note that the function has different semantics than the [String.substring]
/// method for Dart strings - for instance, the [start] index starts at one
/// and [length] can be negative to return a section of the string before
/// [start].
Expression<String> substr(int start, [int? length]) {
return FunctionCallExpression('SUBSTR', [
this,
Constant<int>(start),
if (length != null) Constant<int>(length),
]);
}
}

/// A `text LIKE pattern` expression that will be true if the first expression
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@ void main() {
const literal = Constant(' hello world ');
expect(eval(literal.trimRight()), completion(' hello world'));
});

test('substring', () {
expect(eval(Constant('hello world').substr(7)), completion('world'));
});
});

test('coalesce', () async {
Expand Down
5 changes: 5 additions & 0 deletions drift/test/database/expressions/text_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,9 @@ void main() {
});
});
});

test('substr', () {
expect(expression.substr(10), generates('SUBSTR(col, 10)'));
expect(expression.substr(10, 2), generates('SUBSTR(col, 10, 2)'));
});
}

0 comments on commit f3e6ef2

Please sign in to comment.