Skip to content

Commit

Permalink
support implicit table alias, close #5840 #5940
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Jan 2, 2023
1 parent 3d91802 commit 2bc9137
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 5 deletions.
10 changes: 7 additions & 3 deletions chainable_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
//
Expand All @@ -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)}
Expand Down
3 changes: 1 addition & 2 deletions tests/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions tests/soft_delete_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand Down

0 comments on commit 2bc9137

Please sign in to comment.