【问题标题】:Read/write Postgres large objects with DBI & RPostgres使用 DBI 和 RPostgres 读/写 Postgres 大对象
【发布时间】:2022-01-13 04:51:57
【问题描述】:

我正在尝试在 R 中使用 PostgreSQL 的大对象 (https://www.postgresql.org/docs/10/largeobjects.html) 功能,但在使用 {DBI}/{RPostgres} 进行读写时遇到了一些问题。

这是我迄今为止尝试过的:

# Getting the db
docker run --rm --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d -p 5433:5432 postgres
library(DBI)
con <- dbConnect(
  RPostgres::Postgres(),
  dbname = "postgres",
  host = "localhost",
  port = 5433,
  user = "postgres",
  password = "mysecretpassword"
)

创作作品:

> dbGetQuery(con, "SELECT lo_create(1234);")
  lo_create
1      1234

但是我很难弄清楚如何将 R 对象写入这个大对象。 例如,如何在 Postgres 中使用 {DBI}{RPostgres}mtcars 写为大对象?

然后,我如何在 R 中再次读回它?

【问题讨论】:

    标签: r postgresql rpostgresql


    【解决方案1】:

    我写了这个例子,它可以工作。我希望这是你正在寻找的。 https://gist.github.com/jrosell/7f0ac7df292c750c89582f33930e57e9

    library(RPostgres)
    
    # Get and read the PDF
    path <- file.path("os2.pdf")
    pdf <- readBin(con = path, what = raw(), n = file.info(path)$size)
    
    # Open it
    browseURL(path)
    
    # Connect to default DB and put seralized raw pdf in a data.frame
    # sudo -u postgres createuser jordi
    # sudo -u postgres createdb jordi --owner=jordi
    con <- dbConnect(RPostgres::Postgres())
    pdf_serialized <- serialize(pdf, NULL)
    df <- data.frame(pdfs = I(list(pdf_serialized)))
    
    # Write the table in database
    dbWriteTable(conn = con, name = "mytable", value = df, overwrite = TRUE)
    
    # Read your table, unserialize and write the pdf in a temporary file
    out <- dbReadTable(conn = con, name = "mytable")
    pdf_out <- unserialize(out$pdfs[[1]])
    tmp <- tempfile(fileext = ".pdf")
    writeBin(object = pdf_out, con = tmp)
    
    # Open it
    browseURL(tmp)
    

    【讨论】:

    • 这是写一个常规的 BLOB 列吗? OP 专门询问 Postgres 的“大对象”。
    猜你喜欢
    • 1970-01-01
    • 2019-09-17
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多