-
Notifications
You must be signed in to change notification settings - Fork 8
/
database.go
98 lines (79 loc) · 2.21 KB
/
database.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
package materialize
import (
"database/sql"
"fmt"
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
)
type DatabaseBuilder struct {
ddl Builder
databaseName string
}
func NewDatabaseBuilder(conn *sqlx.DB, obj MaterializeObject) *DatabaseBuilder {
return &DatabaseBuilder{
ddl: Builder{conn, Database},
databaseName: obj.Name,
}
}
func (b *DatabaseBuilder) QualifiedName() string {
return QualifiedName(b.databaseName)
}
func (b *DatabaseBuilder) Create() error {
q := fmt.Sprintf(`CREATE DATABASE %s;`, b.QualifiedName())
return b.ddl.exec(q)
}
func (b *DatabaseBuilder) Drop() error {
qn := b.QualifiedName()
return b.ddl.drop(qn)
}
func (b *DatabaseBuilder) DropPublicSchema() error {
q := fmt.Sprintf(`DROP SCHEMA IF EXISTS %s.%s;`, b.QualifiedName(), QuoteIdentifier("public"))
return b.ddl.exec(q)
}
type DatabaseParams struct {
DatabaseId sql.NullString `db:"id"`
DatabaseName sql.NullString `db:"database_name"`
Comment sql.NullString `db:"comment"`
OwnerName sql.NullString `db:"owner_name"`
Privileges pq.StringArray `db:"privileges"`
}
var databaseQuery = NewBaseQuery(`
SELECT
mz_databases.id,
mz_databases.name AS database_name,
comments.comment AS comment,
mz_roles.name AS owner_name,
mz_databases.privileges
FROM mz_databases
JOIN mz_roles
ON mz_databases.owner_id = mz_roles.id
LEFT JOIN (
SELECT id, comment
FROM mz_internal.mz_comments
WHERE object_type = 'database'
) comments
ON mz_databases.id = comments.id`)
func DatabaseId(conn *sqlx.DB, obj MaterializeObject) (string, error) {
q := databaseQuery.QueryPredicate(map[string]string{"mz_databases.name": obj.Name})
var c DatabaseParams
if err := conn.Get(&c, q); err != nil {
return "", err
}
return c.DatabaseId.String, nil
}
func ScanDatabase(conn *sqlx.DB, id string) (DatabaseParams, error) {
q := databaseQuery.QueryPredicate(map[string]string{"mz_databases.id": id})
var c DatabaseParams
if err := conn.Get(&c, q); err != nil {
return c, err
}
return c, nil
}
func ListDatabases(conn *sqlx.DB) ([]DatabaseParams, error) {
q := databaseQuery.QueryPredicate(map[string]string{})
var c []DatabaseParams
if err := conn.Select(&c, q); err != nil {
return c, err
}
return c, nil
}