vitess.io/vitess@v0.16.2/go/mysql/constants.go (about)

     1  /*
     2  Copyright 2019 The Vitess Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package mysql
    18  
    19  import (
    20  	"strings"
    21  
    22  	"golang.org/x/text/encoding"
    23  	"golang.org/x/text/encoding/charmap"
    24  	"golang.org/x/text/encoding/simplifiedchinese"
    25  )
    26  
    27  const (
    28  	// MaxPacketSize is the maximum payload length of a packet
    29  	// the server supports.
    30  	MaxPacketSize = (1 << 24) - 1
    31  
    32  	// protocolVersion is the current version of the protocol.
    33  	// Always 10.
    34  	protocolVersion = 10
    35  )
    36  
    37  // AuthMethodDescription is the type for different supported and
    38  // implemented authentication methods.
    39  type AuthMethodDescription string
    40  
    41  // Supported auth forms.
    42  const (
    43  	// MysqlNativePassword uses a salt and transmits a hash on the wire.
    44  	MysqlNativePassword = AuthMethodDescription("mysql_native_password")
    45  
    46  	// MysqlClearPassword transmits the password in the clear.
    47  	MysqlClearPassword = AuthMethodDescription("mysql_clear_password")
    48  
    49  	// CachingSha2Password uses a salt and transmits a SHA256 hash on the wire.
    50  	CachingSha2Password = AuthMethodDescription("caching_sha2_password")
    51  
    52  	// MysqlDialog uses the dialog plugin on the client side.
    53  	// It transmits data in the clear.
    54  	MysqlDialog = AuthMethodDescription("dialog")
    55  )
    56  
    57  // Capability flags.
    58  // Originally found in include/mysql/mysql_com.h
    59  const (
    60  	// CapabilityClientLongPassword is CLIENT_LONG_PASSWORD.
    61  	// New more secure passwords. Assumed to be set since 4.1.1.
    62  	// We do not check this anywhere.
    63  	CapabilityClientLongPassword = 1
    64  
    65  	// CapabilityClientFoundRows is CLIENT_FOUND_ROWS.
    66  	CapabilityClientFoundRows = 1 << 1
    67  
    68  	// CapabilityClientLongFlag is CLIENT_LONG_FLAG.
    69  	// Longer flags in Protocol::ColumnDefinition320.
    70  	// Set it everywhere, not used, as we use Protocol::ColumnDefinition41.
    71  	CapabilityClientLongFlag = 1 << 2
    72  
    73  	// CapabilityClientConnectWithDB is CLIENT_CONNECT_WITH_DB.
    74  	// One can specify db on connect.
    75  	CapabilityClientConnectWithDB = 1 << 3
    76  
    77  	// CLIENT_NO_SCHEMA 1 << 4
    78  	// Do not permit database.table.column. We do permit it.
    79  
    80  	// CLIENT_COMPRESS 1 << 5
    81  	// We do not support compression. CPU is usually our bottleneck.
    82  
    83  	// CLIENT_ODBC 1 << 6
    84  	// No special behavior since 3.22.
    85  
    86  	// CLIENT_LOCAL_FILES 1 << 7
    87  	// Client can use LOCAL INFILE request of LOAD DATA|XML.
    88  	// We do not set it.
    89  
    90  	// CLIENT_IGNORE_SPACE 1 << 8
    91  	// Parser can ignore spaces before '('.
    92  	// We ignore this.
    93  
    94  	// CapabilityClientProtocol41 is CLIENT_PROTOCOL_41.
    95  	// New 4.1 protocol. Enforced everywhere.
    96  	CapabilityClientProtocol41 = 1 << 9
    97  
    98  	// CLIENT_INTERACTIVE 1 << 10
    99  	// Not specified, ignored.
   100  
   101  	// CapabilityClientSSL is CLIENT_SSL.
   102  	// Switch to SSL after handshake.
   103  	CapabilityClientSSL = 1 << 11
   104  
   105  	// CLIENT_IGNORE_SIGPIPE 1 << 12
   106  	// Do not issue SIGPIPE if network failures occur (libmysqlclient only).
   107  
   108  	// CapabilityClientTransactions is CLIENT_TRANSACTIONS.
   109  	// Can send status flags in EOF_Packet.
   110  	// This flag is optional in 3.23, but always set by the server since 4.0.
   111  	// We just do it all the time.
   112  	CapabilityClientTransactions = 1 << 13
   113  
   114  	// CLIENT_RESERVED 1 << 14
   115  
   116  	// CapabilityClientSecureConnection is CLIENT_SECURE_CONNECTION.
   117  	// New 4.1 authentication. Always set, expected, never checked.
   118  	CapabilityClientSecureConnection = 1 << 15
   119  
   120  	// CapabilityClientMultiStatements is CLIENT_MULTI_STATEMENTS
   121  	// Can handle multiple statements per COM_QUERY and COM_STMT_PREPARE.
   122  	CapabilityClientMultiStatements = 1 << 16
   123  
   124  	// CapabilityClientMultiResults is CLIENT_MULTI_RESULTS
   125  	// Can send multiple resultsets for COM_QUERY.
   126  	CapabilityClientMultiResults = 1 << 17
   127  
   128  	// CapabilityClientPluginAuth is CLIENT_PLUGIN_AUTH.
   129  	// Client supports plugin authentication.
   130  	CapabilityClientPluginAuth = 1 << 19
   131  
   132  	// CapabilityClientConnAttr is CLIENT_CONNECT_ATTRS
   133  	// Permits connection attributes in Protocol::HandshakeResponse41.
   134  	CapabilityClientConnAttr = 1 << 20
   135  
   136  	// CapabilityClientPluginAuthLenencClientData is CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA
   137  	CapabilityClientPluginAuthLenencClientData = 1 << 21
   138  
   139  	// CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS 1 << 22
   140  	// Announces support for expired password extension.
   141  	// Not yet supported.
   142  
   143  	// CLIENT_SESSION_TRACK 1 << 23
   144  	// Can set ServerSessionStateChanged in the Status Flags
   145  	// and send session-state change data after a OK packet.
   146  	// Not yet supported.
   147  	CapabilityClientSessionTrack = 1 << 23
   148  
   149  	// CapabilityClientDeprecateEOF is CLIENT_DEPRECATE_EOF
   150  	// Expects an OK (instead of EOF) after the resultset rows of a Text Resultset.
   151  	CapabilityClientDeprecateEOF = 1 << 24
   152  )
   153  
   154  // Status flags. They are returned by the server in a few cases.
   155  // Originally found in include/mysql/mysql_com.h
   156  // See http://dev.mysql.com/doc/internals/en/status-flags.html
   157  const (
   158  	// a transaction is active
   159  	ServerStatusInTrans   uint16 = 0x0001
   160  	NoServerStatusInTrans uint16 = 0xFFFE
   161  
   162  	// auto-commit is enabled
   163  	ServerStatusAutocommit   uint16 = 0x0002
   164  	NoServerStatusAutocommit uint16 = 0xFFFD
   165  
   166  	ServerMoreResultsExists     uint16 = 0x0008
   167  	ServerStatusNoGoodIndexUsed uint16 = 0x0010
   168  	ServerStatusNoIndexUsed     uint16 = 0x0020
   169  	// Used by Binary Protocol Resultset to signal that COM_STMT_FETCH must be used to fetch the row-data.
   170  	ServerStatusCursorExists       uint16 = 0x0040
   171  	ServerStatusLastRowSent        uint16 = 0x0080
   172  	ServerStatusDbDropped          uint16 = 0x0100
   173  	ServerStatusNoBackslashEscapes uint16 = 0x0200
   174  	ServerStatusMetadataChanged    uint16 = 0x0400
   175  	ServerQueryWasSlow             uint16 = 0x0800
   176  	ServerPsOutParams              uint16 = 0x1000
   177  	// in a read-only transaction
   178  	ServerStatusInTransReadonly uint16 = 0x2000
   179  	// connection state information has changed
   180  	ServerSessionStateChanged uint16 = 0x4000
   181  )
   182  
   183  // State Change Information
   184  const (
   185  	// one or more system variables changed.
   186  	SessionTrackSystemVariables uint8 = 0x00
   187  	// schema changed.
   188  	SessionTrackSchema uint8 = 0x01
   189  	// "track state change" changed.
   190  	SessionTrackStateChange uint8 = 0x02
   191  	// "track GTIDs" changed.
   192  	SessionTrackGtids uint8 = 0x03
   193  )
   194  
   195  // Packet types.
   196  // Originally found in include/mysql/mysql_com.h
   197  const (
   198  	// ComQuit is COM_QUIT.
   199  	ComQuit = 0x01
   200  
   201  	// ComInitDB is COM_INIT_DB.
   202  	ComInitDB = 0x02
   203  
   204  	// ComQuery is COM_QUERY.
   205  	ComQuery = 0x03
   206  
   207  	// ComFieldList is COM_Field_List.
   208  	ComFieldList = 0x04
   209  
   210  	// ComPing is COM_PING.
   211  	ComPing = 0x0e
   212  
   213  	// ComBinlogDump is COM_BINLOG_DUMP.
   214  	ComBinlogDump = 0x12
   215  
   216  	// ComSemiSyncAck is SEMI_SYNC_ACK.
   217  	ComSemiSyncAck = 0xef
   218  
   219  	// ComPrepare is COM_PREPARE.
   220  	ComPrepare = 0x16
   221  
   222  	// ComStmtExecute is COM_STMT_EXECUTE.
   223  	ComStmtExecute = 0x17
   224  
   225  	// ComStmtSendLongData is COM_STMT_SEND_LONG_DATA
   226  	ComStmtSendLongData = 0x18
   227  
   228  	// ComStmtClose is COM_STMT_CLOSE.
   229  	ComStmtClose = 0x19
   230  
   231  	// ComStmtReset is COM_STMT_RESET
   232  	ComStmtReset = 0x1a
   233  
   234  	//ComStmtFetch is COM_STMT_FETCH
   235  	ComStmtFetch = 0x1c
   236  
   237  	// ComSetOption is COM_SET_OPTION
   238  	ComSetOption = 0x1b
   239  
   240  	// ComResetConnection is COM_RESET_CONNECTION
   241  	ComResetConnection = 0x1f
   242  
   243  	// ComBinlogDumpGTID is COM_BINLOG_DUMP_GTID.
   244  	ComBinlogDumpGTID = 0x1e
   245  
   246  	// ComRegisterReplica is COM_REGISTER_SLAVE
   247  	// https://dev.mysql.com/doc/internals/en/com-register-slave.html
   248  	ComRegisterReplica = 0x15
   249  
   250  	// OKPacket is the header of the OK packet.
   251  	OKPacket = 0x00
   252  
   253  	// EOFPacket is the header of the EOF packet.
   254  	EOFPacket = 0xfe
   255  
   256  	// ErrPacket is the header of the error packet.
   257  	ErrPacket = 0xff
   258  
   259  	// NullValue is the encoded value of NULL.
   260  	NullValue = 0xfb
   261  )
   262  
   263  // Auth packet types
   264  const (
   265  	// AuthMoreDataPacket is sent when server requires more data to authenticate
   266  	AuthMoreDataPacket = 0x01
   267  
   268  	// CachingSha2FastAuth is sent before OKPacket when server authenticates using cache
   269  	CachingSha2FastAuth = 0x03
   270  
   271  	// CachingSha2FullAuth is sent when server requests un-scrambled password to authenticate
   272  	CachingSha2FullAuth = 0x04
   273  
   274  	// AuthSwitchRequestPacket is used to switch auth method.
   275  	AuthSwitchRequestPacket = 0xfe
   276  )
   277  
   278  // Error codes for client-side errors.
   279  // Originally found in include/mysql/errmsg.h and
   280  // https://dev.mysql.com/doc/mysql-errors/en/client-error-reference.html
   281  const (
   282  	// CRUnknownError is CR_UNKNOWN_ERROR
   283  	CRUnknownError = 2000
   284  
   285  	// CRConnectionError is CR_CONNECTION_ERROR
   286  	// This is returned if a connection via a Unix socket fails.
   287  	CRConnectionError = 2002
   288  
   289  	// CRConnHostError is CR_CONN_HOST_ERROR
   290  	// This is returned if a connection via a TCP socket fails.
   291  	CRConnHostError = 2003
   292  
   293  	// CRUnknownHost is CR_UNKNOWN_HOST
   294  	// This is returned if the host name cannot be resolved.
   295  	CRUnknownHost = 2005
   296  
   297  	// CRServerGone is CR_SERVER_GONE_ERROR.
   298  	// This is returned if the client tries to send a command but it fails.
   299  	CRServerGone = 2006
   300  
   301  	// CRVersionError is CR_VERSION_ERROR
   302  	// This is returned if the server versions don't match what we support.
   303  	CRVersionError = 2007
   304  
   305  	// CRServerHandshakeErr is CR_SERVER_HANDSHAKE_ERR
   306  	CRServerHandshakeErr = 2012
   307  
   308  	// CRServerLost is CR_SERVER_LOST.
   309  	// Used when:
   310  	// - the client cannot write an initial auth packet.
   311  	// - the client cannot read an initial auth packet.
   312  	// - the client cannot read a response from the server.
   313  	//     This happens when a running query is killed.
   314  	CRServerLost = 2013
   315  
   316  	// CRCommandsOutOfSync is CR_COMMANDS_OUT_OF_SYNC
   317  	// Sent when the streaming calls are not done in the right order.
   318  	CRCommandsOutOfSync = 2014
   319  
   320  	// CRNamedPipeStateError is CR_NAMEDPIPESETSTATE_ERROR.
   321  	// This is the highest possible number for a connection error.
   322  	CRNamedPipeStateError = 2018
   323  
   324  	// CRCantReadCharset is CR_CANT_READ_CHARSET
   325  	CRCantReadCharset = 2019
   326  
   327  	// CRSSLConnectionError is CR_SSL_CONNECTION_ERROR
   328  	CRSSLConnectionError = 2026
   329  
   330  	// CRMalformedPacket is CR_MALFORMED_PACKET
   331  	CRMalformedPacket = 2027
   332  )
   333  
   334  // Error codes for server-side errors.
   335  // Originally found in include/mysql/mysqld_error.h and
   336  // https://dev.mysql.com/doc/mysql-errors/en/server-error-reference.html
   337  // The below are in sorted order by value, grouped by vterror code they should be bucketed into.
   338  // See above reference for more information on each code.
   339  const (
   340  	// Vitess specific errors, (100-999)
   341  	ERNotReplica = 100
   342  
   343  	// unknown
   344  	ERUnknownError = 1105
   345  
   346  	// internal
   347  	ERInternalError = 1815
   348  
   349  	// unimplemented
   350  	ERNotSupportedYet = 1235
   351  	ERUnsupportedPS   = 1295
   352  
   353  	// resource exhausted
   354  	ERDiskFull               = 1021
   355  	EROutOfMemory            = 1037
   356  	EROutOfSortMemory        = 1038
   357  	ERConCount               = 1040
   358  	EROutOfResources         = 1041
   359  	ERRecordFileFull         = 1114
   360  	ERHostIsBlocked          = 1129
   361  	ERCantCreateThread       = 1135
   362  	ERTooManyDelayedThreads  = 1151
   363  	ERNetPacketTooLarge      = 1153
   364  	ERTooManyUserConnections = 1203
   365  	ERLockTableFull          = 1206
   366  	ERUserLimitReached       = 1226
   367  
   368  	// deadline exceeded
   369  	ERLockWaitTimeout = 1205
   370  
   371  	// unavailable
   372  	ERServerShutdown = 1053
   373  
   374  	// not found
   375  	ERDbDropExists          = 1008
   376  	ERCantFindFile          = 1017
   377  	ERFormNotFound          = 1029
   378  	ERKeyNotFound           = 1032
   379  	ERBadFieldError         = 1054
   380  	ERNoSuchThread          = 1094
   381  	ERUnknownTable          = 1109
   382  	ERCantFindUDF           = 1122
   383  	ERNonExistingGrant      = 1141
   384  	ERNoSuchTable           = 1146
   385  	ERNonExistingTableGrant = 1147
   386  	ERKeyDoesNotExist       = 1176
   387  
   388  	// permissions
   389  	ERDBAccessDenied            = 1044
   390  	ERAccessDeniedError         = 1045
   391  	ERKillDenied                = 1095
   392  	ERNoPermissionToCreateUsers = 1211
   393  	ERSpecifiedAccessDenied     = 1227
   394  
   395  	// failed precondition
   396  	ERNoDb                          = 1046
   397  	ERNoSuchIndex                   = 1082
   398  	ERCantDropFieldOrKey            = 1091
   399  	ERTableNotLockedForWrite        = 1099
   400  	ERTableNotLocked                = 1100
   401  	ERTooBigSelect                  = 1104
   402  	ERNotAllowedCommand             = 1148
   403  	ERTooLongString                 = 1162
   404  	ERDelayedInsertTableLocked      = 1165
   405  	ERDupUnique                     = 1169
   406  	ERRequiresPrimaryKey            = 1173
   407  	ERCantDoThisDuringAnTransaction = 1179
   408  	ERReadOnlyTransaction           = 1207
   409  	ERCannotAddForeign              = 1215
   410  	ERNoReferencedRow               = 1216
   411  	ERRowIsReferenced               = 1217
   412  	ERCantUpdateWithReadLock        = 1223
   413  	ERNoDefault                     = 1230
   414  	ERMasterFatalReadingBinlog      = 1236
   415  	EROperandColumns                = 1241
   416  	ERSubqueryNo1Row                = 1242
   417  	ERWarnDataOutOfRange            = 1264
   418  	ERNonUpdateableTable            = 1288
   419  	ERFeatureDisabled               = 1289
   420  	EROptionPreventsStatement       = 1290
   421  	ERDuplicatedValueInType         = 1291
   422  	ERSPDoesNotExist                = 1305
   423  	ERNoDefaultForField             = 1364
   424  	ErSPNotVarArg                   = 1414
   425  	ERRowIsReferenced2              = 1451
   426  	ErNoReferencedRow2              = 1452
   427  	ERDupIndex                      = 1831
   428  	ERInnodbReadOnly                = 1874
   429  
   430  	// already exists
   431  	ERDbCreateExists = 1007
   432  	ERTableExists    = 1050
   433  	ERDupEntry       = 1062
   434  	ERFileExists     = 1086
   435  	ERUDFExists      = 1125
   436  
   437  	// aborted
   438  	ERGotSignal          = 1078
   439  	ERForcingClose       = 1080
   440  	ERAbortingConnection = 1152
   441  	ERLockDeadlock       = 1213
   442  
   443  	// invalid arg
   444  	ERUnknownComError              = 1047
   445  	ERBadNullError                 = 1048
   446  	ERBadDb                        = 1049
   447  	ERBadTable                     = 1051
   448  	ERNonUniq                      = 1052
   449  	ERWrongFieldWithGroup          = 1055
   450  	ERWrongGroupField              = 1056
   451  	ERWrongSumSelect               = 1057
   452  	ERWrongValueCount              = 1058
   453  	ERTooLongIdent                 = 1059
   454  	ERDupFieldName                 = 1060
   455  	ERDupKeyName                   = 1061
   456  	ERWrongFieldSpec               = 1063
   457  	ERParseError                   = 1064
   458  	EREmptyQuery                   = 1065
   459  	ERNonUniqTable                 = 1066
   460  	ERInvalidDefault               = 1067
   461  	ERMultiplePriKey               = 1068
   462  	ERTooManyKeys                  = 1069
   463  	ERTooManyKeyParts              = 1070
   464  	ERTooLongKey                   = 1071
   465  	ERKeyColumnDoesNotExist        = 1072
   466  	ERBlobUsedAsKey                = 1073
   467  	ERTooBigFieldLength            = 1074
   468  	ERWrongAutoKey                 = 1075
   469  	ERWrongFieldTerminators        = 1083
   470  	ERBlobsAndNoTerminated         = 1084
   471  	ERTextFileNotReadable          = 1085
   472  	ERWrongSubKey                  = 1089
   473  	ERCantRemoveAllFields          = 1090
   474  	ERUpdateTableUsed              = 1093
   475  	ERNoTablesUsed                 = 1096
   476  	ERTooBigSet                    = 1097
   477  	ERBlobCantHaveDefault          = 1101
   478  	ERWrongDbName                  = 1102
   479  	ERWrongTableName               = 1103
   480  	ERUnknownProcedure             = 1106
   481  	ERWrongParamCountToProcedure   = 1107
   482  	ERWrongParametersToProcedure   = 1108
   483  	ERFieldSpecifiedTwice          = 1110
   484  	ERInvalidGroupFuncUse          = 1111
   485  	ERTableMustHaveColumns         = 1113
   486  	ERUnknownCharacterSet          = 1115
   487  	ERTooManyTables                = 1116
   488  	ERTooManyFields                = 1117
   489  	ERTooBigRowSize                = 1118
   490  	ERWrongOuterJoin               = 1120
   491  	ERNullColumnInIndex            = 1121
   492  	ERFunctionNotDefined           = 1128
   493  	ERWrongValueCountOnRow         = 1136
   494  	ERInvalidUseOfNull             = 1138
   495  	ERRegexpError                  = 1139
   496  	ERMixOfGroupFuncAndFields      = 1140
   497  	ERIllegalGrantForTable         = 1144
   498  	ERSyntaxError                  = 1149
   499  	ERWrongColumnName              = 1166
   500  	ERWrongKeyColumn               = 1167
   501  	ERBlobKeyWithoutLength         = 1170
   502  	ERPrimaryCantHaveNull          = 1171
   503  	ERTooManyRows                  = 1172
   504  	ERLockOrActiveTransaction      = 1192
   505  	ERUnknownSystemVariable        = 1193
   506  	ERSetConstantsOnly             = 1204
   507  	ERWrongArguments               = 1210
   508  	ERWrongUsage                   = 1221
   509  	ERWrongNumberOfColumnsInSelect = 1222
   510  	ERDupArgument                  = 1225
   511  	ERLocalVariable                = 1228
   512  	ERGlobalVariable               = 1229
   513  	ERWrongValueForVar             = 1231
   514  	ERWrongTypeForVar              = 1232
   515  	ERVarCantBeRead                = 1233
   516  	ERCantUseOptionHere            = 1234
   517  	ERIncorrectGlobalLocalVar      = 1238
   518  	ERWrongFKDef                   = 1239
   519  	ERKeyRefDoNotMatchTableRef     = 1240
   520  	ERCyclicReference              = 1245
   521  	ERIllegalReference             = 1247
   522  	ERDerivedMustHaveAlias         = 1248
   523  	ERTableNameNotAllowedHere      = 1250
   524  	ERCollationCharsetMismatch     = 1253
   525  	ERWarnDataTruncated            = 1265
   526  	ERCantAggregate2Collations     = 1267
   527  	ERCantAggregate3Collations     = 1270
   528  	ERCantAggregateNCollations     = 1271
   529  	ERVariableIsNotStruct          = 1272
   530  	ERUnknownCollation             = 1273
   531  	ERWrongNameForIndex            = 1280
   532  	ERWrongNameForCatalog          = 1281
   533  	ERBadFTColumn                  = 1283
   534  	ERTruncatedWrongValue          = 1292
   535  	ERTooMuchAutoTimestampCols     = 1293
   536  	ERInvalidOnUpdate              = 1294
   537  	ERUnknownTimeZone              = 1298
   538  	ERInvalidCharacterString       = 1300
   539  	ERQueryInterrupted             = 1317
   540  	ERTruncatedWrongValueForField  = 1366
   541  	ERIllegalValueForType          = 1367
   542  	ERDataTooLong                  = 1406
   543  	ErrWrongValueForType           = 1411
   544  	ERForbidSchemaChange           = 1450
   545  	ERWrongValue                   = 1525
   546  	ERDataOutOfRange               = 1690
   547  	ERInvalidJSONText              = 3140
   548  	ERInvalidJSONTextInParams      = 3141
   549  	ERInvalidJSONBinaryData        = 3142
   550  	ERInvalidJSONCharset           = 3144
   551  	ERInvalidCastToJSON            = 3147
   552  	ERJSONValueTooBig              = 3150
   553  	ERJSONDocumentTooDeep          = 3157
   554  
   555  	// max execution time exceeded
   556  	ERQueryTimeout = 3024
   557  
   558  	ErrCantCreateGeometryObject      = 1416
   559  	ErrGISDataWrongEndianess         = 3055
   560  	ErrNotImplementedForCartesianSRS = 3704
   561  	ErrNotImplementedForProjectedSRS = 3705
   562  	ErrNonPositiveRadius             = 3706
   563  
   564  	// server not available
   565  	ERServerIsntAvailable = 3168
   566  )
   567  
   568  // Sql states for errors.
   569  // Originally found in include/mysql/sql_state.h
   570  const (
   571  	// SSUnknownSqlstate is ER_SIGNAL_EXCEPTION in
   572  	// include/mysql/sql_state.h, but:
   573  	// const char *unknown_sqlstate= "HY000"
   574  	// in client.c. So using that one.
   575  	SSUnknownSQLState = "HY000"
   576  
   577  	// SSNetError is network related error
   578  	SSNetError = "08S01"
   579  
   580  	// SSWrongNumberOfColumns is related to columns error
   581  	SSWrongNumberOfColumns = "21000"
   582  
   583  	// SSWrongValueCountOnRow is related to columns count mismatch error
   584  	SSWrongValueCountOnRow = "21S01"
   585  
   586  	// SSDataTooLong is ER_DATA_TOO_LONG
   587  	SSDataTooLong = "22001"
   588  
   589  	// SSDataOutOfRange is ER_DATA_OUT_OF_RANGE
   590  	SSDataOutOfRange = "22003"
   591  
   592  	// SSConstraintViolation is constraint violation
   593  	SSConstraintViolation = "23000"
   594  
   595  	// SSCantDoThisDuringAnTransaction is
   596  	// ER_CANT_DO_THIS_DURING_AN_TRANSACTION
   597  	SSCantDoThisDuringAnTransaction = "25000"
   598  
   599  	// SSAccessDeniedError is ER_ACCESS_DENIED_ERROR
   600  	SSAccessDeniedError = "28000"
   601  
   602  	// SSNoDB is ER_NO_DB_ERROR
   603  	SSNoDB = "3D000"
   604  
   605  	// SSLockDeadlock is ER_LOCK_DEADLOCK
   606  	SSLockDeadlock = "40001"
   607  
   608  	// SSClientError is the state on client errors
   609  	SSClientError = "42000"
   610  
   611  	// SSDupFieldName is ER_DUP_FIELD_NAME
   612  	SSDupFieldName = "42S21"
   613  
   614  	// SSBadFieldError is ER_BAD_FIELD_ERROR
   615  	SSBadFieldError = "42S22"
   616  
   617  	// SSUnknownTable is ER_UNKNOWN_TABLE
   618  	SSUnknownTable = "42S02"
   619  
   620  	// SSQueryInterrupted is ER_QUERY_INTERRUPTED;
   621  	SSQueryInterrupted = "70100"
   622  )
   623  
   624  // CharacterSetEncoding maps a charset name to a golang encoder.
   625  // golang does not support encoders for all MySQL charsets.
   626  // A charset not in this map is unsupported.
   627  // A trivial encoding (e.g. utf8) has a `nil` encoder
   628  var CharacterSetEncoding = map[string]encoding.Encoding{
   629  	"cp850":   charmap.CodePage850,
   630  	"koi8r":   charmap.KOI8R,
   631  	"latin1":  charmap.Windows1252,
   632  	"latin2":  charmap.ISO8859_2,
   633  	"ascii":   nil,
   634  	"hebrew":  charmap.ISO8859_8,
   635  	"greek":   charmap.ISO8859_7,
   636  	"cp1250":  charmap.Windows1250,
   637  	"gbk":     simplifiedchinese.GBK,
   638  	"latin5":  charmap.ISO8859_9,
   639  	"utf8":    nil,
   640  	"utf8mb3": nil,
   641  	"cp866":   charmap.CodePage866,
   642  	"cp852":   charmap.CodePage852,
   643  	"latin7":  charmap.ISO8859_13,
   644  	"utf8mb4": nil,
   645  	"cp1251":  charmap.Windows1251,
   646  	"cp1256":  charmap.Windows1256,
   647  	"cp1257":  charmap.Windows1257,
   648  	"binary":  nil,
   649  }
   650  
   651  // IsNum returns true if a MySQL type is a numeric value.
   652  // It is the same as IS_NUM defined in mysql.h.
   653  func IsNum(typ uint8) bool {
   654  	return (typ <= TypeInt24 && typ != TypeTimestamp) ||
   655  		typ == TypeYear ||
   656  		typ == TypeNewDecimal
   657  }
   658  
   659  // IsConnErr returns true if the error is a connection error.
   660  func IsConnErr(err error) bool {
   661  	if IsTooManyConnectionsErr(err) {
   662  		return false
   663  	}
   664  	if sqlErr, ok := err.(*SQLError); ok {
   665  		num := sqlErr.Number()
   666  		return (num >= CRUnknownError && num <= CRNamedPipeStateError) || num == ERQueryInterrupted
   667  	}
   668  	return false
   669  }
   670  
   671  // IsConnLostDuringQuery returns true if the error is a CRServerLost error.
   672  // Happens most commonly when a query is killed MySQL server-side.
   673  func IsConnLostDuringQuery(err error) bool {
   674  	if sqlErr, ok := err.(*SQLError); ok {
   675  		num := sqlErr.Number()
   676  		return (num == CRServerLost)
   677  	}
   678  	return false
   679  }
   680  
   681  // IsEphemeralError returns true if the error is ephemeral and the caller should
   682  // retry if possible. Note: non-SQL errors are always treated as ephemeral.
   683  func IsEphemeralError(err error) bool {
   684  	if sqlErr, ok := err.(*SQLError); ok {
   685  		en := sqlErr.Number()
   686  		switch en {
   687  		case
   688  			CRConnectionError,
   689  			CRConnHostError,
   690  			CRMalformedPacket,
   691  			CRNamedPipeStateError,
   692  			CRServerHandshakeErr,
   693  			CRServerGone,
   694  			CRServerLost,
   695  			CRSSLConnectionError,
   696  			CRUnknownError,
   697  			CRUnknownHost,
   698  			ERCantCreateThread,
   699  			ERDiskFull,
   700  			ERForcingClose,
   701  			ERGotSignal,
   702  			ERHostIsBlocked,
   703  			ERLockTableFull,
   704  			ERInnodbReadOnly,
   705  			ERInternalError,
   706  			ERLockDeadlock,
   707  			ERLockWaitTimeout,
   708  			ERQueryTimeout,
   709  			EROutOfMemory,
   710  			EROutOfResources,
   711  			EROutOfSortMemory,
   712  			ERQueryInterrupted,
   713  			ERServerIsntAvailable,
   714  			ERServerShutdown,
   715  			ERTooManyUserConnections,
   716  			ERUnknownError,
   717  			ERUserLimitReached:
   718  			return true
   719  		default:
   720  			return false
   721  		}
   722  	}
   723  	// If it's not an sqlError then we assume it's ephemeral
   724  	return true
   725  }
   726  
   727  // IsTooManyConnectionsErr returns true if the error is due to too many connections.
   728  func IsTooManyConnectionsErr(err error) bool {
   729  	if sqlErr, ok := err.(*SQLError); ok {
   730  		if sqlErr.Number() == CRServerHandshakeErr && strings.Contains(sqlErr.Message, "Too many connections") {
   731  			return true
   732  		}
   733  	}
   734  	return false
   735  }
   736  
   737  // IsSchemaApplyError returns true when given error is a MySQL error applying schema change
   738  func IsSchemaApplyError(err error) bool {
   739  	merr, isSQLErr := err.(*SQLError)
   740  	if !isSQLErr {
   741  		return false
   742  	}
   743  	switch merr.Num {
   744  	case
   745  		ERDupKeyName,
   746  		ERCantDropFieldOrKey,
   747  		ERTableExists,
   748  		ERDupFieldName:
   749  		return true
   750  	}
   751  	return false
   752  }
   753  
   754  type ReplicationState int
   755  
   756  const (
   757  	ReplicationStateUnknown ReplicationState = iota
   758  	ReplicationStateStopped
   759  	ReplicationStateConnecting
   760  	ReplicationStateRunning
   761  )
   762  
   763  // ReplicationStatusToState converts a value you have for the IO thread(s) or SQL
   764  // thread(s) or Group Replication applier thread(s) from MySQL or intermediate
   765  // layers to a mysql.ReplicationState.
   766  // on,yes,true == ReplicationStateRunning
   767  // off,no,false == ReplicationStateStopped
   768  // connecting == ReplicationStateConnecting
   769  // anything else == ReplicationStateUnknown
   770  func ReplicationStatusToState(s string) ReplicationState {
   771  	// Group Replication uses ON instead of Yes
   772  	switch strings.ToLower(s) {
   773  	case "yes", "on", "true":
   774  		return ReplicationStateRunning
   775  	case "no", "off", "false":
   776  		return ReplicationStateStopped
   777  	case "connecting":
   778  		return ReplicationStateConnecting
   779  	default:
   780  		return ReplicationStateUnknown
   781  	}
   782  }