Merge pull request #209 from rbg/master

Add HasTable()
This commit is contained in:
Jinzhu 2014-08-29 13:57:20 +08:00
commit 80b563e312
2 changed files with 24 additions and 1 deletions

View File

@ -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 {

View File

@ -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" {