-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
sql_error.go
227 lines (197 loc) · 8.02 KB
/
sql_error.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/*
Copyright 2019 The Vitess Authors.
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 mysql
import (
"bytes"
"fmt"
"regexp"
"strconv"
"vitess.io/vitess/go/vt/sqlparser"
"vitess.io/vitess/go/vt/vterrors"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
)
// SQLError is the error structure returned from calling a db library function
type SQLError struct {
Num int
State string
Message string
Query string
}
// NewSQLError creates a new SQLError.
// If sqlState is left empty, it will default to "HY000" (general error).
// TODO: Should be aligned with vterrors, stack traces and wrapping
func NewSQLError(number int, sqlState string, format string, args ...interface{}) *SQLError {
if sqlState == "" {
sqlState = SSUnknownSQLState
}
return &SQLError{
Num: number,
State: sqlState,
Message: fmt.Sprintf(format, args...),
}
}
// Error implements the error interface
func (se *SQLError) Error() string {
buf := &bytes.Buffer{}
buf.WriteString(se.Message)
// Add MySQL errno and SQLSTATE in a format that we can later parse.
// There's no avoiding string parsing because all errors
// are converted to strings anyway at RPC boundaries.
// See NewSQLErrorFromError.
fmt.Fprintf(buf, " (errno %v) (sqlstate %v)", se.Num, se.State)
if se.Query != "" {
fmt.Fprintf(buf, " during query: %s", sqlparser.TruncateForLog(se.Query))
}
return buf.String()
}
// Number returns the internal MySQL error code.
func (se *SQLError) Number() int {
return se.Num
}
// SQLState returns the SQLSTATE value.
func (se *SQLError) SQLState() string {
return se.State
}
var errExtract = regexp.MustCompile(`.*\(errno ([0-9]*)\) \(sqlstate ([0-9a-zA-Z]{5})\).*`)
// NewSQLErrorFromError returns a *SQLError from the provided error.
// If it's not the right type, it still tries to get it from a regexp.
func NewSQLErrorFromError(err error) error {
if err == nil {
return nil
}
if serr, ok := err.(*SQLError); ok {
return serr
}
sErr := convertToMysqlError(err)
if serr, ok := sErr.(*SQLError); ok {
return serr
}
msg := err.Error()
match := errExtract.FindStringSubmatch(msg)
if len(match) >= 2 {
return extractSQLErrorFromMessage(match, msg)
}
return mapToSQLErrorFromErrorCode(err, msg)
}
func extractSQLErrorFromMessage(match []string, msg string) *SQLError {
num, err := strconv.Atoi(match[1])
if err != nil {
return &SQLError{
Num: ERUnknownError,
State: SSUnknownSQLState,
Message: msg,
}
}
return &SQLError{
Num: num,
State: match[2],
Message: msg,
}
}
func mapToSQLErrorFromErrorCode(err error, msg string) *SQLError {
// Map vitess error codes into the mysql equivalent
num := ERUnknownError
ss := SSUnknownSQLState
switch vterrors.Code(err) {
case vtrpcpb.Code_CANCELED, vtrpcpb.Code_DEADLINE_EXCEEDED, vtrpcpb.Code_ABORTED:
num = ERQueryInterrupted
ss = SSQueryInterrupted
case vtrpcpb.Code_PERMISSION_DENIED, vtrpcpb.Code_UNAUTHENTICATED:
num = ERAccessDeniedError
ss = SSAccessDeniedError
case vtrpcpb.Code_RESOURCE_EXHAUSTED:
num = demuxResourceExhaustedErrors(err.Error())
ss = SSClientError
case vtrpcpb.Code_UNIMPLEMENTED:
num = ERNotSupportedYet
ss = SSClientError
case vtrpcpb.Code_INTERNAL:
num = ERInternalError
ss = SSUnknownSQLState
}
// Not found, build a generic SQLError.
return &SQLError{
Num: num,
State: ss,
Message: msg,
}
}
var stateToMysqlCode = map[vterrors.State]struct {
num int
state string
}{
vterrors.Undefined: {num: ERUnknownError, state: SSUnknownSQLState},
vterrors.AccessDeniedError: {num: ERAccessDeniedError, state: SSAccessDeniedError},
vterrors.BadDb: {num: ERBadDb, state: SSClientError},
vterrors.BadFieldError: {num: ERBadFieldError, state: SSBadFieldError},
vterrors.BadTableError: {num: ERBadTable, state: SSUnknownTable},
vterrors.CantUseOptionHere: {num: ERCantUseOptionHere, state: SSClientError},
vterrors.DataOutOfRange: {num: ERDataOutOfRange, state: SSDataOutOfRange},
vterrors.DbCreateExists: {num: ERDbCreateExists, state: SSUnknownSQLState},
vterrors.DbDropExists: {num: ERDbDropExists, state: SSUnknownSQLState},
vterrors.DupFieldName: {num: ERDupFieldName, state: SSDupFieldName},
vterrors.EmptyQuery: {num: EREmptyQuery, state: SSClientError},
vterrors.IncorrectGlobalLocalVar: {num: ERIncorrectGlobalLocalVar, state: SSUnknownSQLState},
vterrors.InnodbReadOnly: {num: ERInnodbReadOnly, state: SSUnknownSQLState},
vterrors.LockOrActiveTransaction: {num: ERLockOrActiveTransaction, state: SSUnknownSQLState},
vterrors.NoDB: {num: ERNoDb, state: SSNoDB},
vterrors.NoSuchTable: {num: ERNoSuchTable, state: SSUnknownTable},
vterrors.NotSupportedYet: {num: ERNotSupportedYet, state: SSClientError},
vterrors.ForbidSchemaChange: {num: ERForbidSchemaChange, state: SSUnknownSQLState},
vterrors.MixOfGroupFuncAndFields: {num: ERMixOfGroupFuncAndFields, state: SSClientError},
vterrors.NetPacketTooLarge: {num: ERNetPacketTooLarge, state: SSNetError},
vterrors.NonUniqError: {num: ERNonUniq, state: SSConstraintViolation},
vterrors.NonUniqTable: {num: ERNonUniqTable, state: SSClientError},
vterrors.NonUpdateableTable: {num: ERNonUpdateableTable, state: SSUnknownSQLState},
vterrors.QueryInterrupted: {num: ERQueryInterrupted, state: SSQueryInterrupted},
vterrors.SPDoesNotExist: {num: ERSPDoesNotExist, state: SSClientError},
vterrors.SyntaxError: {num: ERSyntaxError, state: SSClientError},
vterrors.UnsupportedPS: {num: ERUnsupportedPS, state: SSUnknownSQLState},
vterrors.UnknownSystemVariable: {num: ERUnknownSystemVariable, state: SSUnknownSQLState},
vterrors.UnknownTable: {num: ERUnknownTable, state: SSUnknownTable},
vterrors.WrongGroupField: {num: ERWrongGroupField, state: SSClientError},
vterrors.WrongNumberOfColumnsInSelect: {num: ERWrongNumberOfColumnsInSelect, state: SSWrongNumberOfColumns},
vterrors.WrongTypeForVar: {num: ERWrongTypeForVar, state: SSClientError},
vterrors.WrongValueForVar: {num: ERWrongValueForVar, state: SSClientError},
vterrors.WrongFieldWithGroup: {num: ERWrongFieldWithGroup, state: SSClientError},
vterrors.ServerNotAvailable: {num: ERServerIsntAvailable, state: SSNetError},
vterrors.CantDoThisInTransaction: {num: ERCantDoThisDuringAnTransaction, state: SSCantDoThisDuringAnTransaction},
vterrors.RequiresPrimaryKey: {num: ERRequiresPrimaryKey, state: SSClientError},
vterrors.NoSuchSession: {num: ERUnknownComError, state: SSNetError},
vterrors.OperandColumns: {num: EROperandColumns, state: SSWrongNumberOfColumns},
}
func init() {
if len(stateToMysqlCode) != int(vterrors.NumOfStates) {
panic("all vterrors states are not mapped to mysql errors")
}
}
func convertToMysqlError(err error) error {
errState := vterrors.ErrState(err)
if errState == vterrors.Undefined {
return err
}
mysqlCode, ok := stateToMysqlCode[errState]
if !ok {
return err
}
return NewSQLError(mysqlCode.num, mysqlCode.state, err.Error())
}
var isGRPCOverflowRE = regexp.MustCompile(`.*?grpc: (received|trying to send) message larger than max \(\d+ vs. \d+\)`)
func demuxResourceExhaustedErrors(msg string) int {
switch {
case isGRPCOverflowRE.Match([]byte(msg)):
return ERNetPacketTooLarge
default:
return ERTooManyUserConnections
}
}