Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix: fix tests for get database metadata (#17172)
rebelice576d2bb424eb
diff --git a/backend/plugin/schema/mysql/get_database_metadata.go b/backend/plugin/schema/mysql/get_database_metadata.goindex 158fc66e5d..0535d3f82f 100644--- a/backend/plugin/schema/mysql/get_database_metadata.go+++ b/backend/plugin/schema/mysql/get_database_metadata.go@@ -27,15 +27,16 @@ func GetDatabaseMetadata(schemaText string) (*storepb.DatabaseSchemaMetadata, er}extractor := &metadataExtractor{- currentDatabase: "",- currentSchema: "",- tables: make(map[string]*storepb.TableMetadata),- views: make(map[string]*storepb.ViewMetadata),- functions: make(map[string]*storepb.FunctionMetadata),- procedures: make(map[string]*storepb.ProcedureMetadata),- triggers: make(map[string]*storepb.TriggerMetadata),- columnPrimaryKeys: make(map[string][]string),- columnUniqueKeys: make(map[string]map[string]bool),+ currentDatabase: "",+ currentSchema: "",+ tables: make(map[string]*storepb.TableMetadata),+ views: make(map[string]*storepb.ViewMetadata),+ functions: make(map[string]*storepb.FunctionMetadata),+ procedures: make(map[string]*storepb.ProcedureMetadata),+ triggers: make(map[string]*storepb.TriggerMetadata),+ columnPrimaryKeys: make(map[string][]string),+ columnUniqueKeys: make(map[string]map[string]bool),+ pendingForeignKeyIndexes: make(map[string][]*storepb.ForeignKeyMetadata),}// Walk each parse tree@@ -53,6 +54,8 @@ func GetDatabaseMetadata(schemaText string) (*storepb.DatabaseSchemaMetadata, erextractor.createColumnPrimaryKeyIndexes()// Create unique indexes from column-level definitionsextractor.createColumnUniqueKeyIndexes()+ // Create indexes for foreign keys that don't have existing suitable indexes+ extractor.createPendingForeignKeyIndexes()// Build the final metadata structureschemaMetadata := &storepb.DatabaseSchemaMetadata{@@ -125,7 +128,9 @@ type metadataExtractor struct {columnPrimaryKeys map[string][]string // tableName -> []columnNames// Track column-level unique constraints to create index entries latercolumnUniqueKeys map[string]map[string]bool // tableName -> columnName -> true- err error+ // Track foreign keys to create index entries after all table elements are processed+ pendingForeignKeyIndexes map[string][]*storepb.ForeignKeyMetadata // tableName -> []foreignKeys+ err error}// Helper function to get or create table@@ -183,9 +188,6 @@ func (e *metadataExtractor) EnterCreateTable(ctx *mysql.CreateTableContext) {// Extract table commente.extractTableComment(ctx, table)-- // Remove duplicate indexes after all processing is complete- e.removeDuplicateIndexes(table)}// extractTableElements extracts columns and constraints from table elements@@ -541,7 +543,7 @@ func (*metadataExtractor) extractPrimaryKey(ctx mysql.ITableConstraintDefContext}// extractForeignKey extracts foreign key constraint-func (*metadataExtractor) extractForeignKey(ctx mysql.ITableConstraintDefContext, table *storepb.TableMetadata) {+func (e *metadataExtractor) extractForeignKey(ctx mysql.ITableConstraintDefContext, table *storepb.TableMetadata) {if ctx.KeyList() == nil || ctx.References() == nil {return}@@ -625,48 +627,11 @@ func (*metadataExtractor) extractForeignKey(ctx mysql.ITableConstraintDefContexttable.ForeignKeys = append(table.ForeignKeys, fk)- // MySQL automatically creates indexes on foreign key columns if they don't exist- // Create an index for the foreign key columns if one doesn't already exist- if len(columns) > 0 {- // Check if an index already exists on these columns- indexExists := false- for _, existingIndex := range table.Indexes {- // Check if any existing index covers the foreign key columns- if len(existingIndex.Expressions) >= len(columns) {- // Check if the first N columns of the index match our FK columns- match := true- for i, fkCol := range columns {- if i >= len(existingIndex.Expressions) || existingIndex.Expressions[i] != fkCol {- match = false- break- }- }- if match {- indexExists = true- break- }- }- }-- // Create index if none exists- if !indexExists {- // Generate index name based on constraint name or columns- indexName := constraintName- if indexName == "" {- // Use first column name as index name if no constraint name- indexName = columns[0]- }-- fkIndex := &storepb.IndexMetadata{- Name: indexName,- Type: "BTREE",- Expressions: columns,- Primary: false,- Unique: false,- }- table.Indexes = append(table.Indexes, fkIndex)- }+ // Store the foreign key for later index creation (after all table elements are processed)+ if e.pendingForeignKeyIndexes[table.Name] == nil {+ e.pendingForeignKeyIndexes[table.Name] = []*storepb.ForeignKeyMetadata{}}+ e.pendingForeignKeyIndexes[table.Name] = append(e.pendingForeignKeyIndexes[table.Name], fk)}// extractIndex extracts regular index@@ -1206,94 +1171,6 @@ func isLiteralValue(value string) bool {return true}-// removeDuplicateIndexes removes duplicate indexes that cover the same columns-func (*metadataExtractor) removeDuplicateIndexes(table *storepb.TableMetadata) {- if len(table.Indexes) <= 1 {- return- }-- // Build a map of column signature to indexes- indexMap := make(map[string][]*storepb.IndexMetadata)- for _, index := range table.Indexes {- if len(index.Expressions) == 0 {- continue- }-- // Create a signature from the column expressions- signature := strings.Join(index.Expressions, ",")- indexMap[signature] = append(indexMap[signature], index)- }-- // Keep only unique indexes, preferring explicit indexes over auto-generated ones- var uniqueIndexes []*storepb.IndexMetadata- for _, indexes := range indexMap {- if len(indexes) == 1 {- // No duplicates, keep the index- uniqueIndexes = append(uniqueIndexes, indexes[0])- } else {- // Multiple indexes with same columns, pick the best one- bestIndex := chooseBestIndex(indexes)- uniqueIndexes = append(uniqueIndexes, bestIndex)- }- }-- table.Indexes = uniqueIndexes-}--// chooseBestIndex selects the best index from duplicates based on priority rules-func chooseBestIndex(indexes []*storepb.IndexMetadata) *storepb.IndexMetadata {- if len(indexes) == 1 {- return indexes[0]- }-- // Priority rules (higher priority first):- // 1. PRIMARY key indexes- // 2. UNIQUE indexes- // 3. Explicitly named indexes (not auto-generated by foreign keys)- // 4. Foreign key indexes-- var primaryIndex, uniqueIndex, explicitIndex, foreignKeyIndex *storepb.IndexMetadata-- for _, index := range indexes {- if index.Primary {- primaryIndex = index- } else if index.Unique {- uniqueIndex = index- } else if !isAutoGeneratedIndexName(index.Name) {- explicitIndex = index- } else {- foreignKeyIndex = index- }- }-- // Return in priority order- if primaryIndex != nil {- return primaryIndex- }- if uniqueIndex != nil {- return uniqueIndex- }- if explicitIndex != nil {- return explicitIndex- }- if foreignKeyIndex != nil {- return foreignKeyIndex- }-- // Fallback to first index- return indexes[0]-}--// isAutoGeneratedIndexName checks if an index name looks auto-generated-func isAutoGeneratedIndexName(name string) bool {- // Foreign key index names typically match constraint names- // Check if this looks like a foreign key constraint name- return strings.HasPrefix(name, "fk_") ||- strings.HasPrefix(name, "FK_") ||- strings.Contains(name, "_fkey") ||- strings.Contains(name, "_foreign")-}-// addColumnPrimaryKey tracks a column-level primary key definitionfunc (e *metadataExtractor) addColumnPrimaryKey(tableName, columnName string) {if e.columnPrimaryKeys[tableName] == nil {@@ -1381,6 +1258,61 @@ func (e *metadataExtractor) createColumnUniqueKeyIndexes() {}}+// createPendingForeignKeyIndexes creates index metadata for foreign keys that don't have existing suitable indexes+func (e *metadataExtractor) createPendingForeignKeyIndexes() {+ for tableName, foreignKeys := range e.pendingForeignKeyIndexes {+ table, exists := e.tables[tableName]+ if !exists {+ continue+ }++ for _, fk := range foreignKeys {+ // MySQL automatically creates indexes on foreign key columns if they don't already exist.+ // Check if an index already exists on these columns+ hasMatchingIndex := false+ for _, existingIndex := range table.Indexes {+ // Check if an index already covers the foreign key columns+ if len(existingIndex.Expressions) >= len(fk.Columns) {+ matches := true+ for i, col := range fk.Columns {+ if i >= len(existingIndex.Expressions) || existingIndex.Expressions[i] != col {+ matches = false+ break+ }+ }+ if matches {+ hasMatchingIndex = true+ break+ }+ }+ }++ // If no matching index exists, create one+ if !hasMatchingIndex {+ // MySQL creates indexes using the constraint name for foreign keys+ // If no constraint name is provided, MySQL would generate one automatically+ indexName := fk.Name+ if indexName == "" {+ // Fallback to column names if no constraint name (shouldn't happen in practice)+ indexName = fk.Columns[0]+ if len(fk.Columns) > 1 {+ indexName = strings.Join(fk.Columns, "_")+ }+ }++ index := &storepb.IndexMetadata{+ Name: indexName,+ Type: "BTREE",+ Expressions: fk.Columns,+ Primary: false,+ Unique: false,+ }+ table.Indexes = append(table.Indexes, index)+ }+ }+ }+}+// extractFulltextIndex extracts FULLTEXT indexfunc (*metadataExtractor) extractFulltextIndex(ctx mysql.ITableConstraintDefContext, table *storepb.TableMetadata) {// Extract index namediff --git a/backend/plugin/schema/mysql/get_database_metadata_testcontainer_test.go b/backend/plugin/schema/mysql/get_database_metadata_testcontainer_test.goindex 1aa33e3685..680140fb48 100644--- a/backend/plugin/schema/mysql/get_database_metadata_testcontainer_test.go+++ b/backend/plugin/schema/mysql/get_database_metadata_testcontainer_test.go@@ -696,35 +696,49 @@ func compareIndexes(t *testing.T, dbIndexes, parsedIndexes []*storepb.IndexMetaddbIndexMap[idx.Name] = idx}- parsedIndexMap := make(map[string]*storepb.IndexMetadata)- for _, idx := range parsedIndexes {- parsedIndexMap[idx.Name] = idx- }-- // Check that all parsed indexes exist in db- for name, parsedIdx := range parsedIndexMap {- dbIdx, exists := dbIndexMap[name]- if !exists {- // Skip if it's a generated index name- if strings.HasPrefix(name, "idx_") {- continue- }- t.Errorf("index %s on table %s not found in database metadata", name, tableName)- continue- }+ // Check that all parsed indexes exist in db with exact match+ for _, parsedIdx := range parsedIndexes {+ dbIdx, exists := dbIndexMap[parsedIdx.Name]+ require.True(t, exists, "index %s on table %s not found in database metadata", parsedIdx.Name, tableName)// Compare index propertiesrequire.Equal(t, dbIdx.Primary, parsedIdx.Primary,- "primary mismatch for index %s on table %s", name, tableName)+ "primary mismatch for index %s on table %s", parsedIdx.Name, tableName)require.Equal(t, dbIdx.Unique, parsedIdx.Unique,- "unique mismatch for index %s on table %s", name, tableName)+ "unique mismatch for index %s on table %s", parsedIdx.Name, tableName)- // Compare expressions (allowing for some differences in formatting)+ // Compare expressionsrequire.Equal(t, len(dbIdx.Expressions), len(parsedIdx.Expressions),- "expression count mismatch for index %s on table %s", name, tableName)+ "expression count mismatch for index %s on table %s", parsedIdx.Name, tableName)++ for i, expr := range parsedIdx.Expressions {+ if i < len(dbIdx.Expressions) {+ // Normalize expressions for comparison+ dbExpr := normalizeIndexExpression(dbIdx.Expressions[i])+ parsedExpr := normalizeIndexExpression(expr)+ require.Equal(t, dbExpr, parsedExpr,+ "expression mismatch for index %s on table %s at position %d", parsedIdx.Name, tableName, i)+ }+ }}}+// normalizeIndexExpression normalizes index expressions for comparison+func normalizeIndexExpression(expr string) string {+ // Remove backticks+ expr = strings.ReplaceAll(expr, "`", "")++ // Remove outer parentheses from expressions like "(year(created_at))"+ if strings.HasPrefix(expr, "(") && strings.HasSuffix(expr, ")") {+ expr = expr[1 : len(expr)-1]+ }++ // Convert to uppercase for case-insensitive comparison+ expr = strings.ToUpper(expr)++ return expr+}+func compareForeignKeys(t *testing.T, dbFKs, parsedFKs []*storepb.ForeignKeyMetadata, tableName string) {require.Equal(t, len(dbFKs), len(parsedFKs),"mismatch in number of foreign keys for table %s", tableName)diff --git a/backend/plugin/schema/oracle/get_database_metadata.go b/backend/plugin/schema/oracle/get_database_metadata.goindex 3956d36fde..d90026cc82 100644--- a/backend/plugin/schema/oracle/get_database_metadata.go+++ b/backend/plugin/schema/oracle/get_database_metadata.go@@ -28,6 +28,7 @@ func GetDatabaseMetadata(schemaText string) (*storepb.DatabaseSchemaMetadata, erextractor := &metadataExtractor{currentSchema: "",+ currentTable: "",tables: make(map[string]*storepb.TableMetadata),views: make(map[string]*storepb.ViewMetadata),materializedViews: make(map[string]*storepb.MaterializedViewMetadata),@@ -36,6 +37,8 @@ func GetDatabaseMetadata(schemaText string) (*storepb.DatabaseSchemaMetadata, ertriggers: make(map[string]*storepb.TriggerMetadata),sequences: make(map[string]*storepb.SequenceMetadata),packages: make(map[string]*storepb.PackageMetadata),+ inlinePrimaryKeys: make(map[string][]string),+ inlineUniqueKeys: make(map[string][]string),}// Walk the parse tree@@ -142,6 +145,7 @@ type metadataExtractor struct {currentDatabase stringcurrentSchema string+ currentTable string // Track current table being processedtables map[string]*storepb.TableMetadataviews map[string]*storepb.ViewMetadatamaterializedViews map[string]*storepb.MaterializedViewMetadata@@ -151,6 +155,8 @@ type metadataExtractor struct {sequences map[string]*storepb.SequenceMetadatapackages map[string]*storepb.PackageMetadataerr error+ inlinePrimaryKeys map[string][]string // Track inline primary key columns by table+ inlineUniqueKeys map[string][]string // Track inline unique key columns by table}// Helper function to get or create table@@ -192,12 +198,20 @@ func (e *metadataExtractor) EnterCreate_table(ctx *parser.Create_tableContext) {return}+ // Set current table for inline constraint tracking+ e.currentTable = tableNametable := e.getOrCreateTable(tableName)// Extract table elements (columns, constraints)if ctx.Relational_table() != nil {e.extractRelationalTable(ctx.Relational_table(), table)++ // Process inline constraints after all columns are parsed+ e.processInlineConstraints(tableName, table)}++ // Clear current table+ e.currentTable = ""}// EnterCreate_index is called when entering a create index statement@@ -697,7 +711,7 @@ func (*metadataExtractor) extractDataType(ctx parser.IDatatypeContext) string {}// extractInlineConstraint extracts inline column constraints-func (*metadataExtractor) extractInlineConstraint(ctx parser.IInline_constraintContext, column *storepb.ColumnMetadata) {+func (e *metadataExtractor) extractInlineConstraint(ctx parser.IInline_constraintContext, column *storepb.ColumnMetadata) {if ctx == nil {return}@@ -715,14 +729,25 @@ func (*metadataExtractor) extractInlineConstraint(ctx parser.IInline_constraintC// Handle PRIMARY KEY constraintif ctx.PRIMARY() != nil && ctx.KEY() != nil {column.Nullable = false- // Don't add any comment for primary key - this is structural information+ // Track this column for primary key index creation+ if e.currentTable != "" {+ if e.inlinePrimaryKeys[e.currentTable] == nil {+ e.inlinePrimaryKeys[e.currentTable] = []string{}+ }+ e.inlinePrimaryKeys[e.currentTable] = append(e.inlinePrimaryKeys[e.currentTable], column.Name)+ }}// Handle UNIQUE constraintif ctx.UNIQUE() != nil {// Note: UNIQUE columns can be nullable in Oracle- // Don't add any comment for unique constraint - this is structural information- _ = ctx.UNIQUE() // Acknowledge the context+ // Track this column for unique index creation+ if e.currentTable != "" {+ if e.inlineUniqueKeys[e.currentTable] == nil {+ e.inlineUniqueKeys[e.currentTable] = []string{}+ }+ e.inlineUniqueKeys[e.currentTable] = append(e.inlineUniqueKeys[e.currentTable], column.Name)+ }}// Handle CHECK constraint - check if the text contains CHECK keyword@@ -1375,3 +1400,67 @@ func getTextFromContext(ctx any) string {return ""}++// processInlineConstraints creates indexes for inline PRIMARY KEY and UNIQUE constraints+// This simulates Oracle's automatic index creation behavior+func (e *metadataExtractor) processInlineConstraints(tableName string, table *storepb.TableMetadata) {+ // Process inline primary key constraints+ if primaryKeyColumns := e.inlinePrimaryKeys[tableName]; len(primaryKeyColumns) > 0 {+ constraintName := fmt.Sprintf("PK_%s", tableName)++ // Check if a primary key index already exists (from out-of-line constraints)+ hasExistingPK := false+ for _, idx := range table.Indexes {+ if idx.Primary {+ hasExistingPK = true+ break+ }+ }++ // Oracle automatically creates a unique index for PRIMARY KEY constraints+ if !hasExistingPK {+ index := &storepb.IndexMetadata{+ Name: constraintName,+ Primary: true,+ Unique: true,+ Type: "NORMAL",+ Expressions: primaryKeyColumns,+ }+ table.Indexes = append(table.Indexes, index)+ }++ // Clean up the tracking+ delete(e.inlinePrimaryKeys, tableName)+ }++ // Process inline unique constraints+ if uniqueKeyColumns := e.inlineUniqueKeys[tableName]; len(uniqueKeyColumns) > 0 {+ for _, columnName := range uniqueKeyColumns {+ constraintName := fmt.Sprintf("UK_%s_%s", tableName, columnName)++ // Check if a unique index already exists for this column+ hasExistingUnique := false+ for _, idx := range table.Indexes {+ if idx.Unique && !idx.Primary && len(idx.Expressions) == 1 && idx.Expressions[0] == columnName {+ hasExistingUnique = true+ break+ }+ }++ // Oracle automatically creates a unique index for UNIQUE constraints+ if !hasExistingUnique {+ index := &storepb.IndexMetadata{+ Name: constraintName,+ Primary: false,+ Unique: true,+ Type: "NORMAL",+ Expressions: []string{columnName},+ }+ table.Indexes = append(table.Indexes, index)+ }+ }++ // Clean up the tracking+ delete(e.inlineUniqueKeys, tableName)+ }+}diff --git a/backend/plugin/schema/oracle/get_database_metadata_test.go b/backend/plugin/schema/oracle/get_database_metadata_test.goindex a2fbedaadc..d3871a6d31 100644--- a/backend/plugin/schema/oracle/get_database_metadata_test.go+++ b/backend/plugin/schema/oracle/get_database_metadata_test.go@@ -1145,6 +1145,9 @@ func compareIndexes(t *testing.T, dbIndexes, parsedIndexes []*storepb.IndexMetadparsedIndexMap[idx.Name] = idx}+ // Check that both directions have the same indexes+ require.Equal(t, len(dbIndexes), len(parsedIndexes), "mismatch in number of indexes for table %s", tableName)+// Compare each parsed indexfor idxName, parsedIdx := range parsedIndexMap {dbIdx, exists := dbIndexMap[idxName]@@ -1186,6 +1189,10 @@ func compareIndexes(t *testing.T, dbIndexes, parsedIndexes []*storepb.IndexMetad// compareForeignKeys compares foreign key metadatafunc compareForeignKeys(t *testing.T, dbFKs, parsedFKs []*storepb.ForeignKeyMetadata, _ string) {+ // TODO: Oracle foreign key parsing needs improvement - for now we only check that parsed FKs are correct+ // Full bidirectional comparison would require fixing the Oracle parser first+ // require.Equal(t, len(dbFKs), len(parsedFKs), "mismatch in number of foreign keys for table %s", tableName)+// Create maps for easier lookupdbFKMap := make(map[string]*storepb.ForeignKeyMetadata)for _, fk := range dbFKs {diff --git a/backend/plugin/schema/pg/get_database_metadata.go b/backend/plugin/schema/pg/get_database_metadata.goindex e96a7cb6cc..886ce9d8a8 100644--- a/backend/plugin/schema/pg/get_database_metadata.go+++ b/backend/plugin/schema/pg/get_database_metadata.go@@ -175,6 +175,21 @@ func (e *metadataExtractor) getOrCreateTable(schemaName, tableName string) *storreturn table}+// Helper function to find materialized view in a schema+func (e *metadataExtractor) findMaterializedView(schemaName, viewName string) *storepb.MaterializedViewMetadata {+ schema := e.getOrCreateSchema(schemaName)+ if schema.MaterializedViews == nil {+ return nil+ }++ for _, mv := range schema.MaterializedViews {+ if mv.Name == viewName {+ return mv+ }+ }+ return nil+}+// EnterCreateschemastmt is called when entering a create schema statementfunc (e *metadataExtractor) EnterCreateschemastmt(ctx *parser.CreateschemastmtContext) {if e.err != nil {@@ -1308,13 +1323,33 @@ func (e *metadataExtractor) EnterIndexstmt(ctx *parser.IndexstmtContext) {return}- // Extract table name from relation_expr+ // Extract table/view name from relation_exprif relationExpr := ctx.Relation_expr(); relationExpr != nil {if qualifiedName := relationExpr.Qualified_name(); qualifiedName != nil {- schemaName, tableName := e.extractSchemaAndTableName(qualifiedName)+ schemaName, relationName := e.extractSchemaAndTableName(qualifiedName)- // Get or create the table- tableMetadata := e.getOrCreateTable(schemaName, tableName)+ // Try to find materialized view first, then table+ var indexTarget any+ var targetIndexes *[]*storepb.IndexMetadata++ if materializedView := e.findMaterializedView(schemaName, relationName); materializedView != nil {+ // Index is on a materialized view+ indexTarget = materializedView+ if materializedView.Indexes == nil {+ materializedView.Indexes = []*storepb.IndexMetadata{}+ }+ targetIndexes = &materializedView.Indexes+ } else {+ // Index is on a table - get or create the table+ tableMetadata := e.getOrCreateTable(schemaName, relationName)+ indexTarget = tableMetadata+ targetIndexes = &tableMetadata.Indexes+ }++ // If we couldn't find either table or materialized view, skip+ if indexTarget == nil || targetIndexes == nil {+ return+ }// Create index metadataindex := &storepb.IndexMetadata{@@ -1378,11 +1413,8 @@ func (e *metadataExtractor) EnterIndexstmt(ctx *parser.IndexstmtContext) {}}- // Add the index to the table- if tableMetadata.Indexes == nil {- tableMetadata.Indexes = []*storepb.IndexMetadata{}- }- tableMetadata.Indexes = append(tableMetadata.Indexes, index)+ // Add the index to the table or materialized view+ *targetIndexes = append(*targetIndexes, index)}}}diff --git a/backend/plugin/schema/pg/get_database_metadata_testcontainer_test.go b/backend/plugin/schema/pg/get_database_metadata_testcontainer_test.goindex bd9d61eadd..2fad530c94 100644--- a/backend/plugin/schema/pg/get_database_metadata_testcontainer_test.go+++ b/backend/plugin/schema/pg/get_database_metadata_testcontainer_test.go@@ -806,7 +806,10 @@ func compareIndexes(t *testing.T, tableName string, syncIndexes, parseIndexes []parseMap[idx.Name] = idx}- // Compare common indexes+ // Check that both directions have the same indexes+ require.Equal(t, len(syncIndexes), len(parseIndexes), "mismatch in number of indexes for table %s", tableName)++ // Compare indexes that exist in parsefor name, parseIdx := range parseMap {syncIdx, exists := syncMap[name]if !exists {