Skip to content

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

chore: split tidb advisor (#8866)

zll60013fd2afcd7fc
diff --git a/backend/plugin/advisor/mysql/advisor_charset_allowlist.go b/backend/plugin/advisor/mysql/advisor_charset_allowlist.go
index 3354fdf813..ee3f3c2e1e 100644
--- a/backend/plugin/advisor/mysql/advisor_charset_allowlist.go
+++ b/backend/plugin/advisor/mysql/advisor_charset_allowlist.go
@@ -20,7 +20,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLCharsetAllowlist, &CharsetAllowlistAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLCharsetAllowlist, &CharsetAllowlistAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLCharsetAllowlist, &CharsetAllowlistAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLCharsetAllowlist, &CharsetAllowlistAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_collation_allowlist.go b/backend/plugin/advisor/mysql/advisor_collation_allowlist.go
index bbed34adfb..8b086a652d 100644
--- a/backend/plugin/advisor/mysql/advisor_collation_allowlist.go
+++ b/backend/plugin/advisor/mysql/advisor_collation_allowlist.go
@@ -20,7 +20,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLCollationAllowlist, &CollationAllowlistAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLCollationAllowlist, &CollationAllowlistAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLCollationAllowlist, &CollationAllowlistAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLCollationAllowlist, &CollationAllowlistAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_colum_require_default.go b/backend/plugin/advisor/mysql/advisor_colum_require_default.go
index fa09b25e1a..dc19d19b97 100644
--- a/backend/plugin/advisor/mysql/advisor_colum_require_default.go
+++ b/backend/plugin/advisor/mysql/advisor_colum_require_default.go
@@ -21,7 +21,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLRequireColumnDefault, &ColumRequireDefaultAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLRequireColumnDefault, &ColumRequireDefaultAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLRequireColumnDefault, &ColumRequireDefaultAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLRequireColumnDefault, &ColumRequireDefaultAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_column_auto_increment_initial_value.go b/backend/plugin/advisor/mysql/advisor_column_auto_increment_initial_value.go
index 61695591ae..e514ce526c 100644
--- a/backend/plugin/advisor/mysql/advisor_column_auto_increment_initial_value.go
+++ b/backend/plugin/advisor/mysql/advisor_column_auto_increment_initial_value.go
@@ -19,7 +19,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLAutoIncrementColumnInitialValue, &ColumnAutoIncrementInitialValueAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLAutoIncrementColumnInitialValue, &ColumnAutoIncrementInitialValueAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLAutoIncrementColumnInitialValue, &ColumnAutoIncrementInitialValueAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLAutoIncrementColumnInitialValue, &ColumnAutoIncrementInitialValueAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_column_auto_increment_must_integer.go b/backend/plugin/advisor/mysql/advisor_column_auto_increment_must_integer.go
index 9b008cf2e8..f0e8344769 100644
--- a/backend/plugin/advisor/mysql/advisor_column_auto_increment_must_integer.go
+++ b/backend/plugin/advisor/mysql/advisor_column_auto_increment_must_integer.go
@@ -21,7 +21,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLAutoIncrementColumnMustInteger, &ColumnAutoIncrementMustIntegerAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLAutoIncrementColumnMustInteger, &ColumnAutoIncrementMustIntegerAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLAutoIncrementColumnMustInteger, &ColumnAutoIncrementMustIntegerAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLAutoIncrementColumnMustInteger, &ColumnAutoIncrementMustIntegerAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_column_auto_increment_must_unsigned.go b/backend/plugin/advisor/mysql/advisor_column_auto_increment_must_unsigned.go
index b4d5b85369..dcaba44c6b 100644
--- a/backend/plugin/advisor/mysql/advisor_column_auto_increment_must_unsigned.go
+++ b/backend/plugin/advisor/mysql/advisor_column_auto_increment_must_unsigned.go
@@ -20,7 +20,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLAutoIncrementColumnMustUnsigned, &ColumnAutoIncrementMustUnsignedAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLAutoIncrementColumnMustUnsigned, &ColumnAutoIncrementMustUnsignedAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLAutoIncrementColumnMustUnsigned, &ColumnAutoIncrementMustUnsignedAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLAutoIncrementColumnMustUnsigned, &ColumnAutoIncrementMustUnsignedAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_column_comment_convention.go b/backend/plugin/advisor/mysql/advisor_column_comment_convention.go
index db896291e5..d03390f404 100644
--- a/backend/plugin/advisor/mysql/advisor_column_comment_convention.go
+++ b/backend/plugin/advisor/mysql/advisor_column_comment_convention.go
@@ -20,7 +20,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLColumnCommentConvention, &ColumnCommentConventionAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnCommentConvention, &ColumnCommentConventionAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLColumnCommentConvention, &ColumnCommentConventionAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLColumnCommentConvention, &ColumnCommentConventionAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_column_current_time_count_limit.go b/backend/plugin/advisor/mysql/advisor_column_current_time_count_limit.go
index 8262a22bbf..0517a7ab71 100644
--- a/backend/plugin/advisor/mysql/advisor_column_current_time_count_limit.go
+++ b/backend/plugin/advisor/mysql/advisor_column_current_time_count_limit.go
@@ -27,7 +27,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLCurrentTimeColumnCountLimit, &ColumnCurrentTimeCountLimitAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLCurrentTimeColumnCountLimit, &ColumnCurrentTimeCountLimitAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLCurrentTimeColumnCountLimit, &ColumnCurrentTimeCountLimitAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLCurrentTimeColumnCountLimit, &ColumnCurrentTimeCountLimitAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_column_disallow_changing.go b/backend/plugin/advisor/mysql/advisor_column_disallow_changing.go
index 166e33d6af..67e675e994 100644
--- a/backend/plugin/advisor/mysql/advisor_column_disallow_changing.go
+++ b/backend/plugin/advisor/mysql/advisor_column_disallow_changing.go
@@ -19,7 +19,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLColumnDisallowChanging, &ColumnDisallowChangingAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnDisallowChanging, &ColumnDisallowChangingAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLColumnDisallowChanging, &ColumnDisallowChangingAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLColumnDisallowChanging, &ColumnDisallowChangingAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_column_disallow_changing_order.go b/backend/plugin/advisor/mysql/advisor_column_disallow_changing_order.go
index 18d8e1e538..cda6419bfa 100644
--- a/backend/plugin/advisor/mysql/advisor_column_disallow_changing_order.go
+++ b/backend/plugin/advisor/mysql/advisor_column_disallow_changing_order.go
@@ -19,7 +19,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLColumnDisallowChangingOrder, &ColumnDisallowChangingOrderAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnDisallowChangingOrder, &ColumnDisallowChangingOrderAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLColumnDisallowChangingOrder, &ColumnDisallowChangingOrderAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLColumnDisallowChangingOrder, &ColumnDisallowChangingOrderAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_column_disallow_changing_type.go b/backend/plugin/advisor/mysql/advisor_column_disallow_changing_type.go
index 55635802d3..3260c2429f 100644
--- a/backend/plugin/advisor/mysql/advisor_column_disallow_changing_type.go
+++ b/backend/plugin/advisor/mysql/advisor_column_disallow_changing_type.go
@@ -21,7 +21,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLColumnDisallowChangingType, &ColumnDisallowChangingTypeAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnDisallowChangingType, &ColumnDisallowChangingTypeAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLColumnDisallowChangingType, &ColumnDisallowChangingTypeAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLColumnDisallowChangingType, &ColumnDisallowChangingTypeAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_column_disallow_drop_in_index.go b/backend/plugin/advisor/mysql/advisor_column_disallow_drop_in_index.go
index 5b25f633a8..e8f615353a 100644
--- a/backend/plugin/advisor/mysql/advisor_column_disallow_drop_in_index.go
+++ b/backend/plugin/advisor/mysql/advisor_column_disallow_drop_in_index.go
@@ -20,7 +20,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLColumnDisallowDropInIndex, &ColumnDisallowDropInIndexAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnDisallowDropInIndex, &ColumnDisallowDropInIndexAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLColumnDisallowDropInIndex, &ColumnDisallowDropInIndexAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLColumnDisallowDropInIndex, &ColumnDisallowDropInIndexAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_column_disallow_set_charset.go b/backend/plugin/advisor/mysql/advisor_column_disallow_set_charset.go
index 69569ddf41..b1e6024e21 100644
--- a/backend/plugin/advisor/mysql/advisor_column_disallow_set_charset.go
+++ b/backend/plugin/advisor/mysql/advisor_column_disallow_set_charset.go
@@ -19,7 +19,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLDisallowSetColumnCharset, &ColumnDisallowSetCharsetAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLDisallowSetColumnCharset, &ColumnDisallowSetCharsetAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLDisallowSetColumnCharset, &ColumnDisallowSetCharsetAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLDisallowSetColumnCharset, &ColumnDisallowSetCharsetAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_column_maximum_character_length.go b/backend/plugin/advisor/mysql/advisor_column_maximum_character_length.go
index 8b8348d0e9..2a93d48e0a 100644
--- a/backend/plugin/advisor/mysql/advisor_column_maximum_character_length.go
+++ b/backend/plugin/advisor/mysql/advisor_column_maximum_character_length.go
@@ -20,7 +20,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLColumnMaximumCharacterLength, &ColumnMaximumCharacterLengthAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnMaximumCharacterLength, &ColumnMaximumCharacterLengthAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLColumnMaximumCharacterLength, &ColumnMaximumCharacterLengthAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLColumnMaximumCharacterLength, &ColumnMaximumCharacterLengthAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_column_no_null.go b/backend/plugin/advisor/mysql/advisor_column_no_null.go
index db70a64e49..4452c6419b 100644
--- a/backend/plugin/advisor/mysql/advisor_column_no_null.go
+++ b/backend/plugin/advisor/mysql/advisor_column_no_null.go
@@ -19,7 +19,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLColumnNoNull, &ColumnNoNullAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnNoNull, &ColumnNoNullAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLColumnNoNull, &ColumnNoNullAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLColumnNoNull, &ColumnNoNullAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_column_required.go b/backend/plugin/advisor/mysql/advisor_column_required.go
index 2d6a70a909..1799af1ea5 100644
--- a/backend/plugin/advisor/mysql/advisor_column_required.go
+++ b/backend/plugin/advisor/mysql/advisor_column_required.go
@@ -19,7 +19,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLColumnRequirement, &ColumnRequirementAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnRequirement, &ColumnRequirementAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLColumnRequirement, &ColumnRequirementAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLColumnRequirement, &ColumnRequirementAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_column_set_default_for_not_null.go b/backend/plugin/advisor/mysql/advisor_column_set_default_for_not_null.go
index a7f97fc9a0..06bc6743bb 100644
--- a/backend/plugin/advisor/mysql/advisor_column_set_default_for_not_null.go
+++ b/backend/plugin/advisor/mysql/advisor_column_set_default_for_not_null.go
@@ -19,7 +19,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLColumnSetDefaultForNotNull, &ColumnSetDefaultForNotNullAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnSetDefaultForNotNull, &ColumnSetDefaultForNotNullAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLColumnSetDefaultForNotNull, &ColumnSetDefaultForNotNullAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLColumnSetDefaultForNotNull, &ColumnSetDefaultForNotNullAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_column_type_restriction.go b/backend/plugin/advisor/mysql/advisor_column_type_restriction.go
index 24a2f3394c..487424e7fe 100644
--- a/backend/plugin/advisor/mysql/advisor_column_type_restriction.go
+++ b/backend/plugin/advisor/mysql/advisor_column_type_restriction.go
@@ -20,7 +20,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLColumnTypeRestriction, &ColumnTypeRestrictionAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnTypeRestriction, &ColumnTypeRestrictionAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLColumnTypeRestriction, &ColumnTypeRestrictionAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLColumnTypeRestriction, &ColumnTypeRestrictionAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_database_drop_empty_db.go b/backend/plugin/advisor/mysql/advisor_database_drop_empty_db.go
index 7b62cf8ca4..8a3e9eeb23 100644
--- a/backend/plugin/advisor/mysql/advisor_database_drop_empty_db.go
+++ b/backend/plugin/advisor/mysql/advisor_database_drop_empty_db.go
@@ -18,7 +18,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLDatabaseAllowDropIfEmpty, &DatabaseAllowDropIfEmptyAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLDatabaseAllowDropIfEmpty, &DatabaseAllowDropIfEmptyAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLDatabaseAllowDropIfEmpty, &DatabaseAllowDropIfEmptyAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLDatabaseAllowDropIfEmpty, &DatabaseAllowDropIfEmptyAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_index_key_number_limit.go b/backend/plugin/advisor/mysql/advisor_index_key_number_limit.go
index 6465ed0e50..4fd07f160b 100644
--- a/backend/plugin/advisor/mysql/advisor_index_key_number_limit.go
+++ b/backend/plugin/advisor/mysql/advisor_index_key_number_limit.go
@@ -19,7 +19,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLIndexKeyNumberLimit, &IndexKeyNumberLimitAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLIndexKeyNumberLimit, &IndexKeyNumberLimitAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLIndexKeyNumberLimit, &IndexKeyNumberLimitAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLIndexKeyNumberLimit, &IndexKeyNumberLimitAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_index_no_duplicate_column.go b/backend/plugin/advisor/mysql/advisor_index_no_duplicate_column.go
index 9300e7b5fe..4781e844f9 100644
--- a/backend/plugin/advisor/mysql/advisor_index_no_duplicate_column.go
+++ b/backend/plugin/advisor/mysql/advisor_index_no_duplicate_column.go
@@ -19,7 +19,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLIndexNoDuplicateColumn, &IndexNoDuplicateColumnAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLIndexNoDuplicateColumn, &IndexNoDuplicateColumnAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLIndexNoDuplicateColumn, &IndexNoDuplicateColumnAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLIndexNoDuplicateColumn, &IndexNoDuplicateColumnAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_index_pk_type.go b/backend/plugin/advisor/mysql/advisor_index_pk_type.go
index 39c3006ba3..9942abcbbd 100644
--- a/backend/plugin/advisor/mysql/advisor_index_pk_type.go
+++ b/backend/plugin/advisor/mysql/advisor_index_pk_type.go
@@ -22,7 +22,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLIndexPKType, &IndexPkTypeAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLIndexPKType, &IndexPkTypeAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLIndexPKType, &IndexPkTypeAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLIndexPKType, &IndexPkTypeAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_index_primary_key_type_allowlist.go b/backend/plugin/advisor/mysql/advisor_index_primary_key_type_allowlist.go
index e2d924726d..b341548dc7 100644
--- a/backend/plugin/advisor/mysql/advisor_index_primary_key_type_allowlist.go
+++ b/backend/plugin/advisor/mysql/advisor_index_primary_key_type_allowlist.go
@@ -22,7 +22,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLPrimaryKeyTypeAllowlist, &IndexPrimaryKeyTypeAllowlistAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLPrimaryKeyTypeAllowlist, &IndexPrimaryKeyTypeAllowlistAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLPrimaryKeyTypeAllowlist, &IndexPrimaryKeyTypeAllowlistAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_index_total_number_limit.go b/backend/plugin/advisor/mysql/advisor_index_total_number_limit.go
index 4e3a94f63a..8ba9e23ccd 100644
--- a/backend/plugin/advisor/mysql/advisor_index_total_number_limit.go
+++ b/backend/plugin/advisor/mysql/advisor_index_total_number_limit.go
@@ -21,7 +21,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLIndexTotalNumberLimit, &IndexTotalNumberLimitAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLIndexTotalNumberLimit, &IndexTotalNumberLimitAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLIndexTotalNumberLimit, &IndexTotalNumberLimitAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLIndexTotalNumberLimit, &IndexTotalNumberLimitAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_index_type_no_blob.go b/backend/plugin/advisor/mysql/advisor_index_type_no_blob.go
index 37e354c833..827e58c8e6 100644
--- a/backend/plugin/advisor/mysql/advisor_index_type_no_blob.go
+++ b/backend/plugin/advisor/mysql/advisor_index_type_no_blob.go
@@ -23,7 +23,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLIndexTypeNoBlob, &IndexTypeNoBlobAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLIndexTypeNoBlob, &IndexTypeNoBlobAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLIndexTypeNoBlob, &IndexTypeNoBlobAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLIndexTypeNoBlob, &IndexTypeNoBlobAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_insert_disallow_order_by_rand.go b/backend/plugin/advisor/mysql/advisor_insert_disallow_order_by_rand.go
index 5630b93566..d4fdd858b1 100644
--- a/backend/plugin/advisor/mysql/advisor_insert_disallow_order_by_rand.go
+++ b/backend/plugin/advisor/mysql/advisor_insert_disallow_order_by_rand.go
@@ -19,7 +19,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLInsertDisallowOrderByRand, &InsertDisallowOrderByRandAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLInsertDisallowOrderByRand, &InsertDisallowOrderByRandAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLInsertDisallowOrderByRand, &InsertDisallowOrderByRandAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLInsertDisallowOrderByRand, &InsertDisallowOrderByRandAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_insert_must_specify_column.go b/backend/plugin/advisor/mysql/advisor_insert_must_specify_column.go
index 3be17214ab..25da7a1c15 100644
--- a/backend/plugin/advisor/mysql/advisor_insert_must_specify_column.go
+++ b/backend/plugin/advisor/mysql/advisor_insert_must_specify_column.go
@@ -19,7 +19,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLInsertMustSpecifyColumn, &InsertMustSpecifyColumnAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLInsertMustSpecifyColumn, &InsertMustSpecifyColumnAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLInsertMustSpecifyColumn, &InsertMustSpecifyColumnAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLInsertMustSpecifyColumn, &InsertMustSpecifyColumnAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_migration_compatibility.go b/backend/plugin/advisor/mysql/advisor_migration_compatibility.go
index 2c72536738..e9638e87f3 100644
--- a/backend/plugin/advisor/mysql/advisor_migration_compatibility.go
+++ b/backend/plugin/advisor/mysql/advisor_migration_compatibility.go
@@ -18,7 +18,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLMigrationCompatibility, &CompatibilityAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLMigrationCompatibility, &CompatibilityAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLMigrationCompatibility, &CompatibilityAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLMigrationCompatibility, &CompatibilityAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_naming_auto_increment_column.go b/backend/plugin/advisor/mysql/advisor_naming_auto_increment_column.go
index 179114dad1..9d56f5524c 100644
--- a/backend/plugin/advisor/mysql/advisor_naming_auto_increment_column.go
+++ b/backend/plugin/advisor/mysql/advisor_naming_auto_increment_column.go
@@ -20,7 +20,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLNamingAutoIncrementColumnConvention, &NamingAutoIncrementColumnAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLNamingAutoIncrementColumnConvention, &NamingAutoIncrementColumnAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLNamingAutoIncrementColumnConvention, &NamingAutoIncrementColumnAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLNamingAutoIncrementColumnConvention, &NamingAutoIncrementColumnAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_naming_column.go b/backend/plugin/advisor/mysql/advisor_naming_column.go
index ece557b2a8..edd0b7e83a 100644
--- a/backend/plugin/advisor/mysql/advisor_naming_column.go
+++ b/backend/plugin/advisor/mysql/advisor_naming_column.go
@@ -18,7 +18,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLNamingColumnConvention, &NamingColumnConventionAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLNamingColumnConvention, &NamingColumnConventionAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLNamingColumnConvention, &NamingColumnConventionAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLNamingColumnConvention, &NamingColumnConventionAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_naming_foreign_key_convention.go b/backend/plugin/advisor/mysql/advisor_naming_foreign_key_convention.go
index f317096677..820f2b8e7d 100644
--- a/backend/plugin/advisor/mysql/advisor_naming_foreign_key_convention.go
+++ b/backend/plugin/advisor/mysql/advisor_naming_foreign_key_convention.go
@@ -18,7 +18,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLNamingFKConvention, &NamingFKConventionAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLNamingFKConvention, &NamingFKConventionAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLNamingFKConvention, &NamingFKConventionAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLNamingFKConvention, &NamingFKConventionAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_naming_index_convention.go b/backend/plugin/advisor/mysql/advisor_naming_index_convention.go
index cc1faef97e..90bf37fa96 100644
--- a/backend/plugin/advisor/mysql/advisor_naming_index_convention.go
+++ b/backend/plugin/advisor/mysql/advisor_naming_index_convention.go
@@ -20,7 +20,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLNamingIndexConvention, &NamingIndexConventionAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLNamingIndexConvention, &NamingIndexConventionAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLNamingIndexConvention, &NamingIndexConventionAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLNamingIndexConvention, &NamingIndexConventionAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_naming_unique_key_convention.go b/backend/plugin/advisor/mysql/advisor_naming_unique_key_convention.go
index 262326d663..6640420f04 100644
--- a/backend/plugin/advisor/mysql/advisor_naming_unique_key_convention.go
+++ b/backend/plugin/advisor/mysql/advisor_naming_unique_key_convention.go
@@ -19,7 +19,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLNamingUKConvention, &NamingUKConventionAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLNamingUKConvention, &NamingUKConventionAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLNamingUKConvention, &NamingUKConventionAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLNamingUKConvention, &NamingUKConventionAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_statement_dml_dry_run.go b/backend/plugin/advisor/mysql/advisor_statement_dml_dry_run.go
index 30ba288fd9..bb891042c6 100644
--- a/backend/plugin/advisor/mysql/advisor_statement_dml_dry_run.go
+++ b/backend/plugin/advisor/mysql/advisor_statement_dml_dry_run.go
@@ -21,7 +21,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLStatementDMLDryRun, &StatementDmlDryRunAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLStatementDMLDryRun, &StatementDmlDryRunAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLStatementDMLDryRun, &StatementDmlDryRunAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLStatementDMLDryRun, &StatementDmlDryRunAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_statement_merge_alter_table.go b/backend/plugin/advisor/mysql/advisor_statement_merge_alter_table.go
index f2434d4fc5..386ad53ef8 100644
--- a/backend/plugin/advisor/mysql/advisor_statement_merge_alter_table.go
+++ b/backend/plugin/advisor/mysql/advisor_statement_merge_alter_table.go
@@ -20,7 +20,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLMergeAlterTable, &StatementMergeAlterTableAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLMergeAlterTable, &StatementMergeAlterTableAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLMergeAlterTable, &StatementMergeAlterTableAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLMergeAlterTable, &StatementMergeAlterTableAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_stmt_disallow_commit.go b/backend/plugin/advisor/mysql/advisor_stmt_disallow_commit.go
index e140d903b6..0433ddbcf9 100644
--- a/backend/plugin/advisor/mysql/advisor_stmt_disallow_commit.go
+++ b/backend/plugin/advisor/mysql/advisor_stmt_disallow_commit.go
@@ -19,7 +19,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLStatementDisallowCommit, &StatementDisallowCommitAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLStatementDisallowCommit, &StatementDisallowCommitAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLStatementDisallowCommit, &StatementDisallowCommitAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLStatementDisallowCommit, &StatementDisallowCommitAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_stmt_disallow_limit.go b/backend/plugin/advisor/mysql/advisor_stmt_disallow_limit.go
index 47e79377fe..1c99cf0404 100644
--- a/backend/plugin/advisor/mysql/advisor_stmt_disallow_limit.go
+++ b/backend/plugin/advisor/mysql/advisor_stmt_disallow_limit.go
@@ -19,7 +19,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLDisallowLimit, &DisallowLimitAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLDisallowLimit, &DisallowLimitAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLDisallowLimit, &DisallowLimitAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLDisallowLimit, &DisallowLimitAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_stmt_disallow_order_by.go b/backend/plugin/advisor/mysql/advisor_stmt_disallow_order_by.go
index 788622a382..2ef11660d1 100644
--- a/backend/plugin/advisor/mysql/advisor_stmt_disallow_order_by.go
+++ b/backend/plugin/advisor/mysql/advisor_stmt_disallow_order_by.go
@@ -19,7 +19,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLDisallowOrderBy, &DisallowOrderByAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLDisallowOrderBy, &DisallowOrderByAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLDisallowOrderBy, &DisallowOrderByAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLDisallowOrderBy, &DisallowOrderByAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_stmt_no_leading_wildcard_like.go b/backend/plugin/advisor/mysql/advisor_stmt_no_leading_wildcard_like.go
index dac371cccf..e4919b76f2 100644
--- a/backend/plugin/advisor/mysql/advisor_stmt_no_leading_wildcard_like.go
+++ b/backend/plugin/advisor/mysql/advisor_stmt_no_leading_wildcard_like.go
@@ -22,7 +22,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLNoLeadingWildcardLike, &NoLeadingWildcardLikeAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLNoLeadingWildcardLike, &NoLeadingWildcardLikeAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLNoLeadingWildcardLike, &NoLeadingWildcardLikeAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLNoLeadingWildcardLike, &NoLeadingWildcardLikeAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_stmt_no_select_all.go b/backend/plugin/advisor/mysql/advisor_stmt_no_select_all.go
index eab395134f..59f346c9f8 100644
--- a/backend/plugin/advisor/mysql/advisor_stmt_no_select_all.go
+++ b/backend/plugin/advisor/mysql/advisor_stmt_no_select_all.go
@@ -17,7 +17,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLNoSelectAll, &NoSelectAllAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLNoSelectAll, &NoSelectAllAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLNoSelectAll, &NoSelectAllAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLNoSelectAll, &NoSelectAllAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_stmt_where_required.go b/backend/plugin/advisor/mysql/advisor_stmt_where_required.go
index 1ca2af1150..daa337e777 100644
--- a/backend/plugin/advisor/mysql/advisor_stmt_where_required.go
+++ b/backend/plugin/advisor/mysql/advisor_stmt_where_required.go
@@ -18,7 +18,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLWhereRequirement, &WhereRequirementAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLWhereRequirement, &WhereRequirementAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLWhereRequirement, &WhereRequirementAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLWhereRequirement, &WhereRequirementAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_table_comment_convention.go b/backend/plugin/advisor/mysql/advisor_table_comment_convention.go
index 8e3e952f30..1be57e032b 100644
--- a/backend/plugin/advisor/mysql/advisor_table_comment_convention.go
+++ b/backend/plugin/advisor/mysql/advisor_table_comment_convention.go
@@ -19,7 +19,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLTableCommentConvention, &TableCommentConventionAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLTableCommentConvention, &TableCommentConventionAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLTableCommentConvention, &TableCommentConventionAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLTableCommentConvention, &TableCommentConventionAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_table_disallow_partition.go b/backend/plugin/advisor/mysql/advisor_table_disallow_partition.go
index 2b582de02f..591f303489 100644
--- a/backend/plugin/advisor/mysql/advisor_table_disallow_partition.go
+++ b/backend/plugin/advisor/mysql/advisor_table_disallow_partition.go
@@ -19,7 +19,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLTableDisallowPartition, &TableDisallowPartitionAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLTableDisallowPartition, &TableDisallowPartitionAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLTableDisallowPartition, &TableDisallowPartitionAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLTableDisallowPartition, &TableDisallowPartitionAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_table_drop_naming_convention.go b/backend/plugin/advisor/mysql/advisor_table_drop_naming_convention.go
index 9631001ddf..e8e7f54ad4 100644
--- a/backend/plugin/advisor/mysql/advisor_table_drop_naming_convention.go
+++ b/backend/plugin/advisor/mysql/advisor_table_drop_naming_convention.go
@@ -18,7 +18,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLTableDropNamingConvention, &TableDropNamingConventionAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLTableDropNamingConvention, &TableDropNamingConventionAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLTableDropNamingConvention, &TableDropNamingConventionAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLTableDropNamingConvention, &TableDropNamingConventionAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_table_no_fk.go b/backend/plugin/advisor/mysql/advisor_table_no_fk.go
index c7494f594c..5af755dca5 100644
--- a/backend/plugin/advisor/mysql/advisor_table_no_fk.go
+++ b/backend/plugin/advisor/mysql/advisor_table_no_fk.go
@@ -17,7 +17,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLTableNoFK, &TableNoFKAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLTableNoFK, &TableNoFKAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLTableNoFK, &TableNoFKAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLTableNoFK, &TableNoFKAdvisor{})
}
diff --git a/backend/plugin/advisor/mysql/advisor_table_require_pk.go b/backend/plugin/advisor/mysql/advisor_table_require_pk.go
index 4550aaeba6..cea85d8fa4 100644
--- a/backend/plugin/advisor/mysql/advisor_table_require_pk.go
+++ b/backend/plugin/advisor/mysql/advisor_table_require_pk.go
@@ -23,7 +23,6 @@ var (
func init() {
advisor.Register(storepb.Engine_MYSQL, advisor.MySQLTableRequirePK, &TableRequirePKAdvisor{})
- advisor.Register(storepb.Engine_TIDB, advisor.MySQLTableRequirePK, &TableRequirePKAdvisor{})
advisor.Register(storepb.Engine_MARIADB, advisor.MySQLTableRequirePK, &TableRequirePKAdvisor{})
advisor.Register(storepb.Engine_OCEANBASE, advisor.MySQLTableRequirePK, &TableRequirePKAdvisor{})
}
diff --git a/backend/plugin/advisor/tidb/advisor_charset_allowlist.go b/backend/plugin/advisor/tidb/advisor_charset_allowlist.go
new file mode 100644
index 0000000000..04512267d7
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_charset_allowlist.go
@@ -0,0 +1,183 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*CharsetAllowlistAdvisor)(nil)
+ _ ast.Visitor = (*charsetAllowlistChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLCharsetAllowlist, &CharsetAllowlistAdvisor{})
+}
+
+// CharsetAllowlistAdvisor is the advisor checking for charset allowlist.
+type CharsetAllowlistAdvisor struct {
+}
+
+// Check checks for charset allowlist.
+func (*CharsetAllowlistAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ payload, err := advisor.UnmarshalStringArrayTypeRulePayload(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &charsetAllowlistChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ allowlist: make(map[string]bool),
+ }
+ for _, charset := range payload.List {
+ checker.allowlist[strings.ToLower(charset)] = true
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type charsetAllowlistChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ allowlist map[string]bool
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *charsetAllowlistChecker) Enter(in ast.Node) (ast.Node, bool) {
+ code := advisor.Ok
+ var disabledCharset string
+ line := checker.line
+ switch node := in.(type) {
+ case *ast.CreateDatabaseStmt:
+ charset := getDatabaseCharset(node.Options)
+ if _, exist := checker.allowlist[charset]; charset != "" && !exist {
+ code = advisor.DisabledCharset
+ disabledCharset = charset
+ }
+ case *ast.CreateTableStmt:
+ charset := getTableCharset(node.Options)
+ if _, exist := checker.allowlist[charset]; charset != "" && !exist {
+ code = advisor.DisabledCharset
+ disabledCharset = charset
+ break
+ }
+ for _, column := range node.Cols {
+ charset := getColumnCharset(column)
+ if _, exist := checker.allowlist[charset]; charset != "" && !exist {
+ code = advisor.DisabledCharset
+ disabledCharset = charset
+ line = column.OriginTextPosition()
+ break
+ }
+ }
+ case *ast.AlterDatabaseStmt:
+ charset := getDatabaseCharset(node.Options)
+ if _, exist := checker.allowlist[charset]; charset != "" && !exist {
+ code = advisor.DisabledCharset
+ disabledCharset = charset
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableOption:
+ charset := getTableCharset(spec.Options)
+ if _, exist := checker.allowlist[charset]; charset != "" && !exist {
+ code = advisor.DisabledCharset
+ disabledCharset = charset
+ }
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ charset := getColumnCharset(column)
+ if _, exist := checker.allowlist[charset]; charset != "" && !exist {
+ code = advisor.DisabledCharset
+ disabledCharset = charset
+ break
+ }
+ }
+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:
+ charset := getColumnCharset(spec.NewColumns[0])
+ if _, exist := checker.allowlist[charset]; charset != "" && !exist {
+ code = advisor.DisabledCharset
+ disabledCharset = charset
+ }
+ }
+ }
+ }
+
+ if code != advisor.Ok {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: code,
+ Title: checker.title,
+ Content: fmt.Sprintf("\"%s\" used disabled charset '%s'", checker.text, disabledCharset),
+ Line: line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*charsetAllowlistChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func getDatabaseCharset(optionList []*ast.DatabaseOption) string {
+ for _, option := range optionList {
+ if option.Tp == ast.DatabaseOptionCharset {
+ return strings.ToLower(option.Value)
+ }
+ }
+
+ return ""
+}
+
+func getTableCharset(optionList []*ast.TableOption) string {
+ for _, option := range optionList {
+ if option.Tp == ast.TableOptionCharset {
+ if option.Default {
+ return ""
+ }
+ return strings.ToLower(option.StrValue)
+ }
+ }
+
+ return ""
+}
+
+func getColumnCharset(column *ast.ColumnDef) string {
+ return strings.ToLower(column.Tp.GetCharset())
+}
diff --git a/backend/plugin/advisor/tidb/advisor_collation_allowlist.go b/backend/plugin/advisor/tidb/advisor_collation_allowlist.go
new file mode 100644
index 0000000000..2112dabbab
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_collation_allowlist.go
@@ -0,0 +1,184 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*CollationAllowlistAdvisor)(nil)
+ _ ast.Visitor = (*collationAllowlistChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLCollationAllowlist, &CollationAllowlistAdvisor{})
+}
+
+// CollationAllowlistAdvisor is the advisor checking for collation allowlist.
+type CollationAllowlistAdvisor struct {
+}
+
+// Check checks for collation allowlist.
+func (*CollationAllowlistAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ payload, err := advisor.UnmarshalStringArrayTypeRulePayload(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &collationAllowlistChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ allowlist: make(map[string]bool),
+ }
+ for _, collation := range payload.List {
+ checker.allowlist[strings.ToLower(collation)] = true
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type collationAllowlistChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ allowlist map[string]bool
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *collationAllowlistChecker) Enter(in ast.Node) (ast.Node, bool) {
+ code := advisor.Ok
+ var disabledCollation string
+ line := checker.line
+ switch node := in.(type) {
+ case *ast.CreateDatabaseStmt:
+ collation := getDatabaseCollation(node.Options)
+ if _, exists := checker.allowlist[collation]; collation != "" && !exists {
+ code = advisor.DisabledCollation
+ disabledCollation = collation
+ }
+ case *ast.CreateTableStmt:
+ collation := getTableCollation(node.Options)
+ if _, exist := checker.allowlist[collation]; collation != "" && !exist {
+ code = advisor.DisabledCollation
+ disabledCollation = collation
+ break
+ }
+ for _, column := range node.Cols {
+ collation := getColumnCollation(column)
+ if _, exist := checker.allowlist[collation]; collation != "" && !exist {
+ code = advisor.DisabledCollation
+ disabledCollation = collation
+ line = column.OriginTextPosition()
+ break
+ }
+ }
+ case *ast.AlterDatabaseStmt:
+ collation := getDatabaseCollation(node.Options)
+ if _, exist := checker.allowlist[collation]; collation != "" && !exist {
+ code = advisor.DisabledCollation
+ disabledCollation = collation
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableOption:
+ collation := getTableCollation(spec.Options)
+ if _, exist := checker.allowlist[collation]; collation != "" && !exist {
+ code = advisor.DisabledCollation
+ disabledCollation = collation
+ }
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ collation := getColumnCollation(column)
+ if _, exist := checker.allowlist[collation]; collation != "" && !exist {
+ code = advisor.DisabledCollation
+ disabledCollation = collation
+ break
+ }
+ }
+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:
+ collation := getColumnCollation(spec.NewColumns[0])
+ if _, exist := checker.allowlist[collation]; collation != "" && !exist {
+ code = advisor.DisabledCollation
+ disabledCollation = collation
+ }
+ }
+ }
+ }
+
+ if code != advisor.Ok {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: code,
+ Title: checker.title,
+ Content: fmt.Sprintf("\"%s\" used disabled collation '%s'", checker.text, disabledCollation),
+ Line: line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*collationAllowlistChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func getDatabaseCollation(optionList []*ast.DatabaseOption) string {
+ for _, option := range optionList {
+ if option.Tp == ast.DatabaseOptionCollate {
+ return strings.ToLower(option.Value)
+ }
+ }
+ return ""
+}
+
+func getTableCollation(optionList []*ast.TableOption) string {
+ for _, option := range optionList {
+ if option.Tp == ast.TableOptionCollate {
+ return strings.ToLower(option.StrValue)
+ }
+ }
+ return ""
+}
+
+func getColumnCollation(column *ast.ColumnDef) string {
+ for _, option := range column.Options {
+ if option.Tp == ast.ColumnOptionCollate {
+ return strings.ToLower(option.StrValue)
+ }
+ }
+ return ""
+}
diff --git a/backend/plugin/advisor/tidb/advisor_colum_require_default.go b/backend/plugin/advisor/tidb/advisor_colum_require_default.go
new file mode 100644
index 0000000000..3583e468a4
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_colum_require_default.go
@@ -0,0 +1,156 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pingcap/tidb/parser/mysql"
+ "github.com/pingcap/tidb/parser/types"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*ColumRequireDefaultAdvisor)(nil)
+ _ ast.Visitor = (*columRequireDefaultChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLRequireColumnDefault, &ColumRequireDefaultAdvisor{})
+}
+
+// ColumRequireDefaultAdvisor is the advisor checking for column default requirement.
+type ColumRequireDefaultAdvisor struct {
+}
+
+// Check checks for column default requirement.
+func (*ColumRequireDefaultAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &columRequireDefaultChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type columRequireDefaultChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *columRequireDefaultChecker) Enter(in ast.Node) (ast.Node, bool) {
+ var columnList []columnData
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ tableName := node.Table.Name.O
+ for _, column := range node.Cols {
+ if !hasDefault(column) && needDefault(column) {
+ columnList = append(columnList, columnData{
+ table: tableName,
+ column: column.Name.Name.O,
+ line: column.OriginTextPosition(),
+ })
+ }
+ }
+ case *ast.AlterTableStmt:
+ tableName := node.Table.Name.O
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ if !hasDefault(column) && needDefault(column) {
+ columnList = append(columnList, columnData{
+ table: tableName,
+ column: column.Name.Name.O,
+ line: node.OriginTextPosition(),
+ })
+ }
+ }
+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:
+ column := spec.NewColumns[0]
+ if !hasDefault(column) && needDefault(column) {
+ columnList = append(columnList, columnData{
+ table: tableName,
+ column: column.Name.Name.O,
+ line: node.OriginTextPosition(),
+ })
+ }
+ }
+ }
+ }
+
+ for _, column := range columnList {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.NoDefault,
+ Title: checker.title,
+ Content: fmt.Sprintf("Column `%s`.`%s` doesn't have DEFAULT.", column.table, column.column),
+ Line: column.line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*columRequireDefaultChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func needDefault(column *ast.ColumnDef) bool {
+ for _, option := range column.Options {
+ switch option.Tp {
+ case ast.ColumnOptionAutoIncrement, ast.ColumnOptionPrimaryKey, ast.ColumnOptionGenerated:
+ return false
+ }
+ }
+
+ if types.IsTypeBlob(column.Tp.GetType()) {
+ return false
+ }
+ switch column.Tp.GetType() {
+ case mysql.TypeJSON, mysql.TypeGeometry:
+ return false
+ }
+ return true
+}
+
+func hasDefault(column *ast.ColumnDef) bool {
+ for _, option := range column.Options {
+ if option.Tp == ast.ColumnOptionDefaultValue {
+ return true
+ }
+ }
+ return false
+}
diff --git a/backend/plugin/advisor/tidb/advisor_column_auto_increment_initial_value.go b/backend/plugin/advisor/tidb/advisor_column_auto_increment_initial_value.go
new file mode 100644
index 0000000000..572090f7f7
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_column_auto_increment_initial_value.go
@@ -0,0 +1,99 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnAutoIncrementInitialValueAdvisor)(nil)
+ _ ast.Visitor = (*columnAutoIncrementInitialValueChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLAutoIncrementColumnInitialValue, &ColumnAutoIncrementInitialValueAdvisor{})
+}
+
+// ColumnAutoIncrementInitialValueAdvisor is the advisor checking for auto-increment column initial value.
+type ColumnAutoIncrementInitialValueAdvisor struct {
+}
+
+// Check checks for auto-increment column initial value.
+func (*ColumnAutoIncrementInitialValueAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ payload, err := advisor.UnmarshalNumberTypeRulePayload(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &columnAutoIncrementInitialValueChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ value: payload.Number,
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type columnAutoIncrementInitialValueChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ value int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *columnAutoIncrementInitialValueChecker) Enter(in ast.Node) (ast.Node, bool) {
+ if createTable, ok := in.(*ast.CreateTableStmt); ok {
+ for _, option := range createTable.Options {
+ if option.Tp == ast.TableOptionAutoIncrement {
+ if option.UintValue != uint64(checker.value) {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.AutoIncrementColumnInitialValueNotMatch,
+ Title: checker.title,
+ Content: fmt.Sprintf("The initial auto-increment value in table `%s` is %v, which doesn't equal %v", createTable.Table.Name.O, option.UintValue, checker.value),
+ Line: checker.line,
+ })
+ }
+ }
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*columnAutoIncrementInitialValueChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_column_auto_increment_must_integer.go b/backend/plugin/advisor/tidb/advisor_column_auto_increment_must_integer.go
new file mode 100644
index 0000000000..c68a85957f
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_column_auto_increment_must_integer.go
@@ -0,0 +1,150 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pingcap/tidb/parser/mysql"
+ "github.com/pingcap/tidb/parser/types"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnAutoIncrementMustIntegerAdvisor)(nil)
+ _ ast.Visitor = (*columnAutoIncrementMustIntegerChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLAutoIncrementColumnMustInteger, &ColumnAutoIncrementMustIntegerAdvisor{})
+}
+
+// ColumnAutoIncrementMustIntegerAdvisor is the advisor checking for auto-increment column type.
+type ColumnAutoIncrementMustIntegerAdvisor struct {
+}
+
+// Check checks for auto-increment column type.
+func (*ColumnAutoIncrementMustIntegerAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &columnAutoIncrementMustIntegerChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type columnAutoIncrementMustIntegerChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+type columnData struct {
+ table string
+ column string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *columnAutoIncrementMustIntegerChecker) Enter(in ast.Node) (ast.Node, bool) {
+ var columnList []columnData
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, column := range node.Cols {
+ if !autoIncrementColumnIsInteger(column) {
+ columnList = append(columnList, columnData{
+ table: node.Table.Name.O,
+ column: column.Name.Name.O,
+ line: column.OriginTextPosition(),
+ })
+ }
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ if !autoIncrementColumnIsInteger(column) {
+ columnList = append(columnList, columnData{
+ table: node.Table.Name.O,
+ column: column.Name.Name.O,
+ line: node.OriginTextPosition(),
+ })
+ }
+ }
+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:
+ if !autoIncrementColumnIsInteger(spec.NewColumns[0]) {
+ columnList = append(columnList, columnData{
+ table: node.Table.Name.O,
+ column: spec.NewColumns[0].Name.Name.O,
+ line: node.OriginTextPosition(),
+ })
+ }
+ }
+ }
+ }
+
+ for _, column := range columnList {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.AutoIncrementColumnNotInteger,
+ Title: checker.title,
+ Content: fmt.Sprintf("Auto-increment column `%s`.`%s` requires integer type", column.table, column.column),
+ Line: checker.line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*columnAutoIncrementMustIntegerChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func autoIncrementColumnIsInteger(column *ast.ColumnDef) bool {
+ for _, option := range column.Options {
+ if option.Tp == ast.ColumnOptionAutoIncrement && !isInteger(column.Tp) {
+ return false
+ }
+ }
+ return true
+}
+
+func isInteger(tp *types.FieldType) bool {
+ switch tp.GetType() {
+ case mysql.TypeTiny, mysql.TypeShort, mysql.TypeInt24, mysql.TypeLong, mysql.TypeLonglong:
+ return true
+ default:
+ return false
+ }
+}
diff --git a/backend/plugin/advisor/tidb/advisor_column_auto_increment_must_unsigned.go b/backend/plugin/advisor/tidb/advisor_column_auto_increment_must_unsigned.go
new file mode 100644
index 0000000000..45942cbe1a
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_column_auto_increment_must_unsigned.go
@@ -0,0 +1,134 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pingcap/tidb/parser/mysql"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnAutoIncrementMustUnsignedAdvisor)(nil)
+ _ ast.Visitor = (*columnAutoIncrementMustUnsignedChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLAutoIncrementColumnMustUnsigned, &ColumnAutoIncrementMustUnsignedAdvisor{})
+}
+
+// ColumnAutoIncrementMustUnsignedAdvisor is the advisor checking for unsigned auto-increment column.
+type ColumnAutoIncrementMustUnsignedAdvisor struct {
+}
+
+// Check checks for unsigned auto-increment column.
+func (*ColumnAutoIncrementMustUnsignedAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &columnAutoIncrementMustUnsignedChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type columnAutoIncrementMustUnsignedChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *columnAutoIncrementMustUnsignedChecker) Enter(in ast.Node) (ast.Node, bool) {
+ var columnList []columnData
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, column := range node.Cols {
+ if !autoIncrementColumnIsUnsigned(column) {
+ columnList = append(columnList, columnData{
+ table: node.Table.Name.O,
+ column: column.Name.Name.O,
+ line: column.OriginTextPosition(),
+ })
+ }
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ if !autoIncrementColumnIsUnsigned(column) {
+ columnList = append(columnList, columnData{
+ table: node.Table.Name.O,
+ column: column.Name.Name.O,
+ line: node.OriginTextPosition(),
+ })
+ }
+ }
+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:
+ if !autoIncrementColumnIsUnsigned(spec.NewColumns[0]) {
+ columnList = append(columnList, columnData{
+ table: node.Table.Name.O,
+ column: spec.NewColumns[0].Name.Name.O,
+ line: node.OriginTextPosition(),
+ })
+ }
+ }
+ }
+ }
+
+ for _, column := range columnList {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.AutoIncrementColumnSigned,
+ Title: checker.title,
+ Content: fmt.Sprintf("Auto-increment column `%s`.`%s` is not UNSIGNED type", column.table, column.column),
+ Line: checker.line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*columnAutoIncrementMustUnsignedChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func autoIncrementColumnIsUnsigned(column *ast.ColumnDef) bool {
+ for _, option := range column.Options {
+ if option.Tp == ast.ColumnOptionAutoIncrement && !mysql.HasUnsignedFlag(column.Tp.GetFlag()) {
+ return false
+ }
+ }
+ return true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_column_comment_convention.go b/backend/plugin/advisor/tidb/advisor_column_comment_convention.go
new file mode 100644
index 0000000000..1ed3e3e336
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_column_comment_convention.go
@@ -0,0 +1,176 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pingcap/tidb/parser/format"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnCommentConventionAdvisor)(nil)
+ _ ast.Visitor = (*columnCommentConventionChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnCommentConvention, &ColumnCommentConventionAdvisor{})
+}
+
+// ColumnCommentConventionAdvisor is the advisor checking for column comment convention.
+type ColumnCommentConventionAdvisor struct {
+}
+
+// Check checks for column comment convention.
+func (*ColumnCommentConventionAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ payload, err := advisor.UnmarshalCommentConventionRulePayload(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &columnCommentConventionChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ required: payload.Required,
+ maxLength: payload.MaxLength,
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type columnCommentConventionChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ required bool
+ maxLength int
+}
+
+type columnCommentData struct {
+ exist bool
+ comment string
+ table string
+ column string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *columnCommentConventionChecker) Enter(in ast.Node) (ast.Node, bool) {
+ var columnList []columnCommentData
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, column := range node.Cols {
+ exist, comment := checker.columnComment(column)
+ columnList = append(columnList, columnCommentData{
+ exist: exist,
+ comment: comment,
+ table: node.Table.Name.O,
+ column: column.Name.Name.O,
+ line: column.OriginTextPosition(),
+ })
+ }
+ case *ast.AlterTableStmt:
+ table := node.Table.Name.O
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ exist, comment := checker.columnComment(column)
+ columnList = append(columnList, columnCommentData{
+ exist: exist,
+ comment: comment,
+ table: table,
+ column: column.Name.Name.O,
+ line: checker.line,
+ })
+ }
+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:
+ exist, comment := checker.columnComment(spec.NewColumns[0])
+ columnList = append(columnList, columnCommentData{
+ exist: exist,
+ comment: comment,
+ table: table,
+ column: spec.NewColumns[0].Name.Name.O,
+ line: checker.line,
+ })
+ }
+ }
+ }
+
+ for _, column := range columnList {
+ if checker.required && !column.exist {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.NoColumnComment,
+ Title: checker.title,
+ Content: fmt.Sprintf("Column `%s`.`%s` requires comments", column.table, column.column),
+ Line: column.line,
+ })
+ }
+ if checker.maxLength >= 0 && len(column.comment) > checker.maxLength {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.ColumnCommentTooLong,
+ Title: checker.title,
+ Content: fmt.Sprintf("The length of column `%s`.`%s` comment should be within %d characters", column.table, column.column, checker.maxLength),
+ Line: column.line,
+ })
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*columnCommentConventionChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func (checker *columnCommentConventionChecker) columnComment(column *ast.ColumnDef) (bool, string) {
+ for _, option := range column.Options {
+ if option.Tp == ast.ColumnOptionComment {
+ comment, err := restoreNode(option.Expr, format.RestoreStringWithoutCharset)
+ if err != nil {
+ comment = ""
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.Internal,
+ Title: "Internal error for parsing column comment",
+ Content: fmt.Sprintf("\"%q\" meet internal error %s", checker.text, err),
+ })
+ }
+ return true, comment
+ }
+ }
+
+ return false, ""
+}
diff --git a/backend/plugin/advisor/tidb/advisor_column_current_time_count_limit.go b/backend/plugin/advisor/tidb/advisor_column_current_time_count_limit.go
new file mode 100644
index 0000000000..803277cf5c
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_column_current_time_count_limit.go
@@ -0,0 +1,206 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pingcap/tidb/parser/mysql"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+const (
+ maxDefaultCurrentTimeColumCount = 2
+ maxOnUpdateCurrentTimeColumnCount = 1
+)
+
+var (
+ _ advisor.Advisor = (*ColumnCurrentTimeCountLimitAdvisor)(nil)
+ _ ast.Visitor = (*columnCurrentTimeCountLimitChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLCurrentTimeColumnCountLimit, &ColumnCurrentTimeCountLimitAdvisor{})
+}
+
+// ColumnCurrentTimeCountLimitAdvisor is the advisor checking for current time column count limit.
+type ColumnCurrentTimeCountLimitAdvisor struct {
+}
+
+// Check checks for current time column count limit.
+func (*ColumnCurrentTimeCountLimitAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &columnCurrentTimeCountLimitChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ tableSet: make(map[string]tableData),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ return checker.generateAdvice(), nil
+}
+
+type columnCurrentTimeCountLimitChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ tableSet map[string]tableData
+}
+
+type tableData struct {
+ tableName string
+ defaultCurrentTimeCount int
+ onUpdateCurrentTimeCount int
+ line int
+}
+
+func (checker *columnCurrentTimeCountLimitChecker) generateAdvice() []advisor.Advice {
+ var tableList []tableData
+ for _, table := range checker.tableSet {
+ tableList = append(tableList, table)
+ }
+ sort.Slice(tableList, func(i, j int) bool {
+ return tableList[i].line < tableList[j].line
+ })
+ for _, table := range tableList {
+ if table.defaultCurrentTimeCount > maxDefaultCurrentTimeColumCount {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.DefaultCurrentTimeColumnCountExceedsLimit,
+ Title: checker.title,
+ Content: fmt.Sprintf("Table `%s` has %d DEFAULT CURRENT_TIMESTAMP() columns. The count greater than %d.", table.tableName, table.defaultCurrentTimeCount, maxDefaultCurrentTimeColumCount),
+ Line: table.line,
+ })
+ }
+ if table.onUpdateCurrentTimeCount > maxOnUpdateCurrentTimeColumnCount {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.OnUpdateCurrentTimeColumnCountExceedsLimit,
+ Title: checker.title,
+ Content: fmt.Sprintf("Table `%s` has %d ON UPDATE CURRENT_TIMESTAMP() columns. The count greater than %d.", table.tableName, table.onUpdateCurrentTimeCount, maxOnUpdateCurrentTimeColumnCount),
+ Line: table.line,
+ })
+ }
+ }
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList
+}
+
+func (checker *columnCurrentTimeCountLimitChecker) count(tableName string, column *ast.ColumnDef, line int) {
+ switch column.Tp.GetType() {
+ case mysql.TypeDatetime, mysql.TypeTimestamp:
+ if isDefaultCurrentTime(column) {
+ table, exists := checker.tableSet[tableName]
+ if !exists {
+ table = tableData{
+ tableName: tableName,
+ }
+ }
+ table.defaultCurrentTimeCount++
+ table.line = line
+ checker.tableSet[tableName] = table
+ }
+ if isOnUpdateCurrentTime(column) {
+ table, exists := checker.tableSet[tableName]
+ if !exists {
+ table = tableData{
+ tableName: tableName,
+ }
+ }
+ table.onUpdateCurrentTimeCount++
+ table.line = line
+ checker.tableSet[tableName] = table
+ }
+ }
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *columnCurrentTimeCountLimitChecker) Enter(in ast.Node) (ast.Node, bool) {
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ tableName := node.Table.Name.O
+ for _, column := range node.Cols {
+ checker.count(tableName, column, node.OriginTextPosition())
+ }
+ case *ast.AlterTableStmt:
+ tableName := node.Table.Name.O
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ checker.count(tableName, column, node.OriginTextPosition())
+ }
+ case ast.AlterTableModifyColumn, ast.AlterTableChangeColumn:
+ checker.count(tableName, spec.NewColumns[0], node.OriginTextPosition())
+ }
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*columnCurrentTimeCountLimitChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func isOnUpdateCurrentTime(column *ast.ColumnDef) bool {
+ for _, option := range column.Options {
+ if option.Tp == ast.ColumnOptionOnUpdate {
+ if function, ok := option.Expr.(*ast.FuncCallExpr); ok && isCurrentTime(function.FnName.L) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func isDefaultCurrentTime(column *ast.ColumnDef) bool {
+ for _, option := range column.Options {
+ if option.Tp == ast.ColumnOptionDefaultValue {
+ if function, ok := option.Expr.(*ast.FuncCallExpr); ok && isCurrentTime(function.FnName.L) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func isCurrentTime(name string) bool {
+ switch strings.ToLower(name) {
+ // Any of the synonyms for CURRENT_TIMESTAMP have the same meaning as CURRENT_TIMESTAMP.
+ // These are CURRENT_TIMESTAMP(), NOW(), LOCALTIME, LOCALTIME(), LOCALTIMESTAMP, and LOCALTIMESTAMP().
+ // See https://dev.mysql.com/doc/refman/8.0/en/timestamp-initialization.html.
+ case "current_timestamp", "now", "localtime", "localtimestamp":
+ return true
+ }
+ return false
+}
diff --git a/backend/plugin/advisor/tidb/advisor_column_disallow_changing.go b/backend/plugin/advisor/tidb/advisor_column_disallow_changing.go
new file mode 100644
index 0000000000..debae84346
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_column_disallow_changing.go
@@ -0,0 +1,92 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnDisallowChangingAdvisor)(nil)
+ _ ast.Visitor = (*columnDisallowChangingChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnDisallowChanging, &ColumnDisallowChangingAdvisor{})
+}
+
+// ColumnDisallowChangingAdvisor is the advisor checking for disallow CHANGE COLUMN statement.
+type ColumnDisallowChangingAdvisor struct {
+}
+
+// Check checks for disallow CHANGE COLUMN statement.
+func (*ColumnDisallowChangingAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &columnDisallowChangingChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type columnDisallowChangingChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *columnDisallowChangingChecker) Enter(in ast.Node) (ast.Node, bool) {
+ if node, ok := in.(*ast.AlterTableStmt); ok {
+ for _, spec := range node.Specs {
+ if spec.Tp == ast.AlterTableChangeColumn {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.UseChangeColumnStatement,
+ Title: checker.title,
+ Content: fmt.Sprintf("\"%s\" contains CHANGE COLUMN statement", checker.text),
+ Line: checker.line,
+ })
+ break
+ }
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*columnDisallowChangingChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_column_disallow_changing_order.go b/backend/plugin/advisor/tidb/advisor_column_disallow_changing_order.go
new file mode 100644
index 0000000000..5476afda92
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_column_disallow_changing_order.go
@@ -0,0 +1,93 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnDisallowChangingOrderAdvisor)(nil)
+ _ ast.Visitor = (*columnDisallowChangingOrderChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnDisallowChangingOrder, &ColumnDisallowChangingOrderAdvisor{})
+}
+
+// ColumnDisallowChangingOrderAdvisor is the advisor checking for disallow changing column order.
+type ColumnDisallowChangingOrderAdvisor struct {
+}
+
+// Check checks for disallow changing column order.
+func (*ColumnDisallowChangingOrderAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &columnDisallowChangingOrderChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type columnDisallowChangingOrderChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *columnDisallowChangingOrderChecker) Enter(in ast.Node) (ast.Node, bool) {
+ if node, ok := in.(*ast.AlterTableStmt); ok {
+ for _, spec := range node.Specs {
+ if (spec.Tp == ast.AlterTableChangeColumn || spec.Tp == ast.AlterTableModifyColumn) &&
+ spec.Position.Tp != ast.ColumnPositionNone {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.ChangeColumnOrder,
+ Title: checker.title,
+ Content: fmt.Sprintf("\"%s\" changes column order", checker.text),
+ Line: checker.line,
+ })
+ break
+ }
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*columnDisallowChangingOrderChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_column_disallow_changing_type.go b/backend/plugin/advisor/tidb/advisor_column_disallow_changing_type.go
new file mode 100644
index 0000000000..3b674fce06
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_column_disallow_changing_type.go
@@ -0,0 +1,146 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/catalog"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnDisallowChangingTypeAdvisor)(nil)
+ _ ast.Visitor = (*columnDisallowChangingTypeChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnDisallowChangingType, &ColumnDisallowChangingTypeAdvisor{})
+}
+
+// ColumnDisallowChangingTypeAdvisor is the advisor checking for disallow changing column type..
+type ColumnDisallowChangingTypeAdvisor struct {
+}
+
+// Check checks for disallow changing column type..
+func (*ColumnDisallowChangingTypeAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &columnDisallowChangingTypeChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ catalog: ctx.Catalog,
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type columnDisallowChangingTypeChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ catalog *catalog.Finder
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *columnDisallowChangingTypeChecker) Enter(in ast.Node) (ast.Node, bool) {
+ changeType := false
+ if node, ok := in.(*ast.AlterTableStmt); ok {
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableChangeColumn:
+ changeType = checker.changeColumnType(node.Table.Name.O, spec.OldColumnName.Name.O, spec.NewColumns[0].Tp.String())
+ case ast.AlterTableModifyColumn:
+ changeType = checker.changeColumnType(node.Table.Name.O, spec.NewColumns[0].Name.Name.O, spec.NewColumns[0].Tp.String())
+ }
+ if changeType {
+ break
+ }
+ }
+ }
+
+ if changeType {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.ChangeColumnType,
+ Title: checker.title,
+ Content: fmt.Sprintf("\"%s\" changes column type", checker.text),
+ Line: checker.line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*columnDisallowChangingTypeChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func normalizeColumnType(tp string) string {
+ switch strings.ToLower(tp) {
+ case "tinyint":
+ return "tinyint(4)"
+ case "tinyint unsigned":
+ return "tinyint(4) unsigned"
+ case "smallint":
+ return "smallint(6)"
+ case "smallint unsigned":
+ return "smallint(6) unsigned"
+ case "mediumint":
+ return "mediumint(9)"
+ case "mediumint unsigned":
+ return "mediumint(9) unsigned"
+ case "int":
+ return "int(11)"
+ case "int unsigned":
+ return "int(11) unsigned"
+ case "bigint":
+ return "bigint(20)"
+ case "bigint unsigned":
+ return "bigint(20) unsigned"
+ default:
+ return strings.ToLower(tp)
+ }
+}
+
+func (checker *columnDisallowChangingTypeChecker) changeColumnType(tableName string, columName string, newType string) bool {
+ column := checker.catalog.Origin.FindColumn(&catalog.ColumnFind{
+ TableName: tableName,
+ ColumnName: columName,
+ })
+
+ if column == nil {
+ return false
+ }
+
+ return normalizeColumnType(column.Type()) != normalizeColumnType(newType)
+}
diff --git a/backend/plugin/advisor/tidb/advisor_column_disallow_drop_in_index.go b/backend/plugin/advisor/tidb/advisor_column_disallow_drop_in_index.go
new file mode 100644
index 0000000000..566212a7d2
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_column_disallow_drop_in_index.go
@@ -0,0 +1,150 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/catalog"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnDisallowDropInIndexAdvisor)(nil)
+ _ ast.Visitor = (*columnDisallowDropInIndexChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnDisallowDropInIndex, &ColumnDisallowDropInIndexAdvisor{})
+}
+
+// ColumnDisallowDropInIndexAdvisor is the advisor checking for disallow DROP COLUMN in index.
+type ColumnDisallowDropInIndexAdvisor struct {
+}
+
+// Check checks for disallow Drop COLUMN in index statement.
+func (*ColumnDisallowDropInIndexAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ checker := &columnDisallowDropInIndexChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ tables: make(tableState),
+ catalog: ctx.Catalog,
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+
+ return checker.adviceList, nil
+}
+
+type columnDisallowDropInIndexChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ tables tableState // the variable mean whether the column in index.
+ catalog *catalog.Finder
+ line int
+}
+
+func (checker *columnDisallowDropInIndexChecker) Enter(in ast.Node) (ast.Node, bool) {
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ checker.addIndexColumn(node)
+ case *ast.AlterTableStmt:
+ return checker.dropColumn(node)
+ }
+ return in, false
+}
+
+func (*columnDisallowDropInIndexChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func (checker *columnDisallowDropInIndexChecker) dropColumn(in ast.Node) (ast.Node, bool) {
+ if node, ok := in.(*ast.AlterTableStmt); ok {
+ for _, spec := range node.Specs {
+ if spec.Tp == ast.AlterTableDropColumn {
+ table := node.Table.Name.O
+
+ index := checker.catalog.Origin.Index(&catalog.TableIndexFind{
+ // In MySQL, the SchemaName is "".
+ SchemaName: "",
+ TableName: table,
+ })
+
+ if index != nil {
+ if checker.tables[table] == nil {
+ checker.tables[table] = make(columnSet)
+ }
+ for _, indexColumn := range *index {
+ for _, column := range indexColumn.ExpressionList() {
+ checker.tables[table][column] = true
+ }
+ }
+ }
+
+ colName := spec.OldColumnName.Name.String()
+ if !checker.canDrop(table, colName) {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.DropIndexColumn,
+ Title: checker.title,
+ Content: fmt.Sprintf("`%s`.`%s` cannot drop index column", table, colName),
+ Line: checker.line,
+ })
+ }
+ }
+ }
+ }
+ return in, false
+}
+
+func (checker *columnDisallowDropInIndexChecker) addIndexColumn(in ast.Node) {
+ if node, ok := in.(*ast.CreateTableStmt); ok {
+ for _, spec := range node.Constraints {
+ if spec.Tp == ast.ConstraintIndex {
+ for _, key := range spec.Keys {
+ table := node.Table.Name.O
+ if checker.tables[table] == nil {
+ checker.tables[table] = make(columnSet)
+ }
+ checker.tables[table][key.Column.Name.O] = true
+ }
+ }
+ }
+ }
+}
+
+func (checker *columnDisallowDropInIndexChecker) canDrop(table string, column string) bool {
+ if _, ok := checker.tables[table][column]; ok {
+ return false
+ }
+ return true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_column_disallow_set_charset.go b/backend/plugin/advisor/tidb/advisor_column_disallow_set_charset.go
new file mode 100644
index 0000000000..7191b760b0
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_column_disallow_set_charset.go
@@ -0,0 +1,129 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnDisallowSetCharsetAdvisor)(nil)
+ _ ast.Visitor = (*columnDisallowSetCharsetChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLDisallowSetColumnCharset, &ColumnDisallowSetCharsetAdvisor{})
+}
+
+// ColumnDisallowSetCharsetAdvisor is the advisor checking for disallow set column charset.
+type ColumnDisallowSetCharsetAdvisor struct {
+}
+
+// Check checks for disallow set column charset.
+func (*ColumnDisallowSetCharsetAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &columnDisallowSetCharsetChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type columnDisallowSetCharsetChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *columnDisallowSetCharsetChecker) Enter(in ast.Node) (ast.Node, bool) {
+ code := advisor.Ok
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, column := range node.Cols {
+ charset := getColumnCharset(column)
+ if !checkCharset(charset) {
+ code = advisor.SetColumnCharset
+ break
+ }
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ charset := getColumnCharset(column)
+ if !checkCharset(charset) {
+ code = advisor.SetColumnCharset
+ }
+ }
+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:
+ charset := getColumnCharset(spec.NewColumns[0])
+ if !checkCharset(charset) {
+ code = advisor.SetColumnCharset
+ }
+ }
+ if code != advisor.Ok {
+ break
+ }
+ }
+ }
+
+ if code != advisor.Ok {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.SetColumnCharset,
+ Title: checker.title,
+ Content: fmt.Sprintf("Disallow set column charset but \"%s\" does", checker.text),
+ Line: checker.line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*columnDisallowSetCharsetChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func checkCharset(charset string) bool {
+ switch charset {
+ // empty charset or binary for JSON.
+ case "", "binary":
+ return true
+ default:
+ return false
+ }
+}
diff --git a/backend/plugin/advisor/tidb/advisor_column_maximum_character_length.go b/backend/plugin/advisor/tidb/advisor_column_maximum_character_length.go
new file mode 100644
index 0000000000..86f52efb8b
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_column_maximum_character_length.go
@@ -0,0 +1,140 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pingcap/tidb/parser/mysql"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnMaximumCharacterLengthAdvisor)(nil)
+ _ ast.Visitor = (*columnMaximumCharacterLengthChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnMaximumCharacterLength, &ColumnMaximumCharacterLengthAdvisor{})
+}
+
+// ColumnMaximumCharacterLengthAdvisor is the advisor checking for max character length.
+type ColumnMaximumCharacterLengthAdvisor struct {
+}
+
+// Check checks for maximum character length.
+func (*ColumnMaximumCharacterLengthAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ payload, err := advisor.UnmarshalNumberTypeRulePayload(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &columnMaximumCharacterLengthChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ maximum: payload.Number,
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type columnMaximumCharacterLengthChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ maximum int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *columnMaximumCharacterLengthChecker) Enter(in ast.Node) (ast.Node, bool) {
+ var tableName, columnName string
+ var line int
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, column := range node.Cols {
+ charLength := getCharLength(column)
+ if checker.maximum > 0 && charLength > checker.maximum {
+ tableName = node.Table.Name.O
+ columnName = column.Name.Name.O
+ line = column.OriginTextPosition()
+ break
+ }
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ charLength := getCharLength(column)
+ if checker.maximum > 0 && charLength > checker.maximum {
+ tableName = node.Table.Name.O
+ columnName = column.Name.Name.O
+ line = node.OriginTextPosition()
+ }
+ }
+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:
+ charLength := getCharLength(spec.NewColumns[0])
+ if checker.maximum > 0 && charLength > checker.maximum {
+ tableName = node.Table.Name.O
+ columnName = spec.NewColumns[0].Name.Name.O
+ line = node.OriginTextPosition()
+ }
+ }
+ if tableName != "" {
+ break
+ }
+ }
+ }
+
+ if tableName != "" {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.CharLengthExceedsLimit,
+ Title: checker.title,
+ Content: fmt.Sprintf("The length of the CHAR column `%s` is bigger than %d, please use VARCHAR instead", columnName, checker.maximum),
+ Line: line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*columnMaximumCharacterLengthChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func getCharLength(column *ast.ColumnDef) int {
+ if column.Tp.GetType() == mysql.TypeString {
+ return column.Tp.GetFlen()
+ }
+ return 0
+}
diff --git a/backend/plugin/advisor/tidb/advisor_column_no_null.go b/backend/plugin/advisor/tidb/advisor_column_no_null.go
new file mode 100644
index 0000000000..d0d88d8bfe
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_column_no_null.go
@@ -0,0 +1,170 @@
+package tidb
+
+import (
+ "fmt"
+ "sort"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/catalog"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnNoNullAdvisor)(nil)
+ _ ast.Visitor = (*columnNoNullChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnNoNull, &ColumnNoNullAdvisor{})
+}
+
+// ColumnNoNullAdvisor is the advisor checking for column no NULL value.
+type ColumnNoNullAdvisor struct {
+}
+
+// Check checks for column no NULL value.
+func (*ColumnNoNullAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ root, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &columnNoNullChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ columnSet: make(map[string]columnName),
+ catalog: ctx.Catalog,
+ }
+
+ for _, stmtNode := range root {
+ (stmtNode).Accept(checker)
+ }
+
+ return checker.generateAdvice(), nil
+}
+
+type columnNoNullChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ columnSet map[string]columnName
+ catalog *catalog.Finder
+}
+
+func (checker columnNoNullChecker) generateAdvice() []advisor.Advice {
+ var columnList []columnName
+ for _, column := range checker.columnSet {
+ columnList = append(columnList, column)
+ }
+ sort.Slice(columnList, func(i, j int) bool {
+ if columnList[i].line != columnList[j].line {
+ return columnList[i].line < columnList[j].line
+ }
+ return columnList[i].columnName < columnList[j].columnName
+ })
+
+ for _, column := range columnList {
+ col := checker.catalog.Final.FindColumn(&catalog.ColumnFind{
+ TableName: column.tableName,
+ ColumnName: column.columnName,
+ })
+ if col != nil && col.Nullable() {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.ColumnCannotNull,
+ Title: checker.title,
+ Content: fmt.Sprintf("`%s`.`%s` cannot have NULL value", column.tableName, column.columnName),
+ Line: column.line,
+ })
+ }
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList
+}
+
+type columnName struct {
+ tableName string
+ columnName string
+ line int
+}
+
+func (c columnName) name() string {
+ return fmt.Sprintf("%s.%s", c.tableName, c.columnName)
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *columnNoNullChecker) Enter(in ast.Node) (ast.Node, bool) {
+ switch node := in.(type) {
+ // CREATE TABLE
+ case *ast.CreateTableStmt:
+ for _, column := range node.Cols {
+ col := columnName{
+ tableName: node.Table.Name.O,
+ columnName: column.Name.Name.O,
+ line: column.OriginTextPosition(),
+ }
+ if _, exists := checker.columnSet[col.name()]; !exists {
+ checker.columnSet[col.name()] = col
+ }
+ }
+ // ALTER TABLE
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ // ADD COLUMNS
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ col := columnName{
+ tableName: node.Table.Name.O,
+ columnName: column.Name.Name.O,
+ line: node.OriginTextPosition(),
+ }
+ if _, exists := checker.columnSet[col.name()]; !exists {
+ checker.columnSet[col.name()] = col
+ }
+ }
+ // CHANGE COLUMN
+ case ast.AlterTableChangeColumn:
+ col := columnName{
+ tableName: node.Table.Name.O,
+ columnName: spec.NewColumns[0].Name.Name.O,
+ line: node.OriginTextPosition(),
+ }
+ if _, exists := checker.columnSet[col.name()]; !exists {
+ checker.columnSet[col.name()] = col
+ }
+ }
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*columnNoNullChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func canNull(column *ast.ColumnDef) bool {
+ for _, option := range column.Options {
+ if option.Tp == ast.ColumnOptionNotNull || option.Tp == ast.ColumnOptionPrimaryKey {
+ return false
+ }
+ }
+ return true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_column_required.go b/backend/plugin/advisor/tidb/advisor_column_required.go
new file mode 100644
index 0000000000..f23de687ed
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_column_required.go
@@ -0,0 +1,221 @@
+package tidb
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnRequirementAdvisor)(nil)
+ _ ast.Visitor = (*columnRequirementChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnRequirement, &ColumnRequirementAdvisor{})
+}
+
+// ColumnRequirementAdvisor is the advisor checking for column requirement.
+type ColumnRequirementAdvisor struct {
+}
+
+// Check checks for the column requirement.
+func (*ColumnRequirementAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ root, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ columnList, err := advisor.UnmarshalRequiredColumnList(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ requiredColumns := make(columnSet)
+ for _, column := range columnList {
+ requiredColumns[column] = true
+ }
+ checker := &columnRequirementChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ requiredColumns: requiredColumns,
+ tables: make(tableState),
+ line: make(map[string]int),
+ }
+
+ for _, stmtNode := range root {
+ (stmtNode).Accept(checker)
+ }
+
+ return checker.generateAdviceList(), nil
+}
+
+type columnRequirementChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ requiredColumns columnSet
+ tables tableState
+ line map[string]int
+}
+
+// Enter implements the ast.Visitor interface.
+func (v *columnRequirementChecker) Enter(in ast.Node) (ast.Node, bool) {
+ switch node := in.(type) {
+ // CREATE TABLE
+ case *ast.CreateTableStmt:
+ v.createTable(node)
+ // DROP TABLE
+ case *ast.DropTableStmt:
+ for _, table := range node.Tables {
+ delete(v.tables, table.Name.String())
+ }
+ // ALTER TABLE
+ case *ast.AlterTableStmt:
+ table := node.Table.Name.O
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ // RENAME COLUMN
+ case ast.AlterTableRenameColumn:
+ v.renameColumn(table, spec.OldColumnName.Name.O, spec.NewColumnName.Name.O)
+ v.line[table] = node.OriginTextPosition()
+ // ADD COLUMNS
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ v.addColumn(table, column.Name.Name.O)
+ }
+ // DROP COLUMN
+ case ast.AlterTableDropColumn:
+ if v.dropColumn(table, spec.OldColumnName.Name.O) {
+ v.line[table] = node.OriginTextPosition()
+ }
+ // CHANGE COLUMN
+ case ast.AlterTableChangeColumn:
+ if v.renameColumn(table, spec.OldColumnName.Name.O, spec.NewColumns[0].Name.Name.O) {
+ v.line[table] = node.OriginTextPosition()
+ }
+ }
+ }
+ }
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*columnRequirementChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func (v *columnRequirementChecker) generateAdviceList() []advisor.Advice {
+ // Order it cause the random iteration order in Go, see https://go.dev/blog/maps
+ tableList := v.tables.tableList()
+ for _, tableName := range tableList {
+ table := v.tables[tableName]
+ var missingColumns []string
+ for column := range v.requiredColumns {
+ if exist, ok := table[column]; !ok || !exist {
+ missingColumns = append(missingColumns, column)
+ }
+ }
+ if len(missingColumns) > 0 {
+ // Order it cause the random iteration order in Go, see https://go.dev/blog/maps
+ sort.Strings(missingColumns)
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: v.level,
+ Code: advisor.NoRequiredColumn,
+ Title: v.title,
+ Content: fmt.Sprintf("Table `%s` requires columns: %s", tableName, strings.Join(missingColumns, ", ")),
+ Line: v.line[tableName],
+ })
+ }
+ }
+
+ if len(v.adviceList) == 0 {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return v.adviceList
+}
+
+// initEmptyTable will initialize a table without any required columns.
+func (v *columnRequirementChecker) initEmptyTable(name string) columnSet {
+ v.tables[name] = make(columnSet)
+ return v.tables[name]
+}
+
+// initFullTable will initialize a table with all required columns.
+func (v *columnRequirementChecker) initFullTable(name string) columnSet {
+ table := v.initEmptyTable(name)
+ for column := range v.requiredColumns {
+ table[column] = true
+ }
+ return table
+}
+
+func (v *columnRequirementChecker) renameColumn(table string, oldColumn string, newColumn string) bool {
+ _, oldNeed := v.requiredColumns[oldColumn]
+ _, newNeed := v.requiredColumns[newColumn]
+ if !oldNeed && !newNeed {
+ return false
+ }
+ t, ok := v.tables[table]
+ if !ok {
+ // We do not retrospectively check.
+ // So we assume it contains all required columns.
+ t = v.initFullTable(table)
+ }
+ if oldNeed {
+ t[oldColumn] = false
+ }
+ if newNeed {
+ t[newColumn] = true
+ }
+ return oldNeed
+}
+
+func (v *columnRequirementChecker) dropColumn(table string, column string) bool {
+ if _, ok := v.requiredColumns[column]; !ok {
+ return false
+ }
+ t, ok := v.tables[table]
+ if !ok {
+ // We do not retrospectively check.
+ // So we assume it contains all required columns.
+ t = v.initFullTable(table)
+ }
+ t[column] = false
+ return true
+}
+
+func (v *columnRequirementChecker) addColumn(table string, column string) {
+ if _, ok := v.requiredColumns[column]; !ok {
+ return
+ }
+ if t, ok := v.tables[table]; !ok {
+ // We do not retrospectively check.
+ // So we assume it contains all required columns.
+ v.initFullTable(table)
+ } else {
+ t[column] = true
+ }
+}
+
+func (v *columnRequirementChecker) createTable(node *ast.CreateTableStmt) {
+ v.line[node.Table.Name.O] = node.OriginTextPosition()
+ v.initEmptyTable(node.Table.Name.O)
+ for _, column := range node.Cols {
+ v.addColumn(node.Table.Name.O, column.Name.Name.O)
+ }
+}
diff --git a/backend/plugin/advisor/tidb/advisor_column_set_default_for_not_null.go b/backend/plugin/advisor/tidb/advisor_column_set_default_for_not_null.go
new file mode 100644
index 0000000000..0a1d66db3e
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_column_set_default_for_not_null.go
@@ -0,0 +1,146 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnSetDefaultForNotNullAdvisor)(nil)
+ _ ast.Visitor = (*columnSetDefaultForNotNullChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnSetDefaultForNotNull, &ColumnSetDefaultForNotNullAdvisor{})
+}
+
+// ColumnSetDefaultForNotNullAdvisor is the advisor checking for set default value for not null column.
+type ColumnSetDefaultForNotNullAdvisor struct {
+}
+
+// Check checks for set default value for not null column.
+func (*ColumnSetDefaultForNotNullAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &columnSetDefaultForNotNullChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type columnSetDefaultForNotNullChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *columnSetDefaultForNotNullChecker) Enter(in ast.Node) (ast.Node, bool) {
+ var notNullColumnWithNoDefault []columnName
+ switch node := in.(type) {
+ // CREATE TABLE
+ case *ast.CreateTableStmt:
+ pkColumn := make(map[string]bool)
+ for _, cons := range node.Constraints {
+ if cons.Tp == ast.ConstraintPrimaryKey {
+ for _, key := range cons.Keys {
+ pkColumn[key.Column.Name.O] = true
+ }
+ }
+ }
+
+ for _, column := range node.Cols {
+ _, ok := pkColumn[column.Name.Name.O]
+ notNull := ok || !canNull(column)
+ if notNull && !setDefault(column) && needDefault(column) {
+ notNullColumnWithNoDefault = append(notNullColumnWithNoDefault, columnName{
+ tableName: node.Table.Name.O,
+ columnName: column.Name.Name.O,
+ line: column.OriginTextPosition(),
+ })
+ }
+ }
+ // ALTER TABLE
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ // ADD COLUMNS
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ if !canNull(column) && !setDefault(column) && needDefault(column) {
+ notNullColumnWithNoDefault = append(notNullColumnWithNoDefault, columnName{
+ tableName: node.Table.Name.O,
+ columnName: column.Name.Name.O,
+ line: node.OriginTextPosition(),
+ })
+ }
+ }
+ // CHANGE COLUMN and MODIFY COLUMN
+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:
+ if !canNull(spec.NewColumns[0]) && !setDefault(spec.NewColumns[0]) && needDefault(spec.NewColumns[0]) {
+ notNullColumnWithNoDefault = append(notNullColumnWithNoDefault, columnName{
+ tableName: node.Table.Name.O,
+ columnName: spec.NewColumns[0].Name.Name.O,
+ line: node.OriginTextPosition(),
+ })
+ }
+ }
+ }
+ }
+
+ for _, column := range notNullColumnWithNoDefault {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.NotNullColumnWithNoDefault,
+ Title: checker.title,
+ Content: fmt.Sprintf("Column `%s`.`%s` is NOT NULL but doesn't have DEFAULT", column.tableName, column.columnName),
+ Line: column.line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*columnSetDefaultForNotNullChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func setDefault(column *ast.ColumnDef) bool {
+ for _, option := range column.Options {
+ if option.Tp == ast.ColumnOptionDefaultValue {
+ return true
+ }
+ }
+ return false
+}
diff --git a/backend/plugin/advisor/tidb/advisor_column_type_restriction.go b/backend/plugin/advisor/tidb/advisor_column_type_restriction.go
new file mode 100644
index 0000000000..2d66fdb212
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_column_type_restriction.go
@@ -0,0 +1,145 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*ColumnTypeRestrictionAdvisor)(nil)
+ _ ast.Visitor = (*columnTypeRestrictionChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLColumnTypeRestriction, &ColumnTypeRestrictionAdvisor{})
+}
+
+// ColumnTypeRestrictionAdvisor is the advisor checking for column type restriction.
+type ColumnTypeRestrictionAdvisor struct {
+}
+
+// Check checks for column type restriction.
+func (*ColumnTypeRestrictionAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ paylaod, err := advisor.UnmarshalStringArrayTypeRulePayload(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &columnTypeRestrictionChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ typeRestriction: make(map[string]bool),
+ }
+ for _, tp := range paylaod.List {
+ checker.typeRestriction[strings.ToUpper(tp)] = true
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type columnTypeRestrictionChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ typeRestriction map[string]bool
+}
+
+type columnTypeData struct {
+ table string
+ column string
+ tp string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *columnTypeRestrictionChecker) Enter(in ast.Node) (ast.Node, bool) {
+ var columnList []columnTypeData
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, column := range node.Cols {
+ if _, exist := checker.typeRestriction[strings.ToUpper(column.Tp.CompactStr())]; exist {
+ columnList = append(columnList, columnTypeData{
+ table: node.Table.Name.O,
+ column: column.Name.Name.O,
+ tp: strings.ToUpper(column.Tp.CompactStr()),
+ line: column.OriginTextPosition(),
+ })
+ }
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ if _, exist := checker.typeRestriction[strings.ToUpper(column.Tp.CompactStr())]; exist {
+ columnList = append(columnList, columnTypeData{
+ table: node.Table.Name.O,
+ column: column.Name.Name.O,
+ tp: strings.ToUpper(column.Tp.CompactStr()),
+ line: node.OriginTextPosition(),
+ })
+ }
+ }
+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:
+ column := spec.NewColumns[0]
+ if _, exist := checker.typeRestriction[strings.ToUpper(column.Tp.CompactStr())]; exist {
+ columnList = append(columnList, columnTypeData{
+ table: node.Table.Name.O,
+ column: column.Name.Name.O,
+ tp: strings.ToUpper(column.Tp.CompactStr()),
+ line: node.OriginTextPosition(),
+ })
+ }
+ }
+ }
+ }
+
+ for _, column := range columnList {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.DisabledColumnType,
+ Title: checker.title,
+ Content: fmt.Sprintf("Disallow column type %s but column `%s`.`%s` is", column.tp, column.table, column.column),
+ Line: column.line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*columnTypeRestrictionChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_database_drop_empty_db.go b/backend/plugin/advisor/tidb/advisor_database_drop_empty_db.go
new file mode 100644
index 0000000000..ef7c93e5f5
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_database_drop_empty_db.go
@@ -0,0 +1,93 @@
+package tidb
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/catalog"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*DatabaseAllowDropIfEmptyAdvisor)(nil)
+ _ ast.Visitor = (*allowDropEmptyDBChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLDatabaseAllowDropIfEmpty, &DatabaseAllowDropIfEmptyAdvisor{})
+}
+
+// DatabaseAllowDropIfEmptyAdvisor is the advisor checking the MySQLDatabaseAllowDropIfEmpty rule.
+type DatabaseAllowDropIfEmptyAdvisor struct {
+}
+
+// Check checks for drop table naming convention.
+func (*DatabaseAllowDropIfEmptyAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ root, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ checker := &allowDropEmptyDBChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ catalog: ctx.Catalog,
+ }
+ for _, stmtNode := range root {
+ (stmtNode).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type allowDropEmptyDBChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ catalog *catalog.Finder
+}
+
+// Enter implements the ast.Visitor interface.
+func (v *allowDropEmptyDBChecker) Enter(in ast.Node) (ast.Node, bool) {
+ if node, ok := in.(*ast.DropDatabaseStmt); ok {
+ if v.catalog.Origin.DatabaseName() != node.Name.O {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: v.level,
+ Code: advisor.NotCurrentDatabase,
+ Title: v.title,
+ Content: fmt.Sprintf("Database `%s` that is trying to be deleted is not the current database `%s`", node.Name, v.catalog.Origin.DatabaseName()),
+ Line: node.OriginTextPosition(),
+ })
+ } else if !v.catalog.Origin.HasNoTable() {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: v.level,
+ Code: advisor.DatabaseNotEmpty,
+ Title: v.title,
+ Content: fmt.Sprintf("Database `%s` is not allowed to drop if not empty", node.Name),
+ Line: node.OriginTextPosition(),
+ })
+ }
+ }
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*allowDropEmptyDBChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_index_key_number_limit.go b/backend/plugin/advisor/tidb/advisor_index_key_number_limit.go
new file mode 100644
index 0000000000..f33cada4de
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_index_key_number_limit.go
@@ -0,0 +1,144 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*IndexKeyNumberLimitAdvisor)(nil)
+ _ ast.Visitor = (*indexKeyNumberLimitChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLIndexKeyNumberLimit, &IndexKeyNumberLimitAdvisor{})
+}
+
+// IndexKeyNumberLimitAdvisor is the advisor checking for index key number limit.
+type IndexKeyNumberLimitAdvisor struct {
+}
+
+// Check checks for index key number limit.
+func (*IndexKeyNumberLimitAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ payload, err := advisor.UnmarshalNumberTypeRulePayload(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &indexKeyNumberLimitChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ max: payload.Number,
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type indexKeyNumberLimitChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ max int
+}
+
+type indexData struct {
+ table string
+ index string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *indexKeyNumberLimitChecker) Enter(in ast.Node) (ast.Node, bool) {
+ var indexList []indexData
+
+ appendIndexItem := func(table, index string, line int) {
+ indexList = append(indexList, indexData{
+ table: table,
+ index: index,
+ line: line,
+ })
+ }
+
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, constraint := range node.Constraints {
+ if checker.max > 0 && indexKeyNumber(constraint) > checker.max {
+ appendIndexItem(node.Table.Name.O, constraint.Name, constraint.OriginTextPosition())
+ }
+ }
+ case *ast.CreateIndexStmt:
+ if checker.max > 0 && len(node.IndexPartSpecifications) > checker.max {
+ appendIndexItem(node.Table.Name.O, node.IndexName, checker.line)
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ if spec.Tp == ast.AlterTableAddConstraint {
+ if checker.max > 0 && indexKeyNumber(spec.Constraint) > checker.max {
+ appendIndexItem(node.Table.Name.O, spec.Constraint.Name, checker.line)
+ }
+ }
+ }
+ }
+
+ for _, index := range indexList {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.IndexKeyNumberExceedsLimit,
+ Title: checker.title,
+ Content: fmt.Sprintf("The number of index `%s` in table `%s` should be not greater than %d", index.index, index.table, checker.max),
+ Line: index.line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*indexKeyNumberLimitChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func indexKeyNumber(constraint *ast.Constraint) int {
+ switch constraint.Tp {
+ case ast.ConstraintIndex,
+ ast.ConstraintPrimaryKey,
+ ast.ConstraintUniq,
+ ast.ConstraintUniqKey,
+ ast.ConstraintUniqIndex,
+ ast.ConstraintForeignKey:
+ return len(constraint.Keys)
+ default:
+ return 0
+ }
+}
diff --git a/backend/plugin/advisor/tidb/advisor_index_no_duplicate_column.go b/backend/plugin/advisor/tidb/advisor_index_no_duplicate_column.go
new file mode 100644
index 0000000000..16bc95caf1
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_index_no_duplicate_column.go
@@ -0,0 +1,176 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*IndexNoDuplicateColumnAdvisor)(nil)
+ _ ast.Visitor = (*indexNoDuplicateColumnChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLIndexNoDuplicateColumn, &IndexNoDuplicateColumnAdvisor{})
+}
+
+// IndexNoDuplicateColumnAdvisor is the advisor checking for no duplicate columns in index.
+type IndexNoDuplicateColumnAdvisor struct {
+}
+
+// Check checks for no duplicate columns in index.
+func (*IndexNoDuplicateColumnAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &indexNoDuplicateColumnChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type indexNoDuplicateColumnChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *indexNoDuplicateColumnChecker) Enter(in ast.Node) (ast.Node, bool) {
+ type duplicateColumn struct {
+ table string
+ index string
+ column string
+ line int
+ tp string
+ }
+ var columnList []duplicateColumn
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, constraint := range node.Constraints {
+ switch constraint.Tp {
+ case ast.ConstraintPrimaryKey,
+ ast.ConstraintUniq,
+ ast.ConstraintUniqIndex,
+ ast.ConstraintIndex,
+ ast.ConstraintForeignKey:
+ if column, duplicate := hasDuplicateColumn(constraint.Keys); duplicate {
+ columnList = append(columnList, duplicateColumn{
+ tp: indexTypeString(constraint.Tp),
+ table: node.Table.Name.O,
+ index: constraint.Name,
+ column: column,
+ line: constraint.OriginTextPosition(),
+ })
+ }
+ }
+ }
+ case *ast.CreateIndexStmt:
+ if column, duplicate := hasDuplicateColumn(node.IndexPartSpecifications); duplicate {
+ columnList = append(columnList, duplicateColumn{
+ tp: "INDEX",
+ table: node.Table.Name.O,
+ index: node.IndexName,
+ column: column,
+ line: checker.line,
+ })
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ if spec.Tp == ast.AlterTableAddConstraint {
+ switch spec.Constraint.Tp {
+ case ast.ConstraintPrimaryKey,
+ ast.ConstraintUniq,
+ ast.ConstraintUniqIndex,
+ ast.ConstraintIndex,
+ ast.ConstraintForeignKey:
+ if column, duplicate := hasDuplicateColumn(spec.Constraint.Keys); duplicate {
+ columnList = append(columnList, duplicateColumn{
+ tp: indexTypeString(spec.Constraint.Tp),
+ table: node.Table.Name.O,
+ index: spec.Constraint.Name,
+ column: column,
+ line: checker.line,
+ })
+ }
+ }
+ }
+ }
+ }
+
+ for _, column := range columnList {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.DuplicateColumnInIndex,
+ Title: checker.title,
+ Content: fmt.Sprintf("%s `%s` has duplicate column `%s`.`%s`", column.tp, column.index, column.table, column.column),
+ Line: column.line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*indexNoDuplicateColumnChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func hasDuplicateColumn(keyList []*ast.IndexPartSpecification) (string, bool) {
+ checker := make(map[string]bool)
+ for _, key := range keyList {
+ if key.Expr == nil {
+ if _, exists := checker[key.Column.Name.O]; exists {
+ return key.Column.Name.O, true
+ }
+ checker[key.Column.Name.O] = true
+ }
+ }
+
+ return "", false
+}
+
+func indexTypeString(tp ast.ConstraintType) string {
+ switch tp {
+ case ast.ConstraintPrimaryKey:
+ return "PRIMARY KEY"
+ case ast.ConstraintUniq, ast.ConstraintUniqKey, ast.ConstraintUniqIndex:
+ return "UNIQUE KEY"
+ case ast.ConstraintForeignKey:
+ return "FOREIGN KEY"
+ case ast.ConstraintIndex:
+ return "INDEX"
+ }
+ return "INDEX"
+}
diff --git a/backend/plugin/advisor/tidb/advisor_index_pk_type.go b/backend/plugin/advisor/tidb/advisor_index_pk_type.go
new file mode 100644
index 0000000000..cf5fc0020e
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_index_pk_type.go
@@ -0,0 +1,249 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pingcap/tidb/parser/mysql"
+ "github.com/pingcap/tidb/parser/types"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/catalog"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*IndexPkTypeAdvisor)(nil)
+ _ ast.Visitor = (*indexPkTypeChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLIndexPKType, &IndexPkTypeAdvisor{})
+}
+
+// IndexPkTypeAdvisor is the advisor checking for correct type of PK.
+type IndexPkTypeAdvisor struct {
+}
+
+// Check checks for correct type of PK.
+func (*IndexPkTypeAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &indexPkTypeChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ line: make(map[string]int),
+ catalog: ctx.Catalog,
+ tablesNewColumns: make(map[string]columnNameToColumnDef),
+ }
+
+ for _, stmt := range stmtList {
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type columnNameToColumnDef map[string]*ast.ColumnDef
+type tableNewColumn map[string]columnNameToColumnDef
+
+func (t tableNewColumn) set(tableName string, columnName string, colDef *ast.ColumnDef) {
+ if _, ok := t[tableName]; !ok {
+ t[tableName] = make(map[string]*ast.ColumnDef)
+ }
+ t[tableName][columnName] = colDef
+}
+
+func (t tableNewColumn) get(tableName string, columnName string) (colDef *ast.ColumnDef, ok bool) {
+ if _, ok := t[tableName]; !ok {
+ return nil, false
+ }
+ col, ok := t[tableName][columnName]
+ return col, ok
+}
+
+func (t tableNewColumn) delete(tableName string, columnName string) {
+ if _, ok := t[tableName]; !ok {
+ return
+ }
+ delete(t[tableName], columnName)
+}
+
+type indexPkTypeChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ line map[string]int
+ catalog *catalog.Finder
+ tablesNewColumns tableNewColumn
+}
+
+type pkData struct {
+ table string
+ column string
+ columnType string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (v *indexPkTypeChecker) Enter(in ast.Node) (ast.Node, bool) {
+ var pkDataList []pkData
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ tableName := node.Table.Name.String()
+ for _, column := range node.Cols {
+ pds := v.addNewColumn(tableName, column.OriginTextPosition(), column)
+ pkDataList = append(pkDataList, pds...)
+ }
+ for _, constraint := range node.Constraints {
+ pds := v.addConstraint(tableName, constraint.OriginTextPosition(), constraint)
+ pkDataList = append(pkDataList, pds...)
+ }
+ case *ast.AlterTableStmt:
+ tableName := node.Table.Name.String()
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ pds := v.addNewColumn(tableName, node.OriginTextPosition(), column)
+ pkDataList = append(pkDataList, pds...)
+ }
+ case ast.AlterTableAddConstraint:
+ pds := v.addConstraint(tableName, node.OriginTextPosition(), spec.Constraint)
+ pkDataList = append(pkDataList, pds...)
+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:
+ newColumnDef := spec.NewColumns[0]
+ oldColumnName := newColumnDef.Name.Name.String()
+ if spec.OldColumnName != nil {
+ oldColumnName = spec.OldColumnName.Name.String()
+ }
+ pds := v.changeColumn(tableName, oldColumnName, node.OriginTextPosition(), newColumnDef)
+ pkDataList = append(pkDataList, pds...)
+ }
+ }
+ }
+ for _, pd := range pkDataList {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: v.level,
+ Code: advisor.IndexPKType,
+ Title: v.title,
+ Content: fmt.Sprintf("Columns in primary key must be INT/BIGINT but `%s`.`%s` is %s", pd.table, pd.column, pd.columnType),
+ Line: pd.line,
+ })
+ }
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*indexPkTypeChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func (v *indexPkTypeChecker) addNewColumn(tableName string, line int, colDef *ast.ColumnDef) []pkData {
+ var pkDataList []pkData
+ for _, option := range colDef.Options {
+ if option.Tp == ast.ColumnOptionPrimaryKey {
+ tp := v.getIntOrBigIntStr(colDef.Tp)
+ if tp != "INT" && tp != "BIGINT" {
+ pkDataList = append(pkDataList, pkData{
+ table: tableName,
+ column: colDef.Name.String(),
+ columnType: tp,
+ line: line,
+ })
+ }
+ }
+ }
+ v.tablesNewColumns.set(tableName, colDef.Name.String(), colDef)
+ return pkDataList
+}
+
+func (v *indexPkTypeChecker) changeColumn(tableName, oldColumnName string, line int, newColumnDef *ast.ColumnDef) []pkData {
+ var pkDataList []pkData
+ v.tablesNewColumns.delete(tableName, oldColumnName)
+ for _, option := range newColumnDef.Options {
+ if option.Tp == ast.ColumnOptionPrimaryKey {
+ tp := v.getIntOrBigIntStr(newColumnDef.Tp)
+ if tp != "INT" && tp != "BIGINT" {
+ pkDataList = append(pkDataList, pkData{
+ table: tableName,
+ column: newColumnDef.Name.String(),
+ columnType: tp,
+ line: line,
+ })
+ }
+ }
+ }
+ v.tablesNewColumns.set(tableName, newColumnDef.Name.String(), newColumnDef)
+ return pkDataList
+}
+
+func (v *indexPkTypeChecker) addConstraint(tableName string, line int, constraint *ast.Constraint) []pkData {
+ var pkDataList []pkData
+ if constraint.Tp == ast.ConstraintPrimaryKey {
+ for _, key := range constraint.Keys {
+ columnName := key.Column.Name.String()
+ columnType, err := v.getPKColumnType(tableName, columnName)
+ if err != nil {
+ continue
+ }
+ if columnType != "INT" && columnType != "BIGINT" {
+ pkDataList = append(pkDataList, pkData{
+ table: tableName,
+ column: columnName,
+ columnType: columnType,
+ line: line,
+ })
+ }
+ }
+ }
+ return pkDataList
+}
+
+// getPKColumnType gets the column type string from v.tablesNewColumns or catalog, returns empty string and non-nil error if cannot find the column in given table.
+func (v *indexPkTypeChecker) getPKColumnType(tableName string, columnName string) (string, error) {
+ if colDef, ok := v.tablesNewColumns.get(tableName, columnName); ok {
+ return v.getIntOrBigIntStr(colDef.Tp), nil
+ }
+ column := v.catalog.Origin.FindColumn(&catalog.ColumnFind{
+ TableName: tableName,
+ ColumnName: columnName,
+ })
+ if column != nil {
+ return column.Type(), nil
+ }
+ return "", errors.Errorf("cannot find the type of `%s`.`%s`", tableName, columnName)
+}
+
+// getIntOrBigIntStr returns the type string of tp.
+func (*indexPkTypeChecker) getIntOrBigIntStr(tp *types.FieldType) string {
+ switch tp.GetType() {
+ // https://pkg.go.dev/github.com/pingcap/tidb/parser/mysql#TypeLong
+ case mysql.TypeLong:
+ // tp.String() return int(11)
+ return "INT"
+ // https://pkg.go.dev/github.com/pingcap/tidb/parser/mysql#TypeLonglong
+ case mysql.TypeLonglong:
+ // tp.String() return bigint(20)
+ return "BIGINT"
+ }
+ return tp.String()
+}
diff --git a/backend/plugin/advisor/tidb/advisor_index_primary_key_type_allowlist.go b/backend/plugin/advisor/tidb/advisor_index_primary_key_type_allowlist.go
new file mode 100644
index 0000000000..47d37fedc3
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_index_primary_key_type_allowlist.go
@@ -0,0 +1,214 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/catalog"
+ tidbparser "github.com/bytebase/bytebase/backend/plugin/parser/tidb"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*IndexPrimaryKeyTypeAllowlistAdvisor)(nil)
+ _ ast.Visitor = (*indexPrimaryKeyTypeAllowlistChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLPrimaryKeyTypeAllowlist, &IndexPrimaryKeyTypeAllowlistAdvisor{})
+}
+
+// IndexPrimaryKeyTypeAllowlistAdvisor is the advisor checking for primary key type allowlist.
+type IndexPrimaryKeyTypeAllowlistAdvisor struct {
+}
+
+// Check checks for primary key type allowlist.
+func (*IndexPrimaryKeyTypeAllowlistAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ payload, err := advisor.UnmarshalStringArrayTypeRulePayload(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ allowlist := make(map[string]bool)
+ for _, tp := range payload.List {
+ allowlist[strings.ToLower(tp)] = true
+ }
+ checker := &indexPrimaryKeyTypeAllowlistChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ allowlist: allowlist,
+ catalog: ctx.Catalog,
+ tablesNewColumns: make(map[string]columnNameToColumnDef),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type indexPrimaryKeyTypeAllowlistChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ allowlist map[string]bool
+ catalog *catalog.Finder
+ tablesNewColumns tableNewColumn
+}
+
+// Enter implements the ast.Visitor interface.
+func (v *indexPrimaryKeyTypeAllowlistChecker) Enter(in ast.Node) (ast.Node, bool) {
+ var pkDataList []pkData
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ tableName := node.Table.Name.String()
+ for _, column := range node.Cols {
+ pds := v.addNewColumn(tableName, column.OriginTextPosition(), column)
+ pkDataList = append(pkDataList, pds...)
+ }
+ for _, constraint := range node.Constraints {
+ pds := v.addConstraint(tableName, constraint.OriginTextPosition(), constraint)
+ pkDataList = append(pkDataList, pds...)
+ }
+ case *ast.AlterTableStmt:
+ tableName := node.Table.Name.String()
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ pds := v.addNewColumn(tableName, node.OriginTextPosition(), column)
+ pkDataList = append(pkDataList, pds...)
+ }
+ case ast.AlterTableAddConstraint:
+ pds := v.addConstraint(tableName, node.OriginTextPosition(), spec.Constraint)
+ pkDataList = append(pkDataList, pds...)
+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:
+ newColumnDef := spec.NewColumns[0]
+ oldColumnName := newColumnDef.Name.Name.String()
+ if spec.OldColumnName != nil {
+ oldColumnName = spec.OldColumnName.Name.String()
+ }
+ pds := v.changeColumn(tableName, oldColumnName, node.OriginTextPosition(), newColumnDef)
+ pkDataList = append(pkDataList, pds...)
+ }
+ }
+ }
+ for _, pd := range pkDataList {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: v.level,
+ Code: advisor.IndexPKType,
+ Title: v.title,
+ Content: fmt.Sprintf("The column `%s` in table `%s` is one of the primary key, but its type \"%s\" is not in allowlist", pd.column, pd.table, pd.columnType),
+ Line: pd.line,
+ })
+ }
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*indexPrimaryKeyTypeAllowlistChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func (v *indexPrimaryKeyTypeAllowlistChecker) addNewColumn(tableName string, line int, colDef *ast.ColumnDef) []pkData {
+ var pkDataList []pkData
+ for _, option := range colDef.Options {
+ if option.Tp == ast.ColumnOptionPrimaryKey {
+ tp := tidbparser.TypeString(colDef.Tp.GetType())
+ if _, exists := v.allowlist[strings.ToLower(tp)]; !exists {
+ pkDataList = append(pkDataList, pkData{
+ table: tableName,
+ column: colDef.Name.String(),
+ columnType: tp,
+ line: line,
+ })
+ }
+ }
+ }
+ v.tablesNewColumns.set(tableName, colDef.Name.String(), colDef)
+ return pkDataList
+}
+
+func (v *indexPrimaryKeyTypeAllowlistChecker) changeColumn(tableName, oldColumnName string, line int, newColumnDef *ast.ColumnDef) []pkData {
+ var pkDataList []pkData
+ v.tablesNewColumns.delete(tableName, oldColumnName)
+ for _, option := range newColumnDef.Options {
+ if option.Tp == ast.ColumnOptionPrimaryKey {
+ tp := tidbparser.TypeString(newColumnDef.Tp.GetType())
+ if _, exists := v.allowlist[strings.ToLower(tp)]; !exists {
+ pkDataList = append(pkDataList, pkData{
+ table: tableName,
+ column: newColumnDef.Name.String(),
+ columnType: tp,
+ line: line,
+ })
+ }
+ }
+ }
+ v.tablesNewColumns.set(tableName, newColumnDef.Name.String(), newColumnDef)
+ return pkDataList
+}
+
+func (v *indexPrimaryKeyTypeAllowlistChecker) addConstraint(tableName string, line int, constraint *ast.Constraint) []pkData {
+ var pkDataList []pkData
+ if constraint.Tp == ast.ConstraintPrimaryKey {
+ for _, key := range constraint.Keys {
+ columnName := key.Column.Name.String()
+ columnType, err := v.getPKColumnType(tableName, columnName)
+ if err != nil {
+ continue
+ }
+ if _, exists := v.allowlist[strings.ToLower(columnType)]; !exists {
+ pkDataList = append(pkDataList, pkData{
+ table: tableName,
+ column: columnName,
+ columnType: columnType,
+ line: line,
+ })
+ }
+ }
+ }
+ return pkDataList
+}
+
+// getPKColumnType gets the column type string from v.tablesNewColumns or catalog, returns empty string and non-nil error if cannot find the column in given table.
+func (v *indexPrimaryKeyTypeAllowlistChecker) getPKColumnType(tableName string, columnName string) (string, error) {
+ if colDef, ok := v.tablesNewColumns.get(tableName, columnName); ok {
+ return tidbparser.TypeString(colDef.Tp.GetType()), nil
+ }
+ column := v.catalog.Origin.FindColumn(&catalog.ColumnFind{
+ TableName: tableName,
+ ColumnName: columnName,
+ })
+ if column != nil {
+ return column.Type(), nil
+ }
+ return "", errors.Errorf("cannot find the type of `%s`.`%s`", tableName, columnName)
+}
diff --git a/backend/plugin/advisor/tidb/advisor_index_total_number_limit.go b/backend/plugin/advisor/tidb/advisor_index_total_number_limit.go
new file mode 100644
index 0000000000..19e0e242fd
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_index_total_number_limit.go
@@ -0,0 +1,173 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+ "sort"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/catalog"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*IndexTotalNumberLimitAdvisor)(nil)
+ _ ast.Visitor = (*indexTotalNumberLimitChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLIndexTotalNumberLimit, &IndexTotalNumberLimitAdvisor{})
+}
+
+// IndexTotalNumberLimitAdvisor is the advisor checking for index total number limit.
+type IndexTotalNumberLimitAdvisor struct {
+}
+
+// Check checks for index total number limit.
+func (*IndexTotalNumberLimitAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ payload, err := advisor.UnmarshalNumberTypeRulePayload(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &indexTotalNumberLimitChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ max: payload.Number,
+ lineForTable: make(map[string]int),
+ catalog: ctx.Catalog,
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ return checker.generateAdvice(), nil
+}
+
+type indexTotalNumberLimitChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ max int
+ lineForTable map[string]int
+ catalog *catalog.Finder
+}
+
+func (checker *indexTotalNumberLimitChecker) generateAdvice() []advisor.Advice {
+ type tableName struct {
+ name string
+ line int
+ }
+ var tableList []tableName
+
+ for k, v := range checker.lineForTable {
+ tableList = append(tableList, tableName{
+ name: k,
+ line: v,
+ })
+ }
+ sort.Slice(tableList, func(i, j int) bool {
+ return tableList[i].line < tableList[j].line
+ })
+
+ for _, table := range tableList {
+ tableInfo := checker.catalog.Final.FindTable(&catalog.TableFind{TableName: table.name})
+ if tableInfo != nil && tableInfo.CountIndex() > checker.max {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.IndexCountExceedsLimit,
+ Title: checker.title,
+ Content: fmt.Sprintf("The count of index in table `%s` should be no more than %d, but found %d", table.name, checker.max, tableInfo.CountIndex()),
+ Line: table.line,
+ })
+ }
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *indexTotalNumberLimitChecker) Enter(in ast.Node) (ast.Node, bool) {
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ checker.lineForTable[node.Table.Name.O] = node.OriginTextPosition()
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ if createIndex(column) {
+ checker.lineForTable[node.Table.Name.O] = node.OriginTextPosition()
+ break
+ }
+ }
+ case ast.AlterTableAddConstraint:
+ if createIndex(spec.Constraint) {
+ checker.lineForTable[node.Table.Name.O] = node.OriginTextPosition()
+ }
+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:
+ if createIndex(spec.NewColumns[0]) {
+ checker.lineForTable[node.Table.Name.O] = node.OriginTextPosition()
+ }
+ }
+ }
+ case *ast.CreateIndexStmt:
+ checker.lineForTable[node.Table.Name.O] = node.OriginTextPosition()
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*indexTotalNumberLimitChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func createIndex(in ast.Node) bool {
+ switch node := in.(type) {
+ case *ast.ColumnDef:
+ for _, option := range node.Options {
+ switch option.Tp {
+ case ast.ColumnOptionPrimaryKey, ast.ColumnOptionUniqKey:
+ return true
+ }
+ }
+ case *ast.Constraint:
+ switch node.Tp {
+ case ast.ConstraintPrimaryKey,
+ ast.ConstraintUniq,
+ ast.ConstraintUniqKey,
+ ast.ConstraintUniqIndex,
+ ast.ConstraintKey,
+ ast.ConstraintIndex,
+ ast.ConstraintFulltext:
+ return true
+ }
+ }
+ return false
+}
diff --git a/backend/plugin/advisor/tidb/advisor_index_type_no_blob.go b/backend/plugin/advisor/tidb/advisor_index_type_no_blob.go
new file mode 100644
index 0000000000..650b439291
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_index_type_no_blob.go
@@ -0,0 +1,250 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pingcap/tidb/parser/mysql"
+ "github.com/pingcap/tidb/parser/types"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/catalog"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*IndexTypeNoBlobAdvisor)(nil)
+ _ ast.Visitor = (*indexTypeNoBlobChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLIndexTypeNoBlob, &IndexTypeNoBlobAdvisor{})
+}
+
+// IndexTypeNoBlobAdvisor is the advisor checking for index type no blob.
+type IndexTypeNoBlobAdvisor struct {
+}
+
+// Check checks for index type no blob.
+func (*IndexTypeNoBlobAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &indexTypeNoBlobChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ catalog: ctx.Catalog,
+ tablesNewColumns: make(map[string]columnNameToColumnDef),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type indexTypeNoBlobChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ catalog *catalog.Finder
+ tablesNewColumns tableNewColumn
+}
+
+// Enter implements the ast.Visitor interface.
+func (v *indexTypeNoBlobChecker) Enter(in ast.Node) (ast.Node, bool) {
+ var pkDataList []pkData
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ tableName := node.Table.Name.String()
+ for _, column := range node.Cols {
+ pds := v.addNewColumn(tableName, column.OriginTextPosition(), column)
+ pkDataList = append(pkDataList, pds...)
+ }
+ for _, constraint := range node.Constraints {
+ pds := v.addConstraint(tableName, constraint.OriginTextPosition(), constraint)
+ pkDataList = append(pkDataList, pds...)
+ }
+ case *ast.AlterTableStmt:
+ tableName := node.Table.Name.String()
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ pds := v.addNewColumn(tableName, node.OriginTextPosition(), column)
+ pkDataList = append(pkDataList, pds...)
+ }
+ case ast.AlterTableAddConstraint:
+ pds := v.addConstraint(tableName, node.OriginTextPosition(), spec.Constraint)
+ pkDataList = append(pkDataList, pds...)
+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:
+ newColumnDef := spec.NewColumns[0]
+ oldColumnName := newColumnDef.Name.Name.String()
+ if spec.OldColumnName != nil {
+ oldColumnName = spec.OldColumnName.Name.String()
+ }
+ pds := v.changeColumn(tableName, oldColumnName, node.OriginTextPosition(), newColumnDef)
+ pkDataList = append(pkDataList, pds...)
+ }
+ }
+ case *ast.CreateIndexStmt:
+ tableName := node.Table.Name.String()
+ for _, indexSpec := range node.IndexPartSpecifications {
+ pds := v.addIndex(tableName, node.OriginTextPosition(), indexSpec)
+ pkDataList = append(pkDataList, pds...)
+ }
+ }
+ for _, pd := range pkDataList {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: v.level,
+ Code: advisor.IndexTypeNoBlob,
+ Title: v.title,
+ Content: fmt.Sprintf("Columns in index must not be BLOB but `%s`.`%s` is %s", pd.table, pd.column, pd.columnType),
+ Line: pd.line,
+ })
+ }
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*indexTypeNoBlobChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func (v *indexTypeNoBlobChecker) addNewColumn(tableName string, line int, colDef *ast.ColumnDef) []pkData {
+ var pkDataList []pkData
+ for _, option := range colDef.Options {
+ if option.Tp == ast.ColumnOptionUniqKey {
+ tp := v.getBlobStr(colDef.Tp)
+ if v.isBlob(tp) {
+ pkDataList = append(pkDataList, pkData{
+ table: tableName,
+ column: colDef.Name.String(),
+ columnType: tp,
+ line: line,
+ })
+ }
+ }
+ }
+ v.tablesNewColumns.set(tableName, colDef.Name.String(), colDef)
+ return pkDataList
+}
+
+func (v *indexTypeNoBlobChecker) addIndex(tableName string, line int, indexSpec *ast.IndexPartSpecification) []pkData {
+ var pkDataList []pkData
+ columnName := indexSpec.Column.Name.String()
+ columnType, err := v.getColumnType(tableName, columnName)
+ if err != nil {
+ return nil
+ }
+ if v.isBlob(columnType) {
+ pkDataList = append(pkDataList, pkData{
+ table: tableName,
+ column: columnName,
+ columnType: columnType,
+ line: line,
+ })
+ }
+ return pkDataList
+}
+
+func (v *indexTypeNoBlobChecker) changeColumn(tableName, oldColumnName string, line int, newColumnDef *ast.ColumnDef) []pkData {
+ var pkDataList []pkData
+ v.tablesNewColumns.delete(tableName, oldColumnName)
+ for _, option := range newColumnDef.Options {
+ if option.Tp == ast.ColumnOptionPrimaryKey || option.Tp == ast.ColumnOptionUniqKey {
+ tp := v.getBlobStr(newColumnDef.Tp)
+ if v.isBlob(tp) {
+ pkDataList = append(pkDataList, pkData{
+ table: tableName,
+ column: newColumnDef.Name.String(),
+ columnType: tp,
+ line: line,
+ })
+ }
+ }
+ }
+ v.tablesNewColumns.set(tableName, newColumnDef.Name.String(), newColumnDef)
+ return pkDataList
+}
+
+func (v *indexTypeNoBlobChecker) addConstraint(tableName string, line int, constraint *ast.Constraint) []pkData {
+ var pkDataList []pkData
+ if constraint.Tp == ast.ConstraintPrimaryKey || constraint.Tp == ast.ConstraintUniqKey || constraint.Tp == ast.ConstraintKey ||
+ constraint.Tp == ast.ConstraintIndex || constraint.Tp == ast.ConstraintUniqIndex || constraint.Tp == ast.ConstraintUniq {
+ for _, key := range constraint.Keys {
+ columnName := key.Column.Name.String()
+ columnType, err := v.getColumnType(tableName, columnName)
+ if err != nil {
+ continue
+ }
+ if v.isBlob(columnType) {
+ pkDataList = append(pkDataList, pkData{
+ table: tableName,
+ column: columnName,
+ columnType: columnType,
+ line: line,
+ })
+ }
+ }
+ }
+ return pkDataList
+}
+
+// getPKColumnType gets the column type string from v.tablesNewColumns or catalog, returns empty string and non-nil error if cannot find the column in given table.
+func (v *indexTypeNoBlobChecker) getColumnType(tableName string, columnName string) (string, error) {
+ if colDef, ok := v.tablesNewColumns.get(tableName, columnName); ok {
+ return v.getBlobStr(colDef.Tp), nil
+ }
+ column := v.catalog.Origin.FindColumn(&catalog.ColumnFind{
+ TableName: tableName,
+ ColumnName: columnName,
+ })
+ if column != nil {
+ return column.Type(), nil
+ }
+ return "", errors.Errorf("cannot find the type of `%s`.`%s`", tableName, columnName)
+}
+
+// getIntOrBigIntStr returns the type string of tp.
+func (*indexTypeNoBlobChecker) getBlobStr(tp *types.FieldType) string {
+ switch tp.GetType() {
+ case mysql.TypeTinyBlob:
+ return "tinyblob"
+ case mysql.TypeBlob:
+ return "blob"
+ case mysql.TypeMediumBlob:
+ return "mediumblob"
+ case mysql.TypeLongBlob:
+ return "longblob"
+ }
+ return tp.String()
+}
+
+func (*indexTypeNoBlobChecker) isBlob(tp string) bool {
+ up := strings.ToUpper(tp)
+ return up == "TINYBLOB" || up == "BLOB" || up == "MEDIUMBLOB" || up == "LONGBLOB"
+}
diff --git a/backend/plugin/advisor/tidb/advisor_insert_disallow_order_by_rand.go b/backend/plugin/advisor/tidb/advisor_insert_disallow_order_by_rand.go
new file mode 100644
index 0000000000..05af70d557
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_insert_disallow_order_by_rand.go
@@ -0,0 +1,105 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*InsertDisallowOrderByRandAdvisor)(nil)
+ _ ast.Visitor = (*insertDisallowOrderByRandChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLInsertDisallowOrderByRand, &InsertDisallowOrderByRandAdvisor{})
+}
+
+// InsertDisallowOrderByRandAdvisor is the advisor checking for to disallow order by rand in INSERT statements.
+type InsertDisallowOrderByRandAdvisor struct {
+}
+
+// Check checks for to disallow order by rand in INSERT statements.
+func (*InsertDisallowOrderByRandAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &insertDisallowOrderByRandChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type insertDisallowOrderByRandChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *insertDisallowOrderByRandChecker) Enter(in ast.Node) (ast.Node, bool) {
+ code := advisor.Ok
+ if insert, ok := in.(*ast.InsertStmt); ok {
+ if insert.Select != nil {
+ if selectNode, ok := insert.Select.(*ast.SelectStmt); ok {
+ if selectNode.OrderBy != nil {
+ for _, item := range selectNode.OrderBy.Items {
+ if f, ok := item.Expr.(*ast.FuncCallExpr); ok {
+ if f.FnName.L == ast.Rand {
+ code = advisor.InsertUseOrderByRand
+ break
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if code != advisor.Ok {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: code,
+ Title: checker.title,
+ Content: fmt.Sprintf("\"%s\" uses ORDER BY RAND in the INSERT statement", checker.text),
+ Line: checker.line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*insertDisallowOrderByRandChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_insert_must_specify_column.go b/backend/plugin/advisor/tidb/advisor_insert_must_specify_column.go
new file mode 100644
index 0000000000..cf49d46a63
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_insert_must_specify_column.go
@@ -0,0 +1,89 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*InsertMustSpecifyColumnAdvisor)(nil)
+ _ ast.Visitor = (*insertMustSpecifyColumnChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLInsertMustSpecifyColumn, &InsertMustSpecifyColumnAdvisor{})
+}
+
+// InsertMustSpecifyColumnAdvisor is the advisor checking for to enforce column specified.
+type InsertMustSpecifyColumnAdvisor struct {
+}
+
+// Check checks for to enforce column specified.
+func (*InsertMustSpecifyColumnAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &insertMustSpecifyColumnChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type insertMustSpecifyColumnChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *insertMustSpecifyColumnChecker) Enter(in ast.Node) (ast.Node, bool) {
+ if node, ok := in.(*ast.InsertStmt); ok {
+ if node.Columns == nil {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.InsertNotSpecifyColumn,
+ Title: checker.title,
+ Content: fmt.Sprintf("The INSERT statement must specify columns but \"%s\" does not", checker.text),
+ Line: checker.line,
+ })
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*insertMustSpecifyColumnChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_migration_compatibility.go b/backend/plugin/advisor/tidb/advisor_migration_compatibility.go
new file mode 100644
index 0000000000..2b2f8bb2fd
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_migration_compatibility.go
@@ -0,0 +1,174 @@
+package tidb
+
+import (
+ "fmt"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+
+ "github.com/pingcap/tidb/parser/ast"
+)
+
+var (
+ _ advisor.Advisor = (*CompatibilityAdvisor)(nil)
+ _ ast.Visitor = (*compatibilityChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLMigrationCompatibility, &CompatibilityAdvisor{})
+}
+
+// CompatibilityAdvisor is the advisor checking for schema backward compatibility.
+type CompatibilityAdvisor struct {
+}
+
+// Check checks schema backward compatibility.
+func (*CompatibilityAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ root, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ c := &compatibilityChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+ for _, stmtNode := range root {
+ (stmtNode).Accept(c)
+ }
+
+ if len(c.adviceList) == 0 {
+ c.adviceList = append(c.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return c.adviceList, nil
+}
+
+type compatibilityChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ lastCreateTable string
+}
+
+// Enter implements the ast.Visitor interface.
+func (v *compatibilityChecker) Enter(in ast.Node) (ast.Node, bool) {
+ code := advisor.Ok
+ switch node := in.(type) {
+ // CREATE TABLE
+ case *ast.CreateTableStmt:
+ v.lastCreateTable = node.Table.Name.O
+ // DROP DATABASE
+ case *ast.DropDatabaseStmt:
+ code = advisor.CompatibilityDropDatabase
+ // RENAME TABLE
+ case *ast.RenameTableStmt:
+ code = advisor.CompatibilityRenameTable
+ // DROP TABLE/VIEW
+ case *ast.DropTableStmt:
+ code = advisor.CompatibilityDropTable
+ // ALTER TABLE
+ case *ast.AlterTableStmt:
+ if node.Table.Name.O == v.lastCreateTable {
+ break
+ }
+ for _, spec := range node.Specs {
+ // RENAME COLUMN
+ if spec.Tp == ast.AlterTableRenameColumn {
+ code = advisor.CompatibilityRenameColumn
+ break
+ }
+ // DROP COLUMN
+ if spec.Tp == ast.AlterTableDropColumn {
+ code = advisor.CompatibilityDropColumn
+ break
+ }
+ // RENAME TABLE
+ if spec.Tp == ast.AlterTableRenameTable {
+ code = advisor.CompatibilityRenameTable
+ break
+ }
+
+ if spec.Tp == ast.AlterTableAddConstraint {
+ // ADD PRIMARY KEY
+ if spec.Constraint.Tp == ast.ConstraintPrimaryKey {
+ code = advisor.CompatibilityAddPrimaryKey
+ break
+ }
+ // ADD UNIQUE/UNIQUE KEY/UNIQUE INDEX
+ if spec.Constraint.Tp == ast.ConstraintPrimaryKey ||
+ spec.Constraint.Tp == ast.ConstraintUniq ||
+ spec.Constraint.Tp == ast.ConstraintUniqKey {
+ code = advisor.CompatibilityAddUniqueKey
+ break
+ }
+ // ADD FOREIGN KEY
+ if spec.Constraint.Tp == ast.ConstraintForeignKey {
+ code = advisor.CompatibilityAddForeignKey
+ break
+ }
+ // Check is only supported after 8.0.16 https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html
+ // ADD CHECK ENFORCED
+ if spec.Constraint.Tp == ast.ConstraintCheck && spec.Constraint.Enforced {
+ code = advisor.CompatibilityAddCheck
+ break
+ }
+ }
+
+ // Check is only supported after 8.0.16 https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html
+ // ALTER CHECK ENFORCED
+ if spec.Tp == ast.AlterTableAlterCheck {
+ if spec.Constraint.Enforced {
+ code = advisor.CompatibilityAlterCheck
+ break
+ }
+ }
+
+ // MODIFY COLUMN / CHANGE COLUMN
+ // Due to the limitation that we don't know the current data type of the column before the change,
+ // so we treat all as incompatible. This generates false positive when:
+ // 1. Change to a compatible data type such as INT to BIGINT
+ // 2. Change properties such as comment, change it to NULL
+ if spec.Tp == ast.AlterTableModifyColumn || spec.Tp == ast.AlterTableChangeColumn {
+ code = advisor.CompatibilityAlterColumn
+ break
+ }
+ }
+
+ // ALTER VIEW TBD: https://github.com/pingcap/parser/pull/1252
+ // case *ast.AlterViewStmt:
+
+ // CREATE UNIQUE INDEX
+ case *ast.CreateIndexStmt:
+ if v.lastCreateTable != node.Table.Name.O && node.KeyType == ast.IndexKeyTypeUnique {
+ code = advisor.CompatibilityAddUniqueKey
+ }
+ }
+
+ if code != advisor.Ok {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: v.level,
+ Code: code,
+ Title: v.title,
+ Content: fmt.Sprintf("\"%s\" may cause incompatibility with the existing data and code", in.Text()),
+ Line: in.OriginTextPosition(),
+ })
+ }
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*compatibilityChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_naming_auto_increment_column.go b/backend/plugin/advisor/tidb/advisor_naming_auto_increment_column.go
new file mode 100644
index 0000000000..bb930f164e
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_naming_auto_increment_column.go
@@ -0,0 +1,161 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+ "regexp"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*NamingAutoIncrementColumnAdvisor)(nil)
+ _ ast.Visitor = (*namingAutoIncrementColumnChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLNamingAutoIncrementColumnConvention, &NamingAutoIncrementColumnAdvisor{})
+}
+
+// NamingAutoIncrementColumnAdvisor is the advisor checking for auto-increment naming convention.
+type NamingAutoIncrementColumnAdvisor struct {
+}
+
+// Check checks for auto-increment naming convention.
+func (*NamingAutoIncrementColumnAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ format, maxLength, err := advisor.UnmarshalNamingRulePayloadAsRegexp(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &namingAutoIncrementColumnChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ format: format,
+ maxLength: maxLength,
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type namingAutoIncrementColumnChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ format *regexp.Regexp
+ maxLength int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *namingAutoIncrementColumnChecker) Enter(in ast.Node) (ast.Node, bool) {
+ type columnData struct {
+ name string
+ line int
+ }
+ var columnList []columnData
+ var tableName string
+ switch node := in.(type) {
+ // CREATE TABLE
+ case *ast.CreateTableStmt:
+ tableName = node.Table.Name.O
+ for _, column := range node.Cols {
+ if isAutoIncrement(column) {
+ columnList = append(columnList, columnData{
+ name: column.Name.Name.O,
+ line: column.OriginTextPosition(),
+ })
+ }
+ }
+ // ALTER TABLE
+ case *ast.AlterTableStmt:
+ tableName = node.Table.Name.O
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ // ADD COLUMNS
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ if isAutoIncrement(column) {
+ columnList = append(columnList, columnData{
+ name: column.Name.Name.O,
+ line: in.OriginTextPosition(),
+ })
+ }
+ }
+ // CHANGE COLUMN/MODIFY COLUMN
+ case ast.AlterTableChangeColumn, ast.AlterTableModifyColumn:
+ if isAutoIncrement(spec.NewColumns[0]) {
+ columnList = append(columnList, columnData{
+ name: spec.NewColumns[0].Name.Name.O,
+ line: in.OriginTextPosition(),
+ })
+ }
+ }
+ }
+ }
+
+ for _, column := range columnList {
+ if !checker.format.MatchString(column.name) {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.NamingAutoIncrementColumnConventionMismatch,
+ Title: checker.title,
+ Content: fmt.Sprintf("`%s`.`%s` mismatches auto_increment column naming convention, naming format should be %q", tableName, column.name, checker.format),
+ Line: column.line,
+ })
+ }
+ if checker.maxLength > 0 && len(column.name) > checker.maxLength {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.NamingAutoIncrementColumnConventionMismatch,
+ Title: checker.title,
+ Content: fmt.Sprintf("`%s`.`%s` mismatches auto_increment column naming convention, its length should be within %d characters", tableName, column.name, checker.maxLength),
+ Line: column.line,
+ })
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*namingAutoIncrementColumnChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func isAutoIncrement(column *ast.ColumnDef) bool {
+ for _, option := range column.Options {
+ if option.Tp == ast.ColumnOptionAutoIncrement {
+ return true
+ }
+ }
+ return false
+}
diff --git a/backend/plugin/advisor/tidb/advisor_naming_column.go b/backend/plugin/advisor/tidb/advisor_naming_column.go
new file mode 100644
index 0000000000..40a59d2c2b
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_naming_column.go
@@ -0,0 +1,149 @@
+package tidb
+
+import (
+ "fmt"
+ "regexp"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*NamingColumnConventionAdvisor)(nil)
+ _ ast.Visitor = (*namingColumnConventionChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLNamingColumnConvention, &NamingColumnConventionAdvisor{})
+}
+
+// NamingColumnConventionAdvisor is the advisor checking for column naming convention.
+type NamingColumnConventionAdvisor struct {
+}
+
+// Check checks for column naming convention.
+func (*NamingColumnConventionAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ root, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ format, maxLength, err := advisor.UnmarshalNamingRulePayloadAsRegexp(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &namingColumnConventionChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ format: format,
+ maxLength: maxLength,
+ tables: make(tableState),
+ }
+
+ for _, stmtNode := range root {
+ (stmtNode).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+
+ return checker.adviceList, nil
+}
+
+type namingColumnConventionChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ format *regexp.Regexp
+ maxLength int
+ tables tableState
+}
+
+// Enter implements the ast.Visitor interface.
+func (v *namingColumnConventionChecker) Enter(in ast.Node) (ast.Node, bool) {
+ type columnData struct {
+ name string
+ line int
+ }
+ var columnList []columnData
+ var tableName string
+ switch node := in.(type) {
+ // CREATE TABLE
+ case *ast.CreateTableStmt:
+ tableName = node.Table.Name.O
+ for _, column := range node.Cols {
+ columnList = append(columnList, columnData{
+ name: column.Name.Name.O,
+ line: column.OriginTextPosition(),
+ })
+ }
+ // ALTER TABLE
+ case *ast.AlterTableStmt:
+ tableName = node.Table.Name.O
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ // RENAME COLUMN
+ case ast.AlterTableRenameColumn:
+ columnList = append(columnList, columnData{
+ name: spec.NewColumnName.Name.O,
+ line: in.OriginTextPosition(),
+ })
+ // ADD COLUMNS
+ case ast.AlterTableAddColumns:
+ for _, column := range spec.NewColumns {
+ columnList = append(columnList, columnData{
+ name: column.Name.Name.O,
+ line: in.OriginTextPosition(),
+ })
+ }
+ // CHANGE COLUMN
+ case ast.AlterTableChangeColumn:
+ columnList = append(columnList, columnData{
+ name: spec.NewColumns[0].Name.Name.O,
+ line: in.OriginTextPosition(),
+ })
+ }
+ }
+ }
+
+ for _, column := range columnList {
+ if !v.format.MatchString(column.name) {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: v.level,
+ Code: advisor.NamingColumnConventionMismatch,
+ Title: v.title,
+ Content: fmt.Sprintf("`%s`.`%s` mismatches column naming convention, naming format should be %q", tableName, column.name, v.format),
+ Line: column.line,
+ })
+ }
+ if v.maxLength > 0 && len(column.name) > v.maxLength {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: v.level,
+ Code: advisor.NamingColumnConventionMismatch,
+ Title: v.title,
+ Content: fmt.Sprintf("`%s`.`%s` mismatches column naming convention, its length should be within %d characters", tableName, column.name, v.maxLength),
+ Line: column.line,
+ })
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*namingColumnConventionChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_naming_foreign_key_convention.go b/backend/plugin/advisor/tidb/advisor_naming_foreign_key_convention.go
new file mode 100644
index 0000000000..d5ee46377d
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_naming_foreign_key_convention.go
@@ -0,0 +1,179 @@
+package tidb
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*NamingFKConventionAdvisor)(nil)
+ _ ast.Visitor = (*namingFKConventionChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLNamingFKConvention, &NamingFKConventionAdvisor{})
+}
+
+// NamingFKConventionAdvisor is the advisor checking for foreign key naming convention.
+type NamingFKConventionAdvisor struct {
+}
+
+// Check checks for foreign key naming convention.
+func (*NamingFKConventionAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ root, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ format, templateList, maxLength, err := advisor.UnmarshalNamingRulePayloadAsTemplate(advisor.SQLReviewRuleType(ctx.Rule.Type), ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &namingFKConventionChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ format: format,
+ maxLength: maxLength,
+ templateList: templateList,
+ }
+ for _, stmtNode := range root {
+ (stmtNode).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+
+ return checker.adviceList, nil
+}
+
+type namingFKConventionChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ format string
+ maxLength int
+ templateList []string
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *namingFKConventionChecker) Enter(in ast.Node) (ast.Node, bool) {
+ indexDataList := checker.getMetaDataList(in)
+
+ for _, indexData := range indexDataList {
+ regex, err := getTemplateRegexp(checker.format, checker.templateList, indexData.metaData)
+ if err != nil {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.Internal,
+ Title: "Internal error for foreign key naming convention rule",
+ Content: fmt.Sprintf("%q meet internal error %q", in.Text(), err.Error()),
+ })
+ continue
+ }
+ if !regex.MatchString(indexData.indexName) {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.NamingFKConventionMismatch,
+ Title: checker.title,
+ Content: fmt.Sprintf("Foreign key in table `%s` mismatches the naming convention, expect %q but found `%s`", indexData.tableName, regex, indexData.indexName),
+ Line: indexData.line,
+ })
+ }
+ if checker.maxLength > 0 && len(indexData.indexName) > checker.maxLength {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.NamingFKConventionMismatch,
+ Title: checker.title,
+ Content: fmt.Sprintf("Foreign key `%s` in table `%s` mismatches the naming convention, its length should be within %d characters", indexData.indexName, indexData.tableName, checker.maxLength),
+ Line: indexData.line,
+ })
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*namingFKConventionChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+// getMetaDataList returns the list of foreign key with meta data.
+func (*namingFKConventionChecker) getMetaDataList(in ast.Node) []*indexMetaData {
+ var res []*indexMetaData
+
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, constraint := range node.Constraints {
+ if constraint.Tp == ast.ConstraintForeignKey {
+ var referencingColumnList []string
+ for _, key := range constraint.Keys {
+ referencingColumnList = append(referencingColumnList, key.Column.Name.String())
+ }
+ var referencedColumnList []string
+ for _, spec := range constraint.Refer.IndexPartSpecifications {
+ referencedColumnList = append(referencedColumnList, spec.Column.Name.String())
+ }
+
+ metaData := map[string]string{
+ advisor.ReferencingTableNameTemplateToken: node.Table.Name.String(),
+ advisor.ReferencingColumnNameTemplateToken: strings.Join(referencingColumnList, "_"),
+ advisor.ReferencedTableNameTemplateToken: constraint.Refer.Table.Name.String(),
+ advisor.ReferencedColumnNameTemplateToken: strings.Join(referencedColumnList, "_"),
+ }
+
+ res = append(res, &indexMetaData{
+ indexName: constraint.Name,
+ tableName: node.Table.Name.String(),
+ metaData: metaData,
+ line: constraint.OriginTextPosition(),
+ })
+ }
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ if spec.Tp == ast.AlterTableAddConstraint && spec.Constraint.Tp == ast.ConstraintForeignKey {
+ var referencingColumnList []string
+ for _, key := range spec.Constraint.Keys {
+ referencingColumnList = append(referencingColumnList, key.Column.Name.String())
+ }
+ var referencedColumnList []string
+ for _, spec := range spec.Constraint.Refer.IndexPartSpecifications {
+ referencedColumnList = append(referencedColumnList, spec.Column.Name.String())
+ }
+
+ metaData := map[string]string{
+ advisor.ReferencingTableNameTemplateToken: node.Table.Name.String(),
+ advisor.ReferencingColumnNameTemplateToken: strings.Join(referencingColumnList, "_"),
+ advisor.ReferencedTableNameTemplateToken: spec.Constraint.Refer.Table.Name.String(),
+ advisor.ReferencedColumnNameTemplateToken: strings.Join(referencedColumnList, "_"),
+ }
+ res = append(res, &indexMetaData{
+ indexName: spec.Constraint.Name,
+ tableName: node.Table.Name.String(),
+ metaData: metaData,
+ line: in.OriginTextPosition(),
+ })
+ }
+ }
+ }
+
+ return res
+}
diff --git a/backend/plugin/advisor/tidb/advisor_naming_index_convention.go b/backend/plugin/advisor/tidb/advisor_naming_index_convention.go
new file mode 100644
index 0000000000..feddd81fc4
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_naming_index_convention.go
@@ -0,0 +1,229 @@
+package tidb
+
+import (
+ "fmt"
+ "regexp"
+ "strings"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/catalog"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*NamingIndexConventionAdvisor)(nil)
+ _ ast.Visitor = (*namingIndexConventionChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLNamingIndexConvention, &NamingIndexConventionAdvisor{})
+}
+
+// NamingIndexConventionAdvisor is the advisor checking for index naming convention.
+type NamingIndexConventionAdvisor struct {
+}
+
+// Check checks for index naming convention.
+func (*NamingIndexConventionAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ root, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ format, templateList, maxLength, err := advisor.UnmarshalNamingRulePayloadAsTemplate(advisor.SQLReviewRuleType(ctx.Rule.Type), ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &namingIndexConventionChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ format: format,
+ maxLength: maxLength,
+ templateList: templateList,
+ catalog: ctx.Catalog,
+ }
+ for _, stmtNode := range root {
+ (stmtNode).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+
+ return checker.adviceList, nil
+}
+
+type namingIndexConventionChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ format string
+ maxLength int
+ templateList []string
+ catalog *catalog.Finder
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *namingIndexConventionChecker) Enter(in ast.Node) (ast.Node, bool) {
+ indexDataList := checker.getMetaDataList(in)
+
+ for _, indexData := range indexDataList {
+ regex, err := getTemplateRegexp(checker.format, checker.templateList, indexData.metaData)
+ if err != nil {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.Internal,
+ Title: "Internal error for index naming convention rule",
+ Content: fmt.Sprintf("%q meet internal error %q", in.Text(), err.Error()),
+ })
+ continue
+ }
+ if !regex.MatchString(indexData.indexName) {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.NamingIndexConventionMismatch,
+ Title: checker.title,
+ Content: fmt.Sprintf("Index in table `%s` mismatches the naming convention, expect %q but found `%s`", indexData.tableName, regex, indexData.indexName),
+ Line: indexData.line,
+ })
+ }
+ if checker.maxLength > 0 && len(indexData.indexName) > checker.maxLength {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.NamingIndexConventionMismatch,
+ Title: checker.title,
+ Content: fmt.Sprintf("Index `%s` in table `%s` mismatches the naming convention, its length should be within %d characters", indexData.indexName, indexData.tableName, checker.maxLength),
+ Line: indexData.line,
+ })
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*namingIndexConventionChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+type indexMetaData struct {
+ indexName string
+ tableName string
+ metaData map[string]string
+ line int
+}
+
+// getMetaDataList returns the list of index with meta data.
+func (checker *namingIndexConventionChecker) getMetaDataList(in ast.Node) []*indexMetaData {
+ var res []*indexMetaData
+
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, constraint := range node.Constraints {
+ if constraint.Tp == ast.ConstraintIndex {
+ var columnList []string
+ for _, key := range constraint.Keys {
+ columnList = append(columnList, key.Column.Name.String())
+ }
+ metaData := map[string]string{
+ advisor.ColumnListTemplateToken: strings.Join(columnList, "_"),
+ advisor.TableNameTemplateToken: node.Table.Name.String(),
+ }
+ res = append(res, &indexMetaData{
+ indexName: constraint.Name,
+ tableName: node.Table.Name.String(),
+ metaData: metaData,
+ line: constraint.OriginTextPosition(),
+ })
+ }
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableRenameIndex:
+ _, index := checker.catalog.Origin.FindIndex(&catalog.IndexFind{
+ TableName: node.Table.Name.String(),
+ IndexName: spec.FromKey.String(),
+ })
+ if index == nil {
+ continue
+ }
+ if index.Unique() {
+ // Unique index naming convention should in advisor_naming_unique_key_convention.go
+ continue
+ }
+ metaData := map[string]string{
+ advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList(), "_"),
+ advisor.TableNameTemplateToken: node.Table.Name.String(),
+ }
+ res = append(res, &indexMetaData{
+ indexName: spec.ToKey.String(),
+ tableName: node.Table.Name.String(),
+ metaData: metaData,
+ line: in.OriginTextPosition(),
+ })
+ case ast.AlterTableAddConstraint:
+ if spec.Constraint.Tp == ast.ConstraintIndex {
+ var columnList []string
+ for _, key := range spec.Constraint.Keys {
+ columnList = append(columnList, key.Column.Name.String())
+ }
+
+ metaData := map[string]string{
+ advisor.ColumnListTemplateToken: strings.Join(columnList, "_"),
+ advisor.TableNameTemplateToken: node.Table.Name.String(),
+ }
+ res = append(res, &indexMetaData{
+ indexName: spec.Constraint.Name,
+ tableName: node.Table.Name.String(),
+ metaData: metaData,
+ line: in.OriginTextPosition(),
+ })
+ }
+ }
+ }
+ case *ast.CreateIndexStmt:
+ if node.KeyType != ast.IndexKeyTypeUnique {
+ var columnList []string
+ for _, spec := range node.IndexPartSpecifications {
+ columnList = append(columnList, spec.Column.Name.String())
+ }
+ metaData := map[string]string{
+ advisor.ColumnListTemplateToken: strings.Join(columnList, "_"),
+ advisor.TableNameTemplateToken: node.Table.Name.String(),
+ }
+ res = append(res, &indexMetaData{
+ indexName: node.IndexName,
+ tableName: node.Table.Name.String(),
+ metaData: metaData,
+ line: in.OriginTextPosition(),
+ })
+ }
+ }
+
+ return res
+}
+
+// getTemplateRegexp formats the template as regex.
+func getTemplateRegexp(template string, templateList []string, tokens map[string]string) (*regexp.Regexp, error) {
+ for _, key := range templateList {
+ if token, ok := tokens[key]; ok {
+ template = strings.ReplaceAll(template, key, token)
+ }
+ }
+
+ return regexp.Compile(template)
+}
diff --git a/backend/plugin/advisor/tidb/advisor_naming_unique_key_convention.go b/backend/plugin/advisor/tidb/advisor_naming_unique_key_convention.go
new file mode 100644
index 0000000000..5ad347e4da
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_naming_unique_key_convention.go
@@ -0,0 +1,211 @@
+package tidb
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/catalog"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*NamingUKConventionAdvisor)(nil)
+ _ ast.Visitor = (*namingUKConventionChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLNamingUKConvention, &NamingUKConventionAdvisor{})
+}
+
+// NamingUKConventionAdvisor is the advisor checking for unique key naming convention.
+type NamingUKConventionAdvisor struct {
+}
+
+// Check checks for index naming convention.
+func (*NamingUKConventionAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ root, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ format, templateList, maxLength, err := advisor.UnmarshalNamingRulePayloadAsTemplate(advisor.SQLReviewRuleType(ctx.Rule.Type), ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &namingUKConventionChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ format: format,
+ maxLength: maxLength,
+ templateList: templateList,
+ catalog: ctx.Catalog,
+ }
+ for _, stmtNode := range root {
+ (stmtNode).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type namingUKConventionChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ format string
+ maxLength int
+ templateList []string
+ catalog *catalog.Finder
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *namingUKConventionChecker) Enter(in ast.Node) (ast.Node, bool) {
+ indexDataList := checker.getMetaDataList(in)
+
+ for _, indexData := range indexDataList {
+ regex, err := getTemplateRegexp(checker.format, checker.templateList, indexData.metaData)
+ if err != nil {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.Internal,
+ Title: "Internal error for unique key naming convention rule",
+ Content: fmt.Sprintf("%q meet internal error %q", in.Text(), err.Error()),
+ })
+ continue
+ }
+ if !regex.MatchString(indexData.indexName) {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.NamingUKConventionMismatch,
+ Title: checker.title,
+ Content: fmt.Sprintf("Unique key in table `%s` mismatches the naming convention, expect %q but found `%s`", indexData.tableName, regex, indexData.indexName),
+ Line: indexData.line,
+ })
+ }
+ if checker.maxLength > 0 && len(indexData.indexName) > checker.maxLength {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.NamingUKConventionMismatch,
+ Title: checker.title,
+ Content: fmt.Sprintf("Unique key `%s` in table `%s` mismatches the naming convention, its length should be within %d characters", indexData.indexName, indexData.tableName, checker.maxLength),
+ Line: indexData.line,
+ })
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*namingUKConventionChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+// getMetaDataList returns the list of unique key with meta data.
+func (checker *namingUKConventionChecker) getMetaDataList(in ast.Node) []*indexMetaData {
+ var res []*indexMetaData
+
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, constraint := range node.Constraints {
+ switch constraint.Tp {
+ case ast.ConstraintUniq, ast.ConstraintUniqKey, ast.ConstraintUniqIndex:
+ var columnList []string
+ for _, key := range constraint.Keys {
+ columnList = append(columnList, key.Column.Name.String())
+ }
+ metaData := map[string]string{
+ advisor.ColumnListTemplateToken: strings.Join(columnList, "_"),
+ advisor.TableNameTemplateToken: node.Table.Name.String(),
+ }
+ res = append(res, &indexMetaData{
+ indexName: constraint.Name,
+ tableName: node.Table.Name.String(),
+ metaData: metaData,
+ line: constraint.OriginTextPosition(),
+ })
+ }
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ case ast.AlterTableRenameIndex:
+ _, index := checker.catalog.Origin.FindIndex(&catalog.IndexFind{
+ TableName: node.Table.Name.String(),
+ IndexName: spec.FromKey.String(),
+ })
+ if index == nil {
+ continue
+ }
+ if !index.Unique() {
+ // Index naming convention should in advisor_naming_index_convention.go
+ continue
+ }
+ metaData := map[string]string{
+ advisor.ColumnListTemplateToken: strings.Join(index.ExpressionList(), "_"),
+ advisor.TableNameTemplateToken: node.Table.Name.String(),
+ }
+ res = append(res, &indexMetaData{
+ indexName: spec.ToKey.String(),
+ tableName: node.Table.Name.String(),
+ metaData: metaData,
+ line: in.OriginTextPosition(),
+ })
+ case ast.AlterTableAddConstraint:
+ switch spec.Constraint.Tp {
+ case ast.ConstraintUniq, ast.ConstraintUniqKey, ast.ConstraintUniqIndex:
+ var columnList []string
+ for _, key := range spec.Constraint.Keys {
+ columnList = append(columnList, key.Column.Name.String())
+ }
+
+ metaData := map[string]string{
+ advisor.ColumnListTemplateToken: strings.Join(columnList, "_"),
+ advisor.TableNameTemplateToken: node.Table.Name.String(),
+ }
+ res = append(res, &indexMetaData{
+ indexName: spec.Constraint.Name,
+ tableName: node.Table.Name.String(),
+ metaData: metaData,
+ line: in.OriginTextPosition(),
+ })
+ }
+ }
+ }
+ case *ast.CreateIndexStmt:
+ if node.KeyType == ast.IndexKeyTypeUnique {
+ var columnList []string
+ for _, spec := range node.IndexPartSpecifications {
+ columnList = append(columnList, spec.Column.Name.String())
+ }
+ metaData := map[string]string{
+ advisor.ColumnListTemplateToken: strings.Join(columnList, "_"),
+ advisor.TableNameTemplateToken: node.Table.Name.String(),
+ }
+ res = append(res, &indexMetaData{
+ indexName: node.IndexName,
+ tableName: node.Table.Name.String(),
+ metaData: metaData,
+ line: in.OriginTextPosition(),
+ })
+ }
+ }
+
+ return res
+}
diff --git a/backend/plugin/advisor/tidb/advisor_statement_dml_dry_run.go b/backend/plugin/advisor/tidb/advisor_statement_dml_dry_run.go
new file mode 100644
index 0000000000..4ed69d5c52
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_statement_dml_dry_run.go
@@ -0,0 +1,98 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*StatementDmlDryRunAdvisor)(nil)
+ _ ast.Visitor = (*statementDmlDryRunChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLStatementDMLDryRun, &StatementDmlDryRunAdvisor{})
+}
+
+// StatementDmlDryRunAdvisor is the advisor checking for DML dry run.
+type StatementDmlDryRunAdvisor struct {
+}
+
+// Check checks for DML dry run.
+func (*StatementDmlDryRunAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &statementDmlDryRunChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ driver: ctx.Driver,
+ ctx: ctx.Context,
+ }
+
+ if checker.driver != nil {
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type statementDmlDryRunChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ driver *sql.DB
+ ctx context.Context
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *statementDmlDryRunChecker) Enter(in ast.Node) (ast.Node, bool) {
+ switch node := in.(type) {
+ case *ast.InsertStmt, *ast.UpdateStmt, *ast.DeleteStmt:
+ if _, err := advisor.Query(checker.ctx, checker.driver, fmt.Sprintf("EXPLAIN %s", node.Text())); err != nil {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.StatementDMLDryRunFailed,
+ Title: checker.title,
+ Content: fmt.Sprintf("\"%s\" dry runs failed: %s", node.Text(), err.Error()),
+ Line: checker.line,
+ })
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*statementDmlDryRunChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_statement_merge_alter_table.go b/backend/plugin/advisor/tidb/advisor_statement_merge_alter_table.go
new file mode 100644
index 0000000000..7557de7497
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_statement_merge_alter_table.go
@@ -0,0 +1,131 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+ "sort"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*StatementMergeAlterTableAdvisor)(nil)
+ _ ast.Visitor = (*statementMergeAlterTableChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLMergeAlterTable, &StatementMergeAlterTableAdvisor{})
+}
+
+// StatementMergeAlterTableAdvisor is the advisor checking for merging ALTER TABLE statements.
+type StatementMergeAlterTableAdvisor struct {
+}
+
+// Check checks for merging ALTER TABLE statements.
+func (*StatementMergeAlterTableAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &statementMergeAlterTableChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ tableMap: make(map[string]tableStatement),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ return checker.generateAdvice(), nil
+}
+
+type statementMergeAlterTableChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ tableMap map[string]tableStatement
+}
+
+type tableStatement struct {
+ name string
+ count int
+ lastLine int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *statementMergeAlterTableChecker) Enter(in ast.Node) (ast.Node, bool) {
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ data := tableStatement{
+ name: node.Table.Name.O,
+ count: 1,
+ lastLine: checker.line,
+ }
+ checker.tableMap[node.Table.Name.O] = data
+ case *ast.AlterTableStmt:
+ data, ok := checker.tableMap[node.Table.Name.O]
+ if !ok {
+ data = tableStatement{
+ name: node.Table.Name.O,
+ count: 0,
+ }
+ }
+ data.count++
+ data.lastLine = checker.line
+ checker.tableMap[node.Table.Name.O] = data
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*statementMergeAlterTableChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func (checker *statementMergeAlterTableChecker) generateAdvice() []advisor.Advice {
+ var tableList []tableStatement
+ for _, table := range checker.tableMap {
+ tableList = append(tableList, table)
+ }
+ sort.Slice(tableList, func(i, j int) bool {
+ return tableList[i].lastLine < tableList[j].lastLine
+ })
+
+ for _, table := range tableList {
+ if table.count > 1 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.StatementRedundantAlterTable,
+ Title: checker.title,
+ Content: fmt.Sprintf("There are %d statements to modify table `%s`", table.count, table.name),
+ Line: table.lastLine,
+ })
+ }
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList
+}
diff --git a/backend/plugin/advisor/tidb/advisor_stmt_disallow_commit.go b/backend/plugin/advisor/tidb/advisor_stmt_disallow_commit.go
new file mode 100644
index 0000000000..360432fdee
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_stmt_disallow_commit.go
@@ -0,0 +1,87 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*StatementDisallowCommitAdvisor)(nil)
+ _ ast.Visitor = (*statementDisallowCommitChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLStatementDisallowCommit, &StatementDisallowCommitAdvisor{})
+}
+
+// StatementDisallowCommitAdvisor is the advisor checking for index type no blob.
+type StatementDisallowCommitAdvisor struct {
+}
+
+// Check checks for index type no blob.
+func (*StatementDisallowCommitAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &statementDisallowCommitChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type statementDisallowCommitChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (c *statementDisallowCommitChecker) Enter(in ast.Node) (ast.Node, bool) {
+ if _, ok := in.(*ast.CommitStmt); ok {
+ c.adviceList = append(c.adviceList, advisor.Advice{
+ Status: c.level,
+ Code: advisor.StatementDisallowCommit,
+ Title: c.title,
+ Content: fmt.Sprintf("Commit is not allowed, related statement: \"%s\"", c.text),
+ Line: c.line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*statementDisallowCommitChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_stmt_disallow_limit.go b/backend/plugin/advisor/tidb/advisor_stmt_disallow_limit.go
new file mode 100644
index 0000000000..1fc00865d9
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_stmt_disallow_limit.go
@@ -0,0 +1,115 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*DisallowLimitAdvisor)(nil)
+ _ ast.Visitor = (*disallowLimitChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLDisallowLimit, &DisallowLimitAdvisor{})
+}
+
+// DisallowLimitAdvisor is the advisor checking for no LIMIT clause in INSERT/UPDATE statement.
+type DisallowLimitAdvisor struct {
+}
+
+// Check checks for no LIMIT clause in INSERT/UPDATE statement.
+func (*DisallowLimitAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &disallowLimitChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type disallowLimitChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *disallowLimitChecker) Enter(in ast.Node) (ast.Node, bool) {
+ code := advisor.Ok
+ switch node := in.(type) {
+ case *ast.UpdateStmt:
+ if node.Limit != nil {
+ code = advisor.UpdateUseLimit
+ }
+ case *ast.DeleteStmt:
+ if node.Limit != nil {
+ code = advisor.DeleteUseLimit
+ }
+ case *ast.InsertStmt:
+ if useLimit(node) {
+ code = advisor.InsertUseLimit
+ }
+ }
+
+ if code != advisor.Ok {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: code,
+ Title: checker.title,
+ Content: fmt.Sprintf("LIMIT clause is forbidden in INSERT, UPDATE and DELETE statement, but \"%s\" uses", checker.text),
+ Line: checker.line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*disallowLimitChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func useLimit(node *ast.InsertStmt) bool {
+ if node.Select != nil {
+ switch stmt := node.Select.(type) {
+ case *ast.SelectStmt:
+ return stmt.Limit != nil
+ case *ast.SetOprStmt:
+ return stmt.Limit != nil
+ }
+ }
+ return false
+}
diff --git a/backend/plugin/advisor/tidb/advisor_stmt_disallow_order_by.go b/backend/plugin/advisor/tidb/advisor_stmt_disallow_order_by.go
new file mode 100644
index 0000000000..3e76713482
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_stmt_disallow_order_by.go
@@ -0,0 +1,98 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*DisallowOrderByAdvisor)(nil)
+ _ ast.Visitor = (*disallowOrderByChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLDisallowOrderBy, &DisallowOrderByAdvisor{})
+}
+
+// DisallowOrderByAdvisor is the advisor checking for no ORDER BY clause in DELETE/UPDATE statements.
+type DisallowOrderByAdvisor struct {
+}
+
+// Check checks for no ORDER BY clause in DELETE/UPDATE statements.
+func (*DisallowOrderByAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &disallowOrderByChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type disallowOrderByChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *disallowOrderByChecker) Enter(in ast.Node) (ast.Node, bool) {
+ code := advisor.Ok
+ switch node := in.(type) {
+ case *ast.UpdateStmt:
+ if node.Order != nil {
+ code = advisor.UpdateUseOrderBy
+ }
+ case *ast.DeleteStmt:
+ if node.Order != nil {
+ code = advisor.DeleteUseOrderBy
+ }
+ }
+
+ if code != advisor.Ok {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: code,
+ Title: checker.title,
+ Content: fmt.Sprintf("ORDER BY clause is forbidden in DELETE and UPDATE statements, but \"%s\" uses", checker.text),
+ Line: checker.line,
+ })
+ }
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*disallowOrderByChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_stmt_no_leading_wildcard_like.go b/backend/plugin/advisor/tidb/advisor_stmt_no_leading_wildcard_like.go
new file mode 100644
index 0000000000..b8f10c6f05
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_stmt_no_leading_wildcard_like.go
@@ -0,0 +1,100 @@
+package tidb
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pingcap/tidb/parser/format"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+const (
+ wildcard string = "%"
+)
+
+var (
+ _ advisor.Advisor = (*NoLeadingWildcardLikeAdvisor)(nil)
+ _ ast.Visitor = (*noLeadingWildcardLikeChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLNoLeadingWildcardLike, &NoLeadingWildcardLikeAdvisor{})
+}
+
+// NoLeadingWildcardLikeAdvisor is the advisor checking for no leading wildcard LIKE.
+type NoLeadingWildcardLikeAdvisor struct {
+}
+
+// Check checks for no leading wildcard LIKE.
+func (*NoLeadingWildcardLikeAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ root, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ checker := &noLeadingWildcardLikeChecker{level: level}
+ for _, stmtNode := range root {
+ checker.text = stmtNode.Text()
+ checker.leadingWildcardLike = false
+ (stmtNode).Accept(checker)
+
+ if checker.leadingWildcardLike {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.StatementLeadingWildcardLike,
+ Title: string(ctx.Rule.Type),
+ Content: fmt.Sprintf("\"%s\" uses leading wildcard LIKE", checker.text),
+ Line: stmtNode.OriginTextPosition(),
+ })
+ }
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type noLeadingWildcardLikeChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ text string
+ leadingWildcardLike bool
+}
+
+// Enter implements the ast.Visitor interface.
+func (v *noLeadingWildcardLikeChecker) Enter(in ast.Node) (ast.Node, bool) {
+ if node, ok := in.(*ast.PatternLikeExpr); !v.leadingWildcardLike && ok {
+ pattern, err := restoreNode(node.Pattern, format.RestoreStringWithoutCharset)
+ if err != nil {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: v.level,
+ Code: advisor.Internal,
+ Title: "Internal error for no leading wildcard LIKE rule",
+ Content: fmt.Sprintf("\"%s\" meet internal error %q", v.text, err.Error()),
+ })
+ }
+ if len(pattern) > 0 && pattern[:1] == wildcard {
+ v.leadingWildcardLike = true
+ }
+ }
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*noLeadingWildcardLikeChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_stmt_no_select_all.go b/backend/plugin/advisor/tidb/advisor_stmt_no_select_all.go
new file mode 100644
index 0000000000..01cf78be5a
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_stmt_no_select_all.go
@@ -0,0 +1,88 @@
+package tidb
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*NoSelectAllAdvisor)(nil)
+ _ ast.Visitor = (*noSelectAllChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLNoSelectAll, &NoSelectAllAdvisor{})
+}
+
+// NoSelectAllAdvisor is the advisor checking for no "select *".
+type NoSelectAllAdvisor struct {
+}
+
+// Check checks for no "select *".
+func (*NoSelectAllAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ root, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &noSelectAllChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+ for _, stmtNode := range root {
+ checker.text = stmtNode.Text()
+ checker.line = stmtNode.OriginTextPosition()
+ (stmtNode).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type noSelectAllChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (v *noSelectAllChecker) Enter(in ast.Node) (ast.Node, bool) {
+ if node, ok := in.(*ast.SelectStmt); ok {
+ for _, field := range node.Fields.Fields {
+ if field.WildCard != nil {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: v.level,
+ Code: advisor.StatementSelectAll,
+ Title: v.title,
+ Content: fmt.Sprintf("\"%s\" uses SELECT all", v.text),
+ Line: v.line,
+ })
+ break
+ }
+ }
+ }
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*noSelectAllChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_stmt_where_required.go b/backend/plugin/advisor/tidb/advisor_stmt_where_required.go
new file mode 100644
index 0000000000..bd8a6b8d57
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_stmt_where_required.go
@@ -0,0 +1,103 @@
+package tidb
+
+import (
+ "fmt"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+
+ "github.com/pingcap/tidb/parser/ast"
+)
+
+var (
+ _ advisor.Advisor = (*WhereRequirementAdvisor)(nil)
+ _ ast.Visitor = (*whereRequirementChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLWhereRequirement, &WhereRequirementAdvisor{})
+}
+
+// WhereRequirementAdvisor is the advisor checking for the WHERE clause requirement.
+type WhereRequirementAdvisor struct {
+}
+
+// Check checks for the WHERE clause requirement.
+func (*WhereRequirementAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ root, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &whereRequirementChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+ for _, stmtNode := range root {
+ checker.text = stmtNode.Text()
+ checker.line = stmtNode.OriginTextPosition()
+ (stmtNode).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type whereRequirementChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (v *whereRequirementChecker) Enter(in ast.Node) (ast.Node, bool) {
+ code := advisor.Ok
+ switch node := in.(type) {
+ // DELETE
+ case *ast.DeleteStmt:
+ if node.Where == nil {
+ code = advisor.StatementNoWhere
+ }
+ // UPDATE
+ case *ast.UpdateStmt:
+ if node.Where == nil {
+ code = advisor.StatementNoWhere
+ }
+ // SELECT
+ case *ast.SelectStmt:
+ if node.Where == nil {
+ code = advisor.StatementNoWhere
+ }
+ }
+
+ if code != advisor.Ok {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: v.level,
+ Code: code,
+ Title: v.title,
+ Content: fmt.Sprintf("\"%s\" requires WHERE clause", v.text),
+ Line: v.line,
+ })
+ }
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*whereRequirementChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_table_comment_convention.go b/backend/plugin/advisor/tidb/advisor_table_comment_convention.go
new file mode 100644
index 0000000000..c97203092f
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_table_comment_convention.go
@@ -0,0 +1,117 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*TableCommentConventionAdvisor)(nil)
+ _ ast.Visitor = (*tableCommentConventionChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLTableCommentConvention, &TableCommentConventionAdvisor{})
+}
+
+// TableCommentConventionAdvisor is the advisor checking for table comment convention.
+type TableCommentConventionAdvisor struct {
+}
+
+// Check checks for table comment convention.
+func (*TableCommentConventionAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ payload, err := advisor.UnmarshalCommentConventionRulePayload(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+ checker := &tableCommentConventionChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ required: payload.Required,
+ maxLength: payload.MaxLength,
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type tableCommentConventionChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+ required bool
+ maxLength int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *tableCommentConventionChecker) Enter(in ast.Node) (ast.Node, bool) {
+ if node, ok := in.(*ast.CreateTableStmt); ok {
+ exist, comment := tableComment(node.Options)
+ if checker.required && !exist {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.NoTableComment,
+ Title: checker.title,
+ Content: fmt.Sprintf("Table `%s` requires comments", node.Table.Name.O),
+ Line: checker.line,
+ })
+ }
+ if checker.maxLength >= 0 && len(comment) > checker.maxLength {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.TableCommentTooLong,
+ Title: checker.title,
+ Content: fmt.Sprintf("The length of table `%s` comment should be within %d characters", node.Table.Name.O, checker.maxLength),
+ Line: checker.line,
+ })
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*tableCommentConventionChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func tableComment(options []*ast.TableOption) (bool, string) {
+ for _, option := range options {
+ if option.Tp == ast.TableOptionComment {
+ return true, option.StrValue
+ }
+ }
+
+ return false, ""
+}
diff --git a/backend/plugin/advisor/tidb/advisor_table_disallow_partition.go b/backend/plugin/advisor/tidb/advisor_table_disallow_partition.go
new file mode 100644
index 0000000000..a1c83ee36c
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_table_disallow_partition.go
@@ -0,0 +1,102 @@
+package tidb
+
+// Framework code is generated by the generator.
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*TableDisallowPartitionAdvisor)(nil)
+ _ ast.Visitor = (*tableDisallowPartitionChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLTableDisallowPartition, &TableDisallowPartitionAdvisor{})
+}
+
+// TableDisallowPartitionAdvisor is the advisor checking for disallow table partition.
+type TableDisallowPartitionAdvisor struct {
+}
+
+// Check checks for disallow table partition.
+func (*TableDisallowPartitionAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ stmtList, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &tableDisallowPartitionChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+
+ for _, stmt := range stmtList {
+ checker.text = stmt.Text()
+ checker.line = stmt.OriginTextPosition()
+ (stmt).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type tableDisallowPartitionChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ text string
+ line int
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *tableDisallowPartitionChecker) Enter(in ast.Node) (ast.Node, bool) {
+ code := advisor.Ok
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ if node.Partition != nil {
+ code = advisor.CreateTablePartition
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ if spec.Tp == ast.AlterTablePartition {
+ code = advisor.CreateTablePartition
+ break
+ }
+ }
+ }
+
+ if code != advisor.Ok {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: code,
+ Title: checker.title,
+ Content: fmt.Sprintf("Table partition is forbidden, but \"%s\" creates", checker.text),
+ Line: checker.line,
+ })
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*tableDisallowPartitionChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_table_drop_naming_convention.go b/backend/plugin/advisor/tidb/advisor_table_drop_naming_convention.go
new file mode 100644
index 0000000000..dc61b998f3
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_table_drop_naming_convention.go
@@ -0,0 +1,92 @@
+package tidb
+
+import (
+ "fmt"
+ "regexp"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*TableDropNamingConventionAdvisor)(nil)
+ _ ast.Visitor = (*namingDropTableConventionChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLTableDropNamingConvention, &TableDropNamingConventionAdvisor{})
+}
+
+// TableDropNamingConventionAdvisor is the advisor checking the MySQLTableDropNamingConvention rule.
+type TableDropNamingConventionAdvisor struct {
+}
+
+// Check checks for drop table naming convention.
+func (*TableDropNamingConventionAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ root, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ format, _, err := advisor.UnmarshalNamingRulePayloadAsRegexp(ctx.Rule.Payload)
+ if err != nil {
+ return nil, err
+ }
+
+ checker := &namingDropTableConventionChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ format: format,
+ }
+ for _, stmtNode := range root {
+ (stmtNode).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return checker.adviceList, nil
+}
+
+type namingDropTableConventionChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ format *regexp.Regexp
+}
+
+// Enter implements the ast.Visitor interface.
+func (v *namingDropTableConventionChecker) Enter(in ast.Node) (ast.Node, bool) {
+ if node, ok := in.(*ast.DropTableStmt); ok {
+ for _, table := range node.Tables {
+ if !v.format.MatchString(table.Name.O) {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: v.level,
+ Code: advisor.TableDropNamingConventionMismatch,
+ Title: v.title,
+ Content: fmt.Sprintf("`%s` mismatches drop table naming convention, naming format should be %q", table.Name.O, v.format),
+ Line: node.OriginTextPosition(),
+ })
+ }
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*namingDropTableConventionChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_table_no_fk.go b/backend/plugin/advisor/tidb/advisor_table_no_fk.go
new file mode 100644
index 0000000000..16e3f99c0a
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_table_no_fk.go
@@ -0,0 +1,98 @@
+package tidb
+
+import (
+ "fmt"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+var (
+ _ advisor.Advisor = (*TableNoFKAdvisor)(nil)
+ _ ast.Visitor = (*tableNoFKChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLTableNoFK, &TableNoFKAdvisor{})
+}
+
+// TableNoFKAdvisor is the advisor checking table disallow foreign key.
+type TableNoFKAdvisor struct {
+}
+
+// Check checks table disallow foreign key.
+func (*TableNoFKAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ root, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+
+ checker := &tableNoFKChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ }
+ for _, stmtNode := range root {
+ (stmtNode).Accept(checker)
+ }
+
+ if len(checker.adviceList) == 0 {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+
+ return checker.adviceList, nil
+}
+
+type tableNoFKChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+}
+
+// Enter implements the ast.Visitor interface.
+func (checker *tableNoFKChecker) Enter(in ast.Node) (ast.Node, bool) {
+ switch node := in.(type) {
+ case *ast.CreateTableStmt:
+ for _, constraint := range node.Constraints {
+ if constraint.Tp == ast.ConstraintForeignKey {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.TableHasFK,
+ Title: checker.title,
+ Content: fmt.Sprintf("Foreign key is not allowed in the table `%s`", node.Table.Name),
+ Line: constraint.OriginTextPosition(),
+ })
+ }
+ }
+ case *ast.AlterTableStmt:
+ for _, spec := range node.Specs {
+ if spec.Tp == ast.AlterTableAddConstraint && spec.Constraint.Tp == ast.ConstraintForeignKey {
+ checker.adviceList = append(checker.adviceList, advisor.Advice{
+ Status: checker.level,
+ Code: advisor.TableHasFK,
+ Title: checker.title,
+ Content: fmt.Sprintf("Foreign key is not allowed in the table `%s`", node.Table.Name),
+ Line: in.OriginTextPosition(),
+ })
+ }
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*tableNoFKChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
diff --git a/backend/plugin/advisor/tidb/advisor_table_require_pk.go b/backend/plugin/advisor/tidb/advisor_table_require_pk.go
new file mode 100644
index 0000000000..e34fe19b6f
--- /dev/null
+++ b/backend/plugin/advisor/tidb/advisor_table_require_pk.go
@@ -0,0 +1,214 @@
+package tidb
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/plugin/advisor"
+ "github.com/bytebase/bytebase/backend/plugin/advisor/catalog"
+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"
+)
+
+const (
+ primaryKeyName = "PRIMARY"
+)
+
+var (
+ _ advisor.Advisor = (*TableRequirePKAdvisor)(nil)
+ _ ast.Visitor = (*tableRequirePKChecker)(nil)
+)
+
+func init() {
+ advisor.Register(storepb.Engine_TIDB, advisor.MySQLTableRequirePK, &TableRequirePKAdvisor{})
+}
+
+// TableRequirePKAdvisor is the advisor checking table requires PK.
+type TableRequirePKAdvisor struct {
+}
+
+// Check checks table requires PK.
+func (*TableRequirePKAdvisor) Check(ctx advisor.Context, _ string) ([]advisor.Advice, error) {
+ root, ok := ctx.AST.([]ast.StmtNode)
+ if !ok {
+ return nil, errors.Errorf("failed to convert to StmtNode")
+ }
+
+ level, err := advisor.NewStatusBySQLReviewRuleLevel(ctx.Rule.Level)
+ if err != nil {
+ return nil, err
+ }
+ checker := &tableRequirePKChecker{
+ level: level,
+ title: string(ctx.Rule.Type),
+ tables: make(tablePK),
+ line: make(map[string]int),
+ catalog: ctx.Catalog,
+ }
+
+ for _, stmtNode := range root {
+ (stmtNode).Accept(checker)
+ }
+
+ return checker.generateAdviceList(), nil
+}
+
+type tableRequirePKChecker struct {
+ adviceList []advisor.Advice
+ level advisor.Status
+ title string
+ tables tablePK
+ line map[string]int
+ catalog *catalog.Finder
+}
+
+// Enter implements the ast.Visitor interface.
+func (v *tableRequirePKChecker) Enter(in ast.Node) (ast.Node, bool) {
+ switch node := in.(type) {
+ // CREATE TABLE
+ case *ast.CreateTableStmt:
+ v.createTable(node)
+ v.line[node.Table.Name.O] = node.OriginTextPosition()
+ // DROP TABLE
+ case *ast.DropTableStmt:
+ for _, table := range node.Tables {
+ delete(v.tables, table.Name.String())
+ }
+ // ALTER TABLE
+ case *ast.AlterTableStmt:
+ tableName := node.Table.Name.O
+ for _, spec := range node.Specs {
+ switch spec.Tp {
+ // ADD CONSTRAINT
+ case ast.AlterTableAddConstraint:
+ if spec.Constraint.Tp == ast.ConstraintPrimaryKey {
+ v.tables[tableName] = newColumnSet(convertConstraintToKeySlice(spec.Constraint))
+ }
+ // DROP PRIMARY KEY
+ case ast.AlterTableDropPrimaryKey:
+ v.initEmptyTable(tableName)
+ v.line[tableName] = node.OriginTextPosition()
+ // DROP INDEX
+ case ast.AlterTableDropIndex:
+ if strings.ToUpper(spec.Name) == primaryKeyName {
+ v.initEmptyTable(tableName)
+ v.line[tableName] = node.OriginTextPosition()
+ }
+ // ADD COLUMNS
+ case ast.AlterTableAddColumns:
+ v.addPKIfExistByCols(tableName, spec.NewColumns)
+ // CHANGE COLUMN
+ case ast.AlterTableChangeColumn:
+ if v.changeColumn(tableName, spec.OldColumnName.Name.String(), spec.NewColumns[0].Name.Name.String()) {
+ v.line[tableName] = node.OriginTextPosition()
+ }
+ v.addPKIfExistByCols(tableName, spec.NewColumns[:1])
+ // MODIFY COLUMN
+ case ast.AlterTableModifyColumn:
+ v.addPKIfExistByCols(tableName, spec.NewColumns[:1])
+ // DROP COLUMN
+ case ast.AlterTableDropColumn:
+ if v.dropColumn(tableName, spec.OldColumnName.Name.String()) {
+ v.line[tableName] = node.OriginTextPosition()
+ }
+ }
+ }
+ }
+
+ return in, false
+}
+
+// Leave implements the ast.Visitor interface.
+func (*tableRequirePKChecker) Leave(in ast.Node) (ast.Node, bool) {
+ return in, true
+}
+
+func (v *tableRequirePKChecker) generateAdviceList() []advisor.Advice {
+ tableList := v.tables.tableList()
+ for _, tableName := range tableList {
+ if len(v.tables[tableName]) == 0 {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: v.level,
+ Code: advisor.TableNoPK,
+ Title: v.title,
+ Content: fmt.Sprintf("Table `%s` requires PRIMARY KEY", tableName),
+ Line: v.line[tableName],
+ })
+ }
+ }
+
+ if len(v.adviceList) == 0 {
+ v.adviceList = append(v.adviceList, advisor.Advice{
+ Status: advisor.Success,
+ Code: advisor.Ok,
+ Title: "OK",
+ Content: "",
+ })
+ }
+ return v.adviceList
+}
+
+func (v *tableRequirePKChecker) initEmptyTable(name string) columnSet {
+ v.tables[name] = make(columnSet)
+ return v.tables[name]
+}
+
+func (v *tableRequirePKChecker) createTable(node *ast.CreateTableStmt) {
+ table := node.Table.Name.String()
+ v.initEmptyTable(table)
+ v.addPKIfExistByCols(table, node.Cols)
+
+ for _, constraint := range node.Constraints {
+ if constraint.Tp == ast.ConstraintPrimaryKey {
+ v.tables[table] = newColumnSet(convertConstraintToKeySlice(constraint))
+ }
+ }
+}
+
+func (v *tableRequirePKChecker) dropColumn(table string, column string) bool {
+ if _, ok := v.tables[table]; !ok {
+ _, pk := v.catalog.Origin.FindIndex(&catalog.IndexFind{
+ TableName: table,
+ IndexName: primaryKeyName,
+ })
+ if pk == nil {
+ return false
+ }
+ v.tables[table] = newColumnSet(pk.ExpressionList())
+ }
+
+ pk := v.tables[table]
+ _, columnInPK := pk[column]
+ delete(v.tables[table], column)
+ return columnInPK
+}
+
+func (v *tableRequirePKChecker) changeColumn(table string, oldColumn string, newColumn string) bool {
+ if v.dropColumn(table, oldColumn) {
+ pk := v.tables[table]
+ pk[newColumn] = true
+ return true
+ }
+ return false
+}
+
+func (v *tableRequirePKChecker) addPKIfExistByCols(table string, columns []*ast.ColumnDef) {
+ for _, column := range columns {
+ for _, option := range column.Options {
+ if option.Tp == ast.ColumnOptionPrimaryKey {
+ v.tables[table] = newColumnSet([]string{column.Name.Name.String()})
+ return
+ }
+ }
+ }
+}
+
+func convertConstraintToKeySlice(constraint *ast.Constraint) []string {
+ var columns []string
+ for _, key := range constraint.Keys {
+ columns = append(columns, key.Column.Name.String())
+ }
+ return columns
+}
diff --git a/backend/plugin/advisor/tidb/test/column_auto_increment_initial_value.yaml b/backend/plugin/advisor/tidb/test/column_auto_increment_initial_value.yaml
new file mode 100644
index 0000000000..c84eb6f231
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/column_auto_increment_initial_value.yaml
@@ -0,0 +1,24 @@
+- statement: CREATE TABLE t(a int)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(a int auto_increment) auto_increment = 20
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(a int auto_increment) auto_increment = 2
+ want:
+ - status: WARN
+ code: 416
+ title: column.auto-increment-initial-value
+ content: The initial auto-increment value in table `t` is 2, which doesn't equal 20
+ line: 2
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/column_auto_increment_must_integer.yaml b/backend/plugin/advisor/tidb/test/column_auto_increment_must_integer.yaml
new file mode 100644
index 0000000000..d23d0b34d5
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/column_auto_increment_must_integer.yaml
@@ -0,0 +1,46 @@
+- statement: CREATE TABLE t(a INT AUTO_INCREMENT)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(a varchar(255) AUTO_INCREMENT)
+ want:
+ - status: WARN
+ code: 410
+ title: column.auto-increment-must-integer
+ content: Auto-increment column `t`.`a` requires integer type
+ line: 2
+ details: ""
+- statement: |-
+ CREATE TABLE t(b int);
+ ALTER TABLE t ADD COLUMN a varchar(255) AUTO_INCREMENT
+ want:
+ - status: WARN
+ code: 410
+ title: column.auto-increment-must-integer
+ content: Auto-increment column `t`.`a` requires integer type
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t MODIFY COLUMN a varchar(255) AUTO_INCREMENT
+ want:
+ - status: WARN
+ code: 410
+ title: column.auto-increment-must-integer
+ content: Auto-increment column `t`.`a` requires integer type
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(b int);
+ ALTER TABLE t CHANGE COLUMN b a varchar(255) AUTO_INCREMENT
+ want:
+ - status: WARN
+ code: 410
+ title: column.auto-increment-must-integer
+ content: Auto-increment column `t`.`a` requires integer type
+ line: 3
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/column_auto_increment_must_unsigned.yaml b/backend/plugin/advisor/tidb/test/column_auto_increment_must_unsigned.yaml
new file mode 100644
index 0000000000..7c72ff8355
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/column_auto_increment_must_unsigned.yaml
@@ -0,0 +1,46 @@
+- statement: CREATE TABLE t(a INT UNSIGNED AUTO_INCREMENT)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(a INT AUTO_INCREMENT)
+ want:
+ - status: WARN
+ code: 417
+ title: column.auto-increment-must-unsigned
+ content: Auto-increment column `t`.`a` is not UNSIGNED type
+ line: 2
+ details: ""
+- statement: |-
+ CREATE TABLE t(b int);
+ ALTER TABLE t ADD COLUMN a INT AUTO_INCREMENT
+ want:
+ - status: WARN
+ code: 417
+ title: column.auto-increment-must-unsigned
+ content: Auto-increment column `t`.`a` is not UNSIGNED type
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t MODIFY COLUMN a INT AUTO_INCREMENT
+ want:
+ - status: WARN
+ code: 417
+ title: column.auto-increment-must-unsigned
+ content: Auto-increment column `t`.`a` is not UNSIGNED type
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(b int);
+ ALTER TABLE t CHANGE COLUMN b a INT AUTO_INCREMENT
+ want:
+ - status: WARN
+ code: 417
+ title: column.auto-increment-must-unsigned
+ content: Auto-increment column `t`.`a` is not UNSIGNED type
+ line: 3
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/column_comment.yaml b/backend/plugin/advisor/tidb/test/column_comment.yaml
new file mode 100644
index 0000000000..1e764ba49f
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/column_comment.yaml
@@ -0,0 +1,90 @@
+- statement: CREATE TABLE t(a int COMMENT 'comments')
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(
+ a int COMMENT 'some comments',
+ b int,
+ c int)
+ want:
+ - status: WARN
+ code: 409
+ title: column.comment
+ content: The length of column `t`.`a` comment should be within 10 characters
+ line: 2
+ details: ""
+ - status: WARN
+ code: 408
+ title: column.comment
+ content: Column `t`.`b` requires comments
+ line: 3
+ details: ""
+ - status: WARN
+ code: 408
+ title: column.comment
+ content: Column `t`.`c` requires comments
+ line: 4
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int COMMENT 'comment');
+ ALTER TABLE t ADD COLUMN b int
+ want:
+ - status: WARN
+ code: 408
+ title: column.comment
+ content: Column `t`.`b` requires comments
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int COMMENT 'this is comment');
+ ALTER TABLE t CHANGE COLUMN a b int
+ want:
+ - status: WARN
+ code: 409
+ title: column.comment
+ content: The length of column `t`.`a` comment should be within 10 characters
+ line: 1
+ details: ""
+ - status: WARN
+ code: 408
+ title: column.comment
+ content: Column `t`.`b` requires comments
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(b int COMMENT 'It is comment');
+ ALTER TABLE t MODIFY COLUMN b int
+ want:
+ - status: WARN
+ code: 409
+ title: column.comment
+ content: The length of column `t`.`b` comment should be within 10 characters
+ line: 1
+ details: ""
+ - status: WARN
+ code: 408
+ title: column.comment
+ content: Column `t`.`b` requires comments
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(b int COMMENT 'It is COMMENT');
+ ALTER TABLE t MODIFY COLUMN b int COMMENT 'abcdefghiakljhakljdsfalugelkhnabsdguelkadf'
+ want:
+ - status: WARN
+ code: 409
+ title: column.comment
+ content: The length of column `t`.`b` comment should be within 10 characters
+ line: 1
+ details: ""
+ - status: WARN
+ code: 409
+ title: column.comment
+ content: The length of column `t`.`b` comment should be within 10 characters
+ line: 3
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/column_current_time_count_limit.yaml b/backend/plugin/advisor/tidb/test/column_current_time_count_limit.yaml
new file mode 100644
index 0000000000..f5b200b722
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/column_current_time_count_limit.yaml
@@ -0,0 +1,43 @@
+- statement: CREATE TABLE t(a timestamp, b timestamp)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(
+ a timestamp default now(),
+ b timestamp default current_timestamp(),
+ c timestamp default localtime
+ )
+ want:
+ - status: WARN
+ code: 418
+ title: column.current-time-count-limit
+ content: Table `t` has 3 DEFAULT CURRENT_TIMESTAMP() columns. The count greater than 2.
+ line: 6
+ details: ""
+- statement: |-
+ CREATE TABLE t(
+ a timestamp default now() on update localtime,
+ b timestamp default current_timestamp() on update localtimestamp()
+ )
+ want:
+ - status: WARN
+ code: 419
+ title: column.current-time-count-limit
+ content: Table `t` has 2 ON UPDATE CURRENT_TIMESTAMP() columns. The count greater than 1.
+ line: 5
+ details: ""
+- statement: |-
+ ALTER TABLE tech_book ADD COLUMN a timestamp default now() on update localtime;
+ ALTER TABLE tech_book ADD COLUMN b timestamp default current_timestamp() on update localtimestamp();
+ want:
+ - status: WARN
+ code: 419
+ title: column.current-time-count-limit
+ content: Table `tech_book` has 2 ON UPDATE CURRENT_TIMESTAMP() columns. The count greater than 1.
+ line: 3
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/column_disallow_change.yaml b/backend/plugin/advisor/tidb/test/column_disallow_change.yaml
new file mode 100644
index 0000000000..48b6696a3c
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/column_disallow_change.yaml
@@ -0,0 +1,23 @@
+- statement: |-
+ CREATE TABLE t(b int);
+ ALTER TABLE t ADD COLUMN a int
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(b int);
+ ALTER TABLE t CHANGE COLUMN b a int
+ want:
+ - status: WARN
+ code: 406
+ title: column.disallow-change
+ content: |-
+ "
+ ALTER TABLE t CHANGE COLUMN b a int
+ ;" contains CHANGE COLUMN statement
+ line: 3
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/column_disallow_change_type.yaml b/backend/plugin/advisor/tidb/test/column_disallow_change_type.yaml
new file mode 100644
index 0000000000..54ccb860b1
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/column_disallow_change_type.yaml
@@ -0,0 +1,38 @@
+- statement: ALTER TABLE tech_book MODIFY id INTEGER UNSIGNED
+ want:
+ - status: WARN
+ code: 403
+ title: column.disallow-change-type
+ content: |-
+ "ALTER TABLE tech_book MODIFY id INTEGER UNSIGNED
+ ;" changes column type
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book MODIFY id int
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: ALTER TABLE tech_book MODIFY id bigint
+ want:
+ - status: WARN
+ code: 403
+ title: column.disallow-change-type
+ content: |-
+ "ALTER TABLE tech_book MODIFY id bigint
+ ;" changes column type
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book CHANGE name uname varchar(20)
+ want:
+ - status: WARN
+ code: 403
+ title: column.disallow-change-type
+ content: |-
+ "ALTER TABLE tech_book CHANGE name uname varchar(20)
+ ;" changes column type
+ line: 2
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/column_disallow_changing_order.yaml b/backend/plugin/advisor/tidb/test/column_disallow_changing_order.yaml
new file mode 100644
index 0000000000..d600fbc3ca
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/column_disallow_changing_order.yaml
@@ -0,0 +1,62 @@
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t MODIFY COLUMN a int
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t MODIFY COLUMN a int FIRST
+ want:
+ - status: WARN
+ code: 407
+ title: column.disallow-changing-order
+ content: |-
+ "
+ ALTER TABLE t MODIFY COLUMN a int FIRST
+ ;" changes column order
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(b int, a1 int);
+ ALTER TABLE t CHANGE COLUMN a1 a int FIRST
+ want:
+ - status: WARN
+ code: 407
+ title: column.disallow-changing-order
+ content: |-
+ "
+ ALTER TABLE t CHANGE COLUMN a1 a int FIRST
+ ;" changes column order
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int, b int);
+ ALTER TABLE t MODIFY COLUMN a int AFTER b
+ want:
+ - status: WARN
+ code: 407
+ title: column.disallow-changing-order
+ content: |-
+ "
+ ALTER TABLE t MODIFY COLUMN a int AFTER b
+ ;" changes column order
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a1 int, b int);
+ ALTER TABLE t CHANGE COLUMN a1 a int AFTER b
+ want:
+ - status: WARN
+ code: 407
+ title: column.disallow-changing-order
+ content: |-
+ "
+ ALTER TABLE t CHANGE COLUMN a1 a int AFTER b
+ ;" changes column order
+ line: 3
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/column_disallow_drop_in_index.yaml b/backend/plugin/advisor/tidb/test/column_disallow_drop_in_index.yaml
new file mode 100644
index 0000000000..2b3c284b70
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/column_disallow_drop_in_index.yaml
@@ -0,0 +1,61 @@
+- statement: |-
+ CREATE TABLE t(a int, b int, INDEX idx_a(a));
+ ALTER TABLE t DROP COLUMN b
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+
+- statement: |-
+ CREATE TABLE t(a int, b int, INDEX idx_b(b));
+ ALTER TABLE t DROP COLUMN b
+ want:
+ - status: WARN
+ code: 424
+ title: "column.disallow-drop-in-index"
+ content: "`t`.`b` cannot drop index column"
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int, c int, INDEX idx_ac(a,c));
+ ALTER TABLE t DROP COLUMN c
+ want:
+ - status: WARN
+ code: 424
+ title: "column.disallow-drop-in-index"
+ content: "`t`.`c` cannot drop index column"
+ line: 3
+ details: ""
+
+- statement: |-
+ CREATE TABLE t(a int, b int, INDEX idx_a(a));
+ CREATE TABLE y(a int, b int);
+ ALTER TABLE y DROP COLUMN a
+ want:
+ - status: SUCCESS
+ code: 0
+ title: "OK"
+ content: ""
+ line: 0
+ details: ""
+
+- statement: |-
+ CREATE TABLE t(a int,b int, c int, INDEX idx_ac(a,c));
+ ALTER TABLE t DROP COLUMN a;
+ ALTER TABLE t DROP COLUMN c
+ want:
+ - status: WARN
+ code: 424
+ title: "column.disallow-drop-in-index"
+ content: "`t`.`a` cannot drop index column"
+ line: 2
+ details: ""
+ - status: WARN
+ code: 424
+ title: "column.disallow-drop-in-index"
+ content: "`t`.`c` cannot drop index column"
+ line: 4
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/column_disallow_set_charset.yaml b/backend/plugin/advisor/tidb/test/column_disallow_set_charset.yaml
new file mode 100644
index 0000000000..7125519720
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/column_disallow_set_charset.yaml
@@ -0,0 +1,58 @@
+- statement: |-
+ CREATE TABLE dt_relation_temp(objto int);
+ ALTER TABLE dt_relation_temp ADD COLUMN infos json null comment'关系信息点'AFTER`objto`;
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(a varchar(20))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(a varchar(20) CHARSET ascii)
+ want:
+ - status: WARN
+ code: 414
+ title: column.disallow-set-charset
+ content: |-
+ Disallow set column charset but "CREATE TABLE t(a varchar(20) CHARSET ascii)
+ ;" does
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book ADD COLUMN a varchar(20) CHARSET ascii
+ want:
+ - status: WARN
+ code: 414
+ title: column.disallow-set-charset
+ content: |-
+ Disallow set column charset but "ALTER TABLE tech_book ADD COLUMN a varchar(20) CHARSET ascii
+ ;" does
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book MODIFY COLUMN id varchar(20) CHARSET ascii
+ want:
+ - status: WARN
+ code: 414
+ title: column.disallow-set-charset
+ content: |-
+ Disallow set column charset but "ALTER TABLE tech_book MODIFY COLUMN id varchar(20) CHARSET ascii
+ ;" does
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book CHANGE COLUMN name name varchar(20) CHARSET ascii
+ want:
+ - status: WARN
+ code: 414
+ title: column.disallow-set-charset
+ content: |-
+ Disallow set column charset but "ALTER TABLE tech_book CHANGE COLUMN name name varchar(20) CHARSET ascii
+ ;" does
+ line: 2
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/column_maximum_character_length.yaml b/backend/plugin/advisor/tidb/test/column_maximum_character_length.yaml
new file mode 100644
index 0000000000..a826b65ac6
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/column_maximum_character_length.yaml
@@ -0,0 +1,48 @@
+- statement: CREATE TABLE t(name char(20));
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(name varchar(225));
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(name char(225));
+ want:
+ - status: WARN
+ code: 415
+ title: column.maximum-character-length
+ content: The length of the CHAR column `name` is bigger than 20, please use VARCHAR instead
+ line: 1
+ details: ""
+- statement: ALTER TABLE tech_book ADD COLUMN name_2 char(225)
+ want:
+ - status: WARN
+ code: 415
+ title: column.maximum-character-length
+ content: The length of the CHAR column `name_2` is bigger than 20, please use VARCHAR instead
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book CHANGE COLUMN name name char(225)
+ want:
+ - status: WARN
+ code: 415
+ title: column.maximum-character-length
+ content: The length of the CHAR column `name` is bigger than 20, please use VARCHAR instead
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book MODIFY COLUMN name char(225)
+ want:
+ - status: WARN
+ code: 415
+ title: column.maximum-character-length
+ content: The length of the CHAR column `name` is bigger than 20, please use VARCHAR instead
+ line: 2
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/column_no_null.yaml b/backend/plugin/advisor/tidb/test/column_no_null.yaml
new file mode 100644
index 0000000000..c91a3aa86d
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/column_no_null.yaml
@@ -0,0 +1,81 @@
+- statement: |-
+ CREATE TABLE book(
+ id int,
+ name varchar(255))
+ want:
+ - status: WARN
+ code: 402
+ title: column.no-null
+ content: '`book`.`id` cannot have NULL value'
+ line: 2
+ details: ""
+ - status: WARN
+ code: 402
+ title: column.no-null
+ content: '`book`.`name` cannot have NULL value'
+ line: 3
+ details: ""
+- statement: CREATE TABLE book(id int PRIMARY KEY, name varchar(255))
+ want:
+ - status: WARN
+ code: 402
+ title: column.no-null
+ content: '`book`.`name` cannot have NULL value'
+ line: 1
+ details: ""
+- statement: CREATE TABLE book(id int NOT NULL, name varchar(255))
+ want:
+ - status: WARN
+ code: 402
+ title: column.no-null
+ content: '`book`.`name` cannot have NULL value'
+ line: 1
+ details: ""
+- statement: CREATE TABLE book(id int PRIMARY KEY, name varchar(255) NOT NULL)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE book(a int NOT NULL);
+ ALTER TABLE book ADD COLUMN (id int, name varchar(255) NOT NULL);
+ want:
+ - status: WARN
+ code: 402
+ title: column.no-null
+ content: '`book`.`id` cannot have NULL value'
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE book(a int NOT NULL);
+ ALTER TABLE book ADD COLUMN (id int PRIMARY KEY, name varchar(255) NOT NULL);
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE book(id int NOT NULL);
+ ALTER TABLE book CHANGE COLUMN id name varchar(255);
+ want:
+ - status: WARN
+ code: 402
+ title: column.no-null
+ content: '`book`.`name` cannot have NULL value'
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE book(id int NOT NULL);
+ ALTER TABLE book CHANGE COLUMN id name varchar(255) NOT NULL;
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/column_require_default.yaml b/backend/plugin/advisor/tidb/test/column_require_default.yaml
new file mode 100644
index 0000000000..ed80fca205
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/column_require_default.yaml
@@ -0,0 +1,37 @@
+- statement: CREATE TABLE t(a int primary key, b int default 1)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(
+ a int,
+ b int default 1
+ )
+ want:
+ - status: WARN
+ code: 420
+ title: column.require-default
+ content: Column `t`.`a` doesn't have DEFAULT.
+ line: 2
+ details: ""
+- statement: |-
+ ALTER TABLE tech_book ADD COLUMN a BLOB;
+ ALTER TABLE tech_book ADD COLUMN b timestamp;
+ ALTER TABLE tech_book MODIFY COLUMN a varchar(220);
+ want:
+ - status: WARN
+ code: 420
+ title: column.require-default
+ content: Column `tech_book`.`b` doesn't have DEFAULT.
+ line: 2
+ details: ""
+ - status: WARN
+ code: 420
+ title: column.require-default
+ content: Column `tech_book`.`a` doesn't have DEFAULT.
+ line: 4
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/column_required.yaml b/backend/plugin/advisor/tidb/test/column_required.yaml
new file mode 100644
index 0000000000..fe2b0c2998
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/column_required.yaml
@@ -0,0 +1,180 @@
+- statement: CREATE TABLE book(id int)
+ want:
+ - status: WARN
+ code: 401
+ title: column.required
+ content: 'Table `book` requires columns: created_ts, creator_id, updated_ts, updater_id'
+ line: 2
+ details: ""
+- statement: |-
+ CREATE TABLE book(
+ id int,
+ creator_id int,
+ created_ts timestamp,
+ updater_id int,
+ updated_ts timestamp)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE book(
+ id int,
+ creator_id int,
+ created_ts timestamp,
+ updater_id int,
+ updated_ts timestamp);
+ ALTER TABLE book RENAME COLUMN creator_id TO creator;
+ want:
+ - status: WARN
+ code: 401
+ title: column.required
+ content: 'Table `book` requires columns: creator_id'
+ line: 8
+ details: ""
+- statement: |-
+ CREATE TABLE book(
+ id int,
+ creator int,
+ created_ts timestamp,
+ updater_id int,
+ updated_ts timestamp);
+ ALTER TABLE book RENAME COLUMN creator TO creator_id;
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE book(
+ id int,
+ creator_id int,
+ created_ts timestamp,
+ updater_id int,
+ updated_ts timestamp);
+ ALTER TABLE book CHANGE COLUMN creator_id creator int;
+ want:
+ - status: WARN
+ code: 401
+ title: column.required
+ content: 'Table `book` requires columns: creator_id'
+ line: 8
+ details: ""
+- statement: |-
+ CREATE TABLE book(
+ id int,
+ creator int,
+ created_ts timestamp,
+ updater_id int,
+ updated_ts timestamp);
+ ALTER TABLE book CHANGE COLUMN creator creator_id int;
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE book(
+ id int,
+ creator_id int,
+ created_ts timestamp,
+ updater_id int,
+ updated_ts timestamp);
+ ALTER TABLE book DROP COLUMN creator_id;
+ want:
+ - status: WARN
+ code: 401
+ title: column.required
+ content: 'Table `book` requires columns: creator_id'
+ line: 8
+ details: ""
+- statement: |-
+ CREATE TABLE book(
+ id int,
+ creator_id int,
+ created_ts timestamp,
+ updater_id int,
+ updated_ts timestamp,
+ content varchar(255));
+ ALTER TABLE book DROP COLUMN content;
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE book(
+ id int,
+ creator_id int,
+ created_ts timestamp,
+ updated_ts timestamp);
+ ALTER TABLE book ADD COLUMN content varchar(255);
+ want:
+ - status: WARN
+ code: 401
+ title: column.required
+ content: 'Table `book` requires columns: updater_id'
+ line: 5
+ details: ""
+- statement: |-
+ CREATE TABLE book(
+ id int,
+ creator int,
+ created_ts timestamp,
+ updater_id int,
+ updated_ts timestamp);
+ ALTER TABLE book ADD COLUMN creator_id int;
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE book(
+ id int,
+ created_ts timestamp,
+ updater_id int,
+ updated_ts timestamp);
+ CREATE TABLE student(
+ id int,
+ created_ts timestamp,
+ updated_ts timestamp)
+ want:
+ - status: WARN
+ code: 401
+ title: column.required
+ content: 'Table `book` requires columns: creator_id'
+ line: 5
+ details: ""
+ - status: WARN
+ code: 401
+ title: column.required
+ content: 'Table `student` requires columns: creator_id, updater_id'
+ line: 10
+ details: ""
+- statement: |-
+ CREATE TABLE book(
+ id int,
+ creator int,
+ created_ts timestamp,
+ updater_id int,
+ updated_ts timestamp);
+ DROP TABLE book;
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/column_set_default_for_not_null.yaml b/backend/plugin/advisor/tidb/test/column_set_default_for_not_null.yaml
new file mode 100644
index 0000000000..169e70d0fc
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/column_set_default_for_not_null.yaml
@@ -0,0 +1,113 @@
+- statement: |-
+ CREATE TABLE book(
+ id int PRIMARY KEY DEFAULT 0
+ )
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE book(
+ id int PRIMARY KEY
+ )
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE book(
+ id int NOT NULL
+ )
+ want:
+ - status: WARN
+ code: 404
+ title: column.set-default-for-not-null
+ content: Column `book`.`id` is NOT NULL but doesn't have DEFAULT
+ line: 2
+ details: ""
+- statement: |-
+ CREATE TABLE book(
+ id int,
+ PRIMARY KEY (id)
+ )
+ want:
+ - status: WARN
+ code: 404
+ title: column.set-default-for-not-null
+ content: Column `book`.`id` is NOT NULL but doesn't have DEFAULT
+ line: 2
+ details: ""
+- statement: |-
+ CREATE TABLE book(a int);
+ ALTER TABLE book ADD COLUMN id int PRIMARY KEY
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE book(a int);
+ ALTER TABLE book ADD COLUMN id int NOT NULL
+ want:
+ - status: WARN
+ code: 404
+ title: column.set-default-for-not-null
+ content: Column `book`.`id` is NOT NULL but doesn't have DEFAULT
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE book(id int);
+ ALTER TABLE book MODIFY COLUMN id int NOT NULL
+ want:
+ - status: WARN
+ code: 404
+ title: column.set-default-for-not-null
+ content: Column `book`.`id` is NOT NULL but doesn't have DEFAULT
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE book(id int);
+ ALTER TABLE book MODIFY COLUMN id int PRIMARY KEY
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE book(uid int);
+ ALTER TABLE book CHANGE COLUMN uid id int PRIMARY KEY
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE book(uid int);
+ ALTER TABLE book CHANGE COLUMN uid id int NOT NULL
+ want:
+ - status: WARN
+ code: 404
+ title: column.set-default-for-not-null
+ content: Column `book`.`id` is NOT NULL but doesn't have DEFAULT
+ line: 3
+ details: ""
+- statement: "\n\t\t\t\tCREATE TABLE book(uid int, id int);\n\t\t\t\tALTER TABLE book \n\t\t\t\t\tCHANGE COLUMN uid uid int NOT NULL DEFAULT 0,\n\t\t\t\t\tMODIFY COLUMN id int PRIMARY KEY DEFAULT 0,\n\t\t\t\t\tADD COLUMN name varchar(20) NOT NULL DEFAULT ''\n\t\t\t\t"
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/column_type_disallow_list.yaml b/backend/plugin/advisor/tidb/test/column_type_disallow_list.yaml
new file mode 100644
index 0000000000..aa3d6dc244
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/column_type_disallow_list.yaml
@@ -0,0 +1,36 @@
+- statement: CREATE TABLE t(a int)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(a JSON, b BLOB, c TEXT)
+ want:
+ - status: WARN
+ code: 411
+ title: column.type-disallow-list
+ content: Disallow column type JSON but column `t`.`a` is
+ line: 1
+ details: ""
+- statement: |-
+ CREATE TABLE t(d int);
+ ALTER TABLE t add COLUMN (a JSON, b BLOB, c TEXT)
+ want:
+ - status: WARN
+ code: 411
+ title: column.type-disallow-list
+ content: Disallow column type JSON but column `t`.`a` is
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(c int, b int);
+ ALTER TABLE t CHANGE COLUMN c a JSON, MODIFY b BLOB
+ want:
+ - status: WARN
+ code: 411
+ title: column.type-disallow-list
+ content: Disallow column type JSON but column `t`.`a` is
+ line: 3
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/database_drop_empty_database.yaml b/backend/plugin/advisor/tidb/test/database_drop_empty_database.yaml
new file mode 100644
index 0000000000..c5b2d15f6a
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/database_drop_empty_database.yaml
@@ -0,0 +1,8 @@
+- statement: DROP DATABASE IF EXISTS test
+ want:
+ - status: WARN
+ code: 701
+ title: database.drop-empty-database
+ content: Database `test` is not allowed to drop if not empty
+ line: 2
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/engine_mysql_use_innodb.yaml b/backend/plugin/advisor/tidb/test/engine_mysql_use_innodb.yaml
new file mode 100644
index 0000000000..70190f0dda
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/engine_mysql_use_innodb.yaml
@@ -0,0 +1,62 @@
+- statement: CREATE TABLE book(id int) ENGINE = INNODB
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE book(id int)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE book(id int) ENGINE = CSV
+ want:
+ - status: WARN
+ code: 501
+ title: engine.mysql.use-innodb
+ content: |-
+ "CREATE TABLE book(id int) ENGINE = CSV
+ ;" doesn't use InnoDB engine
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book ENGINE = INNODB
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: ALTER TABLE tech_book ENGINE = CSV
+ want:
+ - status: WARN
+ code: 501
+ title: engine.mysql.use-innodb
+ content: |-
+ "ALTER TABLE tech_book ENGINE = CSV
+ ;" doesn't use InnoDB engine
+ line: 2
+ details: ""
+- statement: SET default_storage_engine=INNODB
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: SET default_storage_engine=CSV
+ want:
+ - status: WARN
+ code: 501
+ title: engine.mysql.use-innodb
+ content: |-
+ "SET default_storage_engine=CSV
+ ;" doesn't use InnoDB engine
+ line: 2
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/index_key_number_limit.yaml b/backend/plugin/advisor/tidb/test/index_key_number_limit.yaml
new file mode 100644
index 0000000000..bab83ee30a
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/index_key_number_limit.yaml
@@ -0,0 +1,50 @@
+- statement: CREATE TABLE t(a int, b int, primary key (a, b))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(
+ a int,
+ b int,
+ primary key pk (a, b, b, b, b, b, b))
+ want:
+ - status: WARN
+ code: 802
+ title: index.key-number-limit
+ content: The number of index `pk` in table `t` should be not greater than 5
+ line: 4
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int, b int, c int, d int, e int, f int, g int);
+ CREATE INDEX idx ON t(a, b, c, d, e, f, g)
+ want:
+ - status: WARN
+ code: 802
+ title: index.key-number-limit
+ content: The number of index `idx` in table `t` should be not greater than 5
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int, b int, c int, d int, e int, f int, g int);
+ ALTER TABLE t ADD UNIQUE KEY uk (a, b, c, d, e, f, g)
+ want:
+ - status: WARN
+ code: 802
+ title: index.key-number-limit
+ content: The number of index `uk` in table `t` should be not greater than 5
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int, b int, c int, d int, e int, f int, g int);
+ ALTER TABLE t ADD FOREIGN KEY uk (a, b, c, d, e, f, g) REFERENCES t1(a, b, c, d, e, f, g)
+ want:
+ - status: WARN
+ code: 802
+ title: index.key-number-limit
+ content: The number of index `uk` in table `t` should be not greater than 5
+ line: 3
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/index_no_duplicate_column.yaml b/backend/plugin/advisor/tidb/test/index_no_duplicate_column.yaml
new file mode 100644
index 0000000000..c16e93b8f3
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/index_no_duplicate_column.yaml
@@ -0,0 +1,69 @@
+- statement: CREATE TABLE t (a int, PRIMARY KEY (a))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t (
+ a int,
+ INDEX idx_a (a, a))
+ want:
+ - status: WARN
+ code: 812
+ title: index.no-duplicate-column
+ content: INDEX `idx_a` has duplicate column `t`.`a`
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ CREATE INDEX idx_a on t(a, a)
+ want:
+ - status: WARN
+ code: 812
+ title: index.no-duplicate-column
+ content: INDEX `idx_a` has duplicate column `t`.`a`
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD INDEX idx_a (a, a)
+ want:
+ - status: WARN
+ code: 812
+ title: index.no-duplicate-column
+ content: INDEX `idx_a` has duplicate column `t`.`a`
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD PRIMARY KEY pk_a (a, a)
+ want:
+ - status: WARN
+ code: 812
+ title: index.no-duplicate-column
+ content: PRIMARY KEY `pk_a` has duplicate column `t`.`a`
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD UNIQUE KEY uk_a (a, a)
+ want:
+ - status: WARN
+ code: 812
+ title: index.no-duplicate-column
+ content: UNIQUE KEY `uk_a` has duplicate column `t`.`a`
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD FOREIGN KEY fk_a (a, a) REFERENCES t1(a, b)
+ want:
+ - status: WARN
+ code: 812
+ title: index.no-duplicate-column
+ content: FOREIGN KEY `fk_a` has duplicate column `t`.`a`
+ line: 3
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/index_pk_type_limit.yaml b/backend/plugin/advisor/tidb/test/index_pk_type_limit.yaml
new file mode 100644
index 0000000000..96e9f4f70c
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/index_pk_type_limit.yaml
@@ -0,0 +1,206 @@
+- statement: CREATE TABLE t(id VARCHAR(5) PRIMARY KEY)
+ want:
+ - status: WARN
+ code: 803
+ title: index.pk-type-limit
+ content: Columns in primary key must be INT/BIGINT but `t`.`id` is varchar(5)
+ line: 1
+ details: ""
+- statement: CREATE TABLE t(id INT PRIMARY KEY)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(id VARCHAR(5), PRIMARY KEY(id))
+ want:
+ - status: WARN
+ code: 803
+ title: index.pk-type-limit
+ content: Columns in primary key must be INT/BIGINT but `t`.`id` is varchar(5)
+ line: 1
+ details: ""
+- statement: CREATE TABLE t(id INT, id2 VARCHAR(5), id3 VARCHAR(5), PRIMARY KEY(id, id2, id3))
+ want:
+ - status: WARN
+ code: 803
+ title: index.pk-type-limit
+ content: Columns in primary key must be INT/BIGINT but `t`.`id2` is varchar(5)
+ line: 1
+ details: ""
+ - status: WARN
+ code: 803
+ title: index.pk-type-limit
+ content: Columns in primary key must be INT/BIGINT but `t`.`id3` is varchar(5)
+ line: 1
+ details: ""
+- statement: CREATE TABLE t(id INT, id2 BIGINT, PRIMARY KEY(id, id2))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(id INT, PRIMARY KEY(id))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD COLUMN id VARCHAR(5) PRIMARY KEY
+ want:
+ - status: WARN
+ code: 803
+ title: index.pk-type-limit
+ content: Columns in primary key must be INT/BIGINT but `t`.`id` is varchar(5)
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD COLUMN id INT PRIMARY KEY
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD COLUMN id VARCHAR(5), ADD PRIMARY KEY (id)
+ want:
+ - status: WARN
+ code: 803
+ title: index.pk-type-limit
+ content: Columns in primary key must be INT/BIGINT but `t`.`id` is varchar(5)
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD COLUMN id INT, ADD COLUMN id2 VARCHAR(5), ADD COLUMN id3 VARCHAR(5), ADD PRIMARY KEY (id, id2, id3)
+ want:
+ - status: WARN
+ code: 803
+ title: index.pk-type-limit
+ content: Columns in primary key must be INT/BIGINT but `t`.`id2` is varchar(5)
+ line: 3
+ details: ""
+ - status: WARN
+ code: 803
+ title: index.pk-type-limit
+ content: Columns in primary key must be INT/BIGINT but `t`.`id3` is varchar(5)
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD COLUMN id INT, ADD COLUMN id2 BIGINT, ADD PRIMARY KEY (id, id2)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD COLUMN id BIGINT, ADD PRIMARY KEY (id)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(id VARCHAR(5));
+ ALTER TABLE t ADD PRIMARY KEY(id);
+ want:
+ - status: WARN
+ code: 803
+ title: index.pk-type-limit
+ content: Columns in primary key must be INT/BIGINT but `t`.`id` is varchar(5)
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(id INT, id2 VARCHAR(5), id3 VARCHAR(5));
+ ALTER TABLE t ADD PRIMARY KEY(id, id2, id3);
+ want:
+ - status: WARN
+ code: 803
+ title: index.pk-type-limit
+ content: Columns in primary key must be INT/BIGINT but `t`.`id2` is varchar(5)
+ line: 3
+ details: ""
+ - status: WARN
+ code: 803
+ title: index.pk-type-limit
+ content: Columns in primary key must be INT/BIGINT but `t`.`id3` is varchar(5)
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(id INT, id2 BIGINT);
+ ALTER TABLE t ADD PRIMARY KEY(id, id2);
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(id BIGINT);
+ ALTER TABLE t ADD PRIMARY KEY(id);
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(id int);
+ ALTER TABLE t MODIFY COLUMN id VARCHAR(5) PRIMARY KEY;
+ want:
+ - status: WARN
+ code: 803
+ title: index.pk-type-limit
+ content: Columns in primary key must be INT/BIGINT but `t`.`id` is varchar(5)
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(id int);
+ ALTER TABLE t MODIFY COLUMN id INT(5) PRIMARY KEY;
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(id int);
+ ALTER TABLE t CHANGE COLUMN id id2 VARCHAR(5) PRIMARY KEY
+ want:
+ - status: WARN
+ code: 803
+ title: index.pk-type-limit
+ content: Columns in primary key must be INT/BIGINT but `t`.`id2` is varchar(5)
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(id int);
+ ALTER TABLE t CHANGE COLUMN id id2 INT(5) PRIMARY KEY
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/index_primary_key_type_allowlist.yaml b/backend/plugin/advisor/tidb/test/index_primary_key_type_allowlist.yaml
new file mode 100644
index 0000000000..6b7fc068ea
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/index_primary_key_type_allowlist.yaml
@@ -0,0 +1,206 @@
+- statement: CREATE TABLE t(id VARCHAR(5) PRIMARY KEY)
+ want:
+ - status: WARN
+ code: 803
+ title: index.primary-key-type-allowlist
+ content: The column `id` in table `t` is one of the primary key, but its type "varchar" is not in allowlist
+ line: 1
+ details: ""
+- statement: CREATE TABLE t(id INT PRIMARY KEY)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(id VARCHAR(5), PRIMARY KEY(id))
+ want:
+ - status: WARN
+ code: 803
+ title: index.primary-key-type-allowlist
+ content: The column `id` in table `t` is one of the primary key, but its type "varchar" is not in allowlist
+ line: 1
+ details: ""
+- statement: CREATE TABLE t(id INT, id2 VARCHAR(5), id3 VARCHAR(5), PRIMARY KEY(id, id2, id3))
+ want:
+ - status: WARN
+ code: 803
+ title: index.primary-key-type-allowlist
+ content: The column `id2` in table `t` is one of the primary key, but its type "varchar" is not in allowlist
+ line: 1
+ details: ""
+ - status: WARN
+ code: 803
+ title: index.primary-key-type-allowlist
+ content: The column `id3` in table `t` is one of the primary key, but its type "varchar" is not in allowlist
+ line: 1
+ details: ""
+- statement: CREATE TABLE t(id INT, id2 BIGINT, PRIMARY KEY(id, id2))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(id INT, PRIMARY KEY(id))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD COLUMN id VARCHAR(5) PRIMARY KEY
+ want:
+ - status: WARN
+ code: 803
+ title: index.primary-key-type-allowlist
+ content: The column `id` in table `t` is one of the primary key, but its type "varchar" is not in allowlist
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD COLUMN id INT PRIMARY KEY
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD COLUMN id VARCHAR(5), ADD PRIMARY KEY (id)
+ want:
+ - status: WARN
+ code: 803
+ title: index.primary-key-type-allowlist
+ content: The column `id` in table `t` is one of the primary key, but its type "varchar" is not in allowlist
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD COLUMN id INT, ADD COLUMN id2 VARCHAR(5), ADD COLUMN id3 VARCHAR(5), ADD PRIMARY KEY (id, id2, id3)
+ want:
+ - status: WARN
+ code: 803
+ title: index.primary-key-type-allowlist
+ content: The column `id2` in table `t` is one of the primary key, but its type "varchar" is not in allowlist
+ line: 3
+ details: ""
+ - status: WARN
+ code: 803
+ title: index.primary-key-type-allowlist
+ content: The column `id3` in table `t` is one of the primary key, but its type "varchar" is not in allowlist
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD COLUMN id INT, ADD COLUMN id2 BIGINT, ADD PRIMARY KEY (id, id2)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD COLUMN id BIGINT, ADD PRIMARY KEY (id)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(id VARCHAR(5));
+ ALTER TABLE t ADD PRIMARY KEY(id);
+ want:
+ - status: WARN
+ code: 803
+ title: index.primary-key-type-allowlist
+ content: The column `id` in table `t` is one of the primary key, but its type "varchar" is not in allowlist
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(id INT, id2 VARCHAR(5), id3 VARCHAR(5));
+ ALTER TABLE t ADD PRIMARY KEY(id, id2, id3);
+ want:
+ - status: WARN
+ code: 803
+ title: index.primary-key-type-allowlist
+ content: The column `id2` in table `t` is one of the primary key, but its type "varchar" is not in allowlist
+ line: 3
+ details: ""
+ - status: WARN
+ code: 803
+ title: index.primary-key-type-allowlist
+ content: The column `id3` in table `t` is one of the primary key, but its type "varchar" is not in allowlist
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(id INT, id2 BIGINT);
+ ALTER TABLE t ADD PRIMARY KEY(id, id2);
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(id BIGINT);
+ ALTER TABLE t ADD PRIMARY KEY(id);
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(id int);
+ ALTER TABLE t MODIFY COLUMN id VARCHAR(5) PRIMARY KEY;
+ want:
+ - status: WARN
+ code: 803
+ title: index.primary-key-type-allowlist
+ content: The column `id` in table `t` is one of the primary key, but its type "varchar" is not in allowlist
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(id int);
+ ALTER TABLE t MODIFY COLUMN id INT(5) PRIMARY KEY;
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(id int);
+ ALTER TABLE t CHANGE COLUMN id id2 VARCHAR(5) PRIMARY KEY
+ want:
+ - status: WARN
+ code: 803
+ title: index.primary-key-type-allowlist
+ content: The column `id2` in table `t` is one of the primary key, but its type "varchar" is not in allowlist
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(id int);
+ ALTER TABLE t CHANGE COLUMN id id2 INT(5) PRIMARY KEY
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/index_total_number_limit.yaml b/backend/plugin/advisor/tidb/test/index_total_number_limit.yaml
new file mode 100644
index 0000000000..70ba0fc71d
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/index_total_number_limit.yaml
@@ -0,0 +1,60 @@
+- statement: CREATE TABLE t(a int, b int, c int, unique key(a, b, c))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE INDEX idx_id_name on tech_book(id, name)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE INDEX idx_id_name_1 on tech_book(id, name);
+ CREATE INDEX idx_id_name_2 on tech_book(id, name);
+ CREATE INDEX idx_id_name_3 on tech_book(id, name);
+ CREATE INDEX idx_id_name_4 on tech_book(id, name);
+ CREATE INDEX idx_id_name_5 on tech_book(id, name);
+ want:
+ - status: WARN
+ code: 813
+ title: index.total-number-limit
+ content: The count of index in table `tech_book` should be no more than 5, but found 8
+ line: 6
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int PRIMARY KEY, b int, c int);
+ CREATE INDEX idx_a_b_1 on t(a, b);
+ CREATE INDEX idx_a_b_2 on t(a, b);
+ CREATE INDEX idx_a_b_3 on t(a, b);
+ CREATE INDEX idx_a_b_4 on t(a, b);
+ CREATE INDEX idx_a_b_5 on t(a, b);
+ want:
+ - status: WARN
+ code: 813
+ title: index.total-number-limit
+ content: The count of index in table `t` should be no more than 5, but found 6
+ line: 7
+ details: ""
+- statement: |-
+ CREATE TABLE t(
+ a int PRIMARY KEY,
+ b int,
+ c int,
+ INDEX idx_a_b_1 (a, b),
+ INDEX idx_a_b_2 (a, b),
+ INDEX idx_a_b_3 (a, b),
+ INDEX idx_a_b_4 (a, b),
+ INDEX idx_a_b_5 (a, b));
+ want:
+ - status: WARN
+ code: 813
+ title: index.total-number-limit
+ content: The count of index in table `t` should be no more than 5, but found 6
+ line: 10
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/index_type_no_blob.yaml b/backend/plugin/advisor/tidb/test/index_type_no_blob.yaml
new file mode 100644
index 0000000000..ef671ba1ea
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/index_type_no_blob.yaml
@@ -0,0 +1,175 @@
+- statement: CREATE TABLE t(b BLOB, PRIMARY KEY(b(10)))
+ want:
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`b` is blob
+ line: 1
+ details: ""
+- statement: CREATE TABLE t(b BLOB, mb MEDIUMBLOB, lb LONGBLOB, id INT, PRIMARY KEY(b(1), mb(2), lb(3), id))
+ want:
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`b` is blob
+ line: 1
+ details: ""
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`lb` is longblob
+ line: 1
+ details: ""
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`mb` is mediumblob
+ line: 1
+ details: ""
+- statement: CREATE TABLE t(b BLOB, mb MEDIUMBLOB, lb LONGBLOB, id INT, UNIQUE INDEX(b(1), mb(2), lb(3), id))
+ want:
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`b` is blob
+ line: 1
+ details: ""
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`lb` is longblob
+ line: 1
+ details: ""
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`mb` is mediumblob
+ line: 1
+ details: ""
+- statement: CREATE TABLE t(b BLOB, mb MEDIUMBLOB, lb LONGBLOB, id iNT, INDEX(b(1), mb(2), lb(3), id))
+ want:
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`b` is blob
+ line: 1
+ details: ""
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`lb` is longblob
+ line: 1
+ details: ""
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`mb` is mediumblob
+ line: 1
+ details: ""
+- statement: CREATE TABLE t(id INT, PRIMARY KEY(id))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD COLUMN b BLOB, ADD COLUMN id INT, ADD PRIMARY KEY(b(1), id)
+ want:
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`b` is blob
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD COLUMN b BLOB, ADD COLUMN mb MEDIUMBLOB, ADD COLUMN lb LONGBLOB, ADD COLUMN id INT, ADD UNIQUE INDEX(b(1), mb(2), lb(3), id)
+ want:
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`b` is blob
+ line: 3
+ details: ""
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`lb` is longblob
+ line: 3
+ details: ""
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`mb` is mediumblob
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD COLUMN b BLOB, ADD COLUMN mb MEDIUMBLOB, ADD COLUMN lb LONGBLOB, ADD COLUMN id INT, ADD INDEX(b(1), mb(2), lb(3), id)
+ want:
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`b` is blob
+ line: 3
+ details: ""
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`lb` is longblob
+ line: 3
+ details: ""
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`mb` is mediumblob
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t ADD COLUMN b BLOB, ADD COLUMN mb MEDIUMBLOB, ADD COLUMN lb LONGBLOB, ADD COLUMN id INT, ADD INDEX(id)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(b blob, mb mediumblob, lb longblob, id int);
+ CREATE INDEX idx_b ON t(b(5));
+ CREATE INDEX idx_mb ON t(mb(5));
+ CREATE INDEX idx_lb ON t(lb(5));
+ CREATE INDEX idx_id ON t(id);
+ want:
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`b` is blob
+ line: 2
+ details: ""
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`mb` is mediumblob
+ line: 3
+ details: ""
+ - status: WARN
+ code: 804
+ title: index.type-no-blob
+ content: Columns in index must not be BLOB but `t`.`lb` is longblob
+ line: 4
+ details: ""
+- statement: |-
+ CREATE TABLE t(b blob, mb mediumblob, lb longblob, id int);
+ CREATE INDEX idx_id ON t(id);
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/naming_column.yaml b/backend/plugin/advisor/tidb/test/naming_column.yaml
new file mode 100644
index 0000000000..97e0bc8a28
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/naming_column.yaml
@@ -0,0 +1,122 @@
+- statement: CREATE TABLE book(id int, creatorId int)
+ want:
+ - status: WARN
+ code: 302
+ title: naming.column
+ content: '`book`.`creatorId` mismatches column naming convention, naming format should be "^[a-z]+(_[a-z]+)*$"'
+ line: 1
+ details: ""
+- statement: CREATE TABLE book(id int, gbhzmtchhsjzyrhdroxmyouwloxqezowdvhcbqalqcgqhfbjnvmhwrbggezmzeusx int)
+ want:
+ - status: WARN
+ code: 302
+ title: naming.column
+ content: '`book`.`gbhzmtchhsjzyrhdroxmyouwloxqezowdvhcbqalqcgqhfbjnvmhwrbggezmzeusx` mismatches column naming convention, its length should be within 64 characters'
+ line: 1
+ details: ""
+- statement: CREATE TABLE book(id int, creator_id int)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE book(id int, creator_id int);
+ ALTER TABLE book RENAME COLUMN creator_id TO creatorId
+ want:
+ - status: WARN
+ code: 302
+ title: naming.column
+ content: '`book`.`creatorId` mismatches column naming convention, naming format should be "^[a-z]+(_[a-z]+)*$"'
+ line: 3
+ details: ""
+- statement: ALTER TABLE tech_book RENAME COLUMN id TO creator_id;
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE book(
+ id int,
+ creator_id int,
+ created_ts timestamp,
+ updater_id int,
+ updated_ts timestamp);
+ ALTER TABLE book CHANGE COLUMN creator_id creatorId int;
+ want:
+ - status: WARN
+ code: 302
+ title: naming.column
+ content: '`book`.`creatorId` mismatches column naming convention, naming format should be "^[a-z]+(_[a-z]+)*$"'
+ line: 8
+ details: ""
+- statement: ALTER TABLE tech_book CHANGE COLUMN id creator_id int;
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: ALTER TABLE tech_book DROP COLUMN id;
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE book(
+ id int,
+ creator_id int,
+ created_ts timestamp,
+ updated_ts timestamp);
+ ALTER TABLE book ADD COLUMN contentString varchar(255);
+ want:
+ - status: WARN
+ code: 302
+ title: naming.column
+ content: '`book`.`contentString` mismatches column naming convention, naming format should be "^[a-z]+(_[a-z]+)*$"'
+ line: 7
+ details: ""
+- statement: |-
+ CREATE TABLE book(
+ id int,
+ createdTs timestamp,
+ updaterId int,
+ updated_ts timestamp);
+ CREATE TABLE student(
+ id int,
+ createdTs timestamp,
+ updatedTs timestamp);
+ want:
+ - status: WARN
+ code: 302
+ title: naming.column
+ content: '`book`.`createdTs` mismatches column naming convention, naming format should be "^[a-z]+(_[a-z]+)*$"'
+ line: 3
+ details: ""
+ - status: WARN
+ code: 302
+ title: naming.column
+ content: '`book`.`updaterId` mismatches column naming convention, naming format should be "^[a-z]+(_[a-z]+)*$"'
+ line: 4
+ details: ""
+ - status: WARN
+ code: 302
+ title: naming.column
+ content: '`student`.`createdTs` mismatches column naming convention, naming format should be "^[a-z]+(_[a-z]+)*$"'
+ line: 8
+ details: ""
+ - status: WARN
+ code: 302
+ title: naming.column
+ content: '`student`.`updatedTs` mismatches column naming convention, naming format should be "^[a-z]+(_[a-z]+)*$"'
+ line: 9
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/naming_column_auto_increment.yaml b/backend/plugin/advisor/tidb/test/naming_column_auto_increment.yaml
new file mode 100644
index 0000000000..29e0a0dc10
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/naming_column_auto_increment.yaml
@@ -0,0 +1,40 @@
+- statement: CREATE TABLE book(id int AUTO_INCREMENT)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE book(a int AUTO_INCREMENT)
+ want:
+ - status: WARN
+ code: 307
+ title: naming.column.auto-increment
+ content: '`book`.`a` mismatches auto_increment column naming convention, naming format should be "^id$"'
+ line: 1
+ details: ""
+- statement: ALTER TABLE tech_book ADD COLUMN a int AUTO_INCREMENT
+ want:
+ - status: WARN
+ code: 307
+ title: naming.column.auto-increment
+ content: '`tech_book`.`a` mismatches auto_increment column naming convention, naming format should be "^id$"'
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book CHANGE COLUMN id a int AUTO_INCREMENT
+ want:
+ - status: WARN
+ code: 307
+ title: naming.column.auto-increment
+ content: '`tech_book`.`a` mismatches auto_increment column naming convention, naming format should be "^id$"'
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book MODIFY COLUMN name int AUTO_INCREMENT
+ want:
+ - status: WARN
+ code: 307
+ title: naming.column.auto-increment
+ content: '`tech_book`.`name` mismatches auto_increment column naming convention, naming format should be "^id$"'
+ line: 2
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/naming_index_fk.yaml b/backend/plugin/advisor/tidb/test/naming_index_fk.yaml
new file mode 100644
index 0000000000..149bba0c69
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/naming_index_fk.yaml
@@ -0,0 +1,54 @@
+- statement: ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_author_id_author_id FOREIGN KEY (author_id) REFERENCES author (id)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: ALTER TABLE tech_book ADD CONSTRAINT fk_author_id FOREIGN KEY (author_id) REFERENCES author (id)
+ want:
+ - status: WARN
+ code: 305
+ title: naming.index.fk
+ content: Foreign key in table `tech_book` mismatches the naming convention, expect "^$|^fk_tech_book_author_id_author_id$" but found `fk_author_id`
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book ADD CONSTRAINT rvemempmcmmhutaskvcidmwaldtfjdgmcpkhmibtadfydtkexpuzczrrneucthfwk FOREIGN KEY (author_id) REFERENCES author (id)
+ want:
+ - status: WARN
+ code: 305
+ title: naming.index.fk
+ content: Foreign key `rvemempmcmmhutaskvcidmwaldtfjdgmcpkhmibtadfydtkexpuzczrrneucthfwk` in table `tech_book` mismatches the naming convention, its length should be within 64 characters
+ line: 2
+ details: ""
+ - status: WARN
+ code: 305
+ title: naming.index.fk
+ content: Foreign key in table `tech_book` mismatches the naming convention, expect "^$|^fk_tech_book_author_id_author_id$" but found `rvemempmcmmhutaskvcidmwaldtfjdgmcpkhmibtadfydtkexpuzczrrneucthfwk`
+ line: 2
+ details: ""
+- statement: CREATE TABLE book(id INT, author_id INT, FOREIGN KEY fk_book_author_id_author_id (author_id) REFERENCES author (id))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE book(id INT, author_id INT, FOREIGN KEY (author_id) REFERENCES author (id))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE book(id INT, author_id INT, FOREIGN KEY fk_book_author_id (author_id) REFERENCES author (id))
+ want:
+ - status: WARN
+ code: 305
+ title: naming.index.fk
+ content: Foreign key in table `book` mismatches the naming convention, expect "^$|^fk_book_author_id_author_id$" but found `fk_book_author_id`
+ line: 1
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/naming_index_idx.yaml b/backend/plugin/advisor/tidb/test/naming_index_idx.yaml
new file mode 100644
index 0000000000..4d2151138f
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/naming_index_idx.yaml
@@ -0,0 +1,78 @@
+- statement: CREATE INDEX idx_tech_book_id_name ON tech_book(id, name)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE INDEX tech_book_id_name ON tech_book(id, name)
+ want:
+ - status: WARN
+ code: 303
+ title: naming.index.idx
+ content: Index in table `tech_book` mismatches the naming convention, expect "^$|^idx_tech_book_id_name$" but found `tech_book_id_name`
+ line: 2
+ details: ""
+- statement: CREATE INDEX afvjwsgrbgqzjfrkmbcoxzstznuypasijbbcdykoboredqovetzfcmmqliaelyavw ON tech_book(id, name)
+ want:
+ - status: WARN
+ code: 303
+ title: naming.index.idx
+ content: Index `afvjwsgrbgqzjfrkmbcoxzstznuypasijbbcdykoboredqovetzfcmmqliaelyavw` in table `tech_book` mismatches the naming convention, its length should be within 64 characters
+ line: 2
+ details: ""
+ - status: WARN
+ code: 303
+ title: naming.index.idx
+ content: Index in table `tech_book` mismatches the naming convention, expect "^$|^idx_tech_book_id_name$" but found `afvjwsgrbgqzjfrkmbcoxzstznuypasijbbcdykoboredqovetzfcmmqliaelyavw`
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book RENAME INDEX old_index TO idx_tech_book_id_name
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: ALTER TABLE tech_book RENAME INDEX old_index TO idx_tech_book
+ want:
+ - status: WARN
+ code: 303
+ title: naming.index.idx
+ content: Index in table `tech_book` mismatches the naming convention, expect "^$|^idx_tech_book_id_name$" but found `idx_tech_book`
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book ADD INDEX idx_tech_book_id_name (id, name)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: ALTER TABLE tech_book ADD INDEX tech_book_id_name (id, name)
+ want:
+ - status: WARN
+ code: 303
+ title: naming.index.idx
+ content: Index in table `tech_book` mismatches the naming convention, expect "^$|^idx_tech_book_id_name$" but found `tech_book_id_name`
+ line: 2
+ details: ""
+- statement: CREATE TABLE tech_book_copy(id INT PRIMARY KEY, name VARCHAR(20), INDEX idx_tech_book_copy_name (name))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE tech_book_copy(id INT PRIMARY KEY, name VARCHAR(20), INDEX (name))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/naming_index_uk.yaml b/backend/plugin/advisor/tidb/test/naming_index_uk.yaml
new file mode 100644
index 0000000000..abe7b98e56
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/naming_index_uk.yaml
@@ -0,0 +1,86 @@
+- statement: CREATE UNIQUE INDEX uk_tech_book_id_name ON tech_book(id, name)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE UNIQUE INDEX tech_book_id_name ON tech_book(id, name)
+ want:
+ - status: WARN
+ code: 304
+ title: naming.index.uk
+ content: Unique key in table `tech_book` mismatches the naming convention, expect "^$|^uk_tech_book_id_name$" but found `tech_book_id_name`
+ line: 2
+ details: ""
+- statement: CREATE UNIQUE INDEX qtzmquwvlnttctfluoouxelxeliltcfzzstrtyocogwwyiyrflmrkbhbfasynlacy ON tech_book(id, name)
+ want:
+ - status: WARN
+ code: 304
+ title: naming.index.uk
+ content: Unique key `qtzmquwvlnttctfluoouxelxeliltcfzzstrtyocogwwyiyrflmrkbhbfasynlacy` in table `tech_book` mismatches the naming convention, its length should be within 64 characters
+ line: 2
+ details: ""
+ - status: WARN
+ code: 304
+ title: naming.index.uk
+ content: Unique key in table `tech_book` mismatches the naming convention, expect "^$|^uk_tech_book_id_name$" but found `qtzmquwvlnttctfluoouxelxeliltcfzzstrtyocogwwyiyrflmrkbhbfasynlacy`
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book ADD UNIQUE uk_tech_book_id_name (id, name)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: ALTER TABLE tech_book ADD UNIQUE tech_book_id_name (id, name)
+ want:
+ - status: WARN
+ code: 304
+ title: naming.index.uk
+ content: Unique key in table `tech_book` mismatches the naming convention, expect "^$|^uk_tech_book_id_name$" but found `tech_book_id_name`
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book RENAME INDEX old_uk TO uk_tech_book_id_name
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: ALTER TABLE tech_book RENAME INDEX old_uk TO uk_tech_book
+ want:
+ - status: WARN
+ code: 304
+ title: naming.index.uk
+ content: Unique key in table `tech_book` mismatches the naming convention, expect "^$|^uk_tech_book_id_name$" but found `uk_tech_book`
+ line: 2
+ details: ""
+- statement: CREATE TABLE book(id INT PRIMARY KEY, name VARCHAR(20), UNIQUE INDEX uk_book_name (name))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE book(id INT PRIMARY KEY, name VARCHAR(20), UNIQUE KEY (name))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE book(id INT PRIMARY KEY, name VARCHAR(20), UNIQUE INDEX (name))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/naming_table.yaml b/backend/plugin/advisor/tidb/test/naming_table.yaml
index 0a879c1070..c6990b158a 100644
--- a/backend/plugin/advisor/tidb/test/naming_table.yaml
+++ b/backend/plugin/advisor/tidb/test/naming_table.yaml
@@ -19,7 +19,7 @@
- status: WARN
code: 301
title: naming.table
- content: "`cjnubexocfhqoogdmihudyahmmghviqkzvpixnwvxtxumvuannpwdcbtsgwrvzpde` mismatches table naming convention, its length should be within 64 characters"
+ content: '`cjnubexocfhqoogdmihudyahmmghviqkzvpixnwvxtxumvuannpwdcbtsgwrvzpde` mismatches table naming convention, its length should be within 64 characters'
line: 2
details: ""
- statement: ALTER TABLE tech_book RENAME TO TechBook
diff --git a/backend/plugin/advisor/tidb/test/schema_backward_compatibility.yaml b/backend/plugin/advisor/tidb/test/schema_backward_compatibility.yaml
new file mode 100644
index 0000000000..4513d1535f
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/schema_backward_compatibility.yaml
@@ -0,0 +1,50 @@
+- statement: ALTER TABLE tech_book CHANGE name f2 TEXT
+ want:
+ - status: WARN
+ code: 111
+ title: schema.backward-compatibility
+ content: |-
+ "ALTER TABLE tech_book CHANGE name f2 TEXT
+ ;" may cause incompatibility with the existing data and code
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book MODIFY name TEXT
+ want:
+ - status: WARN
+ code: 111
+ title: schema.backward-compatibility
+ content: |-
+ "ALTER TABLE tech_book MODIFY name TEXT
+ ;" may cause incompatibility with the existing data and code
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book MODIFY name TEXT NULL
+ want:
+ - status: WARN
+ code: 111
+ title: schema.backward-compatibility
+ content: |-
+ "ALTER TABLE tech_book MODIFY name TEXT NULL
+ ;" may cause incompatibility with the existing data and code
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book MODIFY name TEXT NOT NULL
+ want:
+ - status: WARN
+ code: 111
+ title: schema.backward-compatibility
+ content: |-
+ "ALTER TABLE tech_book MODIFY name TEXT NOT NULL
+ ;" may cause incompatibility with the existing data and code
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book MODIFY name TEXT COMMENT 'bla'
+ want:
+ - status: WARN
+ code: 111
+ title: schema.backward-compatibility
+ content: |-
+ "ALTER TABLE tech_book MODIFY name TEXT COMMENT 'bla'
+ ;" may cause incompatibility with the existing data and code
+ line: 2
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/statement_affected_row_limit.yaml b/backend/plugin/advisor/tidb/test/statement_affected_row_limit.yaml
new file mode 100644
index 0000000000..58391995e6
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/statement_affected_row_limit.yaml
@@ -0,0 +1,16 @@
+- statement: DELETE FROM tech_book WHERE a > 1
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: UPDATE tech_book SET id = 1
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/statement_disallow_commit.yaml b/backend/plugin/advisor/tidb/test/statement_disallow_commit.yaml
new file mode 100644
index 0000000000..632bb3b3ee
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/statement_disallow_commit.yaml
@@ -0,0 +1,40 @@
+- statement: |-
+ START TRANSACTION;
+ CREATE TABLE techBook(id int, name varchar(255));
+ COMMIT;
+ want:
+ - status: WARN
+ code: 206
+ title: statement.disallow-commit
+ content: |-
+ Commit is not allowed, related statement: "
+ COMMIT
+ ;"
+ line: 4
+ details: ""
+- statement: |-
+ START TRANSACTION;
+ CREATE TABLE techBook(id int, name varchar(255));
+ COMMIT;
+
+ START TRANSACTION;
+ INSERT INTO techBook(id, name) VALUES(1, "book");
+ COMMIT;
+ want:
+ - status: WARN
+ code: 206
+ title: statement.disallow-commit
+ content: |-
+ Commit is not allowed, related statement: "
+ COMMIT;"
+ line: 3
+ details: ""
+ - status: WARN
+ code: 206
+ title: statement.disallow-commit
+ content: |-
+ Commit is not allowed, related statement: "
+ COMMIT
+ ;"
+ line: 8
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/statement_disallow_limit.yaml b/backend/plugin/advisor/tidb/test/statement_disallow_limit.yaml
new file mode 100644
index 0000000000..71b6916a92
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/statement_disallow_limit.yaml
@@ -0,0 +1,48 @@
+- statement: ""
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: INSERT INTO tech_book SELECT * FROM tech_book LIMIT 1
+ want:
+ - status: WARN
+ code: 1103
+ title: statement.disallow-limit
+ content: |-
+ LIMIT clause is forbidden in INSERT, UPDATE and DELETE statement, but "INSERT INTO tech_book SELECT * FROM tech_book LIMIT 1
+ ;" uses
+ line: 2
+ details: ""
+- statement: INSERT INTO tech_book SELECT * FROM tech_book UNION SELECT * FROM tech_book LIMIT 1
+ want:
+ - status: WARN
+ code: 1103
+ title: statement.disallow-limit
+ content: |-
+ LIMIT clause is forbidden in INSERT, UPDATE and DELETE statement, but "INSERT INTO tech_book SELECT * FROM tech_book UNION SELECT * FROM tech_book LIMIT 1
+ ;" uses
+ line: 2
+ details: ""
+- statement: UPDATE tech_book SET name = 'my name' LIMIT 10
+ want:
+ - status: WARN
+ code: 1102
+ title: statement.disallow-limit
+ content: |-
+ LIMIT clause is forbidden in INSERT, UPDATE and DELETE statement, but "UPDATE tech_book SET name = 'my name' LIMIT 10
+ ;" uses
+ line: 2
+ details: ""
+- statement: DELETE FROM tech_book LIMIT 10
+ want:
+ - status: WARN
+ code: 1106
+ title: statement.disallow-limit
+ content: |-
+ LIMIT clause is forbidden in INSERT, UPDATE and DELETE statement, but "DELETE FROM tech_book LIMIT 10
+ ;" uses
+ line: 2
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/statement_disallow_order_by.yaml b/backend/plugin/advisor/tidb/test/statement_disallow_order_by.yaml
new file mode 100644
index 0000000000..06853d65b6
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/statement_disallow_order_by.yaml
@@ -0,0 +1,28 @@
+- statement: INSERT INTO tech_book values(1, 'a')
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: UPDATE tech_book SET name = 'my name' ORDER BY id
+ want:
+ - status: WARN
+ code: 1104
+ title: statement.disallow-order-by
+ content: |-
+ ORDER BY clause is forbidden in DELETE and UPDATE statements, but "UPDATE tech_book SET name = 'my name' ORDER BY id
+ ;" uses
+ line: 2
+ details: ""
+- statement: DELETE FROM tech_book ORDER BY id
+ want:
+ - status: WARN
+ code: 1105
+ title: statement.disallow-order-by
+ content: |-
+ ORDER BY clause is forbidden in DELETE and UPDATE statements, but "DELETE FROM tech_book ORDER BY id
+ ;" uses
+ line: 2
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/statement_dml_dry_run.yaml b/backend/plugin/advisor/tidb/test/statement_dml_dry_run.yaml
new file mode 100644
index 0000000000..c9f492fe7a
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/statement_dml_dry_run.yaml
@@ -0,0 +1,16 @@
+- statement: INSERT INTO tech_book values(1, 'a')
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: DELETE FROM tech_book
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/statement_insert_disallow_order_by_rand.yaml b/backend/plugin/advisor/tidb/test/statement_insert_disallow_order_by_rand.yaml
new file mode 100644
index 0000000000..2180032bc7
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/statement_insert_disallow_order_by_rand.yaml
@@ -0,0 +1,18 @@
+- statement: INSERT INTO tech_book VALUES(1, "a")
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: INSERT INTO tech_book SELECT * FROM tech_book ORDER BY rand()
+ want:
+ - status: WARN
+ code: 1108
+ title: statement.insert.disallow-order-by-rand
+ content: |-
+ "INSERT INTO tech_book SELECT * FROM tech_book ORDER BY rand()
+ ;" uses ORDER BY RAND in the INSERT statement
+ line: 2
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/statement_insert_must_specify_column.yaml b/backend/plugin/advisor/tidb/test/statement_insert_must_specify_column.yaml
new file mode 100644
index 0000000000..c6a5a25d87
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/statement_insert_must_specify_column.yaml
@@ -0,0 +1,18 @@
+- statement: INSERT INTO tech_book(id, name) VALUES (1, '1')
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: INSERT INTO tech_book VALUES (1, '1')
+ want:
+ - status: WARN
+ code: 1107
+ title: statement.insert.must-specify-column
+ content: |-
+ The INSERT statement must specify columns but "INSERT INTO tech_book VALUES (1, '1')
+ ;" does not
+ line: 2
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/statement_merge_alter_table.yaml b/backend/plugin/advisor/tidb/test/statement_merge_alter_table.yaml
new file mode 100644
index 0000000000..5f32202d5d
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/statement_merge_alter_table.yaml
@@ -0,0 +1,54 @@
+- statement: ALTER TABLE tech_book ADD COLUMN a int
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ ALTER TABLE tech_book ADD COLUMN a int;
+ ALTER TABLE tech_book ADD COLUMN b int;
+ want:
+ - status: WARN
+ code: 207
+ title: statement.merge-alter-table
+ content: There are 2 statements to modify table `tech_book`
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE tech_book ADD COLUMN a int;
+ ALTER TABLE t ADD COLUMN b int;
+ ALTER TABLE tech_book ADD COLUMN b int;
+ want:
+ - status: WARN
+ code: 207
+ title: statement.merge-alter-table
+ content: There are 2 statements to modify table `t`
+ line: 3
+ details: ""
+ - status: WARN
+ code: 207
+ title: statement.merge-alter-table
+ content: There are 2 statements to modify table `tech_book`
+ line: 5
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE tech_book ADD COLUMN a int;
+ ALTER TABLE tech_book ADD COLUMN b int;
+ ALTER TABLE t ADD COLUMN b int;
+ want:
+ - status: WARN
+ code: 207
+ title: statement.merge-alter-table
+ content: There are 2 statements to modify table `tech_book`
+ line: 3
+ details: ""
+ - status: WARN
+ code: 207
+ title: statement.merge-alter-table
+ content: There are 2 statements to modify table `t`
+ line: 5
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/statement_select_no_select_all.yaml b/backend/plugin/advisor/tidb/test/statement_select_no_select_all.yaml
new file mode 100644
index 0000000000..79fd5cf005
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/statement_select_no_select_all.yaml
@@ -0,0 +1,28 @@
+- statement: SELECT * FROM t
+ want:
+ - status: WARN
+ code: 203
+ title: statement.select.no-select-all
+ content: |-
+ "SELECT * FROM t
+ ;" uses SELECT all
+ line: 2
+ details: ""
+- statement: SELECT a, b FROM t
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: SELECT a, b FROM (SELECT * from t1 JOIN t2) t
+ want:
+ - status: WARN
+ code: 203
+ title: statement.select.no-select-all
+ content: |-
+ "SELECT a, b FROM (SELECT * from t1 JOIN t2) t
+ ;" uses SELECT all
+ line: 2
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/statement_where_no_leading_wildcard_like.yaml b/backend/plugin/advisor/tidb/test/statement_where_no_leading_wildcard_like.yaml
new file mode 100644
index 0000000000..9827bafcfa
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/statement_where_no_leading_wildcard_like.yaml
@@ -0,0 +1,48 @@
+- statement: SELECT * FROM t WHERE a LIKE 'abc%'
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: SELECT * FROM t WHERE a LIKE '%abc'
+ want:
+ - status: WARN
+ code: 204
+ title: statement.where.no-leading-wildcard-like
+ content: |-
+ "SELECT * FROM t WHERE a LIKE '%abc'
+ ;" uses leading wildcard LIKE
+ line: 2
+ details: ""
+- statement: SELECT * FROM t WHERE a LIKE 'abc' OR a LIKE '%abc'
+ want:
+ - status: WARN
+ code: 204
+ title: statement.where.no-leading-wildcard-like
+ content: |-
+ "SELECT * FROM t WHERE a LIKE 'abc' OR a LIKE '%abc'
+ ;" uses leading wildcard LIKE
+ line: 2
+ details: ""
+- statement: SELECT * FROM t WHERE a LIKE '%acc' OR a LIKE '%abc'
+ want:
+ - status: WARN
+ code: 204
+ title: statement.where.no-leading-wildcard-like
+ content: |-
+ "SELECT * FROM t WHERE a LIKE '%acc' OR a LIKE '%abc'
+ ;" uses leading wildcard LIKE
+ line: 2
+ details: ""
+- statement: SELECT * FROM (SELECT * FROM t WHERE a LIKE '%acc' OR a LIKE '%abc') t1
+ want:
+ - status: WARN
+ code: 204
+ title: statement.where.no-leading-wildcard-like
+ content: |-
+ "SELECT * FROM (SELECT * FROM t WHERE a LIKE '%acc' OR a LIKE '%abc') t1
+ ;" uses leading wildcard LIKE
+ line: 2
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/statement_where_require.yaml b/backend/plugin/advisor/tidb/test/statement_where_require.yaml
new file mode 100644
index 0000000000..71011e6780
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/statement_where_require.yaml
@@ -0,0 +1,72 @@
+- statement: INSERT INTO tech_book(id) values (1)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: DELETE FROM tech_book
+ want:
+ - status: WARN
+ code: 202
+ title: statement.where.require
+ content: |-
+ "DELETE FROM tech_book
+ ;" requires WHERE clause
+ line: 2
+ details: ""
+- statement: UPDATE tech_book SET id = 1
+ want:
+ - status: WARN
+ code: 202
+ title: statement.where.require
+ content: |-
+ "UPDATE tech_book SET id = 1
+ ;" requires WHERE clause
+ line: 2
+ details: ""
+- statement: DELETE FROM tech_book WHERE id > 0
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: UPDATE tech_book SET id = 1 WHERE id > 10
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: SELECT id FROM tech_book
+ want:
+ - status: WARN
+ code: 202
+ title: statement.where.require
+ content: |-
+ "SELECT id FROM tech_book
+ ;" requires WHERE clause
+ line: 2
+ details: ""
+- statement: SELECT id FROM tech_book WHERE id > 0
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: SELECT id FROM tech_book WHERE id > (SELECT max(id) FROM tech_book)
+ want:
+ - status: WARN
+ code: 202
+ title: statement.where.require
+ content: |-
+ "SELECT id FROM tech_book WHERE id > (SELECT max(id) FROM tech_book)
+ ;" requires WHERE clause
+ line: 2
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/system_charset_allowlist.yaml b/backend/plugin/advisor/tidb/test/system_charset_allowlist.yaml
new file mode 100644
index 0000000000..15fd1018fd
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/system_charset_allowlist.yaml
@@ -0,0 +1,106 @@
+- statement: CREATE TABLE t(a int) CHARSET utf8mb4
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(a varchar(255))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(a int) CHARSET ascii
+ want:
+ - status: WARN
+ code: 1001
+ title: system.charset.allowlist
+ content: |-
+ "CREATE TABLE t(a int) CHARSET ascii
+ ;" used disabled charset 'ascii'
+ line: 2
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t CHARSET ascii
+ want:
+ - status: WARN
+ code: 1001
+ title: system.charset.allowlist
+ content: |-
+ "
+ ALTER TABLE t CHARSET ascii
+ ;" used disabled charset 'ascii'
+ line: 3
+ details: ""
+- statement: ALTER DATABASE test CHARSET ascii
+ want:
+ - status: WARN
+ code: 1001
+ title: system.charset.allowlist
+ content: |-
+ "ALTER DATABASE test CHARSET ascii
+ ;" used disabled charset 'ascii'
+ line: 2
+ details: ""
+- statement: CREATE TABLE t(a varchar(255) CHARSET ascii)
+ want:
+ - status: WARN
+ code: 1001
+ title: system.charset.allowlist
+ content: |-
+ "CREATE TABLE t(a varchar(255) CHARSET ascii)
+ ;" used disabled charset 'ascii'
+ line: 1
+ details: ""
+- statement: |-
+ CREATE TABLE t(b int);
+ ALTER TABLE t ADD COLUMN a varchar(255) CHARSET ascii
+ want:
+ - status: WARN
+ code: 1001
+ title: system.charset.allowlist
+ content: |-
+ "
+ ALTER TABLE t ADD COLUMN a varchar(255) CHARSET ascii
+ ;" used disabled charset 'ascii'
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t MODIFY COLUMN a varchar(255) CHARSET ascii
+ want:
+ - status: WARN
+ code: 1001
+ title: system.charset.allowlist
+ content: |-
+ "
+ ALTER TABLE t MODIFY COLUMN a varchar(255) CHARSET ascii
+ ;" used disabled charset 'ascii'
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t CHANGE COLUMN a a varchar(255) CHARSET ascii
+ want:
+ - status: WARN
+ code: 1001
+ title: system.charset.allowlist
+ content: |-
+ "
+ ALTER TABLE t CHANGE COLUMN a a varchar(255) CHARSET ascii
+ ;" used disabled charset 'ascii'
+ line: 3
+ details: ""
+- statement: /* this is a comment */
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/system_collation_allowlist.yaml b/backend/plugin/advisor/tidb/test/system_collation_allowlist.yaml
new file mode 100644
index 0000000000..cdba824bb8
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/system_collation_allowlist.yaml
@@ -0,0 +1,100 @@
+- statement: CREATE TABLE t(a int) COLLATE utf8mb4_polish_ci
+ want:
+ - status: WARN
+ code: 1201
+ title: system.collation.allowlist
+ content: |-
+ "CREATE TABLE t(a int) COLLATE utf8mb4_polish_ci
+ ;" used disabled collation 'utf8mb4_polish_ci'
+ line: 2
+ details: ""
+- statement: CREATE TABLE t(a varchar(255))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(a int) COLLATE latin1_bin
+ want:
+ - status: WARN
+ code: 1201
+ title: system.collation.allowlist
+ content: |-
+ "CREATE TABLE t(a int) COLLATE latin1_bin
+ ;" used disabled collation 'latin1_bin'
+ line: 2
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t COLLATE latin1_bin
+ want:
+ - status: WARN
+ code: 1201
+ title: system.collation.allowlist
+ content: |-
+ "
+ ALTER TABLE t COLLATE latin1_bin
+ ;" used disabled collation 'latin1_bin'
+ line: 3
+ details: ""
+- statement: ALTER DATABASE test COLLATE latin1_bin
+ want:
+ - status: WARN
+ code: 1201
+ title: system.collation.allowlist
+ content: |-
+ "ALTER DATABASE test COLLATE latin1_bin
+ ;" used disabled collation 'latin1_bin'
+ line: 2
+ details: ""
+- statement: CREATE TABLE t(a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin)
+ want:
+ - status: WARN
+ code: 1201
+ title: system.collation.allowlist
+ content: |-
+ "CREATE TABLE t(a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin)
+ ;" used disabled collation 'latin1_bin'
+ line: 1
+ details: ""
+- statement: |-
+ CREATE TABLE t(b int);
+ ALTER TABLE t ADD COLUMN a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin
+ want:
+ - status: WARN
+ code: 1201
+ title: system.collation.allowlist
+ content: |-
+ "
+ ALTER TABLE t ADD COLUMN a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin
+ ;" used disabled collation 'latin1_bin'
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t MODIFY COLUMN a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin
+ want:
+ - status: WARN
+ code: 1201
+ title: system.collation.allowlist
+ content: |-
+ "
+ ALTER TABLE t MODIFY COLUMN a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin
+ ;" used disabled collation 'latin1_bin'
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int);
+ ALTER TABLE t CHANGE COLUMN a a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin
+ want:
+ - status: WARN
+ code: 1201
+ title: system.collation.allowlist
+ content: |-
+ "
+ ALTER TABLE t CHANGE COLUMN a a varchar(255) CHARACTER SET latin1 COLLATE latin1_bin
+ ;" used disabled collation 'latin1_bin'
+ line: 3
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/table_comment.yaml b/backend/plugin/advisor/tidb/test/table_comment.yaml
new file mode 100644
index 0000000000..6a2833b108
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/table_comment.yaml
@@ -0,0 +1,24 @@
+- statement: CREATE TABLE t(a int) COMMENT 'some comments'
+ want:
+ - status: WARN
+ code: 606
+ title: table.comment
+ content: The length of table `t` comment should be within 10 characters
+ line: 2
+ details: ""
+- statement: CREATE TABLE t(a int)
+ want:
+ - status: WARN
+ code: 605
+ title: table.comment
+ content: Table `t` requires comments
+ line: 2
+ details: ""
+- statement: CREATE TABLE t(a int) COMMENT 'sdlfkjalkseblkjduafelbnlsdfkljayue'
+ want:
+ - status: WARN
+ code: 606
+ title: table.comment
+ content: The length of table `t` comment should be within 10 characters
+ line: 2
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/table_disallow_partition.yaml b/backend/plugin/advisor/tidb/test/table_disallow_partition.yaml
new file mode 100644
index 0000000000..0d5307a0ae
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/table_disallow_partition.yaml
@@ -0,0 +1,42 @@
+- statement: CREATE TABLE t(a int)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(a int) PARTITION BY RANGE (a) (
+ PARTITION p0 VALUES LESS THAN (6),
+ PARTITION p1 VALUES LESS THAN (11)
+ )
+ want:
+ - status: WARN
+ code: 608
+ title: table.disallow-partition
+ content: |-
+ Table partition is forbidden, but "CREATE TABLE t(a int) PARTITION BY RANGE (a) (
+ PARTITION p0 VALUES LESS THAN (6),
+ PARTITION p1 VALUES LESS THAN (11)
+ )
+ ;" creates
+ line: 5
+ details: ""
+- statement: |-
+ ALTER TABLE tech_book PARTITION BY RANGE (a) (
+ PARTITION p0 VALUES LESS THAN (6),
+ PARTITION p1 VALUES LESS THAN (11)
+ )
+ want:
+ - status: WARN
+ code: 608
+ title: table.disallow-partition
+ content: |-
+ Table partition is forbidden, but "ALTER TABLE tech_book PARTITION BY RANGE (a) (
+ PARTITION p0 VALUES LESS THAN (6),
+ PARTITION p1 VALUES LESS THAN (11)
+ )
+ ;" creates
+ line: 5
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/table_drop_naming_convention.yaml b/backend/plugin/advisor/tidb/test/table_drop_naming_convention.yaml
new file mode 100644
index 0000000000..0394c75b06
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/table_drop_naming_convention.yaml
@@ -0,0 +1,24 @@
+- statement: DROP TABLE IF EXISTS foo_delete
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: DROP TABLE IF EXISTS foo
+ want:
+ - status: WARN
+ code: 603
+ title: table.drop-naming-convention
+ content: '`foo` mismatches drop table naming convention, naming format should be "_delete$"'
+ line: 2
+ details: ""
+- statement: DROP TABLE IF EXISTS foo_delete, bar
+ want:
+ - status: WARN
+ code: 603
+ title: table.drop-naming-convention
+ content: '`bar` mismatches drop table naming convention, naming format should be "_delete$"'
+ line: 2
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/table_no_foreign_key.yaml b/backend/plugin/advisor/tidb/test/table_no_foreign_key.yaml
new file mode 100644
index 0000000000..2657588ef9
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/table_no_foreign_key.yaml
@@ -0,0 +1,16 @@
+- statement: ALTER TABLE tech_book ADD CONSTRAINT fk_tech_book_author_id_author_id FOREIGN KEY (author_id) REFERENCES author (id)
+ want:
+ - status: WARN
+ code: 602
+ title: table.no-foreign-key
+ content: Foreign key is not allowed in the table `tech_book`
+ line: 2
+ details: ""
+- statement: CREATE TABLE book(id INT, author_id INT, FOREIGN KEY fk_book_author_id_author_id (author_id) REFERENCES author (id))
+ want:
+ - status: WARN
+ code: 602
+ title: table.no-foreign-key
+ content: Foreign key is not allowed in the table `book`
+ line: 1
+ details: ""
diff --git a/backend/plugin/advisor/tidb/test/table_require_pk.yaml b/backend/plugin/advisor/tidb/test/table_require_pk.yaml
new file mode 100644
index 0000000000..26a04ea666
--- /dev/null
+++ b/backend/plugin/advisor/tidb/test/table_require_pk.yaml
@@ -0,0 +1,156 @@
+- statement: CREATE TABLE t(id INT PRIMARY KEY)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(id INT, PRIMARY KEY (id))
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: CREATE TABLE t(id INT)
+ want:
+ - status: WARN
+ code: 601
+ title: table.require-pk
+ content: Table `t` requires PRIMARY KEY
+ line: 2
+ details: ""
+- statement: |-
+ CREATE TABLE t(id INT);
+ DROP TABLE t
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(id INT);
+ ALTER TABLE t ADD CONSTRAINT PRIMARY KEY (id)
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(id INT PRIMARY KEY);
+ ALTER TABLE t DROP PRIMARY KEY
+ want:
+ - status: WARN
+ code: 601
+ title: table.require-pk
+ content: Table `t` requires PRIMARY KEY
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(id INT PRIMARY KEY);
+ ALTER TABLE t DROP INDEX `PRIMARY`
+ want:
+ - status: WARN
+ code: 601
+ title: table.require-pk
+ content: Table `t` requires PRIMARY KEY
+ line: 3
+ details: ""
+- statement: |-
+ CREATE TABLE t(id INT);
+ ALTER TABLE t ADD COLUMN name varchar(30) PRIMARY KEY
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(id INT);
+ ALTER TABLE t CHANGE COLUMN id id INT PRIMARY KEY
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: ALTER TABLE tech_book CHANGE COLUMN id uid INT
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(id INT);
+ ALTER TABLE t MODIFY COLUMN id INT PRIMARY KEY
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: ALTER TABLE tech_book MODIFY COLUMN id INT
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(id INT, name varchar(30), PRIMARY KEY(id, name));
+ ALTER TABLE t DROP COLUMN id
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ CREATE TABLE t(id INT, name varchar(30), comment varchar(255), PRIMARY KEY(id, name));
+ ALTER TABLE t DROP COLUMN id, DROP COLUMN name
+ want:
+ - status: WARN
+ code: 601
+ title: table.require-pk
+ content: Table `t` requires PRIMARY KEY
+ line: 3
+ details: ""
+- statement: ALTER TABLE tech_book ADD COLUMN a int, DROP COLUMN id, DROP COLUMN name
+ want:
+ - status: WARN
+ code: 601
+ title: table.require-pk
+ content: Table `tech_book` requires PRIMARY KEY
+ line: 2
+ details: ""
+- statement: ALTER TABLE tech_book DROP COLUMN name
+ want:
+ - status: SUCCESS
+ code: 0
+ title: OK
+ content: ""
+ line: 0
+ details: ""
+- statement: |-
+ ALTER TABLE tech_book CHANGE COLUMN id uid int;
+ ALTER TABLE tech_book ADD COLUMN a int, DROP COLUMN uid, DROP COLUMN name
+ want:
+ - status: WARN
+ code: 601
+ title: table.require-pk
+ content: Table `tech_book` requires PRIMARY KEY
+ line: 3
+ details: ""
diff --git a/backend/plugin/advisor/tidb/tidb_rules_test.go b/backend/plugin/advisor/tidb/tidb_rules_test.go
index 131fadbbca..564854e5e6 100644
--- a/backend/plugin/advisor/tidb/tidb_rules_test.go
+++ b/backend/plugin/advisor/tidb/tidb_rules_test.go
@@ -7,9 +7,111 @@ import (
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
)
-func TestTiDBRules(t *testing.T) {
+func TestMySQLRules(t *testing.T) {
tidbRules := []advisor.SQLReviewRuleType{
+ // advisor.SchemaRuleTableNaming enforce the table name format.
advisor.SchemaRuleTableNaming,
+ // advisor.SchemaRuleColumnNaming enforce the column name format.
+ advisor.SchemaRuleColumnNaming,
+ // advisor.SchemaRuleUKNaming enforce the unique key name format.
+ advisor.SchemaRuleUKNaming,
+ // advisor.SchemaRuleFKNaming enforce the foreign key name format.
+ advisor.SchemaRuleFKNaming,
+ // advisor.SchemaRuleIDXNaming enforce the index name format.
+ advisor.SchemaRuleIDXNaming,
+ // advisor.SchemaRuleAutoIncrementColumnNaming enforce the auto_increment column name format.
+ advisor.SchemaRuleAutoIncrementColumnNaming,
+
+ // advisor.SchemaRuleStatementNoSelectAll disallow 'SELECT *'.
+ advisor.SchemaRuleStatementNoSelectAll,
+ // advisor.SchemaRuleStatementRequireWhere require 'WHERE' clause.
+ advisor.SchemaRuleStatementRequireWhere,
+ // advisor.SchemaRuleStatementNoLeadingWildcardLike disallow leading '%' in LIKE, e.g. LIKE foo = '%x' is not allowed.
+ advisor.SchemaRuleStatementNoLeadingWildcardLike,
+ // advisor.SchemaRuleStatementDisallowCommit disallow using commit in the issue.
+ advisor.SchemaRuleStatementDisallowCommit,
+ // advisor.SchemaRuleStatementDisallowLimit disallow the LIMIT clause in INSERT, DELETE and UPDATE statements.
+ advisor.SchemaRuleStatementDisallowLimit,
+ // advisor.SchemaRuleStatementDisallowOrderBy disallow the ORDER BY clause in DELETE and UPDATE statements.
+ advisor.SchemaRuleStatementDisallowOrderBy,
+ // advisor.SchemaRuleStatementMergeAlterTable disallow redundant ALTER TABLE statements.
+ advisor.SchemaRuleStatementMergeAlterTable,
+ // advisor.SchemaRuleStatementInsertMustSpecifyColumn enforce the insert column specified.
+ advisor.SchemaRuleStatementInsertMustSpecifyColumn,
+ // advisor.SchemaRuleStatementInsertDisallowOrderByRand disallow the order by rand in the INSERT statement.
+ advisor.SchemaRuleStatementInsertDisallowOrderByRand,
+ // advisor.SchemaRuleStatementAffectedRowLimit enforce the UPDATE/DELETE affected row limit.
+ advisor.SchemaRuleStatementAffectedRowLimit,
+ // advisor.SchemaRuleStatementDMLDryRun dry run the dml.
+ advisor.SchemaRuleStatementDMLDryRun,
+
+ // advisor.SchemaRuleTableRequirePK require the table to have a primary key.
+ advisor.SchemaRuleTableRequirePK,
+ // advisor.SchemaRuleTableNoFK require the table disallow the foreign key.
+ advisor.SchemaRuleTableNoFK,
+ // advisor.SchemaRuleTableDropNamingConvention require only the table following the naming convention can be deleted.
+ advisor.SchemaRuleTableDropNamingConvention,
+ // advisor.SchemaRuleTableCommentConvention enforce the table comment convention.
+ advisor.SchemaRuleTableCommentConvention,
+ // advisor.SchemaRuleTableDisallowPartition disallow the table partition.
+ advisor.SchemaRuleTableDisallowPartition,
+
+ // advisor.SchemaRuleRequiredColumn enforce the required columns in each table.
+ advisor.SchemaRuleRequiredColumn,
+ // advisor.SchemaRuleColumnNotNull enforce the columns cannot have NULL value.
+ advisor.SchemaRuleColumnNotNull,
+ // advisor.SchemaRuleColumnDisallowChangeType disallow change column type.
+ advisor.SchemaRuleColumnDisallowChangeType,
+ // advisor.SchemaRuleColumnSetDefaultForNotNull require the not null column to set default value.
+ advisor.SchemaRuleColumnSetDefaultForNotNull,
+ // advisor.SchemaRuleColumnDisallowChange disallow CHANGE COLUMN statement.
+ advisor.SchemaRuleColumnDisallowChange,
+ // advisor.SchemaRuleColumnDisallowChangingOrder disallow changing column order.
+ advisor.SchemaRuleColumnDisallowChangingOrder,
+ // advisor.SchemaRuleColumnDisallowDropIndex disallow drop index column.
+ advisor.SchemaRuleColumnDisallowDropInIndex,
+ // advisor.SchemaRuleColumnCommentConvention enforce the column comment convention.
+ advisor.SchemaRuleColumnCommentConvention,
+ // advisor.SchemaRuleColumnAutoIncrementMustInteger require the auto-increment column to be integer.
+ advisor.SchemaRuleColumnAutoIncrementMustInteger,
+ // advisor.SchemaRuleColumnTypeDisallowList enforce the column type disallow list.
+ advisor.SchemaRuleColumnTypeDisallowList,
+ // advisor.SchemaRuleColumnDisallowSetCharset disallow set column charset.
+ advisor.SchemaRuleColumnDisallowSetCharset,
+ // advisor.SchemaRuleColumnMaximumCharacterLength enforce the maximum character length.
+ advisor.SchemaRuleColumnMaximumCharacterLength,
+ // advisor.SchemaRuleColumnAutoIncrementInitialValue enforce the initial auto-increment value.
+ advisor.SchemaRuleColumnAutoIncrementInitialValue,
+ // advisor.SchemaRuleColumnAutoIncrementMustUnsigned enforce the auto-increment column to be unsigned.
+ advisor.SchemaRuleColumnAutoIncrementMustUnsigned,
+ // advisor.SchemaRuleCurrentTimeColumnCountLimit enforce the current column count limit.
+ advisor.SchemaRuleCurrentTimeColumnCountLimit,
+ // advisor.SchemaRuleColumnRequireDefault enforce the column default.
+ advisor.SchemaRuleColumnRequireDefault,
+
+ // advisor.SchemaRuleSchemaBackwardCompatibility enforce the MySQL and TiDB support check whether the schema change is backward compatible.
+ advisor.SchemaRuleSchemaBackwardCompatibility,
+
+ // advisor.SchemaRuleDropEmptyDatabase enforce the MySQL and TiDB support check if the database is empty before users drop it.
+ advisor.SchemaRuleDropEmptyDatabase,
+
+ // advisor.SchemaRuleIndexNoDuplicateColumn require the index no duplicate column.
+ advisor.SchemaRuleIndexNoDuplicateColumn,
+ // advisor.SchemaRuleIndexKeyNumberLimit enforce the index key number limit.
+ advisor.SchemaRuleIndexKeyNumberLimit,
+ // advisor.SchemaRuleIndexPKTypeLimit enforce the type restriction of columns in primary key.
+ advisor.SchemaRuleIndexPKTypeLimit,
+ // advisor.SchemaRuleIndexTypeNoBlob enforce the type restriction of columns in index.
+ advisor.SchemaRuleIndexTypeNoBlob,
+ // advisor.SchemaRuleIndexTotalNumberLimit enforce the index total number limit.
+ advisor.SchemaRuleIndexTotalNumberLimit,
+ advisor.SchemaRuleIndexPrimaryKeyTypeAllowlist,
+
+ // advisor.SchemaRuleCharsetAllowlist enforce the charset allowlist.
+ advisor.SchemaRuleCharsetAllowlist,
+
+ // advisor.SchemaRuleCollationAllowlist enforce the collation allowlist.
+ advisor.SchemaRuleCollationAllowlist,
}
for _, rule := range tidbRules {
diff --git a/backend/plugin/advisor/tidb/utils.go b/backend/plugin/advisor/tidb/utils.go
new file mode 100644
index 0000000000..aa8c46bf29
--- /dev/null
+++ b/backend/plugin/advisor/tidb/utils.go
@@ -0,0 +1,53 @@
+// Package mysql implements the SQL advisor rules for MySQL.
+package tidb
+
+import (
+ "sort"
+ "strings"
+
+ "github.com/pingcap/tidb/parser/ast"
+ "github.com/pingcap/tidb/parser/format"
+)
+
+type columnSet map[string]bool
+
+func newColumnSet(columns []string) columnSet {
+ res := make(columnSet)
+ for _, col := range columns {
+ res[col] = true
+ }
+ return res
+}
+
+type tableState map[string]columnSet
+
+// tableList returns table list in lexicographical order.
+func (t tableState) tableList() []string {
+ var tableList []string
+ for tableName := range t {
+ tableList = append(tableList, tableName)
+ }
+ sort.Strings(tableList)
+ return tableList
+}
+
+type tablePK map[string]columnSet
+
+// tableList returns table list in lexicographical order.
+func (t tablePK) tableList() []string {
+ var tableList []string
+ for tableName := range t {
+ tableList = append(tableList, tableName)
+ }
+ sort.Strings(tableList)
+ return tableList
+}
+
+func restoreNode(node ast.Node, flag format.RestoreFlags) (string, error) {
+ var buffer strings.Builder
+ ctx := format.NewRestoreCtx(flag, &buffer)
+ if err := node.Restore(ctx); err != nil {
+ return "", err
+ }
+ return buffer.String(), nil
+}
diff --git a/backend/server/minimal_demo.go b/backend/server/minimal_demo.go
index 0ee027038a..db3a0c267a 100644
--- a/backend/server/minimal_demo.go
+++ b/backend/server/minimal_demo.go
@@ -16,6 +16,7 @@ import (
// Advisors.
_ "github.com/bytebase/bytebase/backend/plugin/advisor/mysql"
+ _ "github.com/bytebase/bytebase/backend/plugin/advisor/tidb"
// Transformers.
_ "github.com/bytebase/bytebase/backend/plugin/parser/sql/transform/mysql"