feat: add mssql info extraction script
This commit is contained in:
107
scripts/mssql-info-test/main.go
Normal file
107
scripts/mssql-info-test/main.go
Normal file
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user