Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create and drop view #6097

Merged
merged 4 commits into from
Feb 27, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions migrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ func (db *DB) AutoMigrate(dst ...interface{}) error {

// ViewOption view option
type ViewOption struct {
Replace bool
CheckOption string
Replace bool // CREATE [ OR REPLACE ]
CheckOption string // WITH [ CASCADED | LOCAL ] CHECK OPTION
Query *DB
}

Expand Down
19 changes: 17 additions & 2 deletions migrator/migrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -559,12 +559,27 @@ func (m Migrator) ColumnTypes(value interface{}) ([]gorm.ColumnType, error) {

// CreateView create view
func (m Migrator) CreateView(name string, option gorm.ViewOption) error {
return gorm.ErrNotImplemented
sql := new(strings.Builder)
sql.WriteString("CREATE ")
if option.Replace {
sql.WriteString("OR REPLACE ")
}
sql.WriteString("VIEW ")
m.QuoteTo(sql, name)
sql.WriteString(" AS ")

m.DB.Statement.AddVar(sql, option.Query)

if option.CheckOption != "" {
sql.WriteString(" ")
sql.WriteString(option.CheckOption)
}
return m.DB.Exec(sql.String()).Error
}

// DropView drop view
func (m Migrator) DropView(name string) error {
return gorm.ErrNotImplemented
return m.DB.Exec("DROP VIEW IF EXISTS ?", clause.Table{Name: name}).Error
}

func buildConstraint(constraint *schema.Constraint) (sql string, results []interface{}) {
Expand Down
21 changes: 21 additions & 0 deletions tests/migrate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1509,3 +1509,24 @@ func TestMigrateIgnoreRelations(t *testing.T) {
t.Errorf("RelationModel2 should not be migrated")
}
}

func TestMigrateView(t *testing.T) {
DB.Save(GetUser("joins-args-db", Config{Pets: 2}))

query := DB.Model(&User{}).
Select("users.id as users_id, users.name as users_name, pets.id as pets_id, pets.name as pets_name").
Joins("inner join pets on pets.user_id = users.id")

if err := DB.Migrator().CreateView("users_pets", gorm.ViewOption{Query: query}); err != nil {
t.Fatalf("Failed to crate view, got %v", err)
}

var count int64
if err := DB.Table("users_pets").Count(&count).Error; err != nil {
t.Fatalf("should found created view")
}

if err := DB.Migrator().DropView("users_pets"); err != nil {
t.Fatalf("Failed to drop view, got %v", err)
}
}