以下是一个用 Go 链接两个 PostgreSQL 数据库并比较两个表结构是否一致的示例代码:
package main
import (
"fmt"
"log"
"github.com/jackc/pgx/v4"
)
type Table struct {
Name string
Columns []Column
}
type Column struct {
Name string
DataType string
}
func main() {
// Connect to first database
conn1, err := pgx.Connect(context.Background(), "postgres://user:password@localhost:5432/db1")
if err != nil {
log.Fatal(err)
}
defer conn1.Close()
// Connect to second database
conn2, err := pgx.Connect(context.Background(), "postgres://user:password@localhost:5432/db2")
if err != nil {
log.Fatal(err)
}
defer conn2.Close()
// Get list of tables in first database
rows, err := conn1.Query(context.Background(), "SELECT table_name FROM information_schema.tables WHERE table_schema='public'")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var tables []Table
for rows.Next() {
var tableName string
err = rows.Scan(&tableName)
if err != nil {
log.Fatal(err)
}
// Get columns for table in first database
table1, err := getTable(conn1, tableName)
if err != nil {
log.Fatal(err)
}
// Get columns for table in second database
table2, err := getTable(conn2, tableName)
if err != nil {
log.Fatal(err)
}
// Compare tables
if !compareTables(table1, table2) {
fmt.Printf("Tables %s are not the same\n", tableName)
// Do something if tables are not the same
} else {
fmt.Printf("Tables %s are the same\n", tableName)
// Do something if tables are the same
}
}
if err = rows.Err(); err != nil {
log.Fatal(err)
}
}
func getTable(conn pgx.Conn, tableName string) (Table, error) {
var table Table
table.Name = tableName
rows, err := conn.Query(context.Background(), fmt.Sprintf("SELECT column_name, data_type FROM information_schema.columns WHERE table_name='%s'", tableName))
if err != nil {
return table, err
}
defer rows.Close()
for rows.Next() {
var columnName string
var dataType string
err = rows.Scan(&columnName, &dataType)
if err != nil {
return table, err
}
column := Column{Name: columnName, DataType: dataType}
table.Columns = append(table.Columns, column)
}
if err = rows.Err(); err != nil {
return table, err
}
return table, nil
}
func compareTables(table1 Table, table2 Table) bool {
if len(table1.Columns) != len(table2.Columns) {
return false
}
for i := 0; i < len(table1.Columns); i++ {
if table1.Columns[i].Name != table2.Columns[i].Name ||
table1.Columns[i].DataType != table2.Columns[i].DataType {
return false
}
}
return true
}
这个代码使用了 pgx
包来连接 PostgreSQL 数据库,并比较两个数据库中的表是否具有相同的结构。首先,它获取第一个数据库中的所有表的列表,并遍历这个列表。对于每张表,它获取第一个数据库和第二个数据库中的列列表,并将它们与 compareTables
函数进行比较。如果两个表具有不同的结构,则会打印出错误消息或执行其他适当的操作。