App in Go

    The startup script given below uses and Go. Be sure to install the first.

    Create a working directory and use it to run from the command line the command to clone the GitHub repository:

    Next, from the same working directory, run the command to start the test app. The command will differ depending on the database to connect to.

    Local Docker

    Any database

    To connect to a locally deployed YDB database according to the Docker use case, run the following command in the default configuration:

    1. go run ./basic -ydb="grpc://localhost:2136?database=/local" )

    Go - 图2

    To run the example using any available YDB database, you need to know the and Database location.

    If authentication is enabled in the database, you also need to choose the and obtain secrets: a token or username/password.

    Run the command as follows:

    1. ( export <auth_mode_var>="<auth_mode_value>" && cd ydb-go-examples && \
    2. go run ./basic -ydb="<endpoint>?database=<database>" )

    • <endpoint> is the Endpoint
    • <database> is the .
    • <auth_mode_var> is the Environment variable that determines the authentication mode.
    • <auth_mode_value> is the authentication parameter value for the selected mode.

    For example:

    Go - 图4

    Note

    If you previously reviewed the articles of the “Getting started” section, you must have used the necessary parameters when and can get them from the profile:

    1. ydb config profile get db1

    To interact with YDB, create an instance of the driver, client, and session:

    • The YDB driver lets the app and YDB interact at the transport layer. The driver must exist throughout the YDB access lifecycle and be initialized before creating a client or session.
    • The YDB client runs on top of the YDB driver and enables the handling of entities and transactions.
    • The YDB session contains information about executed transactions and prepared queries, and is part of the YDB client context.

    To work with YDB in Go, import the ydb-go-sdk driver package:

    1. import (
    2. // general imports
    3. "context"
    4. "path"
    5. // imports of ydb-go-sdk packages
    6. "github.com/ydb-platform/ydb-go-sdk/v3"
    7. "github.com/ydb-platform/ydb-go-sdk/v3/table" // to work with the table service
    8. "github.com/ydb-platform/ydb-go-sdk/v3/table/options" // to work with the table service
    9. "github.com/ydb-platform/ydb-go-sdk/v3/table/result" // to work with the table service
    10. "github.com/ydb-platform/ydb-go-sdk/v3/table/result/named" // to work with the table service
    11. "github.com/ydb-platform/ydb-go-sdk-auth-environ" // for authentication using environment variables
    12. "github.com/ydb-platform/ydb-go-yc" // to work with YDB in Yandex.Cloud
    13. )

    Go - 图6

    App code snippet for driver initialization:

    The db object is an input point for working with YDB services.
    To work with the table service, use the db.Table() client.
    The client of the table service provides an API for making queries to tables.
    The most popular method is db.Table().Do(ctx, op). It implements background session creation and repeated attempts to perform the op user operation where the created session is passed to the user-defined code.
    The session has an exhaustive API that lets you perform DDL, DML, DQL, and TCL requests.

    Creating tables to be used in operations on a test app. This step results in the creation of DB tables of the series directory data model:

    • Series
    • Seasons
    • Episodes

    To create tables, use the table.Session.CreateTable() method:

    1. err = db.Table().Do(
    2. ctx,
    3. func(ctx context.Context, s table.Session) (err error) {
    4. return s.CreateTable(ctx, path.Join(db.Name(), "series"),
    5. options.WithColumn("series_id", types.Optional(types.TypeUint64)),
    6. options.WithColumn("series_info", types.Optional(types.TypeUTF8)),
    7. options.WithColumn("release_date", types.Optional(types.TypeDate)),
    8. options.WithColumn("comment", types.Optional(types.TypeUTF8)),
    9. options.WithPrimaryKeyColumn("series_id"),
    10. )
    11. },
    12. )
    13. if err != nil {
    14. // handling the situation when the request failed
    15. }

    Go - 图8

    You can use the table.Session.DescribeTable() method to output information about the table structure and make sure that it was properly created:

    1. err = db.Table().Do(
    2. ctx,
    3. func(ctx context.Context, s table.Session) (err error) {
    4. desc, err := s.DescribeTable(ctx, path.Join(db.Name(), "series"))
    5. if err != nil {
    6. return
    7. }
    8. log.Printf("> describe table: %s\n", tableName)
    9. for _, c := range desc.Columns {
    10. log.Printf(" > column, name: %s, %s\n", c.Type, c.Name)
    11. }
    12. return
    13. }
    14. )
    15. if err != nil {
    16. // handling the situation when the request failed
    17. }

    Retrieving data using a SELECT statement in . Handling the retrieved data selection in the app.

    To execute YQL queries, use the table.Session.Execute() method.
    The SDK lets you explicitly control the execution of transactions and configure the transaction execution mode using the table.TxControl structure.

    Go - 图10

    Making a scan query that results in a data stream. Streaming lets you read an unlimited number of rows and amount of data.

    To execute scan queries, use the table.Session.StreamExecuteScanQuery() method.

    1. var (
    2. query = `
    3. DECLARE $series AS List<UInt64>;
    4. SELECT series_id, season_id, title, first_aired
    5. FROM seasons
    6. WHERE series_id IN $series
    7. `
    8. res result.StreamResult
    9. )
    10. err = c.Do(
    11. ctx,
    12. func(ctx context.Context, s table.Session) (err error) {
    13. res, err = s.StreamExecuteScanQuery(ctx, query,
    14. table.NewQueryParameters(
    15. types.ListValue(
    16. types.Uint64Value(1),
    17. ),
    18. ),
    19. ),
    20. )
    21. if err != nil {
    22. return err
    23. }
    24. defer func() {
    25. _ = res.Close() // making sure the result is closed
    26. }()
    27. var (
    28. seriesID uint64
    29. seasonID uint64
    30. title string
    31. date time.Time
    32. )
    33. log.Print("\n> scan_query_select:")
    34. for res.NextResultSet(ctx) {
    35. if err = res.Err(); err != nil {
    36. return err
    37. }
    38. for res.NextRow() {
    39. // named.OptionalOrDefault lets you "deploy" optional
    40. // results or use the default value of the go type
    41. err = res.ScanNamed(
    42. named.OptionalOrDefault("series_id", &seriesID),
    43. named.OptionalOrDefault("season_id", &seasonID),
    44. named.OptionalOrDefault("title", &title),
    45. named.OptionalOrDefault("first_aired", &date),
    46. )
    47. if err != nil {
    48. return err
    49. }
    50. log.Printf("# Season, SeriesId: %d, SeasonId: %d, Title: %s, Air date: %s", seriesID, seasonID, title, date)
    51. }
    52. }
    53. return res.Err()
    54. },
    55. )
    56. if err != nil {
    57. // handling the query execution error
    58. }

    Note

    Sample code of a test app that uses archived of versions the Go SDK:

    • is available at this link,
    • is available at this link.