Skip to content

Commit

Permalink
Merge pull request #614 from sqlkata/iss-182_delete_join_support
Browse files Browse the repository at this point in the history
Issue 182 - delete with join support
  • Loading branch information
ahmad-moussawi authored Sep 27, 2022
2 parents 5d369af + 2cd0125 commit b394802
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 1 deletion.
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

0 comments on commit b394802

Please sign in to comment.