forked from jordanlewis/twitch-cockroachdb-gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
229 lines (212 loc) · 5.11 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
package main
import (
"context"
"fmt"
"os"
"strings"
"time"
"github.com/gempir/go-twitch-irc/v2"
"github.com/jackc/pgproto3/v2"
"github.com/jackc/pgtype"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
)
var stmts = []string{
"ADD",
"ALTER",
//"BACKUP",
"CANCEL",
"COMMENT",
//"COPY",
"CREATE",
//"DEALLOCATE",
"DELETE",
"DISCARD",
"DROP",
"EXECUTE",
"EXPLAIN",
//"EXPORT",
//"IMPORT",
"INSERT",
//"GRANT",
"PAUSE",
"PREPARE",
"RELEASE",
"RESET",
//"REVOKE",
"SAVEPOINT",
"SELECT",
//"SET",
"SHOW",
"TABLE",
"TRUNCATE",
"UPDATE",
"UPSERT",
"VALUES",
}
var blocklist = map[string]struct{}{
"SESSIONS": {},
"USER": {},
"ROLE": {},
"USERS": {},
"ROLES": {},
"CONFIGURATIONS": {},
"CLUSTER": {},
"SETTINGS": {},
"SETTING": {},
"CRDB_INTERNAL.CLUSTER_SETTINGS": {},
"CRDB_INTERNAL.NODE_SESSIONS": {},
"CRDB_INTERNAL.CLUSTER_SESSIONS": {},
"CLUSTER_SESSIONS": {},
"NODE_SESSIONS": {},
"SET_CONFIG": {},
"PG_CATALOG.SET_CONFIG": {},
"JOBS": {},
}
var stmtsMap map[string]struct{}
func init() {
stmtsMap = make(map[string]struct{})
for _, s := range stmts {
stmtsMap[s] = struct{}{}
}
}
func main() {
ctx := context.Background()
client := twitch.NewAnonymousClient()
client.Join("twitchrunscockroachdb")
url := os.Getenv("DATABASE_URL")
config, err := pgxpool.ParseConfig(url)
if err != nil {
panic(err)
}
config.BeforeAcquire = func(ctx context.Context, conn *pgx.Conn) bool {
_, err := conn.Exec(ctx, "SET statement_timeout='5s'")
if err != nil {
fmt.Println("error acquiring connection", err)
return false
}
return true
}
pool, err := pgxpool.ConnectConfig(ctx, config)
if err != nil {
panic(err)
}
/*
conn, err := pool.Acquire(ctx)
if err != nil {
panic(err)
}
//connInfo := conn.Conn().ConnInfo()
conn.Release()
*/
processMessage := func(message twitch.PrivateMessage) {
if err := func() error {
tokens := strings.Split(message.Message, " ")
for i := range tokens {
tokens[i] = strings.ToUpper(tokens[i])
}
for i := range tokens {
if _, ok := blocklist[strings.Trim(tokens[i], " \t;")]; ok {
return nil
}
}
if _, ok := stmtsMap[strings.ToUpper(tokens[0])]; ok {
fmt.Printf("%s: `%s`\n", message.User.DisplayName, message.Message)
ctx, _ := context.WithTimeout(ctx, 10*time.Second)
rows, err := pool.Query(ctx, message.Message, pgx.QuerySimpleProtocol(true))
if err != nil {
return err
}
i := 0
var descriptions []pgproto3.FieldDescription
for rows.Next() {
if i == 0 {
sb := strings.Builder{}
descriptions = rows.FieldDescriptions()
for i, col := range descriptions {
if i > 0 {
sb.WriteRune(',')
}
sb.WriteString(string(col.Name))
}
fmt.Println(sb.String())
}
i++
if i > 10 {
rows.Close()
break
}
/*
if err != nil {
return err
}
*/
row := rows.RawValues()
buf := make([]byte, 0, len(row)*10)
for i, v := range row {
if i > 0 {
buf = append(buf, ',')
}
buf = append(buf, v...)
//buf, err = formatVal(buf, connInfo, v)
//if err != nil {
// return err
//}
}
fmt.Println(string(buf))
}
if err := rows.Err(); err != nil {
return err
}
if i > 10 {
fmt.Printf("... more rows ...\n")
}
if i == 0 && !rows.CommandTag().Select() {
// Print the command tag if it wasn't a select.
fmt.Println(rows.CommandTag())
}
}
return nil
}(); err != nil {
fmt.Println(err)
}
}
client.OnPrivateMessage(processMessage)
processMessage(twitch.PrivateMessage{
User: twitch.User{DisplayName: "jordan"},
Message: "show cluster settings",
})
if err := client.Connect(); err != nil {
panic(err)
}
}
func encodeByteArrayToRawBytes(data string) string {
// PostgreSQL does not allow all the escapes formats recognized by
// CockroachDB's scanner. It only recognizes octal and \\ for the
// backslash itself.
// See https://www.postgresql.org/docs/current/static/datatype-binary.html#AEN5667
res := make([]byte, 0, len(data))
for _, c := range []byte(data) {
if c == '\\' {
res = append(res, '\\', '\\')
} else if c < 32 || c >= 127 {
// Escape the character in octal.
//
// Note: CockroachDB only supports UTF-8 for which all values
// below 128 are ASCII. There is no locale-dependent escaping
// in that case.
res = append(res, '\\', '0'+(c>>6), '0'+((c>>3)&7), '0'+(c&7))
} else {
res = append(res, c)
}
}
return string(res)
}
func formatVal(buf []byte, connInfo *pgtype.ConnInfo, v interface{}) ([]byte, error) {
if encoder, ok := v.(pgtype.TextEncoder); ok {
return encoder.EncodeText(connInfo, buf)
}
buf = append(buf, []byte(fmt.Sprintf("%v", v))...)
return buf, nil
}
const timestampOutputFormat = "2006-01-02 15:04:05.999999-07:00"