Skip to content

Commit 2121725

Browse files
authored
Merge pull request #197 from ydb-platform/readme
simplify README.md + add table.DefaultTxControl()
2 parents f54c60d + 13dbdea commit 2121725

15 files changed

+248
-77
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
* Added `table.DefaultTxControl()` transaction control creator with serializable read-write isolation mode and auto-commit
2+
* Fixed passing nil query parameters
13
* Fixed locking of cluster during call `cluster.Get`
24

35
## v3.19.1

CREDENTIALS.md

Lines changed: 0 additions & 13 deletions
This file was deleted.

DEBUG.md

Lines changed: 0 additions & 13 deletions
This file was deleted.

ENVIRON.md

Lines changed: 0 additions & 10 deletions
This file was deleted.

README.md

Lines changed: 84 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,96 @@
1-
# ydb-go-sdk
1+
# `ydb-go-sdk` - native Go's driver for [YDB](https://github.com/ydb-platform/ydb).
22

33
[![PkgGoDev](https://pkg.go.dev/badge/github.com/ydb-platform/ydb-go-sdk/v3)](https://pkg.go.dev/github.com/ydb-platform/ydb-go-sdk/v3)
4-
[![GoDoc](https://godoc.org/github.com/ydb-platform/ydb-go-sdk/v3?status.svg)](https://godoc.org/github.com/ydb-platform/ydb-go-sdk/v3)
54
![tests](https://github.com/ydb-platform/ydb-go-sdk/workflows/tests/badge.svg?branch=master)
65
![lint](https://github.com/ydb-platform/ydb-go-sdk/workflows/lint/badge.svg?branch=master)
76
[![Go Report Card](https://goreportcard.com/badge/github.com/ydb-platform/ydb-go-sdk/v3)](https://goreportcard.com/report/github.com/ydb-platform/ydb-go-sdk/v3)
87
[![codecov](https://codecov.io/gh/ydb-platform/ydb-go-sdk/branch/master/graph/badge.svg?precision=2)](https://app.codecov.io/gh/ydb-platform/ydb-go-sdk)
98

10-
[YDB](https://github.com/ydb-platform/ydb) native Go's driver.
9+
Supports `table`, `discovery`, `coordination`, `ratelimiter`, `scheme` and `scripting` clients for `YDB`.
10+
`YDB` is an open-source Distributed SQL Database that combines high availability and scalability with strict consistency and ACID transactions.
1111

12-
Supports `table`, `discovery`, `coordination`, `ratelimiter`, `scheme` and `scripting` clients for `YDB`.
12+
## Example Usage <a name="example"></a>
1313

14-
Simple example see in [example](example_table_test.go). More examples of usage placed in [examples](https://github.com/ydb-platform/ydb-go-examples) repository.
14+
* connect to YDB
15+
```
16+
db, err := ydb.New(ctx,
17+
ydb.WithConnectionString("grpcs://localhost:2135/?database=/local"),
18+
ydb.WithAnonymousCredentials(),
19+
)
20+
if err != nil {
21+
log.Fatal(err)
22+
}
23+
```
24+
* execute `SELECT` query
25+
```
26+
const query = `SELECT 42 as id, "myStr" as myStr;`
27+
28+
// Do retry operation on errors with best effort
29+
queryErr := db.Table().Do(ctx, func(ctx context.Context, s table.Session) (err error) {
30+
_, res, err := s.Execute(ctx, table.DefaultTxControl(), query, nil)
31+
if err != nil {
32+
return err
33+
}
34+
defer res.Close()
35+
if err = res.NextResultSetErr(ctx); err != nil {
36+
return err
37+
}
38+
for res.NextRow() {
39+
var id int32
40+
var myStr string
41+
err = res.ScanNamed(named.Required("id", &id),named.OptionalWithDefault("myStr", &myStr))
42+
if err != nil {
43+
log.Fatal(err)
44+
}
45+
log.Printf("id=%v, myStr='%s'\n", id, myStr)
46+
}
47+
return res.Err() // for driver retry if not nil
48+
})
49+
if queryErr != nil {
50+
log.Fatal(queryErr)
51+
}
52+
```
53+
More examples of usage placed in [examples](https://github.com/ydb-platform/ydb-go-examples) repository.
54+
55+
## Credentials <a name="credentials"></a>
56+
57+
Driver contains two options for making simple `credentials.Credentials`:
58+
- `ydb.WithAnonymousCredentials()`
59+
- `ydb.WithAccessTokenCredentials("token")`
60+
61+
Another variants of `credentials.Credentials` object provides with external packages:
62+
63+
Package | Type | Description | Link of example usage
64+
--- | --- |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| ---
65+
[ydb-go-yc](https://github.com/ydb-platform/ydb-go-yc) | credentials | credentials provider for Yandex.Cloud | [yc.WithServiceAccountKeyFileCredentials](https://github.com/ydb-platform/ydb-go-yc/blob/master/internal/cmd/connect/main.go#L22)
66+
[yc.WithInternalCA](https://github.com/ydb-platform/ydb-go-yc/blob/master/internal/cmd/connect/main.go#L22) [yc.WithMetadataCredentials](https://github.com/ydb-platform/ydb-go-yc/blob/master/internal/cmd/connect/main.go#L24)
67+
[ydb-go-yc-metadata](https://github.com/ydb-platform/ydb-go-yc-metadata) | credentials | metadata credentials provider for Yandex.Cloud | [yc.WithInternalCA](https://github.com/ydb-platform/ydb-go-yc-metadata/blob/master/options.go#L23) [yc.WithCredentials](https://github.com/ydb-platform/ydb-go-yc-metadata/blob/master/options.go#L17)
68+
[ydb-go-sdk-auth-environ](https://github.com/ydb-platform/ydb-go-sdk-auth-environ) | credentials | create credentials from environ | [ydbEnviron.WithEnvironCredentials](https://github.com/ydb-platform/ydb-go-sdk-auth-environ/blob/master/env.go#L11)
69+
70+
## Ecosystem of debug tools over `ydb-go-sdk` <a name="debug"></a>
71+
72+
Package `ydb-go-sdk` provide debugging over trace events in package `trace`.
73+
Next packages provide debug tooling:
74+
75+
Package | Type | Description | Link of example usage
76+
--- | --- |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| ---
77+
[ydb-go-sdk-zap](https://github.com/ydb-platform/ydb-go-sdk-zap) | logging | logging ydb-go-sdk events with zap package | [ydbZap.WithTraces](https://github.com/ydb-platform/ydb-go-sdk-zap/blob/master/internal/cmd/bench/main.go#L64)
78+
[ydb-go-sdk-zerolog](https://github.com/ydb-platform/ydb-go-sdk-zap) | logging | logging ydb-go-sdk events with zerolog package | [ydbZerolog.WithTraces](https://github.com/ydb-platform/ydb-go-sdk-zerolog/blob/master/internal/cmd/bench/main.go#L47)
79+
[ydb-go-sdk-metrics](https://github.com/ydb-platform/ydb-go-sdk-metrics) | metrics | common metrics of ydb-go-sdk. Package declare interfaces such as `Registry`, `GaugeVec` and `Gauge` and use it for traces |
80+
[ydb-go-sdk-prometheus](https://github.com/ydb-platform/ydb-go-sdk-prometheus) | metrics | prometheus wrapper over [ydb-go-sdk-metrics](https://github.com/ydb-platform/ydb-go-sdk-metrics) | [ydbPrometheus.WithTraces](https://github.com/ydb-platform/ydb-go-sdk-prometheus/blob/master/internal/cmd/bench/main.go#L56)
81+
[ydb-go-sdk-opentracing](https://github.com/ydb-platform/ydb-go-sdk-opentracing) | tracing | opentracing plugin for trace internal ydb-go-sdk calls | [ydbOpentracing.WithTraces](https://github.com/ydb-platform/ydb-go-sdk-opentracing/blob/master/internal/cmd/bench/main.go#L86)
82+
83+
## Environment variables <a name="environ"></a>
84+
85+
`ydb-go-sdk` supports next environment variables which redefines default behavior of driver
86+
87+
Name | Type | Default | Description
88+
--- | --- | --- | ---
89+
`YDB_SSL_ROOT_CERTIFICATES_FILE` | `string` | | path to certificates file
90+
`YDB_LOG_SEVERITY_LEVEL` | `string` | `quiet` | severity logging level of internal driver logger. Supported: `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `quiet`
91+
`YDB_LOG_NO_COLOR` | `bool` | `false` | set any non empty value to disable colouring logs with internal driver logger
92+
`GRPC_GO_LOG_VERBOSITY_LEVEL` | `integer` | | set to `99` to see grpc logs
93+
`GRPC_GO_LOG_SEVERITY_LEVEL` | `string` | | set to `info` to see grpc logs
1594
16-
See also [CREDENTIALS.md](CREDENTIALS.md) about supported YDB credentials.
1795
18-
See [DEBUG.md](DEBUG.md) about supported debug tooling over `ydb-go-sdk`.
1996
20-
See [ENVIRON.md](ENVIRON.md) about supported environment variables of `ydb-go-sdk`.

connection.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ func (c *connection) Scripting() scripting.Client {
223223
return c.scripting
224224
}
225225

226-
// New connects to name and return name runtime holder
226+
// New connects to database and return driver runtime holder
227227
func New(ctx context.Context, opts ...Option) (_ Connection, err error) {
228228
c := &connection{
229229
opts: opts,

doc.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// Package ydb-go-sdk - native Go's driver for YDB.
2+
/*
3+
Supports table, discovery, coordination, ratelimiter, scheme and scripting clients for YDB.
4+
YDB is an open-source Distributed SQL Database that combines high availability and scalability
5+
with strict consistency and ACID transactions.
6+
*/
7+
package ydb

errors.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,60 +10,78 @@ import (
1010
"github.com/ydb-platform/ydb-go-sdk/v3/ratelimiter"
1111
)
1212

13+
// IterateByIssues helps to iterate over internal issues of operation error
1314
func IterateByIssues(err error, it func(message string, code Ydb.StatusIds_StatusCode, severity uint32)) {
1415
xerrors.IterateByIssues(err, it)
1516
}
1617

18+
// IsTimeoutError checks whether given err is a some timeout error (context, transport or operation)
1719
func IsTimeoutError(err error) bool {
1820
return xerrors.IsTimeoutError(err)
1921
}
2022

23+
// IsTransportError checks whether given err is a transport (grpc) error
2124
func IsTransportError(err error, codes ...grpcCodes.Code) bool {
2225
return xerrors.IsTransportError(err, codes...)
2326
}
2427

28+
// Error is an interface of error which reports about error code and error name
2529
type Error xerrors.Error
2630

31+
// TransportError checks when given error is a transport error and returns description of transport error
2732
func TransportError(err error) Error {
2833
return xerrors.TransportError(err)
2934
}
3035

36+
// IsYdbError reports when given error is and ydb error (transport, operation or internal driver error)
3137
func IsYdbError(err error) bool {
3238
return xerrors.IsYdb(err)
3339
}
3440

41+
// IsOperationError reports whether any error is an operation error with one of passed codes
42+
// If codes not defined IsOperationError returns true on error is an operation error
3543
func IsOperationError(err error, codes ...Ydb.StatusIds_StatusCode) bool {
3644
return xerrors.IsOperationError(err, codes...)
3745
}
3846

47+
// OperationError returns operation error description
48+
// If given err is not an operation error - returns nil
3949
func OperationError(err error) Error {
4050
return xerrors.OperationError(err)
4151
}
4252

53+
// IsOperationErrorOverloaded checks whether given err is an operation error with code Overloaded
4354
func IsOperationErrorOverloaded(err error) bool {
4455
return IsOperationError(err, Ydb.StatusIds_OVERLOADED)
4556
}
4657

58+
// IsOperationErrorUnavailable checks whether given err is an operation error with code Unavailable
4759
func IsOperationErrorUnavailable(err error) bool {
4860
return IsOperationError(err, Ydb.StatusIds_UNAVAILABLE)
4961
}
5062

63+
// IsOperationErrorAlreadyExistsError checks whether given err is an operation error with code AlreadyExistsError
5164
func IsOperationErrorAlreadyExistsError(err error) bool {
5265
return IsOperationError(err, Ydb.StatusIds_ALREADY_EXISTS)
5366
}
5467

68+
// IsOperationErrorNotFoundError checks whether given err is an operation error with code NotFoundError
5569
func IsOperationErrorNotFoundError(err error) bool {
5670
return IsOperationError(err, Ydb.StatusIds_NOT_FOUND)
5771
}
5872

73+
// IsOperationErrorSchemeError checks whether given err is an operation error with code SchemeError
5974
func IsOperationErrorSchemeError(err error) bool {
6075
return IsOperationError(err, Ydb.StatusIds_SCHEME_ERROR)
6176
}
6277

78+
// IsRatelimiterAcquireError checks whether given err is an ratelimiter acquire error
6379
func IsRatelimiterAcquireError(err error) bool {
6480
return ratelimiterErrors.IsAcquireError(err)
6581
}
6682

83+
// ToRatelimiterAcquireError casts given err to ratelimiter.AcquireError
84+
// If given err is not ratelimiter acquire error - returns nil
6785
func ToRatelimiterAcquireError(err error) ratelimiter.AcquireError {
6886
return ratelimiterErrors.ToAcquireError(err)
6987
}

example_table_bulk_upsert_test.go

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package ydb_test
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"log"
7+
"time"
8+
9+
"github.com/ydb-platform/ydb-go-sdk/v3"
10+
"github.com/ydb-platform/ydb-go-sdk/v3/table"
11+
"github.com/ydb-platform/ydb-go-sdk/v3/table/types"
12+
)
13+
14+
func Example_tableBulkUpsert() {
15+
ctx := context.Background()
16+
db, err := ydb.New(ctx,
17+
ydb.WithConnectionString("grpcs://localhost:2135/?database=/local"),
18+
ydb.WithAnonymousCredentials(),
19+
)
20+
if err != nil {
21+
log.Fatal(err)
22+
}
23+
defer func() {
24+
_ = db.Close(ctx)
25+
}()
26+
type logMessage struct {
27+
App string
28+
Host string
29+
Timestamp time.Time
30+
HTTPCode uint32
31+
Message string
32+
}
33+
// prepare native go data
34+
const batchSize = 10000
35+
logs := make([]logMessage, 0, batchSize)
36+
for i := 0; i < batchSize; i++ {
37+
message := logMessage{
38+
App: fmt.Sprintf("App_%d", i/256),
39+
Host: fmt.Sprintf("192.168.0.%d", i%256),
40+
Timestamp: time.Now().Add(time.Millisecond * time.Duration(i%1000)),
41+
HTTPCode: 200,
42+
}
43+
if i%2 == 0 {
44+
message.Message = "GET / HTTP/1.1"
45+
} else {
46+
message.Message = "GET /images/logo.png HTTP/1.1"
47+
}
48+
logs = append(logs, message)
49+
}
50+
// execute bulk upsert with native ydb data
51+
err = db.Table().Do( // Do retry operation on errors with best effort
52+
ctx, // context manage exiting from Do
53+
func(ctx context.Context, s table.Session) (err error) { // retry operation
54+
rows := make([]types.Value, 0, len(logs))
55+
for _, msg := range logs {
56+
rows = append(rows, types.StructValue(
57+
types.StructFieldValue("App", types.UTF8Value(msg.App)),
58+
types.StructFieldValue("Host", types.UTF8Value(msg.Host)),
59+
types.StructFieldValue("Timestamp", types.TimestampValueFromTime(msg.Timestamp)),
60+
types.StructFieldValue("HTTPCode", types.Uint32Value(msg.HTTPCode)),
61+
types.StructFieldValue("Message", types.UTF8Value(msg.Message)),
62+
))
63+
}
64+
return s.BulkUpsert(ctx, "/local/bulk_upsert_example", types.ListValue(rows...))
65+
},
66+
)
67+
if err != nil {
68+
log.Printf("unexpected error: %v", err)
69+
}
70+
}

example_table_create_table_test.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package ydb_test
2+
3+
import (
4+
"context"
5+
"log"
6+
"path"
7+
8+
"github.com/ydb-platform/ydb-go-sdk/v3"
9+
"github.com/ydb-platform/ydb-go-sdk/v3/table"
10+
"github.com/ydb-platform/ydb-go-sdk/v3/table/options"
11+
"github.com/ydb-platform/ydb-go-sdk/v3/table/types"
12+
)
13+
14+
func Example_tableCreateTable() {
15+
ctx := context.Background()
16+
db, err := ydb.New(ctx,
17+
ydb.WithConnectionString("grpcs://localhost:2135/?database=/local"),
18+
ydb.WithAnonymousCredentials(),
19+
)
20+
if err != nil {
21+
log.Fatal(err)
22+
}
23+
defer func() {
24+
_ = db.Close(ctx)
25+
}()
26+
err = db.Table().Do(
27+
ctx,
28+
func(ctx context.Context, s table.Session) (err error) {
29+
return s.CreateTable(ctx, path.Join(db.Name(), "series"),
30+
options.WithColumn("series_id", types.Optional(types.TypeUint64)),
31+
options.WithColumn("title", types.Optional(types.TypeUTF8)),
32+
options.WithColumn("series_info", types.Optional(types.TypeUTF8)),
33+
options.WithColumn("release_date", types.Optional(types.TypeDate)),
34+
options.WithColumn("comment", types.Optional(types.TypeUTF8)),
35+
options.WithPrimaryKeyColumn("series_id"),
36+
)
37+
},
38+
)
39+
if err != nil {
40+
log.Printf("unexpected error: %v", err)
41+
}
42+
}

0 commit comments

Comments
 (0)