ydb-go-sdk icon indicating copy to clipboard operation
ydb-go-sdk copied to clipboard

dev: Auto Declare when using `ydb.Params` or another way to understand how to make Declare for variables added to `ydb.Params`

Open flymedllva opened this issue 8 months ago • 0 comments

Now it is not at all clear how to work with ydb.ParamsFromMap(m)/ydb.ParamsBuilder().Build(), let's say I do the filling of ydb.Params using these methods, using various if-then witches, but it is not clear how I should do Declare after that.

It seems only while adding a variable to Builder to change the SQL query, which seems to completely kill the essence of the builder.

Besides, it is not clear how to work with scanner/builder in the bundle

  • YDB -> Go Struct Field - it is necessary to use a scanner, which is not clear what type of field to scan into, because the types do not coincide.
  • Go Struct Field -> YDB - it is necessary to build with Builder and make Declare manually, formally types coincide.

To understand a simple example of how it is comfortable to use this builder now:

var (
	declareSb strings.Builder
	sqlSb     strings.Builder
	ydbPb     = ydb.ParamsBuilder()
)
sqlSb.WriteString(`$data = AsList(AsStruct(1 AS id),AsStruct(2 AS id));`)
sqlSb.WriteString(`SELECT id FROM AS_TABLE($data) WHERE`)
if a > 0 {
	declareSb.WriteString("DECLARE $a AS Uint64;\n")
	sqlSb.WriteString(" id = $a")
	ydbPb = ydbPb.Param("$a").Uint64(a)
} else {
	declareSb.WriteString("DECLARE $b AS Uint64;\n")
	sqlSb.WriteString(" id = $b")
	ydbPb = ydbPb.Param("$b").Uint64(uint64(b))
}
sqlSb.WriteString(";")
declareSb.WriteString(
	sqlSb.String(),
)
sql := declareSb.String()
params := ydbPb.Build()

err = db.Query().Do(ctx, func(ctx context.Context, s query.Session) (err error) {
	row, err := s.QueryRow(ctx, sql, query.WithParameters(params))
	...
})

flymedllva avatar Mar 25 '25 23:03 flymedllva