// NewSQLErrorFromError returns a *SQLError from the provided error.
// If it's not the right type, it still tries to get it from a regexp.
434734
func NewSQLErrorFromError(err error) error {
	if err == nil {
		return nil
	}

	if serr, ok := err.(*SQLError); ok {
		return serr
	}

	msg := err.Error()
	match := errExtract.FindStringSubmatch(msg)
	if len(match) < 2 {
		// Map vitess error codes into the mysql equivalent
		code := vterrors.Code(err)
		num := ERUnknownError
		switch code {
		case vtrpcpb.Code_CANCELED:
			num = ERQueryInterrupted
		case vtrpcpb.Code_UNKNOWN:
			num = ERUnknownError
		case vtrpcpb.Code_INVALID_ARGUMENT:
			// TODO/demmer there are several more appropriate mysql error
			// codes for the various invalid argument cases.
			// it would be better to change the call sites to use
			// the mysql style "(errno X) (sqlstate Y)" format rather than
			// trying to add vitess error codes for all these cases
			num = ERUnknownError
		case vtrpcpb.Code_DEADLINE_EXCEEDED:
			num = ERQueryInterrupted
		case vtrpcpb.Code_NOT_FOUND:
			num = ERUnknownError
		case vtrpcpb.Code_ALREADY_EXISTS:
			num = ERUnknownError
		case vtrpcpb.Code_PERMISSION_DENIED:
			num = ERAccessDeniedError
		case vtrpcpb.Code_UNAUTHENTICATED:
			num = ERAccessDeniedError
		case vtrpcpb.Code_RESOURCE_EXHAUSTED:
			num = ERTooManyUserConnections
		case vtrpcpb.Code_FAILED_PRECONDITION:
			num = ERUnknownError
		case vtrpcpb.Code_ABORTED:
			num = ERQueryInterrupted
		case vtrpcpb.Code_OUT_OF_RANGE:
			num = ERUnknownError
		case vtrpcpb.Code_UNIMPLEMENTED:
			num = ERNotSupportedYet
		case vtrpcpb.Code_INTERNAL:
			num = ERUnknownError
		case vtrpcpb.Code_UNAVAILABLE:
			num = ERUnknownError
		case vtrpcpb.Code_DATA_LOSS:
			num = ERUnknownError
		}

		// Not found, build a generic SQLError.
		return &SQLError{
			Num:     num,
			State:   SSUnknownSQLState,
			Message: msg,
		}
	}

	num, err := strconv.Atoi(match[1])
	if err != nil {
		return &SQLError{
			Num:     ERUnknownError,
			State:   SSUnknownSQLState,
			Message: msg,
		}
	}

	serr := &SQLError{
		Num:     num,
		State:   match[2],
		Message: msg,
	}
	return serr
}
1023638
func NewSQLDB(connection types.SQLConnection) (*SQLDB, error) {
	db := &SQLDB{
		Schema: connection.DBSchema,
		Log:    connection.Log,
	}

	var url string

	switch connection.DBAdapter {
	case types.PostgresDB:
		db.DBAdapter = adapters.NewPostgresAdapter(safe(connection.DBSchema), connection.Log)
		url = connection.DBURL

	case types.SQLiteDB:
		db.DBAdapter = adapters.NewSQLiteAdapter(connection.Log)
		// "?_journal_mode=WAL" parameter is necessary to prevent database locking
		url = connection.DBURL + "?_journal_mode=WAL"

	default:
		return nil, errors.New("invalid database adapter")
	}

	var err error
	db.DB, err = db.DBAdapter.Open(url)
	if err != nil {
		db.Log.Info("msg", "Error opening database connection", "err", err)
		return nil, err
	}

	if err = db.Ping(); err != nil {
		db.Log.Info("msg", "Error database not available", "err", err)
		return nil, err
	}

	db.Log.Info("msg", "Initializing DB")

	// Create dictionary and log tables
	sysTables := db.getSysTablesDefinition()

	// IMPORTANT: DO NOT CHANGE TABLE CREATION ORDER (1)
	if err = db.createTable(sysTables[types.SQLDictionaryTableName], true); err != nil {
		if !db.DBAdapter.ErrorEquals(err, types.SQLErrorTypeDuplicatedTable) {
			db.Log.Info("msg", "Error creating Dictionary table", "err", err)
			return nil, err
		}
	}

	// IMPORTANT: DO NOT CHANGE TABLE CREATION ORDER (2)
	if err = db.createTable(sysTables[types.SQLLogTableName], true); err != nil {
		if !db.DBAdapter.ErrorEquals(err, types.SQLErrorTypeDuplicatedTable) {
			db.Log.Info("msg", "Error creating Log table", "err", err)
			return nil, err
		}
	}

	// IMPORTANT: DO NOT CHANGE TABLE CREATION ORDER (3)
	if err = db.createTable(sysTables[types.SQLChainInfoTableName], true); err != nil {
		if !db.DBAdapter.ErrorEquals(err, types.SQLErrorTypeDuplicatedTable) {
			db.Log.Info("msg", "Error creating Chain Info table", "err", err)
			return nil, err
		}
	}

	if err = db.CleanTables(connection.ChainID, connection.BurrowVersion); err != nil {
		db.Log.Info("msg", "Error cleaning tables", "err", err)
		return nil, err
	}
	return db, nil
}
512141
func NewErr(errCode uint16, args ...interface{}) *SQLError {
	e := &SQLError{Code: errCode}

	if s, ok := MySQLState[errCode]; ok {
		e.State = s
	} else {
		e.State = DefaultMySQLState
	}

	if format, ok := MySQLErrName[errCode]; ok {
		e.Message = fmt.Sprintf(format, args...)
	} else {
		e.Message = fmt.Sprint(args...)
	}

	return e
}
111684
func DefaultOnError(err error, w http.ResponseWriter, r *http.Request) {
	log.Printf("[httpgzip] %v", err)
}
1343085
func errLexerInvalidChar(err error) *s3Error {
	return &s3Error{
		code:       "LexerInvalidChar",
		message:    "The SQL expression contains an invalid character.",
		statusCode: 400,
		cause:      err,
	}
}
118370
func (d *defaulter) logFormatError(t string, err error) {
	d.logError(fmt.Sprintf("value has illegal format for %q", t), err)
}
816245
func txRuleError(c wire.RejectCode, desc string) RuleError {
	return RuleError{
		Err: TxRuleError{RejectCode: c, Description: desc},
	}
}
474810
func FirstError(errs ...error) error {
	for i := range errs {
		if errs[i] != nil {
			return errs[i]
		}
	}
	return nil
}
314737
func MySQLErrorNumber(err error) uint16 {
	if err, ok := err.(*mysql.MySQLError); ok {
		return err.Number
	}
	return 0
}
599127
func IsErrorTsquerySyntax(err error) bool {
	if ErrorTsquerySyntax.Match(err) {
		return true
	}
	switch err.(type) {
	case nil:
		return false
	case *pq.Error:
		e := err.(*pq.Error)
		if e.Code != "42601" {
			return false
		}
		return strings.Contains(e.Message, "syntax error in tsquery:")
	default:
		return strings.Contains(err.Error(), "pq: syntax error in tsquery:")
	}
}
1265872
func errCastFailed(err error) *s3Error {
	return &s3Error{
		code:       "CastFailed",
		message:    "Attempt to convert from one data type to another using CAST failed in the SQL expression.",
		statusCode: 400,
		cause:      err,
	}
}
692585
func NewStatErrorResponse(
	err error,
	entries map[int](map[string]string)) StatResponse {
	return &genericResponse{
		err:         err,
		statEntries: entries,
	}
}
603237
func (is *Is) Err(e error) {
	is.TB.Helper()
	if isNil(e) {
		fail(is, "expected error")
	}
}
70768
func NewErrf(errCode uint16, format string, args ...interface{}) *SQLError {
	e := &SQLError{Code: errCode}

	if s, ok := MySQLState[errCode]; ok {
		e.State = s
	} else {
		e.State = DefaultMySQLState
	}

	e.Message = fmt.Sprintf(format, args...)

	return e
}
407953
func multiErrorFromErrors(ch <-chan error) error {
	if ch == nil {
		return nil
	}
	ret := errors.MultiError(nil)
	for e := range ch {
		if e == nil {
			continue
		}
		ret = append(ret, e)
	}
	if len(ret) == 0 {
		return nil
	}
	return ret
}
179499
func IsErrorDuplicateViolateUniqueConstraint(err error) bool {
	if ErrorDuplicateViolateUniqueConstraint.Match(err) {
		return true
	}
	switch e := err.(type) {
	case nil:
		return false
	case *pq.Error:
		return e.Code == "23505"
	case *mysql.MySQLError:
		return e.Number == 1062
	default:
		return strings.Contains(err.Error(), "pq: duplicate key value violates unique constraint")
	}
}
1144283
func NewSQLStorage(dialect string, args ...interface{}) (*SQLStorage, error) {
	gormDB, err := gorm.Open(dialect, args...)
	if err != nil {
		return nil, err
	}
	return &SQLStorage{
		DB: *gormDB,
	}, nil
}