Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixed delete + where in issue on mysql (#699) #784

Merged
merged 1 commit into from Sep 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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, " ")
sio4 marked this conversation as resolved.
Show resolved Hide resolved

_, 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