-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathturboquery.go
109 lines (88 loc) · 1.93 KB
/
turboquery.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
package turboquery
import (
"context"
"database/sql"
"log"
)
type ReplicaInfo struct {
Name string
DSN string
}
type Conn struct {
Name string
Endpoint *sql.DB
}
type Result struct {
DatabaseName string
Columns []string
Rows [][]string
}
func MultiQuery(replicas []ReplicaInfo, query string) Result {
conns := make([]Conn, len(replicas))
for i, replica := range replicas {
db, err := sql.Open("mysql", replica.DSN)
if err != nil {
log.Fatalf("failed to connect to %s: %v", replica.Name, err)
}
defer db.Close()
conns[i] = Conn{
Name: replica.Name,
Endpoint: db,
}
}
ctx, cancel := context.WithCancel(context.Background())
ch := make(chan Result, len(conns))
done := make(chan struct{})
defer func() {
cancel() // Ensure cancel is always called before returning
close(done)
}()
for _, conn := range conns {
go func(conn Conn) {
select {
case ch <- Query(ctx, conn, query):
cancel() // Cancel other queries
case <-done:
// Do nothing if a result has already been received
}
}(conn)
}
result := <-ch
return result
}
func Query(ctx context.Context, c Conn, query string) Result {
rows, err := c.Endpoint.QueryContext(ctx, query)
if err != nil {
log.Panic(err)
}
defer rows.Close()
columns, err := rows.Columns()
if err != nil {
log.Panic(err)
}
values := make([]sql.RawBytes, len(columns))
scanArgs := make([]interface{}, len(values))
for i := range values {
scanArgs[i] = &values[i]
}
var rowsData [][]string
for rows.Next() {
err := rows.Scan(scanArgs...)
if err != nil {
log.Panic(err)
}
var rowData []string
for _, value := range values {
if value == nil {
rowData = append(rowData, "")
} else {
rowData = append(rowData, string(value))
}
}
rowsData = append(rowsData, rowData)
}
if err := rows.Err(); err != nil {
log.Panic(err)
}
return Result{DatabaseName: c.Name, Columns: columns, Rows: rowsData}
}