diff --git a/delete.go b/delete.go index f3f31e6..403f543 100644 --- a/delete.go +++ b/delete.go @@ -19,6 +19,7 @@ type deleteData struct { Limit string Offset string Suffixes []Sqlizer + Joins []Sqlizer } func (d *deleteData) Exec() (sql.Result, error) { @@ -48,6 +49,14 @@ func (d *deleteData) ToSql() (sqlStr string, args []interface{}, err error) { sql.WriteString("DELETE FROM ") sql.WriteString(d.From) + if len(d.Joins) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Joins, sql, " ", args) + if err != nil { + return + } + } + if len(d.WhereParts) > 0 { sql.WriteString(" WHERE ") args, err = appendToSql(d.WhereParts, sql, " AND ", args) @@ -189,3 +198,33 @@ func (d *deleteData) Query() (*sql.Rows, error) { } return QueryWith(d.RunWith, d) } + +// JoinClause adds a join clause to the query. +func (b DeleteBuilder) JoinClause(pred interface{}, args ...interface{}) DeleteBuilder { + return builder.Append(b, "Joins", newPart(pred, args...)).(DeleteBuilder) +} + +// Join adds a JOIN clause to the query. +func (b DeleteBuilder) Join(join string, rest ...interface{}) DeleteBuilder { + return b.JoinClause("JOIN "+join, rest...) +} + +// LeftJoin adds a LEFT JOIN clause to the query. +func (b DeleteBuilder) LeftJoin(join string, rest ...interface{}) DeleteBuilder { + return b.JoinClause("LEFT JOIN "+join, rest...) +} + +// RightJoin adds a RIGHT JOIN clause to the query. +func (b DeleteBuilder) RightJoin(join string, rest ...interface{}) DeleteBuilder { + return b.JoinClause("RIGHT JOIN "+join, rest...) +} + +// InnerJoin adds a INNER JOIN clause to the query. +func (b DeleteBuilder) InnerJoin(join string, rest ...interface{}) DeleteBuilder { + return b.JoinClause("INNER JOIN "+join, rest...) +} + +// CrossJoin adds a CROSS JOIN clause to the query. +func (b DeleteBuilder) CrossJoin(join string, rest ...interface{}) DeleteBuilder { + return b.JoinClause("CROSS JOIN "+join, rest...) +} diff --git a/delete_test.go b/delete_test.go index 62691f2..7cd862d 100644 --- a/delete_test.go +++ b/delete_test.go @@ -10,6 +10,12 @@ func TestDeleteBuilderToSql(t *testing.T) { b := Delete(""). Prefix("WITH prefix AS ?", 0). From("a"). + JoinClause("CROSS JOIN j1"). + Join("j2"). + LeftJoin("j3"). + RightJoin("j4"). + InnerJoin("j5"). + CrossJoin("j6"). Where("b = ?", 1). OrderBy("c"). Limit(2). @@ -21,7 +27,9 @@ func TestDeleteBuilderToSql(t *testing.T) { expectedSql := "WITH prefix AS ? " + - "DELETE FROM a WHERE b = ? ORDER BY c LIMIT 2 OFFSET 3 " + + "DELETE FROM a " + + "CROSS JOIN j1 JOIN j2 LEFT JOIN j3 RIGHT JOIN j4 INNER JOIN j5 CROSS JOIN j6 " + + "WHERE b = ? ORDER BY c LIMIT 2 OFFSET 3 " + "RETURNING ?" assert.Equal(t, expectedSql, sql)