Add methods do add and drop check constraints

Ref #1020
This commit is contained in:
Andrey Nering 2017-04-27 20:40:31 -03:00
parent 717654b31c
commit 386bc9925c
2 changed files with 35 additions and 0 deletions

16
main.go
View File

@ -602,6 +602,22 @@ func (s *DB) AddForeignKey(field string, dest string, onDelete string, onUpdate
return scope.db
}
// AddCheckConstraint Add check to the given scope, e.g:
// db.Model(&User{}).AddCheckConstraint("users_login_count_chk", "login_count >= 0")
func (s *DB) AddCheckConstraint(constraintName, check string) *DB {
scope := s.clone().NewScope(s.Value)
scope.addCheckConstraint(constraintName, check)
return scope.db
}
// DropCheckConstraint Drop check constraint, e.g:
// db.Model(&User{}).DropCheckConstraint("users_login_count_chk")
func (s *DB) DropCheckConstraint(constraintName string) *DB {
scope := s.clone().NewScope(s.Value)
scope.dropCheckConstraint(constraintName)
return scope.db
}
// Association start `Association Mode` to handler relations things easir in that mode, refer: https://jinzhu.github.io/gorm/associations.html#association-mode
func (s *DB) Association(column string) *Association {
var err error

View File

@ -1164,6 +1164,25 @@ func (scope *Scope) addForeignKey(field string, dest string, onDelete string, on
scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.quoteIfPossible(keyName), scope.quoteIfPossible(field), dest, onDelete, onUpdate)).Exec()
}
func (scope *Scope) addCheckConstraint(constraintName, check string) {
q := fmt.Sprintf(
"ALTER TABLE %s ADD CONSTRAINT %s CHECK (%s)",
scope.QuotedTableName(),
scope.quoteIfPossible(constraintName),
check,
)
scope.Raw(q).Exec()
}
func (scope *Scope) dropCheckConstraint(constraintName string) {
q := fmt.Sprintf(
"ALTER TABLE %s DROP CONSTRAINT %s",
scope.QuotedTableName(),
scope.quoteIfPossible(constraintName),
)
scope.Raw(q).Exec()
}
func (scope *Scope) removeIndex(indexName string) {
scope.Dialect().RemoveIndex(scope.TableName(), indexName)
}