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:
go run ./basic -ydb="grpc://localhost:2136?database=/local" )
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:
( export <auth_mode_var>="<auth_mode_value>" && cd ydb-go-examples && \
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:
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:
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:
import (
// general imports
"context"
"path"
// imports of ydb-go-sdk packages
"github.com/ydb-platform/ydb-go-sdk/v3"
"github.com/ydb-platform/ydb-go-sdk/v3/table" // to work with the table service
"github.com/ydb-platform/ydb-go-sdk/v3/table/options" // to work with the table service
"github.com/ydb-platform/ydb-go-sdk/v3/table/result" // to work with the table service
"github.com/ydb-platform/ydb-go-sdk/v3/table/result/named" // to work with the table service
"github.com/ydb-platform/ydb-go-sdk-auth-environ" // for authentication using environment variables
"github.com/ydb-platform/ydb-go-yc" // to work with YDB in Yandex.Cloud
)
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:
err = db.Table().Do(
ctx,
func(ctx context.Context, s table.Session) (err error) {
return s.CreateTable(ctx, path.Join(db.Name(), "series"),
options.WithColumn("series_id", types.Optional(types.TypeUint64)),
options.WithColumn("series_info", types.Optional(types.TypeUTF8)),
options.WithColumn("release_date", types.Optional(types.TypeDate)),
options.WithColumn("comment", types.Optional(types.TypeUTF8)),
options.WithPrimaryKeyColumn("series_id"),
)
},
)
if err != nil {
// handling the situation when the request failed
}
You can use the table.Session.DescribeTable()
method to output information about the table structure and make sure that it was properly created:
err = db.Table().Do(
ctx,
func(ctx context.Context, s table.Session) (err error) {
desc, err := s.DescribeTable(ctx, path.Join(db.Name(), "series"))
if err != nil {
return
}
log.Printf("> describe table: %s\n", tableName)
for _, c := range desc.Columns {
log.Printf(" > column, name: %s, %s\n", c.Type, c.Name)
}
return
}
)
if err != nil {
// handling the situation when the request failed
}
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.
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.
var (
query = `
DECLARE $series AS List<UInt64>;
SELECT series_id, season_id, title, first_aired
FROM seasons
WHERE series_id IN $series
`
res result.StreamResult
)
err = c.Do(
ctx,
func(ctx context.Context, s table.Session) (err error) {
res, err = s.StreamExecuteScanQuery(ctx, query,
table.NewQueryParameters(
types.ListValue(
types.Uint64Value(1),
),
),
),
)
if err != nil {
return err
}
defer func() {
_ = res.Close() // making sure the result is closed
}()
var (
seriesID uint64
seasonID uint64
title string
date time.Time
)
log.Print("\n> scan_query_select:")
for res.NextResultSet(ctx) {
if err = res.Err(); err != nil {
return err
}
for res.NextRow() {
// named.OptionalOrDefault lets you "deploy" optional
// results or use the default value of the go type
err = res.ScanNamed(
named.OptionalOrDefault("series_id", &seriesID),
named.OptionalOrDefault("season_id", &seasonID),
named.OptionalOrDefault("title", &title),
named.OptionalOrDefault("first_aired", &date),
)
if err != nil {
return err
}
log.Printf("# Season, SeriesId: %d, SeasonId: %d, Title: %s, Air date: %s", seriesID, seasonID, title, date)
}
}
return res.Err()
},
)
if err != nil {
// handling the query execution error
}
Note
Sample code of a test app that uses archived of versions the Go SDK: