diff --git a/chainable_api.go b/chainable_api.go index 8a92a9e3..676fe914 100644 --- a/chainable_api.go +++ b/chainable_api.go @@ -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)} diff --git a/tests/go.mod b/tests/go.mod index efa597a2..2ba97179 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -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 diff --git a/tests/soft_delete_test.go b/tests/soft_delete_test.go index 9ac8da10..1f9a4786 100644 --- a/tests/soft_delete_test.go +++ b/tests/soft_delete_test.go @@ -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") }