Skip to content

Commit b394802

Browse files
Merge pull request #614 from sqlkata/iss-182_delete_join_support
Issue 182 - delete with join support
2 parents 5d369af + 2cd0125 commit b394802

File tree

2 files changed

+68
-1
lines changed

2 files changed

+68
-1
lines changed

QueryBuilder.Tests/DeleteTests.cs

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
using SqlKata.Compilers;
2+
using SqlKata.Extensions;
3+
using SqlKata.Tests.Infrastructure;
4+
using System;
5+
using System.Linq;
6+
using Xunit;
7+
8+
namespace SqlKata.Tests
9+
{
10+
public class DeleteTests : TestSupport
11+
{
12+
[Fact]
13+
public void BasicDelete()
14+
{
15+
var q = new Query("Posts").AsDelete();
16+
17+
var c = Compile(q);
18+
19+
Assert.Equal("DELETE FROM [Posts]", c[EngineCodes.SqlServer]);
20+
}
21+
22+
[Fact]
23+
public void DeleteWithJoin()
24+
{
25+
var q = new Query("Posts")
26+
.Join("Authors", "Authors.Id", "Posts.AuthorId")
27+
.Where("Authors.Id", 5)
28+
.AsDelete();
29+
30+
var c = Compile(q);
31+
32+
Assert.Equal("DELETE [Posts] FROM [Posts] \nINNER JOIN [Authors] ON [Authors].[Id] = [Posts].[AuthorId] WHERE [Authors].[Id] = 5", c[EngineCodes.SqlServer]);
33+
Assert.Equal("DELETE `Posts` FROM `Posts` \nINNER JOIN `Authors` ON `Authors`.`Id` = `Posts`.`AuthorId` WHERE `Authors`.`Id` = 5", c[EngineCodes.MySql]);
34+
}
35+
36+
[Fact]
37+
public void DeleteWithJoinAndAlias()
38+
{
39+
var q = new Query("Posts as P")
40+
.Join("Authors", "Authors.Id", "P.AuthorId")
41+
.Where("Authors.Id", 5)
42+
.AsDelete();
43+
44+
var c = Compile(q);
45+
46+
Assert.Equal("DELETE [P] FROM [Posts] AS [P] \nINNER JOIN [Authors] ON [Authors].[Id] = [P].[AuthorId] WHERE [Authors].[Id] = 5", c[EngineCodes.SqlServer]);
47+
}
48+
}
49+
}

QueryBuilder/Compilers/Compiler.cs

+19-1
Original file line numberDiff line numberDiff line change
@@ -263,14 +263,32 @@ protected virtual SqlResult CompileDeleteQuery(Query query)
263263
throw new InvalidOperationException("Invalid table expression");
264264
}
265265

266+
var joins = CompileJoins(ctx);
267+
266268
var where = CompileWheres(ctx);
267269

268270
if (!string.IsNullOrEmpty(where))
269271
{
270272
where = " " + where;
271273
}
272274

273-
ctx.RawSql = $"DELETE FROM {table}{where}";
275+
if (string.IsNullOrEmpty(joins))
276+
{
277+
ctx.RawSql = $"DELETE FROM {table}{where}";
278+
}
279+
else
280+
{
281+
// check if we have alias
282+
if (fromClause is FromClause && !string.IsNullOrEmpty(fromClause.Alias))
283+
{
284+
ctx.RawSql = $"DELETE {Wrap(fromClause.Alias)} FROM {table} {joins}{where}";
285+
}
286+
else
287+
{
288+
ctx.RawSql = $"DELETE {table} FROM {table} {joins}{where}";
289+
}
290+
291+
}
274292

275293
return ctx;
276294
}

0 commit comments

Comments
 (0)