diff --git a/CHANGELOG.md b/CHANGELOG.md index c6225b23c..af03a6b66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,4 @@ +* Added experimental ydb.ParamsFromMap and ydb.MustParamsFromMap for build query parameters * Refactored coordination traces ## v3.91.0 diff --git a/example_test.go b/example_test.go index cfce3c14c..b597fe665 100644 --- a/example_test.go +++ b/example_test.go @@ -510,3 +510,46 @@ func ExampleOpen_advanced() { defer db.Close(ctx) // cleanup resources fmt.Printf("connected to %s, database '%s'", db.Endpoint(), db.Name()) } + +// func ExampleParamsMap +func ExampleMustParamsFromMap() { + ctx := context.TODO() + db, err := ydb.Open( + ctx, + "grpc://localhost:2135/local", + ydb.WithAnonymousCredentials(), + ydb.WithBalancer( + balancers.PreferLocationsWithFallback( + balancers.RandomChoice(), "a", "b", + ), + ), + ydb.WithSessionPoolSizeLimit(100), + ) + if err != nil { + fmt.Printf("Driver failed: %v", err) + } + defer db.Close(ctx) // cleanup resources + fmt.Printf("connected to %s, database '%s'", db.Endpoint(), db.Name()) + + res, err := db.Query().QueryRow(ctx, ` +DECLARE $textArg AS Text; +DECLARE $intArg AS Int64; + +SELECT $textArg AS TextField, $intArg AS IntField +`, query.WithParameters(ydb.MustParamsFromMap(map[string]any{ + "$textArg": "asd", + "$intArg": int64(123), + }))) + if err != nil { + fmt.Printf("query failed") + } + + var result struct { + TextField string + IntField int64 + } + err = res.ScanStruct(&result) + if err != nil { + fmt.Printf("scan failed") + } +} diff --git a/params_map.go b/params_map.go new file mode 100644 index 000000000..9cf350959 --- /dev/null +++ b/params_map.go @@ -0,0 +1,34 @@ +package ydb + +import ( + "database/sql/driver" + "fmt" + + "github.com/ydb-platform/ydb-go-sdk/v3/internal/bind" + "github.com/ydb-platform/ydb-go-sdk/v3/internal/params" +) + +// MustParamsFromMap build parameters from named map, panic if error +// +// Experimental: https://github.com/ydb-platform/ydb-go-sdk/blob/master/VERSIONING.md#experimental +func MustParamsFromMap(m map[string]any) *params.Parameters { + p, err := ParamsFromMap(m) + if err != nil { + panic(fmt.Sprintf("ydb: MustParamsFromMap failed with error: %v", err)) + } + + return p +} + +// ParamsFromMap build parameters from named map +// +// Experimental: https://github.com/ydb-platform/ydb-go-sdk/blob/master/VERSIONING.md#experimental +func ParamsFromMap(m map[string]any) (*params.Parameters, error) { + namedParameters := make([]any, 0, len(m)) + for name, val := range m { + namedParameters = append(namedParameters, driver.NamedValue{Name: name, Value: val}) + } + p, err := bind.Params(namedParameters...) + + return (*params.Parameters)(&p), err +}