-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
190 lines (173 loc) · 3.91 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
package main
import (
"context"
"fmt"
"log"
"os"
"strconv"
"strings"
"github.com/gofrs/uuid/v5"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/jedib0t/go-pretty/v6/table"
"github.com/jedib0t/go-pretty/v6/text"
"github.com/urfave/cli/v2"
)
type connArgs struct {
host string
port string
user string
password string
database string
url string
}
func main() {
args := connArgs{}
app := &cli.App{
Name: "pgexec",
UsageText: "pgexec --url \"postgres://...\" \"SELECT * FROM users;\"",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "url",
Destination: &args.url,
Usage: "Connection string, e.g. postgres://<user>:<pw>@<host>:<port>/<db>",
},
&cli.StringFlag{
Name: "host",
Destination: &args.host,
Usage: "Host addres",
},
&cli.StringFlag{
Name: "port",
Aliases: []string{"p"},
Destination: &args.port,
Usage: "Port",
},
&cli.StringFlag{
Name: "user",
Aliases: []string{"u"},
Destination: &args.user,
Usage: "User name",
},
&cli.StringFlag{
Name: "password",
Aliases: []string{"pw"},
Destination: &args.password,
Usage: "Password",
},
&cli.StringFlag{
Name: "db",
Destination: &args.database,
Usage: "Database name",
},
},
Action: func(cCtx *cli.Context) error {
err := execCommand(cCtx.Context, args, cCtx.Args().Get(0))
return err
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
func trim(str string) string {
return strings.Trim(str, " \t\n\r")
}
func getConnPool(ctx context.Context, connArgs connArgs) (*pgxpool.Pool, error) {
if trim(connArgs.url) != "" {
return pgxpool.New(context.Background(), connArgs.url)
}
port, err := strconv.Atoi(trim(connArgs.port))
if err != nil {
return nil, err
}
return pgxpool.NewWithConfig(ctx, &pgxpool.Config{
MaxConns: 10,
ConnConfig: &pgx.ConnConfig{
Config: pgconn.Config{
Host: connArgs.host,
Port: uint16(port),
Database: connArgs.database,
User: connArgs.user,
Password: connArgs.password,
},
},
})
}
func execCommand(ctx context.Context, connArgs connArgs, sql string) error {
pool, err := getConnPool(ctx, connArgs)
if err != nil {
return err
}
defer pool.Close()
tx, err := pool.Begin(ctx)
defer tx.Rollback(ctx)
if err != nil {
return err
}
res, err := tx.Query(ctx, sql)
if err != nil {
return err
}
vals := scanRowsToMaps(res)
t := table.NewWriter()
t.SetOutputMirror(os.Stdout)
t.SetStyle(table.StyleLight)
t.Style().Format.Header = text.FormatDefault
header := table.Row{}
for _, v := range res.FieldDescriptions() {
header = append(header, v.Name)
}
t.AppendHeader(header)
for _, val := range vals {
row := table.Row{}
for _, field := range res.FieldDescriptions() {
row = append(row, val[field.Name])
}
t.AppendRow(row)
}
t.Render()
err = tx.Commit(ctx)
if err != nil {
return err
}
return nil
}
func scanRowsToMaps(rows pgx.Rows) []map[string]interface{} {
var rowMaps []map[string]interface{}
fields := rows.FieldDescriptions()
for rows.Next() {
scans := make([]interface{}, len(fields))
row := make(map[string]interface{})
for i := range scans {
scans[i] = &scans[i]
}
rows.Scan(scans...)
for i, v := range scans {
var value = ""
if v != nil {
switch fields[i].DataTypeOID {
case pgtype.UUIDOID:
arr := v.([16]uint8)
uuidVal, err := uuid.FromBytes(arr[:])
if err != nil {
value = fmt.Sprintf("%x", v)
} else {
value = uuidVal.String()
}
case pgtype.BoolOID:
value = fmt.Sprintf("%t", v)
default:
value = fmt.Sprintf("%s", v)
}
} else {
value = "null"
}
row[fields[i].Name] = value
}
rowMaps = append(rowMaps, row)
}
return rowMaps
}