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

Allow non-text/blob columns as a foreign key #7

Merged
merged 1 commit into from
Oct 15, 2018
Merged
Changes from all 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
13 changes: 7 additions & 6 deletions src/guess/guess.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,25 @@ const (

type GuessOption func(database.Column, string, database.Column) bool

func isAcceptableAsPrimaryKey(columnType, primaryKeyType string) bool {
colIsOk := strings.Index(columnType, "int") != -1
pkIsOk := strings.Index(primaryKeyType, "int") != -1
return colIsOk && pkIsOk && columnType == primaryKeyType
func isAcceptableAsIndex(left, right string) bool {
return left == right &&
!(strings.Index(left, "text") != -1 || strings.Index(left, "blob") != -1) &&
!(strings.Index(right, "text") != -1 || strings.Index(right, "blob") != -1)
}

// Recongnize a column thats same name of other table's primary key is a foreign key
// This base idea refers to SchemaSpy DbAnalyzer:
// https://github.com/schemaspy/schemaspy/blob/master/src/main/java/org/schemaspy/DbAnalyzer.java
func GuessByPrimaryKey() GuessOption {
return func(i database.Column, table string, pk database.Column) bool {
return isAcceptableAsPrimaryKey(i.Type, pk.Type) && i.Name == pk.Name && pk.Name != idColumn
return isAcceptableAsIndex(i.Type, pk.Type) && i.Name == pk.Name && pk.Name != idColumn
}
}

// Recongnize a column thats same name without '_id' suffix of other table name is a foreign key
func GuessByTableAndColumn() GuessOption {
return func(i database.Column, table string, pk database.Column) bool {
if !isAcceptableAsPrimaryKey(i.Type, pk.Type) {
if !isAcceptableAsIndex(i.Type, pk.Type) {
return false
}

Expand Down