-
Notifications
You must be signed in to change notification settings - Fork 427
/
database.go
93 lines (80 loc) · 2.47 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
package snowflake
import (
"database/sql"
"fmt"
"log"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
// Database returns a pointer to a Builder for a database
func Database(name string) *Builder {
return &Builder{
name: name,
entityType: DatabaseType,
}
}
// DatabaseShareBuilder is a basic builder that just creates databases from shares
type DatabaseShareBuilder struct {
name string
provider string
share string
}
// DatabaseFromShare returns a pointer to a builder that can create a database from a share
func DatabaseFromShare(name, provider, share string) *DatabaseShareBuilder {
return &DatabaseShareBuilder{
name: name,
provider: provider,
share: share,
}
}
// Create returns the SQL statement required to create a database from a share
func (dsb *DatabaseShareBuilder) Create() string {
return fmt.Sprintf(`CREATE DATABASE "%v" FROM SHARE "%v"."%v"`, dsb.name, dsb.provider, dsb.share)
}
// DatabaseCloneBuilder is a basic builder that just creates databases from a source database
type DatabaseCloneBuilder struct {
name string
database string
}
// DatabaseFromDatabase returns a pointer to a builder that can create a database from a source database
func DatabaseFromDatabase(name, database string) *DatabaseCloneBuilder {
return &DatabaseCloneBuilder{
name: name,
database: database,
}
}
// Create returns the SQL statement required to create a database from a source database
func (dsb *DatabaseCloneBuilder) Create() string {
return fmt.Sprintf(`CREATE DATABASE "%v" CLONE "%v"`, dsb.name, dsb.database)
}
type database struct {
CreatedOn sql.NullString `db:"created_on"`
DBName sql.NullString `db:"name"`
IsDefault sql.NullString `db:"is_default"`
IsCurrent sql.NullString `db:"is_current"`
Origin sql.NullString `db:"origin"`
Owner sql.NullString `db:"owner"`
Comment sql.NullString `db:"comment"`
Options sql.NullString `db:"options"`
RetentionTime sql.NullString `db:"retention_time"`
}
func ScanDatabase(row *sqlx.Row) (*database, error) {
d := &database{}
e := row.StructScan(d)
return d, e
}
func ListDatabases(sdb *sqlx.DB) ([]database, error) {
stmt := "SHOW DATABASES"
rows, err := sdb.Queryx(stmt)
if err != nil {
return nil, err
}
defer rows.Close()
dbs := []database{}
err = sqlx.StructScan(rows, &dbs)
if err == sql.ErrNoRows {
log.Printf("[DEBUG] no databases found")
return nil, nil
}
return dbs, errors.Wrapf(err, "unable to scan row for %s", stmt)
}