Skip to content

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

refactor: simplify WalkThrough to return single advice (#18133)

Danny Xuc8665dd30e59
diff --git a/backend/plugin/advisor/pg/test_helper.go b/backend/plugin/advisor/pg/test_helper.go
index 7d57a2262e..95c28865d1 100644
--- a/backend/plugin/advisor/pg/test_helper.go
+++ b/backend/plugin/advisor/pg/test_helper.go
@@ -85,8 +85,8 @@ func RunANTLRAdvisorRuleTest(t *testing.T, rule advisor.SQLReviewRuleType, dbTyp
require.NoError(t, err, "Failed to parse SQL: %s", tc.Statement)
// Always walk through the catalog to build metadata.
- err = schema.WalkThrough(dbType, finalMetadata, tree)
- require.NoError(t, err, "Failed to walk through final catalog: %s", tc.Statement)
+ advice := schema.WalkThrough(dbType, finalMetadata, tree)
+ require.Nil(t, advice, "Failed to walk through final catalog: %s", tc.Statement)
ruleList := []*storepb.SQLReviewRule{
{
diff --git a/backend/plugin/advisor/sql_review.go b/backend/plugin/advisor/sql_review.go
index f79029c884..1caacb8a8e 100644
--- a/backend/plugin/advisor/sql_review.go
+++ b/backend/plugin/advisor/sql_review.go
@@ -11,10 +11,8 @@ import (
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/component/sheet"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/advisor/code"
"github.com/bytebase/bytebase/backend/plugin/parser/base"
"github.com/bytebase/bytebase/backend/plugin/schema"
- "github.com/bytebase/bytebase/backend/plugin/schema/catalogutil"
"github.com/bytebase/bytebase/backend/store/model"
// Register walk-through implementations
@@ -541,8 +539,8 @@ func SQLReviewCheck(
if !builtinOnly && checkContext.FinalMetadata != nil {
switch checkContext.DBType {
case storepb.Engine_TIDB, storepb.Engine_MYSQL, storepb.Engine_MARIADB, storepb.Engine_POSTGRES, storepb.Engine_OCEANBASE:
- if err := schema.WalkThrough(checkContext.DBType, checkContext.FinalMetadata, asts); err != nil {
- return convertWalkThroughErrorToAdvice(err)
+ if advice := schema.WalkThrough(checkContext.DBType, checkContext.FinalMetadata, asts); advice != nil {
+ return []*storepb.Advice{advice}, nil
}
default:
// Other database types don't need walkthrough
@@ -607,27 +605,3 @@ func SQLReviewCheck(
advices = append(advices, warningAdvices...)
return advices, nil
}
-
-func convertWalkThroughErrorToAdvice(err error) ([]*storepb.Advice, error) {
- walkThroughError, ok := err.(*catalogutil.WalkThroughError)
- if !ok {
- return nil, err
- }
-
- // Determine the advice status based on the error code
- // Most errors are ERROR level, except for a few special cases
- status := storepb.Advice_ERROR
- if walkThroughError.Code == code.ReferenceOtherDatabase {
- status = storepb.Advice_WARNING
- }
-
- return []*storepb.Advice{
- {
- Status: status,
- Code: walkThroughError.Code.Int32(),
- Title: walkThroughError.Content,
- Content: walkThroughError.Content,
- StartPosition: common.ConvertANTLRLineToPosition(walkThroughError.Line),
- },
- }, nil
-}
diff --git a/backend/plugin/schema/catalogutil/types.go b/backend/plugin/schema/catalogutil/types.go
deleted file mode 100644
index c8b3c1e598..0000000000
--- a/backend/plugin/schema/catalogutil/types.go
+++ /dev/null
@@ -1,87 +0,0 @@
-package catalogutil
-
-import (
- "fmt"
- "strings"
-
- "github.com/bytebase/bytebase/backend/plugin/advisor/code"
-)
-
-// WalkThroughError is the error for walking-through.
-// It represents SQL review errors that should be converted to advisor codes.
-type WalkThroughError struct {
- Code code.Code
- Content string
- // TODO(zp): position
- Line int
-}
-
-// Error implements the error interface.
-func (e *WalkThroughError) Error() string {
- return e.Content
-}
-
-// CompareIdentifier returns true if the engine will regard the two identifiers as the same one.
-// This is kept in catalogutil for the isCurrentDatabase helper functions in engine packages.
-func CompareIdentifier(a, b string, ignoreCaseSensitive bool) bool {
- if ignoreCaseSensitive {
- return strings.EqualFold(a, b)
- }
- return a == b
-}
-
-// NewRelationExistsError returns a new RelationExists error.
-func NewRelationExistsError(relationName string, schemaName string) *WalkThroughError {
- return &WalkThroughError{
- Code: code.RelationExists,
- Content: fmt.Sprintf("Relation %q already exists in schema %q", relationName, schemaName),
- }
-}
-
-// NewColumnNotExistsError returns a new ColumnNotExists error.
-func NewColumnNotExistsError(tableName string, columnName string) *WalkThroughError {
- return &WalkThroughError{
- Code: code.ColumnNotExists,
- Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, tableName),
- }
-}
-
-// NewIndexNotExistsError returns a new IndexNotExists error.
-func NewIndexNotExistsError(tableName string, indexName string) *WalkThroughError {
- return &WalkThroughError{
- Code: code.IndexNotExists,
- Content: fmt.Sprintf("Index `%s` does not exist in table `%s`", indexName, tableName),
- }
-}
-
-// NewIndexExistsError returns a new IndexExists error.
-func NewIndexExistsError(tableName string, indexName string) *WalkThroughError {
- return &WalkThroughError{
- Code: code.IndexExists,
- Content: fmt.Sprintf("Index `%s` already exists in table `%s`", indexName, tableName),
- }
-}
-
-// NewAccessOtherDatabaseError returns a new NotCurrentDatabase error.
-func NewAccessOtherDatabaseError(current string, target string) *WalkThroughError {
- return &WalkThroughError{
- Code: code.NotCurrentDatabase,
- Content: fmt.Sprintf("Database `%s` is not the current database `%s`", target, current),
- }
-}
-
-// NewTableNotExistsError returns a new TableNotExists error.
-func NewTableNotExistsError(tableName string) *WalkThroughError {
- return &WalkThroughError{
- Code: code.TableNotExists,
- Content: fmt.Sprintf("Table `%s` does not exist", tableName),
- }
-}
-
-// NewTableExistsError returns a new TableExists error.
-func NewTableExistsError(tableName string) *WalkThroughError {
- return &WalkThroughError{
- Code: code.TableExists,
- Content: fmt.Sprintf("Table `%s` already exists", tableName),
- }
-}
diff --git a/backend/plugin/schema/mysql/testdata/walk_through.yaml b/backend/plugin/schema/mysql/testdata/walk_through.yaml
index d7d04ea91a..c52aa47129 100644
--- a/backend/plugin/schema/mysql/testdata/walk_through.yaml
+++ b/backend/plugin/schema/mysql/testdata/walk_through.yaml
@@ -5,16 +5,19 @@
RENAME TABLE `other`.`t1` TO `other`.`t2`;'
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 702
+ title: Database `other` is not the current database `test`
content: Database `other` is not the current database `test`
- line: 2
+ startPosition:
+ line: 2
- statement: 'CREATE TABLE `test`.`t1` (a INT);
RENAME TABLE `test`.`t1` TO `other`.`t1`;'
ignore_case_sensitive: false
want: "{\n \"name\": \"test\",\n \"schemas\": [\n {}\n ]\n}"
- err: null
+ advice: null
- statement: 'CREATE TABLE t1(a INT);
CREATE TABLE t2(a INT);
@@ -22,19 +25,25 @@
RENAME TABLE t2 TO t1;'
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 607
+ title: Table `t1` already exists
content: Table `t1` already exists
- line: 3
+ startPosition:
+ line: 3
- statement: 'CREATE TABLE t1(a INT);
RENAME TABLE t2 TO t3;'
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 604
+ title: Table `t2` does not exist
content: Table `t2` does not exist
- line: 2
+ startPosition:
+ line: 2
- statement: 'CREATE TABLE t1 (a INT);
RENAME TABLE t1 TO t2;'
@@ -44,14 +53,17 @@
\ {\n \"name\": \"a\",\n \"position\": 1,\n \
\ \"nullable\": true,\n \"type\": \"int\"\n }\n\
\ ]\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: CREATE DATABASE another;
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 702
+ title: Database `another` is not the current database `test`
content: Database `another` is not the current database `test`
- line: 1
+ startPosition:
+ line: 1
- statement: '-- this is comment
DROP DATABASE test;
@@ -59,17 +71,20 @@
CREATE TABLE t(a int);'
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 703
+ title: Database `test` is deleted
content: Database `test` is deleted
- line: 1
+ startPosition:
+ line: 1
- statement: 'ALTER DATABASE CHARACTER SET = utf8mb4;
ALTER DATABASE test COLLATE utf8mb4_polish_ci;'
ignore_case_sensitive: false
want: "{\n \"name\": \"test\",\n \"schemas\": [\n {}\n ],\n \"characterSet\"\
: \"utf8mb4\",\n \"collation\": \"utf8mb4_polish_ci\"\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE t1(\n a INT PRIMARY KEY,\n c VARCHAR(255) NOT NULL\n\
);\nALTER TABLE t1 ADD INDEX idx1 (c);\nCREATE FULLTEXT INDEX ftk1 ON t1 (c);\n\
DROP INDEX `PRIMARY` ON t1;\nDROP INDEX idx1 ON t1;\nDROP INDEX ftk1 ON t1;"
@@ -80,7 +95,7 @@
\ \"type\": \"int\"\n },\n {\n \"name\"\
: \"c\",\n \"position\": 2,\n \"type\": \"varchar\"\n\
\ }\n ]\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE t1(\n a INT,\n b INT,\n c VARCHAR(255) NOT NULL,\n \
\ d GEOMETRY NOT NULL\n);\nCREATE INDEX idx1 ON t1 (a) INVISIBLE;\nCREATE UNIQUE\
\ INDEX uk1 ON t1 (b);\nCREATE FULLTEXT INDEX ftk1 ON t1 (c);\nCREATE SPATIAL\
@@ -108,16 +123,19 @@
b\"\n ],\n \"type\": \"BTREE\",\n \"unique\"\
: true,\n \"visible\": true\n }\n ]\n \
\ }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: 'CREATE TABLE t1(a GEOMETRY);
CREATE SPATIAL INDEX sk1 ON t1 (a);'
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 811
+ title: All parts of a SPATIAL index must be NOT NULL, but `a` is nullable
content: All parts of a SPATIAL index must be NOT NULL, but `a` is nullable
- line: 2
+ startPosition:
+ line: 2
- statement: "CREATE TABLE t1(\n a INT PRIMARY KEY,\n b INT,\n UNIQUE uk1 (b)\n\
);\nALTER TABLE t1 ENGINE = MyISAM;\nALTER TABLE t1 COMMENT = 't1 table';\nALTER\
\ TABLE t1 COLLATE utf8mb4_unicode_ci;"
@@ -137,7 +155,7 @@
\ \"visible\": true\n }\n ],\n \"engine\"\
: \"MyISAM\",\n \"collation\": \"utf8mb4_unicode_ci\",\n \"\
comment\": \"t1 table\"\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE t1(\n a INT PRIMARY KEY,\n b INT,\n UNIQUE uk1 (b)\n\
);\nALTER TABLE t1 DROP PRIMARY KEY;\nALTER TABLE t1 DROP INDEX uk1;"
ignore_case_sensitive: false
@@ -148,7 +166,7 @@
: \"b\",\n \"position\": 2,\n \"nullable\": true,\n\
\ \"type\": \"int\"\n }\n ]\n }\n \
\ ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE t1(\n a INT,\n b INT,\n UNIQUE uk1 (b)\n);\nALTER TABLE\
\ t1 RENAME INDEX uk1 TO uk_b;\nALTER TABLE t1 ADD INDEX idx1 (b);\nALTER TABLE\
\ t1 RENAME INDEX idx1 TO idx2;\nALTER TABLE t1 ALTER INDEX idx2 INVISIBLE;\n\
@@ -167,16 +185,19 @@
\ \"b\"\n ],\n \"type\": \"BTREE\",\n\
\ \"unique\": true,\n \"visible\": true\n \
\ }\n ]\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: 'CREATE TABLE t1(a INT NOT NULL);
ALTER TABLE t1 ALTER COLUMN a SET DEFAULT NULL;'
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 428
+ title: Invalid default value for column `a`
content: Invalid default value for column `a`
- line: 2
+ startPosition:
+ line: 2
- statement: 'CREATE TABLE t1(a INT);
ALTER TABLE t1 CHANGE COLUMN a a BLOB;
@@ -184,10 +205,13 @@
ALTER TABLE t1 ALTER COLUMN a SET DEFAULT ''default value'';'
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 423
+ title: BLOB, TEXT, GEOMETRY or JSON column `a` can't have a default value
content: BLOB, TEXT, GEOMETRY or JSON column `a` can't have a default value
- line: 3
+ startPosition:
+ line: 3
- statement: 'CREATE TABLE t1(a INT);
ALTER TABLE t1 CHANGE COLUMN a a BLOB;
@@ -199,7 +223,7 @@
\ {\n \"name\": \"a\",\n \"position\": 1,\n \
\ \"nullable\": true,\n \"type\": \"blob\"\n }\n\
\ ]\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE t1(\n a INT\n);\nALTER TABLE t1 ADD COLUMN b INT AFTER\
\ a;\nALTER TABLE t1 ADD COLUMN c INT NOT NULL DEFAULT 1 AFTER a;\nALTER TABLE\
\ t1 CHANGE COLUMN b d TEXT AFTER a;\nALTER TABLE t1 ALTER COLUMN a SET DEFAULT\
@@ -215,7 +239,7 @@
\ \"type\": \"text\"\n },\n {\n \"\
name\": \"c\",\n \"position\": 3,\n \"type\": \"int\"\
\n }\n ]\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE t1(\n a INT\n);\nALTER TABLE t1 ADD COLUMN b VARCHAR(255)\
\ FIRST;\nALTER TABLE t1 ADD COLUMN (c INT, d BLOB);\nALTER TABLE t1 MODIFY COLUMN\
\ b INT AFTER a;\nALTER TABLE t1 RENAME COLUMN b TO e;\nALTER TABLE t1 CHANGE\
@@ -230,7 +254,7 @@
\ },\n {\n \"name\": \"c\",\n \"position\"\
: 3,\n \"nullable\": true,\n \"type\": \"int\"\n \
\ }\n ]\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: 'CREATE TABLE t1(a INT);
CREATE TABLE t2(a INT);
@@ -244,34 +268,45 @@
\ {\n \"name\": \"a\",\n \"position\": 1,\n \
\ \"nullable\": true,\n \"type\": \"int\"\n }\n\
\ ]\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE t1(\n a INT AUTO_INCREMENT,\n b INT AUTO_INCREMENT\n\
);"
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 426
+ title: There can be only one auto column for table `t1`
content: There can be only one auto column for table `t1`
- line: 1
+ startPosition:
+ line: 1
- 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:
+ advice:
+ status: 1
code: 205
+ title: 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
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
+ startPosition:
+ line: 1
- statement: 'CREATE TABLE t1(a int);
CREATE TABLE t2 (b INT) SELECT a FROM t1;'
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 205
+ title: Disallow the CREATE TABLE AS statement but "CREATE TABLE t2 (b INT) SELECT
+ a FROM t1;" uses
content: Disallow the CREATE TABLE AS statement but "CREATE TABLE t2 (b INT) SELECT
a FROM t1;" uses
- line: 2
+ startPosition:
+ line: 2
- statement: "CREATE TABLE t1(\n a int\n);\nCREATE TABLE t2 LIKE t1;"
ignore_case_sensitive: false
want: "{\n \"name\": \"test\",\n \"schemas\": [\n {\n \"tables\": [\n\
@@ -282,7 +317,7 @@
columns\": [\n {\n \"name\": \"a\",\n \"\
position\": 1,\n \"nullable\": true,\n \"type\": \"\
int\"\n }\n ]\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE t1(\n a INT PRIMARY KEY,\n b INT NOT NULL DEFAULT 1,\n\
\ c INT,\n d VARCHAR(255) NOT NULL,\n e VARCHAR(255),\n UNIQUE KEY uk1 (b,\
\ c),\n KEY idx1 (c),\n FULLTEXT(d, e) WITH PARSER ngram INVISIBLE\n);"
@@ -312,28 +347,37 @@
\ \"b\",\n \"c\"\n ],\n \"type\"\
: \"BTREE\",\n \"unique\": true,\n \"visible\": true\n\
\ }\n ]\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE t1(\n a INT NOT NULL DEFAULT NULL\n);"
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 428
+ title: Invalid default value for column `a`
content: Invalid default value for column `a`
- line: 2
+ startPosition:
+ line: 2
- statement: "CREATE TABLE t1(\n a BLOB DEFAULT 'this is a default value'\n);"
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 423
+ title: BLOB, TEXT, GEOMETRY or JSON column `a` can't have a default value
content: BLOB, TEXT, GEOMETRY or JSON column `a` can't have a default value
- line: 2
+ startPosition:
+ line: 2
- statement: "CREATE TABLE t1(\n a INT ON UPDATE NOW()\n);"
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 427
+ title: Column `a` use ON UPDATE but is not DATETIME or TIMESTAMP
content: Column `a` use ON UPDATE but is not DATETIME or TIMESTAMP
- line: 2
+ startPosition:
+ line: 2
- statement: "CREATE TABLE t1(\n a INT NOT NULL DEFAULT 1 PRIMARY KEY,\n b INT UNIQUE,\n\
\ c VARCHAR(255) NOT NULL DEFAULT 'NULL' COMMENT 'column c',\n e INT NULL DEFAULT\
\ NULL,\n f VARCHAR(10) NOT NULL COLLATE utf8mb4_polish_ci,\n g VARCHAR(200)\
@@ -363,7 +407,7 @@
\ ],\n \"type\": \"BTREE\",\n \"unique\": true,\n\
\ \"visible\": true\n }\n ]\n }\n \
\ ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE t1(\n id int,\n name varchar(255),\n key idx_name(name)\n\
);\ncreate table t2 (\n id int,\n t1_name varchar(255),\n constraint fk_t1_name\
\ foreign key (t1_name) references t1 (name)\n);\nalter table t2 drop foreign\
@@ -385,7 +429,7 @@
\ \"name\": \"t1_name\",\n \"position\": 2,\n \
\ \"nullable\": true,\n \"type\": \"varchar\"\n }\n\
\ ]\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "create table all_types(\n c1 tinyblob not null,\n c2 blob not null,\n\
\ c3 mediumblob not null,\n c4 longblob not null,\n c5 tinytext not null,\n\
\ c6 text not null,\n c7 mediumtext not null,\n c8 longtext not null,\n c9\
@@ -416,4 +460,4 @@
\ \"name\": \"c12\",\n \"position\": 12,\n \"\
type\": \"long\"\n }\n ]\n }\n ]\n }\n ]\n\
}"
- err: null
+ advice: null
diff --git a/backend/plugin/schema/mysql/walk_through.go b/backend/plugin/schema/mysql/walk_through.go
index 2a424a23b0..99f6f205e3 100644
--- a/backend/plugin/schema/mysql/walk_through.go
+++ b/backend/plugin/schema/mysql/walk_through.go
@@ -9,7 +9,6 @@ import (
tidbast "github.com/pingcap/tidb/pkg/parser/ast"
mysqldriver "github.com/pingcap/tidb/pkg/parser/mysql"
"github.com/pingcap/tidb/pkg/types"
- "github.com/pkg/errors"
"google.golang.org/protobuf/proto"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
@@ -17,7 +16,6 @@ import (
mysqlparser "github.com/bytebase/bytebase/backend/plugin/parser/mysql"
"github.com/bytebase/bytebase/backend/plugin/parser/tidb"
"github.com/bytebase/bytebase/backend/plugin/schema"
- "github.com/bytebase/bytebase/backend/plugin/schema/catalogutil"
"github.com/bytebase/bytebase/backend/store/model"
)
@@ -37,7 +35,7 @@ func init() {
}
// WalkThrough walks through MySQL AST and updates the database metadata.
-func WalkThrough(d *model.DatabaseMetadata, ast any) error {
+func WalkThrough(d *model.DatabaseMetadata, ast any) *storepb.Advice {
// We define the Catalog as Database -> Schema -> Table. The Schema is only for PostgreSQL.
// So we use a Schema whose name is empty for other engines, such as MySQL.
// If there is no empty-string-name schema, create it to avoid corner cases.
@@ -47,11 +45,19 @@ func WalkThrough(d *model.DatabaseMetadata, ast any) error {
nodeList, ok := ast.([]*mysqlparser.ParseResult)
if !ok {
- return errors.Errorf("invalid ast type %T", ast)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: fmt.Sprintf("invalid ast type %T", ast),
+ Content: fmt.Sprintf("invalid ast type %T", ast),
+ StartPosition: &storepb.Position{
+ Line: 0,
+ },
+ }
}
for _, node := range nodeList {
- if err := mysqlChangeState(d, node); err != nil {
- return err
+ if advice := mysqlChangeState(d, node); advice != nil {
+ return advice
}
}
@@ -65,7 +71,7 @@ type mysqlListener struct {
lineNumber int
text string
databaseMetadata *model.DatabaseMetadata
- err *catalogutil.WalkThroughError
+ advice *storepb.Advice
}
func (l *mysqlListener) EnterQuery(ctx *mysql.QueryContext) {
@@ -73,26 +79,17 @@ func (l *mysqlListener) EnterQuery(ctx *mysql.QueryContext) {
l.lineNumber = l.baseLine + ctx.GetStart().GetLine()
}
-func mysqlChangeState(d *model.DatabaseMetadata, in *mysqlparser.ParseResult) (err *catalogutil.WalkThroughError) {
- defer func() {
- if err == nil {
- return
- }
- if err.Line == 0 {
- err.Line = in.BaseLine
- }
- }()
-
+func mysqlChangeState(d *model.DatabaseMetadata, in *mysqlparser.ParseResult) *storepb.Advice {
listener := &mysqlListener{
baseLine: in.BaseLine,
databaseMetadata: d,
}
antlr.ParseTreeWalkerDefault.Walk(listener, in.Tree)
- if listener.err != nil {
- if listener.err.Line == 0 {
- listener.err.Line = listener.lineNumber
+ if listener.advice != nil {
+ if listener.advice.StartPosition.Line == 0 {
+ listener.advice.StartPosition.Line = int32(listener.lineNumber)
}
- return listener.err
+ return listener.advice
}
return nil
}
@@ -107,18 +104,24 @@ func (l *mysqlListener) EnterCreateTable(ctx *mysql.CreateTableContext) {
}
databaseName, tableName := mysqlparser.NormalizeMySQLTableName(ctx.TableName())
if databaseName != "" && !isCurrentDatabase(l.databaseMetadata, databaseName) {
- l.err = &catalogutil.WalkThroughError{
- Code: code.NotCurrentDatabase,
- Content: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, l.databaseMetadata.DatabaseName()),
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, l.databaseMetadata.DatabaseName()),
+ Content: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, l.databaseMetadata.DatabaseName()),
+ StartPosition: &storepb.Position{Line: 0},
}
return
}
schema := l.databaseMetadata.GetSchema("")
if schema == nil {
- l.err = &catalogutil.WalkThroughError{
- Code: code.SchemaNotExists,
- Content: "Schema does not exist",
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.SchemaNotExists.Int32(),
+ Title: "Schema does not exist",
+ Content: "Schema does not exist",
+ StartPosition: &storepb.Position{Line: 0},
}
return
}
@@ -126,30 +129,42 @@ func (l *mysqlListener) EnterCreateTable(ctx *mysql.CreateTableContext) {
if ctx.IfNotExists() != nil {
return
}
- l.err = &catalogutil.WalkThroughError{
- Code: code.TableExists,
- Content: fmt.Sprintf("Table `%s` already exists", tableName),
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableExists.Int32(),
+ Title: fmt.Sprintf("Table `%s` already exists", tableName),
+ Content: fmt.Sprintf("Table `%s` already exists", tableName),
+ StartPosition: &storepb.Position{Line: 0},
}
return
}
if ctx.DuplicateAsQueryExpression() != nil {
- l.err = &catalogutil.WalkThroughError{
- Code: code.StatementCreateTableAs,
- Content: fmt.Sprintf("Disallow the CREATE TABLE AS statement but \"%s\" uses", l.text),
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.StatementCreateTableAs.Int32(),
+ Title: fmt.Sprintf("Disallow the CREATE TABLE AS statement but \"%s\" uses", l.text),
+ Content: fmt.Sprintf("Disallow the CREATE TABLE AS statement but \"%s\" uses", l.text),
+ StartPosition: &storepb.Position{Line: 0},
}
return
}
if ctx.LIKE_SYMBOL() != nil {
_, referTable := mysqlparser.NormalizeMySQLTableRef(ctx.TableRef())
- l.err = mysqlCopyTable(l.databaseMetadata, databaseName, tableName, referTable)
+ l.advice = mysqlCopyTable(l.databaseMetadata, databaseName, tableName, referTable)
return
}
table, err := schema.CreateTable(tableName)
if err != nil {
- l.err = &catalogutil.WalkThroughError{Code: code.TableExists, Content: err.Error()}
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
return
}
@@ -167,24 +182,32 @@ func (l *mysqlListener) EnterCreateTable(ctx *mysql.CreateTableContext) {
}
if mysqlparser.IsAutoIncrement(tableElement.ColumnDefinition().FieldDefinition()) {
if hasAutoIncrement {
- l.err = &catalogutil.WalkThroughError{
- Code: code.AutoIncrementExists,
- // The content comes from MySQL error content.
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.AutoIncrementExists.Int32(),
+ Title: fmt.Sprintf("There can be only one auto column for table `%s`", table.GetProto().Name),
Content: fmt.Sprintf("There can be only one auto column for table `%s`", table.GetProto().Name),
+ StartPosition: &storepb.Position{
+ Line: int32(l.baseLine + tableElement.GetStart().GetLine()),
+ },
}
}
hasAutoIncrement = true
}
_, _, columnName := mysqlparser.NormalizeMySQLColumnName(tableElement.ColumnDefinition().ColumnName())
- if err := mysqlCreateColumn(table, columnName, tableElement.ColumnDefinition().FieldDefinition(), nil /* position */); err != nil {
- err.Line = l.baseLine + tableElement.GetStart().GetLine()
- l.err = err
+ if advice := mysqlCreateColumn(table, columnName, tableElement.ColumnDefinition().FieldDefinition(), nil /* position */); advice != nil {
+ if advice.StartPosition.Line == 0 {
+ advice.StartPosition.Line = int32(l.baseLine + tableElement.GetStart().GetLine())
+ }
+ l.advice = advice
return
}
case tableElement.TableConstraintDef() != nil:
- if err := mysqlCreateConstraint(table, tableElement.TableConstraintDef()); err != nil {
- err.Line = tableElement.GetStart().GetLine()
- l.err = err
+ if advice := mysqlCreateConstraint(table, tableElement.TableConstraintDef()); advice != nil {
+ if advice.StartPosition.Line == 0 {
+ advice.StartPosition.Line = int32(tableElement.GetStart().GetLine())
+ }
+ l.advice = advice
return
}
default:
@@ -205,17 +228,23 @@ func (l *mysqlListener) EnterDropTable(ctx *mysql.DropTableContext) {
for _, tableRef := range ctx.TableRefList().AllTableRef() {
databaseName, tableName := mysqlparser.NormalizeMySQLTableRef(tableRef)
if databaseName != "" && !isCurrentDatabase(l.databaseMetadata, databaseName) {
- l.err = &catalogutil.WalkThroughError{
- Code: code.NotCurrentDatabase,
- Content: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, tableName),
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, tableName),
+ Content: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, tableName),
+ StartPosition: &storepb.Position{Line: 0},
}
}
schema := l.databaseMetadata.GetSchema("")
if schema == nil {
- l.err = &catalogutil.WalkThroughError{
- Code: code.SchemaNotExists,
- Content: "Schema does not exist",
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.SchemaNotExists.Int32(),
+ Title: "Schema does not exist",
+ Content: "Schema does not exist",
+ StartPosition: &storepb.Position{Line: 0},
}
return
}
@@ -225,16 +254,25 @@ func (l *mysqlListener) EnterDropTable(ctx *mysql.DropTableContext) {
if ctx.IfExists() != nil {
return
}
- l.err = &catalogutil.WalkThroughError{
- Code: code.TableNotExists,
- Content: fmt.Sprintf("Table `%s` does not exist", tableName),
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: fmt.Sprintf("Table `%s` does not exist", tableName),
+ Content: fmt.Sprintf("Table `%s` does not exist", tableName),
+ StartPosition: &storepb.Position{Line: 0},
}
return
}
// MySQL doesn't check view dependencies for DROP TABLE
if err := schema.DropTable(tableName); err != nil {
- l.err = &catalogutil.WalkThroughError{Code: code.TableNotExists, Content: err.Error()}
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
return
}
}
@@ -251,9 +289,9 @@ func (l *mysqlListener) EnterAlterTable(ctx *mysql.AlterTableContext) {
}
databaseName, tableName := mysqlparser.NormalizeMySQLTableRef(ctx.TableRef())
- table, err := mysqlFindTableState(l.databaseMetadata, databaseName, tableName)
- if err != nil {
- l.err = err
+ table, advice := mysqlFindTableState(l.databaseMetadata, databaseName, tableName)
+ if advice != nil {
+ l.advice = advice
return
}
@@ -302,8 +340,8 @@ func (l *mysqlListener) EnterAlterTable(ctx *mysql.AlterTableContext) {
// add single column.
case item.Identifier() != nil && item.FieldDefinition() != nil:
columnName := mysqlparser.NormalizeMySQLIdentifier(item.Identifier())
- if err := mysqlCreateColumn(table, columnName, item.FieldDefinition(), positionFromPlaceContext(item.Place())); err != nil {
- l.err = err
+ if advice := mysqlCreateColumn(table, columnName, item.FieldDefinition(), positionFromPlaceContext(item.Place())); advice != nil {
+ l.advice = advice
return
}
// add multi columns.
@@ -313,15 +351,15 @@ func (l *mysqlListener) EnterAlterTable(ctx *mysql.AlterTableContext) {
continue
}
_, _, columnName := mysqlparser.NormalizeMySQLColumnName(tableElement.ColumnDefinition().ColumnName())
- if err := mysqlCreateColumn(table, columnName, tableElement.ColumnDefinition().FieldDefinition(), nil); err != nil {
- l.err = err
+ if advice := mysqlCreateColumn(table, columnName, tableElement.ColumnDefinition().FieldDefinition(), nil); advice != nil {
+ l.advice = advice
return
}
}
// add constraint.
case item.TableConstraintDef() != nil:
- if err := mysqlCreateConstraint(table, item.TableConstraintDef()); err != nil {
- l.err = err
+ if advice := mysqlCreateConstraint(table, item.TableConstraintDef()); advice != nil {
+ l.advice = advice
return
}
default:
@@ -338,24 +376,48 @@ func (l *mysqlListener) EnterAlterTable(ctx *mysql.AlterTableContext) {
columnName := mysqlparser.NormalizeMySQLColumnInternalRef(item.ColumnInternalRef())
// Validate column exists
if table.GetColumn(columnName) == nil {
- l.err = catalogutil.NewColumnNotExistsError(table.GetProto().Name, columnName)
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name),
+ Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: 0},
+ }
return
}
if err := table.DropColumn(columnName); err != nil {
- l.err = &catalogutil.WalkThroughError{Code: code.Internal, Content: fmt.Sprintf("failed to drop column: %v", err)}
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: fmt.Sprintf("failed to drop column: %v", err),
+ Content: fmt.Sprintf("failed to drop column: %v", err),
+ StartPosition: &storepb.Position{Line: 0},
+ }
return
}
// drop primary key.
case item.PRIMARY_SYMBOL() != nil && item.KEY_SYMBOL() != nil:
if err := table.DropIndex(PrimaryKeyName); err != nil {
- l.err = &catalogutil.WalkThroughError{Code: code.IndexNotExists, Content: err.Error()}
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
return
}
// drop key/index.
case item.KeyOrIndex() != nil && item.IndexRef() != nil:
_, _, indexName := mysqlparser.NormalizeIndexRef(item.IndexRef())
if err := table.DropIndex(indexName); err != nil {
- l.err = &catalogutil.WalkThroughError{Code: code.IndexNotExists, Content: err.Error()}
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
return
}
default:
@@ -364,16 +426,16 @@ func (l *mysqlListener) EnterAlterTable(ctx *mysql.AlterTableContext) {
// modify column.
case item.MODIFY_SYMBOL() != nil && item.ColumnInternalRef() != nil:
columnName := mysqlparser.NormalizeMySQLColumnInternalRef(item.ColumnInternalRef())
- if err := mysqlChangeColumn(table, columnName, columnName, item.FieldDefinition(), positionFromPlaceContext(item.Place())); err != nil {
- l.err = err
+ if advice := mysqlChangeColumn(table, columnName, columnName, item.FieldDefinition(), positionFromPlaceContext(item.Place())); advice != nil {
+ l.advice = advice
return
}
// change column
case item.CHANGE_SYMBOL() != nil && item.ColumnInternalRef() != nil && item.Identifier() != nil:
oldColumnName := mysqlparser.NormalizeMySQLColumnInternalRef(item.ColumnInternalRef())
newColumnName := mysqlparser.NormalizeMySQLIdentifier(item.Identifier())
- if err := mysqlChangeColumn(table, oldColumnName, newColumnName, item.FieldDefinition(), positionFromPlaceContext(item.Place())); err != nil {
- l.err = err
+ if advice := mysqlChangeColumn(table, oldColumnName, newColumnName, item.FieldDefinition(), positionFromPlaceContext(item.Place())); advice != nil {
+ l.advice = advice
return
}
// rename column
@@ -382,34 +444,49 @@ func (l *mysqlListener) EnterAlterTable(ctx *mysql.AlterTableContext) {
newColumnName := mysqlparser.NormalizeMySQLIdentifier(item.Identifier())
// Validate old column exists
if table.GetColumn(oldColumnName) == nil {
- l.err = catalogutil.NewColumnNotExistsError(table.GetProto().Name, oldColumnName)
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` does not exist in table `%s`", oldColumnName, table.GetProto().Name),
+ Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", oldColumnName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: 0},
+ }
return
}
// Validate new column doesn't already exist
if table.GetColumn(newColumnName) != nil {
- l.err = &catalogutil.WalkThroughError{
- Code: code.ColumnExists,
- Content: fmt.Sprintf("Column `%s` already exists in table `%s`", newColumnName, table.GetProto().Name),
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` already exists in table `%s`", newColumnName, table.GetProto().Name),
+ Content: fmt.Sprintf("Column `%s` already exists in table `%s`", newColumnName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: 0},
}
return
}
if err := table.RenameColumn(oldColumnName, newColumnName); err != nil {
- l.err = &catalogutil.WalkThroughError{Code: code.Internal, Content: fmt.Sprintf("failed to rename column: %v", err)}
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: fmt.Sprintf("failed to rename column: %v", err),
+ Content: fmt.Sprintf("failed to rename column: %v", err),
+ StartPosition: &storepb.Position{Line: 0},
+ }
return
}
case item.ALTER_SYMBOL() != nil:
switch {
// alter column.
case item.ColumnInternalRef() != nil:
- if err := mysqlAlterColumn(table, item); err != nil {
- l.err = err
+ if advice := mysqlAlterColumn(table, item); advice != nil {
+ l.advice = advice
return
}
// alter index visibility.
case item.INDEX_SYMBOL() != nil && item.IndexRef() != nil && item.Visibility() != nil:
_, _, indexName := mysqlparser.NormalizeIndexRef(item.IndexRef())
- if err := mysqlChangeIndexVisibility(table, indexName, item.Visibility()); err != nil {
- l.err = err
+ if advice := mysqlChangeIndexVisibility(table, indexName, item.Visibility()); advice != nil {
+ l.advice = advice
return
}
default:
@@ -419,14 +496,23 @@ func (l *mysqlListener) EnterAlterTable(ctx *mysql.AlterTableContext) {
_, newTableName := mysqlparser.NormalizeMySQLTableName(item.TableName())
schema := l.databaseMetadata.GetSchema("")
if schema == nil {
- l.err = &catalogutil.WalkThroughError{
- Code: code.SchemaNotExists,
- Content: "Schema does not exist",
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.SchemaNotExists.Int32(),
+ Title: "Schema does not exist",
+ Content: "Schema does not exist",
+ StartPosition: &storepb.Position{Line: 0},
}
return
}
if err := schema.RenameTable(table.GetProto().Name, newTableName); err != nil {
- l.err = &catalogutil.WalkThroughError{Code: code.TableNotExists, Content: err.Error()}
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
return
}
// rename index.
@@ -434,7 +520,13 @@ func (l *mysqlListener) EnterAlterTable(ctx *mysql.AlterTableContext) {
_, _, oldIndexName := mysqlparser.NormalizeIndexRef(item.IndexRef())
newIndexName := mysqlparser.NormalizeIndexName(item.IndexName())
if err := table.RenameIndex(oldIndexName, newIndexName); err != nil {
- l.err = &catalogutil.WalkThroughError{Code: code.IndexNotExists, Content: err.Error()}
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
return
}
default:
@@ -452,9 +544,9 @@ func (l *mysqlListener) EnterDropIndex(ctx *mysql.DropIndexContext) {
return
}
databaseName, tableName := mysqlparser.NormalizeMySQLTableRef(ctx.TableRef())
- table, err := mysqlFindTableState(l.databaseMetadata, databaseName, tableName)
- if err != nil {
- l.err = err
+ table, advice := mysqlFindTableState(l.databaseMetadata, databaseName, tableName)
+ if advice != nil {
+ l.advice = advice
return
}
@@ -464,7 +556,13 @@ func (l *mysqlListener) EnterDropIndex(ctx *mysql.DropIndexContext) {
_, _, indexName := mysqlparser.NormalizeIndexRef(ctx.IndexRef())
if err := table.DropIndex(indexName); err != nil {
- l.err = &catalogutil.WalkThroughError{Code: code.IndexNotExists, Content: err.Error()}
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
}
@@ -476,9 +574,9 @@ func (l *mysqlListener) EnterCreateIndex(ctx *mysql.CreateIndexContext) {
return
}
databaseName, tableName := mysqlparser.NormalizeMySQLTableRef(ctx.CreateIndexTarget().TableRef())
- table, err := mysqlFindTableState(l.databaseMetadata, databaseName, tableName)
- if err != nil {
- l.err = err
+ table, advice := mysqlFindTableState(l.databaseMetadata, databaseName, tableName)
+ if advice != nil {
+ l.advice = advice
return
}
@@ -514,14 +612,14 @@ func (l *mysqlListener) EnterCreateIndex(ctx *mysql.CreateIndexContext) {
if ctx.CreateIndexTarget() == nil || ctx.CreateIndexTarget().KeyListVariants() == nil {
return
}
- if err := mysqlValidateKeyListVariants(table, ctx.CreateIndexTarget().KeyListVariants(), false /* primary */, isSpatial); err != nil {
- l.err = err
+ if advice := mysqlValidateKeyListVariants(table, ctx.CreateIndexTarget().KeyListVariants(), false /* primary */, isSpatial); advice != nil {
+ l.advice = advice
return
}
columnList := mysqlparser.NormalizeKeyListVariants(ctx.CreateIndexTarget().KeyListVariants())
- if err := mysqlCreateIndex(table, indexName, columnList, unique, tp, mysql.NewEmptyTableConstraintDefContext(), ctx); err != nil {
- l.err = err
+ if advice := mysqlCreateIndex(table, indexName, columnList, unique, tp, mysql.NewEmptyTableConstraintDefContext(), ctx); advice != nil {
+ l.advice = advice
return
}
}
@@ -534,7 +632,13 @@ func (l *mysqlListener) EnterAlterDatabase(ctx *mysql.AlterDatabaseContext) {
if ctx.SchemaRef() != nil {
databaseName := mysqlparser.NormalizeMySQLSchemaRef(ctx.SchemaRef())
if !isCurrentDatabase(l.databaseMetadata, databaseName) {
- l.err = catalogutil.NewAccessOtherDatabaseError(l.databaseMetadata.DatabaseName(), databaseName)
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, l.databaseMetadata.DatabaseName()),
+ Content: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, l.databaseMetadata.DatabaseName()),
+ StartPosition: &storepb.Position{Line: 0},
+ }
return
}
}
@@ -568,7 +672,13 @@ func (l *mysqlListener) EnterDropDatabase(ctx *mysql.DropDatabaseContext) {
databaseName := mysqlparser.NormalizeMySQLSchemaRef(ctx.SchemaRef())
if !isCurrentDatabase(l.databaseMetadata, databaseName) {
- l.err = catalogutil.NewAccessOtherDatabaseError(l.databaseMetadata.DatabaseName(), databaseName)
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, l.databaseMetadata.DatabaseName()),
+ Content: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, l.databaseMetadata.DatabaseName()),
+ StartPosition: &storepb.Position{Line: 0},
+ }
return
}
@@ -584,7 +694,13 @@ func (l *mysqlListener) EnterCreateDatabase(ctx *mysql.CreateDatabaseContext) {
return
}
databaseName := mysqlparser.NormalizeMySQLSchemaName(ctx.SchemaName())
- l.err = catalogutil.NewAccessOtherDatabaseError(l.databaseMetadata.DatabaseName(), databaseName)
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, l.databaseMetadata.DatabaseName()),
+ Content: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, l.databaseMetadata.DatabaseName()),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
// EnterRenameTableStatement is called when production renameTableStatement is entered.
@@ -595,9 +711,12 @@ func (l *mysqlListener) EnterRenameTableStatement(ctx *mysql.RenameTableStatemen
for _, pair := range ctx.AllRenamePair() {
schema := l.databaseMetadata.GetSchema("")
if schema == nil {
- l.err = &catalogutil.WalkThroughError{
- Code: code.SchemaNotExists,
- Content: "Schema does not exist",
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.SchemaNotExists.Int32(),
+ Title: "Schema does not exist",
+ Content: "Schema does not exist",
+ StartPosition: &storepb.Position{Line: 0},
}
return
}
@@ -610,28 +729,64 @@ func (l *mysqlListener) EnterRenameTableStatement(ctx *mysql.RenameTableStatemen
return
}
if schema.GetTable(oldTableName) == nil {
- l.err = catalogutil.NewTableNotExistsError(oldTableName)
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: fmt.Sprintf("Table `%s` does not exist", oldTableName),
+ Content: fmt.Sprintf("Table `%s` does not exist", oldTableName),
+ StartPosition: &storepb.Position{Line: 0},
+ }
return
}
if schema.GetTable(newTableName) != nil {
- l.err = catalogutil.NewTableExistsError(newTableName)
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableExists.Int32(),
+ Title: fmt.Sprintf("Table `%s` already exists", newTableName),
+ Content: fmt.Sprintf("Table `%s` already exists", newTableName),
+ StartPosition: &storepb.Position{Line: 0},
+ }
return
}
if err := schema.RenameTable(oldTableName, newTableName); err != nil {
- l.err = &catalogutil.WalkThroughError{Code: code.Internal, Content: err.Error()}
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
return
}
} else if mysqlMoveToOtherDatabase(l.databaseMetadata, pair) {
if schema.GetTable(oldTableName) == nil {
- l.err = catalogutil.NewTableNotExistsError(oldTableName)
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: fmt.Sprintf("Table `%s` does not exist", oldTableName),
+ Content: fmt.Sprintf("Table `%s` does not exist", oldTableName),
+ StartPosition: &storepb.Position{Line: 0},
+ }
return
}
if err := schema.DropTable(oldTableName); err != nil {
- l.err = &catalogutil.WalkThroughError{Code: code.TableNotExists, Content: err.Error()}
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
return
}
} else {
- l.err = catalogutil.NewAccessOtherDatabaseError(l.databaseMetadata.DatabaseName(), mysqlTargetDatabase(l.databaseMetadata, pair))
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: fmt.Sprintf("Database `%s` is not the current database `%s`", mysqlTargetDatabase(l.databaseMetadata, pair), l.databaseMetadata.DatabaseName()),
+ Content: fmt.Sprintf("Database `%s` is not the current database `%s`", mysqlTargetDatabase(l.databaseMetadata, pair), l.databaseMetadata.DatabaseName()),
+ StartPosition: &storepb.Position{Line: 0},
+ }
return
}
}
@@ -650,9 +805,9 @@ func (l *mysqlListener) EnterCreateTrigger(ctx *mysql.CreateTriggerContext) {
return
}
databaseName, tableName := mysqlparser.NormalizeMySQLTableRef(ctx.TableRef())
- _, err := mysqlFindTableState(l.databaseMetadata, databaseName, tableName)
- if err != nil {
- l.err = err
+ _, advice := mysqlFindTableState(l.databaseMetadata, databaseName, tableName)
+ if advice != nil {
+ l.advice = advice
return
}
}
@@ -707,10 +862,16 @@ func mysqlTheCurrentDatabase(d *model.DatabaseMetadata, renamePair mysql.IRename
return true
}
-func mysqlChangeIndexVisibility(table *model.TableMetadata, indexName string, visibility mysql.IVisibilityContext) *catalogutil.WalkThroughError {
+func mysqlChangeIndexVisibility(table *model.TableMetadata, indexName string, visibility mysql.IVisibilityContext) *storepb.Advice {
index := table.GetIndex(indexName)
if index == nil {
- return catalogutil.NewIndexNotExistsError(table.GetProto().Name, indexName)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexNotExists.Int32(),
+ Title: fmt.Sprintf("Index `%s` does not exist in table `%s`", indexName, table.GetProto().Name),
+ Content: fmt.Sprintf("Index `%s` does not exist in table `%s`", indexName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
indexProto := index.GetProto()
switch {
@@ -724,7 +885,7 @@ func mysqlChangeIndexVisibility(table *model.TableMetadata, indexName string, vi
return nil
}
-func mysqlAlterColumn(table *model.TableMetadata, itemDef mysql.IAlterListItemContext) *catalogutil.WalkThroughError {
+func mysqlAlterColumn(table *model.TableMetadata, itemDef mysql.IAlterListItemContext) *storepb.Advice {
if itemDef.ColumnInternalRef() == nil {
// should not reach here.
return nil
@@ -732,7 +893,13 @@ func mysqlAlterColumn(table *model.TableMetadata, itemDef mysql.IAlterListItemCo
columnName := mysqlparser.NormalizeMySQLColumnInternalRef(itemDef.ColumnInternalRef())
col := table.GetColumn(columnName)
if col == nil {
- return catalogutil.NewColumnNotExistsError(table.GetProto().Name, columnName)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name),
+ Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
switch {
@@ -747,10 +914,12 @@ func mysqlAlterColumn(table *model.TableMetadata, itemDef mysql.IAlterListItemCo
"text", "tinytext", "mediumtext", "longtext",
"json",
"geometry":
- return &catalogutil.WalkThroughError{
- Code: code.InvalidColumnDefault,
- // Content comes from MySQL Error content.
- Content: fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName),
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.InvalidColumnDefault.Int32(),
+ Title: fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName),
+ Content: fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName),
+ StartPosition: &storepb.Position{Line: 0},
}
default:
// Other column types allow default values
@@ -770,10 +939,12 @@ func mysqlAlterColumn(table *model.TableMetadata, itemDef mysql.IAlterListItemCo
col.Default = defaultValue
} else {
if !col.Nullable {
- return &catalogutil.WalkThroughError{
- Code: code.SetNullDefaultForNotNullColumn,
- // Content comes from MySQL Error content.
- Content: fmt.Sprintf("Invalid default value for column `%s`", columnName),
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.SetNullDefaultForNotNullColumn.Int32(),
+ Title: fmt.Sprintf("Invalid default value for column `%s`", columnName),
+ Content: fmt.Sprintf("Invalid default value for column `%s`", columnName),
+ StartPosition: &storepb.Position{Line: 0},
}
}
@@ -796,23 +967,38 @@ func mysqlAlterColumn(table *model.TableMetadata, itemDef mysql.IAlterListItemCo
// 1. rename column if name changed
// 2. update column properties from fieldDef
// 3. handle position changes by reordering columns in the table
-func mysqlChangeColumn(table *model.TableMetadata, oldColumnName string, newColumnName string, fieldDef mysql.IFieldDefinitionContext, position *mysqlColumnPosition) *catalogutil.WalkThroughError {
+func mysqlChangeColumn(table *model.TableMetadata, oldColumnName string, newColumnName string, fieldDef mysql.IFieldDefinitionContext, position *mysqlColumnPosition) *storepb.Advice {
column := table.GetColumn(oldColumnName)
if column == nil {
- return catalogutil.NewColumnNotExistsError(table.GetProto().Name, oldColumnName)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` does not exist in table `%s`", oldColumnName, table.GetProto().Name),
+ Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", oldColumnName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
// If renaming, validate and use RenameColumn
if oldColumnName != newColumnName {
// Validate new column doesn't already exist
if table.GetColumn(newColumnName) != nil {
- return &catalogutil.WalkThroughError{
- Code: code.ColumnExists,
- Content: fmt.Sprintf("Column `%s` already exists in table `%s`", newColumnName, table.GetProto().Name),
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` already exists in table `%s`", newColumnName, table.GetProto().Name),
+ Content: fmt.Sprintf("Column `%s` already exists in table `%s`", newColumnName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: 0},
}
}
if err := table.RenameColumn(oldColumnName, newColumnName); err != nil {
- return &catalogutil.WalkThroughError{Code: code.Internal, Content: fmt.Sprintf("failed to rename column: %v", err)}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: fmt.Sprintf("failed to rename column: %v", err),
+ Content: fmt.Sprintf("failed to rename column: %v", err),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
// Get the renamed column
column = table.GetColumn(newColumnName)
@@ -932,24 +1118,33 @@ func positionFromPlaceContext(place mysql.IPlaceContext) *mysqlColumnPosition {
return columnPosition
}
-func mysqlCopyTable(d *model.DatabaseMetadata, databaseName, tableName, referTable string) *catalogutil.WalkThroughError {
- targetTable, err := mysqlFindTableState(d, databaseName, referTable)
- if err != nil {
- return err
+func mysqlCopyTable(d *model.DatabaseMetadata, databaseName, tableName, referTable string) *storepb.Advice {
+ targetTable, advice := mysqlFindTableState(d, databaseName, referTable)
+ if advice != nil {
+ return advice
}
schema := d.GetSchema("")
if schema == nil {
- return &catalogutil.WalkThroughError{
- Code: code.SchemaNotExists,
- Content: "Schema does not exist",
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.SchemaNotExists.Int32(),
+ Title: "Schema does not exist",
+ Content: "Schema does not exist",
+ StartPosition: &storepb.Position{Line: 0},
}
}
// Create the new table
newTable, createErr := schema.CreateTable(tableName)
if createErr != nil {
- return &catalogutil.WalkThroughError{Code: code.TableExists, Content: createErr.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableExists.Int32(),
+ Title: createErr.Error(),
+ Content: createErr.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
// Copy table properties
@@ -963,10 +1158,22 @@ func mysqlCopyTable(d *model.DatabaseMetadata, databaseName, tableName, referTab
for _, col := range targetTable.GetColumns() {
colCopy, ok := proto.Clone(col).(*storepb.ColumnMetadata)
if !ok {
- return &catalogutil.WalkThroughError{Code: code.Internal, Content: "failed to clone column metadata"}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: "failed to clone column metadata",
+ Content: "failed to clone column metadata",
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
if err := newTable.CreateColumn(colCopy); err != nil {
- return &catalogutil.WalkThroughError{Code: code.ColumnExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
}
@@ -974,38 +1181,65 @@ func mysqlCopyTable(d *model.DatabaseMetadata, databaseName, tableName, referTab
for _, idx := range targetProto.Indexes {
idxCopy, ok := proto.Clone(idx).(*storepb.IndexMetadata)
if !ok {
- return &catalogutil.WalkThroughError{Code: code.Internal, Content: "failed to clone index metadata"}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: "failed to clone index metadata",
+ Content: "failed to clone index metadata",
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
if err := newTable.CreateIndex(idxCopy); err != nil {
- return &catalogutil.WalkThroughError{Code: code.IndexExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
}
return nil
}
-func mysqlFindTableState(d *model.DatabaseMetadata, databaseName, tableName string) (*model.TableMetadata, *catalogutil.WalkThroughError) {
+func mysqlFindTableState(d *model.DatabaseMetadata, databaseName, tableName string) (*model.TableMetadata, *storepb.Advice) {
if databaseName != "" && !isCurrentDatabase(d, databaseName) {
- return nil, catalogutil.NewAccessOtherDatabaseError(d.DatabaseName(), databaseName)
+ return nil, &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, d.DatabaseName()),
+ Content: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, d.DatabaseName()),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
schema := d.GetSchema("")
if schema == nil {
- return nil, &catalogutil.WalkThroughError{
- Code: code.SchemaNotExists,
- Content: "Schema does not exist",
+ return nil, &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.SchemaNotExists.Int32(),
+ Title: "Schema does not exist",
+ Content: "Schema does not exist",
+ StartPosition: &storepb.Position{Line: 0},
}
}
table := schema.GetTable(tableName)
if table == nil {
- return nil, catalogutil.NewTableNotExistsError(tableName)
+ return nil, &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: fmt.Sprintf("Table `%s` does not exist", tableName),
+ Content: fmt.Sprintf("Table `%s` does not exist", tableName),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
return table, nil
}
-func mysqlCreateConstraint(table *model.TableMetadata, constraintDef mysql.ITableConstraintDefContext) *catalogutil.WalkThroughError {
+func mysqlCreateConstraint(table *model.TableMetadata, constraintDef mysql.ITableConstraintDefContext) *storepb.Advice {
if constraintDef.GetType_() != nil {
switch constraintDef.GetType_().GetTokenType() {
// PRIMARY KEY.
@@ -1090,7 +1324,7 @@ func mysqlCreateConstraint(table *model.TableMetadata, constraintDef mysql.ITabl
}
// mysqlValidateKeyListVariants validates the key list variants.
-func mysqlValidateKeyListVariants(table *model.TableMetadata, keyList mysql.IKeyListVariantsContext, primary bool, isSpatial bool) *catalogutil.WalkThroughError {
+func mysqlValidateKeyListVariants(table *model.TableMetadata, keyList mysql.IKeyListVariantsContext, primary bool, isSpatial bool) *storepb.Advice {
if keyList.KeyList() != nil {
columns := mysqlparser.NormalizeKeyList(keyList.KeyList())
if err := mysqlValidateColumnList(table, columns, primary, isSpatial); err != nil {
@@ -1106,20 +1340,28 @@ func mysqlValidateKeyListVariants(table *model.TableMetadata, keyList mysql.IKey
return nil
}
-func mysqlValidateColumnList(table *model.TableMetadata, columnList []string, primary bool, isSpatial bool) *catalogutil.WalkThroughError {
+func mysqlValidateColumnList(table *model.TableMetadata, columnList []string, primary bool, isSpatial bool) *storepb.Advice {
for _, columnName := range columnList {
column := table.GetColumn(columnName)
if column == nil {
- return catalogutil.NewColumnNotExistsError(table.GetProto().Name, columnName)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name),
+ Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
if primary {
column.Nullable = false
}
if isSpatial && column.Nullable {
- return &catalogutil.WalkThroughError{
- Code: code.SpatialIndexKeyNullable,
- // 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 &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.SpatialIndexKeyNullable.Int32(),
+ Title: fmt.Sprintf("All parts of a SPATIAL index must be NOT NULL, but `%s` is nullable", column.Name),
+ Content: fmt.Sprintf("All parts of a SPATIAL index must be NOT NULL, but `%s` is nullable", column.Name),
+ StartPosition: &storepb.Position{Line: 0},
}
}
}
@@ -1128,7 +1370,7 @@ func mysqlValidateColumnList(table *model.TableMetadata, columnList []string, pr
// mysqlValidateExpressionList validates the expression list.
// TODO: update expression validation.
-func mysqlValidateExpressionList(table *model.TableMetadata, expressionList []string, primary bool, isSpatial bool) *catalogutil.WalkThroughError {
+func mysqlValidateExpressionList(table *model.TableMetadata, expressionList []string, primary bool, isSpatial bool) *storepb.Advice {
for _, expression := range expressionList {
column := table.GetColumn(expression)
// If expression is not a column, we do not need to validate it.
@@ -1140,10 +1382,12 @@ func mysqlValidateExpressionList(table *model.TableMetadata, expressionList []st
column.Nullable = false
}
if isSpatial && column.Nullable {
- return &catalogutil.WalkThroughError{
- Code: code.SpatialIndexKeyNullable,
- // 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 &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.SpatialIndexKeyNullable.Int32(),
+ Title: fmt.Sprintf("All parts of a SPATIAL index must be NOT NULL, but `%s` is nullable", column.Name),
+ Content: fmt.Sprintf("All parts of a SPATIAL index must be NOT NULL, but `%s` is nullable", column.Name),
+ StartPosition: &storepb.Position{Line: 0},
}
}
}
@@ -1188,11 +1432,14 @@ func mysqlGetIndexType(tableConstraint mysql.ITableConstraintDefContext) string
return "BTREE"
}
-func mysqlCreateColumn(table *model.TableMetadata, columnName string, fieldDef mysql.IFieldDefinitionContext, position *mysqlColumnPosition) *catalogutil.WalkThroughError {
+func mysqlCreateColumn(table *model.TableMetadata, columnName string, fieldDef mysql.IFieldDefinitionContext, position *mysqlColumnPosition) *storepb.Advice {
if table.GetColumn(columnName) != nil {
- return &catalogutil.WalkThroughError{
- Code: code.ColumnExists,
- Content: fmt.Sprintf("Column `%s` already exists in table `%s`", columnName, table.GetProto().Name),
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` already exists in table `%s`", columnName, table.GetProto().Name),
+ Content: fmt.Sprintf("Column `%s` already exists in table `%s`", columnName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: 0},
}
}
@@ -1261,9 +1508,12 @@ func mysqlCreateColumn(table *model.TableMetadata, columnName string, fieldDef m
continue
}
if !mysqlparser.IsTimeType(fieldDef.DataType()) {
- return &catalogutil.WalkThroughError{
- Code: code.OnUpdateColumnNotDatetimeOrTimestamp,
- Content: fmt.Sprintf("Column `%s` use ON UPDATE but is not DATETIME or TIMESTAMP", col.Name),
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.OnUpdateColumnNotDatetimeOrTimestamp.Int32(),
+ Title: fmt.Sprintf("Column `%s` use ON UPDATE but is not DATETIME or TIMESTAMP", col.Name),
+ Content: fmt.Sprintf("Column `%s` use ON UPDATE but is not DATETIME or TIMESTAMP", col.Name),
+ StartPosition: &storepb.Position{Line: 0},
}
}
// primary key.
@@ -1296,15 +1546,23 @@ func mysqlCreateColumn(table *model.TableMetadata, columnName string, fieldDef m
}
if !col.Nullable && setNullDefault {
- return &catalogutil.WalkThroughError{
- Code: code.SetNullDefaultForNotNullColumn,
- // Content comes from MySQL Error content.
- Content: fmt.Sprintf("Invalid default value for column `%s`", col.Name),
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.SetNullDefaultForNotNullColumn.Int32(),
+ Title: fmt.Sprintf("Invalid default value for column `%s`", col.Name),
+ Content: fmt.Sprintf("Invalid default value for column `%s`", col.Name),
+ StartPosition: &storepb.Position{Line: 0},
}
}
if err := table.CreateColumn(col); err != nil {
- return &catalogutil.WalkThroughError{Code: code.ColumnExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
// Handle position by reordering columns in the proto
@@ -1356,17 +1614,26 @@ func mysqlCreateColumn(table *model.TableMetadata, columnName string, fieldDef m
return nil
}
-func mysqlCreateIndex(table *model.TableMetadata, name string, keyList []string, unique bool, tp string, tableConstraint mysql.ITableConstraintDefContext, createIndexDef mysql.ICreateIndexContext) *catalogutil.WalkThroughError {
+func mysqlCreateIndex(table *model.TableMetadata, name string, keyList []string, unique bool, tp string, tableConstraint mysql.ITableConstraintDefContext, createIndexDef mysql.ICreateIndexContext) *storepb.Advice {
if len(keyList) == 0 {
- return &catalogutil.WalkThroughError{
- Code: code.IndexEmptyKeys,
- Content: fmt.Sprintf("Index `%s` in table `%s` has empty key", name, table.GetProto().Name),
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexEmptyKeys.Int32(),
+ Title: fmt.Sprintf("Index `%s` in table `%s` has empty key", name, table.GetProto().Name),
+ Content: fmt.Sprintf("Index `%s` in table `%s` has empty key", name, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: 0},
}
}
// construct a index name if name is empty.
if name != "" {
if table.GetIndex(name) != nil {
- return catalogutil.NewIndexExistsError(table.GetProto().Name, name)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexExists.Int32(),
+ Title: fmt.Sprintf("Index `%s` already exists in table `%s`", name, table.GetProto().Name),
+ Content: fmt.Sprintf("Index `%s` already exists in table `%s`", name, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
} else {
suffix := 1
@@ -1452,16 +1719,25 @@ func mysqlCreateIndex(table *model.TableMetadata, name string, keyList []string,
}
if err := table.CreateIndex(index); err != nil {
- return &catalogutil.WalkThroughError{Code: code.IndexExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
return nil
}
-func mysqlCreatePrimaryKey(table *model.TableMetadata, keys []string, tp string) *catalogutil.WalkThroughError {
+func mysqlCreatePrimaryKey(table *model.TableMetadata, keys []string, tp string) *storepb.Advice {
if table.GetPrimaryKey() != nil {
- return &catalogutil.WalkThroughError{
- Code: code.PrimaryKeyExists,
- Content: fmt.Sprintf("Primary key exists in table `%s`", table.GetProto().Name),
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.PrimaryKeyExists.Int32(),
+ Title: fmt.Sprintf("Primary key exists in table `%s`", table.GetProto().Name),
+ Content: fmt.Sprintf("Primary key exists in table `%s`", table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: 0},
}
}
@@ -1474,12 +1750,18 @@ func mysqlCreatePrimaryKey(table *model.TableMetadata, keys []string, tp string)
Visible: true,
}
if err := table.CreateIndex(pk); err != nil {
- return &catalogutil.WalkThroughError{Code: code.PrimaryKeyExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.PrimaryKeyExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
return nil
}
-func mysqlCheckDefault(_ *model.TableMetadata, columnName string, fieldDefinition mysql.IFieldDefinitionContext) *catalogutil.WalkThroughError {
+func mysqlCheckDefault(_ *model.TableMetadata, columnName string, fieldDefinition mysql.IFieldDefinitionContext) *storepb.Advice {
if fieldDefinition.DataType() == nil || fieldDefinition.DataType().GetType_() == nil {
return nil
}
@@ -1504,10 +1786,12 @@ func mysqlCheckDefault(_ *model.TableMetadata, columnName string, fieldDefinitio
mysql.MySQLParserMULTILINESTRING_SYMBOL,
mysql.MySQLParserPOLYGON_SYMBOL,
mysql.MySQLParserMULTIPOLYGON_SYMBOL:
- return &catalogutil.WalkThroughError{
- Code: code.InvalidColumnDefault,
- // Content comes from MySQL Error content.
- Content: fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName),
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.InvalidColumnDefault.Int32(),
+ Title: fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName),
+ Content: fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName),
+ StartPosition: &storepb.Position{Line: 0},
}
default:
// Other data types are allowed to have default values
@@ -1516,7 +1800,7 @@ func mysqlCheckDefault(_ *model.TableMetadata, columnName string, fieldDefinitio
return checkDefaultConvert(columnName, fieldDefinition)
}
-func checkDefaultConvert(columnName string, fieldDefinition mysql.IFieldDefinitionContext) *catalogutil.WalkThroughError {
+func checkDefaultConvert(columnName string, fieldDefinition mysql.IFieldDefinitionContext) *storepb.Advice {
if fieldDefinition == nil {
return nil
}
@@ -1546,14 +1830,16 @@ func checkDefaultConvert(columnName string, fieldDefinition mysql.IFieldDefiniti
return nil
}
-func checkDefault(columnName string, columnType *types.FieldType, value tidbast.ExprNode) *catalogutil.WalkThroughError {
+func checkDefault(columnName string, columnType *types.FieldType, value tidbast.ExprNode) *storepb.Advice {
if value.GetType().GetType() != mysqldriver.TypeNull {
switch columnType.GetType() {
case mysqldriver.TypeBlob, mysqldriver.TypeTinyBlob, mysqldriver.TypeMediumBlob, mysqldriver.TypeLongBlob, mysqldriver.TypeJSON, mysqldriver.TypeGeometry:
- return &catalogutil.WalkThroughError{
- Code: code.InvalidColumnDefault,
- // Content comes from MySQL Error content.
- Content: fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName),
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.InvalidColumnDefault.Int32(),
+ Title: fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName),
+ Content: fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName),
+ StartPosition: &storepb.Position{Line: 0},
}
default:
// Other column types allow default values
@@ -1563,9 +1849,12 @@ 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 &catalogutil.WalkThroughError{
- Code: code.InvalidColumnDefault,
- Content: err.Error(),
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.InvalidColumnDefault.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
}
}
}
diff --git a/backend/plugin/schema/mysql/walk_through_test.go b/backend/plugin/schema/mysql/walk_through_test.go
index 1760c812fa..d7d24b8755 100644
--- a/backend/plugin/schema/mysql/walk_through_test.go
+++ b/backend/plugin/schema/mysql/walk_through_test.go
@@ -15,7 +15,6 @@ import (
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/component/sheet"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/schema/catalogutil"
"github.com/bytebase/bytebase/backend/store/model"
)
@@ -24,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 *catalogutil.WalkThroughError
+ Advice *storepb.Advice
}
func TestWalkThrough(t *testing.T) {
@@ -53,14 +52,13 @@ func TestWalkThrough(t *testing.T) {
state := model.NewDatabaseMetadata(protoData, !test.IgnoreCaseSensitive, !test.IgnoreCaseSensitive)
asts, _ := sm.GetASTsForChecks(storepb.Engine_MYSQL, test.Statement)
- err := WalkThrough(state, asts)
- if err != nil {
- walkErr, yes := err.(*catalogutil.WalkThroughError)
- require.True(t, yes)
- require.Equal(t, test.Err, walkErr)
+ advice := WalkThrough(state, asts)
+ if advice != nil {
+ // Compare the advice fields
+ require.Equal(t, test.Advice.Code, advice.Code)
+ require.Equal(t, test.Advice.Content, advice.Content)
continue
}
- require.NoError(t, err, test.Statement)
// Skip comparison if want is empty (error cases)
if test.Want == "" {
@@ -68,7 +66,7 @@ func TestWalkThrough(t *testing.T) {
}
want := &storepb.DatabaseSchemaMetadata{}
- err = common.ProtojsonUnmarshaler.Unmarshal([]byte(test.Want), want)
+ err := common.ProtojsonUnmarshaler.Unmarshal([]byte(test.Want), want)
require.NoError(t, err)
// Sort proto for deterministic comparison
state.SortProto()
diff --git a/backend/plugin/schema/pg/testdata/walk_through.yaml b/backend/plugin/schema/pg/testdata/walk_through.yaml
index 2c41122a3e..e41246db1c 100644
--- a/backend/plugin/schema/pg/testdata/walk_through.yaml
+++ b/backend/plugin/schema/pg/testdata/walk_through.yaml
@@ -19,7 +19,7 @@
\ \"schema\": \"public\",\n \"table\": \"test\",\n \
\ \"column\": \"name\"\n }\n ]\n }\n \
\ ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: 'CREATE TABLE public.t(a int, "B" int);
CREATE INDEX ON t(a, "B");
@@ -53,7 +53,7 @@
\ \"schema\": \"public\",\n \"table\": \"test\",\n \
\ \"column\": \"name\"\n }\n ]\n }\n \
\ ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE public.t(\n a int primary key,\n b int NOT NULL DEFAULT\
\ 1,\n c int UNIQUE,\n UNIQUE (a, b, c),\n CONSTRAINT uk_a_b UNIQUE (a, b)\n\
)"
@@ -93,7 +93,7 @@
\ \"column\": \"id\"\n },\n {\n \"schema\"\
: \"public\",\n \"table\": \"test\",\n \"column\": \"\
name\"\n }\n ]\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE public.t(\n a int primary key,\n b int NOT NULL DEFAULT\
\ 1,\n c int UNIQUE,\n UNIQUE (a, b, c),\n CONSTRAINT uk_a_b UNIQUE (a, b)\n\
);\nALTER TABLE t rename to t1;\nALTER TABLE t1 rename column a to a1;\nalter\
@@ -135,7 +135,7 @@
\ \"schema\": \"public\",\n \"table\": \"test\",\n \
\ \"column\": \"name\"\n }\n ]\n }\n \
\ ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE public.t(\n a int primary key,\n b int NOT NULL DEFAULT\
\ 1,\n c int UNIQUE,\n UNIQUE (a, b, c),\n CONSTRAINT uk_a_b UNIQUE (a, b)\n\
);\nalter index uk_a_b rename to ukk_a_b;"
@@ -175,7 +175,7 @@
\ \"column\": \"id\"\n },\n {\n \"schema\"\
: \"public\",\n \"table\": \"test\",\n \"column\": \"\
name\"\n }\n ]\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE public.t(\n a int primary key,\n b int NOT NULL DEFAULT\
\ 1,\n c int UNIQUE,\n UNIQUE (a, b, c),\n CONSTRAINT uk_a_b UNIQUE (a, b)\n\
);\ndrop index uk_a_b;"
@@ -212,7 +212,7 @@
\ \"schema\": \"public\",\n \"table\": \"test\",\n \
\ \"column\": \"name\"\n }\n ]\n }\n \
\ ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE public.t(\n a int primary key,\n b int NOT NULL DEFAULT\
\ 1,\n c int UNIQUE,\n UNIQUE (a, b, c),\n CONSTRAINT uk_a_b UNIQUE (a, b)\n\
);\ndrop table t;"
@@ -230,36 +230,47 @@
\ \"column\": \"id\"\n },\n {\n \"schema\"\
: \"public\",\n \"table\": \"test\",\n \"column\": \"\
name\"\n }\n ]\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE public.t(\n a int primary key,\n b int NOT NULL DEFAULT\
\ 1,\n c int UNIQUE,\n UNIQUE (a, b, c),\n CONSTRAINT uk_a_b UNIQUE (a, b)\n\
);\ndrop schema public;"
ignore_case_sensitive: false
want: "{\n \"name\": \"postgres\"\n}"
- err: null
+ advice: null
- statement: ALTER TABLE test DROP COLUMN id;
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 421
+ title: 'Cannot drop column "id" in table "public"."test", it''s referenced by
+ view: "public"."v1"'
content: 'Cannot drop column "id" in table "public"."test", it''s referenced by
view: "public"."v1"'
- line: 1
+ startPosition:
+ line: 1
- statement: ALTER TABLE test ALTER COLUMN id TYPE varchar(20);
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 421
+ title: 'Cannot alter type of column "id" in table "public"."test", it''s referenced
+ by view: "public"."v1"'
content: 'Cannot alter type of column "id" in table "public"."test", it''s referenced
by view: "public"."v1"'
- line: 1
+ startPosition:
+ line: 1
- statement: DROP TABLE test;
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 609
+ title: 'Cannot drop table "public"."test", it''s referenced by view: "public"."v1"'
content: 'Cannot drop table "public"."test", it''s referenced by view: "public"."v1"'
- line: 1
+ startPosition:
+ line: 1
- statement: 'DROP VIEW v1;
ALTER TABLE test DROP COLUMN id;'
@@ -270,7 +281,7 @@
\ \"position\": 2,\n \"nullable\": true,\n \
\ \"type\": \"varchar(20)\"\n }\n ]\n }\n ]\n\
\ }\n ]\n}"
- err: null
+ advice: null
- statement: 'create view v1 as select * from t;
alter view v1 rename to this_is_view_del;
@@ -284,4 +295,4 @@
\ {\n \"name\": \"name\",\n \"position\"\
: 2,\n \"nullable\": true,\n \"type\": \"varchar(20)\"\
\n }\n ]\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
diff --git a/backend/plugin/schema/pg/walk_through.go b/backend/plugin/schema/pg/walk_through.go
index c38689d05c..e067c782d0 100644
--- a/backend/plugin/schema/pg/walk_through.go
+++ b/backend/plugin/schema/pg/walk_through.go
@@ -6,13 +6,11 @@ import (
"github.com/antlr4-go/antlr/v4"
parser "github.com/bytebase/parser/postgresql"
- "github.com/pkg/errors"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor/code"
pgparser "github.com/bytebase/bytebase/backend/plugin/parser/pg"
"github.com/bytebase/bytebase/backend/plugin/schema"
- "github.com/bytebase/bytebase/backend/plugin/schema/catalogutil"
"github.com/bytebase/bytebase/backend/store/model"
)
@@ -26,15 +24,31 @@ func init() {
}
// WalkThrough walks through the PostgreSQL ANTLR parse tree and builds catalog metadata.
-func WalkThrough(d *model.DatabaseMetadata, ast any) error {
+func WalkThrough(d *model.DatabaseMetadata, ast any) *storepb.Advice {
// ANTLR-based walkthrough
parseResult, ok := ast.(*pgparser.ParseResult)
if !ok {
- return errors.Errorf("PostgreSQL walk-through expects *pgparser.ParseResult, got %T", ast)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: fmt.Sprintf("PostgreSQL walk-through expects *pgparser.ParseResult, got %T", ast),
+ Content: fmt.Sprintf("PostgreSQL walk-through expects *pgparser.ParseResult, got %T", ast),
+ StartPosition: &storepb.Position{
+ Line: 0,
+ },
+ }
}
root, ok := parseResult.Tree.(parser.IRootContext)
if !ok {
- return errors.Errorf("invalid ANTLR tree type %T", parseResult.Tree)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: fmt.Sprintf("invalid ANTLR tree type %T", parseResult.Tree),
+ Content: fmt.Sprintf("invalid ANTLR tree type %T", parseResult.Tree),
+ StartPosition: &storepb.Position{
+ Line: 0,
+ },
+ }
}
// Build listener with database state
listener := &pgCatalogListener{
@@ -44,37 +58,23 @@ func WalkThrough(d *model.DatabaseMetadata, ast any) error {
// Walk through the parse tree
antlr.ParseTreeWalkerDefault.Walk(listener, root)
// Return any error encountered during walk
- if listener.err != nil {
- return listener.err
- }
- return nil
+ return listener.advice
}
// pgCatalogListener builds catalog state by listening to ANTLR parse tree events.
type pgCatalogListener struct {
*parser.BasePostgreSQLParserListener
databaseState *model.DatabaseMetadata
- err *catalogutil.WalkThroughError
+ advice *storepb.Advice
currentLine int
}
-// Helper method to set error with line number
-func (l *pgCatalogListener) setError(err *catalogutil.WalkThroughError) {
- if l.err != nil {
- return // Keep first error
- }
- if err != nil && err.Line == 0 {
- err.Line = l.currentLine
- }
- l.err = err
-}
-
// ========================================
// CREATE TABLE handling
// ========================================
// EnterCreatestmt handles CREATE TABLE statements.
func (l *pgCatalogListener) EnterCreatestmt(ctx *parser.CreatestmtContext) {
- if !isTopLevel(ctx.GetParent()) || l.err != nil {
+ if !isTopLevel(ctx.GetParent()) || l.advice != nil {
return
}
l.currentLine = ctx.GetStart().GetLine()
@@ -91,16 +91,21 @@ func (l *pgCatalogListener) EnterCreatestmt(ctx *parser.CreatestmtContext) {
// Check database name if specified
databaseName := extractDatabaseName(qualifiedNames[0])
if databaseName != "" && l.databaseState.DatabaseName() != databaseName {
- l.setError(&catalogutil.WalkThroughError{
- Code: code.NotCurrentDatabase,
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: fmt.Sprintf("Database %q is not the current database %q", databaseName, l.databaseState.DatabaseName()),
Content: fmt.Sprintf("Database %q is not the current database %q", databaseName, l.databaseState.DatabaseName()),
- })
+ StartPosition: &storepb.Position{
+ Line: int32(l.currentLine),
+ },
+ }
return
}
// Get or create schema
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName)
+ schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
if err != nil {
- l.setError(err)
+ l.advice = err
return
}
// Check if table already exists
@@ -110,16 +115,29 @@ func (l *pgCatalogListener) EnterCreatestmt(ctx *parser.CreatestmtContext) {
if ifNotExists {
return
}
- l.setError(&catalogutil.WalkThroughError{
- Code: code.TableExists,
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableExists.Int32(),
+ Title: fmt.Sprintf(`The table %q already exists in the schema %q`, tableName, schema.GetProto().Name),
Content: fmt.Sprintf(`The table %q already exists in the schema %q`, tableName, schema.GetProto().Name),
- })
+ StartPosition: &storepb.Position{
+ Line: int32(l.currentLine),
+ },
+ }
return
}
// Create table
table, createErr := schema.CreateTable(tableName)
if createErr != nil {
- l.setError(&catalogutil.WalkThroughError{Code: code.TableExists, Content: createErr.Error()})
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableExists.Int32(),
+ Title: createErr.Error(),
+ Content: createErr.Error(),
+ StartPosition: &storepb.Position{
+ Line: int32(l.currentLine),
+ },
+ }
return
}
// Process column definitions
@@ -129,14 +147,14 @@ func (l *pgCatalogListener) EnterCreatestmt(ctx *parser.CreatestmtContext) {
// Handle column definitions
if elem.ColumnDef() != nil {
if err := pgCreateColumn(schema, table, elem.ColumnDef()); err != nil {
- l.setError(err)
+ l.advice = err
return
}
}
// Handle table-level constraints
if elem.Tableconstraint() != nil {
- if err := createTableConstraint(schema, table, elem.Tableconstraint()); err != nil {
- l.setError(err)
+ if err := createTableConstraint(schema, table, elem.Tableconstraint(), l.currentLine); err != nil {
+ l.advice = err
return
}
}
@@ -145,7 +163,7 @@ func (l *pgCatalogListener) EnterCreatestmt(ctx *parser.CreatestmtContext) {
}
// pgCreateColumn creates a column in the table.
-func pgCreateColumn(schema *model.SchemaMetadata, table *model.TableMetadata, columnDef parser.IColumnDefContext) *catalogutil.WalkThroughError {
+func pgCreateColumn(schema *model.SchemaMetadata, table *model.TableMetadata, columnDef parser.IColumnDefContext) *storepb.Advice {
if columnDef == nil {
return nil
}
@@ -159,9 +177,14 @@ func pgCreateColumn(schema *model.SchemaMetadata, table *model.TableMetadata, co
}
// Check if column already exists
if table.GetColumn(columnName) != nil {
- return &catalogutil.WalkThroughError{
- Code: code.ColumnExists,
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnExists.Int32(),
+ Title: fmt.Sprintf("The column %q already exists in table %q", columnName, table.GetProto().Name),
Content: fmt.Sprintf("The column %q already exists in table %q", columnName, table.GetProto().Name),
+ StartPosition: &storepb.Position{
+ Line: 0,
+ },
}
}
// Get column type
@@ -218,7 +241,13 @@ func pgCreateColumn(schema *model.SchemaMetadata, table *model.TableMetadata, co
IsConstraint: true,
}
if err := table.CreateIndex(index); err != nil {
- return &catalogutil.WalkThroughError{Code: code.PrimaryKeyExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.PrimaryKeyExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
}
// Handle UNIQUE
@@ -240,20 +269,32 @@ func pgCreateColumn(schema *model.SchemaMetadata, table *model.TableMetadata, co
IsConstraint: true,
}
if err := table.CreateIndex(index); err != nil {
- return &catalogutil.WalkThroughError{Code: code.IndexExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
}
}
}
// Create the column
if err := table.CreateColumn(col); err != nil {
- return &catalogutil.WalkThroughError{Code: code.ColumnExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
return nil
}
// createTableConstraint creates a table-level constraint.
-func createTableConstraint(schema *model.SchemaMetadata, table *model.TableMetadata, constraint parser.ITableconstraintContext) *catalogutil.WalkThroughError {
+func createTableConstraint(schema *model.SchemaMetadata, table *model.TableMetadata, constraint parser.ITableconstraintContext, line int) *storepb.Advice {
if constraint == nil || constraint.Constraintelem() == nil {
return nil
}
@@ -281,7 +322,13 @@ func createTableConstraint(schema *model.SchemaMetadata, table *model.TableMetad
if column != nil {
column.Nullable = false
} else {
- return catalogutil.NewColumnNotExistsError(table.GetProto().Name, colName)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` does not exist in table `%s`", colName, table.GetProto().Name),
+ Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", colName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: int32(line)},
+ }
}
}
// Generate PK name if not provided
@@ -291,9 +338,12 @@ func createTableConstraint(schema *model.SchemaMetadata, table *model.TableMetad
}
// Check if primary key already exists
if table.GetPrimaryKey() != nil {
- return &catalogutil.WalkThroughError{
- Code: code.PrimaryKeyExists,
- Content: fmt.Sprintf("Primary key already exists in table %q", table.GetProto().Name),
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.PrimaryKeyExists.Int32(),
+ Title: fmt.Sprintf("Primary key already exists in table %q", table.GetProto().Name),
+ Content: fmt.Sprintf("Primary key already exists in table %q", table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: int32(line)},
}
}
// Create primary key index
@@ -306,7 +356,13 @@ func createTableConstraint(schema *model.SchemaMetadata, table *model.TableMetad
IsConstraint: true,
}
if err := table.CreateIndex(index); err != nil {
- return &catalogutil.WalkThroughError{Code: code.PrimaryKeyExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.PrimaryKeyExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: int32(line)},
+ }
}
}
// Handle UNIQUE constraint
@@ -328,15 +384,24 @@ func createTableConstraint(schema *model.SchemaMetadata, table *model.TableMetad
}
// Check if index already exists
if table.GetIndex(indexName) != nil {
- return &catalogutil.WalkThroughError{
- Code: code.IndexExists,
- Content: fmt.Sprintf("Index %q already exists in table %q", indexName, table.GetProto().Name),
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexExists.Int32(),
+ Title: fmt.Sprintf("Index %q already exists in table %q", indexName, table.GetProto().Name),
+ Content: fmt.Sprintf("Index %q already exists in table %q", indexName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: int32(line)},
}
}
// Validate columns exist
for _, colName := range columnList {
if table.GetColumn(colName) == nil {
- return catalogutil.NewColumnNotExistsError(table.GetProto().Name, colName)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` does not exist in table `%s`", colName, table.GetProto().Name),
+ Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", colName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: int32(line)},
+ }
}
}
// Create unique index (from UNIQUE constraint)
@@ -349,7 +414,13 @@ func createTableConstraint(schema *model.SchemaMetadata, table *model.TableMetad
IsConstraint: true,
}
if err := table.CreateIndex(index); err != nil {
- return &catalogutil.WalkThroughError{Code: code.IndexExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: int32(line)},
+ }
}
}
// Note: We skip CHECK, FOREIGN KEY, EXCLUSION constraints for now
@@ -362,7 +433,7 @@ func createTableConstraint(schema *model.SchemaMetadata, table *model.TableMetad
// ========================================
// EnterIndexstmt handles CREATE INDEX statements.
func (l *pgCatalogListener) EnterIndexstmt(ctx *parser.IndexstmtContext) {
- if !isTopLevel(ctx.GetParent()) || l.err != nil {
+ if !isTopLevel(ctx.GetParent()) || l.advice != nil {
return
}
l.currentLine = ctx.GetStart().GetLine()
@@ -373,14 +444,20 @@ func (l *pgCatalogListener) EnterIndexstmt(ctx *parser.IndexstmtContext) {
}
tableName := extractTableName(relationExpr.Qualified_name())
schemaName := extractSchemaName(relationExpr.Qualified_name())
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName)
+ schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
if err != nil {
- l.setError(err)
+ l.advice = err
return
}
table := schema.GetTable(tableName)
if table == nil {
- l.setError(catalogutil.NewTableNotExistsError(tableName))
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: fmt.Sprintf("Table `%s` does not exist", tableName),
+ Content: fmt.Sprintf("Table `%s` does not exist", tableName),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
// Extract index name (can be empty for auto-generated names)
@@ -405,10 +482,13 @@ func (l *pgCatalogListener) EnterIndexstmt(ctx *parser.IndexstmtContext) {
}
}
if len(columnList) == 0 {
- l.setError(&catalogutil.WalkThroughError{
- Code: code.IndexEmptyKeys,
- Content: fmt.Sprintf("Index %q in table %q has empty key", indexName, tableName),
- })
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexEmptyKeys.Int32(),
+ Title: fmt.Sprintf("Index %q in table %q has empty key", indexName, tableName),
+ Content: fmt.Sprintf("Index %q in table %q has empty key", indexName, tableName),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
// Generate index name if not provided
@@ -426,7 +506,13 @@ func (l *pgCatalogListener) EnterIndexstmt(ctx *parser.IndexstmtContext) {
if wasAutoGenerated {
indexName = generateUniqueIndexName(schema, tableName, columnList, isUnique)
} else {
- l.setError(catalogutil.NewRelationExistsError(indexName, schema.GetProto().Name))
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.RelationExists.Int32(),
+ Title: fmt.Sprintf("Relation %q already exists in schema %q", indexName, schema.GetProto().Name),
+ Content: fmt.Sprintf("Relation %q already exists in schema %q", indexName, schema.GetProto().Name),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
}
@@ -434,7 +520,13 @@ func (l *pgCatalogListener) EnterIndexstmt(ctx *parser.IndexstmtContext) {
for _, colName := range columnList {
if colName != "expr" {
if table.GetColumn(colName) == nil {
- l.setError(catalogutil.NewColumnNotExistsError(tableName, colName))
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` does not exist in table `%s`", colName, tableName),
+ Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", colName, tableName),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
}
@@ -454,7 +546,13 @@ func (l *pgCatalogListener) EnterIndexstmt(ctx *parser.IndexstmtContext) {
Primary: false,
}
if err := table.CreateIndex(index); err != nil {
- l.setError(&catalogutil.WalkThroughError{Code: code.IndexExists, Content: err.Error()})
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
}
}
@@ -464,7 +562,7 @@ func (l *pgCatalogListener) EnterIndexstmt(ctx *parser.IndexstmtContext) {
// TODO: EnterCreateschemastatement - Need to find correct ANTLR context name
//
// func (l *pgCatalogListener) EnterCreateschemastatement(ctx *parser.CreateschemaContext) {
-// if !isTopLevel(ctx.GetParent()) || l.err != nil {
+// if !isTopLevel(ctx.GetParent()) || l.advice != nil {
// return
// }
//
@@ -483,7 +581,7 @@ func (l *pgCatalogListener) EnterIndexstmt(ctx *parser.IndexstmtContext) {
// ========================================
// EnterAltertablestmt handles ALTER TABLE statements.
func (l *pgCatalogListener) EnterAltertablestmt(ctx *parser.AltertablestmtContext) {
- if !isTopLevel(ctx.GetParent()) || l.err != nil {
+ if !isTopLevel(ctx.GetParent()) || l.advice != nil {
return
}
l.currentLine = ctx.GetStart().GetLine()
@@ -496,21 +594,30 @@ func (l *pgCatalogListener) EnterAltertablestmt(ctx *parser.AltertablestmtContex
databaseName := extractDatabaseName(ctx.Relation_expr().Qualified_name())
// Check database access
if databaseName != "" && l.databaseState.DatabaseName() != databaseName {
- l.setError(&catalogutil.WalkThroughError{
- Code: code.NotCurrentDatabase,
- Content: fmt.Sprintf("Database %q is not the current database %q", databaseName, l.databaseState.DatabaseName()),
- })
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: fmt.Sprintf("Database %q is not the current database %q", databaseName, l.databaseState.DatabaseName()),
+ Content: fmt.Sprintf("Database %q is not the current database %q", databaseName, l.databaseState.DatabaseName()),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
// Get schema and table
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName)
+ schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
if err != nil {
- l.setError(err)
+ l.advice = err
return
}
table := schema.GetTable(tableName)
if table == nil {
- l.setError(catalogutil.NewTableNotExistsError(tableName))
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: fmt.Sprintf("Table `%s` does not exist", tableName),
+ Content: fmt.Sprintf("Table `%s` does not exist", tableName),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
// Process alter table commands
@@ -520,7 +627,7 @@ func (l *pgCatalogListener) EnterAltertablestmt(ctx *parser.AltertablestmtContex
allCmds := ctx.Alter_table_cmds().AllAlter_table_cmd()
for _, cmd := range allCmds {
l.processAlterTableCmd(schema, table, cmd)
- if l.err != nil {
+ if l.advice != nil {
return
}
}
@@ -603,7 +710,13 @@ func (l *pgCatalogListener) alterTableDropColumn(schema *model.SchemaMetadata, t
if ifExists {
return
}
- l.setError(catalogutil.NewColumnNotExistsError(table.GetProto().Name, columnName))
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name),
+ Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
// Check if any views depend on this column
@@ -614,10 +727,13 @@ func (l *pgCatalogListener) alterTableDropColumn(schema *model.SchemaMetadata, t
for _, v := range dependentViews {
viewNames = append(viewNames, fmt.Sprintf("%q.%q", schema.GetProto().Name, v))
}
- l.setError(&catalogutil.WalkThroughError{
- Code: code.ColumnIsReferencedByView,
- Content: fmt.Sprintf("Cannot drop column %q in table %q.%q, it's referenced by view: %s", columnName, schema.GetProto().Name, table.GetProto().Name, strings.Join(viewNames, ", ")),
- })
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnIsReferencedByView.Int32(),
+ Title: fmt.Sprintf("Cannot drop column %q in table %q.%q, it's referenced by view: %s", columnName, schema.GetProto().Name, table.GetProto().Name, strings.Join(viewNames, ", ")),
+ Content: fmt.Sprintf("Cannot drop column %q in table %q.%q, it's referenced by view: %s", columnName, schema.GetProto().Name, table.GetProto().Name, strings.Join(viewNames, ", ")),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
// Drop the constraints and indexes involving the column
@@ -633,7 +749,13 @@ func (l *pgCatalogListener) alterTableDropColumn(schema *model.SchemaMetadata, t
}
for _, indexName := range dropIndexList {
if err := table.DropIndex(indexName); err != nil {
- l.setError(&catalogutil.WalkThroughError{Code: code.IndexNotExists, Content: err.Error()})
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
}
@@ -641,13 +763,25 @@ func (l *pgCatalogListener) alterTableDropColumn(schema *model.SchemaMetadata, t
// TODO(zp): deal with CASCADE.
// Validate column exists before dropping
if table.GetColumn(columnName) == nil {
- l.setError(catalogutil.NewColumnNotExistsError(table.GetProto().Name, columnName))
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name),
+ Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
// Delete the column without renumbering positions
// PostgreSQL maintains stable column positions (attnum) even after dropping columns
if err := table.DropColumnWithoutRenumbering(columnName); err != nil {
- l.setError(&catalogutil.WalkThroughError{Code: code.Internal, Content: fmt.Sprintf("failed to drop column: %v", err)})
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: fmt.Sprintf("failed to drop column: %v", err),
+ Content: fmt.Sprintf("failed to drop column: %v", err),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
}
}
@@ -655,7 +789,13 @@ func (l *pgCatalogListener) alterTableDropColumn(schema *model.SchemaMetadata, t
func (l *pgCatalogListener) alterTableAlterColumnType(schema *model.SchemaMetadata, table *model.TableMetadata, columnName string, typeString string) {
column := table.GetColumn(columnName)
if column == nil {
- l.setError(catalogutil.NewColumnNotExistsError(table.GetProto().Name, columnName))
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name),
+ Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
// Check if any views depend on this column
@@ -666,10 +806,13 @@ func (l *pgCatalogListener) alterTableAlterColumnType(schema *model.SchemaMetada
for _, v := range dependentViews {
viewNames = append(viewNames, fmt.Sprintf("%q.%q", schema.GetProto().Name, v))
}
- l.setError(&catalogutil.WalkThroughError{
- Code: code.ColumnIsReferencedByView,
- Content: fmt.Sprintf("Cannot alter type of column %q in table %q.%q, it's referenced by view: %s", columnName, schema.GetProto().Name, table.GetProto().Name, strings.Join(viewNames, ", ")),
- })
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnIsReferencedByView.Int32(),
+ Title: fmt.Sprintf("Cannot alter type of column %q in table %q.%q, it's referenced by view: %s", columnName, schema.GetProto().Name, table.GetProto().Name, strings.Join(viewNames, ", ")),
+ Content: fmt.Sprintf("Cannot alter type of column %q in table %q.%q, it's referenced by view: %s", columnName, schema.GetProto().Name, table.GetProto().Name, strings.Join(viewNames, ", ")),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
// Update column type
@@ -687,10 +830,13 @@ func (l *pgCatalogListener) alterTableAddColumn(schema *model.SchemaMetadata, ta
if ifNotExists {
return
}
- l.setError(&catalogutil.WalkThroughError{
- Code: code.ColumnExists,
- Content: fmt.Sprintf("The column %q already exists in table %q", columnName, table.GetProto().Name),
- })
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnExists.Int32(),
+ Title: fmt.Sprintf("The column %q already exists in table %q", columnName, table.GetProto().Name),
+ Content: fmt.Sprintf("The column %q already exists in table %q", columnName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
// Extract column type
@@ -747,7 +893,13 @@ func (l *pgCatalogListener) alterTableAddColumn(schema *model.SchemaMetadata, ta
Primary: false,
}
if err := table.CreateIndex(index); err != nil {
- l.setError(&catalogutil.WalkThroughError{Code: code.IndexExists, Content: err.Error()})
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
}
@@ -762,7 +914,13 @@ func (l *pgCatalogListener) alterTableAddColumn(schema *model.SchemaMetadata, ta
}
// Check for collision
if table.GetIndex(constraintName) != nil {
- l.setError(catalogutil.NewRelationExistsError(constraintName, schema.GetProto().Name))
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.RelationExists.Int32(),
+ Title: fmt.Sprintf("Relation %q already exists in schema %q", constraintName, schema.GetProto().Name),
+ Content: fmt.Sprintf("Relation %q already exists in schema %q", constraintName, schema.GetProto().Name),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
col.Nullable = false
@@ -776,7 +934,13 @@ func (l *pgCatalogListener) alterTableAddColumn(schema *model.SchemaMetadata, ta
IsConstraint: true,
}
if err := table.CreateIndex(index); err != nil {
- l.setError(&catalogutil.WalkThroughError{Code: code.PrimaryKeyExists, Content: err.Error()})
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.PrimaryKeyExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
}
@@ -784,7 +948,13 @@ func (l *pgCatalogListener) alterTableAddColumn(schema *model.SchemaMetadata, ta
}
// Create the column
if err := table.CreateColumn(col); err != nil {
- l.setError(&catalogutil.WalkThroughError{Code: code.ColumnExists, Content: err.Error()})
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
}
}
@@ -794,9 +964,9 @@ func (l *pgCatalogListener) alterTableAddConstraint(schema *model.SchemaMetadata
return
}
// Reuse the constraint creation logic from CREATE TABLE
- err := createTableConstraint(schema, table, constraint)
+ err := createTableConstraint(schema, table, constraint, l.currentLine)
if err != nil {
- l.setError(err)
+ l.advice = err
}
}
@@ -805,15 +975,24 @@ func (l *pgCatalogListener) alterTableDropConstraint(_ *model.SchemaMetadata, ta
// Check if constraint exists as an index
if table.GetIndex(constraintName) != nil {
if err := table.DropIndex(constraintName); err != nil {
- l.setError(&catalogutil.WalkThroughError{Code: code.IndexNotExists, Content: err.Error()})
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
}
return
}
if !ifExists {
- l.setError(&catalogutil.WalkThroughError{
- Code: code.ConstraintNotExists,
- Content: fmt.Sprintf("Constraint %q for table %q does not exist", constraintName, table.GetProto().Name),
- })
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ConstraintNotExists.Int32(),
+ Title: fmt.Sprintf("Constraint %q for table %q does not exist", constraintName, table.GetProto().Name),
+ Content: fmt.Sprintf("Constraint %q for table %q does not exist", constraintName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
}
}
@@ -821,7 +1000,13 @@ func (l *pgCatalogListener) alterTableDropConstraint(_ *model.SchemaMetadata, ta
func (l *pgCatalogListener) alterTableSetDefault(table *model.TableMetadata, columnName string, defaultValue string) {
column := table.GetColumn(columnName)
if column == nil {
- l.setError(catalogutil.NewColumnNotExistsError(table.GetProto().Name, columnName))
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name),
+ Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
column.Default = defaultValue
@@ -831,7 +1016,13 @@ func (l *pgCatalogListener) alterTableSetDefault(table *model.TableMetadata, col
func (l *pgCatalogListener) alterTableDropDefault(table *model.TableMetadata, columnName string) {
column := table.GetColumn(columnName)
if column == nil {
- l.setError(catalogutil.NewColumnNotExistsError(table.GetProto().Name, columnName))
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name),
+ Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
column.Default = ""
@@ -841,45 +1032,78 @@ func (l *pgCatalogListener) alterTableDropDefault(table *model.TableMetadata, co
func (l *pgCatalogListener) alterTableSetNotNull(table *model.TableMetadata, columnName string) {
column := table.GetColumn(columnName)
if column == nil {
- l.setError(catalogutil.NewColumnNotExistsError(table.GetProto().Name, columnName))
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name),
+ Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
column.Nullable = false
}
// renameTable handles RENAME TO for tables.
-func (*pgCatalogListener) pgRenameTable(schema *model.SchemaMetadata, table *model.TableMetadata, newName string) *catalogutil.WalkThroughError {
+func (*pgCatalogListener) pgRenameTable(schema *model.SchemaMetadata, table *model.TableMetadata, newName string, line int) *storepb.Advice {
// Check if new name already exists
if schema.GetTable(newName) != nil {
- return catalogutil.NewRelationExistsError(newName, schema.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.RelationExists.Int32(),
+ Title: fmt.Sprintf("Relation %q already exists in schema %q", newName, schema.GetProto().Name),
+ Content: fmt.Sprintf("Relation %q already exists in schema %q", newName, schema.GetProto().Name),
+ StartPosition: &storepb.Position{Line: int32(line)},
+ }
}
// Use the RenameTable method from schema
oldName := table.GetProto().Name
if err := schema.RenameTable(oldName, newName); err != nil {
- return &catalogutil.WalkThroughError{Code: code.TableNotExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: int32(line)},
+ }
}
return nil
}
// renameColumn handles RENAME COLUMN.
-func (*pgCatalogListener) renameColumn(table *model.TableMetadata, oldName string, newName string) *catalogutil.WalkThroughError {
+func (*pgCatalogListener) renameColumn(table *model.TableMetadata, oldName string, newName string, line int) *storepb.Advice {
if oldName == newName {
return nil
}
// Validate old column exists
if table.GetColumn(oldName) == nil {
- return catalogutil.NewColumnNotExistsError(table.GetProto().Name, oldName)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` does not exist in table `%s`", oldName, table.GetProto().Name),
+ Content: fmt.Sprintf("Column `%s` does not exist in table `%s`", oldName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: int32(line)},
+ }
}
// Validate new column doesn't already exist
if table.GetColumn(newName) != nil {
- return &catalogutil.WalkThroughError{
- Code: code.ColumnExists,
- Content: fmt.Sprintf("Column `%s` already exists in table `%s`", newName, table.GetProto().Name),
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnExists.Int32(),
+ Title: fmt.Sprintf("Column `%s` already exists in table `%s`", newName, table.GetProto().Name),
+ Content: fmt.Sprintf("Column `%s` already exists in table `%s`", newName, table.GetProto().Name),
+ StartPosition: &storepb.Position{Line: int32(line)},
}
}
// Use the RenameColumn method
if err := table.RenameColumn(oldName, newName); err != nil {
- return &catalogutil.WalkThroughError{Code: code.Internal, Content: fmt.Sprintf("failed to rename column: %v", err)}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: fmt.Sprintf("failed to rename column: %v", err),
+ Content: fmt.Sprintf("failed to rename column: %v", err),
+ StartPosition: &storepb.Position{Line: int32(line)},
+ }
}
// Rename column in all indexes that reference it
for _, index := range table.GetProto().Indexes {
@@ -893,7 +1117,7 @@ func (*pgCatalogListener) renameColumn(table *model.TableMetadata, oldName strin
}
// renameConstraint handles RENAME CONSTRAINT.
-func (*pgCatalogListener) renameConstraint(schema *model.SchemaMetadata, table *model.TableMetadata, oldName string, newName string) *catalogutil.WalkThroughError {
+func (*pgCatalogListener) renameConstraint(schema *model.SchemaMetadata, table *model.TableMetadata, oldName string, newName string, line int) *storepb.Advice {
index := table.GetIndex(oldName)
if index == nil {
// We haven't dealt with foreign and check constraints, so skip if not exists
@@ -901,11 +1125,23 @@ func (*pgCatalogListener) renameConstraint(schema *model.SchemaMetadata, table *
}
// Check if new name already exists
if table.GetIndex(newName) != nil {
- return catalogutil.NewRelationExistsError(newName, schema.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.RelationExists.Int32(),
+ Title: fmt.Sprintf("Relation %q already exists in schema %q", newName, schema.GetProto().Name),
+ Content: fmt.Sprintf("Relation %q already exists in schema %q", newName, schema.GetProto().Name),
+ StartPosition: &storepb.Position{Line: int32(line)},
+ }
}
// Use the RenameIndex method
if err := table.RenameIndex(oldName, newName); err != nil {
- return &catalogutil.WalkThroughError{Code: code.IndexNotExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: int32(line)},
+ }
}
return nil
}
@@ -915,7 +1151,7 @@ func (*pgCatalogListener) renameConstraint(schema *model.SchemaMetadata, table *
// ========================================
// EnterDropstmt handles DROP TABLE/VIEW/INDEX statements.
func (l *pgCatalogListener) EnterDropstmt(ctx *parser.DropstmtContext) {
- if !isTopLevel(ctx.GetParent()) || l.err != nil {
+ if !isTopLevel(ctx.GetParent()) || l.advice != nil {
return
}
l.currentLine = ctx.GetStart().GetLine()
@@ -929,7 +1165,7 @@ func (l *pgCatalogListener) EnterDropstmt(ctx *parser.DropstmtContext) {
if ctx.Any_name_list() != nil {
for _, anyName := range ctx.Any_name_list().AllAny_name() {
if err := l.dropTable(anyName, ifExists); err != nil {
- l.setError(err)
+ l.advice = err
return
}
}
@@ -939,7 +1175,7 @@ func (l *pgCatalogListener) EnterDropstmt(ctx *parser.DropstmtContext) {
if ctx.Any_name_list() != nil {
for _, anyName := range ctx.Any_name_list().AllAny_name() {
if err := l.dropView(anyName, ifExists); err != nil {
- l.setError(err)
+ l.advice = err
return
}
}
@@ -949,7 +1185,7 @@ func (l *pgCatalogListener) EnterDropstmt(ctx *parser.DropstmtContext) {
if ctx.Any_name_list() != nil {
for _, anyName := range ctx.Any_name_list().AllAny_name() {
if err := l.dropIndex(anyName, ifExists); err != nil {
- l.setError(err)
+ l.advice = err
return
}
}
@@ -960,7 +1196,7 @@ func (l *pgCatalogListener) EnterDropstmt(ctx *parser.DropstmtContext) {
if ctx.Name_list() != nil {
for _, schemaName := range ctx.Name_list().AllName() {
if err := l.dropSchema(schemaName, ifExists); err != nil {
- l.setError(err)
+ l.advice = err
return
}
}
@@ -975,7 +1211,7 @@ func (l *pgCatalogListener) EnterDropstmt(ctx *parser.DropstmtContext) {
// PostgreSQL does not allow dropping the currently connected database.
// Walk-through also disallows DROP DATABASE for other databases as it's out of scope.
func (l *pgCatalogListener) EnterDropdbstmt(ctx *parser.DropdbstmtContext) {
- if !isTopLevel(ctx.GetParent()) || l.err != nil {
+ if !isTopLevel(ctx.GetParent()) || l.advice != nil {
return
}
l.currentLine = ctx.GetStart().GetLine()
@@ -987,16 +1223,25 @@ func (l *pgCatalogListener) EnterDropdbstmt(ctx *parser.DropdbstmtContext) {
// PostgreSQL does not allow dropping the currently open database.
// This matches the real PostgreSQL behavior: "ERROR: cannot drop the currently open database"
if isCurrentDatabase(l.databaseState, databaseName) {
- l.setError(&catalogutil.WalkThroughError{
- Code: code.NotCurrentDatabase,
- Content: fmt.Sprintf("Cannot drop the currently open database %q", databaseName),
- })
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: fmt.Sprintf("Cannot drop the currently open database %q", databaseName),
+ Content: fmt.Sprintf("Cannot drop the currently open database %q", databaseName),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
// DROP DATABASE for other databases is out of scope for single-database walk-through
- l.setError(catalogutil.NewAccessOtherDatabaseError(l.databaseState.DatabaseName(), databaseName))
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, l.databaseState.DatabaseName()),
+ Content: fmt.Sprintf("Database `%s` is not the current database `%s`", databaseName, l.databaseState.DatabaseName()),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
}
-func (l *pgCatalogListener) dropTable(anyName parser.IAny_nameContext, ifExists bool) *catalogutil.WalkThroughError {
+func (l *pgCatalogListener) dropTable(anyName parser.IAny_nameContext, ifExists bool) *storepb.Advice {
parts := pgparser.NormalizePostgreSQLAnyName(anyName)
if len(parts) == 0 {
return nil
@@ -1009,7 +1254,7 @@ func (l *pgCatalogListener) dropTable(anyName parser.IAny_nameContext, ifExists
schemaName = parts[0]
tableName = parts[1]
}
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName)
+ schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
if err != nil {
if ifExists {
return nil
@@ -1021,7 +1266,13 @@ func (l *pgCatalogListener) dropTable(anyName parser.IAny_nameContext, ifExists
if ifExists {
return nil
}
- return catalogutil.NewTableNotExistsError(tableName)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: fmt.Sprintf("Table `%s` does not exist", tableName),
+ Content: fmt.Sprintf("Table `%s` does not exist", tableName),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
}
// Check if any views depend on this table
dependentViews := schema.GetDependentViews(tableName, "")
@@ -1031,18 +1282,27 @@ func (l *pgCatalogListener) dropTable(anyName parser.IAny_nameContext, ifExists
for _, v := range dependentViews {
viewNames = append(viewNames, fmt.Sprintf("%q.%q", schema.GetProto().Name, v))
}
- return &catalogutil.WalkThroughError{
- Code: code.TableIsReferencedByView,
- Content: fmt.Sprintf("Cannot drop table %q.%q, it's referenced by view: %s", schema.GetProto().Name, tableName, strings.Join(viewNames, ", ")),
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableIsReferencedByView.Int32(),
+ Title: fmt.Sprintf("Cannot drop table %q.%q, it's referenced by view: %s", schema.GetProto().Name, tableName, strings.Join(viewNames, ", ")),
+ Content: fmt.Sprintf("Cannot drop table %q.%q, it's referenced by view: %s", schema.GetProto().Name, tableName, strings.Join(viewNames, ", ")),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
}
}
// Drop the table using the schema method
if err := schema.DropTable(tableName); err != nil {
- return &catalogutil.WalkThroughError{Code: code.TableNotExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
}
return nil
}
-func (l *pgCatalogListener) dropView(anyName parser.IAny_nameContext, ifExists bool) *catalogutil.WalkThroughError {
+func (l *pgCatalogListener) dropView(anyName parser.IAny_nameContext, ifExists bool) *storepb.Advice {
parts := pgparser.NormalizePostgreSQLAnyName(anyName)
if len(parts) == 0 {
return nil
@@ -1057,19 +1317,25 @@ func (l *pgCatalogListener) dropView(anyName parser.IAny_nameContext, ifExists b
default:
return nil
}
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName)
+ schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
if err != nil {
return err
}
// Try to drop the view
if dropErr := schema.DropView(viewName); dropErr != nil {
if !ifExists {
- return &catalogutil.WalkThroughError{Code: code.ViewNotExists, Content: dropErr.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ViewNotExists.Int32(),
+ Title: dropErr.Error(),
+ Content: dropErr.Error(),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
}
}
return nil
}
-func (l *pgCatalogListener) dropIndex(anyName parser.IAny_nameContext, ifExists bool) *catalogutil.WalkThroughError {
+func (l *pgCatalogListener) dropIndex(anyName parser.IAny_nameContext, ifExists bool) *storepb.Advice {
parts := pgparser.NormalizePostgreSQLAnyName(anyName)
if len(parts) == 0 {
return nil
@@ -1082,7 +1348,7 @@ func (l *pgCatalogListener) dropIndex(anyName parser.IAny_nameContext, ifExists
schemaName = parts[0]
indexName = parts[1]
}
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName)
+ schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
if err != nil {
if ifExists {
return nil
@@ -1098,27 +1364,42 @@ func (l *pgCatalogListener) dropIndex(anyName parser.IAny_nameContext, ifExists
}
// Drop the index from the table
if err := table.DropIndex(index.GetProto().Name); err != nil {
- return &catalogutil.WalkThroughError{Code: code.IndexNotExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
}
return nil
}
-func (l *pgCatalogListener) dropSchema(schemaNameCtx parser.INameContext, ifExists bool) *catalogutil.WalkThroughError {
+func (l *pgCatalogListener) dropSchema(schemaNameCtx parser.INameContext, ifExists bool) *storepb.Advice {
schemaName := pgparser.NormalizePostgreSQLName(schemaNameCtx)
schema := l.databaseState.GetSchema(schemaName)
if schema == nil {
if ifExists {
return nil
}
- return &catalogutil.WalkThroughError{
- Code: code.SchemaNotExists,
- Content: fmt.Sprintf("Schema %q does not exist", schemaName),
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.SchemaNotExists.Int32(),
+ Title: fmt.Sprintf("Schema %q does not exist", schemaName),
+ Content: fmt.Sprintf("Schema %q does not exist", schemaName),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
}
}
// Drop the schema (this will also drop all objects in the schema)
// Note: We don't check for objects in the schema to match the old behavior
// In real PostgreSQL, this would require CASCADE if the schema is not empty
if err := l.databaseState.DropSchema(schemaName); err != nil {
- return &catalogutil.WalkThroughError{Code: code.SchemaNotExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.SchemaNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
}
return nil
}
@@ -1126,7 +1407,7 @@ func (l *pgCatalogListener) dropSchema(schemaNameCtx parser.INameContext, ifExis
// TODO: EnterDropindexstmt - Need to find correct ANTLR context name
//
// func (l *pgCatalogListener) EnterDropindexstmt(ctx *parser.DropIndexContext) {
-// if !isTopLevel(ctx.GetParent()) || l.err != nil {
+// if !isTopLevel(ctx.GetParent()) || l.advice != nil {
// return
// }
//
@@ -1143,7 +1424,7 @@ func (l *pgCatalogListener) dropSchema(schemaNameCtx parser.INameContext, ifExis
// TODO: EnterDropschemastatement - Need to find correct ANTLR context name
//
// func (l *pgCatalogListener) EnterDropschemastatement(ctx *parser.DropschemaContext) {
-// if !isTopLevel(ctx.GetParent()) || l.err != nil {
+// if !isTopLevel(ctx.GetParent()) || l.advice != nil {
// return
// }
//
@@ -1162,7 +1443,7 @@ func (l *pgCatalogListener) dropSchema(schemaNameCtx parser.INameContext, ifExis
// ========================================
// EnterRenamestmt handles RENAME INDEX/CONSTRAINT/TABLE/COLUMN statements.
func (l *pgCatalogListener) EnterRenamestmt(ctx *parser.RenamestmtContext) {
- if !isTopLevel(ctx.GetParent()) || l.err != nil {
+ if !isTopLevel(ctx.GetParent()) || l.advice != nil {
return
}
l.currentLine = ctx.GetStart().GetLine()
@@ -1173,9 +1454,9 @@ func (l *pgCatalogListener) EnterRenamestmt(ctx *parser.RenamestmtContext) {
indexName := extractTableName(ctx.Qualified_name())
schemaName := extractSchemaName(ctx.Qualified_name())
newName := pgparser.NormalizePostgreSQLName(ctx.AllName()[0])
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName)
+ schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
if err != nil {
- l.setError(err)
+ l.advice = err
return
}
// Find the index across all tables
@@ -1184,8 +1465,8 @@ func (l *pgCatalogListener) EnterRenamestmt(ctx *parser.RenamestmtContext) {
// Index not found, silently ignore (PostgreSQL behavior)
return
}
- if err := l.renameConstraint(schema, foundTable, indexName, newName); err != nil {
- l.setError(err)
+ if err := l.renameConstraint(schema, foundTable, indexName, newName, l.currentLine); err != nil {
+ l.advice = err
}
}
return
@@ -1197,15 +1478,21 @@ func (l *pgCatalogListener) EnterRenamestmt(ctx *parser.RenamestmtContext) {
viewName := extractTableName(ctx.Qualified_name())
schemaName := extractSchemaName(ctx.Qualified_name())
newName := pgparser.NormalizePostgreSQLName(ctx.AllName()[0])
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName)
+ schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
if err != nil {
- l.setError(err)
+ l.advice = err
return
}
// Check if it's a view
if schema.GetView(viewName) != nil {
if err := schema.RenameView(viewName, newName); err != nil {
- l.setError(&catalogutil.WalkThroughError{Code: code.ViewNotExists, Content: err.Error()})
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ViewNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
}
return
}
@@ -1216,9 +1503,9 @@ func (l *pgCatalogListener) EnterRenamestmt(ctx *parser.RenamestmtContext) {
tableName = extractTableName(ctx.Relation_expr().Qualified_name())
schemaName = extractSchemaName(ctx.Relation_expr().Qualified_name())
}
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName)
+ schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
if err != nil {
- l.setError(err)
+ l.advice = err
return
}
// Check if this is column rename
@@ -1231,11 +1518,17 @@ func (l *pgCatalogListener) EnterRenamestmt(ctx *parser.RenamestmtContext) {
newName := pgparser.NormalizePostgreSQLName(allNames[1])
table := schema.GetTable(tableName)
if table == nil {
- l.setError(catalogutil.NewTableNotExistsError(tableName))
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: fmt.Sprintf("Table `%s` does not exist", tableName),
+ Content: fmt.Sprintf("Table `%s` does not exist", tableName),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
- if err := l.renameColumn(table, oldName, newName); err != nil {
- l.setError(err)
+ if err := l.renameColumn(table, oldName, newName, l.currentLine); err != nil {
+ l.advice = err
}
}
return
@@ -1249,11 +1542,17 @@ func (l *pgCatalogListener) EnterRenamestmt(ctx *parser.RenamestmtContext) {
newName := pgparser.NormalizePostgreSQLName(allNames[1])
table := schema.GetTable(tableName)
if table == nil {
- l.setError(catalogutil.NewTableNotExistsError(tableName))
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: fmt.Sprintf("Table `%s` does not exist", tableName),
+ Content: fmt.Sprintf("Table `%s` does not exist", tableName),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
- if err := l.renameConstraint(schema, table, oldName, newName); err != nil {
- l.setError(err)
+ if err := l.renameConstraint(schema, table, oldName, newName, l.currentLine); err != nil {
+ l.advice = err
}
}
return
@@ -1263,11 +1562,17 @@ func (l *pgCatalogListener) EnterRenamestmt(ctx *parser.RenamestmtContext) {
newName := pgparser.NormalizePostgreSQLName(ctx.AllName()[0])
table := schema.GetTable(tableName)
if table == nil {
- l.setError(catalogutil.NewTableNotExistsError(tableName))
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: fmt.Sprintf("Table `%s` does not exist", tableName),
+ Content: fmt.Sprintf("Table `%s` does not exist", tableName),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
- if err := l.pgRenameTable(schema, table, newName); err != nil {
- l.setError(err)
+ if err := l.pgRenameTable(schema, table, newName, l.currentLine); err != nil {
+ l.advice = err
}
return
}
@@ -1278,7 +1583,7 @@ func (l *pgCatalogListener) EnterRenamestmt(ctx *parser.RenamestmtContext) {
// ========================================
// EnterViewstmt handles CREATE VIEW statements.
func (l *pgCatalogListener) EnterViewstmt(ctx *parser.ViewstmtContext) {
- if !isTopLevel(ctx.GetParent()) || l.err != nil {
+ if !isTopLevel(ctx.GetParent()) || l.advice != nil {
return
}
l.currentLine = ctx.GetStart().GetLine()
@@ -1291,15 +1596,18 @@ func (l *pgCatalogListener) EnterViewstmt(ctx *parser.ViewstmtContext) {
databaseName := extractDatabaseName(ctx.Qualified_name())
// Check if accessing other database
if databaseName != "" && l.databaseState.DatabaseName() != databaseName {
- l.setError(&catalogutil.WalkThroughError{
- Code: code.NotCurrentDatabase,
- Content: fmt.Sprintf("Database %q is not the current database %q", databaseName, l.databaseState.DatabaseName()),
- })
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: fmt.Sprintf("Database %q is not the current database %q", databaseName, l.databaseState.DatabaseName()),
+ Content: fmt.Sprintf("Database %q is not the current database %q", databaseName, l.databaseState.DatabaseName()),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
return
}
- schema, err := getOrCreatePublicSchema(l.databaseState, schemaName)
+ schema, err := getOrCreatePublicSchema(l.databaseState, schemaName, l.currentLine)
if err != nil {
- l.setError(err)
+ l.advice = err
return
}
// Check if view already exists - silently ignore duplicates
@@ -1317,7 +1625,13 @@ func (l *pgCatalogListener) EnterViewstmt(ctx *parser.ViewstmtContext) {
// Create the view
_, createErr := schema.CreateView(viewName, definition, nil)
if createErr != nil {
- l.setError(&catalogutil.WalkThroughError{Code: code.ViewExists, Content: createErr.Error()})
+ l.advice = &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ViewExists.Int32(),
+ Title: createErr.Error(),
+ Content: createErr.Error(),
+ StartPosition: &storepb.Position{Line: int32(l.currentLine)},
+ }
}
}
@@ -1480,7 +1794,7 @@ func pgGeneratePrimaryKeyName(schema *model.SchemaMetadata, tableName string) st
// getOrCreatePublicSchema gets a schema by name, or creates the "public" schema if it doesn't exist.
// For PostgreSQL, the "public" schema is auto-created, but other schemas must exist.
-func getOrCreatePublicSchema(d *model.DatabaseMetadata, schemaName string) (*model.SchemaMetadata, *catalogutil.WalkThroughError) {
+func getOrCreatePublicSchema(d *model.DatabaseMetadata, schemaName string, line int) (*model.SchemaMetadata, *storepb.Advice) {
if schemaName == "" {
schemaName = PublicSchemaName
}
@@ -1490,9 +1804,12 @@ func getOrCreatePublicSchema(d *model.DatabaseMetadata, schemaName string) (*mod
}
// Only auto-create the "public" schema
if schemaName != PublicSchemaName {
- return nil, &catalogutil.WalkThroughError{
- Code: code.SchemaNotExists,
- Content: fmt.Sprintf("The schema %q doesn't exist", schemaName),
+ return nil, &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.SchemaNotExists.Int32(),
+ Title: fmt.Sprintf("The schema %q doesn't exist", schemaName),
+ Content: fmt.Sprintf("The schema %q doesn't exist", schemaName),
+ StartPosition: &storepb.Position{Line: int32(line)},
}
}
return d.CreateSchema(PublicSchemaName), nil
@@ -1500,21 +1817,27 @@ func getOrCreatePublicSchema(d *model.DatabaseMetadata, schemaName string) (*mod
// getIndexFromSchema finds an index by name within a schema and returns the table and index.
// For PostgreSQL, index names are unique within a schema (not just within a table).
-func getIndexFromSchema(s *model.SchemaMetadata, indexName string) (*model.TableMetadata, *model.IndexMetadata, *catalogutil.WalkThroughError) {
+func getIndexFromSchema(s *model.SchemaMetadata, indexName string) (*model.TableMetadata, *model.IndexMetadata, *storepb.Advice) {
// For PostgreSQL, index names are unique within a schema
index := s.GetIndex(indexName)
if index == nil {
- return nil, nil, &catalogutil.WalkThroughError{
- Code: code.IndexNotExists,
- Content: fmt.Sprintf("Index %q does not exist in schema %q", indexName, s.GetProto().Name),
+ return nil, nil, &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexNotExists.Int32(),
+ Title: fmt.Sprintf("Index %q does not exist in schema %q", indexName, s.GetProto().Name),
+ Content: fmt.Sprintf("Index %q does not exist in schema %q", indexName, s.GetProto().Name),
+ StartPosition: &storepb.Position{Line: 0},
}
}
// Find the table that owns this index
table := s.GetTable(index.GetTableProto().Name)
if table == nil {
- return nil, nil, &catalogutil.WalkThroughError{
- Code: code.TableNotExists,
- Content: fmt.Sprintf("Table %q does not exist in schema %q", index.GetTableProto().Name, s.GetProto().Name),
+ return nil, nil, &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: fmt.Sprintf("Table %q does not exist in schema %q", index.GetTableProto().Name, s.GetProto().Name),
+ Content: fmt.Sprintf("Table %q does not exist in schema %q", index.GetTableProto().Name, s.GetProto().Name),
+ StartPosition: &storepb.Position{Line: 0},
}
}
return table, index, nil
@@ -1522,5 +1845,5 @@ func getIndexFromSchema(s *model.SchemaMetadata, indexName string) (*model.Table
// isCurrentDatabase returns true if the given database is the current database.
func isCurrentDatabase(d *model.DatabaseMetadata, database string) bool {
- return catalogutil.CompareIdentifier(d.DatabaseName(), database, !d.GetIsObjectCaseSensitive())
+ return d.DatabaseName() == database
}
diff --git a/backend/plugin/schema/pg/walk_through_test.go b/backend/plugin/schema/pg/walk_through_test.go
index e4115dcab8..5b18109dc2 100644
--- a/backend/plugin/schema/pg/walk_through_test.go
+++ b/backend/plugin/schema/pg/walk_through_test.go
@@ -16,7 +16,6 @@ import (
"github.com/bytebase/bytebase/backend/component/sheet"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
pgparser "github.com/bytebase/bytebase/backend/plugin/parser/pg"
- "github.com/bytebase/bytebase/backend/plugin/schema/catalogutil"
"github.com/bytebase/bytebase/backend/store/model"
)
@@ -25,7 +24,7 @@ type testData struct {
// Use custom yaml tag to avoid generate field name `ignorecasesensitive`.
IgnoreCaseSensitive bool `yaml:"ignore_case_sensitive"`
Want string
- Err *catalogutil.WalkThroughError
+ Advice *storepb.Advice
}
func TestWalkThrough(t *testing.T) {
@@ -96,14 +95,13 @@ func TestWalkThrough(t *testing.T) {
state := model.NewDatabaseMetadata(protoData, !test.IgnoreCaseSensitive, !test.IgnoreCaseSensitive)
asts, _ := sm.GetASTsForChecks(storepb.Engine_POSTGRES, test.Statement)
- err := WalkThrough(state, asts)
- if err != nil {
- walkErr, yes := err.(*catalogutil.WalkThroughError)
- require.True(t, yes)
- require.Equal(t, test.Err, walkErr)
+ advice := WalkThrough(state, asts)
+ if advice != nil {
+ // Compare the advice fields
+ require.Equal(t, test.Advice.Code, advice.Code)
+ require.Equal(t, test.Advice.Content, advice.Content)
continue
}
- require.NoError(t, err, test.Statement)
// Skip comparison if want is empty (error cases)
if test.Want == "" {
@@ -111,7 +109,7 @@ func TestWalkThrough(t *testing.T) {
}
want := &storepb.DatabaseSchemaMetadata{}
- err = common.ProtojsonUnmarshaler.Unmarshal([]byte(test.Want), want)
+ err := common.ProtojsonUnmarshaler.Unmarshal([]byte(test.Want), want)
require.NoError(t, err)
// Sort proto for deterministic comparison
state.SortProto()
@@ -194,14 +192,13 @@ func TestWalkThroughANTLR(t *testing.T) {
}
// Call WalkThrough with ANTLR tree
- err := WalkThrough(state, parseResult)
- if err != nil {
- walkErr, yes := err.(*catalogutil.WalkThroughError)
- require.True(t, yes)
- require.Equal(t, test.Err, walkErr)
+ advice := WalkThrough(state, parseResult)
+ if advice != nil {
+ // Compare the advice fields
+ require.Equal(t, test.Advice.Code, advice.Code)
+ require.Equal(t, test.Advice.Content, advice.Content)
continue
}
- require.NoError(t, err, test.Statement)
// Skip comparison if want is empty (error cases)
if test.Want == "" {
@@ -209,7 +206,7 @@ func TestWalkThroughANTLR(t *testing.T) {
}
want := &storepb.DatabaseSchemaMetadata{}
- err = common.ProtojsonUnmarshaler.Unmarshal([]byte(test.Want), want)
+ err := common.ProtojsonUnmarshaler.Unmarshal([]byte(test.Want), want)
require.NoError(t, err)
// Sort proto for deterministic comparison
state.SortProto()
diff --git a/backend/plugin/schema/schema.go b/backend/plugin/schema/schema.go
index 57e5e06560..6025945914 100644
--- a/backend/plugin/schema/schema.go
+++ b/backend/plugin/schema/schema.go
@@ -39,7 +39,7 @@ type getSequenceDefinition func(string, *storepb.SequenceMetadata) (string, erro
type getDatabaseMetadata func(string) (*storepb.DatabaseSchemaMetadata, error)
type generateMigration func(*MetadataDiff) (string, error)
type getSDLDiff func(currentSDLText, previousUserSDLText string, currentSchema, previousSchema *model.DatabaseSchema) (*MetadataDiff, error)
-type walkThrough func(*model.DatabaseMetadata, any) error
+type walkThrough func(*model.DatabaseMetadata, any) *storepb.Advice
type GetDefinitionContext struct {
SkipBackupSchema bool
@@ -277,10 +277,10 @@ func RegisterWalkThrough(engine storepb.Engine, f walkThrough) {
walkThroughs[engine] = f
}
-func WalkThrough(engine storepb.Engine, d *model.DatabaseMetadata, ast any) error {
+func WalkThrough(engine storepb.Engine, d *model.DatabaseMetadata, ast any) *storepb.Advice {
f, ok := walkThroughs[engine]
if !ok {
- return errors.Errorf("Walk-through doesn't support engine type: %s", engine)
+ return nil
}
return f(d, ast)
}
diff --git a/backend/plugin/schema/tidb/testdata/walk_through.yaml b/backend/plugin/schema/tidb/testdata/walk_through.yaml
index 53d2662a34..5bc740eb26 100644
--- a/backend/plugin/schema/tidb/testdata/walk_through.yaml
+++ b/backend/plugin/schema/tidb/testdata/walk_through.yaml
@@ -1,127 +1,173 @@
- statement: CREATE TABLE t(a date default '');
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 423
+ title: '[types:1292]Incorrect datetime value: '''''
content: '[types:1292]Incorrect datetime value: '''''
- line: 1
+ startPosition:
+ line: 1
- statement: 'CREATE TABLE t(a TEXT);
ALTER TABLE T ALTER COLUMN a SET DEFAULT ''1'';'
ignore_case_sensitive: true
want: ''
- err:
+ advice:
+ status: 1
code: 423
+ title: BLOB, TEXT, GEOMETRY or JSON column `a` can't have a default value
content: BLOB, TEXT, GEOMETRY or JSON column `a` can't have a default value
- line: 2
+ startPosition:
+ line: 2
- statement: ' CREATE TABLE t(a TEXT DEFAULT ''1'')'
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 423
+ title: BLOB, TEXT, GEOMETRY or JSON column `a` can't have a default value
content: BLOB, TEXT, GEOMETRY or JSON column `a` can't have a default value
- line: 1
+ startPosition:
+ line: 1
- statement: 'CREATE TABLE t(a INT NOT NULL);
ALTER TABLE t ALTER COLUMN a SET DEFAULT NULL;'
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 428
+ title: Invalid default value for column `a`
content: Invalid default value for column `a`
- line: 2
+ startPosition:
+ line: 2
- statement: ' CREATE TABLE t(a INT NOT NULL DEFAULT NULL)'
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 428
+ title: Invalid default value for column `a`
content: Invalid default value for column `a`
- line: 1
+ startPosition:
+ line: 1
- statement: ' CREATE TABLE t(a int ON UPDATE NOW())'
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 427
+ title: Column `a` use ON UPDATE but is not DATETIME or TIMESTAMP
content: Column `a` use ON UPDATE but is not DATETIME or TIMESTAMP
- line: 1
+ startPosition:
+ line: 1
- statement: ' CREATE TABLE t(a int auto_increment, b int auto_increment);'
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 426
+ title: There can be only one auto column for table `t`
content: There can be only one auto column for table `t`
- line: 1
+ startPosition:
+ line: 1
- statement: ' CREATE TABLE t as select * from t1;'
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 205
+ title: Disallow the CREATE TABLE AS statement but "CREATE TABLE t as select *
+ from t1;" uses
content: Disallow the CREATE TABLE AS statement but "CREATE TABLE t as select
* from t1;" uses
- line: 1
+ startPosition:
+ line: 1
- 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:
+ advice:
+ status: 1
code: 405
+ title: Column `c` does not exist in table `t`
content: Column `c` does not exist in table `t`
- line: 3
+ startPosition:
+ line: 3
- 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:
+ advice:
+ status: 1
code: 405
+ title: Column `c` does not exist in table `t`
content: Column `c` does not exist in table `t`
- line: 3
+ startPosition:
+ line: 3
- 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:
+ advice:
+ status: 1
code: 405
+ title: Column `c` does not exist in table `t`
content: Column `c` does not exist in table `t`
- line: 3
+ startPosition:
+ line: 3
- 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:
+ advice:
+ status: 1
code: 405
+ title: Column `c` does not exist in table `t`
content: Column `c` does not exist in table `t`
- line: 3
+ startPosition:
+ line: 3
- 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:
+ advice:
+ status: 1
code: 405
+ title: Column `c` does not exist in table `t`
content: Column `c` does not exist in table `t`
- line: 3
+ startPosition:
+ line: 3
- 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:
+ advice:
+ status: 1
code: 405
+ title: Column `c` does not exist in table `t`
content: Column `c` does not exist in table `t`
- line: 3
+ startPosition:
+ line: 3
- 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:
+ advice:
+ status: 1
code: 405
+ title: Column `c` does not exist in table `t`
content: Column `c` does not exist in table `t`
- line: 3
+ startPosition:
+ line: 3
- statement: 'ALTER DATABASE CHARACTER SET = utf8mb4;
ALTER DATABASE test COLLATE utf8mb4_polish_ci;'
ignore_case_sensitive: false
want: "{\n \"name\": \"test\",\n \"schemas\": [\n {}\n ],\n \"characterSet\"\
: \"utf8mb4\",\n \"collation\": \"utf8mb4_polish_ci\"\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE t(\n a int PRIMARY KEY DEFAULT 1,\n b varchar(200) CHARACTER\
\ SET utf8mb4 NOT NULL UNIQUE,\n c int auto_increment NULL COMMENT 'This is a\
\ comment' DEFAULT NULL,\n d varchar(10) COLLATE utf8mb4_polish_ci,\n KEY idx_a\
@@ -191,7 +237,7 @@
,\n \"expressions\": [\n \"a\"\n ],\n\
\ \"type\": \"BTREE\",\n \"visible\": true\n \
\ }\n ]\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE t(\n a int PRIMARY KEY DEFAULT 1,\n b varchar(200) CHARACTER\
\ SET utf8mb4 NOT NULL UNIQUE,\n c int auto_increment NULL COMMENT 'This is a\
\ comment',\n d varchar(10) COLLATE utf8mb4_polish_ci,\n KEY idx_a (a),\n INDEX\
@@ -230,7 +276,7 @@
name\": \"idx_a\",\n \"expressions\": [\n \"a\"\n\
\ ],\n \"type\": \"BTREE\",\n \"visible\"\
: true\n }\n ]\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE t(\n a int,\n b int,\n PRIMARY KEY (a, b)\n)"
ignore_case_sensitive: false
want: "{\n \"name\": \"test\",\n \"schemas\": [\n {\n \"tables\": [\n\
@@ -244,7 +290,7 @@
: \"BTREE\",\n \"unique\": true,\n \"primary\": true,\n\
\ \"visible\": true\n }\n ]\n }\n \
\ ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: 'CREATE TABLE t1(a int, b int, c int);
CREATE TABLE t2(a int);
@@ -252,20 +298,23 @@
DROP TABLE t1, t2'
ignore_case_sensitive: false
want: "{\n \"name\": \"test\",\n \"schemas\": [\n {}\n ]\n}"
- err: null
+ advice: null
- statement: ' DROP TABLE t1, t2'
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 604
+ title: Table `t1` does not exist
content: Table `t1` does not exist
- line: 1
+ startPosition:
+ line: 1
- statement: 'CREATE TABLE t(a int);
RENAME TABLE t to other_db.t1'
ignore_case_sensitive: false
want: "{\n \"name\": \"test\",\n \"schemas\": [\n {}\n ]\n}"
- err: null
+ advice: null
- statement: 'CREATE TABLE t(a int);
RENAME TABLE t to test.t1'
@@ -275,15 +324,18 @@
\ {\n \"name\": \"a\",\n \"position\": 1,\n \
\ \"nullable\": true,\n \"type\": \"int(11)\"\n \
\ }\n ]\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "-- this is comment\n DROP DATABASE test;\n CREATE TABLE\
\ t(a int);"
ignore_case_sensitive: false
want: ''
- err:
+ advice:
+ status: 1
code: 703
+ title: Database `test` is deleted
content: Database `test` is deleted
- line: 3
+ startPosition:
+ line: 3
- statement: "CREATE TABLE t(\n a int PRIMARY KEY DEFAULT 1,\n b varchar(200) CHARACTER\
\ SET utf8mb4 NOT NULL UNIQUE,\n c int auto_increment NULL COMMENT 'This is a\
\ comment',\n d varchar(10) COLLATE utf8mb4_polish_ci,\n e int,\n KEY idx_a\
@@ -328,7 +380,7 @@
\ \"visible\": true\n }\n ],\n \"engine\": \"\
INNODB\",\n \"collation\": \"utf8mb4_0900_ai_ci\",\n \"comment\"\
: \"This is a table comment\"\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE t(\n a int PRIMARY KEY DEFAULT 1,\n b varchar(200) CHARACTER\
\ SET utf8mb4 NOT NULL UNIQUE,\n c int auto_increment NULL COMMENT 'This is a\
\ comment',\n d varchar(10) COLLATE utf8mb4_polish_ci\n);\nCREATE INDEX idx_a\
@@ -367,7 +419,7 @@
name\": \"idx_a\",\n \"expressions\": [\n \"a\"\n\
\ ],\n \"type\": \"BTREE\",\n \"visible\"\
: true\n }\n ]\n }\n ]\n }\n ]\n}"
- err: null
+ advice: null
- statement: "CREATE TABLE t(\n a int PRIMARY KEY DEFAULT 1,\n b varchar(200) CHARACTER\
\ SET utf8mb4 NOT NULL UNIQUE\n);\nDROP INDEX b on t;"
ignore_case_sensitive: false
@@ -383,4 +435,4 @@
\ \"unique\": true,\n \"primary\": true,\n \
\ \"visible\": true\n }\n ]\n }\n ]\n }\n\
\ ]\n}"
- err: null
+ advice: null
diff --git a/backend/plugin/schema/tidb/walk_through.go b/backend/plugin/schema/tidb/walk_through.go
index c34ff2a533..d75d8e869d 100644
--- a/backend/plugin/schema/tidb/walk_through.go
+++ b/backend/plugin/schema/tidb/walk_through.go
@@ -15,7 +15,6 @@ import (
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
"github.com/bytebase/bytebase/backend/plugin/advisor/code"
"github.com/bytebase/bytebase/backend/plugin/schema"
- "github.com/bytebase/bytebase/backend/plugin/schema/catalogutil"
"github.com/bytebase/bytebase/backend/store/model"
)
@@ -28,12 +27,19 @@ const (
SpatialName string = "SPATIAL"
)
+func compareIdentifier(a, b string, ignoreCaseSensitive bool) bool {
+ if ignoreCaseSensitive {
+ return strings.EqualFold(a, b)
+ }
+ return a == b
+}
+
func init() {
schema.RegisterWalkThrough(storepb.Engine_TIDB, WalkThrough)
}
// WalkThrough walks through TiDB AST and updates the database state.
-func WalkThrough(d *model.DatabaseMetadata, ast any) error {
+func WalkThrough(d *model.DatabaseMetadata, ast any) *storepb.Advice {
// We define the Catalog as Database -> Schema -> Table. The Schema is only for PostgreSQL.
// So we use a Schema whose name is empty for other engines, such as MySQL.
// If there is no empty-string-name schema, create it to avoid corner cases.
@@ -43,7 +49,8 @@ func WalkThrough(d *model.DatabaseMetadata, ast any) error {
nodeList, ok := ast.([]tidbast.StmtNode)
if !ok {
- return errors.Errorf("invalid ast type %T", ast)
+ // Internal error - invalid AST type, return nil to skip walkthrough
+ return nil
}
for _, node := range nodeList {
// change state
@@ -55,13 +62,13 @@ func WalkThrough(d *model.DatabaseMetadata, ast any) error {
return nil
}
-func changeStateTiDB(d *model.DatabaseMetadata, in tidbast.StmtNode) (err *catalogutil.WalkThroughError) {
+func changeStateTiDB(d *model.DatabaseMetadata, in tidbast.StmtNode) (err *storepb.Advice) {
defer func() {
if err == nil {
return
}
- if err.Line == 0 {
- err.Line = in.OriginTextPosition()
+ if err.StartPosition.Line == 0 {
+ err.StartPosition.Line = int32(in.OriginTextPosition())
}
}()
// Note: removed database deleted check as it's not stored in protobuf
@@ -81,7 +88,14 @@ func changeStateTiDB(d *model.DatabaseMetadata, in tidbast.StmtNode) (err *catal
case *tidbast.DropDatabaseStmt:
return tidbDropDatabase(d, node)
case *tidbast.CreateDatabaseStmt:
- return catalogutil.NewAccessOtherDatabaseError(d.GetProto().Name, node.Name.O)
+ content := fmt.Sprintf("Database `%s` is not the current database `%s`", node.Name.O, d.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
case *tidbast.RenameTableStmt:
return tidbRenameTable(d, node)
default:
@@ -89,7 +103,7 @@ func changeStateTiDB(d *model.DatabaseMetadata, in tidbast.StmtNode) (err *catal
}
}
-func tidbRenameTable(d *model.DatabaseMetadata, node *tidbast.RenameTableStmt) *catalogutil.WalkThroughError {
+func tidbRenameTable(d *model.DatabaseMetadata, node *tidbast.RenameTableStmt) *storepb.Advice {
for _, tableToTable := range node.TableToTables {
schema := d.GetSchema("")
if schema == nil {
@@ -103,23 +117,63 @@ func tidbRenameTable(d *model.DatabaseMetadata, node *tidbast.RenameTableStmt) *
}
table := schema.GetTable(oldTableName)
if table == nil {
- return catalogutil.NewTableNotExistsError(oldTableName)
+ content := fmt.Sprintf("Table `%s` does not exist", oldTableName)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
if schema.GetTable(newTableName) != nil {
- return catalogutil.NewTableExistsError(newTableName)
+ content := fmt.Sprintf("Table `%s` already exists", newTableName)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
if err := schema.RenameTable(table.GetProto().Name, newTableName); err != nil {
- return &catalogutil.WalkThroughError{Code: code.TableNotExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
} else if tidbMoveToOtherDatabase(d, tableToTable) {
if schema.GetTable(tableToTable.OldTable.Name.O) == nil {
- return catalogutil.NewTableNotExistsError(tableToTable.OldTable.Name.O)
+ content := fmt.Sprintf("Table `%s` does not exist", tableToTable.OldTable.Name.O)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
if err := schema.DropTable(tableToTable.OldTable.Name.O); err != nil {
- return &catalogutil.WalkThroughError{Code: code.TableNotExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
} else {
- return catalogutil.NewAccessOtherDatabaseError(d.GetProto().Name, tidbTargetDatabase(d, tableToTable))
+ content := fmt.Sprintf("Database `%s` is not the current database `%s`", tidbTargetDatabase(d, tableToTable), d.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
}
return nil
@@ -149,9 +203,16 @@ func tidbTheCurrentDatabase(d *model.DatabaseMetadata, node *tidbast.TableToTabl
return true
}
-func tidbDropDatabase(d *model.DatabaseMetadata, node *tidbast.DropDatabaseStmt) *catalogutil.WalkThroughError {
+func tidbDropDatabase(d *model.DatabaseMetadata, node *tidbast.DropDatabaseStmt) *storepb.Advice {
if !isCurrentDatabase(d, node.Name.O) {
- return catalogutil.NewAccessOtherDatabaseError(d.GetProto().Name, node.Name.O)
+ content := fmt.Sprintf("Database `%s` is not the current database `%s`", node.Name.O, d.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
// Note: In walk-through, we don't need to actually delete the database metadata
@@ -159,9 +220,16 @@ func tidbDropDatabase(d *model.DatabaseMetadata, node *tidbast.DropDatabaseStmt)
return nil
}
-func tidbAlterDatabase(d *model.DatabaseMetadata, node *tidbast.AlterDatabaseStmt) *catalogutil.WalkThroughError {
+func tidbAlterDatabase(d *model.DatabaseMetadata, node *tidbast.AlterDatabaseStmt) *storepb.Advice {
if !node.AlterDefaultDatabase && !isCurrentDatabase(d, node.Name.O) {
- return catalogutil.NewAccessOtherDatabaseError(d.GetProto().Name, node.Name.O)
+ content := fmt.Sprintf("Database `%s` is not the current database `%s`", node.Name.O, d.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
for _, option := range node.Options {
@@ -177,9 +245,16 @@ func tidbAlterDatabase(d *model.DatabaseMetadata, node *tidbast.AlterDatabaseStm
return nil
}
-func tidbFindTableState(d *model.DatabaseMetadata, tableName *tidbast.TableName) (*model.TableMetadata, *catalogutil.WalkThroughError) {
+func tidbFindTableState(d *model.DatabaseMetadata, tableName *tidbast.TableName) (*model.TableMetadata, *storepb.Advice) {
if tableName.Schema.O != "" && !isCurrentDatabase(d, tableName.Schema.O) {
- return nil, catalogutil.NewAccessOtherDatabaseError(d.GetProto().Name, tableName.Schema.O)
+ content := fmt.Sprintf("Database `%s` is not the current database `%s`", tableName.Schema.O, d.GetProto().Name)
+ return nil, &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
schema := d.GetSchema("")
@@ -189,25 +264,38 @@ func tidbFindTableState(d *model.DatabaseMetadata, tableName *tidbast.TableName)
table := schema.GetTable(tableName.Name.O)
if table == nil {
- return nil, catalogutil.NewTableNotExistsError(tableName.Name.O)
+ content := fmt.Sprintf("Table `%s` does not exist", tableName.Name.O)
+ return nil, &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
return table, nil
}
-func tidbDropIndex(d *model.DatabaseMetadata, node *tidbast.DropIndexStmt) *catalogutil.WalkThroughError {
+func tidbDropIndex(d *model.DatabaseMetadata, node *tidbast.DropIndexStmt) *storepb.Advice {
table, err := tidbFindTableState(d, node.Table)
if err != nil {
return err
}
if err := table.DropIndex(node.IndexName); err != nil {
- return &catalogutil.WalkThroughError{Code: code.IndexNotExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
return nil
}
-func tidbHandleCreateIndex(d *model.DatabaseMetadata, node *tidbast.CreateIndexStmt) *catalogutil.WalkThroughError {
+func tidbHandleCreateIndex(d *model.DatabaseMetadata, node *tidbast.CreateIndexStmt) *storepb.Advice {
table, err := tidbFindTableState(d, node.Table)
if err != nil {
return err
@@ -238,7 +326,7 @@ func tidbHandleCreateIndex(d *model.DatabaseMetadata, node *tidbast.CreateIndexS
return tidbCreateIndexHelper(table, node.IndexName, keyList, unique, tp, node.IndexOption)
}
-func tidbAlterTable(d *model.DatabaseMetadata, node *tidbast.AlterTableStmt) *catalogutil.WalkThroughError {
+func tidbAlterTable(d *model.DatabaseMetadata, node *tidbast.AlterTableStmt) *storepb.Advice {
table, err := tidbFindTableState(d, node.Table)
if err != nil {
return err
@@ -297,18 +385,44 @@ func tidbAlterTable(d *model.DatabaseMetadata, node *tidbast.AlterTableStmt) *ca
columnName := spec.OldColumnName.Name.O
// Validate column exists
if table.GetColumn(columnName) == nil {
- return catalogutil.NewColumnNotExistsError(table.GetProto().Name, columnName)
+ content := fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, table.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
if err := table.DropColumn(columnName); err != nil {
- return &catalogutil.WalkThroughError{Code: code.Internal, Content: fmt.Sprintf("failed to drop column: %v", err)}
+ content := fmt.Sprintf("failed to drop column: %v", err)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
case tidbast.AlterTableDropPrimaryKey:
if err := table.DropIndex(PrimaryKeyName); err != nil {
- return &catalogutil.WalkThroughError{Code: code.IndexNotExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
case tidbast.AlterTableDropIndex:
if err := table.DropIndex(spec.Name); err != nil {
- return &catalogutil.WalkThroughError{Code: code.IndexNotExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
case tidbast.AlterTableDropForeignKey:
// we do not deal with DROP FOREIGN KEY statements.
@@ -325,22 +439,46 @@ func tidbAlterTable(d *model.DatabaseMetadata, node *tidbast.AlterTableStmt) *ca
newColumnName := spec.NewColumnName.Name.O
// Validate old column exists
if table.GetColumn(oldColumnName) == nil {
- return catalogutil.NewColumnNotExistsError(table.GetProto().Name, oldColumnName)
+ content := fmt.Sprintf("Column `%s` does not exist in table `%s`", oldColumnName, table.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
// Validate new column doesn't already exist
if table.GetColumn(newColumnName) != nil {
- return &catalogutil.WalkThroughError{
- Code: code.ColumnExists,
- Content: fmt.Sprintf("Column `%s` already exists in table `%s`", newColumnName, table.GetProto().Name),
+ content := fmt.Sprintf("Column `%s` already exists in table `%s`", newColumnName, table.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
if err := table.RenameColumn(oldColumnName, newColumnName); err != nil {
- return &catalogutil.WalkThroughError{Code: code.Internal, Content: fmt.Sprintf("failed to rename column: %v", err)}
+ content := fmt.Sprintf("failed to rename column: %v", err)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
case tidbast.AlterTableRenameTable:
schema := d.GetSchema("")
if err := schema.RenameTable(table.GetProto().Name, spec.NewTable.Name.O); err != nil {
- return &catalogutil.WalkThroughError{Code: code.TableNotExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
case tidbast.AlterTableAlterColumn:
if err := tidbChangeColumnDefault(table, spec.NewColumns[0]); err != nil {
@@ -349,14 +487,35 @@ func tidbAlterTable(d *model.DatabaseMetadata, node *tidbast.AlterTableStmt) *ca
case tidbast.AlterTableRenameIndex:
// Validate old index exists
if table.GetIndex(spec.FromKey.O) == nil {
- return &catalogutil.WalkThroughError{Code: code.IndexNotExists, Content: fmt.Sprintf("index %q does not exist in table %q", spec.FromKey.O, table.GetProto().Name)}
+ content := fmt.Sprintf("index %q does not exist in table %q", spec.FromKey.O, table.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexNotExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
// Validate new index doesn't already exist
if table.GetIndex(spec.ToKey.O) != nil {
- return &catalogutil.WalkThroughError{Code: code.IndexExists, Content: fmt.Sprintf("index %q already exists in table %q", spec.ToKey.O, table.GetProto().Name)}
+ content := fmt.Sprintf("index %q already exists in table %q", spec.ToKey.O, table.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
if err := table.RenameIndex(spec.FromKey.O, spec.ToKey.O); err != nil {
- return &catalogutil.WalkThroughError{Code: code.Internal, Content: fmt.Sprintf("failed to rename index: %v", err)}
+ content := fmt.Sprintf("failed to rename index: %v", err)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
case tidbast.AlterTableIndexInvisible:
if err := tidbChangeIndexVisibility(table, spec.IndexName.O, spec.Visibility); err != nil {
@@ -370,10 +529,17 @@ func tidbAlterTable(d *model.DatabaseMetadata, node *tidbast.AlterTableStmt) *ca
return nil
}
-func tidbChangeIndexVisibility(t *model.TableMetadata, indexName string, visibility tidbast.IndexVisibility) *catalogutil.WalkThroughError {
+func tidbChangeIndexVisibility(t *model.TableMetadata, indexName string, visibility tidbast.IndexVisibility) *storepb.Advice {
index := t.GetIndex(indexName)
if index == nil {
- return catalogutil.NewIndexNotExistsError(t.GetProto().Name, indexName)
+ content := fmt.Sprintf("Index `%s` does not exist in table `%s`", indexName, t.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexNotExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
switch visibility {
case tidbast.IndexVisibilityVisible:
@@ -386,11 +552,18 @@ func tidbChangeIndexVisibility(t *model.TableMetadata, indexName string, visibil
return nil
}
-func tidbChangeColumnDefault(t *model.TableMetadata, column *tidbast.ColumnDef) *catalogutil.WalkThroughError {
+func tidbChangeColumnDefault(t *model.TableMetadata, column *tidbast.ColumnDef) *storepb.Advice {
columnName := column.Name.Name.L
col := t.GetColumn(columnName)
if col == nil {
- return catalogutil.NewColumnNotExistsError(t.GetProto().Name, columnName)
+ content := fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, t.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
if len(column.Options) == 1 {
@@ -402,10 +575,13 @@ func tidbChangeColumnDefault(t *model.TableMetadata, column *tidbast.ColumnDef)
"text", "tinytext", "mediumtext", "longtext",
"json",
"geometry":
- return &catalogutil.WalkThroughError{
- Code: code.InvalidColumnDefault,
- // Content comes from MySQL Error content.
- Content: fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName),
+ content := fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.InvalidColumnDefault.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
default:
// Other column types allow default values
@@ -414,18 +590,25 @@ func tidbChangeColumnDefault(t *model.TableMetadata, column *tidbast.ColumnDef)
defaultValue, err := restoreNode(column.Options[0].Expr, format.RestoreStringWithoutCharset)
if err != nil {
- return &catalogutil.WalkThroughError{
- Code: code.Internal,
- Content: fmt.Sprintf("Failed to deparse default value: %v", err),
+ content := fmt.Sprintf("Failed to deparse default value: %v", err)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
col.Default = defaultValue
} else {
if !col.Nullable {
- return &catalogutil.WalkThroughError{
- Code: code.SetNullDefaultForNotNullColumn,
- // Content comes from MySQL Error content.
- Content: fmt.Sprintf("Invalid default value for column `%s`", columnName),
+ content := fmt.Sprintf("Invalid default value for column `%s`", columnName)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.SetNullDefaultForNotNullColumn.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
col.Default = ""
@@ -455,10 +638,17 @@ func tidbRenameColumnInIndexKey(t *model.TableMetadata, oldName string, newName
// 1. Dropping the old column from the column list (but keeping it in index expressions)
// 2. Renaming the column in index expressions
// 3. Creating a new column with the new definition
-func tidbCompleteTableChangeColumn(t *model.TableMetadata, oldName string, newColumn *tidbast.ColumnDef, position *tidbast.ColumnPosition) *catalogutil.WalkThroughError {
+func tidbCompleteTableChangeColumn(t *model.TableMetadata, oldName string, newColumn *tidbast.ColumnDef, position *tidbast.ColumnPosition) *storepb.Advice {
column := t.GetColumn(oldName)
if column == nil {
- return catalogutil.NewColumnNotExistsError(t.GetProto().Name, oldName)
+ content := fmt.Sprintf("Column `%s` does not exist in table `%s`", oldName, t.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
// Store the current position info if no position specified
@@ -497,7 +687,14 @@ func tidbCompleteTableChangeColumn(t *model.TableMetadata, oldName string, newCo
// We use DropColumnWithoutUpdatingIndexes to remove from internal map and proto
// without affecting index expressions
if err := t.DropColumnWithoutUpdatingIndexes(oldName); err != nil {
- return &catalogutil.WalkThroughError{Code: code.Internal, Content: fmt.Sprintf("failed to drop column: %v", err)}
+ content := fmt.Sprintf("failed to drop column: %v", err)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
// Rename column in index expressions
@@ -530,12 +727,12 @@ func tidbCompleteTableChangeColumn(t *model.TableMetadata, oldName string, newCo
return nil
}
-func tidbChangeColumn(t *model.TableMetadata, oldName string, newColumn *tidbast.ColumnDef, position *tidbast.ColumnPosition) *catalogutil.WalkThroughError {
+func tidbChangeColumn(t *model.TableMetadata, oldName string, newColumn *tidbast.ColumnDef, position *tidbast.ColumnPosition) *storepb.Advice {
return tidbCompleteTableChangeColumn(t, oldName, newColumn, position)
}
// tidbReorderColumn reorders the columns for new column and returns the new column position.
-func tidbReorderColumn(t *model.TableMetadata, position *tidbast.ColumnPosition) (int, *catalogutil.WalkThroughError) {
+func tidbReorderColumn(t *model.TableMetadata, position *tidbast.ColumnPosition) (int, *storepb.Advice) {
switch position.Tp {
case tidbast.ColumnPositionNone:
return len(t.GetColumns()) + 1, nil
@@ -548,7 +745,14 @@ func tidbReorderColumn(t *model.TableMetadata, position *tidbast.ColumnPosition)
columnName := position.RelativeColumn.Name.L
column := t.GetColumn(columnName)
if column == nil {
- return 0, catalogutil.NewColumnNotExistsError(t.GetProto().Name, columnName)
+ content := fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, t.GetProto().Name)
+ return 0, &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
for _, col := range t.GetColumns() {
if col.Position > column.Position {
@@ -557,21 +761,29 @@ func tidbReorderColumn(t *model.TableMetadata, position *tidbast.ColumnPosition)
}
return int(column.Position) + 1, nil
default:
- return 0, &catalogutil.WalkThroughError{
- Code: code.Unsupported,
- Content: fmt.Sprintf("Unsupported column position type: %d", position.Tp),
+ content := fmt.Sprintf("Unsupported column position type: %d", position.Tp)
+ return 0, &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Unsupported.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
}
-func tidbDropTable(d *model.DatabaseMetadata, node *tidbast.DropTableStmt) *catalogutil.WalkThroughError {
+func tidbDropTable(d *model.DatabaseMetadata, node *tidbast.DropTableStmt) *storepb.Advice {
// TODO(rebelice): deal with DROP VIEW statement.
if !node.IsView {
for _, name := range node.Tables {
if name.Schema.O != "" && !isCurrentDatabase(d, name.Schema.O) {
- return &catalogutil.WalkThroughError{
- Code: code.NotCurrentDatabase,
- Content: fmt.Sprintf("Database `%s` is not the current database `%s`", name.Schema.O, d.GetProto().Name),
+ content := fmt.Sprintf("Database `%s` is not the current database `%s`", name.Schema.O, d.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
@@ -585,27 +797,41 @@ func tidbDropTable(d *model.DatabaseMetadata, node *tidbast.DropTableStmt) *cata
if node.IfExists {
return nil
}
- return &catalogutil.WalkThroughError{
- Code: code.TableNotExists,
- Content: fmt.Sprintf("Table `%s` does not exist", name.Name.O),
+ content := fmt.Sprintf("Table `%s` does not exist", name.Name.O)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
if err := schema.DropTable(table.GetProto().Name); err != nil {
- return &catalogutil.WalkThroughError{Code: code.TableNotExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableNotExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
}
}
return nil
}
-func tidbCopyTable(d *model.DatabaseMetadata, node *tidbast.CreateTableStmt) *catalogutil.WalkThroughError {
+func tidbCopyTable(d *model.DatabaseMetadata, node *tidbast.CreateTableStmt) *storepb.Advice {
targetTable, err := tidbFindTableState(d, node.ReferTable)
if err != nil {
- if err.Code == code.NotCurrentDatabase {
- return &catalogutil.WalkThroughError{
- Code: code.ReferenceOtherDatabase,
- Content: fmt.Sprintf("Reference table `%s` in other database `%s`, skip walkthrough", node.ReferTable.Name.O, node.ReferTable.Schema.O),
+ if err.Code == code.NotCurrentDatabase.Int32() {
+ content := fmt.Sprintf("Reference table `%s` in other database `%s`, skip walkthrough", node.ReferTable.Name.O, node.ReferTable.Schema.O)
+ return &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.ReferenceOtherDatabase.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
return err
@@ -615,37 +841,71 @@ func tidbCopyTable(d *model.DatabaseMetadata, node *tidbast.CreateTableStmt) *ca
// Create new table
newTable, createErr := schema.CreateTable(node.Table.Name.O)
if createErr != nil {
- return &catalogutil.WalkThroughError{Code: code.TableExists, Content: createErr.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableExists.Int32(),
+ Title: createErr.Error(),
+ Content: createErr.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
// Copy columns and indexes from the target table
for _, col := range targetTable.GetColumns() {
colCopy, ok := proto.Clone(col).(*storepb.ColumnMetadata)
if !ok {
- return &catalogutil.WalkThroughError{Code: code.Internal, Content: "failed to clone column metadata"}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: "failed to clone column metadata",
+ Content: "failed to clone column metadata",
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
if err := newTable.CreateColumn(colCopy); err != nil {
- return &catalogutil.WalkThroughError{Code: code.ColumnExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
}
for _, idx := range targetTable.GetProto().Indexes {
idxCopy, ok := proto.Clone(idx).(*storepb.IndexMetadata)
if !ok {
- return &catalogutil.WalkThroughError{Code: code.Internal, Content: "failed to clone index metadata"}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: "failed to clone index metadata",
+ Content: "failed to clone index metadata",
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
if err := newTable.CreateIndex(idxCopy); err != nil {
- return &catalogutil.WalkThroughError{Code: code.IndexExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
}
return nil
}
-func tidbCreateTable(d *model.DatabaseMetadata, node *tidbast.CreateTableStmt) *catalogutil.WalkThroughError {
+func tidbCreateTable(d *model.DatabaseMetadata, node *tidbast.CreateTableStmt) *storepb.Advice {
if node.Table.Schema.O != "" && !isCurrentDatabase(d, node.Table.Schema.O) {
- return &catalogutil.WalkThroughError{
- Code: code.NotCurrentDatabase,
- Content: fmt.Sprintf("Database `%s` is not the current database `%s`", node.Table.Schema.O, d.GetProto().Name),
+ content := fmt.Sprintf("Database `%s` is not the current database `%s`", node.Table.Schema.O, d.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_WARNING,
+ Code: code.NotCurrentDatabase.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
@@ -658,16 +918,24 @@ func tidbCreateTable(d *model.DatabaseMetadata, node *tidbast.CreateTableStmt) *
if node.IfNotExists {
return nil
}
- return &catalogutil.WalkThroughError{
- Code: code.TableExists,
- Content: fmt.Sprintf("Table `%s` already exists", node.Table.Name.O),
+ content := fmt.Sprintf("Table `%s` already exists", node.Table.Name.O)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
if node.Select != nil {
- return &catalogutil.WalkThroughError{
- Code: code.StatementCreateTableAs,
- Content: fmt.Sprintf("Disallow the CREATE TABLE AS statement but \"%s\" uses", node.Text()),
+ content := fmt.Sprintf("Disallow the CREATE TABLE AS statement but \"%s\" uses", node.Text())
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.StatementCreateTableAs.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
@@ -677,7 +945,13 @@ func tidbCreateTable(d *model.DatabaseMetadata, node *tidbast.CreateTableStmt) *
table, createErr := schema.CreateTable(node.Table.Name.O)
if createErr != nil {
- return &catalogutil.WalkThroughError{Code: code.TableExists, Content: createErr.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.TableExists.Int32(),
+ Title: createErr.Error(),
+ Content: createErr.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
hasAutoIncrement := false
@@ -685,23 +959,26 @@ func tidbCreateTable(d *model.DatabaseMetadata, node *tidbast.CreateTableStmt) *
for _, column := range node.Cols {
if isAutoIncrementColumn(column) {
if hasAutoIncrement {
- return &catalogutil.WalkThroughError{
- Code: code.AutoIncrementExists,
- // The content comes from MySQL error content.
- Content: fmt.Sprintf("There can be only one auto column for table `%s`", table.GetProto().Name),
+ content := fmt.Sprintf("There can be only one auto column for table `%s`", table.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.AutoIncrementExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: int32(column.OriginTextPosition())},
}
}
hasAutoIncrement = true
}
if err := tidbCreateColumnHelper(table, column, nil /* position */); err != nil {
- err.Line = column.OriginTextPosition()
+ err.StartPosition.Line = int32(column.OriginTextPosition())
return err
}
}
for _, constraint := range node.Constraints {
if err := tidbCreateConstraint(table, constraint); err != nil {
- err.Line = constraint.OriginTextPosition()
+ err.StartPosition.Line = int32(constraint.OriginTextPosition())
return err
}
}
@@ -709,7 +986,7 @@ func tidbCreateTable(d *model.DatabaseMetadata, node *tidbast.CreateTableStmt) *
return nil
}
-func tidbCreateConstraint(t *model.TableMetadata, constraint *tidbast.Constraint) *catalogutil.WalkThroughError {
+func tidbCreateConstraint(t *model.TableMetadata, constraint *tidbast.Constraint) *storepb.Advice {
switch constraint.Tp {
case tidbast.ConstraintPrimaryKey:
keyList, err := tidbValidateAndGetKeyStringList(t, constraint.Keys, true /* primary */, false /* isSpatial */)
@@ -754,15 +1031,19 @@ func tidbCreateConstraint(t *model.TableMetadata, constraint *tidbast.Constraint
return nil
}
-func tidbValidateAndGetKeyStringList(t *model.TableMetadata, keyList []*tidbast.IndexPartSpecification, primary bool, isSpatial bool) ([]string, *catalogutil.WalkThroughError) {
+func tidbValidateAndGetKeyStringList(t *model.TableMetadata, keyList []*tidbast.IndexPartSpecification, primary bool, isSpatial bool) ([]string, *storepb.Advice) {
var res []string
for _, key := range keyList {
if key.Expr != nil {
str, err := restoreNode(key, format.DefaultRestoreFlags)
if err != nil {
- return nil, &catalogutil.WalkThroughError{
- Code: code.Internal,
- Content: fmt.Sprintf("Failed to deparse index key: %v", err),
+ content := fmt.Sprintf("Failed to deparse index key: %v", err)
+ return nil, &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
res = append(res, str)
@@ -770,16 +1051,26 @@ func tidbValidateAndGetKeyStringList(t *model.TableMetadata, keyList []*tidbast.
columnName := key.Column.Name.L
column := t.GetColumn(columnName)
if column == nil {
- return nil, catalogutil.NewColumnNotExistsError(t.GetProto().Name, columnName)
+ content := fmt.Sprintf("Column `%s` does not exist in table `%s`", columnName, t.GetProto().Name)
+ return nil, &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnNotExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
if primary {
column.Nullable = false
}
if isSpatial && column.Nullable {
- return nil, &catalogutil.WalkThroughError{
- Code: code.SpatialIndexKeyNullable,
- // 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),
+ content := fmt.Sprintf("All parts of a SPATIAL index must be NOT NULL, but `%s` is nullable", column.Name)
+ return nil, &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.SpatialIndexKeyNullable.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
@@ -798,14 +1089,17 @@ func isAutoIncrementColumn(column *tidbast.ColumnDef) bool {
return false
}
-func checkDefault(columnName string, columnType *types.FieldType, value tidbast.ExprNode) *catalogutil.WalkThroughError {
+func checkDefault(columnName string, columnType *types.FieldType, value tidbast.ExprNode) *storepb.Advice {
if value.GetType().GetType() != mysql.TypeNull {
switch columnType.GetType() {
case mysql.TypeBlob, mysql.TypeTinyBlob, mysql.TypeMediumBlob, mysql.TypeLongBlob, mysql.TypeJSON, mysql.TypeGeometry:
- return &catalogutil.WalkThroughError{
- Code: code.InvalidColumnDefault,
- // Content comes from MySQL Error content.
- Content: fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName),
+ content := fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.InvalidColumnDefault.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
default:
// Other column types allow default values
@@ -815,26 +1109,33 @@ 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 &catalogutil.WalkThroughError{
- Code: code.InvalidColumnDefault,
- Content: err.Error(),
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.InvalidColumnDefault.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
}
}
}
return nil
}
-func tidbCreateColumnHelper(t *model.TableMetadata, column *tidbast.ColumnDef, position *tidbast.ColumnPosition) *catalogutil.WalkThroughError {
+func tidbCreateColumnHelper(t *model.TableMetadata, column *tidbast.ColumnDef, position *tidbast.ColumnPosition) *storepb.Advice {
if t.GetColumn(column.Name.Name.L) != nil {
- return &catalogutil.WalkThroughError{
- Code: code.ColumnExists,
- Content: fmt.Sprintf("Column `%s` already exists in table `%s`", column.Name.Name.O, t.GetProto().Name),
+ content := fmt.Sprintf("Column `%s` already exists in table `%s`", column.Name.Name.O, t.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
pos := len(t.GetColumns()) + 1
if position != nil {
- var err *catalogutil.WalkThroughError
+ var err *storepb.Advice
pos, err = tidbReorderColumn(t, position)
if err != nil {
return err
@@ -870,9 +1171,13 @@ func tidbCreateColumnHelper(t *model.TableMetadata, column *tidbast.ColumnDef, p
if option.Expr.GetType().GetType() != mysql.TypeNull {
defaultValue, err := restoreNode(option.Expr, format.RestoreStringWithoutCharset)
if err != nil {
- return &catalogutil.WalkThroughError{
- Code: code.Internal,
- Content: fmt.Sprintf("Failed to deparse default value: %v", err),
+ content := fmt.Sprintf("Failed to deparse default value: %v", err)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
col.Default = defaultValue
@@ -888,17 +1193,25 @@ func tidbCreateColumnHelper(t *model.TableMetadata, column *tidbast.ColumnDef, p
case tidbast.ColumnOptionOnUpdate:
// we do not deal with ON UPDATE
if column.Tp.GetType() != mysql.TypeDatetime && column.Tp.GetType() != mysql.TypeTimestamp {
- return &catalogutil.WalkThroughError{
- Code: code.OnUpdateColumnNotDatetimeOrTimestamp,
- Content: fmt.Sprintf("Column `%s` use ON UPDATE but is not DATETIME or TIMESTAMP", col.Name),
+ content := fmt.Sprintf("Column `%s` use ON UPDATE but is not DATETIME or TIMESTAMP", col.Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.OnUpdateColumnNotDatetimeOrTimestamp.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
case tidbast.ColumnOptionComment:
comment, err := restoreNode(option.Expr, format.RestoreStringWithoutCharset)
if err != nil {
- return &catalogutil.WalkThroughError{
- Code: code.Internal,
- Content: fmt.Sprintf("Failed to deparse comment: %v", err),
+ content := fmt.Sprintf("Failed to deparse comment: %v", err)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.Internal.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
col.Comment = comment
@@ -923,29 +1236,49 @@ func tidbCreateColumnHelper(t *model.TableMetadata, column *tidbast.ColumnDef, p
}
if !col.Nullable && setNullDefault {
- return &catalogutil.WalkThroughError{
- Code: code.SetNullDefaultForNotNullColumn,
- // Content comes from MySQL Error content.
- Content: fmt.Sprintf("Invalid default value for column `%s`", col.Name),
+ content := fmt.Sprintf("Invalid default value for column `%s`", col.Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.SetNullDefaultForNotNullColumn.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
if err := t.CreateColumn(col); err != nil {
- return &catalogutil.WalkThroughError{Code: code.ColumnExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.ColumnExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
return nil
}
-func tidbCreateIndexHelper(t *model.TableMetadata, name string, keyList []string, unique bool, tp string, option *tidbast.IndexOption) *catalogutil.WalkThroughError {
+func tidbCreateIndexHelper(t *model.TableMetadata, name string, keyList []string, unique bool, tp string, option *tidbast.IndexOption) *storepb.Advice {
if len(keyList) == 0 {
- return &catalogutil.WalkThroughError{
- Code: code.IndexEmptyKeys,
- Content: fmt.Sprintf("Index `%s` in table `%s` has empty key", name, t.GetProto().Name),
+ content := fmt.Sprintf("Index `%s` in table `%s` has empty key", name, t.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexEmptyKeys.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
if name != "" {
if t.GetIndex(name) != nil {
- return catalogutil.NewIndexExistsError(t.GetProto().Name, name)
+ content := fmt.Sprintf("Index `%s` already exists in table `%s`", name, t.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
} else {
suffix := 1
@@ -973,16 +1306,26 @@ func tidbCreateIndexHelper(t *model.TableMetadata, name string, keyList []string
}
if err := t.CreateIndex(index); err != nil {
- return &catalogutil.WalkThroughError{Code: code.IndexExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
return nil
}
-func tidbCreatePrimaryKeyHelper(t *model.TableMetadata, keys []string, tp string) *catalogutil.WalkThroughError {
+func tidbCreatePrimaryKeyHelper(t *model.TableMetadata, keys []string, tp string) *storepb.Advice {
if t.GetIndex(PrimaryKeyName) != nil {
- return &catalogutil.WalkThroughError{
- Code: code.PrimaryKeyExists,
- Content: fmt.Sprintf("Primary key exists in table `%s`", t.GetProto().Name),
+ content := fmt.Sprintf("Primary key exists in table `%s`", t.GetProto().Name)
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.PrimaryKeyExists.Int32(),
+ Title: content,
+ Content: content,
+ StartPosition: &storepb.Position{Line: 0},
}
}
@@ -995,7 +1338,13 @@ func tidbCreatePrimaryKeyHelper(t *model.TableMetadata, keys []string, tp string
Visible: true,
}
if err := t.CreateIndex(pk); err != nil {
- return &catalogutil.WalkThroughError{Code: code.IndexExists, Content: err.Error()}
+ return &storepb.Advice{
+ Status: storepb.Advice_ERROR,
+ Code: code.IndexExists.Int32(),
+ Title: err.Error(),
+ Content: err.Error(),
+ StartPosition: &storepb.Position{Line: 0},
+ }
}
return nil
}
@@ -1025,5 +1374,5 @@ func getIndexType(option *tidbast.IndexOption) string {
// isCurrentDatabase returns true if the given database is the current database.
func isCurrentDatabase(d *model.DatabaseMetadata, database string) bool {
- return catalogutil.CompareIdentifier(d.DatabaseName(), database, !d.GetIsObjectCaseSensitive())
+ return compareIdentifier(d.DatabaseName(), database, !d.GetIsObjectCaseSensitive())
}
diff --git a/backend/plugin/schema/tidb/walk_through_test.go b/backend/plugin/schema/tidb/walk_through_test.go
index ccfd066cb1..ee19881075 100644
--- a/backend/plugin/schema/tidb/walk_through_test.go
+++ b/backend/plugin/schema/tidb/walk_through_test.go
@@ -15,7 +15,6 @@ import (
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/component/sheet"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
- "github.com/bytebase/bytebase/backend/plugin/schema/catalogutil"
"github.com/bytebase/bytebase/backend/store/model"
)
@@ -24,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 *catalogutil.WalkThroughError
+ Advice *storepb.Advice
}
func TestWalkThrough(t *testing.T) {
@@ -53,14 +52,13 @@ func TestWalkThrough(t *testing.T) {
state := model.NewDatabaseMetadata(protoData, !test.IgnoreCaseSensitive, !test.IgnoreCaseSensitive)
asts, _ := sm.GetASTsForChecks(storepb.Engine_TIDB, test.Statement)
- err := WalkThrough(state, asts)
- if err != nil {
- walkErr, yes := err.(*catalogutil.WalkThroughError)
- require.True(t, yes)
- require.Equal(t, test.Err, walkErr)
+ advice := WalkThrough(state, asts)
+ if advice != nil {
+ // Compare the advice fields
+ require.Equal(t, test.Advice.Code, advice.Code)
+ require.Equal(t, test.Advice.Content, advice.Content)
continue
}
- require.NoError(t, err, test.Statement)
// Skip comparison if want is empty (error cases)
if test.Want == "" {
@@ -68,7 +66,7 @@ func TestWalkThrough(t *testing.T) {
}
want := &storepb.DatabaseSchemaMetadata{}
- err = common.ProtojsonUnmarshaler.Unmarshal([]byte(test.Want), want)
+ err := common.ProtojsonUnmarshaler.Unmarshal([]byte(test.Want), want)
require.NoError(t, err)
// Sort proto for deterministic comparison
state.SortProto()