github.com/matrixorigin/matrixone@v1.2.0/pkg/common/moerr/error.go (about)

     1  // Copyright 2021 - 2022 Matrix Origin
     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 moerr
    16  
    17  import (
    18  	"context"
    19  	"encoding"
    20  	"encoding/hex"
    21  	"fmt"
    22  	"io"
    23  	"sync/atomic"
    24  
    25  	moerrpb "github.com/matrixorigin/matrixone/pkg/pb/moerr"
    26  	"github.com/matrixorigin/matrixone/pkg/util/errutil"
    27  	"github.com/matrixorigin/matrixone/pkg/util/stack"
    28  )
    29  
    30  const MySQLDefaultSqlState = "HY000"
    31  
    32  const (
    33  	// 0 - 99 is OK.  They do not contain info, and are special handled
    34  	// using a static instance, no alloc.
    35  	Ok              uint16 = 0
    36  	OkStopCurrRecur uint16 = 1
    37  	OkExpectedEOF   uint16 = 2 // Expected End Of File
    38  	OkExpectedEOB   uint16 = 3 // Expected End of Batch
    39  	OkExpectedDup   uint16 = 4 // Expected Duplicate
    40  
    41  	OkExpectedPossibleDup uint16 = 5 // Expected Possible Duplicate
    42  
    43  	// OkExpectedNotSafeToStartTransfer is not an error, but is expected
    44  	// phenomenon that the connection is not safe to transfer to other nodes.
    45  	OkExpectedNotSafeToStartTransfer uint16 = 6
    46  	//mysql client sends the COM_QUIT to the server before closing the connection.
    47  	MysqlClientQuit uint16 = 7
    48  
    49  	OkMax uint16 = 99
    50  
    51  	// 100 - 200 is Info
    52  	ErrInfo     uint16 = 100
    53  	ErrLoadInfo uint16 = 101
    54  
    55  	// 100 - 200 is WARNING
    56  	ErrWarn uint16 = 200
    57  	// In some cases, for example, varchar(N), truncated is a warning instead error.
    58  	ErrWarnDataTruncated uint16 = 201
    59  
    60  	// Group 1: Internal errors
    61  	ErrStart            uint16 = 20100
    62  	ErrInternal         uint16 = 20101
    63  	ErrNYI              uint16 = 20102
    64  	ErrOOM              uint16 = 20103
    65  	ErrQueryInterrupted uint16 = 20104
    66  	ErrNotSupported     uint16 = 20105
    67  
    68  	// Group 2: numeric and functions
    69  	ErrDivByZero                   uint16 = 20200
    70  	ErrOutOfRange                  uint16 = 20201
    71  	ErrDataTruncated               uint16 = 20202
    72  	ErrInvalidArg                  uint16 = 20203
    73  	ErrTruncatedWrongValueForField uint16 = 20204
    74  
    75  	// Group 3: invalid input
    76  	ErrBadConfig            uint16 = 20300
    77  	ErrInvalidInput         uint16 = 20301
    78  	ErrSyntaxError          uint16 = 20302
    79  	ErrParseError           uint16 = 20303
    80  	ErrConstraintViolation  uint16 = 20304
    81  	ErrDuplicate            uint16 = 20305
    82  	ErrRoleGrantedToSelf    uint16 = 20306
    83  	ErrDuplicateEntry       uint16 = 20307
    84  	ErrWrongValueCountOnRow uint16 = 20308
    85  	ErrBadFieldError        uint16 = 20309
    86  	ErrWrongDatetimeSpec    uint16 = 20310
    87  	ErrUpgrateError         uint16 = 20311
    88  	ErrInvalidTz            uint16 = 20312
    89  
    90  	// Group 4: unexpected state and io errors
    91  	ErrInvalidState                             uint16 = 20400
    92  	ErrLogServiceNotReady                       uint16 = 20401
    93  	ErrBadDB                                    uint16 = 20402
    94  	ErrNoSuchTable                              uint16 = 20403
    95  	ErrEmptyVector                              uint16 = 20404
    96  	ErrFileNotFound                             uint16 = 20405
    97  	ErrFileAlreadyExists                        uint16 = 20406
    98  	ErrUnexpectedEOF                            uint16 = 20407
    99  	ErrEmptyRange                               uint16 = 20408
   100  	ErrSizeNotMatch                             uint16 = 20409
   101  	ErrNoProgress                               uint16 = 20410
   102  	ErrInvalidPath                              uint16 = 20411
   103  	ErrShortWrite                               uint16 = 20412
   104  	ErrInvalidWrite                             uint16 = 20413
   105  	ErrShortBuffer                              uint16 = 20414
   106  	ErrNoDB                                     uint16 = 20415
   107  	ErrNoWorkingStore                           uint16 = 20416
   108  	ErrNoHAKeeper                               uint16 = 20417
   109  	ErrInvalidTruncateLsn                       uint16 = 20418
   110  	ErrNotLeaseHolder                           uint16 = 20419
   111  	ErrDBAlreadyExists                          uint16 = 20420
   112  	ErrTableAlreadyExists                       uint16 = 20421
   113  	ErrNoService                                uint16 = 20422
   114  	ErrDupServiceName                           uint16 = 20423
   115  	ErrWrongService                             uint16 = 20424
   116  	ErrBadS3Config                              uint16 = 20425
   117  	ErrBadView                                  uint16 = 20426
   118  	ErrInvalidTask                              uint16 = 20427
   119  	ErrInvalidServiceIndex                      uint16 = 20428
   120  	ErrDragonboatTimeout                        uint16 = 20429
   121  	ErrDragonboatTimeoutTooSmall                uint16 = 20430
   122  	ErrDragonboatInvalidDeadline                uint16 = 20431
   123  	ErrDragonboatRejected                       uint16 = 20432
   124  	ErrDragonboatInvalidPayloadSize             uint16 = 20433
   125  	ErrDragonboatShardNotReady                  uint16 = 20434
   126  	ErrDragonboatSystemClosed                   uint16 = 20435
   127  	ErrDragonboatInvalidRange                   uint16 = 20436
   128  	ErrDragonboatShardNotFound                  uint16 = 20437
   129  	ErrDragonboatOtherSystemError               uint16 = 20438
   130  	ErrDropNonExistsDB                          uint16 = 20439
   131  	ErrResultFileNotFound                       uint16 = 20440
   132  	ErrFunctionAlreadyExists                    uint16 = 20441
   133  	ErrDropNonExistsFunction                    uint16 = 20442
   134  	ErrNoConfig                                 uint16 = 20443
   135  	ErrNoSuchSequence                           uint16 = 20444
   136  	ErrProcedureAlreadyExists                   uint16 = 20445
   137  	ErrTooManyFields                            uint16 = 20446
   138  	ErrDupFieldName                             uint16 = 20447
   139  	ErrMultiplePriKey                           uint16 = 20448
   140  	ErrTooManyKeys                              uint16 = 20449
   141  	ErrTooManyKeyParts                          uint16 = 20450
   142  	ErrWrongColumnName                          uint16 = 20451
   143  	ErrWrongNameForIndex                        uint16 = 20452
   144  	ErrInvalidDefault                           uint16 = 20453
   145  	ErrDropIndexNeededInForeignKey              uint16 = 20454
   146  	ErrFKIncompatibleColumns                    uint16 = 20455
   147  	ErrForeignKeyColumnCannotChangeChild        uint16 = 20456
   148  	ErrForeignKeyColumnCannotChange             uint16 = 20457
   149  	ErrForeignKeyOnPartitioned                  uint16 = 20458
   150  	ErrKeyColumnDoesNotExist                    uint16 = 20459
   151  	ErrCantDropFieldOrKey                       uint16 = 20460
   152  	ErrTableMustHaveColumns                     uint16 = 20461
   153  	ErrCantRemoveAllFields                      uint16 = 20462
   154  	ErrFkColumnCannotDrop                       uint16 = 20463
   155  	ErrFkColumnCannotDropChild                  uint16 = 20464
   156  	ErrDependentByPartitionFunction             uint16 = 20465
   157  	ErrAlterOperationNotSupportedReasonFkRename uint16 = 20466
   158  	ErrPrimaryCantHaveNull                      uint16 = 20467
   159  	ErrPartitionMgmtOnNonpartitioned            uint16 = 20468
   160  	ErrFKRowIsReferenced                        uint16 = 20469
   161  	ErrDuplicateKeyName                         uint16 = 20470
   162  	ErrFKNoReferencedRow2                       uint16 = 20471
   163  	// Group 5: rpc timeout
   164  	// ErrRPCTimeout rpc timeout
   165  	ErrRPCTimeout uint16 = 20500
   166  	// ErrClientClosed rpc client closed
   167  	ErrClientClosed uint16 = 20501
   168  	// ErrBackendClosed backend closed
   169  	ErrBackendClosed uint16 = 20502
   170  	// ErrStreamClosed rpc stream closed
   171  	ErrStreamClosed uint16 = 20503
   172  	// ErrNoAvailableBackend no available backend
   173  	ErrNoAvailableBackend uint16 = 20504
   174  	// ErrBackendCannotConnect can not connect to remote backend
   175  	ErrBackendCannotConnect uint16 = 20505
   176  
   177  	// Group 6: txn
   178  	// ErrTxnAborted read and write a transaction that has been rolled back.
   179  	ErrTxnClosed uint16 = 20600
   180  	// ErrTxnWriteConflict write conflict error for concurrent transactions
   181  	ErrTxnWriteConflict uint16 = 20601
   182  	// ErrMissingTxn missing transaction error
   183  	ErrMissingTxn uint16 = 20602
   184  	// ErrUnresolvedConflict read transaction encounters unresolved data
   185  	ErrUnresolvedConflict uint16 = 20603
   186  	// ErrTxnError TxnError wrapper
   187  	ErrTxnError uint16 = 20604
   188  	// ErrTNShardNotFound DNShard not found, need to get the latest TN list from HAKeeper
   189  	ErrTNShardNotFound  uint16 = 20605
   190  	ErrShardNotReported uint16 = 20606
   191  	// Generic TAE error
   192  	ErrTAEError                   uint16 = 20607
   193  	ErrTAERead                    uint16 = 20608
   194  	ErrRpcError                   uint16 = 20609
   195  	ErrWaitTxn                    uint16 = 20610
   196  	ErrTxnNotFound                uint16 = 20611
   197  	ErrTxnNotActive               uint16 = 20612
   198  	ErrTAEWrite                   uint16 = 20613
   199  	ErrTAECommit                  uint16 = 20614
   200  	ErrTAERollback                uint16 = 20615
   201  	ErrTAEPrepare                 uint16 = 20616
   202  	ErrTAEPossibleDuplicate       uint16 = 20617
   203  	ErrTxnRWConflict              uint16 = 20618
   204  	ErrTxnWWConflict              uint16 = 20619
   205  	ErrNotFound                   uint16 = 20620
   206  	ErrTxnInternal                uint16 = 20621
   207  	ErrTxnReadConflict            uint16 = 20622
   208  	ErrPrimaryKeyDuplicated       uint16 = 20623
   209  	ErrAppendableObjectNotFound   uint16 = 20624
   210  	ErrAppendableBlockNotFound    uint16 = 20625
   211  	ErrTAEDebug                   uint16 = 20626
   212  	ErrDuplicateKey               uint16 = 20627
   213  	ErrTxnNeedRetry               uint16 = 20628
   214  	ErrTAENeedRetry               uint16 = 20629
   215  	ErrTxnCannotRetry             uint16 = 20630
   216  	ErrTxnNeedRetryWithDefChanged uint16 = 20631
   217  	ErrTxnStale                   uint16 = 20632
   218  	ErrWaiterPaused               uint16 = 20633
   219  	ErrRetryForCNRollingRestart   uint16 = 20634
   220  	ErrNewTxnInCNRollingRestart   uint16 = 20635
   221  	ErrPrevCheckpointNotFinished  uint16 = 20636
   222  
   223  	// Group 7: lock service
   224  	// ErrDeadLockDetected lockservice has detected a deadlock and should abort the transaction if it receives this error
   225  	ErrDeadLockDetected uint16 = 20701
   226  	// ErrLockTableBindChanged lockservice and lock table bind changed
   227  	ErrLockTableBindChanged uint16 = 20702
   228  	// ErrLockTableNotFound lock table not found on remote lock service instance
   229  	ErrLockTableNotFound uint16 = 20703
   230  	// ErrDeadlockCheckBusy deadlock busy error, cannot check deadlock.
   231  	ErrDeadlockCheckBusy uint16 = 20704
   232  	// ErrCannotCommitOrphan cannot commit orphan transaction
   233  	ErrCannotCommitOrphan uint16 = 20705
   234  	// ErrLockConflict lock operation conflict
   235  	ErrLockConflict uint16 = 20706
   236  
   237  	// Group 8: partition
   238  	ErrPartitionFunctionIsNotAllowed       uint16 = 20801
   239  	ErrWrongExprInPartitionFunc            uint16 = 20802
   240  	ErrMultipleDefConstInListPart          uint16 = 20803
   241  	ErrPartitionConstDomain                uint16 = 20804
   242  	ErrFieldNotFoundPart                   uint16 = 20805
   243  	ErrPartitionsMustBeDefined             uint16 = 20806
   244  	ErrWrongTypeColumnValue                uint16 = 20807
   245  	ErrValuesIsNotIntType                  uint16 = 20808
   246  	ErrPartitionColumnList                 uint16 = 20809
   247  	ErrSameNamePartition                   uint16 = 20810
   248  	ErrTooManyPartitions                   uint16 = 20811
   249  	ErrPartitionFuncNotAllowed             uint16 = 20812
   250  	ErrFieldTypeNotAllowedAsPartitionField uint16 = 20813
   251  	ErrPartitionNoTemporary                uint16 = 20814
   252  	ErrBlobFieldInPartFunc                 uint16 = 20815
   253  	ErrUniqueKeyNeedAllFieldsInPf          uint16 = 20816
   254  	ErrPartitionMaxvalue                   uint16 = 20817
   255  	ErrRangeNotIncreasing                  uint16 = 20818
   256  	ErrCheckRecursiveLevel                 uint16 = 20819
   257  	ErrSameNamePartitionField              uint16 = 20820
   258  	ErrMaxvalueInValuesIn                  uint16 = 20821
   259  	ErrRowSinglePartitionField             uint16 = 20822
   260  	ErrTooManyPartitionFuncFields          uint16 = 20823
   261  	ErrTooManyParameter                    uint16 = 20824
   262  
   263  	// Group 9: streaming
   264  	ErrUnsupportedOption   uint16 = 20901
   265  	ErrInvalidValue        uint16 = 20902
   266  	ErrLackOption          uint16 = 20903
   267  	ErrDuplicateConnector  uint16 = 20904
   268  	ErrUnsupportedDataType uint16 = 20905
   269  	ErrTaskNotFound        uint16 = 20906
   270  
   271  	// Group 10: skip list
   272  	ErrKeyAlreadyExists uint16 = 21001
   273  	ErrArenaFull        uint16 = 21002
   274  
   275  	// ErrEnd, the max value of MOErrorCode
   276  	ErrEnd uint16 = 65535
   277  )
   278  
   279  type moErrorMsgItem struct {
   280  	mysqlCode        uint16
   281  	sqlStates        []string
   282  	errorMsgOrFormat string
   283  }
   284  
   285  var errorMsgRefer = map[uint16]moErrorMsgItem{
   286  	// OK code not in this table.  They do not have a mysql code, as
   287  	// they are OK -- should not leak back to client.
   288  
   289  	// Info
   290  	ErrInfo:     {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "info: %s"},
   291  	ErrLoadInfo: {ER_LOAD_INFO, []string{MySQLDefaultSqlState}, "load info: %d, %d, %d, %d, %d"},
   292  
   293  	// Warn
   294  	ErrWarn:              {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "warning: %s"},
   295  	ErrWarnDataTruncated: {WARN_DATA_TRUNCATED, []string{MySQLDefaultSqlState}, "warning: data truncated"},
   296  
   297  	// Group 1: Internal errors
   298  	ErrStart:            {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "internal error: error code start"},
   299  	ErrInternal:         {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "internal error: %s"},
   300  	ErrNYI:              {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "%s is not yet implemented"},
   301  	ErrOOM:              {ER_ENGINE_OUT_OF_MEMORY, []string{MySQLDefaultSqlState}, "error: out of memory"},
   302  	ErrQueryInterrupted: {ER_QUERY_INTERRUPTED, []string{MySQLDefaultSqlState}, "query interrupted"},
   303  	ErrNotSupported:     {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "not supported: %s"},
   304  
   305  	// Group 2: numeric
   306  	ErrDivByZero:                   {ER_DIVISION_BY_ZERO, []string{MySQLDefaultSqlState}, "division by zero"},
   307  	ErrOutOfRange:                  {ER_DATA_OUT_OF_RANGE, []string{MySQLDefaultSqlState}, "data out of range: data type %s, %s"},
   308  	ErrDataTruncated:               {ER_DATA_TOO_LONG, []string{MySQLDefaultSqlState}, "data truncated: data type %s, %s"},
   309  	ErrInvalidArg:                  {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "invalid argument %s, bad value %s"},
   310  	ErrTruncatedWrongValueForField: {ER_TRUNCATED_WRONG_VALUE_FOR_FIELD, []string{MySQLDefaultSqlState}, "truncated type %s value %s for column %s, %d"},
   311  
   312  	// Group 3: invalid input
   313  	ErrBadConfig:            {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "invalid configuration: %s"},
   314  	ErrInvalidInput:         {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "invalid input: %s"},
   315  	ErrSyntaxError:          {ER_SYNTAX_ERROR, []string{MySQLDefaultSqlState}, "SQL syntax error: %s"},
   316  	ErrParseError:           {ER_PARSE_ERROR, []string{MySQLDefaultSqlState}, "SQL parser error: %s"},
   317  	ErrConstraintViolation:  {ER_CHECK_CONSTRAINT_VIOLATED, []string{MySQLDefaultSqlState}, "constraint violation: %s"},
   318  	ErrDuplicate:            {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "tae data: duplicate"},
   319  	ErrRoleGrantedToSelf:    {ER_ROLE_GRANTED_TO_ITSELF, []string{MySQLDefaultSqlState}, "cannot grant role %s to %s"},
   320  	ErrDuplicateEntry:       {ER_DUP_ENTRY, []string{MySQLDefaultSqlState}, "Duplicate entry '%s' for key '%s'"},
   321  	ErrWrongValueCountOnRow: {ER_WRONG_VALUE_COUNT_ON_ROW, []string{MySQLDefaultSqlState}, "Column count doesn't match value count at row %d"},
   322  	ErrBadFieldError:        {ER_BAD_FIELD_ERROR, []string{MySQLDefaultSqlState}, "Unknown column '%s' in '%s'"},
   323  	ErrWrongDatetimeSpec:    {ER_WRONG_DATETIME_SPEC, []string{MySQLDefaultSqlState}, "wrong date/time format specifier: %s"},
   324  	ErrUpgrateError:         {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "CN upgrade table or view '%s.%s' under tenant '%s:%d' reports error: %s"},
   325  
   326  	// Group 4: unexpected state or file io error
   327  	ErrInvalidState:                             {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "invalid state %s"},
   328  	ErrLogServiceNotReady:                       {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "log service not ready"},
   329  	ErrBadDB:                                    {ER_BAD_DB_ERROR, []string{MySQLDefaultSqlState}, "invalid database %s"},
   330  	ErrNoSuchTable:                              {ER_NO_SUCH_TABLE, []string{MySQLDefaultSqlState}, "no such table %s.%s"},
   331  	ErrNoSuchSequence:                           {ER_NO_SUCH_TABLE, []string{MySQLDefaultSqlState}, "no such sequence %s.%s"},
   332  	ErrEmptyVector:                              {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "empty vector"},
   333  	ErrFileNotFound:                             {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "file %s is not found"},
   334  	ErrFileAlreadyExists:                        {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "file %s already exists"},
   335  	ErrUnexpectedEOF:                            {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "unexpected end of file %s"},
   336  	ErrEmptyRange:                               {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "empty range of file %s"},
   337  	ErrSizeNotMatch:                             {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "file %s size does not match"},
   338  	ErrNoProgress:                               {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "file %s has no io progress"},
   339  	ErrInvalidPath:                              {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "invalid file path %s"},
   340  	ErrShortWrite:                               {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "file %s io short write"},
   341  	ErrInvalidWrite:                             {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "file %s io invalid write"},
   342  	ErrShortBuffer:                              {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "file %s io short buffer"},
   343  	ErrNoDB:                                     {ER_NO_DB_ERROR, []string{MySQLDefaultSqlState}, "not connect to a database"},
   344  	ErrNoWorkingStore:                           {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "no working store"},
   345  	ErrNoHAKeeper:                               {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "cannot locate ha keeper"},
   346  	ErrInvalidTruncateLsn:                       {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "invalid truncate lsn, shard %d already truncated to %d"},
   347  	ErrNotLeaseHolder:                           {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "not lease holder, current lease holder ID %d"},
   348  	ErrDBAlreadyExists:                          {ER_DB_CREATE_EXISTS, []string{MySQLDefaultSqlState}, "database %s already exists"},
   349  	ErrTableAlreadyExists:                       {ER_TABLE_EXISTS_ERROR, []string{MySQLDefaultSqlState}, "table %s already exists"},
   350  	ErrFunctionAlreadyExists:                    {ER_UDF_ALREADY_EXISTS, []string{MySQLDefaultSqlState}, "function %s already exists"},
   351  	ErrProcedureAlreadyExists:                   {ER_UDF_ALREADY_EXISTS, []string{MySQLDefaultSqlState}, "procedure %s already exists"},
   352  	ErrDropNonExistsFunction:                    {ER_CANT_FIND_UDF, []string{MySQLDefaultSqlState}, "function %s doesn't exist"},
   353  	ErrNoService:                                {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "service %s not found"},
   354  	ErrDupServiceName:                           {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "duplicate service name %s"},
   355  	ErrWrongService:                             {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "wrong service, expecting %s, got %s"},
   356  	ErrBadS3Config:                              {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "bad s3 config: %s"},
   357  	ErrBadView:                                  {ER_VIEW_INVALID, []string{MySQLDefaultSqlState}, "invalid view '%s.%s'"},
   358  	ErrInvalidTask:                              {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "invalid task, task runner %s, id %d"},
   359  	ErrInvalidServiceIndex:                      {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "invalid service idx %d"},
   360  	ErrDragonboatTimeout:                        {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "%s"},
   361  	ErrDragonboatTimeoutTooSmall:                {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "%s"},
   362  	ErrDragonboatInvalidDeadline:                {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "%s"},
   363  	ErrDragonboatRejected:                       {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "%s"},
   364  	ErrDragonboatInvalidPayloadSize:             {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "%s"},
   365  	ErrDragonboatShardNotReady:                  {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "%s"},
   366  	ErrDragonboatSystemClosed:                   {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "%s"},
   367  	ErrDragonboatInvalidRange:                   {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "%s"},
   368  	ErrDragonboatShardNotFound:                  {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "%s"},
   369  	ErrDragonboatOtherSystemError:               {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "%s"},
   370  	ErrDropNonExistsDB:                          {ER_DB_DROP_EXISTS, []string{MySQLDefaultSqlState}, "Can't drop database '%s'; database doesn't exist"},
   371  	ErrResultFileNotFound:                       {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "result file %s not found"},
   372  	ErrNoConfig:                                 {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "no configure: %s"},
   373  	ErrTooManyFields:                            {ER_TOO_MANY_FIELDS, []string{MySQLDefaultSqlState}, "Too many columns"},
   374  	ErrDupFieldName:                             {ER_DUP_FIELDNAME, []string{MySQLDefaultSqlState}, "Duplicate column name '%-.192s'"},
   375  	ErrMultiplePriKey:                           {ER_MULTIPLE_PRI_KEY, []string{MySQLDefaultSqlState}, "Multiple primary key defined"},
   376  	ErrTooManyKeys:                              {ER_TOO_MANY_KEYS, []string{MySQLDefaultSqlState}, "Too many keys specified; max %d keys allowed"},
   377  	ErrTooManyKeyParts:                          {ER_TOO_MANY_KEY_PARTS, []string{MySQLDefaultSqlState}, "Too many key parts specified; max %d parts allowed"},
   378  	ErrWrongColumnName:                          {ER_WRONG_COLUMN_NAME, []string{MySQLDefaultSqlState}, "Incorrect column name '%-.100s'"},
   379  	ErrWrongNameForIndex:                        {ER_WRONG_NAME_FOR_INDEX, []string{MySQLDefaultSqlState}, "Incorrect index name '%-.100s'"},
   380  	ErrInvalidDefault:                           {ER_INVALID_DEFAULT, []string{MySQLDefaultSqlState}, "Invalid default value for '%-.192s'"},
   381  	ErrDropIndexNeededInForeignKey:              {ER_DROP_INDEX_FK, []string{MySQLDefaultSqlState}, "Cannot drop index '%-.192s': needed in a foreign key constraint"},
   382  	ErrFKIncompatibleColumns:                    {ER_FK_INCOMPATIBLE_COLUMNS, []string{MySQLDefaultSqlState}, "Referencing column '%s' and referenced column '%s' in foreign key constraint '%s' are incompatible."},
   383  	ErrForeignKeyColumnCannotChangeChild:        {ER_FK_COLUMN_CANNOT_CHANGE_CHILD, []string{MySQLDefaultSqlState}, "Cannot change column '%-.192s': used in a foreign key constraint '%-.192s' of table '%-.192s'"},
   384  	ErrForeignKeyColumnCannotChange:             {ER_FK_COLUMN_CANNOT_CHANGE, []string{MySQLDefaultSqlState}, "Cannot change column '%-.192s': used in a foreign key constraint '%-.192s'"},
   385  	ErrForeignKeyOnPartitioned:                  {ER_FOREIGN_KEY_ON_PARTITIONED, []string{MySQLDefaultSqlState}, "Foreign keys are not yet supported in conjunction with partitioning"},
   386  	ErrKeyColumnDoesNotExist:                    {ER_KEY_COLUMN_DOES_NOT_EXIST, []string{MySQLDefaultSqlState}, "Key column '%-.192s' doesn't exist in table"},
   387  	ErrCantDropFieldOrKey:                       {ER_CANT_DROP_FIELD_OR_KEY, []string{MySQLDefaultSqlState}, "Can't DROP '%-.192s'; check that column/key exists"},
   388  	ErrTableMustHaveColumns:                     {ER_TABLE_MUST_HAVE_COLUMNS, []string{MySQLDefaultSqlState}, "A table must have at least 1 column"},
   389  	ErrCantRemoveAllFields:                      {ER_CANT_REMOVE_ALL_FIELDS, []string{MySQLDefaultSqlState}, "You can't delete all columns with ALTER TABLE; use DROP TABLE instead"},
   390  	ErrFkColumnCannotDrop:                       {ER_FK_COLUMN_CANNOT_DROP, []string{MySQLDefaultSqlState}, "Cannot drop column '%-.192s': needed in a foreign key constraint '%-.192s'"},
   391  	ErrFkColumnCannotDropChild:                  {ER_FK_COLUMN_CANNOT_DROP_CHILD, []string{MySQLDefaultSqlState}, "Cannot drop column '%-.192s': needed in a foreign key constraint '%-.192s' of table '%-.192s'"},
   392  	ErrDependentByPartitionFunction:             {ER_DEPENDENT_BY_PARTITION_FUNC, []string{MySQLDefaultSqlState}, "Column '%s' has a partitioning function dependency and cannot be dropped or renamed"},
   393  	ErrAlterOperationNotSupportedReasonFkRename: {ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME, []string{MySQLDefaultSqlState}, "Columns participating in a foreign key are renamed"},
   394  	ErrPrimaryCantHaveNull:                      {ER_PRIMARY_CANT_HAVE_NULL, []string{MySQLDefaultSqlState}, "All parts of a PRIMARY KEY must be NOT NULL; if you need NULL in a key, use UNIQUE instead"},
   395  	ErrPartitionMgmtOnNonpartitioned:            {ER_PARTITION_MGMT_ON_NONPARTITIONED, []string{MySQLDefaultSqlState}, "Partition management on a not partitioned table is not possible"},
   396  	ErrFKRowIsReferenced:                        {ER_ROW_IS_REFERENCED, []string{MySQLDefaultSqlState}, "Cannot delete or update a parent row: a foreign key constraint fails"},
   397  	ErrDuplicateKeyName:                         {ER_DUP_KEYNAME, []string{MySQLDefaultSqlState}, "Duplicate foreign key constraint name '%-.192s'"},
   398  	ErrFKNoReferencedRow2:                       {ER_NO_REFERENCED_ROW_2, []string{"23000"}, "Cannot add or update a child row: a foreign key constraint fails"},
   399  	// Group 5: rpc timeout
   400  	ErrRPCTimeout:   {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "rpc timeout"},
   401  	ErrClientClosed: {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "client closed"},
   402  	ErrBackendClosed: {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState},
   403  		"the connection has been disconnected"},
   404  	ErrStreamClosed:         {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "stream closed"},
   405  	ErrNoAvailableBackend:   {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "no available backend"},
   406  	ErrBackendCannotConnect: {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "can not connect to remote backend, %v"},
   407  
   408  	// Group 6: txn
   409  	ErrTxnClosed:                  {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "the transaction %s has been committed or aborted"},
   410  	ErrTxnWriteConflict:           {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "txn write conflict %s"},
   411  	ErrMissingTxn:                 {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "missing txn"},
   412  	ErrUnresolvedConflict:         {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "unresolved conflict"},
   413  	ErrTxnError:                   {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "transaction error: %s"},
   414  	ErrTNShardNotFound:            {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "dn shard uuid %s, id %d not found"},
   415  	ErrShardNotReported:           {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "dn shard uuid %s, id %d not reported"},
   416  	ErrTAEError:                   {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "tae error %s"},
   417  	ErrTAERead:                    {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "tae read error"},
   418  	ErrRpcError:                   {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "rpc error"},
   419  	ErrWaitTxn:                    {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "txn wait error"},
   420  	ErrTxnNotFound:                {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "txn not found"},
   421  	ErrTxnNotActive:               {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "txn not active, state %s"},
   422  	ErrTAEWrite:                   {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "tae write error"},
   423  	ErrTAECommit:                  {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "tae commit error %s"},
   424  	ErrTAERollback:                {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "tae rollback error %s"},
   425  	ErrTAEPrepare:                 {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "tae prepare error %s"},
   426  	ErrTAEPossibleDuplicate:       {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "tae possible duplicate"},
   427  	ErrTxnRWConflict:              {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "r-w conflict"},
   428  	ErrTxnWWConflict:              {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "w-w conflict"},
   429  	ErrNotFound:                   {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "not found"},
   430  	ErrTxnInternal:                {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "txn internal error"},
   431  	ErrTxnReadConflict:            {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "txn read conflict %s"},
   432  	ErrPrimaryKeyDuplicated:       {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "duplicated primary key %v"},
   433  	ErrAppendableObjectNotFound:   {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "appendable Object not found"},
   434  	ErrAppendableBlockNotFound:    {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "appendable block not found"},
   435  	ErrDuplicateKey:               {ER_DUP_KEYNAME, []string{MySQLDefaultSqlState}, "duplicate key name '%s'"},
   436  	ErrTxnNeedRetry:               {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "txn need retry in rc mode"},
   437  	ErrTAENeedRetry:               {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "tae need retry"},
   438  	ErrTxnCannotRetry:             {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "txn s3 writes can not retry in rc mode"},
   439  	ErrTxnNeedRetryWithDefChanged: {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "txn need retry in rc mode, def changed"},
   440  	ErrTxnStale:                   {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "txn is stale: timestamp is too small"},
   441  	ErrWaiterPaused:               {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "waiter is paused"},
   442  	ErrRetryForCNRollingRestart:   {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "retry for CN rolling restart"},
   443  	ErrNewTxnInCNRollingRestart:   {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "new txn in CN rolling restart"},
   444  	ErrPrevCheckpointNotFinished:  {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "prev checkpoint not finished"},
   445  
   446  	// Group 7: lock service
   447  	ErrDeadLockDetected:     {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "deadlock detected"},
   448  	ErrLockTableBindChanged: {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "lock table bind changed"},
   449  	ErrLockTableNotFound:    {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "lock table not found on remote lock service"},
   450  	ErrDeadlockCheckBusy:    {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "deadlock check is busy"},
   451  	ErrCannotCommitOrphan:   {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "cannot commit a orphan transaction"},
   452  	ErrLockConflict:         {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "lock options conflict, wait policy is fast fail"},
   453  
   454  	// Group 8: partition
   455  	ErrPartitionFunctionIsNotAllowed:       {ER_PARTITION_FUNCTION_IS_NOT_ALLOWED, []string{MySQLDefaultSqlState}, "This partition function is not allowed"},
   456  	ErrWrongExprInPartitionFunc:            {ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR, []string{MySQLDefaultSqlState}, "Constant, random or timezone-dependent expressions in (sub)partitioning function are not allowed"},
   457  	ErrMultipleDefConstInListPart:          {ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR, []string{MySQLDefaultSqlState}, "Multiple definition of same constant in list partitioning"},
   458  	ErrPartitionConstDomain:                {ER_PARTITION_CONST_DOMAIN_ERROR, []string{MySQLDefaultSqlState}, "Partition constant is out of partition function domain"},
   459  	ErrFieldNotFoundPart:                   {ER_FIELD_NOT_FOUND_PART_ERROR, []string{MySQLDefaultSqlState}, "Field in list of fields for partition function not found in table"},
   460  	ErrPartitionsMustBeDefined:             {ER_PARTITIONS_MUST_BE_DEFINED_ERROR, []string{MySQLDefaultSqlState}, "For %-.64s partitions each partition must be defined"},
   461  	ErrWrongTypeColumnValue:                {ER_WRONG_TYPE_COLUMN_VALUE_ERROR, []string{MySQLDefaultSqlState}, "Partition column values of incorrect type"},
   462  	ErrValuesIsNotIntType:                  {ER_VALUES_IS_NOT_INT_TYPE_ERROR, []string{MySQLDefaultSqlState}, "VALUES value for partition '%-.64s' must have type INT"},
   463  	ErrPartitionColumnList:                 {ER_PARTITION_COLUMN_LIST_ERROR, []string{MySQLDefaultSqlState}, "Inconsistency in usage of column lists for partitioning"},
   464  	ErrSameNamePartition:                   {ER_SAME_NAME_PARTITION, []string{MySQLDefaultSqlState}, "Duplicate partition name %-.192s"},
   465  	ErrTooManyPartitions:                   {ER_TOO_MANY_PARTITIONS_ERROR, []string{MySQLDefaultSqlState}, "Too many partitions (including subpartitions) were defined"},
   466  	ErrPartitionFuncNotAllowed:             {ER_PARTITION_FUNC_NOT_ALLOWED_ERROR, []string{MySQLDefaultSqlState}, "The %-.192s function returns the wrong type"},
   467  	ErrFieldTypeNotAllowedAsPartitionField: {ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD, []string{MySQLDefaultSqlState}, "Field '%-.192s' is of a not allowed type for this type of partitioning"},
   468  	ErrPartitionNoTemporary:                {ER_PARTITION_NO_TEMPORARY, []string{MySQLDefaultSqlState}, "Cannot create temporary table with partitions"},
   469  	ErrBlobFieldInPartFunc:                 {ER_BLOB_FIELD_IN_PART_FUNC_ERROR, []string{MySQLDefaultSqlState}, "A BLOB field is not allowed in partition function"},
   470  	ErrUniqueKeyNeedAllFieldsInPf:          {ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF, []string{MySQLDefaultSqlState}, "A %-.192s must include all columns in the table's partitioning function"},
   471  	ErrPartitionMaxvalue:                   {ER_PARTITION_MAXVALUE_ERROR, []string{MySQLDefaultSqlState}, "MAXVALUE can only be used in last partition definition"},
   472  	ErrRangeNotIncreasing:                  {ER_RANGE_NOT_INCREASING_ERROR, []string{MySQLDefaultSqlState}, "VALUES LESS THAN value must be strictly increasing for each partition"},
   473  	ErrCheckRecursiveLevel:                 {ErrCheckRecursiveLevel, []string{MySQLDefaultSqlState}, "recursive level out of range"},
   474  	ErrSameNamePartitionField:              {ER_SAME_NAME_PARTITION_FIELD, []string{MySQLDefaultSqlState}, "Duplicate partition field name '%-.192s'"},
   475  	ErrMaxvalueInValuesIn:                  {ER_MAXVALUE_IN_VALUES_IN, []string{MySQLDefaultSqlState}, "Cannot use MAXVALUE as value in VALUES IN"},
   476  	ErrRowSinglePartitionField:             {ER_ROW_SINGLE_PARTITION_FIELD_ERROR, []string{MySQLDefaultSqlState}, "Row expressions in VALUES IN only allowed for multi-field column partitioning"},
   477  	ErrTooManyPartitionFuncFields:          {ER_TOO_MANY_PARTITION_FUNC_FIELDS_ERROR, []string{MySQLDefaultSqlState}, "Too many fields in '%-.192s'"},
   478  	ErrTooManyParameter:                    {ER_PS_MANY_PARAM, []string{MySQLDefaultSqlState}, "Prepared statement contains too many placeholders"},
   479  
   480  	// Group 9: streaming
   481  	ErrUnsupportedOption:   {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "unsupported option %s"},
   482  	ErrInvalidValue:        {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "invalid value %s for option %s"},
   483  	ErrLackOption:          {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "lack of option %s"},
   484  	ErrDuplicateConnector:  {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "the connector for table %s already exists"},
   485  	ErrUnsupportedDataType: {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "unsupported data type %T"},
   486  	ErrTaskNotFound:        {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "task with ID %d not found"},
   487  
   488  	// Group 10: skip list
   489  	ErrKeyAlreadyExists: {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "record with this key already exists"},
   490  	ErrArenaFull:        {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "allocation failed because arena is full"},
   491  
   492  	// Group End: max value of MOErrorCode
   493  	ErrEnd: {ER_UNKNOWN_ERROR, []string{MySQLDefaultSqlState}, "internal error: end of errcode code"},
   494  }
   495  
   496  func newError(ctx context.Context, code uint16, args ...any) *Error {
   497  	var err *Error
   498  	item, has := errorMsgRefer[code]
   499  	if !has {
   500  		panic(NewInternalError(ctx, "not exist MOErrorCode: %d", code))
   501  	}
   502  	if len(args) == 0 {
   503  		err = &Error{
   504  			code:      code,
   505  			mysqlCode: item.mysqlCode,
   506  			message:   item.errorMsgOrFormat,
   507  			sqlState:  item.sqlStates[0],
   508  		}
   509  	} else {
   510  		err = &Error{
   511  			code:      code,
   512  			mysqlCode: item.mysqlCode,
   513  			message:   fmt.Sprintf(item.errorMsgOrFormat, args...),
   514  			sqlState:  item.sqlStates[0],
   515  		}
   516  	}
   517  	_ = errutil.WithContextWithDepth(ctx, err, 2)
   518  	return err
   519  }
   520  
   521  type Error struct {
   522  	code      uint16
   523  	mysqlCode uint16
   524  	message   string
   525  	sqlState  string
   526  	detail    string
   527  }
   528  
   529  func (e *Error) Error() string {
   530  	return e.message
   531  }
   532  
   533  func (e *Error) Detail() string {
   534  	return e.detail
   535  }
   536  
   537  func (e *Error) Display() string {
   538  	if len(e.detail) == 0 {
   539  		return e.message
   540  	}
   541  	return fmt.Sprintf("%s: %s", e.message, e.detail)
   542  }
   543  
   544  func (e *Error) ErrorCode() uint16 {
   545  	return e.code
   546  }
   547  
   548  func (e *Error) MySQLCode() uint16 {
   549  	return e.mysqlCode
   550  }
   551  
   552  func (e *Error) SqlState() string {
   553  	return e.sqlState
   554  }
   555  
   556  var _ encoding.BinaryMarshaler = new(Error)
   557  
   558  func (e *Error) MarshalBinary() ([]byte, error) {
   559  	ee := moerrpb.Error{
   560  		Code:      e.code,
   561  		MysqlCode: e.mysqlCode,
   562  		Message:   e.message,
   563  		SqlState:  e.sqlState,
   564  	}
   565  	data := make([]byte, ee.ProtoSize())
   566  	if _, err := ee.MarshalToSizedBuffer(data); err != nil {
   567  		return nil, ConvertGoError(Context(), err)
   568  	}
   569  	return data, nil
   570  }
   571  
   572  var _ encoding.BinaryUnmarshaler = new(Error)
   573  
   574  func (e *Error) UnmarshalBinary(data []byte) error {
   575  	var ee moerrpb.Error
   576  	if err := ee.Unmarshal(data); err != nil {
   577  		return ConvertGoError(Context(), err)
   578  	}
   579  	e.code = ee.Code
   580  	e.mysqlCode = ee.MysqlCode
   581  	e.message = ee.Message
   582  	e.sqlState = ee.SqlState
   583  	return nil
   584  }
   585  
   586  func IsMoErrCode(e error, rc uint16) bool {
   587  	if e == nil {
   588  		return rc == Ok
   589  	}
   590  
   591  	me, ok := e.(*Error)
   592  	if !ok {
   593  		// This is not a moerr
   594  		return false
   595  	}
   596  	return me.code == rc
   597  }
   598  
   599  func DowncastError(e error) *Error {
   600  	if err, ok := e.(*Error); ok {
   601  		return err
   602  	}
   603  	return newError(Context(), ErrInternal, "downcast error failed: %v", e)
   604  
   605  }
   606  
   607  // ConvertPanicError converts a runtime panic to internal error.
   608  func ConvertPanicError(ctx context.Context, v interface{}) *Error {
   609  	if e, ok := v.(*Error); ok {
   610  		return e
   611  	}
   612  	return newError(ctx, ErrInternal, fmt.Sprintf("panic %v: %+v", v, stack.Callers(3)))
   613  }
   614  
   615  // ConvertGoError converts a go error into mo error.
   616  // Note here we must return error, because nil error
   617  // is the same as nil *Error -- Go strangeness.
   618  func ConvertGoError(ctx context.Context, err error) error {
   619  	// nil is nil
   620  	if err == nil {
   621  		return err
   622  	}
   623  
   624  	// already a moerr, return it as is
   625  	if _, ok := err.(*Error); ok {
   626  		return err
   627  	}
   628  
   629  	// Convert a few well known os/go error.
   630  	if err == io.EOF || err == io.ErrUnexpectedEOF {
   631  		// if io.EOF reaches here, we believe it is not expected.
   632  		return NewUnexpectedEOF(ctx, err.Error())
   633  	}
   634  
   635  	return NewInternalError(ctx, "convert go error to mo error %v", err)
   636  }
   637  
   638  func (e *Error) Succeeded() bool {
   639  	return e.code < OkMax
   640  }
   641  
   642  // Special handling of OK code.   This code are not errors, but used to
   643  // signal different success conditions.  One user is StopCurrRecur.
   644  // TAE use it to loop over memory data structures.  They are tight,
   645  // performance critical loops, so we cannot afford to new an Error and
   646  // definitely not construct call stack and do logging.  Note that exactly
   647  // because of these, Ok code does not have any contextual info.  It is
   648  // just a code.
   649  //
   650  // For these, we have a local var, and caller can use GetOkXXX() to get
   651  // *Error.  The returned *Error can be tested with either
   652  //
   653  //	   if err == GetOkXXX()
   654  //	or if moerr.IsMoErrCode(err, moerr.OkXXX)
   655  //
   656  // They are both fast, one with less typing and the other is consistent
   657  // with other error code checking.
   658  var errOkStopCurrRecur = Error{OkStopCurrRecur, 0, "StopCurrRecur", "00000", ""}
   659  var errOkExpectedEOF = Error{OkExpectedEOF, 0, "ExpectedEOF", "00000", ""}
   660  var errOkExpectedEOB = Error{OkExpectedEOB, 0, "ExpectedEOB", "00000", ""}
   661  var errOkExpectedDup = Error{OkExpectedDup, 0, "ExpectedDup", "00000", ""}
   662  var errOkExpectedPossibleDup = Error{OkExpectedPossibleDup, 0, "OkExpectedPossibleDup", "00000", ""}
   663  var errOkExpectedNotSafeToStartTransfer = Error{OkExpectedNotSafeToStartTransfer, 0, "OkExpectedNotSafeToStartTransfer", "00000", ""}
   664  var errMysqlClientQuit = Error{MysqlClientQuit, 0, "MysqlClientQuit", "00000", ""}
   665  
   666  /*
   667  GetOk is useless in general, should just use nil.
   668  
   669  var errOk = Error{Ok, 0, "Succeeded", "00000"}
   670  func GetOk() *Error {
   671  	return &errOk
   672  }
   673  */
   674  
   675  func GetOkStopCurrRecur() *Error {
   676  	return &errOkStopCurrRecur
   677  }
   678  
   679  func GetOkExpectedEOF() *Error {
   680  	return &errOkExpectedEOF
   681  }
   682  
   683  func GetOkExpectedEOB() *Error {
   684  	return &errOkExpectedEOB
   685  }
   686  
   687  func GetOkExpectedDup() *Error {
   688  	return &errOkExpectedDup
   689  }
   690  
   691  func GetOkExpectedPossibleDup() *Error {
   692  	return &errOkExpectedPossibleDup
   693  }
   694  
   695  func GetOkExpectedNotSafeToStartTransfer() *Error {
   696  	return &errOkExpectedNotSafeToStartTransfer
   697  }
   698  
   699  func GetMysqlClientQuit() *Error {
   700  	return &errMysqlClientQuit
   701  }
   702  
   703  func NewInfo(ctx context.Context, msg string) *Error {
   704  	return newError(ctx, ErrInfo, msg)
   705  }
   706  
   707  func NewLoadInfo(ctx context.Context, rec, del, skip, warn, writeTimeOut uint64) *Error {
   708  	return newError(ctx, ErrLoadInfo, rec, del, skip, warn, writeTimeOut)
   709  }
   710  
   711  func NewWarn(ctx context.Context, msg string) *Error {
   712  	return newError(ctx, ErrWarn, msg)
   713  }
   714  
   715  func NewBadS3Config(ctx context.Context, msg string) *Error {
   716  	return newError(ctx, ErrBadS3Config, msg)
   717  }
   718  
   719  func NewInternalError(ctx context.Context, msg string, args ...any) *Error {
   720  	xmsg := fmt.Sprintf(msg, args...)
   721  	return newError(ctx, ErrInternal, xmsg)
   722  }
   723  
   724  func NewUpgrateError(ctx context.Context, dbName string, table string, tenant string, tenantId uint32, errmsg string) *Error {
   725  	return newError(ctx, ErrUpgrateError, dbName, table, tenant, tenantId, errmsg)
   726  }
   727  
   728  func NewNYI(ctx context.Context, msg string, args ...any) *Error {
   729  	xmsg := fmt.Sprintf(msg, args...)
   730  	return newError(ctx, ErrNYI, xmsg)
   731  }
   732  
   733  func NewNotSupported(ctx context.Context, msg string, args ...any) *Error {
   734  	xmsg := fmt.Sprintf(msg, args...)
   735  	return newError(ctx, ErrNotSupported, xmsg)
   736  }
   737  
   738  func NewOOM(ctx context.Context) *Error {
   739  	return newError(ctx, ErrOOM)
   740  }
   741  
   742  func NewQueryInterrupted(ctx context.Context) *Error {
   743  	return newError(ctx, ErrQueryInterrupted)
   744  }
   745  
   746  func NewDivByZero(ctx context.Context) *Error {
   747  	return newError(ctx, ErrDivByZero)
   748  }
   749  
   750  func NewOutOfRange(ctx context.Context, typ string, msg string, args ...any) *Error {
   751  	xmsg := fmt.Sprintf(msg, args...)
   752  	return newError(ctx, ErrOutOfRange, typ, xmsg)
   753  }
   754  
   755  func NewDataTruncated(ctx context.Context, typ string, msg string, args ...any) *Error {
   756  	xmsg := fmt.Sprintf(msg, args...)
   757  	return newError(ctx, ErrDataTruncated, typ, xmsg)
   758  }
   759  
   760  func NewInvalidArg(ctx context.Context, arg string, val any) *Error {
   761  	return newError(ctx, ErrInvalidArg, arg, fmt.Sprintf("%v", val))
   762  }
   763  
   764  func NewTruncatedValueForField(ctx context.Context, t, v, c string, idx int) *Error {
   765  	return newError(ctx, ErrTruncatedWrongValueForField, t, v, c, idx)
   766  }
   767  
   768  func NewBadConfig(ctx context.Context, msg string, args ...any) *Error {
   769  	xmsg := fmt.Sprintf(msg, args...)
   770  	return newError(ctx, ErrBadConfig, xmsg)
   771  }
   772  
   773  func NewInvalidInput(ctx context.Context, msg string, args ...any) *Error {
   774  	xmsg := fmt.Sprintf(msg, args...)
   775  	return newError(ctx, ErrInvalidInput, xmsg)
   776  }
   777  
   778  func NewSyntaxError(ctx context.Context, msg string, args ...any) *Error {
   779  	xmsg := fmt.Sprintf(msg, args...)
   780  	return newError(ctx, ErrSyntaxError, xmsg)
   781  }
   782  
   783  func NewParseError(ctx context.Context, msg string, args ...any) *Error {
   784  	xmsg := fmt.Sprintf(msg, args...)
   785  	return newError(ctx, ErrParseError, xmsg)
   786  }
   787  
   788  func NewConstraintViolation(ctx context.Context, msg string, args ...any) *Error {
   789  	xmsg := fmt.Sprintf(msg, args...)
   790  	return newError(ctx, ErrConstraintViolation, xmsg)
   791  }
   792  
   793  func NewEmptyVector(ctx context.Context) *Error {
   794  	return newError(ctx, ErrEmptyVector)
   795  }
   796  
   797  func NewFileNotFound(ctx context.Context, f string) *Error {
   798  	return newError(ctx, ErrFileNotFound, f)
   799  }
   800  
   801  func NewResultFileNotFound(ctx context.Context, f string) *Error {
   802  	return newError(ctx, ErrResultFileNotFound, f)
   803  }
   804  
   805  func NewNoConfig(ctx context.Context, f string) *Error {
   806  	return newError(ctx, ErrNoConfig, f)
   807  }
   808  
   809  func NewFileAlreadyExists(ctx context.Context, f string) *Error {
   810  	return newError(ctx, ErrFileAlreadyExists, f)
   811  }
   812  
   813  func NewDBAlreadyExists(ctx context.Context, db string) *Error {
   814  	return newError(ctx, ErrDBAlreadyExists, db)
   815  }
   816  
   817  func NewTableAlreadyExists(ctx context.Context, t string) *Error {
   818  	return newError(ctx, ErrTableAlreadyExists, t)
   819  }
   820  
   821  func NewUnexpectedEOF(ctx context.Context, f string) *Error {
   822  	return newError(ctx, ErrUnexpectedEOF, f)
   823  }
   824  
   825  func NewEmptyRange(ctx context.Context, f string) *Error {
   826  	return newError(ctx, ErrEmptyRange, f)
   827  }
   828  
   829  func NewSizeNotMatch(ctx context.Context, f string) *Error {
   830  	return newError(ctx, ErrSizeNotMatch, f)
   831  }
   832  
   833  func NewNoProgress(ctx context.Context, f string) *Error {
   834  	return newError(ctx, ErrNoProgress, f)
   835  }
   836  
   837  func NewInvalidPath(ctx context.Context, f string) *Error {
   838  	return newError(ctx, ErrInvalidPath, f)
   839  }
   840  
   841  func NewInvalidState(ctx context.Context, msg string, args ...any) *Error {
   842  	xmsg := fmt.Sprintf(msg, args...)
   843  	return newError(ctx, ErrInvalidState, xmsg)
   844  }
   845  
   846  func NewInvalidTask(ctx context.Context, runner string, id uint64) *Error {
   847  	return newError(ctx, ErrInvalidTask, runner, id)
   848  }
   849  
   850  func NewInvalidServiceIndex(ctx context.Context, idx int) *Error {
   851  	return newError(ctx, ErrInvalidServiceIndex, idx)
   852  }
   853  
   854  func NewLogServiceNotReady(ctx context.Context) *Error {
   855  	return newError(ctx, ErrLogServiceNotReady)
   856  }
   857  
   858  func NewBadDB(ctx context.Context, name string) *Error {
   859  	return newError(ctx, ErrBadDB, name)
   860  }
   861  
   862  func NewNoDB(ctx context.Context) *Error {
   863  	return newError(ctx, ErrNoDB)
   864  }
   865  
   866  func NewNoWorkingStore(ctx context.Context) *Error {
   867  	return newError(ctx, ErrNoWorkingStore)
   868  }
   869  
   870  func NewNoService(ctx context.Context, name string) *Error {
   871  	return newError(ctx, ErrNoService, name)
   872  }
   873  
   874  func NewDupServiceName(ctx context.Context, name string) *Error {
   875  	return newError(ctx, ErrDupServiceName, name)
   876  }
   877  
   878  func NewWrongService(ctx context.Context, exp, got string) *Error {
   879  	return newError(ctx, ErrWrongService, exp, got)
   880  }
   881  
   882  func NewNoHAKeeper(ctx context.Context) *Error {
   883  	return newError(ctx, ErrNoHAKeeper)
   884  }
   885  
   886  func NewInvalidTruncateLsn(ctx context.Context, shardId, idx uint64) *Error {
   887  	return newError(ctx, ErrInvalidTruncateLsn, shardId, idx)
   888  }
   889  
   890  func NewNotLeaseHolder(ctx context.Context, holderId uint64) *Error {
   891  	return newError(ctx, ErrNotLeaseHolder, holderId)
   892  }
   893  
   894  func NewNoSuchTable(ctx context.Context, db, tbl string) *Error {
   895  	return newError(ctx, ErrNoSuchTable, db, tbl)
   896  }
   897  
   898  func NewNoSuchSequence(ctx context.Context, db, tbl string) *Error {
   899  	return newError(ctx, ErrNoSuchSequence, db, tbl)
   900  }
   901  
   902  func NewBadView(ctx context.Context, db, v string) *Error {
   903  	return newError(ctx, ErrBadView, db, v)
   904  }
   905  
   906  func NewRPCTimeout(ctx context.Context) *Error {
   907  	return newError(ctx, ErrRPCTimeout)
   908  }
   909  
   910  func NewClientClosed(ctx context.Context) *Error {
   911  	return newError(ctx, ErrClientClosed)
   912  }
   913  
   914  func NewBackendClosed(ctx context.Context) *Error {
   915  	return newError(ctx, ErrBackendClosed)
   916  }
   917  
   918  func NewStreamClosed(ctx context.Context) *Error {
   919  	return newError(ctx, ErrStreamClosed)
   920  }
   921  
   922  func NewNoAvailableBackend(ctx context.Context) *Error {
   923  	return newError(ctx, ErrNoAvailableBackend)
   924  }
   925  
   926  func NewBackendCannotConnect(ctx context.Context) *Error {
   927  	return newError(ctx, ErrBackendCannotConnect)
   928  }
   929  
   930  func NewTxnClosed(ctx context.Context, txnID []byte) *Error {
   931  	id := "unknown"
   932  	if len(txnID) > 0 {
   933  		id = hex.EncodeToString(txnID)
   934  	}
   935  	return newError(ctx, ErrTxnClosed, id)
   936  }
   937  
   938  func NewTxnWriteConflict(ctx context.Context, msg string, args ...any) *Error {
   939  	xmsg := fmt.Sprintf(msg, args...)
   940  	return newError(ctx, ErrTxnWriteConflict, xmsg)
   941  }
   942  
   943  func NewMissingTxn(ctx context.Context) *Error {
   944  	return newError(ctx, ErrMissingTxn)
   945  }
   946  
   947  func NewUnresolvedConflict(ctx context.Context) *Error {
   948  	return newError(ctx, ErrUnresolvedConflict)
   949  }
   950  
   951  func NewTxnError(ctx context.Context, msg string, args ...any) *Error {
   952  	xmsg := fmt.Sprintf(msg, args...)
   953  	return newError(ctx, ErrTxnError, xmsg)
   954  }
   955  
   956  func NewTAEError(ctx context.Context, msg string, args ...any) *Error {
   957  	xmsg := fmt.Sprintf(msg, args...)
   958  	return newError(ctx, ErrTAEError, xmsg)
   959  }
   960  
   961  func NewTNShardNotFound(ctx context.Context, uuid string, id uint64) *Error {
   962  	return newError(ctx, ErrTNShardNotFound, uuid, id)
   963  }
   964  
   965  func NewShardNotReported(ctx context.Context, uuid string, id uint64) *Error {
   966  	return newError(ctx, ErrShardNotReported, uuid, id)
   967  }
   968  
   969  func NewDragonboatTimeout(ctx context.Context, msg string, args ...any) *Error {
   970  	xmsg := fmt.Sprintf(msg, args...)
   971  	return newError(ctx, ErrDragonboatTimeout, xmsg)
   972  }
   973  
   974  func NewDragonboatTimeoutTooSmall(ctx context.Context, msg string, args ...any) *Error {
   975  	xmsg := fmt.Sprintf(msg, args...)
   976  	return newError(ctx, ErrDragonboatTimeoutTooSmall, xmsg)
   977  }
   978  
   979  func NewDragonboatInvalidDeadline(ctx context.Context, msg string, args ...any) *Error {
   980  	xmsg := fmt.Sprintf(msg, args...)
   981  	return newError(ctx, ErrDragonboatInvalidDeadline, xmsg)
   982  }
   983  
   984  func NewDragonboatRejected(ctx context.Context, msg string, args ...any) *Error {
   985  	xmsg := fmt.Sprintf(msg, args...)
   986  	return newError(ctx, ErrDragonboatRejected, xmsg)
   987  }
   988  
   989  func NewDragonboatInvalidPayloadSize(ctx context.Context, msg string, args ...any) *Error {
   990  	xmsg := fmt.Sprintf(msg, args...)
   991  	return newError(ctx, ErrDragonboatInvalidPayloadSize, xmsg)
   992  }
   993  
   994  func NewDragonboatShardNotReady(ctx context.Context, msg string, args ...any) *Error {
   995  	xmsg := fmt.Sprintf(msg, args...)
   996  	return newError(ctx, ErrDragonboatShardNotReady, xmsg)
   997  }
   998  
   999  func NewDragonboatSystemClosed(ctx context.Context, msg string, args ...any) *Error {
  1000  	xmsg := fmt.Sprintf(msg, args...)
  1001  	return newError(ctx, ErrDragonboatSystemClosed, xmsg)
  1002  }
  1003  
  1004  func NewDragonboatInvalidRange(ctx context.Context, msg string, args ...any) *Error {
  1005  	xmsg := fmt.Sprintf(msg, args...)
  1006  	return newError(ctx, ErrDragonboatInvalidRange, xmsg)
  1007  }
  1008  
  1009  func NewDragonboatShardNotFound(ctx context.Context, msg string, args ...any) *Error {
  1010  	xmsg := fmt.Sprintf(msg, args...)
  1011  	return newError(ctx, ErrDragonboatShardNotFound, xmsg)
  1012  }
  1013  
  1014  func NewDragonboatOtherSystemError(ctx context.Context, msg string, args ...any) *Error {
  1015  	xmsg := fmt.Sprintf(msg, args...)
  1016  	return newError(ctx, ErrDragonboatOtherSystemError, xmsg)
  1017  }
  1018  
  1019  func NewErrDropNonExistsDB(ctx context.Context, name string) *Error {
  1020  	return newError(ctx, ErrDropNonExistsDB, name)
  1021  }
  1022  
  1023  func NewTAERead(ctx context.Context) *Error {
  1024  	return newError(ctx, ErrTAERead)
  1025  }
  1026  
  1027  func NewRpcError(ctx context.Context, msg string) *Error {
  1028  	return newError(ctx, ErrRpcError, msg)
  1029  }
  1030  
  1031  func NewWaitTxn(ctx context.Context) *Error {
  1032  	return newError(ctx, ErrWaitTxn)
  1033  }
  1034  
  1035  func NewTxnNotFound(ctx context.Context) *Error {
  1036  	return newError(ctx, ErrTxnNotFound)
  1037  }
  1038  
  1039  func NewTxnNotActive(ctx context.Context, st string) *Error {
  1040  	return newError(ctx, ErrTxnNotActive, st)
  1041  }
  1042  
  1043  func NewTAEWrite(ctx context.Context) *Error {
  1044  	return newError(ctx, ErrTAEWrite)
  1045  }
  1046  
  1047  func NewTAECommit(ctx context.Context, msg string, args ...any) *Error {
  1048  	xmsg := fmt.Sprintf(msg, args...)
  1049  	return newError(ctx, ErrTAECommit, xmsg)
  1050  }
  1051  
  1052  func NewTAERollback(ctx context.Context, msg string, args ...any) *Error {
  1053  	xmsg := fmt.Sprintf(msg, args...)
  1054  	return newError(ctx, ErrTAERollback, xmsg)
  1055  }
  1056  
  1057  func NewTAEPrepare(ctx context.Context, msg string, args ...any) *Error {
  1058  	xmsg := fmt.Sprintf(msg, args...)
  1059  	return newError(ctx, ErrTAEPrepare, xmsg)
  1060  }
  1061  
  1062  func NewTAEPossibleDuplicate(ctx context.Context) *Error {
  1063  	return newError(ctx, ErrTAEPossibleDuplicate)
  1064  }
  1065  
  1066  func NewTxnRWConflict(ctx context.Context) *Error {
  1067  	return newError(ctx, ErrTxnRWConflict)
  1068  }
  1069  
  1070  func NewTxnWWConflict(
  1071  	ctx context.Context,
  1072  	tableID uint64,
  1073  	s string) *Error {
  1074  	e := newError(ctx, ErrTxnWWConflict)
  1075  	e.detail = fmt.Sprintf("tableID: %d, %s", tableID, s)
  1076  	return e
  1077  }
  1078  
  1079  func NewNotFound(ctx context.Context) *Error {
  1080  	return newError(ctx, ErrNotFound)
  1081  }
  1082  
  1083  func NewDuplicate(ctx context.Context) *Error {
  1084  	return newError(ctx, ErrDuplicate)
  1085  }
  1086  
  1087  func NewDuplicateEntry(ctx context.Context, entry string, key string) *Error {
  1088  	return newError(ctx, ErrDuplicateEntry, entry, key)
  1089  }
  1090  
  1091  func NewWrongValueCountOnRow(ctx context.Context, row int) *Error {
  1092  	return newError(ctx, ErrWrongValueCountOnRow, row)
  1093  }
  1094  
  1095  func NewBadFieldError(ctx context.Context, column, table string) *Error {
  1096  	return newError(ctx, ErrBadFieldError, column, table)
  1097  }
  1098  
  1099  func NewWrongDatetimeSpec(ctx context.Context, val string) *Error {
  1100  	return newError(ctx, ErrWrongDatetimeSpec, val)
  1101  }
  1102  
  1103  func NewRoleGrantedToSelf(ctx context.Context, from, to string) *Error {
  1104  	return newError(ctx, ErrRoleGrantedToSelf, from, to)
  1105  }
  1106  
  1107  func NewTxnInternal(ctx context.Context) *Error {
  1108  	return newError(ctx, ErrTxnInternal)
  1109  }
  1110  
  1111  func NewTxnReadConflict(ctx context.Context, msg string, args ...any) *Error {
  1112  	xmsg := fmt.Sprintf(msg, args...)
  1113  	return newError(ctx, ErrTxnReadConflict, xmsg)
  1114  }
  1115  
  1116  func NewPrimaryKeyDuplicated(ctx context.Context, k any) *Error {
  1117  	return newError(ctx, ErrPrimaryKeyDuplicated, k)
  1118  }
  1119  
  1120  func NewDuplicateKey(ctx context.Context, k string) *Error {
  1121  	return newError(ctx, ErrDuplicateKey, k)
  1122  }
  1123  
  1124  func NewAppendableObjectNotFound(ctx context.Context) *Error {
  1125  	return newError(ctx, ErrAppendableObjectNotFound)
  1126  }
  1127  
  1128  func NewAppendableBlockNotFound(ctx context.Context) *Error {
  1129  	return newError(ctx, ErrAppendableBlockNotFound)
  1130  }
  1131  
  1132  func NewTxnNeedRetry(ctx context.Context) *Error {
  1133  	return newError(ctx, ErrTxnNeedRetry)
  1134  }
  1135  
  1136  func NewTxnNeedRetryWithDefChanged(ctx context.Context) *Error {
  1137  	return newError(ctx, ErrTxnNeedRetryWithDefChanged)
  1138  }
  1139  
  1140  func NewTxnCannotRetry(ctx context.Context) *Error {
  1141  	return newError(ctx, ErrTxnCannotRetry)
  1142  }
  1143  
  1144  func NewDeadLockDetected(ctx context.Context) *Error {
  1145  	return newError(ctx, ErrDeadLockDetected)
  1146  }
  1147  
  1148  func NewDeadlockCheckBusy(ctx context.Context) *Error {
  1149  	return newError(ctx, ErrDeadlockCheckBusy)
  1150  }
  1151  
  1152  func NewCannotCommitOrphan(ctx context.Context) *Error {
  1153  	return newError(ctx, ErrCannotCommitOrphan)
  1154  }
  1155  
  1156  func NewLockTableBindChanged(ctx context.Context) *Error {
  1157  	return newError(ctx, ErrLockTableBindChanged)
  1158  }
  1159  
  1160  func NewLockTableNotFound(ctx context.Context) *Error {
  1161  	return newError(ctx, ErrLockTableNotFound)
  1162  }
  1163  
  1164  func NewLockConflict(ctx context.Context) *Error {
  1165  	return newError(ctx, ErrLockConflict)
  1166  }
  1167  
  1168  func NewPartitionFunctionIsNotAllowed(ctx context.Context) *Error {
  1169  	return newError(ctx, ErrPartitionFunctionIsNotAllowed)
  1170  }
  1171  
  1172  func NewWrongExprInPartitionFunc(ctx context.Context) *Error {
  1173  	return newError(ctx, ErrWrongExprInPartitionFunc)
  1174  }
  1175  
  1176  func NewMultipleDefConstInListPart(ctx context.Context) *Error {
  1177  	return newError(ctx, ErrMultipleDefConstInListPart)
  1178  }
  1179  
  1180  func NewPartitionConstDomain(ctx context.Context) *Error {
  1181  	return newError(ctx, ErrPartitionConstDomain)
  1182  }
  1183  
  1184  func NewFieldNotFoundPart(ctx context.Context) *Error {
  1185  	return newError(ctx, ErrFieldNotFoundPart)
  1186  }
  1187  func NewPartitionsMustBeDefined(ctx context.Context, k any) *Error {
  1188  	return newError(ctx, ErrPartitionsMustBeDefined, k)
  1189  }
  1190  
  1191  func NewWrongTypeColumnValue(ctx context.Context) *Error {
  1192  	return newError(ctx, ErrWrongTypeColumnValue)
  1193  }
  1194  
  1195  func NewValuesIsNotIntType(ctx context.Context, k any) *Error {
  1196  	return newError(ctx, ErrValuesIsNotIntType, k)
  1197  }
  1198  
  1199  func NewErrPartitionColumnList(ctx context.Context) *Error {
  1200  	return newError(ctx, ErrPartitionColumnList)
  1201  }
  1202  
  1203  func NewSameNamePartition(ctx context.Context, k any) *Error {
  1204  	return newError(ctx, ErrSameNamePartition, k)
  1205  }
  1206  
  1207  func NewSameNamePartitionField(ctx context.Context, k any) *Error {
  1208  	return newError(ctx, ErrSameNamePartitionField, k)
  1209  }
  1210  
  1211  func NewErrMaxvalueInValuesIn(ctx context.Context) *Error {
  1212  	return newError(ctx, ErrMaxvalueInValuesIn)
  1213  }
  1214  
  1215  func NewErrRowSinglePartitionField(ctx context.Context) *Error {
  1216  	return newError(ctx, ErrRowSinglePartitionField)
  1217  }
  1218  
  1219  func NewErrTooManyPartitionFuncFields(ctx context.Context, k any) *Error {
  1220  	return newError(ctx, ErrTooManyPartitionFuncFields, k)
  1221  }
  1222  
  1223  func NewErrTooManyPartitions(ctx context.Context) *Error {
  1224  	return newError(ctx, ErrTooManyPartitions)
  1225  }
  1226  
  1227  func NewPartitionFuncNotAllowed(ctx context.Context, k any) *Error {
  1228  	return newError(ctx, ErrPartitionFuncNotAllowed, k)
  1229  }
  1230  
  1231  func NewFieldTypeNotAllowedAsPartitionField(ctx context.Context, k any) *Error {
  1232  	return newError(ctx, ErrFieldTypeNotAllowedAsPartitionField, k)
  1233  }
  1234  
  1235  func NewPartitionNoTemporary(ctx context.Context) *Error {
  1236  	return newError(ctx, ErrPartitionNoTemporary)
  1237  }
  1238  
  1239  func NewBlobFieldInPartFunc(ctx context.Context) *Error {
  1240  	return newError(ctx, ErrBlobFieldInPartFunc)
  1241  }
  1242  
  1243  func NewUniqueKeyNeedAllFieldsInPf(ctx context.Context, k any) *Error {
  1244  	return newError(ctx, ErrUniqueKeyNeedAllFieldsInPf, k)
  1245  }
  1246  
  1247  func NewErrPartitionMaxvalue(ctx context.Context) *Error {
  1248  	return newError(ctx, ErrPartitionMaxvalue)
  1249  }
  1250  
  1251  func NewErrRangeNotIncreasing(ctx context.Context) *Error {
  1252  	return newError(ctx, ErrRangeNotIncreasing)
  1253  }
  1254  
  1255  func NewErrForeignKeyOnPartitioned(ctx context.Context) *Error {
  1256  	return newError(ctx, ErrForeignKeyOnPartitioned)
  1257  }
  1258  func NewCheckRecursiveLevel(ctx context.Context) *Error {
  1259  	return newError(ctx, ErrCheckRecursiveLevel)
  1260  }
  1261  
  1262  func NewErrTooManyFields(ctx context.Context) *Error {
  1263  	return newError(ctx, ErrTooManyFields)
  1264  }
  1265  
  1266  func NewErrDupFieldName(ctx context.Context, k any) *Error {
  1267  	return newError(ctx, ErrDupFieldName, k)
  1268  }
  1269  
  1270  func NewErrKeyColumnDoesNotExist(ctx context.Context, k any) *Error {
  1271  	return newError(ctx, ErrKeyColumnDoesNotExist, k)
  1272  }
  1273  
  1274  func NewErrCantDropFieldOrKey(ctx context.Context, k any) *Error {
  1275  	return newError(ctx, ErrCantDropFieldOrKey, k)
  1276  }
  1277  
  1278  func NewErrMultiplePriKey(ctx context.Context) *Error {
  1279  	return newError(ctx, ErrMultiplePriKey)
  1280  }
  1281  
  1282  func NewErrTooManyKeys(ctx context.Context, k any) *Error {
  1283  	return newError(ctx, ErrTooManyKeys, k)
  1284  }
  1285  
  1286  func NewErrTooManyKeyParts(ctx context.Context, k any) *Error {
  1287  	return newError(ctx, ErrTooManyKeyParts, k)
  1288  }
  1289  
  1290  func NewErrWrongColumnName(ctx context.Context, k any) *Error {
  1291  	return newError(ctx, ErrWrongColumnName, k)
  1292  }
  1293  
  1294  func NewErrWrongNameForIndex(ctx context.Context, k any) *Error {
  1295  	return newError(ctx, ErrWrongNameForIndex, k)
  1296  }
  1297  
  1298  func NewErrInvalidDefault(ctx context.Context, k any) *Error {
  1299  	return newError(ctx, ErrInvalidDefault, k)
  1300  }
  1301  
  1302  func NewErrDropIndexNeededInForeignKey(ctx context.Context, args1 any) *Error {
  1303  	return newError(ctx, ErrDropIndexNeededInForeignKey, args1)
  1304  }
  1305  
  1306  func NewErrFKIncompatibleColumns(ctx context.Context, oriColName any, refColName any, fkName any) *Error {
  1307  	return newError(ctx, ErrFKIncompatibleColumns, oriColName, refColName, fkName)
  1308  }
  1309  
  1310  func NewErrForeignKeyColumnCannotChangeChild(ctx context.Context, args1 any, args2 any, args3 any) *Error {
  1311  	return newError(ctx, ErrForeignKeyColumnCannotChangeChild, args1, args2, args3)
  1312  }
  1313  
  1314  func NewErrForeignKeyColumnCannotChange(ctx context.Context, oriColName any, fkName any) *Error {
  1315  	return newError(ctx, ErrForeignKeyColumnCannotChange, oriColName, fkName)
  1316  }
  1317  
  1318  func NewErrTableMustHaveColumns(ctx context.Context) *Error {
  1319  	return newError(ctx, ErrTableMustHaveColumns)
  1320  }
  1321  
  1322  func NewErrCantRemoveAllFields(ctx context.Context) *Error {
  1323  	return newError(ctx, ErrCantRemoveAllFields)
  1324  }
  1325  
  1326  func NewErrFkColumnCannotDropChild(ctx context.Context, oriColName any, childFKName any, childTableName any) *Error {
  1327  	return newError(ctx, ErrFkColumnCannotDropChild, oriColName, childFKName, childTableName)
  1328  }
  1329  
  1330  func NewErrFkColumnCannotDrop(ctx context.Context, colName any, fKName any) *Error {
  1331  	return newError(ctx, ErrFkColumnCannotDrop, colName, fKName)
  1332  }
  1333  
  1334  func NewErrDependentByPartitionFunction(ctx context.Context, colName any) *Error {
  1335  	return newError(ctx, ErrDependentByPartitionFunction, colName)
  1336  }
  1337  
  1338  func NewErrAlterOperationNotSupportedReasonFkRename(ctx context.Context) *Error {
  1339  	return newError(ctx, ErrAlterOperationNotSupportedReasonFkRename)
  1340  }
  1341  
  1342  func NewErrPrimaryCantHaveNull(ctx context.Context) *Error {
  1343  	return newError(ctx, ErrPrimaryCantHaveNull)
  1344  }
  1345  
  1346  func NewErrPartitionMgmtOnNonpartitioned(ctx context.Context) *Error {
  1347  	return newError(ctx, ErrPartitionMgmtOnNonpartitioned)
  1348  }
  1349  
  1350  func NewErrUnsupportedOption(ctx context.Context, option string) *Error {
  1351  	return newError(ctx, ErrUnsupportedOption, option)
  1352  }
  1353  
  1354  func NewErrInvalidValue(ctx context.Context, option string, value string) *Error {
  1355  	return newError(ctx, ErrInvalidValue, option, value)
  1356  }
  1357  
  1358  func NewErrLackOption(ctx context.Context, option string) *Error {
  1359  	return newError(ctx, ErrLackOption, option)
  1360  }
  1361  
  1362  func NewErrDuplicateConnector(ctx context.Context, tableName string) *Error {
  1363  	return newError(ctx, ErrDuplicateConnector, tableName)
  1364  }
  1365  
  1366  func NewErrUnsupportedDataType(ctx context.Context, typ any) *Error {
  1367  	return newError(ctx, ErrUnsupportedDataType, typ)
  1368  }
  1369  
  1370  func NewErrTaskNotFound(ctx context.Context, taskID uint64) *Error {
  1371  	return newError(ctx, ErrTaskNotFound, taskID)
  1372  }
  1373  
  1374  func NewErrTooManyParameter(ctx context.Context) *Error {
  1375  	return newError(ctx, ErrTooManyParameter)
  1376  }
  1377  
  1378  func NewErrFKRowIsReferenced(ctx context.Context) *Error {
  1379  	return newError(ctx, ErrFKRowIsReferenced)
  1380  }
  1381  
  1382  func NewErrDuplicateKeyName(ctx context.Context, fkName any) *Error {
  1383  	return newError(ctx, ErrDuplicateKeyName, fkName)
  1384  }
  1385  
  1386  func NewErrFKNoReferencedRow2(ctx context.Context) *Error {
  1387  	return newError(ctx, ErrFKNoReferencedRow2)
  1388  }
  1389  
  1390  var contextFunc atomic.Value
  1391  
  1392  func SetContextFunc(f func() context.Context) {
  1393  	contextFunc.Store(f)
  1394  }
  1395  
  1396  // Context should be trace.DefaultContext
  1397  func Context() context.Context {
  1398  	return contextFunc.Load().(func() context.Context)()
  1399  }
  1400  
  1401  func init() {
  1402  	SetContextFunc(func() context.Context { return context.Background() })
  1403  }