87 lines
1.9 KiB
Go
87 lines
1.9 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
"sync"
|
|
"time"
|
|
|
|
"git.ksdemosapps.com/kylesoda/go-migrate/internal/app/config"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
_ "github.com/microsoft/go-mssqldb"
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
func main() {
|
|
configureLog()
|
|
log.Info("Starting migration...")
|
|
|
|
var sourceDb *sql.DB
|
|
var targetDb *pgxpool.Pool
|
|
|
|
connectToDatabases(sourceDb, targetDb)
|
|
|
|
log.Info("Migration completed successfully!")
|
|
}
|
|
|
|
func connectToSqlServer() (*sql.DB, error) {
|
|
db, err := sql.Open("sqlserver", config.App.SourceDbUrl)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("Unable to connect to sqlserver: %w", err)
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
defer cancel()
|
|
|
|
if err := db.PingContext(ctx); err != nil {
|
|
return nil, fmt.Errorf("Unable to ping sqlserver: %w", err)
|
|
}
|
|
|
|
return db, nil
|
|
}
|
|
|
|
func connectToPostgres() (*pgxpool.Pool, error) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
defer cancel()
|
|
|
|
pool, err := pgxpool.New(ctx, config.App.TargetDbUrl)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("Unable to connect to postgres: %w", err)
|
|
}
|
|
|
|
if err := pool.Ping(ctx); err != nil {
|
|
pool.Close()
|
|
return nil, fmt.Errorf("Unable to ping postgres: %w", err)
|
|
}
|
|
|
|
return pool, nil
|
|
}
|
|
|
|
func connectToDatabases(sourceDb *sql.DB, targetDb *pgxpool.Pool) error {
|
|
var sourceDbErr, targetDbErr error
|
|
var wg sync.WaitGroup
|
|
|
|
wg.Go(func() {
|
|
sourceDb, sourceDbErr = connectToSqlServer()
|
|
if sourceDbErr != nil {
|
|
log.Error("Unable to connect to source db: ", sourceDbErr)
|
|
}
|
|
})
|
|
|
|
wg.Go(func() {
|
|
targetDb, targetDbErr = connectToPostgres()
|
|
if targetDbErr != nil {
|
|
log.Error("Unable to connect to target db: ", targetDbErr)
|
|
}
|
|
})
|
|
|
|
wg.Wait()
|
|
|
|
if sourceDbErr != nil || targetDbErr != nil {
|
|
return fmt.Errorf("Unable to connect to databases: %w (source), %w (target)", sourceDbErr, targetDbErr)
|
|
}
|
|
|
|
return nil
|
|
}
|