From 3df249c127e637f8af6c99e5e4fed9c466803d79 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 6 Aug 2020 16:25:26 +0800 Subject: [PATCH] Use table expr when inserting table, close #3239 --- callbacks/create.go | 8 ++------ tests/go.mod | 4 ++-- tests/table_test.go | 11 +++++++++++ 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/callbacks/create.go b/callbacks/create.go index b41a3ef2..3a414dd7 100644 --- a/callbacks/create.go +++ b/callbacks/create.go @@ -43,9 +43,7 @@ func Create(config *Config) func(db *gorm.DB) { if db.Statement.SQL.String() == "" { db.Statement.SQL.Grow(180) - db.Statement.AddClauseIfNotExists(clause.Insert{ - Table: clause.Table{Name: db.Statement.Table}, - }) + db.Statement.AddClauseIfNotExists(clause.Insert{}) db.Statement.AddClause(ConvertToCreateValues(db.Statement)) db.Statement.Build("INSERT", "VALUES", "ON CONFLICT") @@ -105,9 +103,7 @@ func CreateWithReturning(db *gorm.DB) { } if db.Statement.SQL.String() == "" { - db.Statement.AddClauseIfNotExists(clause.Insert{ - Table: clause.Table{Name: db.Statement.Table}, - }) + db.Statement.AddClauseIfNotExists(clause.Insert{}) db.Statement.AddClause(ConvertToCreateValues(db.Statement)) db.Statement.Build("INSERT", "VALUES", "ON CONFLICT") diff --git a/tests/go.mod b/tests/go.mod index 6eb6eb07..82d4fdc8 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -8,8 +8,8 @@ require ( github.com/lib/pq v1.6.0 gorm.io/driver/mysql v0.3.1 gorm.io/driver/postgres v0.2.6 - gorm.io/driver/sqlite v1.0.8 - gorm.io/driver/sqlserver v0.2.5 + gorm.io/driver/sqlite v1.0.9 + gorm.io/driver/sqlserver v0.2.6 gorm.io/gorm v0.2.19 ) diff --git a/tests/table_test.go b/tests/table_test.go index faee6499..647b5e19 100644 --- a/tests/table_test.go +++ b/tests/table_test.go @@ -40,6 +40,17 @@ func TestTable(t *testing.T) { t.Errorf("Table with escape character, got %v", r.Statement.SQL.String()) } + r = dryDB.Create(&UserWithTable{}).Statement + if DB.Dialector.Name() != "sqlite" { + if !regexp.MustCompile(`INSERT INTO .gorm.\..user. (.*name.*) VALUES (.*)`).MatchString(r.Statement.SQL.String()) { + t.Errorf("Table with escape character, got %v", r.Statement.SQL.String()) + } + } else { + if !regexp.MustCompile(`INSERT INTO .user. (.*name.*) VALUES (.*)`).MatchString(r.Statement.SQL.String()) { + t.Errorf("Table with escape character, got %v", r.Statement.SQL.String()) + } + } + r = dryDB.Table("(?) as u", DB.Model(&User{}).Select("name")).Find(&User{}).Statement if !regexp.MustCompile("SELECT \\* FROM \\(SELECT .name. FROM .users. WHERE .users.\\..deleted_at. IS NULL\\) 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())