Fix select with association column

This commit is contained in:
Jinzhu 2022-07-13 18:02:11 +08:00
parent a7063848ef
commit cae30e9a50
2 changed files with 17 additions and 17 deletions

View File

@ -650,7 +650,7 @@ func (stmt *Statement) Changed(fields ...string) bool {
return false
}
var nameMatcher = regexp.MustCompile(`^(?:[\W]?(?:[A-Za-z_0-9]+?)[\W]?\.)?[\W]?([A-Za-z_0-9]+?)[\W]?$`)
var nameMatcher = regexp.MustCompile(`^(?:[\W]?([A-Za-z_0-9]+?)[\W]?\.)?[\W]?([A-Za-z_0-9]+?)[\W]?$`)
// SelectAndOmitColumns get select and omit columns, select -> true, omit -> false
func (stmt *Statement) SelectAndOmitColumns(requireCreate, requireUpdate bool) (map[string]bool, bool) {
@ -672,8 +672,8 @@ func (stmt *Statement) SelectAndOmitColumns(requireCreate, requireUpdate bool) (
}
} else if field := stmt.Schema.LookUpField(column); field != nil && field.DBName != "" {
results[field.DBName] = true
} else if matches := nameMatcher.FindStringSubmatch(column); len(matches) == 2 {
results[matches[1]] = true
} else if matches := nameMatcher.FindStringSubmatch(column); len(matches) == 3 && matches[1] == stmt.Table {
results[matches[2]] = true
} else {
results[column] = true
}

View File

@ -36,21 +36,21 @@ func TestWhereCloneCorruption(t *testing.T) {
}
func TestNameMatcher(t *testing.T) {
for k, v := range map[string]string{
"table.name": "name",
"`table`.`name`": "name",
"'table'.'name'": "name",
"'table'.name": "name",
"table1.name_23": "name_23",
"`table_1`.`name23`": "name23",
"'table23'.'name_1'": "name_1",
"'table23'.name1": "name1",
"'name1'": "name1",
"`name_1`": "name_1",
"`Name_1`": "Name_1",
"`Table`.`nAme`": "nAme",
for k, v := range map[string][]string{
"table.name": []string{"table", "name"},
"`table`.`name`": []string{"table", "name"},
"'table'.'name'": []string{"table", "name"},
"'table'.name": []string{"table", "name"},
"table1.name_23": []string{"table1", "name_23"},
"`table_1`.`name23`": []string{"table_1", "name23"},
"'table23'.'name_1'": []string{"table23", "name_1"},
"'table23'.name1": []string{"table23", "name1"},
"'name1'": []string{"", "name1"},
"`name_1`": []string{"", "name_1"},
"`Name_1`": []string{"", "Name_1"},
"`Table`.`nAme`": []string{"Table", "nAme"},
} {
if matches := nameMatcher.FindStringSubmatch(k); len(matches) < 2 || matches[1] != v {
if matches := nameMatcher.FindStringSubmatch(k); len(matches) < 3 || matches[1] != v[0] || matches[2] != v[1] {
t.Errorf("failed to match value: %v, got %v, expect: %v", k, matches, v)
}
}