|
| 1 | +# PostgreSQL-specific features and functions |
| 2 | + |
| 3 | +#' List remote tables |
| 4 | +#' |
| 5 | +#' Returns the unquoted names of remote tables and table-like objects accessible |
| 6 | +#' through this connection. |
| 7 | +#' This includes foreign and partitioned tables, (materialized) views, as well |
| 8 | +#' as temporary objects. |
| 9 | +#' |
| 10 | +#' @inheritParams postgres-tables |
| 11 | +#' |
| 12 | +#' @family PqConnection generics |
| 13 | +#' |
| 14 | +#' @examples |
| 15 | +#' # For running the examples on systems without PostgreSQL connection: |
| 16 | +#' run <- postgresHasDefault() |
| 17 | +#' |
| 18 | +#' library(DBI) |
| 19 | +#' if (run) con <- dbConnect(RPostgres::Postgres()) |
| 20 | +#' if (run) dbListTables(con) |
| 21 | +#' |
| 22 | +#' if (run) dbWriteTable(con, "mtcars", mtcars, temporary = TRUE) |
| 23 | +#' if (run) dbListTables(con) |
| 24 | +#' |
| 25 | +#' if (run) dbDisconnect(con) |
| 26 | +#' |
| 27 | +#' @export |
| 28 | +setGeneric("pqListTables", |
| 29 | + def = function(conn, ...) standardGeneric("pqListTables"), |
| 30 | + valueClass = "character" |
| 31 | +) |
| 32 | + |
| 33 | +#' @rdname pqListTables |
| 34 | +#' @export |
| 35 | +setMethod("pqListTables", "PqConnection", function(conn) { |
| 36 | + major_server_version <- dbGetInfo(conn)$db.version %/% 10000 |
| 37 | + |
| 38 | + query <- paste0( |
| 39 | + # pg_class docs: https://www.postgresql.org/docs/current/catalog-pg-class.html |
| 40 | + "SELECT cl.relname AS name FROM pg_class AS cl ", |
| 41 | + "JOIN pg_namespace AS n ON cl.relnamespace = n.oid ", |
| 42 | + "WHERE (n.nspname = ANY (current_schemas(true))) ", |
| 43 | + "AND (n.nspname <> 'pg_catalog') " |
| 44 | + ) |
| 45 | + |
| 46 | + if (major_server_version >= 10) { |
| 47 | + # relkind = 'p' and relispartition only supported from v10 onwards |
| 48 | + query <- paste0( |
| 49 | + query, |
| 50 | + # r = ordinary table, v = view, m = materialized view, f = foreign table, p = partitioned table |
| 51 | + "AND (cl.relkind IN ('r', 'v', 'm', 'f', 'p')) ", |
| 52 | + "AND NOT cl.relispartition " |
| 53 | + ) |
| 54 | + } else { |
| 55 | + query <- paste0( |
| 56 | + query, |
| 57 | + "AND (cl.relkind IN ('r', 'v', 'm', 'f')) " |
| 58 | + ) |
| 59 | + } |
| 60 | + |
| 61 | + query <- paste0( |
| 62 | + query, |
| 63 | + "ORDER BY name" |
| 64 | + ) |
| 65 | + |
| 66 | + dbGetQuery(conn, query)[[1]] |
| 67 | +}) |
| 68 | + |
0 commit comments