Implement conditional generation of foreign keys.

For now, support is restricted to MySQL and PostgreSQL, while all other
DBMS default to the old behavior.

Signed-off-by: Stephan Peijnik <speijnik@anexia-it.com>
This commit is contained in:
Stephan Peijnik 2016-02-03 12:19:55 +01:00
parent c7b9acefb7
commit e5ca672742
4 changed files with 22 additions and 0 deletions

View File

@ -95,6 +95,13 @@ func (c commonDialect) HasIndex(scope *Scope, tableName string, indexName string
return count > 0
}
func (c commonDialect) HasForeignKey(scope *Scope, tableName string, fkName string) bool {
// Checking if a foreign key constraint exists is DBMS specific. In order to preserve
// the previous logic of AddForeignKey, we are always returning false for dialects which do
// not implement this check.
return false
}
func (commonDialect) RemoveIndex(scope *Scope, indexName string) {
scope.Err(scope.NewDB().Exec(fmt.Sprintf("DROP INDEX %v ON %v", indexName, scope.QuotedTableName())).Error)
}

View File

@ -16,6 +16,7 @@ type Dialect interface {
HasTable(scope *Scope, tableName string) bool
HasColumn(scope *Scope, tableName string, columnName string) bool
HasIndex(scope *Scope, tableName string, indexName string) bool
HasForeignKey(scope *Scope, tableName string, fkName string) bool
RemoveIndex(scope *Scope, indexName string)
CurrentDatabase(scope *Scope) string
}

View File

@ -56,6 +56,13 @@ func (mysql) SqlTag(value reflect.Value, size int, autoIncrease bool) string {
panic(fmt.Sprintf("invalid sql type %s (%s) for mysql", value.Type().Name(), value.Kind().String()))
}
func (s mysql) HasForeignKey(scope *Scope, tableName string, fkName string) bool {
var count int
s.RawScanInt(scope, &count, "SELECT count(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA=? AND TABLE_NAME=? AND CONSTRAINT_NAME=? AND CONSTRAINT_TYPE='FOREIGN KEY'",
s.CurrentDatabase(scope), tableName, fkName)
return count > 0
}
func (mysql) Quote(key string) string {
return fmt.Sprintf("`%s`", key)
}

View File

@ -103,6 +103,13 @@ func (s postgres) HasIndex(scope *Scope, tableName string, indexName string) boo
return count > 0
}
func (s postgres) HasForeignKey(scope *Scope, tableName string, fkName string) bool {
var count int
s.RawScanInt(scope, &count, "SELECT count(con.conname) FROM pg_constraint con WHERE con.conname = ? AND con.contype='f' AND ?::regclass::oid = con.conrelid",
fkName, tableName)
return count > 0
}
func (s postgres) CurrentDatabase(scope *Scope) (name string) {
s.RawScanString(scope, &name, "SELECT CURRENT_DATABASE()")
return