-
Notifications
You must be signed in to change notification settings - Fork 8
/
schema_explorer.go
55 lines (44 loc) · 1.3 KB
/
schema_explorer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package db
import (
"github.com/deckarep/golang-set"
"sort"
)
// SchemaExplorer represents schema explorer
type SchemaExplorer struct {
schema *Schema
graph *UndirectedGraph
}
// NewSchemaExplorer returns a new SchemaExplorer instance
func NewSchemaExplorer(schema *Schema) *SchemaExplorer {
graph := NewUndirectedGraph()
for _, table := range schema.Tables {
for _, foreignKey := range table.ForeignKeys {
graph.PutSymmetric(table.Name, foreignKey.ToTable, true)
}
}
return &SchemaExplorer{schema: schema, graph: graph}
}
// Explore returns surrounding tables from table
func (e *SchemaExplorer) Explore(tableName string, distance int) []string {
if distance < 0 {
distance = 0
}
foundTableNames := mapset.NewSet()
e.explore(tableName, distance, foundTableNames, 0)
var tableNames []string
foundTableNames.Each(func(i interface{}) bool {
tableNames = append(tableNames, i.(string))
return false
})
sort.Strings(tableNames)
return tableNames
}
func (e *SchemaExplorer) explore(tableName string, distance int, foundTableNames mapset.Set, pos int) {
if pos > distance || foundTableNames.Contains(tableName) {
return
}
foundTableNames.Add(tableName)
for _, aroundTableName := range e.graph.GetRowColumns(tableName) {
e.explore(aroundTableName, distance, foundTableNames, pos+1)
}
}