### Run Access Token Credentials Example Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/auth/access_token_credentials/README.md This command-line example shows how to run the access token credentials authentication. ```bash access_token_credentials -ydb="grpcs://endpoint/?database=database" -token="mytoken" ``` -------------------------------- ### Install YDB Go SDK Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/topic/README.md Install the YDB Go SDK using the go get command. This command fetches and installs the latest version of the SDK. ```sh go get -u github.com/ydb-platform/ydb-go-sdk/v3 ``` -------------------------------- ### Run Metadata Credentials Example Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/auth/metadata_credentials/README.md Command to run the metadata_credentials example. Ensure you replace 'grpcs://endpoint/?database=database' with your actual YDB endpoint and database. ```bash metadata_credentials -ydb="grpcs://endpoint/?database=database" ``` -------------------------------- ### Run Service Account Credentials Example Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/auth/service_account_credentials/README.md This bash command demonstrates how to run the service account credentials example. It requires the YDB endpoint and the path to the service account key file. ```bash service_account_credentials -ydb="grpcs://endpoint/?database=database" -sa-file="/Users/user/.ydb/sa.json" ``` -------------------------------- ### Run OAuth 2.0 Token Exchange Credentials Example Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/auth/oauth2_token_exchange_credentials/README.md This command-line snippet shows how to run the example, specifying the YDB endpoint, token exchange details, and audience/issuer/subject information. ```bash oauth2_token_exchange_credentials -ydb="grpcs://endpoint/?database=database" -token-endpoint="https://exchange.token.endpoint/oauth2/token/exchange" -key-id="123" -private-key-file="path/to/key/file" -audience="test-aud" -issuer="test-issuer" -subject="test-subject" ``` -------------------------------- ### Running environ authentication examples Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/auth/environ/README.md Demonstrates setting environment variables for different authentication methods and running the 'environ' command. Use this to test various authentication strategies. ```bash export YDB_CONNECTION_STRING="grpcs://endpoint/?database=database" export YDB_SERVICE_ACCOUNT_KEY_FILE_CREDENTIALS=/Users/user/.ydb/sa.jsoon environ ``` ```bash export YDB_CONNECTION_STRING="grpcs://endpoint/?database=database" export YDB_ANONYMOUS_CREDENTIALS="1" environ ``` ```bash export YDB_CONNECTION_STRING="grpcs://endpoint/?database=database" export YDB_METADATA_CREDENTIALS="1" environ ``` ```bash export YDB_CONNECTION_STRING="grpcs://endpoint/?database=database" export YDB_ACCESS_TOKEN_CREDENTIALS="YDB_ACCESS_TOKEN" environ ``` -------------------------------- ### Run Anonymous Credentials Example Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/auth/anonymous_credentials/README.md Execute the anonymous credentials example by providing the YDB endpoint and database name. ```bash anonymous_credentials -ydb="grpcs://endpoint/?database=database" ``` -------------------------------- ### Run static credentials authentication Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/auth/static_credentials/README.md This command-line snippet shows how to run the static credentials example. It requires the YDB endpoint, database name, username, and password as arguments. ```bash static_credentials -ydb="grpcs://endpoint/?database=database" -user="user" -password="password" ``` -------------------------------- ### Run OpenTelemetry Stack with Docker Compose Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/opentelemetry/README.md Starts the OpenTelemetry stack using Docker Compose. This is the preferred method for running the setup. ```bash docker-compose -f compose-e2e.yaml up -d --build ``` ```bash # Alternative (Docker Compose v2 plugin, if available) # docker compose -f compose-e2e.yaml up -d --build ``` -------------------------------- ### Build and Run Coordination Worker Example Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/coordination/README.md Builds the Go application and runs it with specified parameters, including YDB connection details, path, semaphore prefix, number of tasks, and worker capacity. ```bash $ go build $ YDB_ANONYMOUS_CREDENTIALS=1 ./lock -ydb grpc://localhost:2136/local -path /local/test --semaphore-prefix job- --tasks 10 --capacity 4 ``` -------------------------------- ### Run SLO Workload Example Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/tests/slo/README.md This command demonstrates how to run the SLO workload using the native driver. Ensure all required environment variables are set before execution. ```bash export YDB_ENDPOINT=grpc://ydb:2136 export YDB_DATABASE=/Root/testdb export WORKLOAD_DURATION=600 export OTEL_EXPORTER_OTLP_ENDPOINT=http://ydb-prometheus:9090/api/v1/otlp export PROMETHEUS_URL=http://ydb-prometheus:9090 ./slo-native-table ``` -------------------------------- ### Run All Tests with Local YDB Instance Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/CONTRIBUTING.md Starts a local YDB instance in a Docker container, sets environment variables for connection, runs all tests (including integration tests), and then stops the container. Ensure Docker is installed and running. ```sh docker run -itd --name ydb -dp 2135:2135 -dp 2136:2136 -dp 8765:8765 -v `pwd`/ydb_certs:/ydb_certs -e YDB_LOCAL_SURVIVE_RESTART=true -e YDB_USE_IN_MEMORY_PDISKS=true -h localhost ydbplatform/local-ydb:latest export YDB_CONNECTION_STRING="grpc://localhost:2136/local" export YDB_CONNECTION_STRING_SECURE="grpcs://localhost:2135/local" export YDB_SSL_ROOT_CERTIFICATES_FILE="`pwd`/ydb_certs/ca.pem" export YDB_SESSIONS_SHUTDOWN_URLS="http://localhost:8765/actors/kqp_proxy?force_shutdown=all" go test -race ./... docker stop ydb ``` -------------------------------- ### Run Lock Application Example Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/coordination/README.md This command builds and runs the lock application, demonstrating how to acquire a distributed lock using YDB. Ensure a YDB Docker instance is running. ```bash $ go build $ YDB_ANONYMOUS_CREDENTIALS=1 ./lock -ydb grpc://localhost:2136/local --path /local/test --semaphore lock ``` -------------------------------- ### Decimal Type Scaling Example Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/pkg/decimal/README.md Demonstrates how to correctly perform arithmetic operations with decimal types represented as *math/big.Int, emphasizing the need to account for the scaling factor. ```go import ( "ydb/decimal" "math/big" ) var scaleFactor = big.NewInt(10000000000) // Default scale is 9. func main() { x := decimal.FromInt128([16]byte{...}) x.Add(x, big.NewInt(42)) // Incorrect. x.Add(x, scale(42)) // Correct. } func scale(n int64) *big.Int { x := big.NewInt(n) return x.Mul(x, scaleFactor) } ``` -------------------------------- ### Go SQL Query with Explicit YDB Types and Bindings Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Example of executing a YQL query with explicit YDB types and named/positional parameters using database/sql, requiring direct import of YDB SDK packages. ```go import ( "context" "database/sql" "github.com/ydb-platform/ydb-go-sdk/v3" "github.com/ydb-platform/ydb-go-sdk/v3/table" "github.com/ydb-platform/ydb-go-sdk/v3/table/types" ) func main() { db := sql.Open("ydb", "grpc://localhost:2136/local") defer db.Close() // positional args row := db.QueryRowContext(context.TODO(), ` PRAGMA TablePathPrefix("/local/path/to/my/folder"); DECLARE $p0 AS Int32; DECLARE $p1 AS Utf8; SELECT $p0, $p1`, sql.Named("p0", 42), table.ValueParam("$p1", types.TextValue("my string")), ) // process row ... } ``` -------------------------------- ### Acquire Exclusive Semaphore with Ephemeral Lease Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/coordination/README.md This Go code snippet shows how to open a session, acquire an exclusive semaphore with an ephemeral lease, and start a background task. It includes error handling and a loop to continuously attempt lock acquisition. ```go for { session, err := db.Coordination().OpenSession(ctx, path) if err != nil { // The context is canceled. break } lease, err := session.AcquireSemaphore(ctx, semaphore, coordination.Exclusive, options.WithEphemeral(true)) if err != nil { session.Close(ctx) continue } // The lock is acquired. go doWork(lease.Context()) // Wait until the lock is released. <-lease.Context().Done(): // The lock is not acquired anymore. cancelWork() } ``` -------------------------------- ### Worker Task Distribution Logic Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/coordination/README.md Implements the core logic for distributing tasks among workers using YDB Coordination Service semaphores. It continuously acquires semaphores to start new tasks up to the worker's capacity. ```go for { session, err := db.Coordination().OpenSession(ctx, path) if err != nil { // The context is canceled. break } semaphoreCtx, semaphoreCancel := context.WithCancel(ctx) capacitySemaphore := semaphore.NewWeighted(capacity) leaseChan := make(chan *coordination.Lease) for _, name := range tasks { go awaitSemaphore(semaphoreCtx, semaphoreCancel, session, name, capacitySemaphore, leaseChan) } tasksStarted := 0 loop: for { lease := <-leaseChan // Run a new task every time we acquire a semaphore. go doWork(lease.Context()) tasksStarted++ if tasksStarted == capacity { break } } // The capacity is full, cancel all Acquire operations. semaphoreCancel() // Wait until the session is alive. <-session.Context().Done() // The tasks must be stopped since we do not own the semaphores anymore. cancelTasks() } ``` -------------------------------- ### Initialize YDB Driver with ydb.Connector Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Recommended way to initialize the database/sql driver by first opening a native YDB driver and then creating a connector. Allows for detailed configuration of both the native driver and the connector. ```go import ( "database/sql" "github.com/ydb-platform/ydb-go-sdk/v3" ) func main() { // init native ydb-go-sdk driver nativeDriver, err := ydb.Open(context.TODO(), "grpc://localhost:2136/local", // See many ydb.Option's for configure driver https://pkg.go.dev/github.com/ydb-platform/ydb-go-sdk/v3#Option ) if err != nil { // fallback on error } defer nativeDriver.Close(context.TODO()) connector, err := ydb.Connector(nativeDriver, // See ydb.ConnectorOption's for configure connector https://pkg.go.dev/github.com/ydb-platform/ydb-go-sdk/v3#ConnectorOption ) if err != nil { // fallback on error } db := sql.OpenDB(connector) defer db.Close() db.SetMaxOpenConns(100) db.SetMaxIdleConns(100) db.SetConnMaxIdleTime(time.Second) // workaround for background keep-aliving of YDB sessions } ``` -------------------------------- ### Build and Run URL Shortener as HTTP Server Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/serverless/url_shortener/README.md Clone the repository, build the application, and run it as an HTTP server. Ensure the YDB connection string and port are correctly specified. ```bash git clone github.com/ydb-platform/ydb-go-sdk/v3 ydb-go-sdk cd ydb-go-sdk/examples/serverless/url_shortener go build -o url_shortener . YDB_SERVICE_ACCOUNT_KEY_FILE_CREDENTIALS=/path/to/sa/key/file \ url_shortener \ -ydb=grpcs://ydb.serverless.yandexcloud.net:2135/ru-central1/b1g8skpblkos03malf3s/etn01f8gv9an9sedo9fu \ -port=80 ``` -------------------------------- ### Go SQL Query with Auto-Bindings via Connection String Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Demonstrates simplified query execution using database/sql with auto-bindings enabled via connection string parameters for TablePathPrefix, parameter declaration, and positional arguments. ```go import ( "context" "database/sql" _ "github.com/ydb-platform/ydb-go-sdk/v3" // anonymous import for registering driver ) func main() { var ( ctx = context.TODO() db = sql.Open("ydb", "grpc://localhost:2136/local?" "go_auto_bind="+ "table_path_prefix(/local/path/to/my/folder),"+ "declare,"+ "positional", ) ) defer db.Close() // cleanup resources // positional args row := db.QueryRowContext(ctx, `SELECT ?, ?`, 42, "my string") ``` -------------------------------- ### Deploy URL Shortener as Yandex Serverless Function Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/serverless/url_shortener/README.md Prepare the Go module, zip the project files, and deploy it as a Yandex Serverless function. Configure environment variables for YDB connection and specify function settings. ```bash go mod init example && go mod tidy zip archive.zip service.go go.mod go.sum yc sls fn version create \ --service-account-id=aje46n285h0re8nmm5u6 \ --runtime=golang116 \ --entrypoint=main.Serverless \ --memory=128m \ --execution-timeout=1s \ --environment YDB="grpcs://ydb.serverless.yandexcloud.net:2135/ru-central1/b1g8skpblkos03malf3s/etnpa7o3qltdfgu9vsap" \ --source-path=./archive.zip \ --function-id=d4euc5gp5614b56crpnj ``` -------------------------------- ### Using table.ParameterOption for Query Parameters Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Shows how to specify query parameters using `table.ParameterOption` with explicit YDB types. Parameter names must include the `$` prefix. ```go rows, err := db.QueryContext(ctx, ` DECLARE $title AS Text; DECLARE $views AS Uint64; SELECT season_id FROM seasons WHERE title LIKE $title AND views > $views; `, table.ValueParam("$seasonTitle", types.TextValue("%Season 1%")), table.ValueParam("$views", types.Uint64Value((1000)), ) ``` -------------------------------- ### Configure Client Balancing with PreferLocations Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Demonstrates how to configure the YDB SQL driver to use a custom balancer algorithm, preferring specific locations with a fallback to random choice. This is useful for optimizing connection distribution based on network topology. ```go import ( "github.com/ydb-platform/ydb-go-sdk/v3/balancers" ) func main() { nativeDriver, err := ydb.Open(context.TODO(), "grpc://localhost:2136/local", ydb.WithBalancer( balancers.PreferLocationsWithFallback( balancers.RandomChoice(), "a", "b", ), ), ) if err != nil { // fallback on error } connector, err := ydb.Connector(nativeDriver) if err != nil { // fallback on error } db := sql.OpenDB(connector) db.SetMaxOpenConns(100) db.SetMaxIdleConns(100) db.SetConnMaxIdleTime(time.Second) // workaround for background keep-aliving of YDB sessions } ``` -------------------------------- ### Initialize YDB Driver with Data Source Name Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Alternative method to initialize the database/sql driver using a connection string. Supports static credentials and query mode configuration via URL parameters. ```go import ( "database/sql" _ "github.com/ydb-platform/ydb-go-sdk/v3" ) func main() { db, err := sql.Open("ydb", "grpc://localhost:2136/local") defer db.Close() } ``` -------------------------------- ### Build and Run Healthcheck Application Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/serverless/healthcheck/README.md Clone the SDK, build the healthcheck application, and run it with YDB connection details and URLs to monitor. ```bash git clone github.com/ydb-platform/ydb-go-sdk/v3 ydb-go-sdk cd ydb-go-sdk/examples/serverless/healthcheck go build -o healthcheck . YDB_SERVICE_ACCOUNT_KEY_FILE_CREDENTIALS=/path/to/sa/key/file \ healthcheck \ -ydb=grpcs://types.serverless.yandexcloud.net:2135/ru-central1/b1g8skpblkos03malf3s/etn01f8gv9an9sedo9fu \ -url=www.ya.ru -url=google.com -url=rampler.ru ``` -------------------------------- ### Run Unit Tests Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/CONTRIBUTING.md Execute unit tests with race detection enabled for all project files. Ensure you are in the project directory. ```sh go test -race ./... ``` -------------------------------- ### Run YDB Go SDK code snippet Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/transaction/database/sql/README.md This command demonstrates how to run a Go code snippet using the YDB SDK, specifying the YDB endpoint and database name. ```bash go run -ydb="grpcs://endpoint/?database=database" ``` -------------------------------- ### Deploy Healthcheck as Yandex Serverless Function Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/serverless/healthcheck/README.md Initialize a Go module, create a zip archive, and deploy the healthcheck application as a Yandex Serverless function with specified configurations. ```bash go mod init example && go mod tidy zip archive.zip service.go go.mod go.sum yc sls fn version create \ --service-account-id=aje46n285h0re8nmm5u6 \ --runtime=golang118 \ --entrypoint=main.Serverless \ --memory=128m \ --execution-timeout=1s \ --environment YDB_METADATA_CREDENTIALS="1" \ --environment YDB="grpcs://ydb.serverless.yandexcloud.net:2135/ru-central1/b1g8skpblkos03malf3s/etnpa7o3qltdfgu9vsap" \ --environment URLS="https://ya.ru,https://google.com,https://rambler.ru" \ --source-path=./archive.zip \ --function-id=d4empp866m0b4m2gspu9 ``` -------------------------------- ### Connect to YDB Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/topic/README.md Establish a connection to the YDB database. Ensure the context is valid and the connection string is correct. ```go db, err := ydb.Open(ctx, "grpc://localhost:2136/local") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Local Debugging of Go Program Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/opentelemetry/README.md Scales down the Dockerized app and runs the Go program directly from the host for local iteration. Ensure environment variables for YDB DSN and OTLP endpoint are set. ```bash docker-compose -f compose-e2e.yaml up -d --scale app=0 go mod tidy YDB_DSN=grpc://localhost:2136/local \ OTEL_EXPORTER_OTLP_ENDPOINT=localhost:4317 \ go run . ``` -------------------------------- ### Test Query Binding with TablePathPrefix, Declare, and Positional Args Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md This unit test demonstrates how to create query bindings using TablePathPrefix, Declare, and Positional arguments. It shows how to convert a simple query with positional arguments into a YQL query with declared parameters and the specified TablePathPrefix. ```go func TestBinding(t *testing.T) { bindings := query.NewBind( query.TablePathPrefix("/local/path/to/my/folder"), // bind pragma TablePathPrefix query.Declare(), // bind parameters declare query.Positional(), // auto-replace positional args ) query, params, err := bindings.ToYQL("SELECT ?, ?, ?", 1, uint64(2), "3") require.NoError(t, err) require.Equal(t, "-- bind TablePathPrefix PRAGMA TablePathPrefix(\"/local/path/to/my/folder\"); -- bind declares DECLARE $p0 AS Int32; DECLARE $p1 AS Uint64; DECLARE $p2 AS Utf8; -- origin query with positional args replacement SELECT $p0, $p1, $p2", query) require.Equal(t, table.NewQueryParameters( table.ValueParam("$p0", types.Int32Value(1)), table.ValueParam("$p1", types.Uint64Value(2)), table.ValueParam("$p2", types.TextValue("3")), ), params) } ``` -------------------------------- ### Run Linter Checks Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/CONTRIBUTING.md Execute linter checks on all project files using golangci-lint. Ensure you are in the project directory. ```sh golangci-lint run ./... ``` -------------------------------- ### Go SQL Query with Auto-Bindings via Connector Options Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Shows how to enable auto-bindings for TablePathPrefix, parameter declaration, and positional arguments using connector options with the YDB Go SDK. ```go import ( "context" "database/sql" "github.com/ydb-platform/ydb-go-sdk/v3" ) func main() { var ( ctx = context.TODO() nativeDriver = ydb.MustOpen(ctx, "grpc://localhost:2136/local") db = sql.OpenDB(ydb.MustConnector(nativeDriver, query.TablePathPrefix("/local/path/to/my/folder"), // bind pragma TablePathPrefix query.Declare(), // bind parameters declare query.Positional(), // bind positional args )) ) defer nativeDriver.Close(ctx) // cleanup resources defer db.Close() // positional args row := db.QueryRowContext(ctx, `SELECT ?, ?`, 42, "my string") ``` -------------------------------- ### Use YDB with database/sql Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/README.md Connects to YDB and executes a SELECT query using the standard Go database/sql package. Ensure the YDB driver is imported. ```go import ( "context" "database/sql" "log" _ "github.com/ydb-platform/ydb-go-sdk/v3" ) ... db, err := sql.Open("ydb", "grpc://localhost:2136/local") if err != nil { log.Fatal(err) } defer db.Close() // cleanup resources var ( id int32 myStr string ) row := db.QueryRowContext(context.TODO(), `SELECT 42 as id, "my string" as myStr`) if err = row.Scan(&id, &myStr); err != nil { log.Printf("select failed: %v", err) return } log.Printf("id = %d, myStr = \"%s\"", id, myStr) ``` -------------------------------- ### Configure Read-Write Transaction Options Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Configure transaction options for read-write operations with either default or snapshot isolation levels. ```go rw := sql.TxOption{ ReadOnly: false, Isolation: sql.LevelDefault, } ``` ```go rw := sql.TxOption{ ReadOnly: false, Isolation: sql.LevelSnapshot, } ``` -------------------------------- ### Using sql.NamedArg for Query Parameters Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Demonstrates how to pass query parameters using `sql.NamedArg` with native Go types and YDB types. Argument names are provided without the `$` prefix. ```go rows, err := db.QueryContext(ctx, ` DECLARE $title AS Text; DECLARE $views AS Uint64; DECLARE $ts AS Datetime; SELECT season_id FROM seasons WHERE title LIKE $title AND views > $views AND first_aired > $ts; `, sql.Named("title", "%Season 1%"), // argument name with without prefix `$` sql.Named("views", uint64(1000)), // argument name without prefix `$` (driver will prepend `$` if necessary) sql.Named("ts", types.DatetimeValueFromTime( // native ydb type time.Now().Add(-time.Hour*24*365), )), ) ``` -------------------------------- ### Execute SELECT Query with SDK Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/README.md Executes a SELECT query using the Query service client and handles results. It includes retry logic for transient errors and proper resource cleanup. ```go // Do retry operation on errors with best effort err := db.Query().Do( ctx, // context manage exiting from Do func(ctx context.Context, s query.Session) (err error) { // retry operation streamResult, err := s.Query(ctx, `SELECT 42 as id, "myStr" as myStr;`) if err != nil { return err // for auto-retry with driver } defer func() { _ = streamResult.Close(ctx) }() // cleanup resources for rs, err := range streamResult.ResultSets(ctx) { if err != nil { return err } for row, err := range rs.Rows(ctx) { if err != nil { return err } type myStruct struct { Id int32 `sql:"id"` Str string `sql:"myStr"` } var s myStruct if err = row.ScanStruct(&s); err != nil { return err // generally scan error not retryable, return it for driver check error } } } return nil }, query.WithIdempotent(), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Unwrap Native Driver from *sql.DB Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Access the native YDB driver from a `*sql.DB` instance to perform operations using the native YDB session. This is useful when you need to leverage specific YDB features not exposed through the standard `*sql.DB` interface. ```go db, err := sql.Open("ydb", "grpc://localhost:2136/local") if err != nil { t.Fatal(err) } nativeDriver, err = ydb.Unwrap(db) if err != nil { t.Fatal(err) } nativeDriver.Table().Do(ctx, func(ctx context.Context, s table.Session) error { // doing with native YDB session return nil }) ``` -------------------------------- ### Run Linters and Tests Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/AGENTS.md Execute the project's linters and race detector tests from the repository root. Ensure all code adheres to project standards before merging. ```bash golangci-lint run ./... go test -race ./... ``` -------------------------------- ### Using *table.QueryParameters for Query Parameters Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Illustrates passing query parameters as a single `*table.QueryParameters` argument, which internally uses `table.ValueParam`. ```go rows, err := db.QueryContext(ctx, ` DECLARE $title AS Text; DECLARE $views AS Uint64; SELECT season_id FROM seasons WHERE title LIKE $title AND views > $views; `, table.NewQueryParameters( table.ValueParam("$seasonTitle", types.TextValue("%Season 1%")), table.ValueParam("$views", types.Uint64Value((1000)), ), ) ``` -------------------------------- ### Configure Zap Logging for YDB Driver Events Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Integrate `zap` logging with the YDB driver by using `ydbZap.WithTraces`. This allows capturing detailed driver events when the connection is established via a connector. ```go import ( "github.com/ydb-platform/ydb-go-sdk/v3/trace" ydbZap "github.com/ydb-platform/ydb-go-sdk-zap" ) ... nativeDriver, err := ydb.Open(ctx, connectionString, ... ydbZap.WithTraces(log, trace.DetailsAll), ) if err != nil { // fallback on error } connector, err := ydb.Connector(nativeDriver) if err != nil { // fallback on error } db := sql.OpenDB(connector) ``` -------------------------------- ### Configure Prometheus Metrics for YDB Driver Events Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Add Prometheus monitoring for YDB driver events using `ydbMetrics.WithTraces`. This requires the connection to be established over a connector and allows detailed event monitoring. ```go import ( "github.com/ydb-platform/ydb-go-sdk/v3/trace" ydbMetrics "github.com/ydb-platform/ydb-go-sdk-prometheus" ) ... nativeDriver, err := ydb.Open(ctx, connectionString, ... ydbMetrics.WithTraces(registry, ydbMetrics.WithDetails(trace.DetailsAll)), ) if err != nil { // fallback on error } connector, err := ydb.Connector(nativeDriver) if err != nil { // fallback on error } db := sql.OpenDB(connector) ``` -------------------------------- ### SQL Query with Explicit TablePathPrefix and Parameters Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Demonstrates a YQL query with an explicit TablePathPrefix and declared parameters for title and views. ```sql DECLARE $title AS Text; DECLARE $views AS Uint64; SELECT season_id FROM `/local/path/to/tables/seasons` WHERE title LIKE $title AND views > $views; ``` -------------------------------- ### Unwrap Native Driver from *sql.Conn with Retry Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Unwrap the native YDB driver from a `*sql.Conn` within a `retry.Do` block to handle transient errors. This allows executing native YDB scripts and standard SQL queries while benefiting from automatic retries. ```go err := retry.Do(context.TODO(), db, func(ctx context.Context, cc *sql.Conn) error { nativeDriver, err := ydb.Unwrap(cc) if err != nil { return err // return err to retryer } res, err := nativeDriver.Scripting().Execute(ctx, "SELECT 1+1", table.NewQueryParameters(), ) if err != nil { return err // return err to retryer } // work with cc rows, err := cc.QueryContext(ctx, "SELECT 1;") if err != nil { return err // return err to retryer } ... return nil // good final of retry operation }, retry.WithIdempotent(true)) ``` -------------------------------- ### Configure Read-Only Transaction Options Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Configure transaction options for read-only operations with snapshot isolation. ```go ro := sql.TxOption{ ReadOnly: true, Isolation: sql.LevelSnapshot, } ``` -------------------------------- ### Export Default YDB Configuration Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/opentelemetry/ydb_config/README.md Copies the default YDB configuration file from a running ydb-local container to the local filesystem for modification. ```bash docker cp ydb-local:/ydb_data/cluster/kikimr_configs/config.yaml ./ydb_config/ydb-config.yaml ``` -------------------------------- ### SQL Query with PRAGMA TablePathPrefix and Declared Parameters Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Shows a simplified YQL query using PRAGMA TablePathPrefix to scope table names and declared parameters. ```sql PRAGMA TablePathPrefix("/local/path/to/tables/"); DECLARE $title AS Text; DECLARE $views AS Uint64; SELECT season_id FROM seasons WHERE title LIKE $title AND views > $views; ``` -------------------------------- ### Restart YDB with Overridden Configuration Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/opentelemetry/ydb_config/README.md Restarts the YDB service using a specified configuration file, enabling the previously modified settings for OpenTelemetry tracing. ```bash docker-compose -f compose-e2e.yaml up -d --force-recreate ydb ``` -------------------------------- ### Expanded SQL Query with Bindings Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Illustrates the expanded YQL query sent to the YDB server after auto-bindings are applied, including TablePathPrefix, parameter declarations, and positional argument replacements. ```sql -- bind TablePathPrefix PRAGMA TablePathPrefix("/local/path/to/my/folder"); -- bind declares DECLARE $p0 AS Int32; DECLARE $p1 AS Utf8; -- origin query with positional args replacement SELECT $p0, $p1 ``` -------------------------------- ### Recreate YDB Container with Tracing Config Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/opentelemetry/README.md This command recreates the YDB container to apply changes made to the tracing configuration file. Ensure the `ydb-config.yaml` has been updated. ```bash # Recreate the ydb container after changing ./ydb_config/ydb-config.yaml docker-compose -f compose-e2e.yaml up -d --force-recreate ydb ``` -------------------------------- ### Configure Jaeger Tracing for YDB Driver Events Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Enable Jaeger tracing for YDB driver events using `ydbOpentracing.WithTraces`. This feature is available when connecting via a connector and allows detailed tracing of driver activities. ```go import ( "github.com/ydb-platform/ydb-go-sdk/v3/trace" ydbOpentracing "github.com/ydb-platform/ydb-go-sdk-opentracing" ) ... nativeDriver, err := ydb.Open(ctx, connectionString, ... ydbOpentracing.WithTraces(trace.DriverConnEvents | trace.DriverClusterEvents | trace.DriverRepeaterEvents | trace.DiscoveryEvents), ) if err != nil { // fallback on error } connector, err := ydb.Connector(nativeDriver) if err != nil { // fallback on error } db := sql.OpenDB(connector) ``` -------------------------------- ### Execute SQL Query on Database Object Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Use `db.QueryContext` to execute a SQL query directly on the database object. Ensure to always close rows and check for errors after iteration. ```go rows, err := db.QueryContext(ctx, "SELECT series_id, title, release_date FROM `/full/path/of/table/series`;" ) if err != nil { log.Fatal(err) } defer rows.Close() // always close rows var ( id *string title *string releaseDate *time.Time ) for rows.Next() { // iterate over rows // apply database values to go's type destinations if err = rows.Scan(&id, &title, &releaseDate); err != nil { log.Fatal(err) } log.Printf("> [%s] %s (%s)", *id, *title, releaseDate.Format("2006-01-02")) } if err = rows.Err(); err != nil { // always check final rows err log.Fatal(err) } ``` -------------------------------- ### Integration Test Build Tag Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/tests/integration/README.md This build tag is required to run integration tests. It ensures these tests are only executed in specific environments, such as GitHub Actions. ```go //go:build integration // +build integration ``` -------------------------------- ### Semaphore Acquisition and Task Assignment Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/coordination/README.md Handles acquiring a semaphore for a specific task and assigning it to a worker if capacity is available. It releases the semaphore if no capacity is immediately available. ```go func awaitSemaphore( ctx context.Context, cancel context.CancelFunc, session coordination.Session, semaphoreName string, capacitySemaphore *semaphore.Weighted, leaseChan chan *coordination.Lease, ) { lease, err := session.AcquireSemaphore( ctx, semaphoreName, coordination.Exclusive, options.WithEphemeral(true), ) if err != nil { // Let the main loop know that something is wrong. // ... return } // If there is a need in tasks for the current worker, provide it with a new lease. if capacitySemaphore.TryAcquire(1) { leaseChan <- lease } else { // This may happen since we are waiting for all existing semaphores trying to grab the first available to us. err := lease.Release() if err != nil { // Let the main loop know that something is wrong. // ... } } } ``` -------------------------------- ### Set SchemeQueryMode for DDL Operations Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Use `ydb.WithQueryMode` to explicitly set the query mode for DDL operations like dropping a table. This ensures the correct GRPC service method is used. ```go res, err = db.ExecContext(ydb.WithQueryMode(ctx, ydb.SchemeQueryMode), "DROP TABLE `/full/path/to/table/series`", ) ``` -------------------------------- ### Execute SQL Query within a Transaction Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Execute a SQL query within a transaction using `db.BeginTx` and `tx.QueryContext`. Remember to commit or rollback the transaction and always check for errors. ```go tx, err := db.BeginTx(ctx, sql.TxOption{ ReadOnly: true, Isolation: sql.LevelSnapshot, }) if err != nil { log.Fatal(err) } defer tx.Rollback() rows, err := tx.QueryContext(ctx, "SELECT series_id, title, release_date FROM `/full/path/of/table/series`;" ) if err != nil { log.Fatal(err) } defer rows.Close() // always close rows var ( id *string title *string releaseDate *time.Time ) for rows.Next() { // iterate over rows // apply database values to go's type destinations if err = rows.Scan(&id, &title, &releaseDate); err != nil { log.Fatal(err) } log.Printf("> [%s] %s (%s)", *id, *title, releaseDate.Format("2006-01-02")) } if err = rows.Err(); err != nil { // always check final rows err log.Fatal(err) } if err = tx.Commit(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Change Default Transaction Control Mode Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Update the context to change the default transaction control mode for queries outside of interactive transactions. ```go rows, err := db.QueryContext(ydb.WithTxControl(ctx, table.OnlineReadOnlyTxControl()), "SELECT series_id, title, release_date FROM `/full/path/of/table/series`;" ) ``` -------------------------------- ### Retry Operations over sql.Conn Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Use retry.Do to handle transient errors for operations performed directly on a database connection object. ```go import ( "github.com/ydb-platform/ydb-go-sdk/v3/retry" ) ... er := retry.Do(context.TODO(), db, func(ctx context.Context, cc *sql.Conn) error { // work with cc rows, err := cc.QueryContext(ctx, "SELECT 1;") if err != nil { return err // return err to retryer } ... return nil // good final of retry operation }, retry.WithIdempotent(true)) ``` -------------------------------- ### URL Shortener Client-Side Logic Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/examples/serverless/url_shortener/static/index.html This JavaScript code handles the client-side logic for the URL shortener. It attaches an event listener to a button to capture user input, send a POST request to the server, and display the shortened URL or any errors. ```javascript (function (){ let source = document.getElementById("source"); let shorten = document.getElementById("shorten"); let button = document.getElementById("button"); button.onclick = function(e) { e.preventDefault(); fetch("shorten", { method: 'post', body: source.value, }).then(function (response) { return response.text(); }).then(function (hash) { shorten.innerText = window.location.protocol + '//' + window.location.host + window.location.pathname + hash; shorten.setAttribute("href", window.location.protocol + '//' + window.location.host + window.location.pathname + hash); }).catch(function (error) { shorten.innerText = error; shorten.setAttribute("href", ""); }) }; })() ``` -------------------------------- ### Retry Operations over sql.Tx Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/SQL.md Use retry.DoTx to handle transient errors for operations within a database transaction. The helper manages commit/rollback. ```go import ( "github.com/ydb-platform/ydb-go-sdk/v3/retry" ) ... er := retry.DoTx(context.TODO(), db, func(ctx context.Context, tx *sql.Tx) error { // work with tx rows, err := tx.QueryContext(ctx, "SELECT 1;") if err != nil { return err // return err to retryer } ... return nil // good final of retry tx operation }, retry.WithIdempotent(true), retry.WithTxOptions(&sql.TxOptions{ Isolation: sql.LevelSnapshot, ReadOnly: true, })) ``` -------------------------------- ### Read Messages from YDB Topic Source: https://github.com/ydb-platform/ydb-go-sdk/blob/master/topic/README.md Read messages from a YDB topic using a reader. Messages are processed in a loop, and acknowledged after successful processing. ```go for { msg, err := reader.ReadMessage(ctx) if err != nil { log.Fatal(err) } content, err := io.ReadAll(msg) if err != nil { log.Fatal(err) } fmt.Println(string(content)) err = reader.Commit(msg.Context(), msg) if err != nil { log.Fatal(err) } } ```