Skip to content

Instantly share code, notes, and snippets.

@qascade
Created March 30, 2023 20:16
Show Gist options
  • Save qascade/ec04c90d1cd93a1a208a157b17deca16 to your computer and use it in GitHub Desktop.
Save qascade/ec04c90d1cd93a1a208a157b17deca16 to your computer and use it in GitHub Desktop.
Migrating data from postgres to mysql using tls options.
package main
import (
"crypto/tls"
"crypto/x509"
"database/sql"
"io/ioutil"
"log"
"github.com/go-sql-driver/mysql"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/mysql"
_ "github.com/golang-migrate/migrate/v4/source/file"
"github.com/lib/pq"
"github.com/golang-migrate/migrate/v4/database/postgres"
)
func main() {
// Postgres database configuration
postgresDSN := "user=postgresuser password=postgrespassword dbname=postgresdb sslmode=require"
// MySQL database configuration
mysqlDSN := "mysqluser:mysqlpassword@tcp(mysqlhost:3306)/mysqldb"
// Load the client certificate for Postgres
clientCert, err := ioutil.ReadFile("client.cert")
if err != nil {
panic(err)
}
// Load the client key for Postgres
clientKey, err := ioutil.ReadFile("client.key")
if err != nil {
panic(err)
}
// Load the CA certificate for Postgres
caCert, err := ioutil.ReadFile("ca.cert")
if err != nil {
panic(err)
}
// Create a new TLS configuration for Postgres
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{
{
Certificate: [][]byte{clientCert},
PrivateKey: clientKey,
},
},
RootCAs: x509.NewCertPool(),
}
if ok := tlsConfig.RootCAs.AppendCertsFromPEM(caCert); !ok {
panic("Failed to load CA certificate for Postgres")
}
// Create a new Postgres database connection with TLS
postgresDB, err := sql.Open("postgres", postgresDSN)
if err != nil {
panic(err)
}
postgresDB.SetTLSConfig(tlsConfig)
defer postgresDB.Close()
// Create a new MySQL database connection with TLS
mysqlConfig, err := mysql.ParseDSN(mysqlDSN)
if err != nil {
panic(err)
}
mysqlConfig.TLSConfig = "custom"
mysqlConfig.TLSConfigCustom = tlsConfig
mysqlDSN = mysqlConfig.FormatDSN()
mysqlDB, err := sql.Open("mysql", mysqlDSN)
if err != nil {
panic(err)
}
defer mysqlDB.Close()
// Create new database instances for Postgres and MySQL
postgresDriver, err := postgres.WithInstance(postgresDB, &postgres.Config{})
if err != nil {
panic(err)
}
mysqlDriver, err := mysql.WithInstance(mysqlDB, &mysql.Config{})
if err != nil {
panic(err)
}
// Create a new migrate instance for Postgres
m, err := migrate.NewWithDatabaseInstance(
"file:///path/to/migrations",
"postgres", postgresDriver,
)
if err != nil {
panic(err)
}
// Migrate Postgres schema
err = m.Up()
if err != nil {
panic(err)
}
// Create a new migrate instance for MySQL
m, err = migrate.NewWithDatabaseInstance(
"file:///path/to/migrations",
"mysql", mysqlDriver,
)
if err != nil {
panic(err)
}
// Migrate MySQL schema
err = m.Up()
if err != nil{
panic(err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment