Add even more nullable things for FKeys.

This commit is contained in:
Aaron L 2016-07-12 08:09:26 -07:00
parent fb802ad687
commit 7cdf44376b
3 changed files with 42 additions and 30 deletions

View file

@ -52,11 +52,15 @@ func Tables(db Interface, names ...string) ([]Table, error) {
}
setIsJoinTable(&t)
setForeignKeyNullability(&t)
tables = append(tables, t)
}
// Relationships have a dependency on foreign key nullability.
for i := range tables {
tbl := &tables[i]
setForeignKeyNullability(tbl, tables)
}
for i := range tables {
tbl := &tables[i]
setRelationships(tbl, tables)
@ -89,22 +93,14 @@ func setIsJoinTable(t *Table) {
t.IsJoinTable = true
}
func setForeignKeyNullability(t *Table) {
func setForeignKeyNullability(t *Table, tables []Table) {
for i, fkey := range t.FKeys {
localColumn := t.GetColumn(fkey.Column)
foreignTable := GetTable(tables, fkey.ForeignTable)
foreignColumn := foreignTable.GetColumn(fkey.ForeignColumn)
found := -1
for j, col := range t.Columns {
if col.Name == fkey.Column {
found = j
break
}
}
if found < 0 {
panic("could not find foreign key column in table")
}
t.FKeys[i].Nullable = t.Columns[found].Nullable
t.FKeys[i].Nullable = localColumn.Nullable
t.FKeys[i].ForeignColumnNullable = foreignColumn.Nullable
}
}

View file

@ -128,27 +128,42 @@ func TestSetIsJoinTable(t *testing.T) {
func TestSetForeignKeyNullability(t *testing.T) {
t.Parallel()
table := &Table{
Columns: []Column{
Column{Name: "col1", Type: "string"},
Column{Name: "col2", Type: "string", Nullable: true},
},
FKeys: []ForeignKey{
{
Column: "col1",
tables := []Table{
Table{
Name: "one",
Columns: []Column{
Column{Name: "id1", Type: "string", Nullable: false},
Column{Name: "id2", Type: "string", Nullable: true},
},
{
Column: "col2",
},
Table{
Name: "other",
Columns: []Column{
Column{Name: "one_id_1", Type: "string", Nullable: false},
Column{Name: "one_id_2", Type: "string", Nullable: true},
},
FKeys: []ForeignKey{
{Column: "one_id_1", ForeignTable: "one", ForeignColumn: "id1"},
{Column: "one_id_2", ForeignTable: "one", ForeignColumn: "id2"},
},
},
}
setForeignKeyNullability(table)
setForeignKeyNullability(&tables[0], tables)
setForeignKeyNullability(&tables[1], tables)
if table.FKeys[0].Nullable {
first := tables[1].FKeys[0]
second := tables[1].FKeys[1]
if first.Nullable {
t.Error("should not be nullable")
}
if !table.FKeys[1].Nullable {
if first.ForeignColumnNullable {
t.Error("should be nullable")
}
if !second.Nullable {
t.Error("should be nullable")
}
if !second.ForeignColumnNullable {
t.Error("should be nullable")
}
}

View file

@ -20,8 +20,9 @@ type ForeignKey struct {
Column string
Nullable bool
ForeignTable string
ForeignColumn string
ForeignTable string
ForeignColumn string
ForeignColumnNullable bool
}
// SQLColumnDef formats a column name and type like an SQL column definition.