在 PostgreSQL 中使用 r sf::st_write 到 non-public 模式

Using r sf::st_write to non-public schema in PostgreSQL

我正在尝试将空间 table 写入不是 PostgreSQL 数据库中默认 public 模式的模式。

library(sf)
library(DBI)
library(RPostgreSQL)
library(spData)

# PostgreSQL DB parameters
host <- "myHost" 
port <- 5432
username <- "myName"
dbname <- "myDb"
password <- "MyPassword"

# Connect to db  
conn <- dbConnect(PostgreSQL(), dbname = dbname, host = host, port = port, user = username, password = password)

st_write(obj = cycle_hire, dsn = conn, Id(schema="myOtherSchema", table = "myCycle")) # Write data to db - currently only writes to default schema

# Disconnect db
dbDisconnect(conn)

但这会将我的 table 添加到名称为 "myOtherSchema"."myCycle" 的 public 架构中。

上面也试过...

dbWriteTable(conn = conn, name = "myCycle", value = cycle_hire, Id(schema="mySchema"))

...替代 st_write,导致 myCycle 被写入 public 模式。

我做错了什么?

Session 信息:

R version 3.4.4 (2018-03-15)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows Server >= 2012 x64 (build 9200)

运行 Centos 7 上的 PostgreSQL 11.1 OS.

发生这种情况是因为您正在通过包 RPostgreSQL 连接到数据库,但是用于指定 table 和模式的语法与包 RPostgres 建立的连接一起使用。您可以使用以下方法解决此问题:

    require(RPostgres)
    conn <- dbConnect(Postgres(), dbname = dbname, host = host, port = port, 
                      user = username, password = password)
    st_write(obj = cycle_hire, dsn = conn, Id(schema="roads_spatial", table = "myCycle"))
require(RPostgres)
    conn <- dbConnect(Postgres(), dbname = dbname, host = host, port = port, 
                      user = username, password = password)
    st_write(obj = cycle_hire, dsn = conn, Id(schema="roads_spatial", table = "myCycle"))

使用 Postgres 12,我在 public 中得到 table "roads_spatial"."mycycle" 这不是预期的结果?

所以一个简单的迂回方式是写入public然后使用

dbExecute(
        conn,
        "ALTER TABLE myCycle SET SCHEMA roads_spatial")

 packageVersion("RPostgres") #[1] '1.2.0'
 packageVersion("DBI")       #[1] '1.1.0'

同样使用 Postgres 12,我最初 运行 遇到了与 @Cedric 相同的问题(public 中的新 table 命名为“roads_spatial”。 mycycle”。我终于能够在“roads_spatial”架构(或我的数据库中的等效项)中成功创建一个名为“mycycle”的新 table,内容如下:

st_write(obj = cycle_hire, dsn = conn, layer = c("roads_spatial", "mycycle"), delete_layer = TRUE)