-
Notifications
You must be signed in to change notification settings - Fork 71
/
example_test.go
512 lines (459 loc) · 12.5 KB
/
example_test.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
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//go:build go1.23
package ydb_test
import (
"context"
"database/sql"
"fmt"
"io"
"log"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/encoding/gzip"
"github.com/ydb-platform/ydb-go-sdk/v3"
"github.com/ydb-platform/ydb-go-sdk/v3/balancers"
"github.com/ydb-platform/ydb-go-sdk/v3/config"
"github.com/ydb-platform/ydb-go-sdk/v3/query"
"github.com/ydb-platform/ydb-go-sdk/v3/retry"
"github.com/ydb-platform/ydb-go-sdk/v3/table"
"github.com/ydb-platform/ydb-go-sdk/v3/table/result/named"
"github.com/ydb-platform/ydb-go-sdk/v3/table/types"
"github.com/ydb-platform/ydb-go-sdk/v3/topic/topicoptions"
)
//nolint:testableexamples, nonamedreturns
func Example_query() {
ctx := context.TODO()
db, err := ydb.Open(ctx, "grpc://localhost:2136/local")
if err != nil {
panic(err)
}
defer db.Close(ctx) // cleanup resources
materializedResult, err := db.Query().Query( // Do retry operation on errors with best effort
ctx, // context manage exiting from Do
`SELECT $id as myId, $str as myStr`,
query.WithParameters(
ydb.ParamsBuilder().
Param("$id").Uint64(42).
Param("$str").Text("my string").
Build(),
),
query.WithIdempotent(),
)
if err != nil {
panic(err)
}
defer func() { _ = materializedResult.Close(ctx) }() // cleanup resources
for rs, err := range materializedResult.ResultSets(ctx) {
if err != nil {
panic(err)
}
for row, err := range rs.Rows(ctx) {
if err != nil {
panic(err)
}
type myStruct struct {
ID uint64 `sql:"id"`
Str string `sql:"myStr"`
}
var s myStruct
if err = row.ScanStruct(&s); err != nil {
panic(err)
}
}
}
if err != nil {
panic(err)
}
}
//nolint:testableexamples, nonamedreturns
func Example_table() {
ctx := context.TODO()
db, err := ydb.Open(ctx, "grpc://localhost:2136/local")
if err != nil {
log.Fatal(err)
}
defer db.Close(ctx) // cleanup resources
var (
query = `SELECT 42 as id, "my string" as myStr`
id int32 // required value
myStr string // optional value
)
err = db.Table().Do( // Do retry operation on errors with best effort
ctx, // context manage exiting from Do
func(ctx context.Context, s table.Session) (err error) { // retry operation
_, res, err := s.Execute(ctx, table.DefaultTxControl(), query, nil)
if err != nil {
return err // for auto-retry with driver
}
defer res.Close() // cleanup resources
if err = res.NextResultSetErr(ctx); err != nil { // check single result set and switch to it
return err // for auto-retry with driver
}
for res.NextRow() { // iterate over rows
err = res.ScanNamed(
named.Required("id", &id),
named.OptionalWithDefault("myStr", &myStr),
)
if err != nil {
return err // generally scan error not retryable, return it for driver check error
}
log.Printf("id=%v, myStr='%s'\n", id, myStr)
}
return res.Err() // return finally result error for auto-retry with driver
},
table.WithIdempotent(),
)
if err != nil {
log.Printf("unexpected error: %v", err)
}
}
//nolint:testableexamples
func Example_databaseSQL() {
db, err := sql.Open("ydb", "grpc://localhost:2136/local")
if err != nil {
log.Fatal(err)
}
defer func() { _ = db.Close() }() // cleanup resources
db.SetMaxOpenConns(100)
db.SetMaxIdleConns(100)
db.SetConnMaxIdleTime(time.Second) // workaround for background keep-aliving of YDB sessions
var (
id int32 // required value
myStr string // optional value
)
// retry transaction
err = retry.DoTx(context.TODO(), db, func(ctx context.Context, tx *sql.Tx) error {
row := tx.QueryRowContext(ctx, `SELECT 42 as id, "my string" as myStr`)
if err = row.Scan(&id, &myStr); err != nil {
return err
}
log.Printf("id=%v, myStr='%s'\n", id, myStr)
return nil
}, retry.WithIdempotent(true))
if err != nil {
log.Printf("query failed: %v", err)
}
}
//nolint:testableexamples
func Example_databaseSQLBindNumericArgs() {
db, err := sql.Open("ydb",
"grpc://localhost:2136/local?go_query_bind=declare,numeric",
)
if err != nil {
log.Fatal(err)
}
defer func() { _ = db.Close() }() // cleanup resources
var (
id int32 // required value
myStr string // optional value
)
// numeric args
row := db.QueryRowContext(context.TODO(), "SELECT $2, $1", 42, "my string")
if err = row.Scan(&myStr, &id); err != nil {
log.Printf("query failed: %v", err)
} else {
log.Printf("id=%v, myStr='%s'\n", id, myStr)
}
}
//nolint:testableexamples
func Example_databaseSQLBindNumericArgsOverConnector() {
var (
ctx = context.TODO()
nativeDriver = ydb.MustOpen(ctx, "grpc://localhost:2136/local")
db = sql.OpenDB(
ydb.MustConnector(nativeDriver,
ydb.WithAutoDeclare(),
ydb.WithNumericArgs(),
),
)
)
defer nativeDriver.Close(ctx) // cleanup resources
defer db.Close()
// numeric args
row := db.QueryRowContext(context.TODO(),
"SELECT $2, $1",
42, "my string",
)
var (
id int32 // required value
myStr string // optional value
)
if err := row.Scan(&myStr, &id); err != nil {
log.Printf("query failed: %v", err)
} else {
log.Printf("id=%v, myStr='%s'\n", id, myStr)
}
}
//nolint:testableexamples
func Example_databaseSQLBindPositionalArgs() {
db, err := sql.Open("ydb",
"grpc://localhost:2136/local?go_query_bind=declare,positional",
)
if err != nil {
log.Fatal(err)
}
defer func() { _ = db.Close() }() // cleanup resources
var (
id int32 // required value
myStr string // optional value
)
// positional args
row := db.QueryRowContext(context.TODO(), "SELECT ?, ?", 42, "my string")
if err = row.Scan(&id, &myStr); err != nil {
log.Printf("query failed: %v", err)
} else {
log.Printf("id=%v, myStr='%s'\n", id, myStr)
}
}
//nolint:testableexamples
func Example_databaseSQLBindPositionalArgsOverConnector() {
var (
ctx = context.TODO()
nativeDriver = ydb.MustOpen(ctx, "grpc://localhost:2136/local")
db = sql.OpenDB(
ydb.MustConnector(nativeDriver,
ydb.WithAutoDeclare(),
ydb.WithNumericArgs(),
),
)
)
defer nativeDriver.Close(ctx) // cleanup resources
defer db.Close()
// positional args
row := db.QueryRowContext(context.TODO(), "SELECT ?, ?", 42, "my string")
var (
id int32 // required value
myStr string // optional value
)
if err := row.Scan(&id, &myStr); err != nil {
log.Printf("query failed: %v", err)
} else {
log.Printf("id=%v, myStr='%s'\n", id, myStr)
}
}
//nolint:testableexamples
func Example_databaseSQLBindTablePathPrefix() {
db, err := sql.Open("ydb",
"grpc://localhost:2136/local?go_query_bind=table_path_prefix(/local/path/to/tables)",
)
if err != nil {
log.Fatal(err)
}
defer func() { _ = db.Close() }() // cleanup resources
var (
id int32 // required value
title string // optional value
)
// full table path is "/local/path/to/tables/series"
row := db.QueryRowContext(context.TODO(), "SELECT id, title FROM series")
if err = row.Scan(&id, &title); err != nil {
log.Printf("query failed: %v", err)
} else {
log.Printf("id=%v, title='%s'\n", id, title)
}
}
//nolint:testableexamples
func Example_databaseSQLBindTablePathPrefixOverConnector() {
var (
ctx = context.TODO()
nativeDriver = ydb.MustOpen(ctx, "grpc://localhost:2136/local")
db = sql.OpenDB(ydb.MustConnector(nativeDriver,
ydb.WithTablePathPrefix("/local/path/to/my/folder"),
))
)
// full table path is "/local/path/to/tables/series"
row := db.QueryRowContext(context.TODO(), "SELECT id, title FROM series")
var (
id int32 // required value
title string // optional value
)
if err := row.Scan(&id, &title); err != nil {
log.Printf("query failed: %v", err)
} else {
log.Printf("id=%v, title='%s'\n", id, title)
}
}
//nolint:testableexamples
func Example_databaseSQLBindAutoDeclare() {
db, err := sql.Open("ydb",
"grpc://localhost:2136/local?go_query_bind=declare",
)
if err != nil {
log.Fatal(err)
}
defer func() { _ = db.Close() }() // cleanup resources
var (
id int32 // required value
title string // optional value
)
row := db.QueryRowContext(context.TODO(), "SELECT $id, $title",
table.ValueParam("$id", types.Uint64Value(42)),
table.ValueParam("$title", types.TextValue("title")),
)
if err = row.Scan(&id, &title); err != nil {
log.Printf("query failed: %v", err)
} else {
log.Printf("id=%v, title='%s'\n", id, title)
}
}
//nolint:testableexamples
func Example_databaseSQLBindAutoDeclareOverConnector() {
var (
ctx = context.TODO()
nativeDriver = ydb.MustOpen(ctx, "grpc://localhost:2136/local")
db = sql.OpenDB(ydb.MustConnector(nativeDriver,
ydb.WithAutoDeclare(),
))
)
row := db.QueryRowContext(context.TODO(), "SELECT $id, $title",
table.ValueParam("$id", types.Uint64Value(42)),
table.ValueParam("$title", types.TextValue("title")),
)
var (
id int32 // required value
title string // optional value
)
if err := row.Scan(&id, &title); err != nil {
log.Printf("query failed: %v", err)
} else {
log.Printf("id=%v, title='%s'\n", id, title)
}
}
//nolint:testableexamples
func Example_topic() {
ctx := context.TODO()
db, err := ydb.Open(ctx, "grpc://localhost:2136/local")
if err != nil {
fmt.Printf("failed connect: %v", err)
return
}
defer db.Close(ctx) // cleanup resources
reader, err := db.Topic().StartReader("consumer", topicoptions.ReadTopic("/topic/path"))
if err != nil {
fmt.Printf("failed start reader: %v", err)
return
}
for {
mess, err := reader.ReadMessage(ctx)
if err != nil {
fmt.Printf("failed start reader: %v", err)
return
}
content, err := io.ReadAll(mess)
if err != nil {
fmt.Printf("failed start reader: %v", err)
return
}
fmt.Println(string(content))
}
}
//nolint:testableexamples
func Example_scripting() {
ctx := context.TODO()
db, err := ydb.Open(ctx, "grpc://localhost:2136/local")
if err != nil {
fmt.Printf("failed to connect: %v", err)
return
}
defer db.Close(ctx) // cleanup resources
if err = retry.Retry(ctx, func(ctx context.Context) (err error) { //nolint:nonamedreturns
res, err := db.Scripting().Execute(
ctx,
"SELECT 1+1",
table.NewQueryParameters(),
)
if err != nil {
return err
}
defer res.Close() // cleanup resources
if !res.NextResultSet(ctx) {
return retry.RetryableError(
fmt.Errorf("no result sets"), //nolint:goerr113
retry.WithBackoff(retry.TypeNoBackoff),
)
}
if !res.NextRow() {
return retry.RetryableError(
fmt.Errorf("no rows"), //nolint:goerr113
retry.WithBackoff(retry.TypeSlowBackoff),
)
}
var sum int32
if err = res.Scan(&sum); err != nil {
return fmt.Errorf("scan failed: %w", err)
}
if sum != 2 {
return fmt.Errorf("unexpected sum: %v", sum) //nolint:goerr113
}
return res.Err()
}, retry.WithIdempotent(true)); err != nil {
fmt.Printf("Execute failed: %v", err)
}
}
//nolint:testableexamples
func Example_discovery() {
ctx := context.TODO()
db, err := ydb.Open(ctx, "grpc://localhost:2136/local")
if err != nil {
fmt.Printf("failed to connect: %v", err)
return
}
defer db.Close(ctx) // cleanup resources
endpoints, err := db.Discovery().Discover(ctx)
if err != nil {
fmt.Printf("discover failed: %v", err)
return
}
fmt.Printf("%s endpoints:\n", db.Name())
for i, e := range endpoints {
fmt.Printf("%d) %s\n", i, e.String())
}
}
//nolint:testableexamples
func Example_enableGzipCompressionForAllRequests() {
ctx := context.TODO()
db, err := ydb.Open(
ctx,
"grpc://localhost:2135/local",
ydb.WithAnonymousCredentials(),
ydb.With(config.WithGrpcOptions(
grpc.WithDefaultCallOptions(
grpc.UseCompressor(gzip.Name),
),
)),
)
if err != nil {
fmt.Printf("Driver failed: %v", err)
}
defer db.Close(ctx) // cleanup resources
fmt.Printf("connected to %s, database '%s'", db.Endpoint(), db.Name())
}
//nolint:testableexamples
func ExampleOpen() {
ctx := context.TODO()
db, err := ydb.Open(ctx, "grpc://localhost:2135/local")
if err != nil {
fmt.Printf("Driver failed: %v", err)
}
defer db.Close(ctx) // cleanup resources
fmt.Printf("connected to %s, database '%s'", db.Endpoint(), db.Name())
}
//nolint:testableexamples
func ExampleOpen_advanced() {
ctx := context.TODO()
db, err := ydb.Open(
ctx,
"grpc://localhost:2135/local",
ydb.WithAnonymousCredentials(),
ydb.WithBalancer(
balancers.PreferLocationsWithFallback(
balancers.RandomChoice(), "a", "b",
),
),
ydb.WithSessionPoolSizeLimit(100),
)
if err != nil {
fmt.Printf("Driver failed: %v", err)
}
defer db.Close(ctx) // cleanup resources
fmt.Printf("connected to %s, database '%s'", db.Endpoint(), db.Name())
}