diff --git a/QueryBuilder.Tests/DeleteTests.cs b/QueryBuilder.Tests/DeleteTests.cs new file mode 100644 index 00000000..14fd4043 --- /dev/null +++ b/QueryBuilder.Tests/DeleteTests.cs @@ -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]); + } + } +} diff --git a/QueryBuilder/Compilers/Compiler.cs b/QueryBuilder/Compilers/Compiler.cs index 181d5281..ff8206a1 100644 --- a/QueryBuilder/Compilers/Compiler.cs +++ b/QueryBuilder/Compilers/Compiler.cs @@ -263,6 +263,8 @@ protected virtual SqlResult CompileDeleteQuery(Query query) throw new InvalidOperationException("Invalid table expression"); } + var joins = CompileJoins(ctx); + var where = CompileWheres(ctx); if (!string.IsNullOrEmpty(where)) @@ -270,7 +272,23 @@ protected virtual SqlResult CompileDeleteQuery(Query query) 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; }