From 50169bee9effbbdf0dcd36b776fbe3aa9c73ea37 Mon Sep 17 00:00:00 2001 From: Kylesoda <249518290+kylesoda@users.noreply.github.com> Date: Thu, 2 Apr 2026 18:23:55 -0500 Subject: [PATCH] feat: add mssql info extraction script --- scripts/mssql-info-test/main.go | 107 ++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 scripts/mssql-info-test/main.go diff --git a/scripts/mssql-info-test/main.go b/scripts/mssql-info-test/main.go new file mode 100644 index 0000000..e7be813 --- /dev/null +++ b/scripts/mssql-info-test/main.go @@ -0,0 +1,107 @@ +package main + +import ( + "database/sql" + "time" + + "git.ksdemosapps.com/kylesoda/go-migrate/internal/app/config" + _ "github.com/microsoft/go-mssqldb" + log "github.com/sirupsen/logrus" +) + +func main() { + log.SetFormatter(&log.TextFormatter{ + FullTimestamp: true, + TimestampFormat: time.StampMilli, + }) + log.SetLevel(log.DebugLevel) + + db, err := sql.Open("sqlserver", config.App.SourceDbUrl) + if err != nil { + log.Fatal("Unexpected error connecting to mssql", err) + } + + log.Debug(config.App.SourceDbUrl) + + if err := db.Ping(); err != nil { + log.Fatal("Couldn't ping mssql db", err) + } + + schema := "test" + table := "migration_test" + + columns, err := getTableMetadata(db, schema, table) + if err != nil { + log.Fatal("Unexpected error extracting table info", err) + } + + log.Info("Table info:") + + for _, c := range columns { + log.Infof("%+v", c) + } +} + +type ColumnInfo struct { + Name string + UserDataType string + SystemDataType string + MaxLength int16 + Precision uint8 + Scale uint8 + Nullable bool + IsIdentity bool +} + +func getTableMetadata(db *sql.DB, schema, table string) ([]ColumnInfo, error) { + query := ` +SELECT + c.name AS column_name, + t.name AS user_type_name, + bt.name AS system_type_name, + c.max_length, + c.precision, + c.scale, + c.is_nullable, + c.is_identity +FROM sys.columns c +JOIN sys.types t ON c.user_type_id = t.user_type_id +JOIN sys.types bt ON c.system_type_id = bt.system_type_id AND bt.user_type_id = bt.system_type_id +JOIN sys.tables st ON c.object_id = st.object_id +JOIN sys.schemas s ON st.schema_id = s.schema_id +WHERE s.name = @schema AND st.name = @table +ORDER BY c.column_id;` + + rows, err := db.Query(query, sql.Named("schema", schema), sql.Named("table", table)) + if err != nil { + log.Warn(err) + + return nil, err + } + defer rows.Close() + + var columns []ColumnInfo + for rows.Next() { + var c ColumnInfo + err := rows.Scan( + &c.Name, + &c.UserDataType, + &c.SystemDataType, + &c.MaxLength, + &c.Precision, + &c.Scale, + &c.Nullable, + &c.IsIdentity, + ) + + if err != nil { + log.Warn(err) + + return nil, err + } + + columns = append(columns, c) + } + + return columns, nil +}