2017-06-21 53 views
0

當我從PostgreSQL中抽取空的表時,我無法獲取列名。用dplyr提取postgresql空表

my_db <- dplyr::src_postgres(dbname="x",host="localhost",port=5432,user="x",password="x") 
my_tbl <- tbl(my_db,"test_table") 

在這裏,我得到一個tibble 0 X 0

my_tbl 
# A tibble: 0 x 0 

而我能得到colnames當TEST_TABLE 不爲空

colnames(my_tbl) 
[1] "var1" 

有沒有辦法讓colnames連當test_table有0行時?

回答

1

我會更改爲DBI::dbConnect(RPostgres::Postgres(), ...),如news to dplyr 0.7中所述。

library(dplyr) 
library(DBI) 
library(dbplyr) 

con <- DBI::dbConnect(RPostgres::Postgres(), user = "XXX", password = "XXX", 
         port = "XXX", dbname = "XXX", host = "XXX") 

con2 <- dplyr::src_postgres(user = "XXX", password = "XXX", 
          port = "XXX", dbname = "XXX", host = "XXX") 


empty_tibble <- tribble(~x, ~y) 

dbWriteTable(con, "test", empty_tibble, overwrite = T) 

# works 
tbl(con, "test") 
# Source: table<test> [?? x 2] 
# Database: PqConnection 
# ... with 2 variables: x <lgl>, y <lgl> 


# doesn't work 
tbl(con2, "test") 
# Source: table<test> [?? x 2] 
# Database: postgres 9.5.7 [XXX]