github.com/dolthub/go-mysql-server@v0.18.0/sql/expression/binary.go (about)

     1  // Copyright 2021 Dolthub, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package expression
    16  
    17  import (
    18  	"fmt"
    19  
    20  	"github.com/dolthub/go-mysql-server/sql"
    21  	"github.com/dolthub/go-mysql-server/sql/types"
    22  )
    23  
    24  // The BINARY operator converts the expression to a binary string (a string that has the binary character set and binary
    25  // collation). A common use for BINARY is to force a character string comparison to be done byte by byte using numeric
    26  // byte values rather than character by character. The BINARY operator also causes trailing spaces in comparisons to be
    27  // significant.
    28  //
    29  // cc: https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html#operator_binary
    30  type Binary struct {
    31  	UnaryExpression
    32  }
    33  
    34  var _ sql.Expression = (*Binary)(nil)
    35  var _ sql.CollationCoercible = (*Binary)(nil)
    36  
    37  func NewBinary(e sql.Expression) sql.Expression {
    38  	return &Binary{UnaryExpression{Child: e}}
    39  }
    40  
    41  func (b *Binary) String() string {
    42  	return fmt.Sprintf("BINARY(%s)", b.Child.String())
    43  }
    44  
    45  func (b *Binary) Type() sql.Type {
    46  	return types.LongBlob
    47  }
    48  
    49  // CollationCoercibility implements the interface sql.CollationCoercible.
    50  func (*Binary) CollationCoercibility(ctx *sql.Context) (collation sql.CollationID, coercibility byte) {
    51  	return sql.Collation_binary, 2
    52  }
    53  
    54  func (b *Binary) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {
    55  	val, err := b.Child.Eval(ctx, row)
    56  	if err != nil {
    57  		return nil, err
    58  	}
    59  
    60  	return convertValue(val, ConvertToBinary, b.Child.Type(), 0, 0)
    61  }
    62  
    63  func (b *Binary) WithChildren(children ...sql.Expression) (sql.Expression, error) {
    64  	if len(children) != 1 {
    65  		return nil, sql.ErrInvalidArgumentNumber.New("BINARY", "1", len(children))
    66  	}
    67  
    68  	return NewBinary(children[0]), nil
    69  }