-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbind.go
More file actions
353 lines (300 loc) · 8.49 KB
/
bind.go
File metadata and controls
353 lines (300 loc) · 8.49 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
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package pg
import (
"context"
"encoding/json"
"fmt"
"maps"
"os"
"strings"
"sync"
// Packages
pgx "github.com/jackc/pgx/v5"
types "github.com/mutablelogic/go-pg/pkg/types"
)
///////////////////////////////////////////////////////////////////////////////
// TYPES
// Bind represents a set of variables and arguments to be used in a query.
// The vars are substituted in the query string itself, while the args are
// passed as arguments to the query.
type Bind struct {
sync.RWMutex
vars pgx.NamedArgs
dblink string // Used when executing transactions remotely
}
///////////////////////////////////////////////////////////////////////////////
// LIFECYCLE
// NewBind creates a new Bind object with the given name/value pairs.
// Returns nil if the number of arguments is not even.
func NewBind(pairs ...any) *Bind {
if len(pairs)%2 != 0 {
return nil
}
// Populate the vars map
vars := make(pgx.NamedArgs, len(pairs)>>1)
for i := 0; i < len(pairs); i += 2 {
if key, ok := pairs[i].(string); !ok || key == "" {
return nil
} else {
vars[key] = pairs[i+1]
}
}
// Return the Bind object
return &Bind{vars: vars}
}
// Copy creates a copy of the bind object with additional name/value pairs.
func (bind *Bind) Copy(pairs ...any) *Bind {
if len(pairs)%2 != 0 {
return nil
}
if len(pairs) == 0 {
bind.RLock()
defer bind.RUnlock()
return &Bind{vars: maps.Clone(bind.vars), dblink: bind.dblink}
}
// Lock before copying
varsCopy := func() pgx.NamedArgs {
bind.RLock()
defer bind.RUnlock()
c := make(pgx.NamedArgs, len(bind.vars)+(len(pairs)>>1))
maps.Copy(c, bind.vars)
return c
}()
for i := 0; i < len(pairs); i += 2 {
if key, ok := pairs[i].(string); !ok || key == "" {
return nil
} else {
varsCopy[key] = pairs[i+1]
}
}
// Return the copied Bind object
return &Bind{vars: varsCopy, dblink: bind.dblink}
}
// Return a new bind object with the given database link
func (bind *Bind) withRemote(database string) *Bind {
varsCopy := make(pgx.NamedArgs, len(bind.vars))
maps.Copy(varsCopy, bind.vars)
// Return the copied Bind object
return &Bind{vars: varsCopy, dblink: "dbname=" + types.Quote(database)}
}
// Return a new bind object with one or more sets of queries
func (bind *Bind) withQueries(queries ...*Queries) *Bind {
if len(queries) == 0 {
return bind
}
// Make a copy of the bind vars
varsCopy := make(pgx.NamedArgs, len(bind.vars))
maps.Copy(varsCopy, bind.vars)
// Iterate through queries
for _, q := range queries {
for _, key := range q.Keys() {
varsCopy[key] = q.Query(key)
}
}
// Return the copied Bind object
return &Bind{vars: varsCopy}
}
///////////////////////////////////////////////////////////////////////////////
// STRINGIFY
func (bind *Bind) MarshalJSON() ([]byte, error) {
return json.Marshal(bind.vars)
}
func (bind *Bind) String() string {
data, err := json.MarshalIndent(bind.vars, "", " ")
if err != nil {
return err.Error()
} else {
return string(data)
}
}
///////////////////////////////////////////////////////////////////////////////
// PUBLIC METHODS
// Set sets a bind var and returns the parameter name.
func (bind *Bind) Set(key string, value any) string {
bind.Lock()
defer bind.Unlock()
if key == "" {
return ""
}
bind.vars[key] = value
return "@" + key
}
// Get returns a bind var by key.
func (bind *Bind) Get(key string) any {
bind.RLock()
defer bind.RUnlock()
return bind.vars[key]
}
// Has returns true if there is a bind var with the given key.
func (bind *Bind) Has(key string) bool {
bind.RLock()
defer bind.RUnlock()
_, ok := bind.vars[key]
return ok
}
// Del deletes a bind var.
func (bind *Bind) Del(key string) {
bind.Lock()
defer bind.Unlock()
delete(bind.vars, key)
}
// Join joins a bind var with a separator when it is a
// []any and returns the result as a string. Returns
// an empty string if the key does not exist.
func (bind *Bind) Join(key, sep string) string {
bind.RLock()
defer bind.RUnlock()
if value, ok := bind.vars[key]; !ok {
return ""
} else if v, ok := value.([]any); ok {
str := make([]string, len(v))
for i, value := range v {
str[i] = fmt.Sprint(value)
}
return strings.Join(str, sep)
} else {
return fmt.Sprint(value)
}
}
// Append appends a bind var to a list. Returns false if the key
// is not a list, or the value is not a list.
func (bind *Bind) Append(key string, value any) bool {
bind.Lock()
defer bind.Unlock()
// Create a new list if it doesn't exist
if _, ok := bind.vars[key]; !ok {
bind.vars[key] = make([]any, 0, 5)
}
// Check type
if _, ok := bind.vars[key].([]any); !ok {
return false
}
// Append value
bind.vars[key] = append(bind.vars[key].([]any), value)
// Return success
return true
}
///////////////////////////////////////////////////////////////////////////////
// PUBLIC METHODS - QUERY
// Query looks up a named query, sets the span name for OpenTelemetry tracing,
// and returns the resolved SQL string. The name should match a query key
// that was loaded via withQueries (e.g., "pgqueue.get").
func (bind *Bind) Query(name string) string {
bind.Set(TraceSpanNameArg, name)
return bind.Replace("${" + name + "}")
}
// Queue a query - for bulk operations
func (bind *Bind) queuerow(batch *pgx.Batch, query string, reader Reader) {
bind.RLock()
defer bind.RUnlock()
queuedquery := batch.Queue(bind.Replace(query), bind.vars)
queuedquery.QueryRow(func(row pgx.Row) error {
return reader.Scan(row)
})
}
///////////////////////////////////////////////////////////////////////////////
// PRIVATE METHODS - QUERY EXECUTION
func (bind *Bind) queryRow(ctx context.Context, conn pgx.Tx, query string) pgx.Row {
bind.RLock()
defer bind.RUnlock()
// dblink version
if bind.dblink != "" {
// 'as' is used to define the column names
var def string
if bind.Has("as") {
def = ` AS ` + bind.Get("as").(string)
}
// TODO: Attempt to unroll the @parameters in the query
return conn.QueryRow(ctx, replace(dblinkSelect, pgx.NamedArgs{
"conn": bind.dblink,
"query": bind.Replace(query),
"as": def,
}))
}
// normal version
return conn.QueryRow(ctx, bind.Replace(query), bind.vars)
}
func (bind *Bind) query(ctx context.Context, conn pgx.Tx, query string) (pgx.Rows, error) {
bind.RLock()
defer bind.RUnlock()
// dblink version
if bind.dblink != "" {
// 'as' is used to define the column names
var def string
if bind.Has("as") {
def = ` AS ` + bind.Get("as").(string)
}
return conn.Query(ctx, replace(dblinkSelect, pgx.NamedArgs{
"conn": bind.dblink,
"query": bind.Replace(query),
"as": def,
}))
}
// normal version
return conn.Query(ctx, bind.Replace(query), bind.vars)
}
func (bind *Bind) exec(ctx context.Context, conn pgx.Tx, query string) error {
bind.RLock()
defer bind.RUnlock()
// dblink version
if bind.dblink != "" {
// TODO: Attempt to unroll the parameters
_, err := conn.Exec(ctx, replace(dblinkExec, pgx.NamedArgs{
"conn": bind.dblink,
"query": bind.Replace(query),
}))
return err
}
// normal version
_, err := conn.Exec(ctx, bind.Replace(query), bind.vars)
return err
}
///////////////////////////////////////////////////////////////////////////////
// PRIVATE METHODS
// Replace returns a query string with ${subtitution} replaced by the values:
// - ${key} => value
// - ${'key'} => 'value'
// - ${"key"} => "value"
// - $1 => $1
// - $$ => $$
func (bind *Bind) Replace(query string) string {
// Perform the replacement
return replace(query, bind.vars)
}
func replace(query string, vars pgx.NamedArgs) string {
fetch := func(key string) string {
return fmt.Sprint(vars[key])
}
return os.Expand(query, func(key string) string {
if key == "$" { // $$ => $$
return "$$"
}
if types.IsNumeric(key) {
return "$" + key // $1 => $1
}
if types.IsSingleQuoted(key) { // ${'key'} => 'value'
// Special case where value is []string and single quote for IN (${key})
key := strings.Trim(key, "'")
value := vars[key]
switch v := value.(type) {
case []string:
result := make([]string, len(v))
for i, s := range v {
result[i] = types.Quote(s)
}
return strings.Join(result, ",")
default:
return types.Quote(fetch(key))
}
}
if types.IsDoubleQuoted(key) { // ${"key"} => "value"
return types.DoubleQuote(fetch(strings.Trim(key, "\"")))
}
return fetch(key) // ${key} => value
})
}
///////////////////////////////////////////////////////////////////////////////
// SQL
const (
dblinkSelect = "SELECT * FROM dblink(${'conn'}, ${'query'}, true)${as}"
dblinkExec = "SELECT dblink_exec(${'conn'}, ${'query'}, true)"
)