github.com/ydb-platform/ydb-go-sdk/v3@v3.57.0/tests/integration/table_tx_lazy_test.go (about)

     1  //go:build integration
     2  // +build integration
     3  
     4  package integration
     5  
     6  import (
     7  	"context"
     8  	"os"
     9  	"testing"
    10  	"time"
    11  
    12  	"github.com/stretchr/testify/require"
    13  
    14  	"github.com/ydb-platform/ydb-go-sdk/v3"
    15  	"github.com/ydb-platform/ydb-go-sdk/v3/table"
    16  	"github.com/ydb-platform/ydb-go-sdk/v3/table/options"
    17  )
    18  
    19  func TestTableTxLazy(t *testing.T) {
    20  	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    21  	defer cancel()
    22  
    23  	var db *ydb.Driver
    24  
    25  	t.Run("connect", func(t *testing.T) {
    26  		var err error
    27  		db, err = ydb.Open(ctx,
    28  			"", // corner case for check replacement of endpoint+database+secure
    29  			ydb.WithConnectionString(os.Getenv("YDB_CONNECTION_STRING")),
    30  		)
    31  		require.NoError(t, err)
    32  	})
    33  
    34  	t.Run("tx", func(t *testing.T) {
    35  		t.Run("lazy", func(t *testing.T) {
    36  			err := db.Table().Do(ctx,
    37  				func(ctx context.Context, s table.Session) (err error) {
    38  					// lazy open transaction on first execute query
    39  					tx, res, err := s.Execute(ctx, table.SerializableReadWriteTxControl(), "SELECT 1", nil)
    40  					if err != nil {
    41  						return err // for auto-retry with driver
    42  					}
    43  					defer res.Close() // cleanup resources
    44  					if err = res.Err(); err != nil {
    45  						return err
    46  					}
    47  					// close transaction on last execute query
    48  					res, err = tx.Execute(ctx, "SELECT 2", nil, options.WithCommit())
    49  					if err != nil {
    50  						return err
    51  					}
    52  					defer res.Close()
    53  					return res.Err()
    54  				},
    55  				table.WithIdempotent(),
    56  			)
    57  			require.NoError(t, err)
    58  		})
    59  	})
    60  
    61  	t.Run("disconnect", func(t *testing.T) {
    62  		err := db.Close(ctx)
    63  		require.NoError(t, err)
    64  	})
    65  }