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

[Fix] join_table_handler break insert select into two queries to avoid deadlock #11

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 18 additions & 10 deletions join_table_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,22 +122,30 @@ func (s JoinTableHandler) Add(handler JoinTableHandlerInterface, db *DB, source
values = append(values, value)
}

for _, value := range values {
values = append(values, value)
}

quotedTable := scope.Quote(handler.Table(db))
sql := fmt.Sprintf(
"INSERT INTO %v (%v) SELECT %v %v WHERE NOT EXISTS (SELECT * FROM %v WHERE %v)",
"INSERT INTO %v (%v) VALUES(%v)",
quotedTable,
strings.Join(assignColumns, ","),
strings.Join(binVars, ","),
scope.Dialect().SelectFromDummyTable(),
quotedTable,
strings.Join(conditions, " AND "),
)

return db.Exec(sql, values...).Error
checkSql := fmt.Sprintf("SELECT COUNT(1) FROM %v WHERE %v FOR UPDATE", quotedTable, strings.Join(conditions, " AND "))
if db.Dialect().GetName() == "sqlite3" {
// sqlite does not support SELECT FOR UPDATE. But it is single thread concurrency, safe here.
checkSql = fmt.Sprintf("SELECT COUNT(1) FROM %v WHERE %v", quotedTable, strings.Join(conditions, " AND "))
}
checkCount := 0
rows, err := db.db.Query(checkSql, values...)
if err != nil {
return err
}
rows.Next()
rows.Scan(&checkCount)
rows.Close()
if checkCount == 0 {
return db.Exec(sql, values...).Error
}
return nil
}

// Delete delete relationship in join table for sources
Expand Down