Skip to content
Merged
Show file tree
Hide file tree
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
25 changes: 25 additions & 0 deletions schema/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,31 @@ func (tt Tables) FlattenTables() Tables {
return slices.Clip(deduped)
}

// UnflattenTables returns a new Tables copy with the relations unflattened. This is the
// opposite operation of FlattenTables.
func (tt Tables) UnflattenTables() (Tables, error) {
tables := make(Tables, 0, len(tt))
for _, t := range tt {
table := *t
tables = append(tables, &table)
}
topLevel := make([]*Table, 0, len(tt))
// build relations
for _, table := range tables {
if table.Parent == nil {
topLevel = append(topLevel, table)
continue
}
parent := tables.Get(table.Parent.Name)
if parent == nil {
return nil, fmt.Errorf("parent table %s not found", table.Parent.Name)
}
table.Parent = parent
parent.Relations = append(parent.Relations, table)
}
return slices.Clip(topLevel), nil
}

func (tt Tables) TableNames() []string {
ret := []string{}
for _, t := range tt {
Expand Down
10 changes: 10 additions & 0 deletions schema/table_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ var testTable = &Table{
{
Name: "test2",
Columns: []Column{},
Parent: &Table{Name: "test"},
},
},
}
Expand Down Expand Up @@ -45,6 +46,15 @@ func TestTablesFlatten(t *testing.T) {
}
}

func TestTablesUnflatten(t *testing.T) {
srcTables := Tables{testTable}
tables, err := srcTables.FlattenTables().UnflattenTables()
require.NoError(t, err)
require.Equal(t, 1, len(srcTables)) // verify that the source Tables were left untouched
require.Equal(t, 1, len(tables)) // verify that the tables are equal to what we started with
require.Equal(t, 1, len(tables[0].Relations))
}

func TestTablesFilterDFS(t *testing.T) {
tests := []struct {
name string
Expand Down