Skip to content

Commit

Permalink
Merge pull request #431 from r-dbi/b-402-temp-table-name-clash
Browse files Browse the repository at this point in the history
fix: `dbWriteTable()` correctly handles name clashes between temporary and permanent tables
  • Loading branch information
aviator-app[bot] authored Apr 1, 2024
2 parents 3957ee6 + beb732a commit d3a5569
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 10 deletions.
19 changes: 9 additions & 10 deletions R/dbWriteTable_PqConnection_character_data.frame.R
Original file line number Diff line number Diff line change
Expand Up @@ -44,20 +44,19 @@ dbWriteTable_PqConnection_character_data.frame <- function(conn, name, value, ..
})
}

found <- dbExistsTable(conn, name)
if (found && !overwrite && !append) {
stop("Table ", name, " exists in database, and both overwrite and",
" append are FALSE",
call. = FALSE
)
}
if (found && overwrite) {
dbRemoveTable(conn, name)
if (overwrite) {
suppressMessages(dbRemoveTable(conn, name, temporary = temporary, fail_if_missing = FALSE))
found <- FALSE
} else {
found <- dbExistsTable(conn, name)
if (found && !append) {
stopc("Table ", name, " exists in database, and both overwrite and append are FALSE")
}
}

value <- sqlRownamesToColumn(value, row.names)

if (!found || overwrite) {
if (!found) {
if (is.null(field.types)) {
combined_field_types <- lapply(value, dbDataType, dbObj = conn)
} else {
Expand Down
19 changes: 19 additions & 0 deletions tests/testthat/test-dbWriteTable.R
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,25 @@ if (postgresHasDefault()) {
})
})
})


describe("Name clashes", {
test_that("Can write to temporary table if permanent table exists (#402)", {
skip_on_cran()

dbWriteTable(con, "my_name_clash", data.frame(a = 1), overwrite = TRUE)
expect_equal(dbReadTable(con, "my_name_clash"), data.frame(a = 1))

dbWriteTable(con, "my_name_clash", data.frame(b = 2), overwrite = TRUE, temporary = TRUE)
expect_equal(dbReadTable(con, "my_name_clash"), data.frame(b = 2))

dbRemoveTable(con, "my_name_clash", temporary = TRUE)
expect_equal(dbReadTable(con, "my_name_clash"), data.frame(a = 1))

dbRemoveTable(con, "my_name_clash")
dbDisconnect(con)
})
})
})

}

0 comments on commit d3a5569

Please sign in to comment.