Add DropTable

This commit is contained in:
Jinzhu 2013-11-01 15:01:39 +08:00
parent 600d8e7277
commit 49cfb0d4a0
5 changed files with 29 additions and 6 deletions

View File

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

View File

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

8
do.go
View File

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

View File

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

View File

@ -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)
}