How do I write data from R to PostgreSQL tables with an autoincrementing primary key?

后端 未结 2 1567
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-18 23:10

I have a table in a PostgreSQL database that has a BIGSERIAL auto-incrementing primary key. Recreate it using:

CREATE TABLE foo
(
  \"Id\" bigs         


        
2条回答
  •  不知归路
    2020-12-18 23:28

    From the thread in hrbrmstr's comment, I found a hack to make this work.

    In the postgresqlWriteTable in the RPostgreSQL package, you need to replace the line

    sql4 <- paste("COPY", postgresqlTableRef(name), "FROM STDIN")
    

    with

    sql4 <- paste(
      "COPY ", 
      postgresqlTableRef(name), 
      "(", 
      paste(postgresqlQuoteId(names(value)), collapse = ","), 
      ") FROM STDIN"
    )
    

    Note that the quoting of variables (not included in the original hack) is necessary to pass case-sensitive column names.

    Here's a script to do that:

    body_lines <- deparse(body(RPostgreSQL::postgresqlWriteTable))
    new_body_lines <- sub(
      'postgresqlTableRef(name), "FROM STDIN")', 
      'postgresqlTableRef(name), "(", paste(shQuote(names(value)), collapse = ","), ") FROM STDIN")', 
      body_lines,
      fixed = TRUE
    )
    fn <- RPostgreSQL::postgresqlWriteTable
    body(fn) <- parse(text = new_body_lines)
    while("RPostgreSQL" %in% search()) detach("package:RPostgreSQL")
    assignInNamespace("postgresqlWriteTable", fn, "RPostgreSQL")
    

提交回复
热议问题