-
Notifications
You must be signed in to change notification settings - Fork 25
/
postgres.go
140 lines (113 loc) · 2.6 KB
/
postgres.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package schema
import (
"os"
"strings"
pg_query "github.com/pganalyze/pg_query_go/v4"
)
func (s *Db) LoadPostgres(schemaPath string) error {
schemaBytes, err := os.ReadFile(schemaPath)
if err != nil {
return err
}
s.Tables, err = parsePostgresSchema(string(schemaBytes))
if err != nil {
return err
}
return nil
}
func parsePostgresSchema(schemaInput string) (map[string]Table, error) {
tables := map[string]Table{}
tree, err := pg_query.Parse(schemaInput)
if err != nil {
return nil, err
}
for _, stmt := range tree.Stmts {
if stmt.Stmt == nil {
continue
}
createStmt := stmt.Stmt.GetCreateStmt()
if createStmt != nil {
tableName := createStmt.Relation.Relname
table := Table{
Name: tableName,
Columns: map[string]Column{},
}
for _, colElem := range createStmt.TableElts {
if colElem.GetColumnDef() == nil {
continue
}
colDef := colElem.GetColumnDef()
typeParts := []string{}
for _, typNode := range colDef.TypeName.Names {
if typNode.GetString_() == nil {
continue
}
tStr := typNode.GetString_()
typeParts = append(typeParts, tStr.Sval)
}
colName := colDef.Colname
table.Columns[colName] = Column{
Name: colName,
Type: strings.Join(typeParts, "."),
}
}
tables[tableName] = table
}
viewStmt := stmt.Stmt.GetViewStmt()
if viewStmt != nil {
tableName := viewStmt.View.Relname
table := Table{
Name: tableName,
Columns: map[string]Column{},
ReadOnly: true,
}
query := viewStmt.GetQuery()
if query == nil {
continue
}
selStmt := query.GetSelectStmt()
if selStmt == nil {
continue
}
for _, item := range selStmt.TargetList {
resTarget := item.GetResTarget()
if resTarget == nil {
continue
}
if col, ok := GetResTargetColumn(resTarget); ok {
table.Columns[col.Name] = col
}
}
tables[tableName] = table
}
}
return tables, nil
}
func GetResTargetColumn(resTarget *pg_query.ResTarget) (col Column, ok bool) {
if resTarget.Name != "" {
return Column{Name: resTarget.Name}, true
}
if resTarget.Val == nil {
return
}
colRef := resTarget.Val.GetColumnRef()
if colRef == nil {
// parse only column references when no alias is provided
return
}
var colField *pg_query.Node
if len(colRef.Fields) > 0 {
colField = colRef.Fields[len(colRef.Fields)-1]
}
if colField == nil {
return
}
if colField.GetAStar() != nil {
// SELECT * - force parsing explicit columns for simplicity
return
}
if colField.GetString_() == nil {
return
}
return Column{Name: colField.GetString_().Sval}, true
}