Last active
June 13, 2022 14:25
-
-
Save kaneplusplus/c6df94601773f400d569f614350c0208 to your computer and use it in GitHub Desktop.
`tmp_tbl()` create a database-backed tbl that gets dropped when the handle goes out of scope
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(dplyr) | |
library(dbplyr) | |
library(uuid) | |
tmp_tbl <- function(x, con, tbl_name = UUIDgenerate()) { | |
uuid <- UUIDgenerate() | |
db_copy_to(con, tbl_name, as.data.frame(x), temporary = TRUE) | |
ret <- tbl(con, tbl_name) | |
ret$info <- new.env() | |
ret$info$con <- con | |
ret$info$name <- tbl_name | |
reg.finalizer( | |
ret$info, | |
function(e) dbRemoveTable(e$con, e$name) | |
) | |
ret | |
} | |
# Test it with duckdb | |
library(DBI) | |
library(duckdb) | |
con <- dbConnect(duckdb()) | |
dbcars <- tmp_tbl(mtcars, con) | |
dbListTables(con) | |
rm(dbcars) | |
gc() | |
dbListTables(con) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment