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

     1  package bind
     2  
     3  import (
     4  	"sort"
     5  
     6  	"github.com/ydb-platform/ydb-go-sdk/v3/internal/params"
     7  	"github.com/ydb-platform/ydb-go-sdk/v3/internal/xerrors"
     8  	"github.com/ydb-platform/ydb-go-sdk/v3/internal/xstring"
     9  )
    10  
    11  type blockID int
    12  
    13  const (
    14  	blockPragma = blockID(iota)
    15  	blockDeclare
    16  	blockYQL
    17  )
    18  
    19  type Bind interface {
    20  	RewriteQuery(sql string, args ...interface{}) (
    21  		yql string, newArgs []interface{}, _ error,
    22  	)
    23  
    24  	blockID() blockID
    25  }
    26  
    27  type Bindings []Bind
    28  
    29  func (bindings Bindings) RewriteQuery(query string, args ...interface{}) (
    30  	yql string, parameters []*params.Parameter, err error,
    31  ) {
    32  	if len(bindings) == 0 {
    33  		parameters, err = Params(args...)
    34  		if err != nil {
    35  			return "", nil, xerrors.WithStackTrace(err)
    36  		}
    37  
    38  		return query, parameters, nil
    39  	}
    40  
    41  	buffer := xstring.Buffer()
    42  	defer buffer.Free()
    43  
    44  	for i := range bindings {
    45  		var e error
    46  		query, args, e = bindings[len(bindings)-1-i].RewriteQuery(query, args...)
    47  		if e != nil {
    48  			return "", nil, xerrors.WithStackTrace(e)
    49  		}
    50  	}
    51  
    52  	parameters, err = Params(args...)
    53  	if err != nil {
    54  		return "", nil, xerrors.WithStackTrace(err)
    55  	}
    56  
    57  	return query, parameters, nil
    58  }
    59  
    60  func Sort(bindings []Bind) []Bind {
    61  	sort.Slice(bindings, func(i, j int) bool {
    62  		return bindings[i].blockID() < bindings[j].blockID()
    63  	})
    64  
    65  	return bindings
    66  }