Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

refactor: replace WalkThroughError with SchemaViolationError (#18088)

Danny Xua0cae8b8be6e
diff --git a/backend/plugin/advisor/catalog/test/mysql_walk_through.yaml b/backend/plugin/advisor/catalog/test/mysql_walk_through.yaml
index 7cfecfe1d2..9a91aa2d76 100644
--- a/backend/plugin/advisor/catalog/test/mysql_walk_through.yaml
+++ b/backend/plugin/advisor/catalog/test/mysql_walk_through.yaml
@@ -4,11 +4,7 @@
RENAME TABLE `other`.`t1` TO `other`.`t2`;
ignore_case_sensitive: false
want: ""
- err:
- type: 201
- content: Database `other` is not the current database `test`
- line: 2
- payload: null
+ err: Database `other` is not the current database `test`
- statement: |-
CREATE TABLE `test`.`t1` (a INT);
RENAME TABLE `test`.`t1` TO `other`.`t1`;
@@ -27,21 +23,13 @@
RENAME TABLE t2 TO t1;
ignore_case_sensitive: false
want: ""
- err:
- type: 301
- content: Table `t1` already exists
- line: 3
- payload: null
+ err: Table `t1` already exists
- statement: |-
CREATE TABLE t1(a INT);
RENAME TABLE t2 TO t3;
ignore_case_sensitive: false
want: ""
- err:
- type: 302
- content: Table `t2` does not exist
- line: 2
- payload: null
+ err: Table `t2` does not exist
- statement: |-
CREATE TABLE t1 (a INT);
RENAME TABLE t1 TO t2;
@@ -71,22 +59,14 @@
- statement: CREATE DATABASE another;
ignore_case_sensitive: false
want: ""
- err:
- type: 201
- content: Database `another` is not the current database `test`
- line: 1
- payload: null
+ err: Database `another` is not the current database `test`
- statement: |-
-- this is comment
DROP DATABASE test;
CREATE TABLE t(a int);
ignore_case_sensitive: false
want: ""
- err:
- type: 202
- content: Database `test` is deleted
- line: 1
- payload: null
+ err: Database `test` is deleted
- statement: |-
ALTER DATABASE CHARACTER SET = utf8mb4;
ALTER DATABASE test COLLATE utf8mb4_polish_ci;
@@ -227,11 +207,7 @@
CREATE SPATIAL INDEX sk1 ON t1 (a);
ignore_case_sensitive: false
want: ""
- err:
- type: 507
- content: All parts of a SPATIAL index must be NOT NULL, but `a` is nullable
- line: 2
- payload: null
+ err: All parts of a SPATIAL index must be NOT NULL, but `a` is nullable
- statement: |-
CREATE TABLE t1(
a INT PRIMARY KEY,
@@ -392,22 +368,14 @@
ALTER TABLE t1 ALTER COLUMN a SET DEFAULT NULL;
ignore_case_sensitive: false
want: ""
- err:
- type: 406
- content: Invalid default value for column `a`
- line: 2
- payload: null
+ err: Invalid default value for column `a`
- statement: |-
CREATE TABLE t1(a INT);
ALTER TABLE t1 CHANGE COLUMN a a BLOB;
ALTER TABLE t1 ALTER COLUMN a SET DEFAULT 'default value';
ignore_case_sensitive: false
want: ""
- err:
- type: 407
- content: BLOB, TEXT, GEOMETRY or JSON column `a` can't have a default value
- line: 3
- payload: null
+ err: BLOB, TEXT, GEOMETRY or JSON column `a` can't have a default value
- statement: |-
CREATE TABLE t1(a INT);
ALTER TABLE t1 CHANGE COLUMN a a BLOB;
@@ -560,29 +528,17 @@
);
ignore_case_sensitive: false
want: ""
- err:
- type: 404
- content: There can be only one auto column for table `t1`
- line: 1
- payload: null
+ err: There can be only one auto column for table `t1`
- statement: CREATE TABLE tvx SELECT (x,z) FROM (VALUES ROW(1,3,5), ROW(2,4,6)) AS v(x,y,z);
ignore_case_sensitive: false
want: ""
- err:
- type: 303
- content: Disallow the CREATE TABLE AS statement but "CREATE TABLE tvx SELECT (x,z) FROM (VALUES ROW(1,3,5), ROW(2,4,6)) AS v(x,y,z);" uses
- line: 1
- payload: null
+ err: Disallow the CREATE TABLE AS statement but "CREATE TABLE tvx SELECT (x,z) FROM (VALUES ROW(1,3,5), ROW(2,4,6)) AS v(x,y,z);" uses
- statement: |-
CREATE TABLE t1(a int);
CREATE TABLE t2 (b INT) SELECT a FROM t1;
ignore_case_sensitive: false
want: ""
- err:
- type: 303
- content: Disallow the CREATE TABLE AS statement but "CREATE TABLE t2 (b INT) SELECT a FROM t1;" uses
- line: 2
- payload: null
+ err: Disallow the CREATE TABLE AS statement but "CREATE TABLE t2 (b INT) SELECT a FROM t1;" uses
- statement: |-
CREATE TABLE t1(
a int
@@ -722,33 +678,21 @@
);
ignore_case_sensitive: false
want: ""
- err:
- type: 406
- content: Invalid default value for column `a`
- line: 2
- payload: null
+ err: Invalid default value for column `a`
- statement: |-
CREATE TABLE t1(
a BLOB DEFAULT 'this is a default value'
);
ignore_case_sensitive: false
want: ""
- err:
- type: 407
- content: BLOB, TEXT, GEOMETRY or JSON column `a` can't have a default value
- line: 2
- payload: null
+ err: BLOB, TEXT, GEOMETRY or JSON column `a` can't have a default value
- statement: |-
CREATE TABLE t1(
a INT ON UPDATE NOW()
);
ignore_case_sensitive: false
want: ""
- err:
- type: 405
- content: Column `a` use ON UPDATE but is not DATETIME or TIMESTAMP
- line: 2
- payload: null
+ err: Column `a` use ON UPDATE but is not DATETIME or TIMESTAMP
- statement: |-
CREATE TABLE t1(
a INT NOT NULL DEFAULT 1 PRIMARY KEY,
diff --git a/backend/plugin/advisor/catalog/test/pg_walk_through.yaml b/backend/plugin/advisor/catalog/test/pg_walk_through.yaml
index c222b9090f..ea9621b38a 100644
--- a/backend/plugin/advisor/catalog/test/pg_walk_through.yaml
+++ b/backend/plugin/advisor/catalog/test/pg_walk_through.yaml
@@ -553,30 +553,15 @@
- statement: ALTER TABLE test DROP COLUMN id;
ignore_case_sensitive: false
want: ""
- err:
- type: 408
- content: 'Cannot drop column "id" in table "public"."test", it''s referenced by view: "public"."v1"'
- line: 1
- payload:
- - '"public"."v1"'
+ err: 'Cannot drop column "id" in table "public"."test", it''s referenced by view: "public"."v1"'
- statement: ALTER TABLE test ALTER COLUMN id TYPE varchar(20);
ignore_case_sensitive: false
want: ""
- err:
- type: 408
- content: 'Cannot alter type of column "id" in table "public"."test", it''s referenced by view: "public"."v1"'
- line: 1
- payload:
- - '"public"."v1"'
+ err: 'Cannot alter type of column "id" in table "public"."test", it''s referenced by view: "public"."v1"'
- statement: DROP TABLE test;
ignore_case_sensitive: false
want: ""
- err:
- type: 304
- content: 'Cannot drop table "public"."test", it''s referenced by view: "public"."v1"'
- line: 1
- payload:
- - '"public"."v1"'
+ err: 'Cannot drop table "public"."test", it''s referenced by view: "public"."v1"'
- statement: |-
DROP VIEW v1;
ALTER TABLE test DROP COLUMN id;
diff --git a/backend/plugin/advisor/catalog/test/tidb_walk_through.yaml b/backend/plugin/advisor/catalog/test/tidb_walk_through.yaml
index 691a04403f..894ef49a6f 100644
--- a/backend/plugin/advisor/catalog/test/tidb_walk_through.yaml
+++ b/backend/plugin/advisor/catalog/test/tidb_walk_through.yaml
@@ -1,127 +1,67 @@
- statement: CREATE TABLE t(a date default '');
ignore_case_sensitive: false
want: ""
- err:
- type: 407
- content: '[types:1292]Incorrect datetime value: '''''
- line: 1
- payload: null
+ err: '[types:1292]Incorrect datetime value: '''''
- statement: |-
CREATE TABLE t(a TEXT);
ALTER TABLE T ALTER COLUMN a SET DEFAULT '1';
ignore_case_sensitive: true
want: ""
- err:
- type: 407
- content: BLOB, TEXT, GEOMETRY or JSON column `a` can't have a default value
- line: 2
- payload: null
+ err: BLOB, TEXT, GEOMETRY or JSON column `a` can't have a default value
- statement: ' CREATE TABLE t(a TEXT DEFAULT ''1'')'
ignore_case_sensitive: false
want: ""
- err:
- type: 407
- content: BLOB, TEXT, GEOMETRY or JSON column `a` can't have a default value
- line: 1
- payload: null
+ err: BLOB, TEXT, GEOMETRY or JSON column `a` can't have a default value
- statement: |-
CREATE TABLE t(a INT NOT NULL);
ALTER TABLE t ALTER COLUMN a SET DEFAULT NULL;
ignore_case_sensitive: false
want: ""
- err:
- type: 406
- content: Invalid default value for column `a`
- line: 2
- payload: null
+ err: Invalid default value for column `a`
- statement: ' CREATE TABLE t(a INT NOT NULL DEFAULT NULL)'
ignore_case_sensitive: false
want: ""
- err:
- type: 406
- content: Invalid default value for column `a`
- line: 1
- payload: null
+ err: Invalid default value for column `a`
- statement: ' CREATE TABLE t(a int ON UPDATE NOW())'
ignore_case_sensitive: false
want: ""
- err:
- type: 405
- content: Column `a` use ON UPDATE but is not DATETIME or TIMESTAMP
- line: 1
- payload: null
+ err: Column `a` use ON UPDATE but is not DATETIME or TIMESTAMP
- statement: ' CREATE TABLE t(a int auto_increment, b int auto_increment);'
ignore_case_sensitive: false
want: ""
- err:
- type: 404
- content: There can be only one auto column for table `t`
- line: 1
- payload: null
+ err: There can be only one auto column for table `t`
- statement: ' CREATE TABLE t as select * from t1;'
ignore_case_sensitive: false
want: ""
- err:
- type: 303
- content: Disallow the CREATE TABLE AS statement but "CREATE TABLE t as select * from t1;" uses
- line: 1
- payload: null
+ err: Disallow the CREATE TABLE AS statement but "CREATE TABLE t as select * from t1;" uses
- statement: "\n\t\t\t\tCREATE TABLE t(a int, b int); \n\t\t\t\tCREATE INDEX idx_c on t(c);\n\t\t\t"
ignore_case_sensitive: false
want: ""
- err:
- type: 402
- content: Column `c` does not exist in table `t`
- line: 3
- payload: null
+ err: Column `c` does not exist in table `t`
- statement: "\n\t\t\t\tCREATE TABLE t(a int, b int); \n\t\t\t\tALTER TABLE t MODIFY COLUMN c int;\n\t\t\t"
ignore_case_sensitive: false
want: ""
- err:
- type: 402
- content: Column `c` does not exist in table `t`
- line: 3
- payload: null
+ err: Column `c` does not exist in table `t`
- statement: "\n\t\t\t\tCREATE TABLE t(a int, b int); \n\t\t\t\tALTER TABLE t CHANGE COLUMN c aa int;\n\t\t\t"
ignore_case_sensitive: false
want: ""
- err:
- type: 402
- content: Column `c` does not exist in table `t`
- line: 3
- payload: null
+ err: Column `c` does not exist in table `t`
- statement: "\n\t\t\t\tCREATE TABLE t(a int, b int); \n\t\t\t\tALTER TABLE t DROP COLUMN c;\n\t\t\t"
ignore_case_sensitive: false
want: ""
- err:
- type: 402
- content: Column `c` does not exist in table `t`
- line: 3
- payload: null
+ err: Column `c` does not exist in table `t`
- statement: "\n\t\t\t\tCREATE TABLE t(a int, b int); \n\t\t\t\tALTER TABLE t RENAME COLUMN c TO cc;\n\t\t\t"
ignore_case_sensitive: false
want: ""
- err:
- type: 402
- content: Column `c` does not exist in table `t`
- line: 3
- payload: null
+ err: Column `c` does not exist in table `t`
- statement: "\n\t\t\t\tCREATE TABLE t(a int, b int); \n\t\t\t\tALTER TABLE t RENAME COLUMN c TO cc;\n\t\t\t"
ignore_case_sensitive: false
want: ""
- err:
- type: 402
- content: Column `c` does not exist in table `t`
- line: 3
- payload: null
+ err: Column `c` does not exist in table `t`
- statement: "\n\t\t\t\tCREATE TABLE t(a int, b int); \n\t\t\t\tALTER TABLE t ALTER COLUMN c DROP DEFAULT;\n\t\t\t"
ignore_case_sensitive: false
want: ""
- err:
- type: 402
- content: Column `c` does not exist in table `t`
- line: 3
- payload: null
+ err: Column `c` does not exist in table `t`
- statement: |-
ALTER DATABASE CHARACTER SET = utf8mb4;
ALTER DATABASE test COLLATE utf8mb4_polish_ci;
@@ -509,11 +449,7 @@
- statement: ' DROP TABLE t1, t2'
ignore_case_sensitive: false
want: ""
- err:
- type: 302
- content: Table `t1` does not exist
- line: 1
- payload: null
+ err: Table `t1` does not exist
- statement: |-
CREATE TABLE t(a int);
RENAME TABLE t to other_db.t1
@@ -558,11 +494,7 @@
CREATE TABLE t(a int);
ignore_case_sensitive: false
want: ""
- err:
- type: 202
- content: Database `test` is deleted
- line: 3
- payload: null
+ err: Database `test` is deleted
- statement: |-
CREATE TABLE t(
a int PRIMARY KEY DEFAULT 1,
diff --git a/backend/plugin/advisor/catalog/walk_through.go b/backend/plugin/advisor/catalog/walk_through.go
index aad426b3e1..45b13701f7 100644
--- a/backend/plugin/advisor/catalog/walk_through.go
+++ b/backend/plugin/advisor/catalog/walk_through.go
@@ -10,9 +10,6 @@ import (
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
)
-// WalkThroughErrorType is the type of WalkThroughError.
-type WalkThroughErrorType int
-
const (
// PrimaryKeyName is the string for PK.
PrimaryKeyName string = "PRIMARY"
@@ -22,160 +19,28 @@ const (
SpatialName string = "SPATIAL"
publicSchemaName = "public"
-
- // ErrorTypeUnsupported is the error for unsupported cases.
- ErrorTypeUnsupported WalkThroughErrorType = 1
- // ErrorTypeInternal is the error for internal errors.
- ErrorTypeInternal WalkThroughErrorType = 2
-
- // 101 parse error type.
-
- // ErrorTypeDeparseError is the error in deparsing.
- ErrorTypeDeparseError WalkThroughErrorType = 102
-
- // 201 ~ 299 database error type.
-
- // ErrorTypeAccessOtherDatabase is the error that try to access other database.
- ErrorTypeAccessOtherDatabase = 201
- // ErrorTypeDatabaseIsDeleted is the error that try to access the deleted database.
- ErrorTypeDatabaseIsDeleted = 202
- // ErrorTypeReferenceOtherDatabase is the error that try to reference other database.
- ErrorTypeReferenceOtherDatabase = 203
-
- // 301 ~ 399 table error type.
-
- // ErrorTypeTableExists is the error that table exists.
- ErrorTypeTableExists = 301
- // ErrorTypeTableNotExists is the error that table not exists.
- ErrorTypeTableNotExists = 302
- // ErrorTypeUseCreateTableAs is the error that using CREATE TABLE AS statements.
- ErrorTypeUseCreateTableAs = 303
- // ErrorTypeTableIsReferencedByView is the error that table is referenced by view.
- ErrorTypeTableIsReferencedByView = 304
-
- // 401 ~ 499 column error type.
-
- // ErrorTypeColumnExists is the error that column exists.
- ErrorTypeColumnExists = 401
- // ErrorTypeColumnNotExists is the error that column not exists.
- ErrorTypeColumnNotExists = 402
- // ErrorTypeDropAllColumns is the error that dropping all columns in a table.
- ErrorTypeDropAllColumns = 403
- // ErrorTypeAutoIncrementExists is the error that auto_increment exists.
- ErrorTypeAutoIncrementExists = 404
- // ErrorTypeOnUpdateColumnNotDatetimeOrTimestamp is the error that the ON UPDATE column is not datetime or timestamp.
- ErrorTypeOnUpdateColumnNotDatetimeOrTimestamp = 405
- // ErrorTypeSetNullDefaultForNotNullColumn is the error that setting NULL default value for the NOT NULL column.
- ErrorTypeSetNullDefaultForNotNullColumn = 406
- // ErrorTypeInvalidColumnTypeForDefaultValue is the error that invalid column type for default value.
- ErrorTypeInvalidColumnTypeForDefaultValue = 407
- // ErrorTypeColumnIsReferencedByView is the error that column is referenced by view.
- ErrorTypeColumnIsReferencedByView = 408
-
- // 501 ~ 599 index error type.
-
- // ErrorTypePrimaryKeyExists is the error that PK exists.
- ErrorTypePrimaryKeyExists = 501
- // ErrorTypeIndexExists is the error that index exists.
- ErrorTypeIndexExists = 502
- // ErrorTypeIndexEmptyKeys is the error that index has empty keys.
- ErrorTypeIndexEmptyKeys = 503
- // ErrorTypePrimaryKeyNotExists is the error that PK does not exist.
- ErrorTypePrimaryKeyNotExists = 504
- // ErrorTypeIndexNotExists is the error that index does not exist.
- ErrorTypeIndexNotExists = 505
- // ErrorTypeIncorrectIndexName is the incorrect index name error.
- ErrorTypeIncorrectIndexName = 506
- // ErrorTypeSpatialIndexKeyNullable is the error that keys in spatial index are nullable.
- ErrorTypeSpatialIndexKeyNullable = 507
-
- // 701 ~ 799 schema error type.
-
- // ErrorTypeSchemaNotExists is the error that schema does not exist.
- ErrorTypeSchemaNotExists = 701
-
- // 801 ~ 899 relation error type.
-
- // ErrorTypeRelationExists is the error that relation already exists.
- ErrorTypeRelationExists = 801
-
- // 901 ~ 999 constraint error type.
-
- // ErrorTypeConstraintNotExists is the error that constraint doesn't exist.
- ErrorTypeConstraintNotExists = 901
)
-// WalkThroughError is the error for walking-through.
-type WalkThroughError struct {
- Type WalkThroughErrorType
- Content string
- // TODO(zp): position
- Line int
-
- Payload any
-}
-
-// NewRelationExistsError returns a new ErrorTypeRelationExists.
-func NewRelationExistsError(relationName string, schemaName string) *WalkThroughError {
- return &WalkThroughError{
- Type: ErrorTypeRelationExists,
- Content: fmt.Sprintf("Relation %q already exists in schema %q", relationName, schemaName),
- }
-}
-
-// NewColumnNotExistsError returns a new ErrorTypeColumnNotExists.
-func NewColumnNotExistsError(tableName string, columnName string) *WalkThroughError {
- return &WalkThroughError{
- Type: ErrorTypeColumnNotExists,
- Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, tableName),
- }
-}
-
-// NewIndexNotExistsError returns a new ErrorTypeIndexNotExists.
-func NewIndexNotExistsError(tableName string, indexName string) *WalkThroughError {
- return &WalkThroughError{
- Type: ErrorTypeIndexNotExists,
- Content: fmt.Sprintf("Index `%s` does not exist in table `%s`", indexName, tableName),
- }
+// SchemaViolationError represents a SQL schema validation error that should be reported as advice.
+// It carries an advisor code (int32) that can be converted to advisor.Code by the caller.
+type SchemaViolationError struct {
+ Code int32 // Advisor error code from backend/plugin/advisor/code.go
+ Message string
}
-// NewIndexExistsError returns a new ErrorTypeIndexExists.
-func NewIndexExistsError(tableName string, indexName string) *WalkThroughError {
- return &WalkThroughError{
- Type: ErrorTypeIndexExists,
- Content: fmt.Sprintf("Index `%s` already exists in table `%s`", indexName, tableName),
- }
-}
-
-// NewAccessOtherDatabaseError returns a new ErrorTypeAccessOtherDatabase.
-func NewAccessOtherDatabaseError(current string, target string) *WalkThroughError {
- return &WalkThroughError{
- Type: ErrorTypeAccessOtherDatabase,
- Content: fmt.Sprintf("Database `%s` is not the current database `%s`", target, current),
- }
-}
-
-// NewTableNotExistsError returns a new ErrorTypeTableNotExists.
-func NewTableNotExistsError(tableName string) *WalkThroughError {
- return &WalkThroughError{
- Type: ErrorTypeTableNotExists,
- Content: fmt.Sprintf("Table `%s` does not exist", tableName),
- }
+// Error implements the error interface.
+func (e *SchemaViolationError) Error() string {
+ return e.Message
}
-// NewTableExistsError returns a new ErrorTypeTableExists.
-func NewTableExistsError(tableName string) *WalkThroughError {
- return &WalkThroughError{
- Type: ErrorTypeTableExists,
- Content: fmt.Sprintf("Table `%s` already exists", tableName),
+// NewSchemaViolationError creates a new SchemaViolationError.
+func NewSchemaViolationError(code int32, message string) *SchemaViolationError {
+ return &SchemaViolationError{
+ Code: code,
+ Message: message,
}
}
-// Error implements the error interface.
-func (e *WalkThroughError) Error() string {
- return e.Content
-}
-
// WalkThrough will collect the catalog schema in the databaseState as it walks through the stmt.
func (d *DatabaseState) WalkThrough(ast any) error {
switch d.dbType {
@@ -192,10 +57,7 @@ func (d *DatabaseState) WalkThrough(ast any) error {
}
return nil
default:
- return &WalkThroughError{
- Type: ErrorTypeUnsupported,
- Content: fmt.Sprintf("Walk-through doesn't support engine type: %s", d.dbType),
- }
+ return errors.Errorf("Walk-through doesn't support engine type: %s", d.dbType)
}
}
@@ -232,7 +94,7 @@ func (t *TableState) createIncompleteIndex(name string) *IndexState {
return index
}
-func (s *SchemaState) renameTable(ctx *FinderContext, oldName string, newName string) *WalkThroughError {
+func (s *SchemaState) renameTable(ctx *FinderContext, oldName string, newName string) error {
if oldName == newName {
return nil
}
@@ -240,19 +102,13 @@ func (s *SchemaState) renameTable(ctx *FinderContext, oldName string, newName st
table, exists := s.getTable(oldName)
if !exists {
if ctx.CheckIntegrity {
- return &WalkThroughError{
- Type: ErrorTypeTableNotExists,
- Content: fmt.Sprintf("Table `%s` does not exist", oldName),
- }
+ return NewSchemaViolationError(604, fmt.Sprintf("Table `%s` does not exist", oldName))
}
table = s.createIncompleteTable(oldName)
}
if _, exists := s.getTable(newName); exists {
- return &WalkThroughError{
- Type: ErrorTypeTableExists,
- Content: fmt.Sprintf("Table `%s` already exists", newName),
- }
+ return NewSchemaViolationError(607, fmt.Sprintf("Table `%s` already exists", newName))
}
table.name = newName
@@ -307,15 +163,12 @@ func parseViewName(viewName string) (string, string, error) {
return match[1], match[2], nil
}
-func (d *DatabaseState) existedViewList(viewMap map[string]bool) ([]string, *WalkThroughError) {
+func (d *DatabaseState) existedViewList(viewMap map[string]bool) ([]string, error) {
var result []string
for viewName := range viewMap {
schemaName, viewName, err := parseViewName(viewName)
if err != nil {
- return nil, &WalkThroughError{
- Type: ErrorTypeInternal,
- Content: fmt.Sprintf("failed to check view dependency: %s", err.Error()),
- }
+ return nil, errors.Wrapf(err, "failed to check view dependency")
}
schemaMeta, exists := d.schemaSet[schemaName]
if !exists {
@@ -344,17 +197,14 @@ func (s *SchemaState) pgGeneratePrimaryKeyName(tableName string) string {
}
}
-func (d *DatabaseState) getSchema(schemaName string) (*SchemaState, *WalkThroughError) {
+func (d *DatabaseState) getSchema(schemaName string) (*SchemaState, error) {
if schemaName == "" {
schemaName = publicSchemaName
}
schema, exists := d.schemaSet[schemaName]
if !exists {
if schemaName != publicSchemaName {
- return nil, &WalkThroughError{
- Type: ErrorTypeSchemaNotExists,
- Content: fmt.Sprintf("The schema %q doesn't exist", schemaName),
- }
+ return nil, NewSchemaViolationError(1901, fmt.Sprintf("The schema %q doesn't exist", schemaName))
}
schema = &SchemaState{
ctx: d.ctx.Copy(),
@@ -368,37 +218,28 @@ func (d *DatabaseState) getSchema(schemaName string) (*SchemaState, *WalkThrough
return schema, nil
}
-func (t *TableState) getColumn(columnName string) (*ColumnState, *WalkThroughError) {
+func (t *TableState) getColumn(columnName string) (*ColumnState, error) {
column, exists := t.columnSet[columnName]
if !exists {
- return nil, &WalkThroughError{
- Type: ErrorTypeColumnNotExists,
- Content: fmt.Sprintf("The column %q does not exist in the table %q", columnName, t.name),
- }
+ return nil, NewSchemaViolationError(405, fmt.Sprintf("The column %q does not exist in the table %q", columnName, t.name))
}
return column, nil
}
-func (s *SchemaState) pgGetTable(tableName string) (*TableState, *WalkThroughError) {
+func (s *SchemaState) pgGetTable(tableName string) (*TableState, error) {
table, exists := s.tableSet[tableName]
if !exists {
- return nil, &WalkThroughError{
- Type: ErrorTypeTableNotExists,
- Content: fmt.Sprintf("The table %q does not exist in schema %q", tableName, s.name),
- }
+ return nil, NewSchemaViolationError(604, fmt.Sprintf("The table %q does not exist in schema %q", tableName, s.name))
}
return table, nil
}
-func (s *SchemaState) getIndex(indexName string) (*TableState, *IndexState, *WalkThroughError) {
+func (s *SchemaState) getIndex(indexName string) (*TableState, *IndexState, error) {
for _, table := range s.tableSet {
if index, exists := table.indexSet[indexName]; exists {
return table, index, nil
}
}
- return nil, nil, &WalkThroughError{
- Type: ErrorTypeIndexNotExists,
- Content: fmt.Sprintf("Index %q does not exists in schema %q", indexName, s.name),
- }
+ return nil, nil, NewSchemaViolationError(809, fmt.Sprintf("Index %q does not exists in schema %q", indexName, s.name))
}
diff --git a/backend/plugin/advisor/catalog/walk_through_for_mysql.go b/backend/plugin/advisor/catalog/walk_through_for_mysql.go
index 11b9b6447f..5c1c7eb407 100644
--- a/backend/plugin/advisor/catalog/walk_through_for_mysql.go
+++ b/backend/plugin/advisor/catalog/walk_through_for_mysql.go
@@ -41,7 +41,7 @@ type mysqlListener struct {
lineNumber int
text string
databaseState *DatabaseState
- err *WalkThroughError
+ err error
}
func (l *mysqlListener) EnterQuery(ctx *mysql.QueryContext) {
@@ -49,21 +49,9 @@ func (l *mysqlListener) EnterQuery(ctx *mysql.QueryContext) {
l.lineNumber = l.baseLine + ctx.GetStart().GetLine()
}
-func (d *DatabaseState) mysqlChangeState(in *mysqlparser.ParseResult) (err *WalkThroughError) {
- defer func() {
- if err == nil {
- return
- }
- if err.Line == 0 {
- err.Line = in.BaseLine
- }
- }()
-
+func (d *DatabaseState) mysqlChangeState(in *mysqlparser.ParseResult) error {
if d.deleted {
- return &WalkThroughError{
- Type: ErrorTypeDatabaseIsDeleted,
- Content: fmt.Sprintf("Database `%s` is deleted", d.name),
- }
+ return NewSchemaViolationError(703, fmt.Sprintf("Database `%s` is deleted", d.name))
}
listener := &mysqlListener{
@@ -71,13 +59,7 @@ func (d *DatabaseState) mysqlChangeState(in *mysqlparser.ParseResult) (err *Walk
databaseState: d,
}
antlr.ParseTreeWalkerDefault.Walk(listener, in.Tree)
- if listener.err != nil {
- if listener.err.Line == 0 {
- listener.err.Line = listener.lineNumber
- }
- return listener.err
- }
- return nil
+ return listener.err
}
// EnterCreateTable is called when production createTable is entered.
@@ -90,10 +72,7 @@ func (l *mysqlListener) EnterCreateTable(ctx *mysql.CreateTableContext) {
}
databaseName, tableName := mysqlparser.NormalizeMySQLTableName(ctx.TableName())
if databaseName != "" && !l.databaseState.isCurrentDatabase(databaseName) {
- l.err = &WalkThroughError{
- Type: ErrorTypeAccessOtherDatabase,
- Content: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, l.databaseState.name),
- }
+ l.err = NewSchemaViolationError(702, fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, l.databaseState.name))
return
}
@@ -105,18 +84,12 @@ func (l *mysqlListener) EnterCreateTable(ctx *mysql.CreateTableContext) {
if ctx.IfNotExists() != nil {
return
}
- l.err = &WalkThroughError{
- Type: ErrorTypeTableExists,
- Content: fmt.Sprintf("Table `%s` already exists", tableName),
- }
+ l.err = NewSchemaViolationError(607, fmt.Sprintf("Table `%s` already exists", tableName))
return
}
if ctx.DuplicateAsQueryExpression() != nil {
- l.err = &WalkThroughError{
- Type: ErrorTypeUseCreateTableAs,
- Content: fmt.Sprintf("Disallow the CREATE TABLE AS statement but \"%s\" uses", l.text),
- }
+ l.err = NewSchemaViolationError(205, fmt.Sprintf("Disallow the CREATE TABLE AS statement but \"%s\" uses", l.text))
return
}
@@ -150,23 +123,17 @@ func (l *mysqlListener) EnterCreateTable(ctx *mysql.CreateTableContext) {
}
if mysqlparser.IsAutoIncrement(tableElement.ColumnDefinition().FieldDefinition()) {
if hasAutoIncrement {
- l.err = &WalkThroughError{
- Type: ErrorTypeAutoIncrementExists,
- // The content comes from MySQL error content.
- Content: fmt.Sprintf("There can be only one auto column for table `%s`", table.name),
- }
+ l.err = NewSchemaViolationError(1, fmt.Sprintf("There can be only one auto column for table `%s`", table.name))
}
hasAutoIncrement = true
}
_, _, columnName := mysqlparser.NormalizeMySQLColumnName(tableElement.ColumnDefinition().ColumnName())
if err := table.mysqlCreateColumn(l.databaseState.ctx, columnName, tableElement.ColumnDefinition().FieldDefinition(), nil /* position */); err != nil {
- err.Line = l.baseLine + tableElement.GetStart().GetLine()
l.err = err
return
}
case tableElement.TableConstraintDef() != nil:
if err := table.mysqlCreateConstraint(l.databaseState.ctx, tableElement.TableConstraintDef()); err != nil {
- err.Line = tableElement.GetStart().GetLine()
l.err = err
return
}
@@ -188,10 +155,7 @@ func (l *mysqlListener) EnterDropTable(ctx *mysql.DropTableContext) {
for _, tableRef := range ctx.TableRefList().AllTableRef() {
databaseName, tableName := mysqlparser.NormalizeMySQLTableRef(tableRef)
if databaseName != "" && !l.databaseState.isCurrentDatabase(databaseName) {
- l.err = &WalkThroughError{
- Type: ErrorTypeAccessOtherDatabase,
- Content: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, tableName),
- }
+ l.err = NewSchemaViolationError(702, fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, tableName))
}
schema, exists := l.databaseState.schemaSet[""]
@@ -204,10 +168,7 @@ func (l *mysqlListener) EnterDropTable(ctx *mysql.DropTableContext) {
if ctx.IfExists() != nil || !l.databaseState.ctx.CheckIntegrity {
return
}
- l.err = &WalkThroughError{
- Type: ErrorTypeTableNotExists,
- Content: fmt.Sprintf("Table `%s` does not exist", tableName),
- }
+ l.err = NewSchemaViolationError(604, fmt.Sprintf("Table `%s` does not exist", tableName))
return
}
@@ -484,7 +445,7 @@ func (l *mysqlListener) EnterAlterDatabase(ctx *mysql.AlterDatabaseContext) {
if ctx.SchemaRef() != nil {
databaseName := mysqlparser.NormalizeMySQLSchemaRef(ctx.SchemaRef())
if !l.databaseState.isCurrentDatabase(databaseName) {
- l.err = NewAccessOtherDatabaseError(l.databaseState.name, databaseName)
+ l.err = NewSchemaViolationError(702, fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, l.databaseState.name))
return
}
}
@@ -518,7 +479,7 @@ func (l *mysqlListener) EnterDropDatabase(ctx *mysql.DropDatabaseContext) {
databaseName := mysqlparser.NormalizeMySQLSchemaRef(ctx.SchemaRef())
if !l.databaseState.isCurrentDatabase(databaseName) {
- l.err = NewAccessOtherDatabaseError(l.databaseState.name, databaseName)
+ l.err = NewSchemaViolationError(702, fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, l.databaseState.name))
return
}
@@ -534,7 +495,7 @@ func (l *mysqlListener) EnterCreateDatabase(ctx *mysql.CreateDatabaseContext) {
return
}
databaseName := mysqlparser.NormalizeMySQLSchemaName(ctx.SchemaName())
- l.err = NewAccessOtherDatabaseError(l.databaseState.name, databaseName)
+ l.err = NewSchemaViolationError(702, fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, l.databaseState.name))
}
// EnterRenameTableStatement is called when production renameTableStatement is entered.
@@ -558,13 +519,13 @@ func (l *mysqlListener) EnterRenameTableStatement(ctx *mysql.RenameTableStatemen
table, exists := schema.getTable(oldTableName)
if !exists {
if schema.ctx.CheckIntegrity {
- l.err = NewTableNotExistsError(oldTableName)
+ l.err = NewSchemaViolationError(604, fmt.Sprintf("Table `%s` does not exist", oldTableName))
return
}
table = schema.createIncompleteTable(oldTableName)
}
if _, exists := schema.getTable(newTableName); exists {
- l.err = NewTableExistsError(newTableName)
+ l.err = NewSchemaViolationError(607, fmt.Sprintf("Table `%s` already exists", newTableName))
return
}
delete(schema.tableSet, table.name)
@@ -573,12 +534,12 @@ func (l *mysqlListener) EnterRenameTableStatement(ctx *mysql.RenameTableStatemen
} else if l.databaseState.mysqlMoveToOtherDatabase(pair) {
_, exists := schema.getTable(oldTableName)
if !exists && schema.ctx.CheckIntegrity {
- l.err = NewTableNotExistsError(oldTableName)
+ l.err = NewSchemaViolationError(604, fmt.Sprintf("Table `%s` does not exist", oldTableName))
return
}
delete(schema.tableSet, oldTableName)
} else {
- l.err = NewAccessOtherDatabaseError(l.databaseState.name, l.databaseState.mysqlTargetDatabase(pair))
+ l.err = NewSchemaViolationError(702, fmt.Sprintf("Database `%s` is not the current database `%s`", l.databaseState.mysqlTargetDatabase(pair), l.databaseState.name))
return
}
}
@@ -654,11 +615,11 @@ func (d *DatabaseState) mysqlTheCurrentDatabase(renamePair mysql.IRenamePairCont
return true
}
-func (t *TableState) mysqlChangeIndexVisibility(ctx *FinderContext, indexName string, visibility mysql.IVisibilityContext) *WalkThroughError {
+func (t *TableState) mysqlChangeIndexVisibility(ctx *FinderContext, indexName string, visibility mysql.IVisibilityContext) error {
index, exists := t.indexSet[strings.ToLower(indexName)]
if !exists {
if ctx.CheckIntegrity {
- return NewIndexNotExistsError(t.name, indexName)
+ return NewSchemaViolationError(809, fmt.Sprintf("Index `%s` does not exist in table `%s`", indexName, t.name))
}
index = t.createIncompleteIndex(indexName)
}
@@ -673,7 +634,7 @@ func (t *TableState) mysqlChangeIndexVisibility(ctx *FinderContext, indexName st
return nil
}
-func (t *TableState) mysqlAlterColumn(ctx *FinderContext, itemDef mysql.IAlterListItemContext) *WalkThroughError {
+func (t *TableState) mysqlAlterColumn(ctx *FinderContext, itemDef mysql.IAlterListItemContext) error {
if itemDef.ColumnInternalRef() == nil {
// should not reach here.
return nil
@@ -682,7 +643,7 @@ func (t *TableState) mysqlAlterColumn(ctx *FinderContext, itemDef mysql.IAlterLi
colState, exists := t.columnSet[strings.ToLower(columnName)]
if !exists {
if ctx.CheckIntegrity {
- return NewColumnNotExistsError(t.name, columnName)
+ return NewSchemaViolationError(405, fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, t.name))
}
colState = t.createIncompleteColumn(columnName)
}
@@ -699,11 +660,7 @@ func (t *TableState) mysqlAlterColumn(ctx *FinderContext, itemDef mysql.IAlterLi
"text", "tinytext", "mediumtext", "longtext",
"json",
"geometry":
- return &WalkThroughError{
- Type: ErrorTypeInvalidColumnTypeForDefaultValue,
- // Content comes from MySQL Error content.
- Content: fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName),
- }
+ return NewSchemaViolationError(423, fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName))
default:
// Other column types allow default values
}
@@ -722,11 +679,7 @@ func (t *TableState) mysqlAlterColumn(ctx *FinderContext, itemDef mysql.IAlterLi
colState.defaultValue = &defaultValue
} else {
if colState.nullable != nil && !*colState.nullable {
- return &WalkThroughError{
- Type: ErrorTypeSetNullDefaultForNotNullColumn,
- // Content comes from MySQL Error content.
- Content: fmt.Sprintf("Invalid default value for column `%s`", columnName),
- }
+ return errors.Errorf("Invalid default value for column `%s`", columnName)
}
colState.defaultValue = nil
@@ -743,7 +696,7 @@ func (t *TableState) mysqlAlterColumn(ctx *FinderContext, itemDef mysql.IAlterLi
return nil
}
-func (t *TableState) mysqlChangeColumn(ctx *FinderContext, oldColumnName string, newColumnName string, fieldDef mysql.IFieldDefinitionContext, position *mysqlColumnPosition) *WalkThroughError {
+func (t *TableState) mysqlChangeColumn(ctx *FinderContext, oldColumnName string, newColumnName string, fieldDef mysql.IFieldDefinitionContext, position *mysqlColumnPosition) error {
if ctx.CheckIntegrity {
return t.mysqlCompleteTableChangeColumn(ctx, oldColumnName, newColumnName, fieldDef, position)
}
@@ -752,7 +705,7 @@ func (t *TableState) mysqlChangeColumn(ctx *FinderContext, oldColumnName string,
// mysqlIncompleteTableChangeColumn changes column definition.
// It does not maintain the position of the column.
-func (t *TableState) mysqlIncompleteTableChangeColumn(ctx *FinderContext, oldColumnName string, newColumnName string, fieldDef mysql.IFieldDefinitionContext, position *mysqlColumnPosition) *WalkThroughError {
+func (t *TableState) mysqlIncompleteTableChangeColumn(ctx *FinderContext, oldColumnName string, newColumnName string, fieldDef mysql.IFieldDefinitionContext, position *mysqlColumnPosition) error {
delete(t.columnSet, strings.ToLower(oldColumnName))
// rename column from indexSet
@@ -767,10 +720,10 @@ func (t *TableState) mysqlIncompleteTableChangeColumn(ctx *FinderContext, oldCol
// 1. drop column from tableState.columnSet, but do not drop column from indexSet.
// 2. rename column from indexSet.
// 3. create a new column in columnSet.
-func (t *TableState) mysqlCompleteTableChangeColumn(ctx *FinderContext, oldColumnName string, newColumnName string, fieldDef mysql.IFieldDefinitionContext, position *mysqlColumnPosition) *WalkThroughError {
+func (t *TableState) mysqlCompleteTableChangeColumn(ctx *FinderContext, oldColumnName string, newColumnName string, fieldDef mysql.IFieldDefinitionContext, position *mysqlColumnPosition) error {
column, exists := t.columnSet[strings.ToLower(oldColumnName)]
if !exists {
- return NewColumnNotExistsError(t.name, oldColumnName)
+ return NewSchemaViolationError(405, fmt.Sprintf("Column `%s` does not exist in table `%s`", oldColumnName, t.name))
}
pos := *column.position
@@ -843,7 +796,7 @@ func positionFromPlaceContext(place mysql.IPlaceContext) *mysqlColumnPosition {
return columnPosition
}
-func (d *DatabaseState) mysqlCopyTable(databaseName, tableName, referTable string) *WalkThroughError {
+func (d *DatabaseState) mysqlCopyTable(databaseName, tableName, referTable string) error {
targetTable, err := d.mysqlFindTableState(databaseName, referTable)
if err != nil {
return err
@@ -856,9 +809,9 @@ func (d *DatabaseState) mysqlCopyTable(databaseName, tableName, referTable strin
return nil
}
-func (d *DatabaseState) mysqlFindTableState(databaseName, tableName string) (*TableState, *WalkThroughError) {
+func (d *DatabaseState) mysqlFindTableState(databaseName, tableName string) (*TableState, error) {
if databaseName != "" && !d.isCurrentDatabase(databaseName) {
- return nil, NewAccessOtherDatabaseError(d.name, databaseName)
+ return nil, NewSchemaViolationError(702, fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, d.name))
}
schema, exists := d.schemaSet[""]
@@ -869,7 +822,7 @@ func (d *DatabaseState) mysqlFindTableState(databaseName, tableName string) (*Ta
table, exists := schema.getTable(tableName)
if !exists {
if schema.ctx.CheckIntegrity {
- return nil, NewTableNotExistsError(tableName)
+ return nil, NewSchemaViolationError(604, fmt.Sprintf("Table `%s` does not exist", tableName))
}
table = schema.createIncompleteTable(tableName)
}
@@ -877,7 +830,7 @@ func (d *DatabaseState) mysqlFindTableState(databaseName, tableName string) (*Ta
return table, nil
}
-func (t *TableState) mysqlCreateConstraint(ctx *FinderContext, constraintDef mysql.ITableConstraintDefContext) *WalkThroughError {
+func (t *TableState) mysqlCreateConstraint(ctx *FinderContext, constraintDef mysql.ITableConstraintDefContext) error {
if constraintDef.GetType_() != nil {
switch constraintDef.GetType_().GetTokenType() {
// PRIMARY KEY.
@@ -962,7 +915,7 @@ func (t *TableState) mysqlCreateConstraint(ctx *FinderContext, constraintDef mys
}
// mysqlValidateKeyListVariants validates the key list variants.
-func (t *TableState) mysqlValidateKeyListVariants(ctx *FinderContext, keyList mysql.IKeyListVariantsContext, primary bool, isSpatial bool) *WalkThroughError {
+func (t *TableState) mysqlValidateKeyListVariants(ctx *FinderContext, keyList mysql.IKeyListVariantsContext, primary bool, isSpatial bool) error {
if keyList.KeyList() != nil {
columns := mysqlparser.NormalizeKeyList(keyList.KeyList())
if err := t.mysqlValidateColumnList(ctx, columns, primary, isSpatial); err != nil {
@@ -978,23 +931,19 @@ func (t *TableState) mysqlValidateKeyListVariants(ctx *FinderContext, keyList my
return nil
}
-func (t *TableState) mysqlValidateColumnList(ctx *FinderContext, columnList []string, primary bool, isSpatial bool) *WalkThroughError {
+func (t *TableState) mysqlValidateColumnList(ctx *FinderContext, columnList []string, primary bool, isSpatial bool) error {
for _, columnName := range columnList {
column, exists := t.columnSet[strings.ToLower(columnName)]
if !exists {
if ctx.CheckIntegrity {
- return NewColumnNotExistsError(t.name, columnName)
+ return NewSchemaViolationError(405, fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, t.name))
}
} else {
if primary {
column.nullable = newFalsePointer()
}
if isSpatial && column.nullable != nil && *column.nullable {
- return &WalkThroughError{
- Type: ErrorTypeSpatialIndexKeyNullable,
- // The error content comes from MySQL.
- Content: fmt.Sprintf("All parts of a SPATIAL index must be NOT NULL, but `%s` is nullable", column.name),
- }
+ return errors.Errorf("All parts of a SPATIAL index must be NOT NULL, but `%s` is nullable", column.name)
}
}
}
@@ -1003,7 +952,7 @@ func (t *TableState) mysqlValidateColumnList(ctx *FinderContext, columnList []st
// mysqlValidateExpressionList validates the expression list.
// TODO: update expression validation.
-func (t *TableState) mysqlValidateExpressionList(_ *FinderContext, expressionList []string, primary bool, isSpatial bool) *WalkThroughError {
+func (t *TableState) mysqlValidateExpressionList(_ *FinderContext, expressionList []string, primary bool, isSpatial bool) error {
for _, expression := range expressionList {
column, exists := t.columnSet[strings.ToLower(expression)]
// If expression is not a column, we do not need to validate it.
@@ -1015,11 +964,7 @@ func (t *TableState) mysqlValidateExpressionList(_ *FinderContext, expressionLis
column.nullable = newFalsePointer()
}
if isSpatial && column.nullable != nil && *column.nullable {
- return &WalkThroughError{
- Type: ErrorTypeSpatialIndexKeyNullable,
- // The error content comes from MySQL.
- Content: fmt.Sprintf("All parts of a SPATIAL index must be NOT NULL, but `%s` is nullable", column.name),
- }
+ return errors.Errorf("All parts of a SPATIAL index must be NOT NULL, but `%s` is nullable", column.name)
}
}
return nil
@@ -1063,18 +1008,15 @@ func mysqlGetIndexType(tableConstraint mysql.ITableConstraintDefContext) string
return "BTREE"
}
-func (t *TableState) mysqlCreateColumn(ctx *FinderContext, columnName string, fieldDef mysql.IFieldDefinitionContext, position *mysqlColumnPosition) *WalkThroughError {
+func (t *TableState) mysqlCreateColumn(ctx *FinderContext, columnName string, fieldDef mysql.IFieldDefinitionContext, position *mysqlColumnPosition) error {
if _, exists := t.columnSet[strings.ToLower(columnName)]; exists {
- return &WalkThroughError{
- Type: ErrorTypeColumnExists,
- Content: fmt.Sprintf("Column `%s` already exists in table `%s`", columnName, t.name),
- }
+ return NewSchemaViolationError(412, fmt.Sprintf("Column `%s` already exists in table `%s`", columnName, t.name))
}
// todo: handle position.
pos := len(t.columnSet) + 1
if position != nil && ctx.CheckIntegrity {
- var err *WalkThroughError
+ var err error
pos, err = t.mysqlReorderColumn(position)
if err != nil {
return err
@@ -1146,10 +1088,7 @@ func (t *TableState) mysqlCreateColumn(ctx *FinderContext, columnName string, fi
continue
}
if !mysqlparser.IsTimeType(fieldDef.DataType()) {
- return &WalkThroughError{
- Type: ErrorTypeOnUpdateColumnNotDatetimeOrTimestamp,
- Content: fmt.Sprintf("Column `%s` use ON UPDATE but is not DATETIME or TIMESTAMP", col.name),
- }
+ return errors.Errorf("Column `%s` use ON UPDATE but is not DATETIME or TIMESTAMP", col.name)
}
// primary key.
case mysql.MySQLParserKEY_SYMBOL:
@@ -1181,11 +1120,7 @@ func (t *TableState) mysqlCreateColumn(ctx *FinderContext, columnName string, fi
}
if col.nullable != nil && !*col.nullable && setNullDefault {
- return &WalkThroughError{
- Type: ErrorTypeSetNullDefaultForNotNullColumn,
- // Content comes from MySQL Error content.
- Content: fmt.Sprintf("Invalid default value for column `%s`", col.name),
- }
+ return errors.Errorf("Invalid default value for column `%s`", col.name)
}
t.columnSet[strings.ToLower(col.name)] = col
@@ -1193,7 +1128,7 @@ func (t *TableState) mysqlCreateColumn(ctx *FinderContext, columnName string, fi
}
// reorderColumn reorders the columns for new column and returns the new column position.
-func (t *TableState) mysqlReorderColumn(position *mysqlColumnPosition) (int, *WalkThroughError) {
+func (t *TableState) mysqlReorderColumn(position *mysqlColumnPosition) (int, error) {
switch position.tp {
case ColumnPositionNone:
return len(t.columnSet) + 1, nil
@@ -1206,7 +1141,7 @@ func (t *TableState) mysqlReorderColumn(position *mysqlColumnPosition) (int, *Wa
columnName := strings.ToLower(position.relativeColumn)
column, exist := t.columnSet[columnName]
if !exist {
- return 0, NewColumnNotExistsError(t.name, columnName)
+ return 0, NewSchemaViolationError(405, fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, t.name))
}
for _, col := range t.columnSet {
if *col.position > *column.position {
@@ -1215,24 +1150,18 @@ func (t *TableState) mysqlReorderColumn(position *mysqlColumnPosition) (int, *Wa
}
return *column.position + 1, nil
default:
- return 0, &WalkThroughError{
- Type: ErrorTypeUnsupported,
- Content: fmt.Sprintf("Unsupported column position type: %d", position.tp),
- }
+ return 0, errors.Errorf("Unsupported column position type: %d", position.tp)
}
}
-func (t *TableState) mysqlCreateIndex(name string, keyList []string, unique bool, tp string, tableConstraint mysql.ITableConstraintDefContext, createIndexDef mysql.ICreateIndexContext) *WalkThroughError {
+func (t *TableState) mysqlCreateIndex(name string, keyList []string, unique bool, tp string, tableConstraint mysql.ITableConstraintDefContext, createIndexDef mysql.ICreateIndexContext) error {
if len(keyList) == 0 {
- return &WalkThroughError{
- Type: ErrorTypeIndexEmptyKeys,
- Content: fmt.Sprintf("Index `%s` in table `%s` has empty key", name, t.name),
- }
+ return errors.Errorf("Index `%s` in table `%s` has empty key", name, t.name)
}
// construct a index name if name is empty.
if name != "" {
if _, exists := t.indexSet[strings.ToLower(name)]; exists {
- return NewIndexExistsError(t.name, name)
+ return NewSchemaViolationError(805, fmt.Sprintf("Index `%s` already exists in table `%s`", name, t.name))
}
} else {
suffix := 1
@@ -1331,12 +1260,9 @@ func (t *TableState) mysqlCreateIndex(name string, keyList []string, unique bool
return nil
}
-func (t *TableState) mysqlCreatePrimaryKey(keys []string, tp string) *WalkThroughError {
+func (t *TableState) mysqlCreatePrimaryKey(keys []string, tp string) error {
if _, exists := t.indexSet[strings.ToLower(PrimaryKeyName)]; exists {
- return &WalkThroughError{
- Type: ErrorTypePrimaryKeyExists,
- Content: fmt.Sprintf("Primary key exists in table `%s`", t.name),
- }
+ return errors.Errorf("Primary key exists in table `%s`", t.name)
}
pk := &IndexState{
@@ -1352,7 +1278,7 @@ func (t *TableState) mysqlCreatePrimaryKey(keys []string, tp string) *WalkThroug
return nil
}
-func mysqlCheckDefault(columnName string, fieldDefinition mysql.IFieldDefinitionContext) *WalkThroughError {
+func mysqlCheckDefault(columnName string, fieldDefinition mysql.IFieldDefinitionContext) error {
if fieldDefinition.DataType() == nil || fieldDefinition.DataType().GetType_() == nil {
return nil
}
@@ -1377,11 +1303,7 @@ func mysqlCheckDefault(columnName string, fieldDefinition mysql.IFieldDefinition
mysql.MySQLParserMULTILINESTRING_SYMBOL,
mysql.MySQLParserPOLYGON_SYMBOL,
mysql.MySQLParserMULTIPOLYGON_SYMBOL:
- return &WalkThroughError{
- Type: ErrorTypeInvalidColumnTypeForDefaultValue,
- // Content comes from MySQL Error content.
- Content: fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName),
- }
+ return NewSchemaViolationError(423, fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName))
default:
// Other data types are allowed to have default values
}
@@ -1389,7 +1311,7 @@ func mysqlCheckDefault(columnName string, fieldDefinition mysql.IFieldDefinition
return checkDefaultConvert(columnName, fieldDefinition)
}
-func checkDefaultConvert(columnName string, fieldDefinition mysql.IFieldDefinitionContext) *WalkThroughError {
+func checkDefaultConvert(columnName string, fieldDefinition mysql.IFieldDefinitionContext) error {
if fieldDefinition == nil {
return nil
}
diff --git a/backend/plugin/advisor/catalog/walk_through_for_pg.go b/backend/plugin/advisor/catalog/walk_through_for_pg.go
index 4b81c485e4..8a11bde202 100644
--- a/backend/plugin/advisor/catalog/walk_through_for_pg.go
+++ b/backend/plugin/advisor/catalog/walk_through_for_pg.go
@@ -17,10 +17,7 @@ func (d *DatabaseState) pgWalkThrough(ast any) error {
// ANTLR-based walkthrough
parseResult, ok := ast.(*pgparser.ParseResult)
if !ok {
- return &WalkThroughError{
- Type: ErrorTypeUnsupported,
- Content: fmt.Sprintf("PostgreSQL walk-through expects *pgparser.ParseResult, got %T", ast),
- }
+ return errors.Errorf("PostgreSQL walk-through expects *pgparser.ParseResult, got %T", ast)
}
root, ok := parseResult.Tree.(parser.IRootContext)
@@ -50,28 +47,22 @@ type pgCatalogListener struct {
*parser.BasePostgreSQLParserListener
databaseState *DatabaseState
- err *WalkThroughError
+ err error
currentLine int
}
// Helper method to set error with line number
-func (l *pgCatalogListener) setError(err *WalkThroughError) {
+func (l *pgCatalogListener) setError(err error) {
if l.err != nil {
return // Keep first error
}
- if err != nil && err.Line == 0 {
- err.Line = l.currentLine
- }
l.err = err
}
// Helper method to check if database is deleted
func (l *pgCatalogListener) checkDatabaseNotDeleted() bool {
if l.databaseState.deleted {
- l.setError(&WalkThroughError{
- Type: ErrorTypeDatabaseIsDeleted,
- Content: fmt.Sprintf(`Database %q is deleted`, l.databaseState.name),
- })
+ l.setError(errors.Errorf(`Database %q is deleted`, l.databaseState.name))
return false
}
return true
@@ -109,10 +100,7 @@ func (l *pgCatalogListener) EnterCreatestmt(ctx *parser.CreatestmtContext) {
// Check database name if specified
databaseName := extractDatabaseName(qualifiedNames[0])
if databaseName != "" && l.databaseState.name != databaseName {
- l.setError(&WalkThroughError{
- Type: ErrorTypeAccessOtherDatabase,
- Content: fmt.Sprintf("Database %q is not the current database %q", databaseName, l.databaseState.name),
- })
+ l.setError(errors.Errorf("Database %q is not the current database %q", databaseName, l.databaseState.name))
return
}
@@ -130,10 +118,7 @@ func (l *pgCatalogListener) EnterCreatestmt(ctx *parser.CreatestmtContext) {
if ifNotExists {
return
}
- l.setError(&WalkThroughError{
- Type: ErrorTypeTableExists,
- Content: fmt.Sprintf(`The table %q already exists in the schema %q`, tableName, schema.name),
- })
+ l.setError(errors.Errorf(`The table %q already exists in the schema %q`, tableName, schema.name))
return
}
@@ -168,7 +153,7 @@ func (l *pgCatalogListener) EnterCreatestmt(ctx *parser.CreatestmtContext) {
}
// createColumn creates a column in the table.
-func createColumn(schema *SchemaState, table *TableState, columnDef parser.IColumnDefContext) *WalkThroughError {
+func createColumn(schema *SchemaState, table *TableState, columnDef parser.IColumnDefContext) error {
if columnDef == nil {
return nil
}
@@ -184,10 +169,7 @@ func createColumn(schema *SchemaState, table *TableState, columnDef parser.IColu
// Check if column already exists
if _, exists := table.columnSet[columnName]; exists {
- return &WalkThroughError{
- Type: ErrorTypeColumnExists,
- Content: fmt.Sprintf("The column %q already exists in table %q", columnName, table.name),
- }
+ return errors.Errorf("The column %q already exists in table %q", columnName, table.name)
}
// Get column type
@@ -287,7 +269,7 @@ func createColumn(schema *SchemaState, table *TableState, columnDef parser.IColu
}
// createTableConstraint creates a table-level constraint.
-func createTableConstraint(schema *SchemaState, table *TableState, constraint parser.ITableconstraintContext) *WalkThroughError {
+func createTableConstraint(schema *SchemaState, table *TableState, constraint parser.ITableconstraintContext) error {
if constraint == nil || constraint.Constraintelem() == nil {
return nil
}
@@ -318,7 +300,7 @@ func createTableConstraint(schema *SchemaState, table *TableState, constraint pa
if column, exists := table.columnSet[colName]; exists {
column.nullable = newFalsePointer()
} else {
- return NewColumnNotExistsError(table.name, colName)
+ return NewSchemaViolationError(405, fmt.Sprintf("Column `%s` does not exist in table `%s`", colName, table.name))
}
}
@@ -330,7 +312,7 @@ func createTableConstraint(schema *SchemaState, table *TableState, constraint pa
// Check if identifier already exists
if _, exists := schema.identifierMap[pkName]; exists {
- return NewRelationExistsError(pkName, schema.name)
+ return NewSchemaViolationError(1, fmt.Sprintf("Relation %q already exists in schema %q", pkName, schema.name))
}
// Create primary key index
@@ -367,13 +349,13 @@ func createTableConstraint(schema *SchemaState, table *TableState, constraint pa
// Check if identifier already exists
if _, exists := schema.identifierMap[indexName]; exists {
- return NewRelationExistsError(indexName, schema.name)
+ return NewSchemaViolationError(1, fmt.Sprintf("Relation %q already exists in schema %q", indexName, schema.name))
}
// Validate columns exist
for _, colName := range columnList {
if _, exists := table.columnSet[colName]; !exists {
- return NewColumnNotExistsError(table.name, colName)
+ return NewSchemaViolationError(405, fmt.Sprintf("Column `%s` does not exist in table `%s`", colName, table.name))
}
}
@@ -428,7 +410,7 @@ func (l *pgCatalogListener) EnterIndexstmt(ctx *parser.IndexstmtContext) {
table, exists := schema.tableSet[tableName]
if !exists {
- l.setError(NewTableNotExistsError(tableName))
+ l.setError(NewSchemaViolationError(604, fmt.Sprintf("Table `%s` does not exist", tableName)))
return
}
@@ -457,10 +439,7 @@ func (l *pgCatalogListener) EnterIndexstmt(ctx *parser.IndexstmtContext) {
}
if len(columnList) == 0 {
- l.setError(&WalkThroughError{
- Type: ErrorTypeIndexEmptyKeys,
- Content: fmt.Sprintf("Index %q in table %q has empty key", indexName, tableName),
- })
+ l.setError(errors.Errorf("Index %q in table %q has empty key", indexName, tableName))
return
}
@@ -480,7 +459,7 @@ func (l *pgCatalogListener) EnterIndexstmt(ctx *parser.IndexstmtContext) {
if wasAutoGenerated {
indexName = generateUniqueIndexName(schema, tableName, columnList, isUnique)
} else {
- l.setError(NewRelationExistsError(indexName, schema.name))
+ l.setError(NewSchemaViolationError(1, fmt.Sprintf("Relation %q already exists in schema %q", indexName, schema.name)))
return
}
}
@@ -489,7 +468,7 @@ func (l *pgCatalogListener) EnterIndexstmt(ctx *parser.IndexstmtContext) {
for _, colName := range columnList {
if colName != "expr" {
if _, exists := table.columnSet[colName]; !exists {
- l.setError(NewColumnNotExistsError(tableName, colName))
+ l.setError(NewSchemaViolationError(405, fmt.Sprintf("Column `%s` does not exist in table `%s`", colName, tableName)))
return
}
}
@@ -563,10 +542,7 @@ func (l *pgCatalogListener) EnterAltertablestmt(ctx *parser.AltertablestmtContex
// Check database access
if databaseName != "" && l.databaseState.name != databaseName {
- l.setError(&WalkThroughError{
- Type: ErrorTypeAccessOtherDatabase,
- Content: fmt.Sprintf("Database %q is not the current database %q", databaseName, l.databaseState.name),
- })
+ l.setError(errors.Errorf("Database %q is not the current database %q", databaseName, l.databaseState.name))
return
}
@@ -682,7 +658,7 @@ func (l *pgCatalogListener) alterTableDropColumn(schema *SchemaState, table *Tab
if ifExists {
return
}
- l.setError(NewColumnNotExistsError(table.name, columnName))
+ l.setError(NewSchemaViolationError(405, fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.name)))
return
}
@@ -693,11 +669,7 @@ func (l *pgCatalogListener) alterTableDropColumn(schema *SchemaState, table *Tab
return
}
if len(viewList) > 0 {
- l.setError(&WalkThroughError{
- Type: ErrorTypeColumnIsReferencedByView,
- Content: fmt.Sprintf("Cannot drop column %q in table %q.%q, it's referenced by view: %s", column.name, schema.name, table.name, strings.Join(viewList, ", ")),
- Payload: viewList,
- })
+ l.setError(errors.Errorf("Cannot drop column %q in table %q.%q, it's referenced by view: %s", column.name, schema.name, table.name, strings.Join(viewList, ", ")))
return
}
@@ -740,11 +712,7 @@ func (l *pgCatalogListener) alterTableAlterColumnType(schema *SchemaState, table
return
}
if len(viewList) > 0 {
- l.setError(&WalkThroughError{
- Type: ErrorTypeColumnIsReferencedByView,
- Content: fmt.Sprintf("Cannot alter type of column %q in table %q.%q, it's referenced by view: %s", column.name, schema.name, table.name, strings.Join(viewList, ", ")),
- Payload: viewList,
- })
+ l.setError(errors.Errorf("Cannot alter type of column %q in table %q.%q, it's referenced by view: %s", column.name, schema.name, table.name, strings.Join(viewList, ", ")))
return
}
@@ -765,10 +733,7 @@ func (l *pgCatalogListener) alterTableAddColumn(schema *SchemaState, table *Tabl
if ifNotExists {
return
}
- l.setError(&WalkThroughError{
- Type: ErrorTypeColumnExists,
- Content: fmt.Sprintf("The column %q already exists in table %q", columnName, table.name),
- })
+ l.setError(errors.Errorf("The column %q already exists in table %q", columnName, table.name))
return
}
@@ -850,7 +815,7 @@ func (l *pgCatalogListener) alterTableAddColumn(schema *SchemaState, table *Tabl
}
// Check for collision
if _, exists := schema.identifierMap[constraintName]; exists {
- l.setError(NewRelationExistsError(constraintName, schema.name))
+ l.setError(NewSchemaViolationError(1, fmt.Sprintf("Relation %q already exists in schema %q", constraintName, schema.name)))
return
}
columnState.nullable = newFalsePointer()
@@ -893,10 +858,7 @@ func (l *pgCatalogListener) alterTableDropConstraint(schema *SchemaState, table
}
if !ifExists {
- l.setError(&WalkThroughError{
- Type: ErrorTypeConstraintNotExists,
- Content: fmt.Sprintf("Constraint %q for table %q does not exist", constraintName, table.name),
- })
+ l.setError(errors.Errorf("Constraint %q for table %q does not exist", constraintName, table.name))
}
}
@@ -934,10 +896,10 @@ func (l *pgCatalogListener) alterTableSetNotNull(table *TableState, columnName s
}
// renameTable handles RENAME TO for tables.
-func (*pgCatalogListener) renameTable(schema *SchemaState, table *TableState, newName string) *WalkThroughError {
+func (*pgCatalogListener) renameTable(schema *SchemaState, table *TableState, newName string) error {
// Check if new name already exists
if _, exists := schema.identifierMap[newName]; exists {
- return NewRelationExistsError(newName, schema.name)
+ return NewSchemaViolationError(1, fmt.Sprintf("Relation %q already exists in schema %q", newName, schema.name))
}
// Remove old name from maps
@@ -955,7 +917,7 @@ func (*pgCatalogListener) renameTable(schema *SchemaState, table *TableState, ne
}
// renameColumn handles RENAME COLUMN.
-func (*pgCatalogListener) renameColumn(table *TableState, oldName string, newName string) *WalkThroughError {
+func (*pgCatalogListener) renameColumn(table *TableState, oldName string, newName string) error {
column, err := table.getColumn(oldName)
if err != nil {
return err
@@ -967,10 +929,7 @@ func (*pgCatalogListener) renameColumn(table *TableState, oldName string, newNam
// Check if new name already exists
if _, exists := table.columnSet[newName]; exists {
- return &WalkThroughError{
- Type: ErrorTypeColumnExists,
- Content: fmt.Sprintf("The column %q already exists in table %q", newName, table.name),
- }
+ return errors.Errorf("The column %q already exists in table %q", newName, table.name)
}
// Rename column in all indexes that reference it
@@ -991,7 +950,7 @@ func (*pgCatalogListener) renameColumn(table *TableState, oldName string, newNam
}
// renameConstraint handles RENAME CONSTRAINT.
-func (*pgCatalogListener) renameConstraint(schema *SchemaState, table *TableState, oldName string, newName string) *WalkThroughError {
+func (*pgCatalogListener) renameConstraint(schema *SchemaState, table *TableState, oldName string, newName string) error {
index, exists := table.indexSet[oldName]
if !exists {
// We haven't dealt with foreign and check constraints, so skip if not exists
@@ -1000,7 +959,7 @@ func (*pgCatalogListener) renameConstraint(schema *SchemaState, table *TableStat
// Check if new name already exists
if _, exists := schema.identifierMap[newName]; exists {
- return NewRelationExistsError(newName, schema.name)
+ return NewSchemaViolationError(1, fmt.Sprintf("Relation %q already exists in schema %q", newName, schema.name))
}
// Remove old name from maps
@@ -1084,7 +1043,7 @@ func (l *pgCatalogListener) EnterDropstmt(ctx *parser.DropstmtContext) {
}
}
-func (l *pgCatalogListener) dropTable(anyName parser.IAny_nameContext, ifExists bool) *WalkThroughError {
+func (l *pgCatalogListener) dropTable(anyName parser.IAny_nameContext, ifExists bool) error {
parts := pgparser.NormalizePostgreSQLAnyName(anyName)
if len(parts) == 0 {
return nil
@@ -1121,11 +1080,7 @@ func (l *pgCatalogListener) dropTable(anyName parser.IAny_nameContext, ifExists
return err
}
if len(viewList) > 0 {
- return &WalkThroughError{
- Type: ErrorTypeTableIsReferencedByView,
- Content: fmt.Sprintf("Cannot drop table %q.%q, it's referenced by view: %s", schema.name, table.name, strings.Join(viewList, ", ")),
- Payload: viewList,
- }
+ return errors.Errorf("Cannot drop table %q.%q, it's referenced by view: %s", schema.name, table.name, strings.Join(viewList, ", "))
}
// Delete all indexes associated with the table
@@ -1138,7 +1093,7 @@ func (l *pgCatalogListener) dropTable(anyName parser.IAny_nameContext, ifExists
return nil
}
-func (l *pgCatalogListener) dropView(anyName parser.IAny_nameContext, ifExists bool) *WalkThroughError {
+func (l *pgCatalogListener) dropView(anyName parser.IAny_nameContext, ifExists bool) error {
parts := pgparser.NormalizePostgreSQLAnyName(anyName)
if len(parts) == 0 {
return nil
@@ -1166,7 +1121,7 @@ func (l *pgCatalogListener) dropView(anyName parser.IAny_nameContext, ifExists b
return nil
}
-func (l *pgCatalogListener) dropIndex(anyName parser.IAny_nameContext, ifExists bool) *WalkThroughError {
+func (l *pgCatalogListener) dropIndex(anyName parser.IAny_nameContext, ifExists bool) error {
parts := pgparser.NormalizePostgreSQLAnyName(anyName)
if len(parts) == 0 {
return nil
@@ -1202,7 +1157,7 @@ func (l *pgCatalogListener) dropIndex(anyName parser.IAny_nameContext, ifExists
return nil
}
-func (l *pgCatalogListener) dropSchema(schemaNameCtx parser.INameContext, ifExists bool) *WalkThroughError {
+func (l *pgCatalogListener) dropSchema(schemaNameCtx parser.INameContext, ifExists bool) error {
schemaName := pgparser.NormalizePostgreSQLName(schemaNameCtx)
schema, exists := l.databaseState.schemaSet[schemaName]
@@ -1210,10 +1165,7 @@ func (l *pgCatalogListener) dropSchema(schemaNameCtx parser.INameContext, ifExis
if ifExists {
return nil
}
- return &WalkThroughError{
- Type: ErrorTypeSchemaNotExists,
- Content: fmt.Sprintf("Schema %q does not exist", schemaName),
- }
+ return errors.Errorf("Schema %q does not exist", schemaName)
}
// Delete all identifiers in this schema
@@ -1414,10 +1366,7 @@ func (l *pgCatalogListener) EnterViewstmt(ctx *parser.ViewstmtContext) {
// Check if accessing other database
if databaseName != "" && l.databaseState.name != databaseName {
- l.setError(&WalkThroughError{
- Type: ErrorTypeAccessOtherDatabase,
- Content: fmt.Sprintf("Database %q is not the current database %q", databaseName, l.databaseState.name),
- })
+ l.setError(errors.Errorf("Database %q is not the current database %q", databaseName, l.databaseState.name))
return
}
diff --git a/backend/plugin/advisor/catalog/walk_through_for_tidb.go b/backend/plugin/advisor/catalog/walk_through_for_tidb.go
index 29da7d52bd..698c21c322 100644
--- a/backend/plugin/advisor/catalog/walk_through_for_tidb.go
+++ b/backend/plugin/advisor/catalog/walk_through_for_tidb.go
@@ -33,20 +33,9 @@ func (d *DatabaseState) tidbWalkThrough(ast any) error {
return nil
}
-func (d *DatabaseState) changeState(in tidbast.StmtNode) (err *WalkThroughError) {
- defer func() {
- if err == nil {
- return
- }
- if err.Line == 0 {
- err.Line = in.OriginTextPosition()
- }
- }()
+func (d *DatabaseState) changeState(in tidbast.StmtNode) error {
if d.deleted {
- return &WalkThroughError{
- Type: ErrorTypeDatabaseIsDeleted,
- Content: fmt.Sprintf("Database `%s` is deleted", d.name),
- }
+ return NewSchemaViolationError(703, fmt.Sprintf("Database `%s` is deleted", d.name))
}
switch node := in.(type) {
case *tidbast.CreateTableStmt:
@@ -64,7 +53,7 @@ func (d *DatabaseState) changeState(in tidbast.StmtNode) (err *WalkThroughError)
case *tidbast.DropDatabaseStmt:
return d.dropDatabase(node)
case *tidbast.CreateDatabaseStmt:
- return NewAccessOtherDatabaseError(d.name, node.Name.O)
+ return NewSchemaViolationError(702, fmt.Sprintf("Database `%s` is not the current database `%s`", node.Name.O, d.name))
case *tidbast.RenameTableStmt:
return d.renameTable(node)
default:
@@ -72,7 +61,7 @@ func (d *DatabaseState) changeState(in tidbast.StmtNode) (err *WalkThroughError)
}
}
-func (d *DatabaseState) renameTable(node *tidbast.RenameTableStmt) *WalkThroughError {
+func (d *DatabaseState) renameTable(node *tidbast.RenameTableStmt) error {
for _, tableToTable := range node.TableToTables {
schema, exists := d.schemaSet[""]
if !exists {
@@ -87,12 +76,12 @@ func (d *DatabaseState) renameTable(node *tidbast.RenameTableStmt) *WalkThroughE
table, exists := schema.getTable(oldTableName)
if !exists {
if schema.ctx.CheckIntegrity {
- return NewTableNotExistsError(oldTableName)
+ return NewSchemaViolationError(604, fmt.Sprintf("Table `%s` does not exist", oldTableName))
}
table = schema.createIncompleteTable(oldTableName)
}
if _, exists := schema.getTable(newTableName); exists {
- return NewTableExistsError(newTableName)
+ return NewSchemaViolationError(607, fmt.Sprintf("Table `%s` already exists", newTableName))
}
delete(schema.tableSet, table.name)
table.name = newTableName
@@ -100,11 +89,11 @@ func (d *DatabaseState) renameTable(node *tidbast.RenameTableStmt) *WalkThroughE
} else if d.moveToOtherDatabase(tableToTable) {
_, exists := schema.getTable(tableToTable.OldTable.Name.O)
if !exists && schema.ctx.CheckIntegrity {
- return NewTableNotExistsError(tableToTable.OldTable.Name.O)
+ return NewSchemaViolationError(604, fmt.Sprintf("Table `%s` does not exist", tableToTable.OldTable.Name.O))
}
delete(schema.tableSet, tableToTable.OldTable.Name.O)
} else {
- return NewAccessOtherDatabaseError(d.name, d.targetDatabase(tableToTable))
+ return NewSchemaViolationError(702, fmt.Sprintf("Database `%s` is not the current database `%s`", d.targetDatabase(tableToTable), d.name))
}
}
return nil
@@ -134,18 +123,18 @@ func (d *DatabaseState) theCurrentDatabase(node *tidbast.TableToTable) bool {
return true
}
-func (d *DatabaseState) dropDatabase(node *tidbast.DropDatabaseStmt) *WalkThroughError {
+func (d *DatabaseState) dropDatabase(node *tidbast.DropDatabaseStmt) error {
if !d.isCurrentDatabase(node.Name.O) {
- return NewAccessOtherDatabaseError(d.name, node.Name.O)
+ return NewSchemaViolationError(702, fmt.Sprintf("Database `%s` is not the current database `%s`", node.Name.O, d.name))
}
d.deleted = true
return nil
}
-func (d *DatabaseState) alterDatabase(node *tidbast.AlterDatabaseStmt) *WalkThroughError {
+func (d *DatabaseState) alterDatabase(node *tidbast.AlterDatabaseStmt) error {
if !node.AlterDefaultDatabase && !d.isCurrentDatabase(node.Name.O) {
- return NewAccessOtherDatabaseError(d.name, node.Name.O)
+ return NewSchemaViolationError(702, fmt.Sprintf("Database `%s` is not the current database `%s`", node.Name.O, d.name))
}
for _, option := range node.Options {
@@ -161,9 +150,9 @@ func (d *DatabaseState) alterDatabase(node *tidbast.AlterDatabaseStmt) *WalkThro
return nil
}
-func (d *DatabaseState) findTableState(tableName *tidbast.TableName) (*TableState, *WalkThroughError) {
+func (d *DatabaseState) findTableState(tableName *tidbast.TableName) (*TableState, error) {
if tableName.Schema.O != "" && !d.isCurrentDatabase(tableName.Schema.O) {
- return nil, NewAccessOtherDatabaseError(d.name, tableName.Schema.O)
+ return nil, NewSchemaViolationError(702, fmt.Sprintf("Database `%s` is not the current database `%s`", tableName.Schema.O, d.name))
}
schema, exists := d.schemaSet[""]
@@ -174,7 +163,7 @@ func (d *DatabaseState) findTableState(tableName *tidbast.TableName) (*TableStat
table, exists := schema.getTable(tableName.Name.O)
if !exists {
if schema.ctx.CheckIntegrity {
- return nil, NewTableNotExistsError(tableName.Name.O)
+ return nil, NewSchemaViolationError(604, fmt.Sprintf("Table `%s` does not exist", tableName.Name.O))
}
table = schema.createIncompleteTable(tableName.Name.O)
}
@@ -182,7 +171,7 @@ func (d *DatabaseState) findTableState(tableName *tidbast.TableName) (*TableStat
return table, nil
}
-func (d *DatabaseState) dropIndex(node *tidbast.DropIndexStmt) *WalkThroughError {
+func (d *DatabaseState) dropIndex(node *tidbast.DropIndexStmt) error {
table, err := d.findTableState(node.Table)
if err != nil {
return err
@@ -191,7 +180,7 @@ func (d *DatabaseState) dropIndex(node *tidbast.DropIndexStmt) *WalkThroughError
return table.dropIndex(d.ctx, node.IndexName)
}
-func (d *DatabaseState) createIndex(node *tidbast.CreateIndexStmt) *WalkThroughError {
+func (d *DatabaseState) createIndex(node *tidbast.CreateIndexStmt) error {
table, err := d.findTableState(node.Table)
if err != nil {
return err
@@ -222,7 +211,7 @@ func (d *DatabaseState) createIndex(node *tidbast.CreateIndexStmt) *WalkThroughE
return table.createIndex(node.IndexName, keyList, unique, tp, node.IndexOption)
}
-func (d *DatabaseState) alterTable(node *tidbast.AlterTableStmt) *WalkThroughError {
+func (d *DatabaseState) alterTable(node *tidbast.AlterTableStmt) error {
table, err := d.findTableState(node.Table)
if err != nil {
return err
@@ -314,11 +303,11 @@ func (d *DatabaseState) alterTable(node *tidbast.AlterTableStmt) *WalkThroughErr
return nil
}
-func (t *TableState) changeIndexVisibility(ctx *FinderContext, indexName string, visibility tidbast.IndexVisibility) *WalkThroughError {
+func (t *TableState) changeIndexVisibility(ctx *FinderContext, indexName string, visibility tidbast.IndexVisibility) error {
index, exists := t.indexSet[strings.ToLower(indexName)]
if !exists {
if ctx.CheckIntegrity {
- return NewIndexNotExistsError(t.name, indexName)
+ return NewSchemaViolationError(809, fmt.Sprintf("Index `%s` does not exist in table `%s`", indexName, t.name))
}
index = t.createIncompleteIndex(indexName)
}
@@ -333,7 +322,7 @@ func (t *TableState) changeIndexVisibility(ctx *FinderContext, indexName string,
return nil
}
-func (t *TableState) renameIndex(ctx *FinderContext, oldName string, newName string) *WalkThroughError {
+func (t *TableState) renameIndex(ctx *FinderContext, oldName string, newName string) error {
// For MySQL, the primary key has a special name 'PRIMARY'.
// And the other indexes cannot use the name which case-insensitive equals 'PRIMARY'.
if strings.ToUpper(oldName) == PrimaryKeyName || strings.ToUpper(newName) == PrimaryKeyName {
@@ -341,22 +330,19 @@ func (t *TableState) renameIndex(ctx *FinderContext, oldName string, newName str
if strings.ToUpper(oldName) != PrimaryKeyName {
incorrectName = newName
}
- return &WalkThroughError{
- Type: ErrorTypeIncorrectIndexName,
- Content: fmt.Sprintf("Incorrect index name `%s`", incorrectName),
- }
+ return errors.Errorf("Incorrect index name `%s`", incorrectName)
}
index, exists := t.indexSet[strings.ToLower(oldName)]
if !exists {
if ctx.CheckIntegrity {
- return NewIndexNotExistsError(t.name, oldName)
+ return NewSchemaViolationError(809, fmt.Sprintf("Index `%s` does not exist in table `%s`", oldName, t.name))
}
index = t.createIncompleteIndex(oldName)
}
if _, exists := t.indexSet[strings.ToLower(newName)]; exists {
- return NewIndexExistsError(t.name, newName)
+ return NewSchemaViolationError(805, fmt.Sprintf("Index `%s` already exists in table `%s`", newName, t.name))
}
index.name = newName
@@ -365,12 +351,12 @@ func (t *TableState) renameIndex(ctx *FinderContext, oldName string, newName str
return nil
}
-func (t *TableState) changeColumnDefault(ctx *FinderContext, column *tidbast.ColumnDef) *WalkThroughError {
+func (t *TableState) changeColumnDefault(ctx *FinderContext, column *tidbast.ColumnDef) error {
columnName := column.Name.Name.L
colState, exists := t.columnSet[columnName]
if !exists {
if ctx.CheckIntegrity {
- return NewColumnNotExistsError(t.name, columnName)
+ return NewSchemaViolationError(405, fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, t.name))
}
colState = t.createIncompleteColumn(columnName)
}
@@ -384,11 +370,7 @@ func (t *TableState) changeColumnDefault(ctx *FinderContext, column *tidbast.Col
"text", "tinytext", "mediumtext", "longtext",
"json",
"geometry":
- return &WalkThroughError{
- Type: ErrorTypeInvalidColumnTypeForDefaultValue,
- // Content comes from MySQL Error content.
- Content: fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName),
- }
+ return NewSchemaViolationError(423, fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName))
default:
// Other column types allow default values
}
@@ -401,11 +383,7 @@ func (t *TableState) changeColumnDefault(ctx *FinderContext, column *tidbast.Col
colState.defaultValue = &defaultValue
} else {
if colState.nullable != nil && !*colState.nullable {
- return &WalkThroughError{
- Type: ErrorTypeSetNullDefaultForNotNullColumn,
- // Content comes from MySQL Error content.
- Content: fmt.Sprintf("Invalid default value for column `%s`", columnName),
- }
+ return errors.Errorf("Invalid default value for column `%s`", columnName)
}
colState.defaultValue = nil
}
@@ -416,7 +394,7 @@ func (t *TableState) changeColumnDefault(ctx *FinderContext, column *tidbast.Col
return nil
}
-func (t *TableState) renameColumn(ctx *FinderContext, oldName string, newName string) *WalkThroughError {
+func (t *TableState) renameColumn(ctx *FinderContext, oldName string, newName string) error {
if strings.EqualFold(oldName, newName) {
return nil
}
@@ -424,16 +402,13 @@ func (t *TableState) renameColumn(ctx *FinderContext, oldName string, newName st
column, exists := t.columnSet[strings.ToLower(oldName)]
if !exists {
if ctx.CheckIntegrity {
- return NewColumnNotExistsError(t.name, oldName)
+ return NewSchemaViolationError(405, fmt.Sprintf("Column `%s` does not exist in table `%s`", oldName, t.name))
}
column = t.createIncompleteColumn(oldName)
}
if _, exists := t.columnSet[strings.ToLower(newName)]; exists {
- return &WalkThroughError{
- Type: ErrorTypeColumnExists,
- Content: fmt.Sprintf("Column `%s` already exists in table `%s", newName, t.name),
- }
+ return NewSchemaViolationError(412, fmt.Sprintf("Column `%s` already exists in table `%s", newName, t.name))
}
column.name = newName
@@ -462,10 +437,10 @@ func (t *TableState) renameColumnInIndexKey(oldName string, newName string) {
// 1. drop column from tableState.columnSet, but do not drop column from indexSet.
// 2. rename column from indexSet.
// 3. create a new column in columnSet.
-func (t *TableState) completeTableChangeColumn(ctx *FinderContext, oldName string, newColumn *tidbast.ColumnDef, position *tidbast.ColumnPosition) *WalkThroughError {
+func (t *TableState) completeTableChangeColumn(ctx *FinderContext, oldName string, newColumn *tidbast.ColumnDef, position *tidbast.ColumnPosition) error {
column, exists := t.columnSet[strings.ToLower(oldName)]
if !exists {
- return NewColumnNotExistsError(t.name, oldName)
+ return NewSchemaViolationError(405, fmt.Sprintf("Column `%s` does not exist in table `%s`", oldName, t.name))
}
pos := *column.position
@@ -515,7 +490,7 @@ func (t *TableState) completeTableChangeColumn(ctx *FinderContext, oldName strin
// incompleteTableChangeColumn changes column definition.
// It does not maintain the position of the column.
-func (t *TableState) incompleteTableChangeColumn(ctx *FinderContext, oldName string, newColumn *tidbast.ColumnDef, position *tidbast.ColumnPosition) *WalkThroughError {
+func (t *TableState) incompleteTableChangeColumn(ctx *FinderContext, oldName string, newColumn *tidbast.ColumnDef, position *tidbast.ColumnPosition) error {
delete(t.columnSet, strings.ToLower(oldName))
// rename column from indexSet
@@ -525,23 +500,20 @@ func (t *TableState) incompleteTableChangeColumn(ctx *FinderContext, oldName str
return t.createColumn(ctx, newColumn, position)
}
-func (t *TableState) changeColumn(ctx *FinderContext, oldName string, newColumn *tidbast.ColumnDef, position *tidbast.ColumnPosition) *WalkThroughError {
+func (t *TableState) changeColumn(ctx *FinderContext, oldName string, newColumn *tidbast.ColumnDef, position *tidbast.ColumnPosition) error {
if ctx.CheckIntegrity {
return t.completeTableChangeColumn(ctx, oldName, newColumn, position)
}
return t.incompleteTableChangeColumn(ctx, oldName, newColumn, position)
}
-func (t *TableState) dropIndex(ctx *FinderContext, indexName string) *WalkThroughError {
+func (t *TableState) dropIndex(ctx *FinderContext, indexName string) error {
if ctx.CheckIntegrity {
if _, exists := t.indexSet[strings.ToLower(indexName)]; !exists {
if strings.EqualFold(indexName, PrimaryKeyName) {
- return &WalkThroughError{
- Type: ErrorTypePrimaryKeyNotExists,
- Content: fmt.Sprintf("Primary key does not exist in table `%s`", t.name),
- }
+ return NewSchemaViolationError(808, fmt.Sprintf("Primary key does not exist in table `%s`", t.name))
}
- return NewIndexNotExistsError(t.name, indexName)
+ return NewSchemaViolationError(809, fmt.Sprintf("Index `%s` does not exist in table `%s`", indexName, t.name))
}
}
@@ -549,19 +521,15 @@ func (t *TableState) dropIndex(ctx *FinderContext, indexName string) *WalkThroug
return nil
}
-func (t *TableState) completeTableDropColumn(columnName string) *WalkThroughError {
+func (t *TableState) completeTableDropColumn(columnName string) error {
column, exists := t.columnSet[strings.ToLower(columnName)]
if !exists {
- return NewColumnNotExistsError(t.name, columnName)
+ return NewSchemaViolationError(405, fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, t.name))
}
// Cannot drop all columns in a table using ALTER TABLE DROP COLUMN.
if len(t.columnSet) == 1 {
- return &WalkThroughError{
- Type: ErrorTypeDropAllColumns,
- // Error content comes from MySQL error content.
- Content: fmt.Sprintf("Can't delete all columns with ALTER TABLE; use DROP TABLE %s instead", t.name),
- }
+ return errors.Errorf("Can't delete all columns with ALTER TABLE; use DROP TABLE %s instead", t.name)
}
// If columns are dropped from a table, the columns are also removed from any index of which they are a part.
@@ -584,7 +552,7 @@ func (t *TableState) completeTableDropColumn(columnName string) *WalkThroughErro
return nil
}
-func (t *TableState) incompleteTableDropColumn(columnName string) *WalkThroughError {
+func (t *TableState) incompleteTableDropColumn(columnName string) error {
// If columns are dropped from a table, the columns are also removed from any index of which they are a part.
for _, index := range t.indexSet {
if len(index.expressionList) == 0 {
@@ -601,7 +569,7 @@ func (t *TableState) incompleteTableDropColumn(columnName string) *WalkThroughEr
return nil
}
-func (t *TableState) dropColumn(ctx *FinderContext, columnName string) *WalkThroughError {
+func (t *TableState) dropColumn(ctx *FinderContext, columnName string) error {
if ctx.CheckIntegrity {
return t.completeTableDropColumn(columnName)
}
@@ -623,7 +591,7 @@ func (idx *IndexState) dropColumn(columnName string) {
}
// reorderColumn reorders the columns for new column and returns the new column position.
-func (t *TableState) reorderColumn(position *tidbast.ColumnPosition) (int, *WalkThroughError) {
+func (t *TableState) reorderColumn(position *tidbast.ColumnPosition) (int, error) {
switch position.Tp {
case tidbast.ColumnPositionNone:
return len(t.columnSet) + 1, nil
@@ -636,7 +604,7 @@ func (t *TableState) reorderColumn(position *tidbast.ColumnPosition) (int, *Walk
columnName := position.RelativeColumn.Name.L
column, exist := t.columnSet[columnName]
if !exist {
- return 0, NewColumnNotExistsError(t.name, columnName)
+ return 0, NewSchemaViolationError(405, fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, t.name))
}
for _, col := range t.columnSet {
if *col.position > *column.position {
@@ -645,22 +613,16 @@ func (t *TableState) reorderColumn(position *tidbast.ColumnPosition) (int, *Walk
}
return *column.position + 1, nil
default:
- return 0, &WalkThroughError{
- Type: ErrorTypeUnsupported,
- Content: fmt.Sprintf("Unsupported column position type: %d", position.Tp),
- }
+ return 0, errors.Errorf("Unsupported column position type: %d", position.Tp)
}
}
-func (d *DatabaseState) dropTable(node *tidbast.DropTableStmt) *WalkThroughError {
+func (d *DatabaseState) dropTable(node *tidbast.DropTableStmt) error {
// TODO(rebelice): deal with DROP VIEW statement.
if !node.IsView {
for _, name := range node.Tables {
if name.Schema.O != "" && !d.isCurrentDatabase(name.Schema.O) {
- return &WalkThroughError{
- Type: ErrorTypeAccessOtherDatabase,
- Content: fmt.Sprintf("Database `%s` is not the current database `%s`", name.Schema.O, d.name),
- }
+ return NewSchemaViolationError(702, fmt.Sprintf("Database `%s` is not the current database `%s`", name.Schema.O, d.name))
}
schema, exists := d.schemaSet[""]
@@ -673,10 +635,7 @@ func (d *DatabaseState) dropTable(node *tidbast.DropTableStmt) *WalkThroughError
if node.IfExists || !d.ctx.CheckIntegrity {
return nil
}
- return &WalkThroughError{
- Type: ErrorTypeTableNotExists,
- Content: fmt.Sprintf("Table `%s` does not exist", name.Name.O),
- }
+ return NewSchemaViolationError(604, fmt.Sprintf("Table `%s` does not exist", name.Name.O))
}
delete(schema.tableSet, table.name)
@@ -685,14 +644,11 @@ func (d *DatabaseState) dropTable(node *tidbast.DropTableStmt) *WalkThroughError
return nil
}
-func (d *DatabaseState) copyTable(node *tidbast.CreateTableStmt) *WalkThroughError {
+func (d *DatabaseState) copyTable(node *tidbast.CreateTableStmt) error {
targetTable, err := d.findTableState(node.ReferTable)
if err != nil {
- if err.Type == ErrorTypeAccessOtherDatabase {
- return &WalkThroughError{
- Type: ErrorTypeReferenceOtherDatabase,
- Content: fmt.Sprintf("Reference table `%s` in other database `%s`, skip walkthrough", node.ReferTable.Name.O, node.ReferTable.Schema.O),
- }
+ if strings.Contains(err.Error(), "is not the current database") {
+ return errors.Errorf("Reference table `%s` in other database `%s`, skip walkthrough", node.ReferTable.Name.O, node.ReferTable.Schema.O)
}
}
@@ -703,12 +659,9 @@ func (d *DatabaseState) copyTable(node *tidbast.CreateTableStmt) *WalkThroughErr
return nil
}
-func (d *DatabaseState) createTable(node *tidbast.CreateTableStmt) *WalkThroughError {
+func (d *DatabaseState) createTable(node *tidbast.CreateTableStmt) error {
if node.Table.Schema.O != "" && !d.isCurrentDatabase(node.Table.Schema.O) {
- return &WalkThroughError{
- Type: ErrorTypeAccessOtherDatabase,
- Content: fmt.Sprintf("Database `%s` is not the current database `%s`", node.Table.Schema.O, d.name),
- }
+ return NewSchemaViolationError(702, fmt.Sprintf("Database `%s` is not the current database `%s`", node.Table.Schema.O, d.name))
}
schema, exists := d.schemaSet[""]
@@ -720,17 +673,11 @@ func (d *DatabaseState) createTable(node *tidbast.CreateTableStmt) *WalkThroughE
if node.IfNotExists {
return nil
}
- return &WalkThroughError{
- Type: ErrorTypeTableExists,
- Content: fmt.Sprintf("Table `%s` already exists", node.Table.Name.O),
- }
+ return NewSchemaViolationError(607, fmt.Sprintf("Table `%s` already exists", node.Table.Name.O))
}
if node.Select != nil {
- return &WalkThroughError{
- Type: ErrorTypeUseCreateTableAs,
- Content: fmt.Sprintf("Disallow the CREATE TABLE AS statement but \"%s\" uses", node.Text()),
- }
+ return NewSchemaViolationError(205, fmt.Sprintf("Disallow the CREATE TABLE AS statement but \"%s\" uses", node.Text()))
}
if node.ReferTable != nil {
@@ -751,23 +698,17 @@ func (d *DatabaseState) createTable(node *tidbast.CreateTableStmt) *WalkThroughE
for _, column := range node.Cols {
if isAutoIncrement(column) {
if hasAutoIncrement {
- return &WalkThroughError{
- Type: ErrorTypeAutoIncrementExists,
- // The content comes from MySQL error content.
- Content: fmt.Sprintf("There can be only one auto column for table `%s`", table.name),
- }
+ return NewSchemaViolationError(1, fmt.Sprintf("There can be only one auto column for table `%s`", table.name))
}
hasAutoIncrement = true
}
if err := table.createColumn(d.ctx, column, nil /* position */); err != nil {
- err.Line = column.OriginTextPosition()
return err
}
}
for _, constraint := range node.Constraints {
if err := table.createConstraint(d.ctx, constraint); err != nil {
- err.Line = constraint.OriginTextPosition()
return err
}
}
@@ -775,7 +716,7 @@ func (d *DatabaseState) createTable(node *tidbast.CreateTableStmt) *WalkThroughE
return nil
}
-func (t *TableState) createConstraint(ctx *FinderContext, constraint *tidbast.Constraint) *WalkThroughError {
+func (t *TableState) createConstraint(ctx *FinderContext, constraint *tidbast.Constraint) error {
switch constraint.Tp {
case tidbast.ConstraintPrimaryKey:
keyList, err := t.validateAndGetKeyStringList(ctx, constraint.Keys, true /* primary */, false /* isSpatial */)
@@ -820,7 +761,7 @@ func (t *TableState) createConstraint(ctx *FinderContext, constraint *tidbast.Co
return nil
}
-func (t *TableState) validateAndGetKeyStringList(ctx *FinderContext, keyList []*tidbast.IndexPartSpecification, primary bool, isSpatial bool) ([]string, *WalkThroughError) {
+func (t *TableState) validateAndGetKeyStringList(ctx *FinderContext, keyList []*tidbast.IndexPartSpecification, primary bool, isSpatial bool) ([]string, error) {
var res []string
for _, key := range keyList {
if key.Expr != nil {
@@ -834,18 +775,14 @@ func (t *TableState) validateAndGetKeyStringList(ctx *FinderContext, keyList []*
column, exists := t.columnSet[columnName]
if !exists {
if ctx.CheckIntegrity {
- return nil, NewColumnNotExistsError(t.name, columnName)
+ return nil, NewSchemaViolationError(405, fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, t.name))
}
} else {
if primary {
column.nullable = newFalsePointer()
}
if isSpatial && column.nullable != nil && *column.nullable {
- return nil, &WalkThroughError{
- Type: ErrorTypeSpatialIndexKeyNullable,
- // The error content comes from MySQL.
- Content: fmt.Sprintf("All parts of a SPATIAL index must be NOT NULL, but `%s` is nullable", column.name),
- }
+ return nil, errors.Errorf("All parts of a SPATIAL index must be NOT NULL, but `%s` is nullable", column.name)
}
}
@@ -864,15 +801,11 @@ func isAutoIncrement(column *tidbast.ColumnDef) bool {
return false
}
-func checkDefault(columnName string, columnType *types.FieldType, value tidbast.ExprNode) *WalkThroughError {
+func checkDefault(columnName string, columnType *types.FieldType, value tidbast.ExprNode) error {
if value.GetType().GetType() != mysql.TypeNull {
switch columnType.GetType() {
case mysql.TypeBlob, mysql.TypeTinyBlob, mysql.TypeMediumBlob, mysql.TypeLongBlob, mysql.TypeJSON, mysql.TypeGeometry:
- return &WalkThroughError{
- Type: ErrorTypeInvalidColumnTypeForDefaultValue,
- // Content comes from MySQL Error content.
- Content: fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName),
- }
+ return NewSchemaViolationError(423, fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName))
default:
// Other column types allow default values
}
@@ -881,26 +814,20 @@ func checkDefault(columnName string, columnType *types.FieldType, value tidbast.
if valueExpr, yes := value.(tidbast.ValueExpr); yes {
datum := types.NewDatum(valueExpr.GetValue())
if _, err := datum.ConvertTo(types.Context{}, columnType); err != nil {
- return &WalkThroughError{
- Type: ErrorTypeInvalidColumnTypeForDefaultValue,
- Content: err.Error(),
- }
+ return errors.Errorf("%s", err.Error())
}
}
return nil
}
-func (t *TableState) createColumn(ctx *FinderContext, column *tidbast.ColumnDef, position *tidbast.ColumnPosition) *WalkThroughError {
+func (t *TableState) createColumn(ctx *FinderContext, column *tidbast.ColumnDef, position *tidbast.ColumnPosition) error {
if _, exists := t.columnSet[column.Name.Name.L]; exists {
- return &WalkThroughError{
- Type: ErrorTypeColumnExists,
- Content: fmt.Sprintf("Column `%s` already exists in table `%s`", column.Name.Name.O, t.name),
- }
+ return NewSchemaViolationError(412, fmt.Sprintf("Column `%s` already exists in table `%s`", column.Name.Name.O, t.name))
}
pos := len(t.columnSet) + 1
if position != nil && ctx.CheckIntegrity {
- var err *WalkThroughError
+ var err error
pos, err = t.reorderColumn(position)
if err != nil {
return err
@@ -953,10 +880,7 @@ func (t *TableState) createColumn(ctx *FinderContext, column *tidbast.ColumnDef,
case tidbast.ColumnOptionOnUpdate:
// we do not deal with ON UPDATE
if column.Tp.GetType() != mysql.TypeDatetime && column.Tp.GetType() != mysql.TypeTimestamp {
- return &WalkThroughError{
- Type: ErrorTypeOnUpdateColumnNotDatetimeOrTimestamp,
- Content: fmt.Sprintf("Column `%s` use ON UPDATE but is not DATETIME or TIMESTAMP", col.name),
- }
+ return errors.Errorf("Column `%s` use ON UPDATE but is not DATETIME or TIMESTAMP", col.name)
}
case tidbast.ColumnOptionComment:
comment, err := restoreNode(option.Expr, format.RestoreStringWithoutCharset)
@@ -985,27 +909,20 @@ func (t *TableState) createColumn(ctx *FinderContext, column *tidbast.ColumnDef,
}
if col.nullable != nil && !*col.nullable && setNullDefault {
- return &WalkThroughError{
- Type: ErrorTypeSetNullDefaultForNotNullColumn,
- // Content comes from MySQL Error content.
- Content: fmt.Sprintf("Invalid default value for column `%s`", col.name),
- }
+ return errors.Errorf("Invalid default value for column `%s`", col.name)
}
t.columnSet[strings.ToLower(col.name)] = col
return nil
}
-func (t *TableState) createIndex(name string, keyList []string, unique bool, tp string, option *tidbast.IndexOption) *WalkThroughError {
+func (t *TableState) createIndex(name string, keyList []string, unique bool, tp string, option *tidbast.IndexOption) error {
if len(keyList) == 0 {
- return &WalkThroughError{
- Type: ErrorTypeIndexEmptyKeys,
- Content: fmt.Sprintf("Index `%s` in table `%s` has empty key", name, t.name),
- }
+ return errors.Errorf("Index `%s` in table `%s` has empty key", name, t.name)
}
if name != "" {
if _, exists := t.indexSet[strings.ToLower(name)]; exists {
- return NewIndexExistsError(t.name, name)
+ return NewSchemaViolationError(805, fmt.Sprintf("Index `%s` already exists in table `%s`", name, t.name))
}
} else {
suffix := 1
@@ -1039,12 +956,9 @@ func (t *TableState) createIndex(name string, keyList []string, unique bool, tp
return nil
}
-func (t *TableState) createPrimaryKey(keys []string, tp string) *WalkThroughError {
+func (t *TableState) createPrimaryKey(keys []string, tp string) error {
if _, exists := t.indexSet[strings.ToLower(PrimaryKeyName)]; exists {
- return &WalkThroughError{
- Type: ErrorTypePrimaryKeyExists,
- Content: fmt.Sprintf("Primary key exists in table `%s`", t.name),
- }
+ return errors.Errorf("Primary key exists in table `%s`", t.name)
}
pk := &IndexState{
@@ -1060,14 +974,11 @@ func (t *TableState) createPrimaryKey(keys []string, tp string) *WalkThroughErro
return nil
}
-func restoreNode(node tidbast.Node, flag format.RestoreFlags) (string, *WalkThroughError) {
+func restoreNode(node tidbast.Node, flag format.RestoreFlags) (string, error) {
var buffer strings.Builder
ctx := format.NewRestoreCtx(flag, &buffer)
if err := node.Restore(ctx); err != nil {
- return "", &WalkThroughError{
- Type: ErrorTypeDeparseError,
- Content: err.Error(),
- }
+ return "", errors.Errorf("%s", err.Error())
}
return buffer.String(), nil
}
diff --git a/backend/plugin/advisor/catalog/walk_through_test.go b/backend/plugin/advisor/catalog/walk_through_test.go
index 72b8c66ea0..a3198a7f05 100644
--- a/backend/plugin/advisor/catalog/walk_through_test.go
+++ b/backend/plugin/advisor/catalog/walk_through_test.go
@@ -23,7 +23,7 @@ type testData struct {
// Use custom yaml tag to avoid generate field name `ignorecasesensitive`.
IgnoreCaseSensitive bool `yaml:"ignore_case_sensitive"`
Want string
- Err *WalkThroughError
+ Err string
}
func TestTiDBWalkThrough(t *testing.T) {
@@ -172,14 +172,6 @@ func TestPostgreSQLANTLRWalkThrough(t *testing.T) {
}
}
-func convertInterfaceSliceToStringSlice(slice []any) []string {
- var res []string
- for _, item := range slice {
- res = append(res, item.(string))
- }
- return res
-}
-
func runWalkThroughTest(t *testing.T, file string, engineType storepb.Engine, originDatabase *storepb.DatabaseSchemaMetadata) {
tests := []testData{}
filepath := filepath.Join("test", file+".yaml")
@@ -204,20 +196,9 @@ func runWalkThroughTest(t *testing.T, file string, engineType storepb.Engine, or
asts, _ := sm.GetASTsForChecks(engineType, test.Statement)
err := state.WalkThrough(asts)
- if err != nil {
- err, yes := err.(*WalkThroughError)
- require.True(t, yes)
- if err.Payload != nil {
- actualPayloadText, yes := err.Payload.([]string)
- require.True(t, yes)
- expectedPayloadText := convertInterfaceSliceToStringSlice(test.Err.Payload.([]any))
- err.Payload = nil
- test.Err.Payload = nil
- require.Equal(t, test.Err, err)
- require.Equal(t, expectedPayloadText, actualPayloadText)
- } else {
- require.Equal(t, test.Err, err)
- }
+ if test.Err != "" {
+ require.Error(t, err, test.Statement)
+ require.Equal(t, test.Err, err.Error(), test.Statement)
continue
}
require.NoError(t, err, test.Statement)
@@ -260,20 +241,9 @@ func runANTLRWalkThroughTest(t *testing.T, file string, engineType storepb.Engin
// Call WalkThrough with ANTLR tree
err := state.WalkThrough(parseResult)
- if err != nil {
- err, yes := err.(*WalkThroughError)
- require.True(t, yes)
- if err.Payload != nil {
- actualPayloadText, yes := err.Payload.([]string)
- require.True(t, yes)
- expectedPayloadText := convertInterfaceSliceToStringSlice(test.Err.Payload.([]any))
- err.Payload = nil
- test.Err.Payload = nil
- require.Equal(t, test.Err, err)
- require.Equal(t, expectedPayloadText, actualPayloadText)
- } else {
- require.Equal(t, test.Err, err)
- }
+ if test.Err != "" {
+ require.Error(t, err, test.Statement)
+ require.Equal(t, test.Err, err.Error(), test.Statement)
continue
}
require.NoError(t, err, test.Statement)