-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathview.go
More file actions
90 lines (77 loc) · 1.87 KB
/
view.go
File metadata and controls
90 lines (77 loc) · 1.87 KB
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
package catalog
import (
"github.com/sqlc-dev/sqlc/internal/sql/ast"
"github.com/sqlc-dev/sqlc/internal/sql/astutils"
"github.com/sqlc-dev/sqlc/internal/sql/sqlerr"
)
func (c *Catalog) createView(stmt *ast.ViewStmt, colGen columnGenerator) error {
cols, err := colGen.OutputColumns(stmt.Query)
if err != nil {
return err
}
catName := ""
if stmt.View.Catalogname != nil {
catName = *stmt.View.Catalogname
}
schemaName := ""
if stmt.View.Schemaname != nil {
schemaName = *stmt.View.Schemaname
}
tbl := Table{
Rel: &ast.TableName{
Catalog: catName,
Schema: schemaName,
Name: *stmt.View.Relname,
},
Columns: cols,
}
// Extract table dependencies from the view's SELECT query
tbl.DependsOnTables = extractTableDeps(stmt.Query)
ns := tbl.Rel.Schema
if ns == "" {
ns = c.DefaultSchema
}
schema, err := c.getSchema(ns)
if err != nil {
return err
}
_, existingIdx, err := schema.getTable(tbl.Rel)
if err == nil && !stmt.Replace {
return sqlerr.RelationExists(tbl.Rel.Name)
}
if stmt.Replace && err == nil {
schema.Tables[existingIdx] = &tbl
} else {
schema.Tables = append(schema.Tables, &tbl)
}
return nil
}
// extractTableDeps walks the SELECT query AST and returns all table references (RangeVar nodes).
func extractTableDeps(node ast.Node) []*ast.TableName {
var deps []*ast.TableName
seen := make(map[string]bool)
astutils.Walk(astutils.VisitorFunc(func(n ast.Node) {
rv, ok := n.(*ast.RangeVar)
if !ok || rv.Relname == nil {
return
}
schema := ""
if rv.Schemaname != nil {
schema = *rv.Schemaname
}
key := schema + "." + *rv.Relname
if seen[key] {
return
}
seen[key] = true
// Skip system catalogs and information schema
if schema == "pg_catalog" || schema == "information_schema" {
return
}
deps = append(deps, &ast.TableName{
Schema: schema,
Name: *rv.Relname,
})
}), node)
return deps
}