-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathview.go
87 lines (73 loc) · 1.86 KB
/
view.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
package sol
import (
"fmt"
"github.com/aodin/sol/dialect"
)
// ViewElem is a dialect neutral implementation of a SQL view
type ViewElem struct {
*TableElem
stmt SelectStmt // The statement that builds the view
}
// Create
func (view ViewElem) Create() (stmt CreateViewStmt) {
stmt.view = view
return
}
// View returns a new ViewElem that can be created or queried
func View(name string, stmt SelectStmt) (ViewElem, error) {
var view ViewElem
// Are the columns of the SELECT stmt unique?
columns, err := stmt.columns.MakeUnique()
if err != nil {
return view, err
}
// Create a new table from the stmt
view.TableElem = &TableElem{
name: name,
columns: columns,
}
view.stmt = stmt
return view, nil
}
// CreateViewStmt is the internal representation of a CREATE VIEW statement.
type CreateViewStmt struct {
Stmt
view ViewElem
isTemporary bool
orReplace bool
}
// String outputs the parameter-less CREATE View statement in a neutral
// dialect.
func (stmt CreateViewStmt) String() string {
c, _ := stmt.Compile(&defaultDialect{}, Params())
return c
}
func (stmt CreateViewStmt) Temporary() CreateViewStmt {
stmt.isTemporary = true
return stmt
}
func (stmt CreateViewStmt) OrReplace() CreateViewStmt {
stmt.orReplace = true
return stmt
}
// Compile outputs the CREATE VIEW statement using the given dialect and
// parameters. An error may be returned because of a pre-existing error or
// because an error occurred during compilation.
func (stmt CreateViewStmt) Compile(d dialect.Dialect, p *Parameters) (string, error) {
name := "CREATE"
if stmt.orReplace {
name += " OR REPLACE"
}
if stmt.isTemporary {
name = "TEMPORARY"
}
name += " VIEW"
// TODO column aliases
selectStmt, err := stmt.view.stmt.Compile(d, p)
if err != nil {
return "", err
}
return fmt.Sprintf(
"%s %s AS (%s)", name, stmt.view.Name(), selectStmt,
), nil
}