From 49cfb0d4a0549541a8207924b57b3f2df7615b70 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Fri, 1 Nov 2013 15:01:39 +0800 Subject: [PATCH] Add DropTable --- README.md | 3 +++ chain.go | 5 +++++ do.go | 8 ++++++++ gorm_test.go | 15 +++++++++------ main.go | 4 ++++ 5 files changed, 29 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 4251da6c..28b8d08b 100644 --- a/README.md +++ b/README.md @@ -248,6 +248,9 @@ db.Where("name <> ?", "jinzhu").Where("age >= ? and role <> ?", 20, "admin").Fin // Create Table with struct db.CreateTable(&User{}) +// Drop Table +db.DropTable(&User{}) + // Specify Table Name db.Table("deleted_users").CreateTable(&User{}) db.Table("users").Pluck("age", &ages) diff --git a/chain.go b/chain.go index 7354154d..762fc7f3 100644 --- a/chain.go +++ b/chain.go @@ -236,6 +236,11 @@ func (s *Chain) CreateTable(value interface{}) *Chain { return s } +func (s *Chain) DropTable(value interface{}) *Chain { + s.do(value).dropTable().exec() + return s +} + func (s *Chain) Unscoped() *Chain { s.unscoped = true return s diff --git a/do.go b/do.go index fb3969c6..51beb230 100644 --- a/do.go +++ b/do.go @@ -577,6 +577,14 @@ func (s *Do) createTable() *Do { return s } +func (s *Do) dropTable() *Do { + s.sql = fmt.Sprintf( + "DROP TABLE \"%v\"", + s.tableName(), + ) + return s +} + func (s *Do) initializeWithSearchCondition() { m := Model{data: s.value, driver: s.driver} diff --git a/gorm_test.go b/gorm_test.go index 7bd12e21..5aa6e304 100644 --- a/gorm_test.go +++ b/gorm_test.go @@ -50,18 +50,21 @@ func init() { db.SetPool(10) // db.DebugMode = true - err = db.Exec("drop table users;").Error + err = db.DropTable(&User{}).Error if err != nil { fmt.Printf("Got error when try to delete table users, %+v\n", err) } - db.Exec("drop table products;") + db.Exec("drop table products") - orm := db.CreateTable(&User{}) - if orm.Error != nil { - panic(fmt.Sprintf("No error should happen when create table, but got %+v", orm.Error)) + err = db.CreateTable(&User{}).Error + if err != nil { + panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) } - db.CreateTable(&Product{}) + err = db.CreateTable(&Product{}).Error + if err != nil { + panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) + } var shortForm = "2006-01-02 15:04:05" t1, _ = time.Parse(shortForm, "2000-10-27 12:02:40") diff --git a/main.go b/main.go index 9d093287..84aef79b 100644 --- a/main.go +++ b/main.go @@ -101,3 +101,7 @@ func (s *DB) Debug() *Chain { func (s *DB) CreateTable(value interface{}) *Chain { return s.buildChain().CreateTable(value) } + +func (s *DB) DropTable(value interface{}) *Chain { + return s.buildChain().DropTable(value) +}