Skip to content

Commit

Permalink
fixed delete + where in issue on mysql (#699)
Browse files Browse the repository at this point in the history
  • Loading branch information
sio4 committed Sep 24, 2022
1 parent 9a26827 commit 902a7d1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
21 changes: 11 additions & 10 deletions dialect_mysql.go
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"io"
"os/exec"
"regexp"
"strings"

_mysql "github.com/go-sql-driver/mysql" // Load MySQL Go driver
Expand Down Expand Up @@ -112,17 +113,17 @@ func (m *mysql) Destroy(s store, model *Model) error {
return nil
}

func (m *mysql) Delete(s store, model *Model, query Query) error {
sb := query.toSQLBuilder(model)

sql := fmt.Sprintf("DELETE FROM %s", m.Quote(model.TableName()))
sql = sb.buildWhereClauses(sql)
var asRegex = regexp.MustCompile(`\sAS\s\S+`) // exactly " AS non-spaces"

_, err := genericExec(s, sql, sb.Args()...)
if err != nil {
return fmt.Errorf("mysql delete: %w", err)
}
return nil
func (m *mysql) Delete(s store, model *Model, query Query) error {
sqlQuery, args := query.ToSQL(model)
// * MySQL does not support table alias for DELETE syntax until 8.0.
// * Do not generate SQL manually if they may have `WHERE IN`.
// * Spaces are intentionally added to make it easy to see on the log.
sqlQuery = asRegex.ReplaceAllString(sqlQuery, " ")

_, err := genericExec(s, sqlQuery, args...)
return err
}

func (m *mysql) SelectOne(s store, model *Model, query Query) error {
Expand Down
11 changes: 11 additions & 0 deletions query_test.go
Expand Up @@ -74,10 +74,21 @@ func Test_Where_In_Slice(t *testing.T) {
r.NoError(tx.Create(u2))
r.NoError(tx.Create(u3))

Debug = true
defer func() { Debug = false }()

var songs []Song
err := tx.Where("id in (?)", []uuid.UUID{u1.ID, u3.ID}).Where("title = ?", "A").All(&songs)
r.NoError(err)
r.Len(songs, 2)

// especially https://github.com/gobuffalo/pop/issues/699
err = tx.Where("id in (?)", []uuid.UUID{u1.ID, u3.ID}).Delete(&Song{})
r.NoError(err)

var remainingSongs []Song
r.NoError(tx.All(&remainingSongs))
r.Len(remainingSongs, 1)
})
}

Expand Down

0 comments on commit 902a7d1

Please sign in to comment.