Allow disabling conflict target (#2925)

This commit is contained in:
Simon Binder 2024-03-20 22:47:24 +01:00
parent 7c0c52cdfe
commit 044a0f3980
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
2 changed files with 26 additions and 1 deletions

View File

@ -276,8 +276,15 @@ class InsertStatement<T extends Table, D> {
if (ctx.dialect == SqlDialect.mariadb) {
ctx.buffer.write(' ON DUPLICATE');
} else {
ctx.buffer.write(' ON CONFLICT(');
ctx.buffer.write(' ON CONFLICT');
if (target != null && target.isEmpty) {
// An empty list indicates that no explicit target should be generated
// by drift, the default rules by the database will apply instead.
return;
}
ctx.buffer.write('(');
final conflictTarget = target ?? table.$primaryKey.toList();
if (conflictTarget.isEmpty) {
@ -473,6 +480,8 @@ class DoUpdate<T extends Table, D> extends UpsertClause<T, D> {
/// specifies the uniqueness constraint that will trigger the upsert.
///
/// By default, the primary key of the table will be used.
/// This can be set to an empty list, in which case no explicit conflict
/// target will be generated by drift.
final List<Column>? target;
/// Creates a `DO UPDATE` clause.

View File

@ -263,6 +263,22 @@ void main() {
));
});
test('can ignore conflict target', () async {
await db.into(db.todosTable).insert(
TodosTableCompanion.insert(content: 'my content'),
onConflict: DoUpdate((old) {
return TodosTableCompanion.custom(
content: const Variable('important: ') + old.content);
}, target: []),
);
verify(executor.runInsert(
'INSERT INTO "todos" ("content") VALUES (?) '
'ON CONFLICT DO UPDATE SET "content" = ? || "content"',
argThat(equals(['my content', 'important: '])),
));
});
test(
'can use multiple upsert targets',
() async {