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

Convert errors during ComPrepare to SQLError #1363

Merged
merged 4 commits into from
Oct 31, 2022
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
4 changes: 2 additions & 2 deletions enginetest/evaluation.go
Original file line number Diff line number Diff line change
Expand Up @@ -623,8 +623,8 @@ func AssertErrWithCtx(t *testing.T, e *sqle.Engine, harness Harness, ctx *sql.Co
}
require.Error(t, err)
if expectedErrKind != nil {
_, orig, _ := sql.CastSQLError(err)
require.True(t, expectedErrKind.Is(orig), "Expected error of type %s but got %s", expectedErrKind, err)
err = sql.UnwrapError(err)
require.True(t, expectedErrKind.Is(err), "Expected error of type %s but got %s", expectedErrKind, err)
}
// If there are multiple error strings then we only match against the first
if len(errStrs) >= 1 {
Expand Down
12 changes: 5 additions & 7 deletions server/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ func (h *Handler) ComPrepare(c *mysql.Conn, query string) ([]*query.Field, error
analyzed, err = h.e.PrepareQuery(ctx, query)
}
if err != nil {
err := sql.CastSQLError(err)
return nil, err
}

Expand Down Expand Up @@ -613,18 +614,15 @@ func (h *Handler) errorWrappedDoQuery(
}

remainder, err := h.doQuery(c, query, mode, bindings, callback)
err, _, ok := sql.CastSQLError(err)

var retErr error
if !ok {
retErr = err
if err != nil {
err = sql.CastSQLError(err)
}

if h.sel != nil {
h.sel.QueryCompleted(retErr == nil, time.Since(start))
h.sel.QueryCompleted(err == nil, time.Since(start))
}

return remainder, retErr
return remainder, err
}

// Periodically polls the connection socket to determine if it is has been closed by the client, returning an error
Expand Down
25 changes: 20 additions & 5 deletions server/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,9 +177,10 @@ func TestHandlerComPrepare(t *testing.T) {
handler.NewConnection(dummyConn)

type testcase struct {
name string
statement string
expected []*query.Field
name string
statement string
expected []*query.Field
expectedErr *mysql.SQLError
}

for _, test := range []testcase{
Expand All @@ -205,12 +206,26 @@ func TestHandlerComPrepare(t *testing.T) {
{Name: "c1", Type: query.Type_INT32, Charset: mysql.CharacterSetUtf8, ColumnLength: 11},
},
},
{
name: "errors are cast to SQLError",
statement: "SELECT * from doesnotexist LIMIT ?",
expectedErr: mysql.NewSQLError(mysql.ERNoSuchTable, "", "table not found: %s", "doesnotexist"),
},
} {
t.Run(test.name, func(t *testing.T) {
handler.ComInitDB(dummyConn, "test")
schema, err := handler.ComPrepare(dummyConn, test.statement)
require.NoError(t, err)
require.Equal(t, test.expected, schema)
if test.expectedErr == nil {
require.NoError(t, err)
require.Equal(t, test.expected, schema)
} else {
require.NotNil(t, err)
sqlErr, isSqlError := err.(*mysql.SQLError)
require.True(t, isSqlError)
require.Equal(t, test.expectedErr.Number(), sqlErr.Number())
require.Equal(t, test.expectedErr.SQLState(), sqlErr.SQLState())
require.Equal(t, test.expectedErr.Error(), sqlErr.Error())
}
})
}
}
Expand Down
25 changes: 21 additions & 4 deletions sql/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -653,12 +653,16 @@ var (
ErrNoTablesUsed = errors.NewKind("No tables used")
)

func CastSQLError(err error) (*mysql.SQLError, error, bool) {
// CastSQLError returns a *mysql.SQLError with the error code and in some cases, also a SQL state, populated for the
// specified error object. Using this method enables Vitess to return an error code, instead of just "unknown error".
// Many tools (e.g. ORMs, SQL workbenches) rely on this error metadata to work correctly. If the specified error is nil,
// nil will be returned. If the error is already of type *mysql.SQLError, the error will be returned as is.
func CastSQLError(err error) *mysql.SQLError {
if err == nil {
return nil, nil, true
return nil
}
if mysqlErr, ok := err.(*mysql.SQLError); ok {
return mysqlErr, nil, false
return mysqlErr
}

var code int
Expand Down Expand Up @@ -725,7 +729,20 @@ func CastSQLError(err error) (*mysql.SQLError, error, bool) {
}

// This uses the given error as a format string, so we have to escape any percentage signs else they'll show up as "%!(MISSING)"
return mysql.NewSQLError(code, sqlState, strings.Replace(err.Error(), `%`, `%%`, -1)), err, false // return the original error as well
return mysql.NewSQLError(code, sqlState, strings.Replace(err.Error(), `%`, `%%`, -1))
}

// UnwrapError removes any wrapping errors (e.g. WrappedInsertError) around the specified error and
// returns the first non-wrapped error type.
func UnwrapError(err error) error {
switch wrappedError := err.(type) {
case WrappedInsertError:
return UnwrapError(wrappedError.Cause)
case WrappedTypeConversionError:
return UnwrapError(wrappedError.Err)
default:
return err
}
}

type UniqueKeyError struct {
Expand Down
4 changes: 2 additions & 2 deletions sql/errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ func TestSQLErrorCast(t *testing.T) {
for _, test := range tests {
var nilErr *mysql.SQLError = nil
t.Run(fmt.Sprintf("%v %v", test.err, test.code), func(t *testing.T) {
err, _, ok := CastSQLError(test.err)
if !ok {
err := CastSQLError(test.err)
if err != nil {
require.Error(t, err)
assert.Equal(t, err.Number(), test.code)
} else {
Expand Down
4 changes: 2 additions & 2 deletions sql/plan/insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -569,7 +569,7 @@ func convertDataAndWarn(ctx *sql.Context, tableSchema sql.Schema, row sql.Row, c
row[columnIdx] = tableSchema[columnIdx].Type.Zero()
}

sqlerr, _, _ := sql.CastSQLError(err)
sqlerr := sql.CastSQLError(err)

// Add a warning instead
ctx.Session.Warn(&sql.Warning{
Expand All @@ -585,7 +585,7 @@ func warnOnIgnorableError(ctx *sql.Context, row sql.Row, err error) error {
// Check that this error is a part of the list of Ignorable Errors and create the relevant warning
for _, ie := range IgnorableErrors {
if ie.Is(err) {
sqlerr, _, _ := sql.CastSQLError(err)
sqlerr := sql.CastSQLError(err)

// Add a warning instead
ctx.Session.Warn(&sql.Warning{
Expand Down