Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement random_bytes() #2365

Merged
merged 4 commits into from
Mar 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions enginetest/queries/queries.go
Original file line number Diff line number Diff line change
Expand Up @@ -9458,6 +9458,14 @@ from typestable`,
{"UNSIGNED INTEGER"},
},
},
{
Query: "select length(random_bytes(i)) from mytable;",
Expected: []sql.Row{
{1},
{2},
{3},
},
},
}

var KeylessQueries = []QueryTest{
Expand Down
115 changes: 115 additions & 0 deletions sql/expression/function/random_bytes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// Copyright 2024 Dolthub, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package function

import (
"crypto/rand"
"fmt"

"github.com/dolthub/vitess/go/sqltypes"

"github.com/dolthub/go-mysql-server/sql"
"github.com/dolthub/go-mysql-server/sql/expression"
"github.com/dolthub/go-mysql-server/sql/types"
)

const randomBytesMax = 1024

// RandomBytes returns a random binary string of the given length.
type RandomBytes struct {
expression.UnaryExpression
}

var _ sql.FunctionExpression = (*RandomBytes)(nil)
var _ sql.CollationCoercible = (*RandomBytes)(nil)

// NewRandomBytes returns a new RANDOM_BYTES function.
func NewRandomBytes(e sql.Expression) sql.Expression {
return &RandomBytes{expression.UnaryExpression{Child: e}}
}

// FunctionName implements sql.FunctionExpression
func (r *RandomBytes) FunctionName() string {
return "random_bytes"
}

// Description implements sql.FunctionExpression
func (r *RandomBytes) Description() string {
return "returns a random binary string of the given length"
}

// WithChildren implements the Expression interface.
func (r *RandomBytes) WithChildren(children ...sql.Expression) (sql.Expression, error) {
if len(children) != 1 {
return nil, sql.ErrInvalidChildrenNumber.New(r, len(children), 1)
}

return NewRandomBytes(children[0]), nil
}

// Type implements the sql.Expression interface.
func (r *RandomBytes) Type() sql.Type {
return types.MustCreateString(sqltypes.VarBinary, 1024, sql.Collation_binary)
}

// CollationCoercibility implements the interface sql.CollationCoercible.
func (*RandomBytes) CollationCoercibility(ctx *sql.Context) (collation sql.CollationID, coercibility byte) {
return sql.Collation_binary, 5
}

// String implements the sql.Expression interface.
func (r *RandomBytes) String() string {
return fmt.Sprintf("%s(%s)", r.FunctionName(), r.Child)
}

// IsNonDeterministic implements the sql.Expression interface.
func (r *RandomBytes) IsNonDeterministic() bool {
return true
}

// Eval implements the sql.Expression interface.
func (r *RandomBytes) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {
val, err := r.Child.Eval(ctx, row)
if err != nil {
return nil, err
}

if val == nil {
return nil, nil
}

val, _, err = types.Int64.Convert(val)
if err != nil {
val = 0
ctx.Warn(1292, "Truncated incorrect INTEGER value")
}

length, ok := types.CoalesceInt(val)
if !ok {
return nil, nil
}

if length <= 0 || length > randomBytesMax {
return nil, sql.ErrValueOutOfRange.New(length, r.FunctionName())
}

res := make([]byte, length)
_, err = rand.Read(res)
if err != nil {
return nil, err
}

return res, nil
}
107 changes: 107 additions & 0 deletions sql/expression/function/random_bytes_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// Copyright 2024 Dolthub, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package function

import (
"fmt"
"testing"

"github.com/stretchr/testify/require"
"gopkg.in/src-d/go-errors.v1"

"github.com/dolthub/go-mysql-server/sql"
"github.com/dolthub/go-mysql-server/sql/expression"
"github.com/dolthub/go-mysql-server/sql/types"
)

func TestRandomBytes(t *testing.T) {
testCases := []struct {
expr sql.Expression
exp interface{}
skip bool
err *errors.Kind
}{
{
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(minor) maybe another error test case where the length is of a varchar type or something.

expr: expression.NewLiteral(nil, types.Null),
exp: nil,
},
{
expr: expression.NewLiteral(int32(0), types.Int32),
err: sql.ErrValueOutOfRange,
},
{
expr: expression.NewLiteral(int32(-1), types.Int32),
err: sql.ErrValueOutOfRange,
},
{
expr: expression.NewLiteral(int32(randomBytesMax+1), types.Int32),
err: sql.ErrValueOutOfRange,
},
{
expr: expression.NewLiteral(int32(1), types.Int32),
exp: make([]byte, 1),
},
{
expr: expression.NewLiteral(int32(100), types.Int32),
exp: make([]byte, 100),
},
{
expr: expression.NewLiteral(int32(randomBytesMax), types.Int32),
exp: make([]byte, randomBytesMax),
},
{
expr: expression.NewLiteral(3.9, types.Float64),
exp: make([]byte, 4),
},
{
expr: expression.NewLiteral(3.4, types.Float64),
exp: make([]byte, 3),
},
{
expr: expression.NewLiteral("10", types.Text),
exp: make([]byte, 10),
},
{
expr: expression.NewLiteral("a", types.Text),
err: sql.ErrValueOutOfRange,
},
{
skip: true,
expr: expression.NewLiteral("1abc", types.Text),
exp: make([]byte, 1),
},
}

for _, test := range testCases {
t.Run(fmt.Sprintf("%s(%v)", "random_bytes", test.expr.String()), func(t *testing.T) {
if test.skip {
t.Skip()
}
ctx := sql.NewEmptyContext()
f := NewRandomBytes(test.expr)
res, err := f.Eval(ctx, nil)
if test.err != nil {
require.True(t, test.err.Is(err))
return
}
require.NoError(t, err)
if test.exp == nil {
require.Equal(t, test.exp, res)
return
}
require.Equal(t, len(test.exp.([]byte)), len(res.([]byte)))
})
}
}
1 change: 1 addition & 0 deletions sql/expression/function/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ var BuiltIns = []sql.Function{
sql.Function0{Name: "dense_rank", Fn: window.NewDenseRank},
sql.Function1{Name: "first_value", Fn: window.NewFirstValue},
sql.Function1{Name: "last_value", Fn: window.NewLastValue},
sql.Function1{Name: "random_bytes", Fn: NewRandomBytes},
sql.FunctionN{Name: "rpad", Fn: NewRightPad},
sql.Function1{Name: "rtrim", Fn: NewRightTrim},
sql.Function0{Name: "schema", Fn: NewDatabase},
Expand Down
Loading