Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions QueryBuilder.Tests/DeleteTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using SqlKata.Compilers;
using SqlKata.Extensions;
using SqlKata.Tests.Infrastructure;
using System;
using System.Linq;
using Xunit;

namespace SqlKata.Tests
{
public class DeleteTests : TestSupport
{
[Fact]
public void BasicDelete()
{
var q = new Query("Posts").AsDelete();

var c = Compile(q);

Assert.Equal("DELETE FROM [Posts]", c[EngineCodes.SqlServer]);
}

[Fact]
public void DeleteWithJoin()
{
var q = new Query("Posts")
.Join("Authors", "Authors.Id", "Posts.AuthorId")
.Where("Authors.Id", 5)
.AsDelete();

var c = Compile(q);

Assert.Equal("DELETE [Posts] FROM [Posts] \nINNER JOIN [Authors] ON [Authors].[Id] = [Posts].[AuthorId] WHERE [Authors].[Id] = 5", c[EngineCodes.SqlServer]);
Assert.Equal("DELETE `Posts` FROM `Posts` \nINNER JOIN `Authors` ON `Authors`.`Id` = `Posts`.`AuthorId` WHERE `Authors`.`Id` = 5", c[EngineCodes.MySql]);
}

[Fact]
public void DeleteWithJoinAndAlias()
{
var q = new Query("Posts as P")
.Join("Authors", "Authors.Id", "P.AuthorId")
.Where("Authors.Id", 5)
.AsDelete();

var c = Compile(q);

Assert.Equal("DELETE [P] FROM [Posts] AS [P] \nINNER JOIN [Authors] ON [Authors].[Id] = [P].[AuthorId] WHERE [Authors].[Id] = 5", c[EngineCodes.SqlServer]);
}
}
}
20 changes: 19 additions & 1 deletion QueryBuilder/Compilers/Compiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -263,14 +263,32 @@ protected virtual SqlResult CompileDeleteQuery(Query query)
throw new InvalidOperationException("Invalid table expression");
}

var joins = CompileJoins(ctx);

var where = CompileWheres(ctx);

if (!string.IsNullOrEmpty(where))
{
where = " " + where;
}

ctx.RawSql = $"DELETE FROM {table}{where}";
if (string.IsNullOrEmpty(joins))
{
ctx.RawSql = $"DELETE FROM {table}{where}";
}
else
{
// check if we have alias
if (fromClause is FromClause && !string.IsNullOrEmpty(fromClause.Alias))
{
ctx.RawSql = $"DELETE {Wrap(fromClause.Alias)} FROM {table} {joins}{where}";
}
else
{
ctx.RawSql = $"DELETE {table} FROM {table} {joins}{where}";
}

}

return ctx;
}
Expand Down