From 94aa843830eb014e388aa8e713385445022cbf73 Mon Sep 17 00:00:00 2001 From: Robert B Gordon Date: Fri, 29 Aug 2014 00:28:54 -0500 Subject: [PATCH 1/2] Add HasTable() --- main.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/main.go b/main.go index 973c1b44..3ab03aaf 100644 --- a/main.go +++ b/main.go @@ -346,6 +346,12 @@ func (s *DB) DropTableIfExists(value interface{}) *DB { return s.clone().NewScope(value).dropTableIfExists().db } +func (s *DB) HasTable(value interface{}) bool { + scope := s.clone().NewScope(value) + tableName := scope.TableName() + return scope.Dialect().HasTable(scope, tableName) +} + func (s *DB) AutoMigrate(values ...interface{}) *DB { db := s.clone() for _, value := range values { From 4ee47c922808d0926afbd1502c780b599a3f6efe Mon Sep 17 00:00:00 2001 From: Robert B Gordon Date: Fri, 29 Aug 2014 00:51:45 -0500 Subject: [PATCH 2/2] add test for HasTable() --- main_test.go | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/main_test.go b/main_test.go index e0b39e9f..0555ef67 100644 --- a/main_test.go +++ b/main_test.go @@ -4,13 +4,14 @@ import ( "database/sql" "database/sql/driver" "fmt" + "strconv" + testdb "github.com/erikstmartin/go-testdb" _ "github.com/go-sql-driver/mysql" "github.com/jinzhu/gorm" "github.com/jinzhu/now" _ "github.com/lib/pq" _ "github.com/mattn/go-sqlite3" - "strconv" "os" "testing" @@ -127,6 +128,22 @@ func (c Cart) TableName() string { return "shopping_cart" } +func TestHasTable(t *testing.T) { + type Foo struct { + Id int + Stuff string + } + if table_ok := db.HasTable(&Foo{}); table_ok { + t.Errorf("Table should not exist, but does") + } + if err := db.CreateTable(&Foo{}).Error; err != nil { + t.Errorf("Table should be created") + } + if table_ok := db.HasTable(&Foo{}); !table_ok { + t.Errorf("Table should exist, but HasTable informs it does not") + } +} + func TestTableName(t *testing.T) { db := db.Model("") if db.NewScope(Order{}).TableName() != "orders" {