Skip to content

Commit 6f66242

Browse files
committed
tapdb: allow DB schema errors to be detected
This commit adds database specific detection for errors that represent a mismatch between the query and the actual database schema. This will mainly be used for unit tests and should never occur in production code.
1 parent cdedffd commit 6f66242

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

tapdb/sqlerrors.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package tapdb
33
import (
44
"errors"
55
"fmt"
6+
"strings"
67

78
"github.com/jackc/pgconn"
89
"github.com/jackc/pgerrcode"
@@ -52,6 +53,20 @@ func parseSqliteError(sqliteErr *sqlite.Error) error {
5253
DbError: sqliteErr,
5354
}
5455

56+
// Generic error, need to parse the message further.
57+
case sqlite3.SQLITE_ERROR:
58+
errMsg := sqliteErr.Error()
59+
60+
switch {
61+
case strings.Contains(errMsg, "no such table"):
62+
return &ErrSchemaError{
63+
DbError: sqliteErr,
64+
}
65+
66+
default:
67+
return fmt.Errorf("unknown sqlite error: %w", sqliteErr)
68+
}
69+
5570
default:
5671
return fmt.Errorf("unknown sqlite error: %w", sqliteErr)
5772
}
@@ -73,6 +88,12 @@ func parsePostgresError(pqErr *pgconn.PgError) error {
7388
DbError: pqErr,
7489
}
7590

91+
// Handle schema error.
92+
case pgerrcode.UndefinedColumn, pgerrcode.UndefinedTable:
93+
return &ErrSchemaError{
94+
DbError: pqErr,
95+
}
96+
7697
default:
7798
return fmt.Errorf("unknown postgres error: %w", pqErr)
7899
}
@@ -111,3 +132,25 @@ func IsSerializationError(err error) bool {
111132
var serializationError *ErrSerializationError
112133
return errors.As(err, &serializationError)
113134
}
135+
136+
// ErrSchemaError is an error type which represents a database agnostic error
137+
// that the schema of the database is incorrect for the given query.
138+
type ErrSchemaError struct {
139+
DbError error
140+
}
141+
142+
// Unwrap returns the wrapped error.
143+
func (e ErrSchemaError) Unwrap() error {
144+
return e.DbError
145+
}
146+
147+
// Error returns the error message.
148+
func (e ErrSchemaError) Error() string {
149+
return e.DbError.Error()
150+
}
151+
152+
// IsSchemaError returns true if the given error is a schema error.
153+
func IsSchemaError(err error) bool {
154+
var schemaError *ErrSchemaError
155+
return errors.As(err, &schemaError)
156+
}

0 commit comments

Comments
 (0)