support implicit table alias, close #5840 #5940

This commit is contained in:
Jinzhu 2023-01-02 21:46:27 +08:00
parent 3d91802b1d
commit 2bc913787b
3 changed files with 13 additions and 5 deletions

View File

@ -55,7 +55,7 @@ func (db *DB) Clauses(conds ...clause.Expression) (tx *DB) {
return
}
var tableRegexp = regexp.MustCompile(`(?i).+? AS (\w+)\s*(?:$|,)`)
var tableRegexp = regexp.MustCompile(`(?i)(?:.+? AS (\w+)\s*(?:$|,)|^\w+\s+(\w+)$)`)
// Table specify the table you would like to run db operations
//
@ -65,8 +65,12 @@ func (db *DB) Table(name string, args ...interface{}) (tx *DB) {
tx = db.getInstance()
if strings.Contains(name, " ") || strings.Contains(name, "`") || len(args) > 0 {
tx.Statement.TableExpr = &clause.Expr{SQL: name, Vars: args}
if results := tableRegexp.FindStringSubmatch(name); len(results) == 2 {
tx.Statement.Table = results[1]
if results := tableRegexp.FindStringSubmatch(name); len(results) == 3 {
if results[1] != "" {
tx.Statement.Table = results[1]
} else {
tx.Statement.Table = results[2]
}
}
} else if tables := strings.Split(name, "."); len(tables) == 2 {
tx.Statement.TableExpr = &clause.Expr{SQL: tx.Statement.Quote(name)}

View File

@ -3,13 +3,12 @@ module gorm.io/gorm/tests
go 1.16
require (
github.com/go-sql-driver/mysql v1.7.0 // indirect
github.com/google/uuid v1.3.0
github.com/jinzhu/now v1.1.5
github.com/lib/pq v1.10.7
github.com/mattn/go-sqlite3 v1.14.16 // indirect
github.com/microsoft/go-mssqldb v0.19.0 // indirect
gorm.io/driver/mysql v1.4.4
gorm.io/driver/mysql v1.4.5
gorm.io/driver/postgres v1.4.6
gorm.io/driver/sqlite v1.4.4
gorm.io/driver/sqlserver v1.4.1

View File

@ -39,6 +39,11 @@ func TestSoftDelete(t *testing.T) {
t.Fatalf("invalid sql generated, got %v", sql)
}
sql = DB.Session(&gorm.Session{DryRun: true}).Table("user u").Select("name").Find(&User{}).Statement.SQL.String()
if !regexp.MustCompile(`SELECT .name. FROM user u WHERE .u.\..deleted_at. IS NULL`).MatchString(sql) {
t.Errorf("Table with escape character, got %v", sql)
}
if DB.First(&User{}, "name = ?", user.Name).Error == nil {
t.Errorf("Can't find a soft deleted record")
}