Running a cohortBuilder step on a db source
goes through the following stages:
.pre_filtering - prepare the data object the step
starts from,cb_filter_data - apply each of the step filters (a
dplyr::filter() on the lazy table),.run_binding - apply binding keys (an
inner_join() on the key values),.post_binding - hand the result over to the next
step.Only stages 1 and 4 are configurable. They decide whether the result
of a step stays a lazy dbplyr query or is written to a
temporary table in the database. That single decision is the step
strategy, and it is read from an option on every step run:
Three values are available - "lazy" (the default),
"materialize" and "materialize_selective". See
?"step-strategy" for the reference documentation.
| writes temporary tables | tables written per step | drop statement | |
|---|---|---|---|
lazy |
no | - | - |
materialize |
yes | all source tables | DROP TABLE pg_temp.<name> |
materialize_selective |
yes | only tables touched by a filter or an active binding | DROP TABLE IF EXISTS <name> |
An unset option falls back to "lazy"; an unrecognised
one falls back to "lazy" with a warning.
The examples below use the librarian data shipped with
cohortBuilder, copied into an in-memory SQLite
database.
library(magrittr)
library(cohortBuilder)
library(cohortBuilder.db)
remote_names <- function(data_object) {
vapply(
data_object,
function(x) {
name <- dbplyr::remote_name(x)
if (is.null(name)) "<lazy>" else as.character(name)
},
character(1)
)
}
librarian <- cohortBuilder::librarian
conn <- DBI::dbConnect(RSQLite::SQLite(), dbname = ":memory:")
DBI::dbExecute(conn, paste0("ATTACH '", tempfile(), "' AS cb"))
#> [1] 0
for (table in c("books", "borrowers", "issues")) {
dplyr::copy_to(
conn, librarian[[table]], dbplyr::in_schema("cb", table),
temporary = FALSE, overwrite = TRUE
)
}
db_source <- set_source(
dbtables(tables = c("books", "borrowers", "issues"), schema = "cb", connection = conn),
binding_keys = bind_keys(
bind_key(update = data_key("issues", "isbn"), data_key("books", "isbn"))
)
)
new_cohort <- function() {
cohort(
db_source,
step(
filter("discrete", id = "author", variable = "author", dataset = "books",
value = "Dan Brown")
),
step(
filter("discrete", id = "program", variable = "program", dataset = "borrowers",
value = "premium")
)
)
}"lazy"With "lazy" nothing is ever copied. Each step returns
the lazy query it received, so get_data() or
get_stats() push a single (nested) query to the
database.
options(cohortBuilder.db.step_strategy = "lazy")
coh <- new_cohort()
run(coh)
remote_names(coh$get_data(2, state = "post", collect = FALSE))
#> books borrowers issues
#> "<lazy>" "<lazy>" "<lazy>"
coh$get_data(2, state = "post", collect = FALSE)$issues %>%
dplyr::show_query()
#> <SQL>
#> SELECT `issues`.*
#> FROM `cb`.`issues`
#> INNER JOIN (
#> SELECT DISTINCT `isbn` AS `key_1`
#> FROM `cb`.`books`
#> WHERE (`author` IN ('Dan Brown') OR (`author` IS NULL))
#> ) AS `RHS`
#> ON (`issues`.`isbn` = `RHS`.`key_1`)No table has a remote name - every object is still a query over the
original cb.* tables. The issues query also
shows the nesting the binding key adds on top of the filter.
Pick this when:
shiny app where only counts are refreshed),The trade-off is that every additional step adds another level of subquery. With many steps plus bindings, the final statement grows and the database has to re-evaluate the whole chain on each collect.
"materialize""materialize" is the original behaviour of the package:
.post_binding calls dplyr::compute() for
every source table, so a step’s result is stored as
<table>_<step_id> and the next step reads from
that.
options(cohortBuilder.db.step_strategy = "materialize")
coh <- new_cohort()
run(coh)
dbplyr::remote_name(coh$get_data(1, state = "post", collect = FALSE)$books)
#> [1] "books_1"
dbplyr::remote_name(coh$get_data(2, state = "post", collect = FALSE)$books)
#> [1] "books_2"Each step now starts from a flat table, so the SQL stays shallow no matter how many steps are defined:
coh$get_data(2, state = "post", collect = FALSE)$books %>%
dplyr::show_query()
#> <SQL>
#> SELECT *
#> FROM `books_2`Pick this when:
get_data()
calls),The trade-off is that a step costs a full scan and a write of every source table, even tables no filter in that step touches. On a source with a dozen tables and a filter on one of them, eleven tables are copied for nothing.
"materialize_selective""materialize_selective" materializes only the tables
whose row set actually changed in the step. The "filtered"
attribute, set by cb_filter_data() and by
.run_binding() when the binding is activated, marks those
tables. Untouched tables are returned as they came in, which means they
point at the previous step’s object.
options(cohortBuilder.db.step_strategy = "materialize_selective")
coh <- new_cohort()
run(coh)
remote_names(coh$get_data(1, state = "post", collect = FALSE))
#> books borrowers issues
#> "cb_tmp_books_1" "borrowers" "cb_tmp_issues_1"
remote_names(coh$get_data(2, state = "post", collect = FALSE))
#> books borrowers issues
#> "cb_tmp_books_1" "cb_tmp_borrowers_2" "cb_tmp_issues_1"In step 1 the author filter touches books,
and the binding key propagates that to issues, so both are
written to cb_tmp_books_1 and cb_tmp_issues_1.
borrowers was untouched and is left alone. In step 2 only
borrowers is filtered, so only it is written, while
books and issues keep pointing at the step 1
temporary tables.
Note that bound tables must be materialized rather than reverted to the previous step - otherwise the binding join would be lost.
Pick this when:
"materialize" without
paying for full scans of untouched tables,pg_temp-qualified drop used by
"materialize" (see below).pg_temp schema
(e.g. Redshift)"materialize" cleans up in .pre_filtering
with DBI::dbRemoveTable(temporary = TRUE), which
RPostgres emits as
DROP TABLE pg_temp.<name>. Amazon Redshift has no
pg_temp schema, so that statement fails and the step errors
out on re-run.
Both other strategies are safe there:
"lazy" never drops anything,"materialize_selective" issues an unqualified
DROP TABLE IF EXISTS cb_tmp_<table>_<step_id>,
resolved through the search path. The cb_tmp_ prefix keeps
the statement from ever naming a real table.The option is read on every step run, not when the source or cohort is created, so it can be changed at any time. Re-run the flow afterwards to rebuild the data objects under the new strategy.
options(cohortBuilder.db.step_strategy = "lazy")
coh <- new_cohort()
run(coh)
options(cohortBuilder.db.step_strategy = "materialize")
run(coh)
dbplyr::remote_name(coh$get_data(2, state = "post", collect = FALSE)$books)
#> [1] "books_2"To scope the change to a single block of code, reset the option on exit:
.pre_filtering, which is why re-running a step works.
Dropping is unconditional, so leftovers from an earlier run in the same
connection are cleared as well.<table>_<step_id> versus
cb_tmp_<table>_<step_id>). Switching between
them without a re-run can leave the earlier scheme’s tables behind until
the connection is closed."materialize" names its temporary tables
<table>_<step_id>, which can clash with an
existing table of that name. If your schema has such names, prefer
"materialize_selective".