-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgsp.go
146 lines (129 loc) · 2.46 KB
/
pgsp.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package pgsp
import (
"bytes"
"context"
"reflect"
"sort"
"strings"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
)
type SPTaget string
const (
SPAnalyze SPTaget = "Analyze"
SPCreateIndex SPTaget = "CreateIndex"
SPVacuum SPTaget = "Vacuum"
SPCluster SPTaget = "Cluster"
SPBaseBackup SPTaget = "BaseBackup"
SPCopy SPTaget = "Copy"
)
type SPTable struct {
Enable bool
Get func(ctx context.Context, db *sqlx.DB) ([]Progress, error)
}
type StatProgress map[SPTaget]*SPTable
type Pgsp struct {
DB *sqlx.DB
StatProgress StatProgress
}
type Progress interface {
Name() string
Pid() int
Color() (string, string)
Table() string
Vertical() string
Progress() float64
}
func New(dsn string) (*Pgsp, error) {
db, err := Connect(dsn)
if err != nil {
return nil, err
}
monitor := NewMonitor()
return &Pgsp{
DB: db,
StatProgress: monitor,
}, nil
}
func NewMonitor() StatProgress {
return StatProgress{
SPAnalyze: {
Get: GetAnalyze,
},
SPCreateIndex: {
Get: GetCreateIndex,
},
SPVacuum: {
Get: GetVacuum,
},
SPCluster: {
Get: GetCluster,
},
SPBaseBackup: {
Get: GetBaseBackup,
},
SPCopy: {
Get: GetCopy,
},
}
}
func Connect(dsn string) (*sqlx.DB, error) {
db, err := sqlx.Connect("postgres", dsn)
if err != nil {
return nil, err
}
if err := db.Ping(); err != nil {
return nil, err
}
return db, nil
}
func (p *Pgsp) DisConnect() error {
return p.DB.Close()
}
func (p *Pgsp) Targets(target []string) {
if len(target) != 0 {
enableF := false
for _, t := range target {
if v, ok := p.StatProgress[SPTaget(t)]; ok {
enableF = true
v.Enable = true
}
}
// Return if there is even one target.
if enableF {
return
}
}
// All targets.
for _, v := range p.StatProgress {
v.Enable = true
}
}
func (p *Pgsp) TargetString() string {
var ms []string
for n, v := range p.StatProgress {
if v.Enable {
ms = append(ms, string(n))
}
}
sort.Strings(ms)
return strings.Join(ms, " ")
}
func buildQuery(tableName string, columns []string) string {
buff := new(bytes.Buffer)
buff.WriteString("SELECT ")
buff.WriteString(strings.Join(columns, ", "))
buff.WriteString(" FROM ")
buff.WriteString(tableName)
return buff.String()
}
func getColumns(s interface{}) []string {
t := reflect.TypeOf(s)
var columns []string
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
j := field.Tag.Get("db")
columns = append(columns, j)
}
return columns
}