Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: implement get database schema metadata for SQL Server (#16379)
rebelice3bfa09a1916a
diff --git a/backend/plugin/advisor/mssql/advisor_column_no_null.go b/backend/plugin/advisor/mssql/advisor_column_no_null.goindex f5f01f0067..6f01af9bd9 100644--- a/backend/plugin/advisor/mssql/advisor_column_no_null.go+++ b/backend/plugin/advisor/mssql/advisor_column_no_null.go@@ -114,9 +114,9 @@ func (l *columnNoNullChecker) EnterTable_constraint(ctx *parser.Table_constraintreturn}if ctx.PRIMARY() != nil {- allColumns := ctx.Column_name_list_with_order().AllId_()+ allColumns := ctx.Column_name_list_with_order().AllColumn_name_with_order()for _, column := range allColumns {- _, columnName := tsqlparser.NormalizeTSQLIdentifier(column)+ _, columnName := tsqlparser.NormalizeTSQLIdentifier(column.Id_())l.isCurrentTableColumnNullable[columnName] = false}}diff --git a/backend/plugin/advisor/mssql/advisor_index_not_redundant.go b/backend/plugin/advisor/mssql/advisor_index_not_redundant.goindex 5f8522c9f6..4a453db4b9 100644--- a/backend/plugin/advisor/mssql/advisor_index_not_redundant.go+++ b/backend/plugin/advisor/mssql/advisor_index_not_redundant.go@@ -117,8 +117,8 @@ type IndexMap = map[FindIndexesKey][]*storepb.IndexMetadata// Return the name of the index if redundant prefixes are found.func containRedundantPrefix(metaIdxList []*storepb.IndexMetadata, statColumnList *parser.IColumn_name_list_with_orderContext) string {for _, metaIndex := range metaIdxList {- if statColumnList != nil && len((*statColumnList).AllId_()) != 0 && len(metaIdxList) != 0 {- statIdxCol, _ := tsql.NormalizeTSQLIdentifier((*statColumnList).AllId_()[0])+ if statColumnList != nil && len((*statColumnList).AllColumn_name_with_order()) != 0 && len(metaIdxList) != 0 {+ statIdxCol, _ := tsql.NormalizeTSQLIdentifier((*statColumnList).AllColumn_name_with_order()[0].Id_())if metaIndex.Expressions[0] == statIdxCol {return metaIndex.Name}diff --git a/backend/plugin/schema/mssql/get_database_metadata.go b/backend/plugin/schema/mssql/get_database_metadata.gonew file mode 100644index 0000000000..ca0adfcd33--- /dev/null+++ b/backend/plugin/schema/mssql/get_database_metadata.go@@ -0,0 +1,733 @@+package mssql++import (+ "fmt"+ "sort"+ "strconv"+ "strings"++ "github.com/antlr4-go/antlr/v4"+ "github.com/pkg/errors"++ parser "github.com/bytebase/tsql-parser"++ "github.com/bytebase/bytebase/backend/plugin/parser/tsql"+ "github.com/bytebase/bytebase/backend/plugin/schema"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++func init() {+ schema.RegisterGetDatabaseMetadata(storepb.Engine_MSSQL, GetDatabaseMetadata)+}++// GetDatabaseMetadata parses the SQL schema text and returns the database metadata.+func GetDatabaseMetadata(schemaText string) (*storepb.DatabaseSchemaMetadata, error) {+ parseResult, err := tsql.ParseTSQL(schemaText)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to parse SQL schema")+ }++ if parseResult.Tree == nil {+ return nil, errors.Errorf("empty parse tree")+ }++ extractor := &metadataExtractor{+ currentDatabase: "",+ currentSchema: defaultSchema,+ schemas: make(map[string]*storepb.SchemaMetadata),+ tables: make(map[tableKey]*storepb.TableMetadata),+ }++ antlr.ParseTreeWalkerDefault.Walk(extractor, parseResult.Tree)++ if extractor.err != nil {+ return nil, extractor.err+ }++ // Build the final metadata structure+ schemaMetadata := &storepb.DatabaseSchemaMetadata{+ Name: extractor.currentDatabase,+ }++ // Sort schemas for consistent output+ var schemaNames []string+ for name := range extractor.schemas {+ schemaNames = append(schemaNames, name)+ }+ sort.Strings(schemaNames)++ for _, schemaName := range schemaNames {+ schemaMetadata.Schemas = append(schemaMetadata.Schemas, extractor.schemas[schemaName])+ }++ return schemaMetadata, nil+}++type tableKey struct {+ schema string+ table string+}++// metadataExtractor walks the parse tree and extracts metadata+type metadataExtractor struct {+ *parser.BaseTSqlParserListener++ currentDatabase string+ currentSchema string+ schemas map[string]*storepb.SchemaMetadata+ tables map[tableKey]*storepb.TableMetadata+ err error+ indexCounter int // Counter for generating unique index names+}++// Helper function to get or create schema+func (e *metadataExtractor) getOrCreateSchema(schemaName string) *storepb.SchemaMetadata {+ if schemaName == "" {+ schemaName = defaultSchema+ }++ if schema, exists := e.schemas[schemaName]; exists {+ return schema+ }++ schema := &storepb.SchemaMetadata{+ Name: schemaName,+ Tables: []*storepb.TableMetadata{},+ // Initialize as nil for consistency with expected test results+ Views: nil,+ Procedures: nil,+ Functions: nil,+ Sequences: nil,+ }+ e.schemas[schemaName] = schema+ return schema+}++// Helper function to get or create table+func (e *metadataExtractor) getOrCreateTable(schemaName, tableName string) *storepb.TableMetadata {+ key := tableKey{+ schema: schemaName,+ table: tableName,+ }++ if table, exists := e.tables[key]; exists {+ return table+ }++ table := &storepb.TableMetadata{+ Name: tableName,+ Columns: []*storepb.ColumnMetadata{},+ Indexes: []*storepb.IndexMetadata{},+ // Initialize as nil for consistency with expected test results+ ForeignKeys: nil,+ CheckConstraints: nil,+ }++ schema := e.getOrCreateSchema(schemaName)+ schema.Tables = append(schema.Tables, table)+ e.tables[key] = table++ return table+}++// EnterCreate_schema is called when entering a create_schema parse tree node+func (e *metadataExtractor) EnterCreate_schema(ctx *parser.Create_schemaContext) {+ if e.err != nil {+ return+ }++ if ctx.GetSchema_name() != nil {+ schemaName, _ := tsql.NormalizeTSQLIdentifier(ctx.GetSchema_name())+ e.getOrCreateSchema(schemaName)+ }+}++// EnterCreate_table is called when entering a create_table parse tree node+func (e *metadataExtractor) EnterCreate_table(ctx *parser.Create_tableContext) {+ if e.err != nil {+ return+ }++ tableNameCtx := ctx.Table_name()+ if tableNameCtx == nil {+ return+ }++ _, schema, table := e.normalizeTableNameSeparated(tableNameCtx, e.currentDatabase, e.currentSchema)++ tableMetadata := e.getOrCreateTable(schema, table)++ // Extract columns+ if columnDefList := ctx.Column_def_table_constraints(); columnDefList != nil {+ e.extractTableElements(columnDefList, tableMetadata, schema)+ }+}++// EnterCreate_index is called when entering a create index parse tree node+func (e *metadataExtractor) EnterCreate_index(ctx *parser.Create_indexContext) {+ if e.err != nil {+ return+ }++ // Extract table reference+ if ctx.Table_name() == nil {+ return+ }++ _, schema, table := e.normalizeTableNameSeparated(ctx.Table_name(), e.currentDatabase, e.currentSchema)++ tableMetadata := e.getOrCreateTable(schema, table)++ // Extract index metadata+ index := &storepb.IndexMetadata{+ Expressions: []string{},+ Descending: []bool{},+ IsConstraint: false,+ }++ // Index name+ idList := ctx.AllId_()+ if len(idList) > 0 {+ index.Name, _ = tsql.NormalizeTSQLIdentifier(idList[0])+ }++ // Index type+ if ctx.UNIQUE() != nil {+ index.Unique = true+ }+ if clustered := ctx.Clustered(); clustered != nil {+ if clustered.CLUSTERED() != nil {+ index.Type = "CLUSTERED"+ } else if clustered.NONCLUSTERED() != nil {+ index.Type = "NONCLUSTERED"+ }+ }++ // Extract columns+ if columnList := ctx.Column_name_list_with_order(); columnList != nil {+ e.extractIndexColumns(columnList, index)+ }++ tableMetadata.Indexes = append(tableMetadata.Indexes, index)+}++// EnterCreate_view is called when entering a create view parse tree node+func (e *metadataExtractor) EnterCreate_view(ctx *parser.Create_viewContext) {+ if e.err != nil {+ return+ }++ simpleNameCtx := ctx.Simple_name()+ if simpleNameCtx == nil {+ return+ }++ schema, view := e.normalizeSimpleNameSeparated(simpleNameCtx, e.currentSchema)++ schemaMetadata := e.getOrCreateSchema(schema)++ viewMetadata := &storepb.ViewMetadata{+ Name: view,+ Definition: ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx),+ }++ // Initialize Views slice if nil+ if schemaMetadata.Views == nil {+ schemaMetadata.Views = []*storepb.ViewMetadata{}+ }+ schemaMetadata.Views = append(schemaMetadata.Views, viewMetadata)+}++// EnterCreate_or_alter_procedure is called when entering a create procedure parse tree node+func (e *metadataExtractor) EnterCreate_or_alter_procedure(ctx *parser.Create_or_alter_procedureContext) {+ if e.err != nil {+ return+ }++ funcProcNameCtx := ctx.Func_proc_name_schema()+ if funcProcNameCtx == nil {+ return+ }++ schema, procedure := e.normalizeFuncProcNameSeparated(funcProcNameCtx, e.currentSchema)++ schemaMetadata := e.getOrCreateSchema(schema)++ procedureMetadata := &storepb.ProcedureMetadata{+ Name: procedure,+ Definition: ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx),+ }++ // Initialize Procedures slice if nil+ if schemaMetadata.Procedures == nil {+ schemaMetadata.Procedures = []*storepb.ProcedureMetadata{}+ }+ schemaMetadata.Procedures = append(schemaMetadata.Procedures, procedureMetadata)+}++// EnterCreate_or_alter_function is called when entering a create function parse tree node+func (e *metadataExtractor) EnterCreate_or_alter_function(ctx *parser.Create_or_alter_functionContext) {+ if e.err != nil {+ return+ }++ funcNameCtx := ctx.Func_proc_name_schema()+ if funcNameCtx == nil {+ return+ }++ schema, function := e.normalizeFuncProcNameSeparated(funcNameCtx, e.currentSchema)++ schemaMetadata := e.getOrCreateSchema(schema)++ functionMetadata := &storepb.FunctionMetadata{+ Name: function,+ Definition: ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx),+ }++ // Initialize Functions slice if nil+ if schemaMetadata.Functions == nil {+ schemaMetadata.Functions = []*storepb.FunctionMetadata{}+ }+ schemaMetadata.Functions = append(schemaMetadata.Functions, functionMetadata)+}++// EnterCreate_sequence is called when entering a create sequence parse tree node+func (e *metadataExtractor) EnterCreate_sequence(ctx *parser.Create_sequenceContext) {+ if e.err != nil {+ return+ }++ if ctx.GetSequence_name() == nil {+ return+ }++ sequenceName, _ := tsql.NormalizeTSQLIdentifier(ctx.GetSequence_name())++ // Sequences in MSSQL are schema-scoped, but the parser doesn't provide schema info+ // so we'll use the default schema+ schemaMetadata := e.getOrCreateSchema(e.currentSchema)++ sequenceMetadata := &storepb.SequenceMetadata{+ Name: sequenceName,+ }++ if dataType := ctx.Data_type(); dataType != nil {+ sequenceMetadata.DataType = extractDataType(dataType)+ }++ // Initialize Sequences slice if nil+ if schemaMetadata.Sequences == nil {+ schemaMetadata.Sequences = []*storepb.SequenceMetadata{}+ }+ schemaMetadata.Sequences = append(schemaMetadata.Sequences, sequenceMetadata)+}++// extractTableElements extracts columns and constraints from table definition+func (e *metadataExtractor) extractTableElements(ctx parser.IColumn_def_table_constraintsContext, table *storepb.TableMetadata, schemaName string) {+ if columnDefCtxList := ctx.AllColumn_def_table_constraint(); columnDefCtxList != nil {+ for _, columnDefCtx := range columnDefCtxList {+ if columnDef := columnDefCtx.Column_definition(); columnDef != nil {+ e.extractColumn(columnDef, table)+ } else if constraint := columnDefCtx.Table_constraint(); constraint != nil {+ e.extractTableConstraint(constraint, table, schemaName)+ }+ }+ }+}++// extractColumn extracts column metadata from column definition+func (e *metadataExtractor) extractColumn(ctx parser.IColumn_definitionContext, table *storepb.TableMetadata) {+ if ctx == nil {+ return+ }++ column := &storepb.ColumnMetadata{}++ // Column name+ if ctx.Id_() != nil {+ column.Name, _ = tsql.NormalizeTSQLIdentifier(ctx.Id_())+ }++ // Data type and IDENTITY handling+ if dataTypeCtx := ctx.Data_type(); dataTypeCtx != nil {+ column.Type = extractDataType(dataTypeCtx)++ // Check if IDENTITY is part of the data type context+ // The parser sometimes includes IDENTITY in the data type context+ if dataTypeCtx.IDENTITY() != nil {+ column.IsIdentity = true+ column.IdentitySeed = 1+ column.IdentityIncrement = 1++ if seed := dataTypeCtx.GetSeed(); seed != nil {+ if val, err := strconv.ParseInt(seed.GetText(), 10, 64); err == nil {+ column.IdentitySeed = val+ } else {+ e.err = errors.Wrapf(err, "failed to parse identity seed for column %s", column.Name)+ }+ }++ if increment := dataTypeCtx.GetInc(); increment != nil {+ if val, err := strconv.ParseInt(increment.GetText(), 10, 64); err == nil {+ column.IdentityIncrement = val+ } else {+ e.err = errors.Wrapf(err, "failed to parse identity increment for column %s", column.Name)+ }+ }+ }+ }++ // Nullability and other properties+ column.Nullable = true // Default to nullable++ if columnDefElems := ctx.AllColumn_definition_element(); columnDefElems != nil {+ for _, elem := range columnDefElems {+ // Handle column constraints+ if elem.Column_constraint() != nil {+ constraint := elem.Column_constraint()++ // Handle nullability+ if nullNotNull := constraint.Null_notnull(); nullNotNull != nil {+ if nullNotNull.NOT() != nil {+ column.Nullable = false+ } else {+ column.Nullable = true+ }+ }++ // Handle PRIMARY KEY+ if constraint.PRIMARY() != nil && constraint.KEY() != nil {+ column.Nullable = false // Primary keys are not nullable+ // Create a primary key index+ index := &storepb.IndexMetadata{+ Primary: true,+ Unique: true,+ IsConstraint: true,+ Expressions: []string{column.Name},+ Descending: []bool{false},+ }++ // Get constraint name if specified+ if constraint.GetConstraint() != nil {+ index.Name, _ = tsql.NormalizeTSQLIdentifier(constraint.GetConstraint())+ } else {+ // Generate a unique name for unnamed constraints+ e.indexCounter+++ index.Name = fmt.Sprintf("PK_%s_%d", table.Name, e.indexCounter)+ }++ // Check for CLUSTERED/NONCLUSTERED+ if clustered := constraint.Clustered(); clustered != nil {+ if clustered.CLUSTERED() != nil {+ index.Type = "CLUSTERED"+ } else if clustered.NONCLUSTERED() != nil {+ index.Type = "NONCLUSTERED"+ }+ }++ table.Indexes = append(table.Indexes, index)+ }++ // Handle UNIQUE+ if constraint.UNIQUE() != nil {+ // Create a unique index+ index := &storepb.IndexMetadata{+ Unique: true,+ IsConstraint: true,+ Expressions: []string{column.Name},+ Descending: []bool{false},+ }++ // Get constraint name if specified+ if constraint.GetConstraint() != nil {+ index.Name, _ = tsql.NormalizeTSQLIdentifier(constraint.GetConstraint())+ } else {+ // Generate a unique name for unnamed constraints+ e.indexCounter+++ index.Name = fmt.Sprintf("UQ_%s_%d", table.Name, e.indexCounter)+ }++ // Check for CLUSTERED/NONCLUSTERED+ if clustered := constraint.Clustered(); clustered != nil {+ if clustered.CLUSTERED() != nil {+ index.Type = "CLUSTERED"+ } else if clustered.NONCLUSTERED() != nil {+ index.Type = "NONCLUSTERED"+ }+ }++ table.Indexes = append(table.Indexes, index)+ }+ }++ // Note: IDENTITY is handled in the data type context above since the parser+ // includes it as part of the data type++ // Handle DEFAULT+ if elem.DEFAULT() != nil {+ // Get the default expression (everything after DEFAULT keyword)+ // This is a simplified implementation+ if expr := elem.Expression(); expr != nil {+ column.DefaultValue = &storepb.ColumnMetadata_DefaultExpression{+ DefaultExpression: ctx.GetParser().GetTokenStream().GetTextFromRuleContext(expr),+ }+ }+ }++ // Handle collation+ if elem.COLLATE() != nil && elem.Id_() != nil {+ column.Collation, _ = tsql.NormalizeTSQLIdentifier(elem.Id_())+ }+ }+ }++ table.Columns = append(table.Columns, column)+}++// extractTableConstraint extracts table-level constraints+func (e *metadataExtractor) extractTableConstraint(ctx parser.ITable_constraintContext, table *storepb.TableMetadata, schemaName string) {+ if ctx == nil {+ return+ }++ // Get constraint name+ var constraintName string+ if constraintCtx := ctx.GetConstraint(); constraintCtx != nil {+ constraintName, _ = tsql.NormalizeTSQLIdentifier(constraintCtx)+ }++ // Handle different constraint types+ if ctx.PRIMARY() != nil && ctx.KEY() != nil {+ // Primary key constraint+ index := &storepb.IndexMetadata{+ Name: constraintName,+ Primary: true,+ Unique: true,+ IsConstraint: true,+ Expressions: []string{},+ Descending: []bool{},+ }++ if clustered := ctx.Clustered(); clustered != nil {+ if clustered.CLUSTERED() != nil {+ index.Type = "CLUSTERED"+ } else if clustered.NONCLUSTERED() != nil {+ index.Type = "NONCLUSTERED"+ }+ }++ // Extract columns+ if columnList := ctx.Column_name_list_with_order(); columnList != nil {+ e.extractIndexColumns(columnList, index)+ }++ table.Indexes = append(table.Indexes, index)+ } else if ctx.UNIQUE() != nil {+ // Unique constraint+ index := &storepb.IndexMetadata{+ Name: constraintName,+ Unique: true,+ IsConstraint: true,+ Expressions: []string{},+ Descending: []bool{},+ }++ if clustered := ctx.Clustered(); clustered != nil {+ if clustered.CLUSTERED() != nil {+ index.Type = "CLUSTERED"+ } else if clustered.NONCLUSTERED() != nil {+ index.Type = "NONCLUSTERED"+ }+ }++ // Extract columns+ if columnList := ctx.Column_name_list_with_order(); columnList != nil {+ e.extractIndexColumns(columnList, index)+ }++ table.Indexes = append(table.Indexes, index)+ } else if ctx.Check_constraint() != nil {+ // Check constraint+ check := &storepb.CheckConstraintMetadata{+ Name: constraintName,+ }++ if checkConstraint := ctx.Check_constraint(); checkConstraint != nil && checkConstraint.Search_condition() != nil {+ expr := checkConstraint.Search_condition()+ check.Expression = ctx.GetParser().GetTokenStream().GetTextFromRuleContext(expr)+ }++ // Initialize CheckConstraints slice if nil+ if table.CheckConstraints == nil {+ table.CheckConstraints = []*storepb.CheckConstraintMetadata{}+ }+ table.CheckConstraints = append(table.CheckConstraints, check)+ } else if ctx.FOREIGN() != nil && ctx.KEY() != nil {+ // Foreign key constraint+ fk := &storepb.ForeignKeyMetadata{+ Name: constraintName,+ Columns: []string{},+ ReferencedColumns: []string{},+ }++ // Extract local columns+ if columnList := ctx.GetFk(); columnList != nil {+ if idList := columnList.AllId_(); idList != nil {+ for _, id := range idList {+ colName, _ := tsql.NormalizeTSQLIdentifier(id)+ fk.Columns = append(fk.Columns, colName)+ }+ }+ }++ // Extract referenced table and columns+ if fkOptions := ctx.Foreign_key_options(); fkOptions != nil {+ if fkOptions.Table_name() != nil {+ _, refSchema, refTable := e.normalizeTableNameSeparated(fkOptions.Table_name(), e.currentDatabase, schemaName)+ fk.ReferencedSchema = refSchema+ fk.ReferencedTable = refTable+ }++ if pkList := fkOptions.GetPk(); pkList != nil {+ if idList := pkList.AllId_(); idList != nil {+ for _, id := range idList {+ colName, _ := tsql.NormalizeTSQLIdentifier(id)+ fk.ReferencedColumns = append(fk.ReferencedColumns, colName)+ }+ }+ }++ // Extract ON DELETE/UPDATE actions+ fk.OnDelete = "NO ACTION" // Default+ fk.OnUpdate = "NO ACTION" // Default+ if onDelete := fkOptions.On_delete(0); onDelete != nil {+ switch {+ case onDelete.CASCADE() != nil:+ fk.OnDelete = "CASCADE"+ case onDelete.SET() != nil && onDelete.NULL_() != nil:+ fk.OnDelete = "SET NULL"+ case onDelete.SET() != nil && onDelete.DEFAULT() != nil:+ fk.OnDelete = "SET DEFAULT"+ }+ }+ if onUpdate := fkOptions.On_update(0); onUpdate != nil {+ switch {+ case onUpdate.CASCADE() != nil:+ fk.OnUpdate = "CASCADE"+ case onUpdate.SET() != nil && onUpdate.NULL_() != nil:+ fk.OnDelete = "SET NULL"+ case onUpdate.SET() != nil && onUpdate.DEFAULT() != nil:+ fk.OnUpdate = "SET DEFAULT"+ }+ }+ }++ // Initialize ForeignKeys slice if nil+ if table.ForeignKeys == nil {+ table.ForeignKeys = []*storepb.ForeignKeyMetadata{}+ }+ table.ForeignKeys = append(table.ForeignKeys, fk)+ }+}++// extractIndexColumns extracts column information for indexes+func (*metadataExtractor) extractIndexColumns(ctx parser.IColumn_name_list_with_orderContext, index *storepb.IndexMetadata) {+ if ctx == nil {+ return+ }++ if idList := ctx.AllColumn_name_with_order(); idList != nil {+ for _, id := range idList {+ colName, _ := tsql.NormalizeTSQLIdentifier(id.Id_())+ index.Expressions = append(index.Expressions, colName)++ // Check if DESC is specified - simplified, assuming ASC by default+ // The actual parser might have different structure for ORDER+ if id.DESC() != nil {+ index.Descending = append(index.Descending, true)+ } else {+ index.Descending = append(index.Descending, false)+ }+ }+ }+}++// Helper functions++func extractDataType(ctx parser.IData_typeContext) string {+ if ctx == nil {+ return ""+ }++ // The parser sometimes includes IDENTITY in the data type context+ // We need to extract just the actual data type+ fullText := ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)++ // Check if IDENTITY is included+ if identityIdx := strings.Index(strings.ToUpper(fullText), "IDENTITY"); identityIdx > 0 {+ // Return just the data type part before IDENTITY+ return strings.TrimSpace(fullText[:identityIdx])+ }++ return fullText+}++// normalizeFuncProcNameSeparated extracts schema and name from func_proc_name_schema context+func (*metadataExtractor) normalizeFuncProcNameSeparated(ctx parser.IFunc_proc_name_schemaContext, defaultSchema string) (string, string) {+ schema := defaultSchema+ name := ""++ if s := ctx.GetSchema(); s != nil {+ if id, _ := tsql.NormalizeTSQLIdentifier(s); id != "" {+ schema = id+ }+ }+ if p := ctx.GetProcedure(); p != nil {+ if id, _ := tsql.NormalizeTSQLIdentifier(p); id != "" {+ name = id+ }+ }++ return schema, name+}++// normalizeTableNameSeparated extracts database, schema and table from table_name context+func (*metadataExtractor) normalizeTableNameSeparated(ctx parser.ITable_nameContext, fallbackDatabaseName, fallbackSchemaName string) (string, string, string) {+ database := fallbackDatabaseName+ schema := fallbackSchemaName+ table := ""+ if d := ctx.GetDatabase(); d != nil {+ if id, _ := tsql.NormalizeTSQLIdentifier(d); id != "" {+ database = id+ }+ }+ if s := ctx.GetSchema(); s != nil {+ if id, _ := tsql.NormalizeTSQLIdentifier(s); id != "" {+ schema = id+ }+ }+ if t := ctx.GetTable(); t != nil {+ if id, _ := tsql.NormalizeTSQLIdentifier(t); id != "" {+ table = id+ }+ }+ return database, schema, table+}++// normalizeSimpleNameSeparated extracts schema and name from simple_name context+func (*metadataExtractor) normalizeSimpleNameSeparated(ctx parser.ISimple_nameContext, fallbackSchemaName string) (string, string) {+ schema := fallbackSchemaName+ name := ""+ if s := ctx.GetSchema(); s != nil {+ if id, _ := tsql.NormalizeTSQLIdentifier(s); id != "" {+ schema = id+ }+ }+ if n := ctx.GetName(); n != nil {+ if id, _ := tsql.NormalizeTSQLIdentifier(n); id != "" {+ name = id+ }+ }+ return schema, name+}diff --git a/backend/plugin/schema/mssql/get_database_metadata_test.go b/backend/plugin/schema/mssql/get_database_metadata_test.gonew file mode 100644index 0000000000..31f2347688--- /dev/null+++ b/backend/plugin/schema/mssql/get_database_metadata_test.go@@ -0,0 +1,56 @@+package mssql++import (+ "encoding/json"+ "io"+ "os"+ "testing"++ "github.com/stretchr/testify/require"+ "gopkg.in/yaml.v3"+)++type getDatabaseMetadataCase struct {+ Input string+ Result string+}++func TestGetDatabaseMetadata(t *testing.T) {+ tests := []getDatabaseMetadataCase{}+ const (+ record = false+ )+ var (+ filepath = "test-data/test_get_database_metadata.yaml"+ )++ a := require.New(t)+ yamlFile, err := os.Open(filepath)+ a.NoError(err)+ defer yamlFile.Close()++ byteValue, err := io.ReadAll(yamlFile)+ a.NoError(err)+ a.NoError(yaml.Unmarshal(byteValue, &tests))++ for i, t := range tests {+ meta, err := GetDatabaseMetadata(t.Input)+ a.NoError(err)++ jsonBytes, err := json.MarshalIndent(meta, "", " ")+ a.NoError(err)+ result := string(jsonBytes)++ if record {+ tests[i].Result = result+ } else {+ a.Equal(t.Result, result, t.Input)+ }+ }+ if record {+ byteValue, err := yaml.Marshal(tests)+ a.NoError(err)+ err = os.WriteFile(filepath, byteValue, 0644)+ a.NoError(err)+ }+}diff --git a/backend/plugin/schema/mssql/test-data/test_get_database_metadata.yaml b/backend/plugin/schema/mssql/test-data/test_get_database_metadata.yamlnew file mode 100644index 0000000000..47e3bb7598--- /dev/null+++ b/backend/plugin/schema/mssql/test-data/test_get_database_metadata.yaml@@ -0,0 +1,1769 @@+- input: |+ CREATE TABLE dbo.users (+ id INT IDENTITY(1,1) PRIMARY KEY,+ name NVARCHAR(255) NOT NULL,+ email NVARCHAR(255) UNIQUE+ );+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "tables": [+ {+ "name": "users",+ "columns": [+ {+ "name": "id",+ "DefaultValue": null,+ "type": "INT",+ "is_identity": true,+ "identity_seed": 1,+ "identity_increment": 1+ },+ {+ "name": "name",+ "DefaultValue": null,+ "type": "NVARCHAR(255)"+ },+ {+ "name": "email",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(255)"+ }+ ],+ "indexes": [+ {+ "name": "PK_users_1",+ "expressions": [+ "id"+ ],+ "descending": [+ false+ ],+ "unique": true,+ "primary": true,+ "is_constraint": true+ },+ {+ "name": "UQ_users_2",+ "expressions": [+ "email"+ ],+ "descending": [+ false+ ],+ "unique": true,+ "is_constraint": true+ }+ ]+ }+ ]+ }+ ]+ }+- input: |+ CREATE TABLE dbo.departments (+ dept_id INT PRIMARY KEY,+ dept_name NVARCHAR(100) NOT NULL+ );++ CREATE TABLE dbo.employees (+ emp_id INT PRIMARY KEY,+ emp_name NVARCHAR(100) NOT NULL,+ dept_id INT,+ CONSTRAINT FK_employees_departments FOREIGN KEY (dept_id)+ REFERENCES dbo.departments(dept_id) ON DELETE CASCADE+ );+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "tables": [+ {+ "name": "departments",+ "columns": [+ {+ "name": "dept_id",+ "DefaultValue": null,+ "type": "INT"+ },+ {+ "name": "dept_name",+ "DefaultValue": null,+ "type": "NVARCHAR(100)"+ }+ ],+ "indexes": [+ {+ "name": "PK_departments_1",+ "expressions": [+ "dept_id"+ ],+ "descending": [+ false+ ],+ "unique": true,+ "primary": true,+ "is_constraint": true+ }+ ]+ },+ {+ "name": "employees",+ "columns": [+ {+ "name": "emp_id",+ "DefaultValue": null,+ "type": "INT"+ },+ {+ "name": "emp_name",+ "DefaultValue": null,+ "type": "NVARCHAR(100)"+ },+ {+ "name": "dept_id",+ "DefaultValue": null,+ "nullable": true,+ "type": "INT"+ }+ ],+ "indexes": [+ {+ "name": "PK_employees_2",+ "expressions": [+ "emp_id"+ ],+ "descending": [+ false+ ],+ "unique": true,+ "primary": true,+ "is_constraint": true+ }+ ],+ "foreign_keys": [+ {+ "name": "FK_employees_departments",+ "columns": [+ "dept_id"+ ],+ "referenced_schema": "dbo",+ "referenced_table": "departments",+ "referenced_columns": [+ "dept_id"+ ],+ "on_delete": "CASCADE",+ "on_update": "NO ACTION"+ }+ ]+ }+ ]+ }+ ]+ }+- input: |+ CREATE TABLE dbo.products (+ product_id INT PRIMARY KEY,+ price DECIMAL(10,2),+ CONSTRAINT CK_price_positive CHECK (price > 0)+ );+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "tables": [+ {+ "name": "products",+ "columns": [+ {+ "name": "product_id",+ "DefaultValue": null,+ "type": "INT"+ },+ {+ "name": "price",+ "DefaultValue": null,+ "nullable": true,+ "type": "DECIMAL(10,2)"+ }+ ],+ "indexes": [+ {+ "name": "PK_products_1",+ "expressions": [+ "product_id"+ ],+ "descending": [+ false+ ],+ "unique": true,+ "primary": true,+ "is_constraint": true+ }+ ],+ "check_constraints": [+ {+ "name": "CK_price_positive",+ "expression": "price \u003e 0"+ }+ ]+ }+ ]+ }+ ]+ }+- input: |+ CREATE TABLE dbo.products (+ id INT PRIMARY KEY,+ name NVARCHAR(255),+ category NVARCHAR(50)+ );++ CREATE INDEX IX_products_category ON dbo.products (category);+ CREATE UNIQUE INDEX UX_products_name ON dbo.products (name);+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "tables": [+ {+ "name": "products",+ "columns": [+ {+ "name": "id",+ "DefaultValue": null,+ "type": "INT"+ },+ {+ "name": "name",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(255)"+ },+ {+ "name": "category",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(50)"+ }+ ],+ "indexes": [+ {+ "name": "PK_products_1",+ "expressions": [+ "id"+ ],+ "descending": [+ false+ ],+ "unique": true,+ "primary": true,+ "is_constraint": true+ },+ {+ "name": "IX_products_category",+ "expressions": [+ "category"+ ],+ "descending": [+ false+ ]+ },+ {+ "name": "UX_products_name",+ "expressions": [+ "name"+ ],+ "descending": [+ false+ ],+ "unique": true+ }+ ]+ }+ ]+ }+ ]+ }+- input: |+ CREATE TABLE dbo.orders (+ order_id INT,+ customer_id INT,+ order_date DATETIME,+ CONSTRAINT PK_orders PRIMARY KEY CLUSTERED (order_id)+ );++ CREATE NONCLUSTERED INDEX IX_orders_customer ON dbo.orders (customer_id);+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "tables": [+ {+ "name": "orders",+ "columns": [+ {+ "name": "order_id",+ "DefaultValue": null,+ "nullable": true,+ "type": "INT"+ },+ {+ "name": "customer_id",+ "DefaultValue": null,+ "nullable": true,+ "type": "INT"+ },+ {+ "name": "order_date",+ "DefaultValue": null,+ "nullable": true,+ "type": "DATETIME"+ }+ ],+ "indexes": [+ {+ "name": "PK_orders",+ "expressions": [+ "order_id"+ ],+ "descending": [+ false+ ],+ "type": "CLUSTERED",+ "unique": true,+ "primary": true,+ "is_constraint": true+ },+ {+ "name": "IX_orders_customer",+ "expressions": [+ "customer_id"+ ],+ "descending": [+ false+ ],+ "type": "NONCLUSTERED"+ }+ ]+ }+ ]+ }+ ]+ }+- input: |+ CREATE VIEW dbo.active_users AS+ SELECT id, name, email+ FROM users+ WHERE is_active = 1;+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "views": [+ {+ "name": "active_users",+ "definition": "CREATE VIEW dbo.active_users AS\nSELECT id, name, email\nFROM users\nWHERE is_active = 1;"+ }+ ]+ }+ ]+ }+- input: |+ CREATE PROCEDURE dbo.GetUserById+ @UserId INT+ AS+ BEGIN+ SELECT * FROM users WHERE id = @UserId;+ END;+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "procedures": [+ {+ "name": "GetUserById",+ "definition": "CREATE PROCEDURE dbo.GetUserById\n @UserId INT\nAS\nBEGIN\n SELECT * FROM users WHERE id = @UserId;\nEND;"+ }+ ]+ }+ ]+ }+- input: |+ CREATE FUNCTION dbo.GetFullName+ (+ @FirstName NVARCHAR(50),+ @LastName NVARCHAR(50)+ )+ RETURNS NVARCHAR(101)+ AS+ BEGIN+ RETURN @FirstName + ' ' + @LastName;+ END;+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "functions": [+ {+ "name": "GetFullName",+ "definition": "CREATE FUNCTION dbo.GetFullName\n(\n @FirstName NVARCHAR(50),\n @LastName NVARCHAR(50)\n)\nRETURNS NVARCHAR(101)\nAS\nBEGIN\n RETURN @FirstName + ' ' + @LastName;\nEND;"+ }+ ]+ }+ ]+ }+- input: |+ CREATE SEQUENCE dbo.OrderNumberSeq+ AS INT+ START WITH 1000+ INCREMENT BY 1;+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "sequences": [+ {+ "name": "OrderNumberSeq",+ "data_type": "INT"+ }+ ]+ }+ ]+ }+- input: |+ CREATE SCHEMA sales;+ CREATE SCHEMA hr;++ CREATE TABLE sales.orders (+ order_id INT PRIMARY KEY,+ amount DECIMAL(10,2)+ );++ CREATE TABLE hr.employees (+ emp_id INT PRIMARY KEY,+ name NVARCHAR(100)+ );+ result: |-+ {+ "schemas": [+ {+ "name": "hr",+ "tables": [+ {+ "name": "employees",+ "columns": [+ {+ "name": "emp_id",+ "DefaultValue": null,+ "type": "INT"+ },+ {+ "name": "name",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(100)"+ }+ ],+ "indexes": [+ {+ "name": "PK_employees_2",+ "expressions": [+ "emp_id"+ ],+ "descending": [+ false+ ],+ "unique": true,+ "primary": true,+ "is_constraint": true+ }+ ]+ }+ ]+ },+ {+ "name": "sales",+ "tables": [+ {+ "name": "orders",+ "columns": [+ {+ "name": "order_id",+ "DefaultValue": null,+ "type": "INT"+ },+ {+ "name": "amount",+ "DefaultValue": null,+ "nullable": true,+ "type": "DECIMAL(10,2)"+ }+ ],+ "indexes": [+ {+ "name": "PK_orders_1",+ "expressions": [+ "order_id"+ ],+ "descending": [+ false+ ],+ "unique": true,+ "primary": true,+ "is_constraint": true+ }+ ]+ }+ ]+ }+ ]+ }+- input: |+ CREATE TABLE dbo.settings (+ id INT PRIMARY KEY,+ created_at DATETIME DEFAULT GETDATE(),+ is_active BIT DEFAULT 1,+ status NVARCHAR(20) DEFAULT N'pending'+ );+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "tables": [+ {+ "name": "settings",+ "columns": [+ {+ "name": "id",+ "DefaultValue": null,+ "type": "INT"+ },+ {+ "name": "created_at",+ "DefaultValue": {+ "DefaultExpression": "GETDATE()"+ },+ "nullable": true,+ "type": "DATETIME"+ },+ {+ "name": "is_active",+ "DefaultValue": {+ "DefaultExpression": "1"+ },+ "nullable": true,+ "type": "BIT"+ },+ {+ "name": "status",+ "DefaultValue": {+ "DefaultExpression": "N'pending'"+ },+ "nullable": true,+ "type": "NVARCHAR(20)"+ }+ ],+ "indexes": [+ {+ "name": "PK_settings_1",+ "expressions": [+ "id"+ ],+ "descending": [+ false+ ],+ "unique": true,+ "primary": true,+ "is_constraint": true+ }+ ]+ }+ ]+ }+ ]+ }+- input: |+ CREATE TABLE dbo.logs (+ id INT PRIMARY KEY,+ user_id INT,+ action NVARCHAR(50),+ timestamp DATETIME+ );++ CREATE INDEX IX_logs_user_action ON dbo.logs (user_id ASC, action DESC, timestamp DESC);+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "tables": [+ {+ "name": "logs",+ "columns": [+ {+ "name": "id",+ "DefaultValue": null,+ "type": "INT"+ },+ {+ "name": "user_id",+ "DefaultValue": null,+ "nullable": true,+ "type": "INT"+ },+ {+ "name": "action",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(50)"+ },+ {+ "name": "timestamp",+ "DefaultValue": null,+ "nullable": true,+ "type": "DATETIME"+ }+ ],+ "indexes": [+ {+ "name": "PK_logs_1",+ "expressions": [+ "id"+ ],+ "descending": [+ false+ ],+ "unique": true,+ "primary": true,+ "is_constraint": true+ },+ {+ "name": "IX_logs_user_action",+ "expressions": [+ "user_id",+ "action",+ "timestamp"+ ],+ "descending": [+ false,+ true,+ true+ ]+ }+ ]+ }+ ]+ }+ ]+ }+- input: |+ CREATE TABLE dbo.test (+ id INT NOT NULL PRIMARY KEY CLUSTERED,+ email NVARCHAR(255) UNIQUE NONCLUSTERED+ );+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "tables": [+ {+ "name": "test",+ "columns": [+ {+ "name": "id",+ "DefaultValue": null,+ "type": "INT"+ },+ {+ "name": "email",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(255)"+ }+ ],+ "indexes": [+ {+ "name": "PK_test_1",+ "expressions": [+ "id"+ ],+ "descending": [+ false+ ],+ "type": "CLUSTERED",+ "unique": true,+ "primary": true,+ "is_constraint": true+ },+ {+ "name": "UQ_test_2",+ "expressions": [+ "email"+ ],+ "descending": [+ false+ ],+ "type": "NONCLUSTERED",+ "unique": true,+ "is_constraint": true+ }+ ]+ }+ ]+ }+ ]+ }+- input: |+ CREATE TABLE dbo.test (+ id INT CONSTRAINT PK_test_id PRIMARY KEY,+ email NVARCHAR(255) CONSTRAINT UQ_test_email UNIQUE+ );+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "tables": [+ {+ "name": "test",+ "columns": [+ {+ "name": "id",+ "DefaultValue": null,+ "type": "INT"+ },+ {+ "name": "email",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(255)"+ }+ ],+ "indexes": [+ {+ "name": "PK_test_id",+ "expressions": [+ "id"+ ],+ "descending": [+ false+ ],+ "unique": true,+ "primary": true,+ "is_constraint": true+ },+ {+ "name": "UQ_test_email",+ "expressions": [+ "email"+ ],+ "descending": [+ false+ ],+ "unique": true,+ "is_constraint": true+ }+ ]+ }+ ]+ }+ ]+ }+- input: |+ CREATE TABLE dbo.customers (+ customer_id INT IDENTITY(1,1) NOT NULL,+ first_name VARCHAR(50) NOT NULL,+ last_name VARCHAR(50) NOT NULL,+ email VARCHAR(100),+ phone VARCHAR(20),+ address NVARCHAR(200),+ city NVARCHAR(50),+ state CHAR(2),+ zip_code VARCHAR(10),+ country VARCHAR(50) DEFAULT 'USA',+ created_date DATETIME DEFAULT GETDATE(),+ modified_date DATETIME,+ is_active BIT DEFAULT 1,+ credit_limit DECIMAL(10,2) DEFAULT 0.00,+ CONSTRAINT PK_customers PRIMARY KEY CLUSTERED (customer_id),+ CONSTRAINT UQ_customers_email UNIQUE (email),+ CONSTRAINT CK_customers_credit_limit CHECK (credit_limit >= 0)+ );++ CREATE NONCLUSTERED INDEX IX_customers_name ON dbo.customers (last_name, first_name);+ CREATE NONCLUSTERED INDEX IX_customers_email ON dbo.customers (email) WHERE email IS NOT NULL;+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "tables": [+ {+ "name": "customers",+ "columns": [+ {+ "name": "customer_id",+ "DefaultValue": null,+ "type": "INT",+ "is_identity": true,+ "identity_seed": 1,+ "identity_increment": 1+ },+ {+ "name": "first_name",+ "DefaultValue": null,+ "type": "VARCHAR(50)"+ },+ {+ "name": "last_name",+ "DefaultValue": null,+ "type": "VARCHAR(50)"+ },+ {+ "name": "email",+ "DefaultValue": null,+ "nullable": true,+ "type": "VARCHAR(100)"+ },+ {+ "name": "phone",+ "DefaultValue": null,+ "nullable": true,+ "type": "VARCHAR(20)"+ },+ {+ "name": "address",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(200)"+ },+ {+ "name": "city",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(50)"+ },+ {+ "name": "state",+ "DefaultValue": null,+ "nullable": true,+ "type": "CHAR(2)"+ },+ {+ "name": "zip_code",+ "DefaultValue": null,+ "nullable": true,+ "type": "VARCHAR(10)"+ },+ {+ "name": "country",+ "DefaultValue": {+ "DefaultExpression": "'USA'"+ },+ "nullable": true,+ "type": "VARCHAR(50)"+ },+ {+ "name": "created_date",+ "DefaultValue": {+ "DefaultExpression": "GETDATE()"+ },+ "nullable": true,+ "type": "DATETIME"+ },+ {+ "name": "modified_date",+ "DefaultValue": null,+ "nullable": true,+ "type": "DATETIME"+ },+ {+ "name": "is_active",+ "DefaultValue": {+ "DefaultExpression": "1"+ },+ "nullable": true,+ "type": "BIT"+ },+ {+ "name": "credit_limit",+ "DefaultValue": {+ "DefaultExpression": "0.00"+ },+ "nullable": true,+ "type": "DECIMAL(10,2)"+ }+ ],+ "indexes": [+ {+ "name": "PK_customers",+ "expressions": [+ "customer_id"+ ],+ "descending": [+ false+ ],+ "type": "CLUSTERED",+ "unique": true,+ "primary": true,+ "is_constraint": true+ },+ {+ "name": "UQ_customers_email",+ "expressions": [+ "email"+ ],+ "descending": [+ false+ ],+ "unique": true,+ "is_constraint": true+ },+ {+ "name": "IX_customers_name",+ "expressions": [+ "last_name",+ "first_name"+ ],+ "descending": [+ false,+ false+ ],+ "type": "NONCLUSTERED"+ },+ {+ "name": "IX_customers_email",+ "expressions": [+ "email"+ ],+ "descending": [+ false+ ],+ "type": "NONCLUSTERED"+ }+ ],+ "check_constraints": [+ {+ "name": "CK_customers_credit_limit",+ "expression": "credit_limit \u003e= 0"+ }+ ]+ }+ ]+ }+ ]+ }+- input: |+ CREATE TABLE dbo.inventory (+ product_id INT NOT NULL,+ warehouse_id INT NOT NULL,+ quantity INT NOT NULL DEFAULT 0,+ last_updated DATETIME2 DEFAULT SYSDATETIME(),+ CONSTRAINT PK_inventory PRIMARY KEY (product_id, warehouse_id),+ CONSTRAINT CK_inventory_quantity CHECK (quantity >= 0)+ );+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "tables": [+ {+ "name": "inventory",+ "columns": [+ {+ "name": "product_id",+ "DefaultValue": null,+ "type": "INT"+ },+ {+ "name": "warehouse_id",+ "DefaultValue": null,+ "type": "INT"+ },+ {+ "name": "quantity",+ "DefaultValue": {+ "DefaultExpression": "0"+ },+ "type": "INT"+ },+ {+ "name": "last_updated",+ "DefaultValue": {+ "DefaultExpression": "SYSDATETIME()"+ },+ "nullable": true,+ "type": "DATETIME2"+ }+ ],+ "indexes": [+ {+ "name": "PK_inventory",+ "expressions": [+ "product_id",+ "warehouse_id"+ ],+ "descending": [+ false,+ false+ ],+ "unique": true,+ "primary": true,+ "is_constraint": true+ }+ ],+ "check_constraints": [+ {+ "name": "CK_inventory_quantity",+ "expression": "quantity \u003e= 0"+ }+ ]+ }+ ]+ }+ ]+ }+- input: |+ CREATE TABLE dbo.audit_log (+ log_id BIGINT IDENTITY(1,1) PRIMARY KEY,+ table_name SYSNAME NOT NULL,+ operation CHAR(1) NOT NULL,+ user_name NVARCHAR(128) DEFAULT SUSER_SNAME(),+ timestamp DATETIME2 DEFAULT SYSDATETIME(),+ old_values NVARCHAR(MAX),+ new_values NVARCHAR(MAX),+ CONSTRAINT CK_operation CHECK (operation IN ('I', 'U', 'D'))+ );+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "tables": [+ {+ "name": "audit_log",+ "columns": [+ {+ "name": "log_id",+ "DefaultValue": null,+ "type": "BIGINT",+ "is_identity": true,+ "identity_seed": 1,+ "identity_increment": 1+ },+ {+ "name": "table_name",+ "DefaultValue": null,+ "type": "SYSNAME"+ },+ {+ "name": "operation",+ "DefaultValue": null,+ "type": "CHAR(1)"+ },+ {+ "name": "user_name",+ "DefaultValue": {+ "DefaultExpression": "SUSER_SNAME()"+ },+ "nullable": true,+ "type": "NVARCHAR(128)"+ },+ {+ "name": "timestamp",+ "DefaultValue": {+ "DefaultExpression": "SYSDATETIME()"+ },+ "nullable": true,+ "type": "DATETIME2"+ },+ {+ "name": "old_values",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(MAX)"+ },+ {+ "name": "new_values",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(MAX)"+ }+ ],+ "indexes": [+ {+ "name": "PK_audit_log_1",+ "expressions": [+ "log_id"+ ],+ "descending": [+ false+ ],+ "unique": true,+ "primary": true,+ "is_constraint": true+ }+ ],+ "check_constraints": [+ {+ "name": "CK_operation",+ "expression": "operation IN ('I', 'U', 'D')"+ }+ ]+ }+ ]+ }+ ]+ }+- input: |+ CREATE TABLE dbo.documents (+ doc_id UNIQUEIDENTIFIER DEFAULT NEWID() PRIMARY KEY,+ title NVARCHAR(200) NOT NULL,+ content NVARCHAR(MAX),+ file_data VARBINARY(MAX),+ file_name NVARCHAR(255),+ file_size BIGINT,+ mime_type VARCHAR(100),+ created_by INT NOT NULL,+ created_date DATETIMEOFFSET DEFAULT SYSDATETIMEOFFSET(),+ version INT DEFAULT 1,+ is_published BIT DEFAULT 0+ );+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "tables": [+ {+ "name": "documents",+ "columns": [+ {+ "name": "doc_id",+ "DefaultValue": {+ "DefaultExpression": "NEWID()"+ },+ "type": "UNIQUEIDENTIFIER"+ },+ {+ "name": "title",+ "DefaultValue": null,+ "type": "NVARCHAR(200)"+ },+ {+ "name": "content",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(MAX)"+ },+ {+ "name": "file_data",+ "DefaultValue": null,+ "nullable": true,+ "type": "VARBINARY(MAX)"+ },+ {+ "name": "file_name",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(255)"+ },+ {+ "name": "file_size",+ "DefaultValue": null,+ "nullable": true,+ "type": "BIGINT"+ },+ {+ "name": "mime_type",+ "DefaultValue": null,+ "nullable": true,+ "type": "VARCHAR(100)"+ },+ {+ "name": "created_by",+ "DefaultValue": null,+ "type": "INT"+ },+ {+ "name": "created_date",+ "DefaultValue": {+ "DefaultExpression": "SYSDATETIMEOFFSET()"+ },+ "nullable": true,+ "type": "DATETIMEOFFSET"+ },+ {+ "name": "version",+ "DefaultValue": {+ "DefaultExpression": "1"+ },+ "nullable": true,+ "type": "INT"+ },+ {+ "name": "is_published",+ "DefaultValue": {+ "DefaultExpression": "0"+ },+ "nullable": true,+ "type": "BIT"+ }+ ],+ "indexes": [+ {+ "name": "PK_documents_1",+ "expressions": [+ "doc_id"+ ],+ "descending": [+ false+ ],+ "unique": true,+ "primary": true,+ "is_constraint": true+ }+ ]+ }+ ]+ }+ ]+ }+- input: |+ CREATE TABLE dbo.hierarchical_data (+ node_id INT IDENTITY(1,1) PRIMARY KEY,+ parent_id INT NULL,+ node_name NVARCHAR(100) NOT NULL,+ node_path HIERARCHYID,+ level AS node_path.GetLevel(),+ CONSTRAINT FK_hierarchical_self FOREIGN KEY (parent_id)+ REFERENCES dbo.hierarchical_data(node_id)+ );++ CREATE INDEX IX_hierarchical_path ON dbo.hierarchical_data (node_path);+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "tables": [+ {+ "name": "hierarchical_data",+ "columns": [+ {+ "name": "node_id",+ "DefaultValue": null,+ "type": "INT",+ "is_identity": true,+ "identity_seed": 1,+ "identity_increment": 1+ },+ {+ "name": "parent_id",+ "DefaultValue": null,+ "nullable": true,+ "type": "INT"+ },+ {+ "name": "node_name",+ "DefaultValue": null,+ "type": "NVARCHAR(100)"+ },+ {+ "name": "node_path",+ "DefaultValue": null,+ "nullable": true,+ "type": "HIERARCHYID"+ },+ {+ "name": "level",+ "DefaultValue": null,+ "nullable": true+ }+ ],+ "indexes": [+ {+ "name": "PK_hierarchical_data_1",+ "expressions": [+ "node_id"+ ],+ "descending": [+ false+ ],+ "unique": true,+ "primary": true,+ "is_constraint": true+ },+ {+ "name": "IX_hierarchical_path",+ "expressions": [+ "node_path"+ ],+ "descending": [+ false+ ]+ }+ ],+ "foreign_keys": [+ {+ "name": "FK_hierarchical_self",+ "columns": [+ "parent_id"+ ],+ "referenced_schema": "dbo",+ "referenced_table": "hierarchical_data",+ "referenced_columns": [+ "node_id"+ ],+ "on_delete": "NO ACTION",+ "on_update": "NO ACTION"+ }+ ]+ }+ ]+ }+ ]+ }+- input: |+ CREATE TABLE dbo.edge_cases (+ [Column With Spaces] INT,+ [Column-With-Dashes] NVARCHAR(50),+ [Column.With.Dots] VARCHAR(100),+ [列名] NVARCHAR(50),+ [SELECT] INT,+ [FROM] VARCHAR(50),+ [WHERE] BIT+ );+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "tables": [+ {+ "name": "edge_cases",+ "columns": [+ {+ "name": "Column With Spaces",+ "DefaultValue": null,+ "nullable": true,+ "type": "INT"+ },+ {+ "name": "Column-With-Dashes",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(50)"+ },+ {+ "name": "Column.With.Dots",+ "DefaultValue": null,+ "nullable": true,+ "type": "VARCHAR(100)"+ },+ {+ "name": "列名",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(50)"+ },+ {+ "name": "SELECT",+ "DefaultValue": null,+ "nullable": true,+ "type": "INT"+ },+ {+ "name": "FROM",+ "DefaultValue": null,+ "nullable": true,+ "type": "VARCHAR(50)"+ },+ {+ "name": "WHERE",+ "DefaultValue": null,+ "nullable": true,+ "type": "BIT"+ }+ ]+ }+ ]+ }+ ]+ }+- input: |+ CREATE TABLE dbo.all_data_types (+ -- Exact numerics+ col_bit BIT,+ col_tinyint TINYINT,+ col_smallint SMALLINT,+ col_int INT,+ col_bigint BIGINT,+ col_decimal DECIMAL(18,4),+ col_numeric NUMERIC(15,2),+ col_smallmoney SMALLMONEY,+ col_money MONEY,++ -- Approximate numerics+ col_float FLOAT,+ col_real REAL,++ -- Date and time+ col_date DATE,+ col_time TIME,+ col_datetime DATETIME,+ col_datetime2 DATETIME2,+ col_smalldatetime SMALLDATETIME,+ col_datetimeoffset DATETIMEOFFSET,++ -- Character strings+ col_char CHAR(10),+ col_varchar VARCHAR(50),+ col_varchar_max VARCHAR(MAX),+ col_text TEXT,++ -- Unicode character strings+ col_nchar NCHAR(10),+ col_nvarchar NVARCHAR(50),+ col_nvarchar_max NVARCHAR(MAX),+ col_ntext NTEXT,++ -- Binary strings+ col_binary BINARY(10),+ col_varbinary VARBINARY(50),+ col_varbinary_max VARBINARY(MAX),+ col_image IMAGE,++ -- Other data types+ col_uniqueidentifier UNIQUEIDENTIFIER,+ col_xml XML,+ col_timestamp TIMESTAMP,+ col_hierarchyid HIERARCHYID,+ col_geography GEOGRAPHY,+ col_geometry GEOMETRY,+ col_sql_variant SQL_VARIANT+ );+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "tables": [+ {+ "name": "all_data_types",+ "columns": [+ {+ "name": "col_bit",+ "DefaultValue": null,+ "nullable": true,+ "type": "BIT"+ },+ {+ "name": "col_tinyint",+ "DefaultValue": null,+ "nullable": true,+ "type": "TINYINT"+ },+ {+ "name": "col_smallint",+ "DefaultValue": null,+ "nullable": true,+ "type": "SMALLINT"+ },+ {+ "name": "col_int",+ "DefaultValue": null,+ "nullable": true,+ "type": "INT"+ },+ {+ "name": "col_bigint",+ "DefaultValue": null,+ "nullable": true,+ "type": "BIGINT"+ },+ {+ "name": "col_decimal",+ "DefaultValue": null,+ "nullable": true,+ "type": "DECIMAL(18,4)"+ },+ {+ "name": "col_numeric",+ "DefaultValue": null,+ "nullable": true,+ "type": "NUMERIC(15,2)"+ },+ {+ "name": "col_smallmoney",+ "DefaultValue": null,+ "nullable": true,+ "type": "SMALLMONEY"+ },+ {+ "name": "col_money",+ "DefaultValue": null,+ "nullable": true,+ "type": "MONEY"+ },+ {+ "name": "col_float",+ "DefaultValue": null,+ "nullable": true,+ "type": "FLOAT"+ },+ {+ "name": "col_real",+ "DefaultValue": null,+ "nullable": true,+ "type": "REAL"+ },+ {+ "name": "col_date",+ "DefaultValue": null,+ "nullable": true,+ "type": "DATE"+ },+ {+ "name": "col_time",+ "DefaultValue": null,+ "nullable": true,+ "type": "TIME"+ },+ {+ "name": "col_datetime",+ "DefaultValue": null,+ "nullable": true,+ "type": "DATETIME"+ },+ {+ "name": "col_datetime2",+ "DefaultValue": null,+ "nullable": true,+ "type": "DATETIME2"+ },+ {+ "name": "col_smalldatetime",+ "DefaultValue": null,+ "nullable": true,+ "type": "SMALLDATETIME"+ },+ {+ "name": "col_datetimeoffset",+ "DefaultValue": null,+ "nullable": true,+ "type": "DATETIMEOFFSET"+ },+ {+ "name": "col_char",+ "DefaultValue": null,+ "nullable": true,+ "type": "CHAR(10)"+ },+ {+ "name": "col_varchar",+ "DefaultValue": null,+ "nullable": true,+ "type": "VARCHAR(50)"+ },+ {+ "name": "col_varchar_max",+ "DefaultValue": null,+ "nullable": true,+ "type": "VARCHAR(MAX)"+ },+ {+ "name": "col_text",+ "DefaultValue": null,+ "nullable": true,+ "type": "TEXT"+ },+ {+ "name": "col_nchar",+ "DefaultValue": null,+ "nullable": true,+ "type": "NCHAR(10)"+ },+ {+ "name": "col_nvarchar",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(50)"+ },+ {+ "name": "col_nvarchar_max",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(MAX)"+ },+ {+ "name": "col_ntext",+ "DefaultValue": null,+ "nullable": true,+ "type": "NTEXT"+ },+ {+ "name": "col_binary",+ "DefaultValue": null,+ "nullable": true,+ "type": "BINARY(10)"+ },+ {+ "name": "col_varbinary",+ "DefaultValue": null,+ "nullable": true,+ "type": "VARBINARY(50)"+ },+ {+ "name": "col_varbinary_max",+ "DefaultValue": null,+ "nullable": true,+ "type": "VARBINARY(MAX)"+ },+ {+ "name": "col_image",+ "DefaultValue": null,+ "nullable": true,+ "type": "IMAGE"+ },+ {+ "name": "col_uniqueidentifier",+ "DefaultValue": null,+ "nullable": true,+ "type": "UNIQUEIDENTIFIER"+ },+ {+ "name": "col_xml",+ "DefaultValue": null,+ "nullable": true,+ "type": "XML"+ },+ {+ "name": "col_timestamp",+ "DefaultValue": null,+ "nullable": true,+ "type": "TIMESTAMP"+ },+ {+ "name": "col_hierarchyid",+ "DefaultValue": null,+ "nullable": true,+ "type": "HIERARCHYID"+ },+ {+ "name": "col_geography",+ "DefaultValue": null,+ "nullable": true,+ "type": "GEOGRAPHY"+ },+ {+ "name": "col_geometry",+ "DefaultValue": null,+ "nullable": true,+ "type": "GEOMETRY"+ },+ {+ "name": "col_sql_variant",+ "DefaultValue": null,+ "nullable": true,+ "type": "SQL_VARIANT"+ }+ ]+ }+ ]+ }+ ]+ }+- input: |+ CREATE TABLE dbo.collation_test (+ id INT PRIMARY KEY,+ case_sensitive VARCHAR(50) COLLATE Latin1_General_CS_AS,+ case_insensitive VARCHAR(50) COLLATE Latin1_General_CI_AS,+ accent_sensitive NVARCHAR(50) COLLATE Latin1_General_CI_AS,+ accent_insensitive NVARCHAR(50) COLLATE Latin1_General_CI_AI,+ binary_sort VARCHAR(50) COLLATE Latin1_General_BIN2+ );+ result: |-+ {+ "schemas": [+ {+ "name": "dbo",+ "tables": [+ {+ "name": "collation_test",+ "columns": [+ {+ "name": "id",+ "DefaultValue": null,+ "type": "INT"+ },+ {+ "name": "case_sensitive",+ "DefaultValue": null,+ "nullable": true,+ "type": "VARCHAR(50)",+ "collation": "Latin1_General_CS_AS"+ },+ {+ "name": "case_insensitive",+ "DefaultValue": null,+ "nullable": true,+ "type": "VARCHAR(50)",+ "collation": "Latin1_General_CI_AS"+ },+ {+ "name": "accent_sensitive",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(50)",+ "collation": "Latin1_General_CI_AS"+ },+ {+ "name": "accent_insensitive",+ "DefaultValue": null,+ "nullable": true,+ "type": "NVARCHAR(50)",+ "collation": "Latin1_General_CI_AI"+ },+ {+ "name": "binary_sort",+ "DefaultValue": null,+ "nullable": true,+ "type": "VARCHAR(50)",+ "collation": "Latin1_General_BIN2"+ }+ ],+ "indexes": [+ {+ "name": "PK_collation_test_1",+ "expressions": [+ "id"+ ],+ "descending": [+ false+ ],+ "unique": true,+ "primary": true,+ "is_constraint": true+ }+ ]+ }+ ]+ }+ ]+ }diff --git a/backend/plugin/schema/schema.go b/backend/plugin/schema/schema.goindex 8b512ef1ee..ec5de75d99 100644--- a/backend/plugin/schema/schema.go+++ b/backend/plugin/schema/schema.go@@ -20,6 +20,7 @@ var (getFunctionDefinitions = make(map[storepb.Engine]getFunctionDefinition)getProcedureDefinitions = make(map[storepb.Engine]getProcedureDefinition)getSequenceDefinitions = make(map[storepb.Engine]getSequenceDefinition)+ getDatabaseMetadataMap = make(map[storepb.Engine]getDatabaseMetadata))type checkColumnType func(string) bool@@ -31,6 +32,7 @@ type getMaterializedViewDefinition func(string, *storepb.MaterializedViewMetadattype getFunctionDefinition func(string, *storepb.FunctionMetadata) (string, error)type getProcedureDefinition func(string, *storepb.ProcedureMetadata) (string, error)type getSequenceDefinition func(string, *storepb.SequenceMetadata) (string, error)+type getDatabaseMetadata func(string) (*storepb.DatabaseSchemaMetadata, error)type GetDefinitionContext struct {SkipBackupSchema bool@@ -189,3 +191,20 @@ func CheckColumnType(engine storepb.Engine, tp string) bool {}return f(tp)}++func RegisterGetDatabaseMetadata(engine storepb.Engine, f getDatabaseMetadata) {+ mux.Lock()+ defer mux.Unlock()+ if _, dup := getDatabaseMetadataMap[engine]; dup {+ panic(fmt.Sprintf("Register called twice %s", engine))+ }+ getDatabaseMetadataMap[engine] = f+}++func GetDatabaseMetadata(engine storepb.Engine, schemaText string) (*storepb.DatabaseSchemaMetadata, error) {+ f, ok := getDatabaseMetadataMap[engine]+ if !ok {+ return nil, errors.Errorf("engine %s is not supported", engine)+ }+ return f(schemaText)+}diff --git a/go.mod b/go.modindex cecbcb74f9..152abed32a 100644--- a/go.mod+++ b/go.mod@@ -290,7 +290,7 @@ require (github.com/aws/smithy-go v1.22.3 // indirectgithub.com/beorn7/perks v1.0.1 // indirectgithub.com/bytebase/partiql-parser v0.0.0-20240531101102-1962ff456f2c- github.com/bytebase/tsql-parser v0.0.0-20250311085620-1db45111863e+ github.com/bytebase/tsql-parser v0.0.0-20250603072002-329b1b7f99a7github.com/cespare/xxhash/v2 v2.3.0 // indirectgithub.com/cncf/xds/go v0.0.0-20250121191232-2f005788dc42 // indirectgithub.com/cockroachdb/cockroach-go/v2 v2.4.0diff --git a/go.sum b/go.sumindex 16e1514d11..a8a6854ba1 100644--- a/go.sum+++ b/go.sum@@ -874,8 +874,8 @@ github.com/bytebase/tidb2/pkg/parser v0.0.0-20231129002249-5bbb6bb83940 h1:PZ22Fgithub.com/bytebase/tidb2/pkg/parser v0.0.0-20231129002249-5bbb6bb83940/go.mod h1:yRkiqLFwIqibYg2P7h4bclHjHcJiIFRLKhGRyBcKYus=github.com/bytebase/trino-parser v0.0.0-20250502000119-9977709a63e8 h1:gSJFO4jHhIIDQjTnyrdDncsxMYhtILZip1B8mCSlJIg=github.com/bytebase/trino-parser v0.0.0-20250502000119-9977709a63e8/go.mod h1:n0hMVu7KFEBzmYW0q6Kyd/dJ7cng8+YY0sZeDSWIX8g=-github.com/bytebase/tsql-parser v0.0.0-20250311085620-1db45111863e h1:R7yllkuKkKLbsbZx/OPN985g3QWHrwz4ixq7OGnn2Tw=-github.com/bytebase/tsql-parser v0.0.0-20250311085620-1db45111863e/go.mod h1:L9qgmrnVenkm/SL/fmyUSXK5+iMT1ctn/EsMqItSGVk=+github.com/bytebase/tsql-parser v0.0.0-20250603072002-329b1b7f99a7 h1:wnSjjBXMfE29+da0TUQUpYNa8A1FOZNKYh3jFY2zMl4=+github.com/bytebase/tsql-parser v0.0.0-20250603072002-329b1b7f99a7/go.mod h1:L9qgmrnVenkm/SL/fmyUSXK5+iMT1ctn/EsMqItSGVk=github.com/caarlos0/env/v11 v11.3.1 h1:cArPWC15hWmEt+gWk7YBi7lEXTXCvpaSdCiZE2X5mCA=github.com/caarlos0/env/v11 v11.3.1/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U=github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ=