-
Notifications
You must be signed in to change notification settings - Fork 109
/
postgresql.go
80 lines (65 loc) · 1.62 KB
/
postgresql.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
package main
import (
"database/sql"
"fmt"
"regexp"
"strings"
_ "github.com/lib/pq"
)
const (
INCLUDE_DBS = "/include:"
EXCLUDE_DBS = "/exclude:"
)
func listDatabases(connStr string) ([]string, error) {
db, err := sql.Open("postgres", connStr)
if err != nil {
return nil, err
}
defer db.Close()
rows, err := db.Query("SELECT datname FROM pg_database WHERE datistemplate = false;")
if err != nil {
return nil, err
}
defer rows.Close()
var databases []string
for rows.Next() {
var dbname string
if err := rows.Scan(&dbname); err != nil {
return nil, err
}
databases = append(databases, dbname)
}
return databases, nil
}
func filterDatabases(databases []string, pattern string) ([]string, error) {
var filtered []string
mode, dbs := parsePattern(pattern)
// Split the dbs string into individual patterns
dbPatterns := strings.Split(dbs, ",")
// Process each database name against the patterns
for _, dbname := range databases {
include := false
for _, dbPattern := range dbPatterns {
matched, err := regexp.MatchString(dbPattern, dbname)
if err != nil {
return nil, fmt.Errorf("invalid pattern: %s", dbPattern)
}
if matched {
include = true
break
}
}
if (mode == INCLUDE_DBS && include) || (mode == EXCLUDE_DBS && !include) {
filtered = append(filtered, dbname)
}
}
return filtered, nil
}
func parsePattern(pattern string) (mode string, dbs string) {
if strings.HasPrefix(pattern, INCLUDE_DBS) {
return INCLUDE_DBS, pattern[len(INCLUDE_DBS):]
} else if strings.HasPrefix(pattern, EXCLUDE_DBS) {
return EXCLUDE_DBS, pattern[len(EXCLUDE_DBS):]
}
return "", ""
}