github.com/ydb-platform/ydb-go-sdk/v3@v3.57.0/tests/integration/database_sql_static_credentials_test.go (about) 1 //go:build integration 2 // +build integration 3 4 package integration 5 6 import ( 7 "context" 8 "database/sql" 9 "net/url" 10 "os" 11 "testing" 12 "time" 13 14 "github.com/stretchr/testify/require" 15 "google.golang.org/grpc" 16 grpcCredentials "google.golang.org/grpc/credentials" 17 "google.golang.org/grpc/credentials/insecure" 18 19 "github.com/ydb-platform/ydb-go-sdk/v3" 20 "github.com/ydb-platform/ydb-go-sdk/v3/credentials" 21 "github.com/ydb-platform/ydb-go-sdk/v3/internal/version" 22 ) 23 24 func TestDatabaseSqlStaticCredentials(t *testing.T) { 25 ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) 26 defer cancel() 27 28 var dsn string 29 if v, has := os.LookupEnv("YDB_CONNECTION_STRING"); !has { 30 t.Fatal("env YDB_CONNECTION_STRING required") 31 } else { 32 dsn = v 33 } 34 35 u, err := url.Parse(dsn) 36 if err != nil { 37 t.Fatal(err) 38 } 39 40 if version.Gte(os.Getenv("YDB_VERSION"), "23.3") { 41 u.User = url.UserPassword("root", "1234") 42 } else { 43 u.User = url.User("root") 44 } 45 46 t.Run("sql.Open", func(t *testing.T) { 47 var db *sql.DB 48 db, err = sql.Open("ydb", u.String()) 49 require.NoError(t, err) 50 51 err = db.PingContext(ctx) 52 require.NoError(t, err) 53 54 err = db.Close() 55 require.NoError(t, err) 56 }) 57 58 t.Run("sql.OpenDB", func(t *testing.T) { 59 var cc *ydb.Driver 60 cc, err = ydb.Open(ctx, os.Getenv("YDB_CONNECTION_STRING"), 61 ydb.WithCredentials(credentials.NewStaticCredentials(u.User.Username(), func() string { 62 password, _ := u.User.Password() 63 return password 64 }(), u.Host, credentials.WithGrpcDialOptions(func() grpc.DialOption { 65 if u.Scheme == "grpcs" { //nolint:goconst 66 transportCredentials, transportCredentialsErr := grpcCredentials.NewClientTLSFromFile( 67 os.Getenv("YDB_SSL_ROOT_CERTIFICATES_FILE"), u.Hostname(), 68 ) 69 if err != nil { 70 t.Fatalf("cannot create transport credentials: %v", transportCredentialsErr) 71 } 72 return grpc.WithTransportCredentials(transportCredentials) 73 } 74 return grpc.WithTransportCredentials(insecure.NewCredentials()) 75 }()))), 76 ) 77 require.NoError(t, err) 78 79 defer func() { 80 // cleanup 81 _ = cc.Close(ctx) 82 }() 83 84 c, err := ydb.Connector(cc) 85 require.NoError(t, err) 86 87 defer func() { 88 // cleanup 89 _ = c.Close() 90 }() 91 92 db := sql.OpenDB(c) 93 defer func() { 94 // cleanup 95 _ = db.Close() 96 }() 97 98 err = db.PingContext(ctx) 99 require.NoError(t, err) 100 }) 101 }