github.com/ydb-platform/ydb-go-sdk/v3@v3.57.0/internal/bind/auto_declare.go (about)

     1  package bind
     2  
     3  import (
     4  	"sort"
     5  
     6  	"github.com/ydb-platform/ydb-go-sdk/v3/internal/xerrors"
     7  	"github.com/ydb-platform/ydb-go-sdk/v3/internal/xstring"
     8  )
     9  
    10  type AutoDeclare struct{}
    11  
    12  func (m AutoDeclare) blockID() blockID {
    13  	return blockDeclare
    14  }
    15  
    16  func (m AutoDeclare) RewriteQuery(query string, args ...interface{}) (
    17  	yql string, newArgs []interface{}, err error,
    18  ) {
    19  	params, err := Params(args...)
    20  	if err != nil {
    21  		return "", nil, xerrors.WithStackTrace(err)
    22  	}
    23  
    24  	if len(params) == 0 {
    25  		return query, args, nil
    26  	}
    27  
    28  	var (
    29  		declares = make([]string, 0, len(params))
    30  		buffer   = xstring.Buffer()
    31  	)
    32  	defer buffer.Free()
    33  
    34  	buffer.WriteString("-- bind declares\n")
    35  
    36  	for _, param := range params {
    37  		declares = append(declares, "DECLARE "+param.Name()+" AS "+param.Value().Type().Yql()+";")
    38  	}
    39  
    40  	sort.Strings(declares)
    41  
    42  	for _, d := range declares {
    43  		buffer.WriteString(d)
    44  		buffer.WriteByte('\n')
    45  	}
    46  
    47  	buffer.WriteByte('\n')
    48  
    49  	buffer.WriteString(query)
    50  
    51  	for _, param := range params {
    52  		newArgs = append(newArgs, param)
    53  	}
    54  
    55  	return buffer.String(), newArgs, nil
    56  }