Skip to content

Commit

Permalink
Extract table name from id string
Browse files Browse the repository at this point in the history
  • Loading branch information
hadley committed Nov 8, 2023
1 parent 892b23e commit f7a65bc
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 6 deletions.
4 changes: 2 additions & 2 deletions R/db-sql.R
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,8 @@ sql_table_index.DBIConnection <- function(con,
...,
call = caller_env()) {
table <- as_table_name(table, con, error_call = call)
hash <- substr(hash(table), 1, 6)
name <- name %||% paste0(c("dbplyr", hash, columns), collapse = "_")
table <- db_table_name_extract(con, table)
name <- name %||% paste0(c(table, columns), collapse = "_")
glue_sql2(
con,
"CREATE ", if (unique) "UNIQUE ", "INDEX {.name name}",
Expand Down
17 changes: 17 additions & 0 deletions R/table-name.R
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,23 @@ is_table_name <- function(x) {
inherits(x, "dbplyr_table_name")
}

# TODO: make this generic
db_parse_table_name <- function(con, x) {
quote_char <- substr(as_table_name("", con = con), 1, 1)
scan(
text = x,
what = character(),
quote = quote_char,
quiet = TRUE,
na.strings = character(),
sep = "."
)
}
db_table_name_extract <- function(con, x) {
out <- db_parse_table_name(con, x)
out[[length(out)]]
}

#' @export
escape.dbplyr_table_name <- function(x, parens = FALSE, collapse = ", ", con = NULL) {
alias <- names2(x) # assume alias is already escaped
Expand Down
4 changes: 2 additions & 2 deletions R/verb-joins.R
Original file line number Diff line number Diff line change
Expand Up @@ -821,8 +821,8 @@ join_two_table_alias <- function(names, from) {
tables_have_same_name <- from[1] == "name" && from[2] == "name" && identical(names[1], names[2])
if (tables_have_same_name) {
out <- c(
paste0(names[1], "_LHS"),
paste0(names[2], "_RHS")
paste0(db_table_name_extract(con, names[1]), "_LHS"),
paste0(db_table_name_extract(con, names[2]), "_RHS")
)
return(out)
}
Expand Down
4 changes: 2 additions & 2 deletions tests/testthat/_snaps/backend-.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,14 @@
Code
sql_table_index(con, in_schema("schema", "tbl"), c("a", "b"))
Output
<SQL> CREATE INDEX `dbplyr_119f50_a_b` ON `schema`.`tbl` (`a`, `b`)
<SQL> CREATE INDEX `tbl_a_b` ON `tbl` (`a`, `b`)

---

Code
sql_table_index(con, in_schema("schema", "tbl"), "c", unique = TRUE)
Output
<SQL> CREATE UNIQUE INDEX `dbplyr_119f50_c` ON `schema`.`tbl` (`c`)
<SQL> CREATE UNIQUE INDEX `tbl_c` ON `tbl` (`c`)

---

Expand Down

0 comments on commit f7a65bc

Please sign in to comment.