【问题标题】:List tables within a Postgres schema using R使用 R 列出 Postgres 模式中的表
【发布时间】:2021-03-20 09:49:23
【问题描述】:

我正在使用 R 和 RPostgreSQL 包连接到 PostgreSQL 数据库。 db 有许多模式,我想知道哪些表与特定模式相关联。

到目前为止我已经尝试过:

dbListTables(db, schema="sch2014")
dbGetQuery(db, "dt sch2014.*")
dbGetQuery(db, "\dt sch2014.*")
dbGetQuery(db, "\\dt sch2014.*")

这些都不起作用。

这个相关的问题也存在:Setting the schema name in postgres using R,这将通过在连接处定义架构来解决问题。但是,还没有答案!

【问题讨论】:

    标签: r postgresql


    【解决方案1】:

    阅读此答案https://stackoverflow.com/a/15644435/2773500 有所帮助。我可以使用以下内容来获取与特定架构关联的表:

    dbGetQuery(db,
               "SELECT table_name FROM information_schema.tables
                       WHERE table_schema='sch2014'")
    

    【讨论】:

      【解决方案2】:

      以下应该可以工作(使用DBI_v1.1.1

      DBI::dbListObjects(conn, DBI::Id(schema = 'schema_name'))
      

      虽然它包含您想要的所有信息,但很难访问和阅读。

      我会推荐一些能产生数据框的东西:

      # get a hard to read table given some Postgres connection `conn`
      x = DBI::dbListObjects(conn, DBI::Id(schema = 'schema_name'))
      
      # - extract column "table" comprising a list of Formal class 'Id' objects then
      # - extract the 'name' slot for each S4 object element
      # could also do `lapply(d$table, function(x) x@name)`
      v = lapply(x$table, function(x) slot(x, 'name'))
      
      # create a dataframe with header 'schema', 'table'
      d = as.data.frame(do.call(rbind, v))
      

      或者在一行中:

      d = as.data.frame(do.call(rbind, lapply(DBI::dbListObjects(conn, DBI::Id(schema = 'schema_name'))$table, function(x) slot(x, 'name'))))
      

      或者以更“整洁”的方式:

      conn %>%
          DBI::dbListObjects(DBI::Id(schema = 'schema_name')) %>%
          dplyr::pull(table) %>%
          purrr::map(~slot(.x, 'name')) %>%
          dplyr::bind_rows()
      

      输出类似于

      > d
                schema     table
      1    schema_name    mtcars
      

      【讨论】:

      • 很好的答案@Danton——这真的帮助了我——和小世界在这里见到你!为了通过另一行简化整洁的代码,我们还可以使用purrr::map_df(~slot(.x, 'name')) 并删除bind_rows()
      【解决方案3】:

      您可以使用 table_schema 选项而不仅仅是 schema 来查看特定架构中的表列表。因此,与上面的示例代码 sn-p 保持一致,下面的行应该可以工作:

      dbListTables(db, table_schema="sch2014")
      

      【讨论】:

      • 这似乎不再起作用,RPostgreSQL返回错误消息,RPostgres似乎忽略了table_schema参数。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      • 2016-08-05
      • 2017-12-17
      • 1970-01-01
      相关资源
      最近更新 更多