Skip to content

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

chore: support create column attributions (#9426)

zll600e4c631e24f90
diff --git a/backend/plugin/advisor/catalog/test/mysqlv2_walk_through.yaml b/backend/plugin/advisor/catalog/test/mysqlv2_walk_through.yaml
index 5b7e33ae8e..dfd10d9c5f 100644
--- a/backend/plugin/advisor/catalog/test/mysqlv2_walk_through.yaml
+++ b/backend/plugin/advisor/catalog/test/mysqlv2_walk_through.yaml
@@ -1,31 +1,112 @@
- statement: |-
CREATE TABLE t1(
- col1 CHAR(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_i,
- col2 INT
+ a INT NOT NULL DEFAULT NULL
+ );
+ ignore_case_sensitive: false
+ want: ""
+ err:
+ type: 406
+ content: Invalid default value for column `a`
+ line: 2
+ payload: null
+- statement: |-
+ CREATE TABLE t1(
+ a BLOB DEFAULT 'this is a default value'
+ );
+ ignore_case_sensitive: false
+ want: ""
+ err:
+ type: 407
+ content: BLOB, TEXT, GEOMETRY or JSON column `a` can't have a default value
+ line: 2
+ payload: null
+- statement: |-
+ CREATE TABLE t1(
+ a INT ON UPDATE NOW()
+ );
+ ignore_case_sensitive: false
+ want: ""
+ err:
+ type: 405
+ content: Column `a` use ON UPDATE but is not DATETIME or TIMESTAMP
+ line: 2
+ payload: null
+- statement: |-
+ CREATE TABLE t1(
+ a INT NOT NULL DEFAULT 1 PRIMARY KEY,
+ b INT UNIQUE,
+ c VARCHAR(255) NOT NULL DEFAULT 'NULL' COMMENT 'column c',
+ e INT NULL DEFAULT NULL,
+ f VARCHAR(10) NOT NULL COLLATE utf8mb4_polish_ci,
+ g VARCHAR(200) CHARACTER SET utf8mb4 NOT NULL
);
ignore_case_sensitive: false
want: |-
{
- "name": "test",
- "schemas": [
+ "name": "test",
+ "schemas": [
{
- "tables": [
+ "tables": [
{
- "name": "t1",
- "columns": [
- {
- "name": "col1",
- "position": 1,
- "nullable": true,
- "type": "char",
- "characterSet": "utf8mb4",
- "collation": "utf8mb4_unicode_i"
+ "name": "t1",
+ "columns": [
+ {
+ "name": "a",
+ "position": 1,
+ "default": "1",
+ "type": "int"
+ },
+ {
+ "name": "b",
+ "position": 2,
+ "nullable": true,
+ "type": "int"
+ },
+ {
+ "name": "c",
+ "position": 3,
+ "default": "NULL",
+ "type": "varchar",
+ "comment": "column c"
+ },
+ {
+ "name": "e",
+ "position": 4,
+ "nullable": true,
+ "type": "int"
+ },
+ {
+ "name": "f",
+ "position": 5,
+ "type": "varchar",
+ "collation": "utf8mb4_polish_ci"
+ },
+ {
+ "name": "g",
+ "position": 6,
+ "type": "varchar",
+ "characterSet": "utf8mb4"
+ }
+ ],
+ "indexes": [
+ {
+ "name": "PRIMARY",
+ "expressions": [
+ "a"
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "primary": true,
+ "visible": true
},
{
- "name": "col2",
- "position": 2,
- "nullable": true,
- "type": "int"
+ "name": "b",
+ "expressions": [
+ "b"
+ ],
+ "type": "BTREE",
+ "unique": true,
+ "visible": true
}
]
}
diff --git a/backend/plugin/advisor/catalog/walk_through_for_mysql_v2.go b/backend/plugin/advisor/catalog/walk_through_for_mysql_v2.go
index cb8a312e09..fdc69983a8 100644
--- a/backend/plugin/advisor/catalog/walk_through_for_mysql_v2.go
+++ b/backend/plugin/advisor/catalog/walk_through_for_mysql_v2.go
@@ -144,19 +144,19 @@ func (t *TableState) mysqlV2CreateColumn(_ *FinderContext, columnDef mysql.IColu
columnType := ""
characterSet := ""
collation := ""
- // todo: use fail-open pattern.
- if columnDef.FieldDefinition() != nil && columnDef.FieldDefinition().DataType() != nil {
- columnType = mysqlparser.NormalizeMySQLDataType(columnDef.FieldDefinition().DataType(), true /* compact */)
- characterSet = mysqlparser.GetCharSetName(columnDef.FieldDefinition().DataType())
- collation = mysqlparser.GetCollationName(columnDef.FieldDefinition())
+ if columnDef.FieldDefinition() == nil || columnDef.FieldDefinition().DataType() == nil {
+ // todo: add more error detail.
+ return nil
}
+ columnType = mysqlparser.NormalizeMySQLDataType(columnDef.FieldDefinition().DataType(), true /* compact */)
+ characterSet = mysqlparser.GetCharSetName(columnDef.FieldDefinition().DataType())
+ collation = mysqlparser.GetCollationName(columnDef.FieldDefinition())
- vTrue := true
col := &ColumnState{
name: columnName,
position: &pos,
defaultValue: nil,
- nullable: &vTrue,
+ nullable: newTruePointer(),
columnType: newStringPointer(columnType),
characterSet: newStringPointer(characterSet),
collation: newStringPointer(collation),
@@ -164,6 +164,81 @@ func (t *TableState) mysqlV2CreateColumn(_ *FinderContext, columnDef mysql.IColu
}
setNullDefault := false
+ for _, attribute := range columnDef.FieldDefinition().AllColumnAttribute() {
+ if attribute == nil {
+ continue
+ }
+ if attribute.CheckConstraint() != nil {
+ // we do not deal with CHECK constraint.
+ continue
+ }
+ // not null.
+ if attribute.NullLiteral() != nil && attribute.NOT_SYMBOL() != nil {
+ col.nullable = newFalsePointer()
+ }
+ if attribute.GetValue() != nil {
+ switch attribute.GetValue().GetTokenType() {
+ // default value.
+ case mysql.MySQLParserDEFAULT_SYMBOL:
+ if err := mysqlV2CheckDefault(columnName, columnDef.FieldDefinition()); err != nil {
+ return err
+ }
+ if attribute.SignedLiteral() == nil {
+ continue
+ }
+ // handle default null.
+ if attribute.SignedLiteral().Literal() != nil && attribute.SignedLiteral().Literal().NullLiteral() != nil {
+ setNullDefault = true
+ continue
+ }
+ // handle default 'null' etc.
+ defaultValue := mysqlparser.NormalizeMySQLSignedLiteral(attribute.SignedLiteral())
+ col.defaultValue = &defaultValue
+ // comment.
+ case mysql.MySQLParserCOMMENT_SYMBOL:
+ if attribute.TextLiteral() == nil {
+ continue
+ }
+ comment := mysqlparser.NormalizeMySQLTextLiteral(attribute.TextLiteral())
+ col.comment = &comment
+ // on update now().
+ case mysql.MySQLParserON_SYMBOL:
+ if attribute.UPDATE_SYMBOL() == nil || attribute.NOW_SYMBOL() == nil {
+ continue
+ }
+ if !mysqlparser.IsTimeType(columnDef.FieldDefinition().DataType()) {
+ return &WalkThroughError{
+ Type: ErrorTypeOnUpdateColumnNotDatetimeOrTimestamp,
+ Content: fmt.Sprintf("Column `%s` use ON UPDATE but is not DATETIME or TIMESTAMP", col.name),
+ }
+ }
+ // primary key.
+ case mysql.MySQLParserKEY_SYMBOL:
+ // the key attribute for in a column meaning primary key.
+ col.nullable = newFalsePointer()
+ // we need to check the key type which generated by tidb parser.
+ if err := t.mysqlV2CreatePrimaryKey([]string{col.name}, "BTREE"); err != nil {
+ return err
+ }
+ // unique key.
+ case mysql.MySQLParserUNIQUE_SYMBOL:
+ // unique index.
+ if err := t.mysqlV2CreateIndex("", []string{col.name}, true /* unique */, "BTREE", mysql.NewEmptyTableConstraintDefContext()); err != nil {
+ return err
+ }
+ // auto_increment.
+ case mysql.MySQLParserAUTO_INCREMENT_SYMBOL:
+ // we do not deal with AUTO_INCREMENT.
+ // column_format.
+ case mysql.MySQLParserCOLUMN_FORMAT_SYMBOL:
+ // we do not deal with COLUMN_FORMAT.
+ // storage.
+ case mysql.MySQLParserSTORAGE_SYMBOL:
+ // we do not deal with STORAGE.
+ }
+ }
+ }
+
if col.nullable != nil && !*col.nullable && setNullDefault {
return &WalkThroughError{
Type: ErrorTypeSetNullDefaultForNotNullColumn,
@@ -172,12 +247,111 @@ func (t *TableState) mysqlV2CreateColumn(_ *FinderContext, columnDef mysql.IColu
}
}
- for _, attribute := range columnDef.FieldDefinition().AllColumnAttribute() {
- if attribute == nil {
+ t.columnSet[col.name] = col
+ return nil
+}
+
+func (t *TableState) mysqlV2CreateIndex(name string, keyList []string, unique bool, tp string, tableConstraint mysql.ITableConstraintDefContext) *WalkThroughError {
+ if len(keyList) == 0 {
+ return &WalkThroughError{
+ Type: ErrorTypeIndexEmptyKeys,
+ Content: fmt.Sprintf("Index `%s` in table `%s` has empty key", name, t.name),
+ }
+ }
+ // construct a index name if name is empty.
+ if name != "" {
+ if _, exists := t.indexSet[name]; exists {
+ return NewIndexExistsError(t.name, name)
+ }
+ } else {
+ suffix := 1
+ for {
+ name = keyList[0]
+ if suffix > 1 {
+ name = fmt.Sprintf("%s_%d", keyList[0], suffix)
+ }
+ if _, exists := t.indexSet[name]; !exists {
+ break
+ }
+ suffix++
+ }
+ }
+
+ index := &IndexState{
+ name: name,
+ expressionList: keyList,
+ indexType: &tp,
+ unique: &unique,
+ primary: newFalsePointer(),
+ visible: newTruePointer(),
+ comment: newEmptyStringPointer(),
+ }
+
+ // need to check the visibility of index.
+ // we need a for-loop to determined the visibility of index.
+ for _, attribute := range tableConstraint.AllIndexOption() {
+ if attribute == nil || attribute.CommonIndexOption() == nil {
continue
}
+ if attribute.CommonIndexOption().Visibility() != nil && attribute.CommonIndexOption().Visibility().INVISIBLE_SYMBOL() != nil {
+ index.visible = newFalsePointer()
+ }
}
- t.columnSet[col.name] = col
+ t.indexSet[name] = index
+ return nil
+}
+
+func (t *TableState) mysqlV2CreatePrimaryKey(keys []string, tp string) *WalkThroughError {
+ if _, exists := t.indexSet[PrimaryKeyName]; exists {
+ return &WalkThroughError{
+ Type: ErrorTypePrimaryKeyExists,
+ Content: fmt.Sprintf("Primary key exists in table `%s`", t.name),
+ }
+ }
+
+ pk := &IndexState{
+ name: PrimaryKeyName,
+ expressionList: keys,
+ indexType: &tp,
+ unique: newTruePointer(),
+ primary: newTruePointer(),
+ visible: newTruePointer(),
+ comment: newEmptyStringPointer(),
+ }
+ t.indexSet[pk.name] = pk
+ return nil
+}
+
+func mysqlV2CheckDefault(columnName string, fieldDefinition mysql.IFieldDefinitionContext) *WalkThroughError {
+ if fieldDefinition.DataType() == nil || fieldDefinition.DataType().GetType_() == nil {
+ return nil
+ }
+
+ switch fieldDefinition.DataType().GetType_().GetTokenType() {
+ case mysql.MySQLParserTEXT_SYMBOL,
+ mysql.MySQLParserTINYTEXT_SYMBOL,
+ mysql.MySQLParserMEDIUMTEXT_SYMBOL,
+ mysql.MySQLParserLONGTEXT_SYMBOL,
+ mysql.MySQLParserBLOB_SYMBOL,
+ mysql.MySQLParserTINYBLOB_SYMBOL,
+ mysql.MySQLParserLONGBLOB_SYMBOL,
+ mysql.MySQLParserJSON_SYMBOL,
+ mysql.MySQLParserGEOMETRY_SYMBOL,
+ mysql.MySQLParserGEOMETRYCOLLECTION_SYMBOL,
+ mysql.MySQLParserPOINT_SYMBOL,
+ mysql.MySQLParserMULTIPOINT_SYMBOL,
+ mysql.MySQLParserLINESTRING_SYMBOL,
+ mysql.MySQLParserMULTILINESTRING_SYMBOL,
+ mysql.MySQLParserPOLYGON_SYMBOL,
+ mysql.MySQLParserMULTIPOLYGON_SYMBOL:
+ return &WalkThroughError{
+ Type: ErrorTypeInvalidColumnTypeForDefaultValue,
+ // Content comes from MySQL Error content.
+ Content: fmt.Sprintf("BLOB, TEXT, GEOMETRY or JSON column `%s` can't have a default value", columnName),
+ }
+ }
+
+ // todo: check column type with default value.
return nil
}
diff --git a/backend/plugin/advisor/catalog/walk_through_test.go b/backend/plugin/advisor/catalog/walk_through_test.go
index d0a9a4dc05..f0605993e6 100644
--- a/backend/plugin/advisor/catalog/walk_through_test.go
+++ b/backend/plugin/advisor/catalog/walk_through_test.go
@@ -155,6 +155,7 @@ func runWalkThroughTest(t *testing.T, file string, engineType storepb.Engine, or
walkThroughError, ok := err.(*WalkThroughError)
require.True(t, ok)
tests[i].Err = walkThroughError
+ tests[i].Want = ""
} else {
err, yes := err.(*WalkThroughError)
require.True(t, yes)
@@ -176,6 +177,7 @@ func runWalkThroughTest(t *testing.T, file string, engineType storepb.Engine, or
if record {
tests[i].Want = protojson.Format(state.convertToDatabaseMetadata())
+ tests[i].Err = nil
} else {
want := &storepb.DatabaseSchemaMetadata{}
err = protojson.Unmarshal([]byte(test.Want), want)
diff --git a/backend/plugin/parser/mysql/normalize.go b/backend/plugin/parser/mysql/normalize.go
index 1195918085..5d1f763156 100644
--- a/backend/plugin/parser/mysql/normalize.go
+++ b/backend/plugin/parser/mysql/normalize.go
@@ -105,6 +105,15 @@ func NormalizeMySQLTextStringLiteral(ctx parser.ITextStringLiteralContext) strin
return textString[1 : len(textString)-1]
}
+// NormalizeMySQLSignedStringLiteral normalize the given SignedLiteral.
+func NormalizeMySQLSignedLiteral(ctx parser.ISignedLiteralContext) string {
+ textString := ctx.GetText()
+ if (strings.HasPrefix(textString, "'") && strings.HasSuffix(textString, "'")) || (strings.HasPrefix(textString, "\"") && strings.HasSuffix(textString, "\"")) {
+ textString = textString[1 : len(textString)-1]
+ }
+ return textString
+}
+
// NormalizeMySQLSelectAlias normalizes the given select alias.
func NormalizeMySQLSelectAlias(selectAlias parser.ISelectAliasContext) string {
if selectAlias.Identifier() != nil {
@@ -319,3 +328,17 @@ func GetCollationName(ctx parser.IFieldDefinitionContext) string {
}
return ""
}
+
+// IsTypeType check if the dataType is time type.
+func IsTimeType(ctx parser.IDataTypeContext) bool {
+ if ctx.GetType_() == nil {
+ return false
+ }
+
+ switch ctx.GetType_().GetTokenType() {
+ case parser.MySQLParserDATETIME_SYMBOL, parser.MySQLParserTIMESTAMP_SYMBOL:
+ return true
+ default:
+ return false
+ }
+}