Skip to content

Commit

Permalink
Add support for USING clauses in DELETE statements
Browse files Browse the repository at this point in the history
This commit adds the ability to join in DELETE statements with the USING
clause.

Sample code:

    _, err = z.
        DeleteFrom("one").
        Using("two", "three").
        Where(
            sqlz.Eq("two.fk_id", sqlz.Indirect("one.id")),
            sqlz.Eq("three.fk_id", sqlz.Indirect("one.id")),
        ).
        Exec()
  • Loading branch information
Ido Perlmuter committed Jan 30, 2018
1 parent 02b2c99 commit 5e03778
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
19 changes: 15 additions & 4 deletions delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@ import (

// DeleteStmt represents a DELETE statement
type DeleteStmt struct {
Table string
Conditions []WhereCondition
Return []string
execer sqlx.Ext
Table string
Conditions []WhereCondition
UsingTables []string
Return []string
execer sqlx.Ext
}

// DeleteFrom creates a new DeleteStmt object for the
Expand All @@ -33,6 +34,12 @@ func (tx *Tx) DeleteFrom(table string) *DeleteStmt {
}
}

// Using adds a USING clause for joining in a delete statement
func (stmt *DeleteStmt) Using(tables ...string) *DeleteStmt {
stmt.UsingTables = append(stmt.UsingTables, tables...)
return stmt
}

// Where creates one or more WHERE conditions for the DELETE statement.
// If multiple conditions are passed, they are considered AND conditions.
func (stmt *DeleteStmt) Where(conds ...WhereCondition) *DeleteStmt {
Expand All @@ -55,6 +62,10 @@ func (stmt *DeleteStmt) Returning(cols ...string) *DeleteStmt {
func (stmt *DeleteStmt) ToSQL(rebind bool) (asSQL string, bindings []interface{}) {
var clauses = []string{"DELETE FROM " + stmt.Table}

if len(stmt.UsingTables) > 0 {
clauses = append(clauses, "USING "+strings.Join(stmt.UsingTables, ", "))
}

if len(stmt.Conditions) > 0 {
whereClause, whereBindings := parseConditions(stmt.Conditions)
bindings = append(bindings, whereBindings...)
Expand Down
11 changes: 10 additions & 1 deletion delete_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package sqlz

import "testing"
import (
"testing"
)

func TestDelete(t *testing.T) {
runTests(t, func(dbz *DB) []test {
Expand All @@ -25,6 +27,13 @@ func TestDelete(t *testing.T) {
"DELETE FROM table WHERE id = ? RETURNING name",
[]interface{}{2},
},

test{
"delete using join",
dbz.DeleteFrom("table").Using("other", "another").Where(Eq("other.fk_id", Indirect("table.id")), Eq("another.fk_id", Indirect("table.id"))),
"DELETE FROM table USING other, another WHERE other.fk_id = table.id AND another.fk_id = table.id",
[]interface{}{},
},
}
})
}

0 comments on commit 5e03778

Please sign in to comment.