-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery.go
More file actions
203 lines (165 loc) · 4.81 KB
/
query.go
File metadata and controls
203 lines (165 loc) · 4.81 KB
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
package main
import (
"context"
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
type Next struct {
AffectedRows *AffectedRows `msgpack:"affected_rows"`
InsertRows *InsertRows `msgpack:"insert_rows"`
Next *Next `msgpack:"next"`
QueryRows *QueryRows `msgpack:"query_rows"`
}
type Query struct {
Query string `msgpack:"query"`
Params []any `msgpack:"params"`
Next *Next `msgpack:"next"`
}
type InsertRows Query
type QueryRows Query
type AffectedRows Query
type _DB interface {
PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
}
func (query *Query) handleQuery(_db _DB, ctx context.Context, fn func(stmt *sql.Stmt, ctx context.Context) (any, error)) ([]any, error) {
stmt, err := _db.PrepareContext(ctx, query.Query)
if err != nil {
return nil, err
}
defer stmt.Close() // Prepared statements take up server resources and should be closed after use.
ret, err := fn(stmt, ctx)
if err != nil {
return nil, err
}
var res []any
res = append(res, ret)
if query.Next != nil {
next, err := query.Next.next(db, ctx)
if err != nil {
return nil, err
}
res = append(res, next...)
}
return res, nil
}
func (query *Query) handleTransaction(db *sql.DB, ctx context.Context, fn func(stmt *sql.Stmt, ctx context.Context) (any, error)) (any, error) {
tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable}) // Tx options?
if err != nil {
return nil, fmt.Errorf("failed to start transaction: %s", err)
}
defer tx.Rollback() // The rollback will be ignored if the tx has been committed later in the function.
ret, err := query.handleQuery(tx, ctx, fn)
if err != nil {
return nil, fmt.Errorf("failed to execute transaction: %s", err)
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("failed to commit transaction: %s", err)
}
return ret, nil
}
func (query *Next) next(_db _DB, ctx context.Context) ([]any, error) {
num := 0
var fn func(stmt *sql.Stmt, ctx context.Context) (any, error)
var q *Query
if query.QueryRows != nil {
q = (*Query)(query.QueryRows)
fn = query.QueryRows.run
num++
}
if query.InsertRows != nil {
q = (*Query)(query.InsertRows)
fn = query.InsertRows.run
num++
}
if query.AffectedRows != nil {
q = (*Query)(query.AffectedRows)
fn = query.AffectedRows.run
num++
}
if num == 0 {
return nil, fmt.Errorf("MySQL requires either `query_rows`, `insert_rows`, or `affected_rows``")
}
if num > 1 {
return nil, fmt.Errorf("MySQL requires either `query_rows`, `insert_rows`, or `affected_rows`, not more then one")
}
next, err := q.handleQuery(db, ctx, fn)
if err != nil {
return nil, err
}
return next, nil
}
func (query *QueryRows) run(stmt *sql.Stmt, ctx context.Context) (any, error) {
rows, err := stmt.QueryContext(ctx, query.Params...)
if err != nil {
return nil, fmt.Errorf("query has failed: %s", err)
}
defer rows.Close()
ret, err := returnRowsAsMap(rows)
if err != nil {
return nil, err
}
return ret, nil
}
func (query *InsertRows) run(stmt *sql.Stmt, ctx context.Context) (any, error) {
res, err := stmt.ExecContext(ctx, query.Params...)
if err != nil {
return nil, fmt.Errorf("query has failed: %s", err)
}
lastInsertId, err := res.LastInsertId()
if err != nil {
return nil, fmt.Errorf("failed to get last insert ID: %s", err)
}
affectedRows, err := res.RowsAffected()
if err != nil {
return nil, fmt.Errorf("failed to get affected rows: %s", err)
}
returnMessage := fmt.Sprintf("%s inserted, last inserted ID: %d", retMsg(affectedRows), lastInsertId)
return returnMessage, nil
}
func (query *AffectedRows) run(stmt *sql.Stmt, ctx context.Context) (any, error) {
res, err := stmt.ExecContext(ctx, query.Params...)
if err != nil {
return nil, fmt.Errorf("Query has failed: %s", err)
}
affectedRows, err := res.RowsAffected()
if err != nil {
return nil, fmt.Errorf("failed to get affected rows: %s", err)
}
returnMessage := fmt.Sprintf("%s affected", retMsg(affectedRows))
return returnMessage, nil
}
func returnRowsAsMap(rows *sql.Rows) (any, error) {
// Get column names
columns, err := rows.Columns()
if err != nil {
return nil, fmt.Errorf("failed to get columns: %s", err)
}
// Make a slice for the values
values := make([]sql.RawBytes, len(columns))
scanArgs := make([]any, len(values))
for i := range values {
scanArgs[i] = &values[i]
}
rowsMap := make([]map[string]any, 0)
for rows.Next() {
// get RawBytes from data
err = rows.Scan(scanArgs...)
if err != nil {
return nil, fmt.Errorf("failed to scan rows: %s", err)
}
var value string
row := make(map[string]any)
for i, col := range values {
// Here we can check if the value is nil (NULL value)
if col == nil {
value = "NULL"
} else {
value = string(col)
}
row[columns[i]] = value
}
rowsMap = append(rowsMap, row)
}
return rowsMap, nil
}