-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
102 lines (85 loc) · 2.12 KB
/
main.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
package main
import (
"context"
"fmt"
"os"
"slices"
"strings"
"time"
"github.com/electric-saw/pg-defrag/pkg/defrag"
"github.com/electric-saw/pg-defrag/pkg/params"
"github.com/pterm/pterm"
"github.com/sirupsen/logrus"
)
func main() {
p, err := defrag.NewProcessor(os.Getenv("PG_CONNECTION_STRING"),
logrus.New())
if err != nil {
logrus.Fatal(err)
}
p.Jobs = jobList(p)
p.NoInitialVacuum = true
params.PROGRESS_REPORT_PERIOD = 5 * time.Second
defer p.Close()
if cleaned, err := p.Run(context.Background()); err != nil {
logrus.Panic(err)
} else {
fmt.Printf("cleaned: %v", cleaned)
}
}
func jobList(p *defrag.Process) []defrag.JobInfo {
jobs := []defrag.JobInfo{}
tablesEnv := os.Getenv("PG_TABLES")
tablesToDefrag := []string{}
if tablesEnv == "" || tablesEnv == "*" {
res, err := p.Pg.Conn.Query(
context.Background(),
"SELECT schemaname || '.' || relname FROM pg_stat_user_tables WHERE schemaname NOT IN ('pg_catalog', 'information_schema')",
)
if err != nil {
logrus.Fatal(err)
}
for res.Next() {
var table string
if err := res.Scan(&table); err != nil {
logrus.Fatal(err)
}
if !slices.Contains([]string{
"_timescaledb_catalog.metadata",
"_timescaledb_catalog.chunk",
}, table) {
tablesToDefrag = append(tablesToDefrag, table)
}
}
slices.Sort(tablesToDefrag)
tablesToDefrag, _ = pterm.
DefaultInteractiveMultiselect.
WithOptions(tablesToDefrag).
WithDefaultText("Select tables to defrag").
WithFilter(true).
// WithKeyConfirm(keys.Enter).
// WithKeySelect(keys.Space).
WithCheckmark(&pterm.Checkmark{Checked: pterm.Green("+"), Unchecked: pterm.Red("-")}).
Show()
if len(tablesToDefrag) == 0 {
logrus.Info("No tables selected, exiting")
os.Exit(0)
}
} else {
tablesToDefrag = strings.Split(tablesEnv, ",")
}
for _, name := range tablesToDefrag {
splitedName := strings.Split(name, ".")
if len(splitedName) == 2 {
jobs = append(jobs, defrag.JobInfo{
Schema: splitedName[0],
Table: splitedName[1],
})
} else {
jobs = append(jobs, defrag.JobInfo{
Table: splitedName[0],
})
}
}
return jobs
}