postgresql - 使用 Go 从一个 postgres 数据库复制到另一个

标签 postgresql go copy etl

我想使用 Go 将数据库 A 中的 postgres 数据, View A 复制到数据库 B,表 B 中。这将针对几十个表完成,我想利用 Go 提供的并发性。

我可以使用看起来像这样的 psql 命令行来做到这一点:

psql -h hostServer -p 5432 -U dbUser -d dbName \
    -c "\copy (Select * From myView) TO STDOUT" \
    | psql -h destinationHost -p 5432 -U dbUser -d destinationDB \
    -c "\copy destinationTable FROM STDIN"

或者在 Python 中通过运行上述命令或使用 os.pipe 和 psycpog2 的 copy_from/to 命令。不幸的是,这些选项似乎都不能很好地处理并发性。这就是为什么我希望在 go 中做同样的事情。

所以我的问题 - 我如何在 GO 中运行上述命令行命令?或者通过管道将数据传入/传出不同的 postgres 数据库?我一直在尝试以下代码,但没有成功。任何提示将不胜感激。
import "github.com/go-pg/pg"

//connect to source and destination db's (successful connection confirmed)

r, w := io.Pipe()

println("start")

_, err := destDB.CopyFrom(r, "COPY destinationTable FROM STDIN")
if err != nil {
    println(err)
}

_, err = srcDB.CopyTo(w, "COPY (SELECT * FROM sourceView) TO STDOUT")
if err != nil {
    println(err)
}

srcDB.Close()
destDB.Close()

最佳答案

读取器和写入器应该在不同的 goroutine 中,并且管道的写入端应该在完成后关闭,以防止读取端挂起。请参阅以下内容作为起点:

    r, w := io.Pipe()

    writer := make(chan error)
    go func() {
        defer w.Close()
        _, err := src.CopyTo(w, `COPY (SELECT * FROM sourceView) TO STDOUT`)
        writer <- err
    }()

    reader := make(chan error)
    go func() {
        _, err := dest.CopyFrom(r, "COPY destinationTable FROM STDIN")
        reader <- err
    }()

    errWriter := <-writer
    if errWriter != nil {
        fmt.Printf("Writer (CopyTo) error: %v", errWriter)
    }

    errReader := <-reader
    if errReader != nil {
        fmt.Printf("Reader (CopyFrom) error: %v", errReader)
    }

    if errWriter == nil && errReader == nil {
        fmt.Println("All done - no errors")
    }

关于postgresql - 使用 Go 从一个 postgres 数据库复制到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60348559/

相关文章:

batch-file - 批处理文件递归复制目录

struct - 通过值或指针访问另一个结构

c - 为什么 Golang 比 ANSI C 快,我该如何优化我的解决方案?

sql - PostgreSQL : How do I select top n percent(%) entries from each group/category

database - 将 hstore 数据类型从 PostgreSQL 迁移到 CockroachDB

git - 如何使 git2go tree.Walk() 非递归并显示文件夹并从目标文件夹开始?

linux - 在终端 session 中复制/粘贴

C++ 复制构造函数导致代码无法编译 (gcc)

java - org.apache.axis2.AxisFault 连接被拒绝

postgresql - 使用 Postgresql 设置一些 bytea 列