Skip to content

Commit

Permalink
Add delete query
Browse files Browse the repository at this point in the history
  • Loading branch information
l7ssha committed Nov 11, 2024
1 parent 13f05d0 commit 034df11
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
20 changes: 20 additions & 0 deletions lib/src/util/query_builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ abstract class Query {
final String from;
final String? alias;

String get aliasOrEmpty => alias ?? '';

Query(this.from, {this.alias});

Sql build();
Expand Down Expand Up @@ -158,6 +160,24 @@ class UpdateQuery extends Query with _WhereQuery {
}
}

class DeleteQuery extends Query with _WhereQuery {
DeleteQuery(super.from);

@override
Sql build() {
if (_andWheres.isEmpty && _orWheres.isEmpty) {
throw QueryBuilderException("Delete query requires where statement");
}

final buffer = StringBuffer("DELETE FROM $from $aliasOrEmpty ");

_buildWheres(buffer);
buffer.write(";");

return Sql.named(buffer.toStringClean());
}
}

class SelectQuery extends Query with _WhereQuery, _JoinQuery {
final List<String> _selects = [];

Expand Down
8 changes: 8 additions & 0 deletions test/query_builder_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -115,5 +115,13 @@ void main() {
expect(query.build().asString(), "INSERT INTO test (name,model) VALUES (moron,@model) RETURNING id;");
});
});

group("Delete tests", () {
test("Simple delete", () {
final query = DeleteQuery("test")..andWhere("name = 'test'");

expect(query.build().asString(), "DELETE FROM test WHERE name = 'test';");
});
});
});
}

0 comments on commit 034df11

Please sign in to comment.