diff --git a/R/00-Id.R b/R/00-Id.R index b196513ce..6d75661ad 100644 --- a/R/00-Id.R +++ b/R/00-Id.R @@ -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 #' @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")) @@ -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 @@ -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 + ) +} diff --git a/tests/testthat/test-00-Id.R b/tests/testthat/test-00-Id.R index 1c408f360..3587899ee 100644 --- a/tests/testthat/test-00-Id.R +++ b/tests/testthat/test-00-Id.R @@ -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"') + ) +}) +