Skip to content

Commit

Permalink
Merge pull request #427 from eauleaf/main
Browse files Browse the repository at this point in the history
  • Loading branch information
krlmlr authored Dec 16, 2023
2 parents 4e87378 + 5b91bce commit bd1c796
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
23 changes: 18 additions & 5 deletions R/00-Id.R
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@ setClass("Id", slots = list(name = "character"))
#'
#' Objects of this class are also returned from [dbListObjects()].
#'
#' @param ... Components of the hierarchy, e.g. `schema`, `table`, or `cluster`,
#' `catalog`, `schema`, `table`, depending on the database backend. For more
#' @param ... Components of the hierarchy, e.g. `cluster`,
#' `catalog`, `schema`, or `table`, depending on the database backend. For more
#' on these concepts, see <https://stackoverflow.com/questions/7022755/>
#' @export
#' @examples
#' # Identifies a table in a specific schema:
#' Id("dbo", "Customer")
#' # You can name the components if you want, but it's not needed
#' Id(schema = "dbo", table = "Customer")
#' Id(table = "Customer", schema = "dbo")
#'
#' # Create a SQL expression for an identifier:
#' dbQuoteIdentifier(ANSI(), Id("nycflights13", "flights"))
Expand All @@ -39,12 +39,12 @@ setClass("Id", slots = list(name = "character"))
#' dbWriteTable(con, Id("myschema", "mytable"), data.frame(a = 1))
#' }
Id <- function(...) {
components <- c(...)
components <- orderIdParams(...)
if (!is.character(components)) {
stop("All elements of `...` must be strings.", call. = FALSE)
}

new("Id", name = c(...))
new("Id", name = components)
}

#' @export
Expand All @@ -56,3 +56,16 @@ toString.Id <- function(x, ...) {
dbQuoteIdentifier_DBIConnection_Id <- function(conn, x, ...) {
SQL(paste0(dbQuoteIdentifier(conn, x@name), collapse = "."))
}


orderIdParams <- function(..., database = NULL,
catalog = NULL, cluster = NULL,
schema = NULL, table = NULL){
c(database = database,
cluster = cluster,
catalog = catalog,
schema = schema,
...,
table = table
)
}
18 changes: 18 additions & 0 deletions tests/testthat/test-00-Id.R
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,21 @@ test_that("each element is quoted individually", {
SQL('"a"."b.c"')
)
})

test_that("Id organizes the standard named elements", {
expect_equal(
dbQuoteIdentifier(ANSI(), Id("unnamed",
table = "last", schema = "3rd",
cluster = '1st', catalog = "2nd")),
SQL('"1st"."2nd"."3rd"."unnamed"."last"')
)
})

test_that("Id organizes mingled named and unnamed elements; ignores NULL", {
expect_equal(
dbQuoteIdentifier(ANSI(), Id(
table = "4", some_ref = '2', "3", catalog = "1", cluster = NULL)),
SQL('"1"."2"."3"."4"')
)
})

0 comments on commit bd1c796

Please sign in to comment.