-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
254 lines (207 loc) · 4.67 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
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package main
import (
"bufio"
"database/sql"
"errors"
"fmt"
"os"
"os/signal"
"strconv"
"syscall"
"github.com/fatih/color"
_ "github.com/lib/pq"
"golang.org/x/crypto/ssh/terminal"
)
var (
defaultPgHost = "localhost"
defaultPgPort = "5432"
defaultPgUser = "postgres"
green *color.Color
yellow *color.Color
red *color.Color
cyan *color.Color
)
func init() {
// Exit execution for certain syscalls.
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
go func() {
for _ = range c {
os.Exit(0)
}
}()
// Load the different colors to be used in the CLI.
green = color.New(color.FgGreen)
yellow = color.New(color.FgYellow)
red = color.New(color.FgRed)
cyan = color.New(color.FgCyan)
}
// validateConfirmation validates confirmation ([y/n]) user input.
func validateConfirmation(value string) (bool, error) {
if value == "y" || value == "Y" {
return true, nil
}
if value == "n" || value == "N" {
return false, nil
}
return false, errors.New("invalid value supplied")
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
// PG HOST.
green.Print("Postgres Host (defaults to 'localhost'): ")
scanner.Scan()
pgHost := scanner.Text()
if pgHost == "" {
pgHost = defaultPgHost
}
// PG PORT.
green.Print("Postgres Port (defaults to 5432): ")
scanner.Scan()
pgPort := scanner.Text()
if pgPort == "" {
pgPort = defaultPgPort
}
pgPortInt, _ := strconv.Atoi(pgPort)
// PG USER.
green.Print("Postgres User (defaults to 'postgres'): ")
scanner.Scan()
pgUser := scanner.Text()
if pgUser == "" {
pgUser = defaultPgUser
}
// PG USER PASSWORD.
passwordPrompt := fmt.Sprintf("Password for user '%s': ", pgUser)
pgPassword := ""
for {
green.Print(passwordPrompt)
bytePassword, _ := terminal.ReadPassword(int(syscall.Stdin))
pgPassword = string(bytePassword)
fmt.Println("")
if pgPassword != "" {
break
}
}
// PG DATABASE.
pgDatabase := ""
for {
green.Print("Postgres Database: ")
scanner.Scan()
pgDatabase = scanner.Text()
if pgDatabase != "" {
break
}
}
// DB Connection.
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
pgHost, pgPortInt, pgUser, pgPassword, pgDatabase)
db, err := sql.Open("postgres", psqlInfo)
yellow.Println("Connecting to Postgres database...")
if err != nil {
red.Println(err)
os.Exit(0)
}
err = db.Ping()
if err != nil {
red.Println(err)
os.Exit(0)
}
yellow.Println("Connnected!")
tr:
// TABLE NAME REGEX.
tableNameRegex := ""
for {
green.Print("Table name regex to apply index (E.g. tablename_.*_.*): ")
scanner.Scan()
tableNameRegex = scanner.Text()
if tableNameRegex != "" {
break
}
}
tablesQuery := fmt.Sprintf(`SELECT tablename
FROM pg_tables
WHERE SUBSTRING(tablename FROM '%s') <> '';`, tableNameRegex)
yellow.Println("Finding tables/partitions...")
rows, _ := db.Query(tablesQuery)
var tables []string
for rows.Next() {
var tablename string
if err := rows.Scan(&tablename); err != nil {
fmt.Println(err)
}
cyan.Printf("%s\n", tablename)
tables = append(tables, tablename)
}
var confirmation bool
for {
green.Print("Is this correct? [y/n] ")
scanner.Scan()
confirmation, err = validateConfirmation(scanner.Text())
if err == nil {
break
}
}
if confirmation == false {
goto tr
}
// INDEX NAME.
indexName := ""
for {
green.Print("New index name: ")
scanner.Scan()
indexName = scanner.Text()
if indexName != "" {
break
}
}
// UNIQUE INDEX.
var uniqueIndex bool
for {
green.Print("Is this a unique index? [y/n]: ")
scanner.Scan()
uniqueIndex, err = validateConfirmation(scanner.Text())
if err == nil {
break
}
}
var uniqueIndexStr string
if uniqueIndex {
uniqueIndexStr = "UNIQUE"
}
indexColumns := ""
for {
green.Print("Index columns (E.g. col1, col2 DESC, col3): ")
scanner.Scan()
indexColumns = scanner.Text()
if indexColumns != "" {
break
}
}
var queries []string
for _, table := range tables {
fullIndexName := fmt.Sprintf("%s_%s", table, indexName)
indexQuery := fmt.Sprintf(`CREATE %s INDEX CONCURRENTLY %s ON %s (%s);`, uniqueIndexStr, fullIndexName, table, indexColumns)
queries = append(queries, indexQuery)
cyan.Println(indexQuery)
}
var execute bool
for {
green.Print("FINAL STEP! Execute above queries? [y/n]: ")
scanner.Scan()
execute, err = validateConfirmation(scanner.Text())
if err == nil {
break
}
}
if !execute {
os.Exit(0)
}
for _, query := range queries {
cyan.Println(fmt.Sprintf("Executing '%s'", query))
_, err := db.Exec(query)
if err != nil {
red.Println(err)
}
}
green.Println("All queries executed!")
}