Skip to content

Export Large Objects from Postgres #519

Closed

Description

@DavZim

It is really easy to write large files to Postgres using the function postgresImportLargeObject() (thanks to #472).
However, when the file is larger (eg 1GB+) it is hard to export the file again as one would have to use a query (and afaik fields are limited to 1GB), in fact I'm still trying to figure out how to get the file back out...

It would be great to have a postgresExportLargeObject function or similar which can download the file again.

Eg a simple example code is this (assumes a valid con):

file <- "mytestfile.bin"
# generate a file with 800MB filesize using bash
# system(sprintf("dd if=/dev/urandom of=%s bs=1M count=800", file))
prettyunits::pretty_bytes(file.size(file))
#> [1] "838.86 MB"

# 1. Create Table =====
DBI::dbExecute(
  con,
  "CREATE TABLE IF NOT EXISTS lo_tester (
    id SERIAL PRIMARY KEY,
    name TEXT,
    lo_link OID
  )"
)
"lo_tester" %in% DBI::dbListTables(con)
#> [1] TRUE

# 2. Insert Large Object =====
t0 <- Sys.time()
DBI::dbWithTransaction(con, {
  oid <- RPostgres::postgresImportLargeObject(con, file)
  q <- sprintf(
    "INSERT INTO lo_tester (name, lo_link) VALUES ('%s', %d);",
    file,
    oid
  )
  DBI::dbExecute(con, q)
})
cat(sprintf("Inserting took %0.2fs\n", difftime(Sys.time(), t0, units = "secs")))
#> Inserting took 144.86s

# inserted as oid
oid
#> [1] 557400

DBI::dbGetQuery(con, "SELECT * FROM lo_tester;")
#>   id           name lo_link
#> 1  1 mytestfile.bin  557400


# 3. Fetch the data again ====
r <- DBI::dbGetQuery(con, "SELECT lo_get($1) as lo_data", params = list(oid))
#> Error: Failed to fetch row : ERROR:  invalid memory alloc request size 1677721603

Here postgresExportLargeObject could look like this DBI::postgresExportLargeObject(con, oid, "mytestfile_out.bin").

Is this something that you would consider useful in the package?

Activity

  1. krlmlr commented on Sep 10, 2025

    @krlmlr
    Member

    Thanks. Can you use the offset and length arguments to lo_get() for chunking the data and reassembling client-side? If you're writing to a file, fetching rowwise with dbFetch(n = 1) will also reduce memory pressure.

    I'm not sure if lo_get() exists elsewhere; we could discuss a RPostgres::postgresExportLargeObject() function based on an implementation sketch that works for you.

  2. DavZim commented on Sep 10, 2025

    @DavZim
    Author

    As I am looking at a single object at a time, n = 1 doesnt help too much.

    For the moment I have a function like this, which allows me to download a LO based on its oid

    # gets the size of an oid object
    get_oid_size <- function(con, oid) {
      query <- sprintf("
        WITH lo AS (  SELECT lo_open(%d, 262144) AS fd  ),
          seek AS (  SELECT lo_lseek(fd, 0, 2) AS pos, fd FROM lo  ),
          tell AS (  SELECT lo_tell(fd) AS size, fd FROM seek  )
        SELECT size FROM tell;
      ", oid)
    
      # Execute the block
      DBI::dbGetQuery(con, query)[[1]]
    }
    
    # Downloads a large object in chunks
    download_oid <- function(con, oid, outfile, max_chunk_size = 200 * 1024^2) {
      size <- get_oid_size(con, oid)
    
      if (size <= max_chunk_size) {
        r <- DBI::dbGetQuery(con, "SELECT lo_get($1) AS lo_data", params = list(oid))
        writeBin(r$lo_data[[1]], outfile)
        return(invisible(outfile))
      } else {
        n_chunks <- ceiling(size / max_chunk_size)
        con_out <- file(outfile, "wb")
        on.exit(try(close(con_out), silent = TRUE), add = TRUE)
    
        for (i in seq_len(n_chunks)) {
          offset <- (i - 1) * max_chunk_size
          bytes_to_read <- if (i < n_chunks) max_chunk_size else (size - offset)
          message("Downloading chunk ", i, " of ", n_chunks, " - offset ",
                  offset, " bytes_to_read ", bytes_to_read, " - ", prettyunits::pretty_bytes(bytes_to_read))
    
          r <- DBI::dbGetQuery(con, "SELECT lo_get($1, $2, $3) AS lo_data",
                               params = list(oid, offset, bytes_to_read))
          writeBin(r$lo_data[[1]], con_out)
        }
        close(con_out)
        return(invisible(outfile))
      }
    }
    # deletes a LO
    delete_oid <- function(con, oid) {
      DBI::dbExecute(con, "SELECT lo_unlink($1);", params = list(oid))
      invisible(TRUE)
    }
    
    file.size(outfile)
    #> [1] 838860800
    file.size(file)
    #> [1] 838860800
    
    rlang::hash_file(outfile)
    #> [1] "f9bc115120c045115ecdb1784da09984"
    rlang::hash_file(file)
    #> [1] "f9bc115120c045115ecdb1784da09984"

    This works, but I am not sure if this is robust or fast enough for RPostgres or if there are better low-level alternatives to fetch and store the binary data.

  3. krlmlr commented on Sep 13, 2025

    @krlmlr
    Member

    Thanks. This is similar to what I had in mind. (I'm astonished by how difficult it is to get the size of such a large object.)

    I thought we could create a query that would return the equivalent of

    SELECT lo_get(oid, 0, 1000) AS lo_data
    UNION ALL
    SELECT lo_get(oid, 1000, 2000) AS lo_data
    UNION ALL
    SELECT lo_get(oid, 2000, 3000) AS lo_data
    UNION ALL
    ...
    

    and then use dbFetch(n = 1) . But I'm not sure if the first dbFetch() will not proactively fetch all the data, defeating the purpose of the chunking.

    It really looks like the readily available lo_export() is doing the right thing: https://github.com/postgres/postgres/blob/f6edf403a99923b98f8b8b3398c7ef32e1ae9a3e/src/interfaces/libpq/fe-lobj.c#L748 . Let me take a closer look.

  4. DavZim commented on Sep 13, 2025

    @DavZim
    Author

    As far as I remember, lo_export writes to file on the server and not on the client, right?

  5. krlmlr commented on Sep 13, 2025

    @krlmlr
    Member

    It's part of libpq, and we're already using lo_import() . I expect this to be symmetrical.

  6. krlmlr commented on Sep 13, 2025

    @krlmlr
    Member

    The PR #520 might be worth a try.

  7. DavZim commented on Sep 15, 2025

    @DavZim
    Author

    Wow, that was quick and a very interesting (positive) use-case of AI.

    The code works for me and does what I would expect it to.

    remotes::install_github("r-dbi/RPostgres#520")
    
    t0 <- Sys.time()
    DBI::dbWithTransaction(con, {
      RPostgres::postgresExportLargeObject(con, oid, "mytestfile_out.bin")
    })
    cat(sprintf("Export took %0.2fs\n", difftime(Sys.time(), t0, units = "secs")))
    #> Export took 145.03s
    
    rlang::hash_file("mytestfile_out.bin") == rlang::hash_file(file)
    #> [1] TRUE
  8. added a commit that references this issue on Feb 15, 2026
  9. github-actions commented on Sep 22, 2026

    @github-actions
    Contributor

    This old thread has been automatically locked. If you think you have found something related to this, please open a new issue and link to this old issue if necessary.

  10. locked and limited conversation to collaborators on Sep 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions