fix: table couln't be reentrant

This commit is contained in:
tick 2021-07-22 18:28:54 +08:00
parent 2202e99cbf
commit 18017a09c7
2 changed files with 23 additions and 4 deletions

View File

@ -50,15 +50,14 @@ func (db *DB) Table(name string, args ...interface{}) (tx *DB) {
tx.Statement.TableExpr = &clause.Expr{SQL: name, Vars: args}
if results := tableRegexp.FindStringSubmatch(name); len(results) == 2 {
tx.Statement.Table = results[1]
return
}
} else if tables := strings.Split(name, "."); len(tables) == 2 {
tx.Statement.TableExpr = &clause.Expr{SQL: tx.Statement.Quote(name)}
tx.Statement.Table = tables[1]
return
} else {
tx.Statement.TableExpr = &clause.Expr{SQL: tx.Statement.Quote(name)}
tx.Statement.Table = name
}
tx.Statement.Table = name
return
}

View File

@ -30,6 +30,26 @@ func TestTable(t *testing.T) {
t.Errorf("Table with escape character, got %v", r.Statement.SQL.String())
}
r = dryDB.Table("`people`").Table("`user`").Find(&User{}).Statement
if !regexp.MustCompile("SELECT \\* FROM `user`").MatchString(r.Statement.SQL.String()) {
t.Errorf("Table with escape character, got %v", r.Statement.SQL.String())
}
r = dryDB.Table("people as p").Table("user as u").Find(&User{}).Statement
if !regexp.MustCompile("SELECT \\* FROM user as u WHERE .u.\\..deleted_at. IS NULL").MatchString(r.Statement.SQL.String()) {
t.Errorf("Table with escape character, got %v", r.Statement.SQL.String())
}
r = dryDB.Table("people as p").Table("user").Find(&User{}).Statement
if !regexp.MustCompile("SELECT \\* FROM .user. WHERE .user.\\..deleted_at. IS NULL").MatchString(r.Statement.SQL.String()) {
t.Errorf("Table with escape character, got %v", r.Statement.SQL.String())
}
r = dryDB.Table("gorm.people").Table("user").Find(&User{}).Statement
if !regexp.MustCompile("SELECT \\* FROM .user. WHERE .user.\\..deleted_at. IS NULL").MatchString(r.Statement.SQL.String()) {
t.Errorf("Table with escape character, got %v", r.Statement.SQL.String())
}
r = dryDB.Table("gorm.user").Select("name").Find(&User{}).Statement
if !regexp.MustCompile("SELECT .name. FROM .gorm.\\..user. WHERE .user.\\..deleted_at. IS NULL").MatchString(r.Statement.SQL.String()) {
t.Errorf("Table with escape character, got %v", r.Statement.SQL.String())