From fe0a772e16e757271f6865ecedc5a1d798274ac9 Mon Sep 17 00:00:00 2001 From: Dhruv Gupta Date: Fri, 30 Oct 2026 16:22:28 -0400 Subject: [PATCH] Move the drug era script into its own SQL file and add buildDrugEra() The drug era example script on the SQL Scripts page now lives in inst/sql/sql_server/OMOP_CDM_drug_era.sql, unchanged, and the page includes it from there (engine: knitr, so the page renders the sql chunk without Jupyter). buildDrugEra() renders that script for a CDM schema, translates it with SqlRender and runs it with DatabaseConnector, like executeDdl(). The tests run it on a SQLite CDM for every supported CDM version with the scenarios from #761 and check the era dates and exposure counts. docs/sqlScripts.html only has the changes from re-rendering the page. --- NAMESPACE | 1 + R/buildDrugEra.R | 45 +++ docs/sqlScripts.html | 411 +++++++++++----------- inst/sql/sql_server/OMOP_CDM_drug_era.sql | 204 +++++++++++ man/buildDrugEra.Rd | 43 +++ site/sqlScripts.qmd | 208 +---------- tests/testthat/test-buildDrugEra.R | 144 ++++++++ 7 files changed, 645 insertions(+), 411 deletions(-) create mode 100644 R/buildDrugEra.R create mode 100644 inst/sql/sql_server/OMOP_CDM_drug_era.sql create mode 100644 man/buildDrugEra.Rd create mode 100644 tests/testthat/test-buildDrugEra.R diff --git a/NAMESPACE b/NAMESPACE index 9d0fbc2a..cdba4cdf 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,5 +1,6 @@ # Generated by roxygen2: do not edit by hand +export(buildDrugEra) export(buildRelease) export(buildReleaseZip) export(createDdl) diff --git a/R/buildDrugEra.R b/R/buildDrugEra.R new file mode 100644 index 00000000..6c326813 --- /dev/null +++ b/R/buildDrugEra.R @@ -0,0 +1,45 @@ +#' Build the DRUG_ERA table from the DRUG_EXPOSURE table +#' +#' Runs the drug era script that is shown on the "SQL Scripts" page of the CDM website +#' (\code{inst/sql/sql_server/OMOP_CDM_drug_era.sql}) on a database. The script strings together the +#' periods of time that a person is exposed to an active drug ingredient, allowing for gaps of up to 30 +#' days, and inserts the resulting eras into the DRUG_ERA table. +#' +#' @details +#' The script reads DRUG_EXPOSURE, CONCEPT and CONCEPT_ANCESTOR (RxNorm ingredients) from the CDM schema and +#' inserts into DRUG_ERA without deleting existing rows, so DRUG_ERA is expected to be empty. It uses a +#' temp table, so on dialects that emulate temp tables (for example Oracle, BigQuery, Spark and Snowflake) +#' \code{tempEmulationSchema} has to be set. +#' +#' @param connectionDetails An object of class connectionDetails as created by the DatabaseConnector::createConnectionDetails function. +#' @param cdmDatabaseSchema The schema of the CDM instance that holds the DRUG_EXPOSURE, CONCEPT, CONCEPT_ANCESTOR and DRUG_ERA tables. For example, this would be "ohdsi.dbo" when testing on sql server. +#' @param tempEmulationSchema The schema used to emulate temp tables on dialects that do not support them, see SqlRender::translate. +#' @param ... Other arguments passed on to DatabaseConnector::executeSql. (This allows the user to set the path to errorReportFile.) +#' @return Called for its side effect of populating the DRUG_ERA table; returns NULL invisibly. +#' @export +#' +#' @examples +#' \dontrun{ +#' buildDrugEra(connectionDetails = connectionDetails, +#' cdmDatabaseSchema = "myCdm") +#'} +buildDrugEra <- function(connectionDetails, + cdmDatabaseSchema, + tempEmulationSchema = getOption("sqlRenderTempEmulationSchema"), + ...) { + + sqlFile <- system.file("sql", "sql_server", "OMOP_CDM_drug_era.sql", + package = "CommonDataModel", mustWork = TRUE) + + sql <- SqlRender::render(SqlRender::readSql(sqlFile), cdm_schema = cdmDatabaseSchema) + sql <- SqlRender::translate(sql, + targetDialect = connectionDetails$dbms, + tempEmulationSchema = tempEmulationSchema) + + con <- DatabaseConnector::connect(connectionDetails = connectionDetails) + on.exit(DatabaseConnector::disconnect(con)) + + DatabaseConnector::executeSql(con, sql = sql, reportOverallTime = FALSE, progressBar = FALSE, ...) + + invisible(NULL) +} diff --git a/docs/sqlScripts.html b/docs/sqlScripts.html index 7fb058d7..4da1a40e 100644 --- a/docs/sqlScripts.html +++ b/docs/sqlScripts.html @@ -847,211 +847,212 @@

Condition Eras

Drug Eras

If the DRUG_EXPOSURE table is populated this script will string together periods of time that a person is exposed to an active drug ingredient, allowing for 30 gaps in between. It will then insert the resulting era records into the DRUG_ERA table. NOTE This query only works with the version 5 series and below.

-

--- Code taken from:
--- https://github.com/OHDSI/ETL-CMS/blob/master/SQL/create_CDMv5_drug_era_non_stockpile.sql
-
-if object_id('tempdb..#tmp_de', 'U') is not null drop table #tmp_de;
-
-WITH
-ctePreDrugTarget(drug_exposure_id, person_id, ingredient_concept_id, drug_exposure_start_date, days_supply, drug_exposure_end_date) AS
-(-- Normalize DRUG_EXPOSURE_END_DATE to either the existing drug exposure end date, or add days supply, or add 1 day to the start date
-  SELECT
-    d.drug_exposure_id,
-    d.person_id,
-    c.concept_id AS ingredient_concept_id,
-    d.drug_exposure_start_date AS drug_exposure_start_date,
-    d.days_supply AS days_supply,
-    COALESCE(
-      ---NULLIF returns NULL if both values are the same, otherwise it returns the first parameter
-      NULLIF(drug_exposure_end_date, NULL),
-      ---If drug_exposure_end_date != NULL, return drug_exposure_end_date, otherwise go to next case
-      NULLIF(dateadd(day,days_supply,drug_exposure_start_date), drug_exposure_start_date),
-      ---If days_supply != NULL or 0, return drug_exposure_start_date + days_supply, otherwise go to next case
-      dateadd(day,1,drug_exposure_start_date)
-      ---Add 1 day to the drug_exposure_start_date since there is no end_date or INTERVAL for the days_supply
-    ) AS drug_exposure_end_date
-  FROM @cdm_schema.drug_exposure d
-  JOIN @cdm_schema.concept_ancestor ca ON ca.descendant_concept_id = d.drug_concept_id
-  JOIN @cdm_schema.concept c ON ca.ancestor_concept_id = c.concept_id
-  WHERE c.vocabulary_id = 'RxNorm' ---8 selects RxNorm from the vocabulary_id
-    AND c.concept_class_id = 'Ingredient'
-    AND d.drug_concept_id != 0 ---Our unmapped drug_concept_id's are set to 0, so we don't want different drugs wrapped up in the same era
-    AND coalesce(d.days_supply,0) >= 0 ---We have cases where days_supply is negative, and this can set the end_date before the start_date, which we don't want. So we're just looking over those rows. This is a data-quality issue.
-)
-
-, cteSubExposureEndDates (person_id, ingredient_concept_id, end_date) AS --- A preliminary sorting that groups all of the overlapping exposures into one exposure so that we don't double-count non-gap-days
-(
-  SELECT
-    person_id,
-    ingredient_concept_id,
-    event_date AS end_date
-  FROM
-  (
-    SELECT
-      person_id,
-      ingredient_concept_id,
-      event_date,
-      event_type,
-      MAX(start_ordinal) OVER (PARTITION BY person_id, ingredient_concept_id
-      ORDER BY event_date, event_type ROWS unbounded preceding) AS start_ordinal,
-      -- this pulls the current START down from the prior rows so that the NULLs
-      -- from the END DATES will contain a value we can compare with
-      ROW_NUMBER() OVER (PARTITION BY person_id, ingredient_concept_id
-        ORDER BY event_date, event_type) AS overall_ord
-      -- this re-numbers the inner UNION so all rows are numbered ordered by the event date
-    FROM (
-      -- select the start dates, assigning a row number to each
-      SELECT
-        person_id,
-        ingredient_concept_id,
-        drug_exposure_start_date AS event_date,
-        -1 AS event_type,
-        ROW_NUMBER() OVER (PARTITION BY person_id, ingredient_concept_id
-        ORDER BY drug_exposure_start_date) AS start_ordinal
-      FROM ctePreDrugTarget
-
-      UNION ALL
-
-      SELECT
-        person_id,
-        ingredient_concept_id,
-        drug_exposure_end_date,
-        1 AS event_type,
-        NULL
-      FROM ctePreDrugTarget
-    ) RAWDATA
-  ) e
-  WHERE (2 * e.start_ordinal) - e.overall_ord = 0
-)
-
-, cteDrugExposureEnds (person_id, drug_concept_id, drug_exposure_start_date, drug_sub_exposure_end_date) AS
-(
-SELECT
-  dt.person_id,
-  dt.ingredient_concept_id,
-  dt.drug_exposure_start_date,
-  MIN(e.end_date) AS drug_sub_exposure_end_date
-FROM ctePreDrugTarget dt
-JOIN cteSubExposureEndDates e ON dt.person_id = e.person_id AND dt.ingredient_concept_id = e.ingredient_concept_id AND e.end_date >= dt.drug_exposure_start_date
-GROUP BY
-  dt.drug_exposure_id
-  , dt.person_id
-  , dt.ingredient_concept_id
-  , dt.drug_exposure_start_date
-)
---------------------------------------------------------------------------------------------------------------
-, cteSubExposures(row_number, person_id, drug_concept_id, drug_sub_exposure_start_date, drug_sub_exposure_end_date, drug_exposure_count) AS
-(
-  SELECT
-    ROW_NUMBER() OVER (PARTITION BY person_id, drug_concept_id, drug_sub_exposure_end_date ORDER BY person_id),
-    person_id,
-    drug_concept_id,
-    MIN(drug_exposure_start_date) AS drug_sub_exposure_start_date,
-    drug_sub_exposure_end_date,
-    COUNT(*) AS drug_exposure_count
-  FROM cteDrugExposureEnds
-  GROUP BY person_id, drug_concept_id, drug_sub_exposure_end_date
-  --ORDER BY person_id, drug_concept_id
-)
---------------------------------------------------------------------------------------------------------------
-/*Everything above grouped exposures into sub_exposures if there was overlap between exposures.
- *So there was no persistence window. Now we can add the persistence window to calculate eras.
- */
---------------------------------------------------------------------------------------------------------------
-, cteFinalTarget(row_number, person_id, ingredient_concept_id, drug_sub_exposure_start_date, drug_sub_exposure_end_date, drug_exposure_count, days_exposed) AS
-(
-  SELECT
-    row_number,
-    person_id,
-    drug_concept_id,
-    drug_sub_exposure_start_date,
-    drug_sub_exposure_end_date,
-    drug_exposure_count,
-    datediff(day,drug_sub_exposure_start_date,drug_sub_exposure_end_date) AS days_exposed
-  FROM cteSubExposures
-)
---------------------------------------------------------------------------------------------------------------
-, cteEndDates (person_id, ingredient_concept_id, end_date) AS -- the magic
-(
-  SELECT
-    person_id,
-    ingredient_concept_id,
-    dateadd(day,-30,event_date) AS end_date -- unpad the end date
-  FROM
-  (
-    SELECT
-      person_id,
-      ingredient_concept_id,
-      event_date,
-      event_type,
-      MAX(start_ordinal) OVER (PARTITION BY person_id, ingredient_concept_id
-      ORDER BY event_date, event_type ROWS UNBOUNDED PRECEDING) AS start_ordinal,
-      -- this pulls the current START down from the prior rows so that the NULLs
-      -- from the END DATES will contain a value we can compare with
-      ROW_NUMBER() OVER (PARTITION BY person_id, ingredient_concept_id
-        ORDER BY event_date, event_type) AS overall_ord
-      -- this re-numbers the inner UNION so all rows are numbered ordered by the event date
-    FROM (
-      -- select the start dates, assigning a row number to each
-      SELECT
-        person_id,
-        ingredient_concept_id,
-        drug_sub_exposure_start_date AS event_date,
-        -1 AS event_type,
-        ROW_NUMBER() OVER (PARTITION BY person_id, ingredient_concept_id
-        ORDER BY drug_sub_exposure_start_date) AS start_ordinal
-      FROM cteFinalTarget
-
-      UNION ALL
-
-      -- pad the end dates by 30 to allow a grace period for overlapping ranges.
-      SELECT
-        person_id,
-        ingredient_concept_id,
-        dateadd(day,30,drug_sub_exposure_end_date),
-        1 AS event_type,
-        NULL
-      FROM cteFinalTarget
-    ) RAWDATA
-  ) e
-  WHERE (2 * e.start_ordinal) - e.overall_ord = 0
-
-)
-, cteDrugEraEnds (person_id, drug_concept_id, drug_sub_exposure_start_date, drug_era_end_date, drug_exposure_count, days_exposed) AS
-(
-  SELECT
-    ft.person_id,
-    ft.ingredient_concept_id,
-    ft.drug_sub_exposure_start_date,
-    MIN(e.end_date) AS era_end_date,
-    drug_exposure_count,
-    days_exposed
-  FROM cteFinalTarget ft
-  JOIN cteEndDates e ON ft.person_id = e.person_id AND ft.ingredient_concept_id = e.ingredient_concept_id AND e.end_date >= ft.drug_sub_exposure_start_date
-  GROUP BY
-    ft.person_id
-    , ft.ingredient_concept_id
-    , ft.drug_sub_exposure_start_date
-    , drug_exposure_count
-    , days_exposed
-)
-SELECT
-  row_number()over(order by person_id) drug_era_id,
-  person_id,
-  drug_concept_id,
-  MIN(drug_sub_exposure_start_date) AS drug_era_start_date,
-  drug_era_end_date,
-  SUM(drug_exposure_count) AS drug_exposure_count,
-  datediff(day,MIN(drug_sub_exposure_start_date),drug_era_end_date)-SUM(days_exposed) AS gap_days
-INTO #tmp_de
-FROM cteDrugEraEnds dee
-GROUP BY person_id, drug_concept_id, drug_era_end_date;
-
-INSERT INTO @cdm_schema.drug_era(drug_era_id,person_id, drug_concept_id, drug_era_start_date, drug_era_end_date, drug_exposure_count, gap_days)
-SELECT
-  *
-FROM #tmp_de;
+
+
-- Code taken from:
+-- https://github.com/OHDSI/ETL-CMS/blob/master/SQL/create_CDMv5_drug_era_non_stockpile.sql
+
+if object_id('tempdb..#tmp_de', 'U') is not null drop table #tmp_de;
+
+WITH
+ctePreDrugTarget(drug_exposure_id, person_id, ingredient_concept_id, drug_exposure_start_date, days_supply, drug_exposure_end_date) AS
+(-- Normalize DRUG_EXPOSURE_END_DATE to either the existing drug exposure end date, or add days supply, or add 1 day to the start date
+  SELECT
+    d.drug_exposure_id,
+    d.person_id,
+    c.concept_id AS ingredient_concept_id,
+    d.drug_exposure_start_date AS drug_exposure_start_date,
+    d.days_supply AS days_supply,
+    COALESCE(
+      ---NULLIF returns NULL if both values are the same, otherwise it returns the first parameter
+      NULLIF(drug_exposure_end_date, NULL),
+      ---If drug_exposure_end_date != NULL, return drug_exposure_end_date, otherwise go to next case
+      NULLIF(dateadd(day,days_supply,drug_exposure_start_date), drug_exposure_start_date),
+      ---If days_supply != NULL or 0, return drug_exposure_start_date + days_supply, otherwise go to next case
+      dateadd(day,1,drug_exposure_start_date)
+      ---Add 1 day to the drug_exposure_start_date since there is no end_date or INTERVAL for the days_supply
+    ) AS drug_exposure_end_date
+  FROM @cdm_schema.drug_exposure d
+  JOIN @cdm_schema.concept_ancestor ca ON ca.descendant_concept_id = d.drug_concept_id
+  JOIN @cdm_schema.concept c ON ca.ancestor_concept_id = c.concept_id
+  WHERE c.vocabulary_id = 'RxNorm' ---8 selects RxNorm from the vocabulary_id
+    AND c.concept_class_id = 'Ingredient'
+    AND d.drug_concept_id != 0 ---Our unmapped drug_concept_id's are set to 0, so we don't want different drugs wrapped up in the same era
+    AND coalesce(d.days_supply,0) >= 0 ---We have cases where days_supply is negative, and this can set the end_date before the start_date, which we don't want. So we're just looking over those rows. This is a data-quality issue.
+)
+
+, cteSubExposureEndDates (person_id, ingredient_concept_id, end_date) AS --- A preliminary sorting that groups all of the overlapping exposures into one exposure so that we don't double-count non-gap-days
+(
+  SELECT
+    person_id,
+    ingredient_concept_id,
+    event_date AS end_date
+  FROM
+  (
+    SELECT
+      person_id,
+      ingredient_concept_id,
+      event_date,
+      event_type,
+      MAX(start_ordinal) OVER (PARTITION BY person_id, ingredient_concept_id
+      ORDER BY event_date, event_type ROWS unbounded preceding) AS start_ordinal,
+      -- this pulls the current START down from the prior rows so that the NULLs
+      -- from the END DATES will contain a value we can compare with
+      ROW_NUMBER() OVER (PARTITION BY person_id, ingredient_concept_id
+        ORDER BY event_date, event_type) AS overall_ord
+      -- this re-numbers the inner UNION so all rows are numbered ordered by the event date
+    FROM (
+      -- select the start dates, assigning a row number to each
+      SELECT
+        person_id,
+        ingredient_concept_id,
+        drug_exposure_start_date AS event_date,
+        -1 AS event_type,
+        ROW_NUMBER() OVER (PARTITION BY person_id, ingredient_concept_id
+        ORDER BY drug_exposure_start_date) AS start_ordinal
+      FROM ctePreDrugTarget
+
+      UNION ALL
+
+      SELECT
+        person_id,
+        ingredient_concept_id,
+        drug_exposure_end_date,
+        1 AS event_type,
+        NULL
+      FROM ctePreDrugTarget
+    ) RAWDATA
+  ) e
+  WHERE (2 * e.start_ordinal) - e.overall_ord = 0
+)
+
+, cteDrugExposureEnds (person_id, drug_concept_id, drug_exposure_start_date, drug_sub_exposure_end_date) AS
+(
+SELECT
+  dt.person_id,
+  dt.ingredient_concept_id,
+  dt.drug_exposure_start_date,
+  MIN(e.end_date) AS drug_sub_exposure_end_date
+FROM ctePreDrugTarget dt
+JOIN cteSubExposureEndDates e ON dt.person_id = e.person_id AND dt.ingredient_concept_id = e.ingredient_concept_id AND e.end_date >= dt.drug_exposure_start_date
+GROUP BY
+  dt.drug_exposure_id
+  , dt.person_id
+  , dt.ingredient_concept_id
+  , dt.drug_exposure_start_date
+)
+--------------------------------------------------------------------------------------------------------------
+, cteSubExposures(row_number, person_id, drug_concept_id, drug_sub_exposure_start_date, drug_sub_exposure_end_date, drug_exposure_count) AS
+(
+  SELECT
+    ROW_NUMBER() OVER (PARTITION BY person_id, drug_concept_id, drug_sub_exposure_end_date ORDER BY person_id),
+    person_id,
+    drug_concept_id,
+    MIN(drug_exposure_start_date) AS drug_sub_exposure_start_date,
+    drug_sub_exposure_end_date,
+    COUNT(*) AS drug_exposure_count
+  FROM cteDrugExposureEnds
+  GROUP BY person_id, drug_concept_id, drug_sub_exposure_end_date
+  --ORDER BY person_id, drug_concept_id
+)
+--------------------------------------------------------------------------------------------------------------
+/*Everything above grouped exposures into sub_exposures if there was overlap between exposures.
+ *So there was no persistence window. Now we can add the persistence window to calculate eras.
+ */
+--------------------------------------------------------------------------------------------------------------
+, cteFinalTarget(row_number, person_id, ingredient_concept_id, drug_sub_exposure_start_date, drug_sub_exposure_end_date, drug_exposure_count, days_exposed) AS
+(
+  SELECT
+    row_number,
+    person_id,
+    drug_concept_id,
+    drug_sub_exposure_start_date,
+    drug_sub_exposure_end_date,
+    drug_exposure_count,
+    datediff(day,drug_sub_exposure_start_date,drug_sub_exposure_end_date) AS days_exposed
+  FROM cteSubExposures
+)
+--------------------------------------------------------------------------------------------------------------
+, cteEndDates (person_id, ingredient_concept_id, end_date) AS -- the magic
+(
+  SELECT
+    person_id,
+    ingredient_concept_id,
+    dateadd(day,-30,event_date) AS end_date -- unpad the end date
+  FROM
+  (
+    SELECT
+      person_id,
+      ingredient_concept_id,
+      event_date,
+      event_type,
+      MAX(start_ordinal) OVER (PARTITION BY person_id, ingredient_concept_id
+      ORDER BY event_date, event_type ROWS UNBOUNDED PRECEDING) AS start_ordinal,
+      -- this pulls the current START down from the prior rows so that the NULLs
+      -- from the END DATES will contain a value we can compare with
+      ROW_NUMBER() OVER (PARTITION BY person_id, ingredient_concept_id
+        ORDER BY event_date, event_type) AS overall_ord
+      -- this re-numbers the inner UNION so all rows are numbered ordered by the event date
+    FROM (
+      -- select the start dates, assigning a row number to each
+      SELECT
+        person_id,
+        ingredient_concept_id,
+        drug_sub_exposure_start_date AS event_date,
+        -1 AS event_type,
+        ROW_NUMBER() OVER (PARTITION BY person_id, ingredient_concept_id
+        ORDER BY drug_sub_exposure_start_date) AS start_ordinal
+      FROM cteFinalTarget
+
+      UNION ALL
+
+      -- pad the end dates by 30 to allow a grace period for overlapping ranges.
+      SELECT
+        person_id,
+        ingredient_concept_id,
+        dateadd(day,30,drug_sub_exposure_end_date),
+        1 AS event_type,
+        NULL
+      FROM cteFinalTarget
+    ) RAWDATA
+  ) e
+  WHERE (2 * e.start_ordinal) - e.overall_ord = 0
+
+)
+, cteDrugEraEnds (person_id, drug_concept_id, drug_sub_exposure_start_date, drug_era_end_date, drug_exposure_count, days_exposed) AS
+(
+  SELECT
+    ft.person_id,
+    ft.ingredient_concept_id,
+    ft.drug_sub_exposure_start_date,
+    MIN(e.end_date) AS era_end_date,
+    drug_exposure_count,
+    days_exposed
+  FROM cteFinalTarget ft
+  JOIN cteEndDates e ON ft.person_id = e.person_id AND ft.ingredient_concept_id = e.ingredient_concept_id AND e.end_date >= ft.drug_sub_exposure_start_date
+  GROUP BY
+    ft.person_id
+    , ft.ingredient_concept_id
+    , ft.drug_sub_exposure_start_date
+    , drug_exposure_count
+    , days_exposed
+)
+SELECT
+  row_number()over(order by person_id) drug_era_id,
+  person_id,
+  drug_concept_id,
+  MIN(drug_sub_exposure_start_date) AS drug_era_start_date,
+  drug_era_end_date,
+  SUM(drug_exposure_count) AS drug_exposure_count,
+  datediff(day,MIN(drug_sub_exposure_start_date),drug_era_end_date)-SUM(days_exposed) AS gap_days
+INTO #tmp_de
+FROM cteDrugEraEnds dee
+GROUP BY person_id, drug_concept_id, drug_era_end_date;
+
+INSERT INTO @cdm_schema.drug_era(drug_era_id,person_id, drug_concept_id, drug_era_start_date, drug_era_end_date, drug_exposure_count, gap_days)
+SELECT
+  *
+FROM #tmp_de;
+
diff --git a/inst/sql/sql_server/OMOP_CDM_drug_era.sql b/inst/sql/sql_server/OMOP_CDM_drug_era.sql new file mode 100644 index 00000000..30ccccda --- /dev/null +++ b/inst/sql/sql_server/OMOP_CDM_drug_era.sql @@ -0,0 +1,204 @@ +-- Code taken from: +-- https://github.com/OHDSI/ETL-CMS/blob/master/SQL/create_CDMv5_drug_era_non_stockpile.sql + +if object_id('tempdb..#tmp_de', 'U') is not null drop table #tmp_de; + +WITH +ctePreDrugTarget(drug_exposure_id, person_id, ingredient_concept_id, drug_exposure_start_date, days_supply, drug_exposure_end_date) AS +(-- Normalize DRUG_EXPOSURE_END_DATE to either the existing drug exposure end date, or add days supply, or add 1 day to the start date + SELECT + d.drug_exposure_id, + d.person_id, + c.concept_id AS ingredient_concept_id, + d.drug_exposure_start_date AS drug_exposure_start_date, + d.days_supply AS days_supply, + COALESCE( + ---NULLIF returns NULL if both values are the same, otherwise it returns the first parameter + NULLIF(drug_exposure_end_date, NULL), + ---If drug_exposure_end_date != NULL, return drug_exposure_end_date, otherwise go to next case + NULLIF(dateadd(day,days_supply,drug_exposure_start_date), drug_exposure_start_date), + ---If days_supply != NULL or 0, return drug_exposure_start_date + days_supply, otherwise go to next case + dateadd(day,1,drug_exposure_start_date) + ---Add 1 day to the drug_exposure_start_date since there is no end_date or INTERVAL for the days_supply + ) AS drug_exposure_end_date + FROM @cdm_schema.drug_exposure d + JOIN @cdm_schema.concept_ancestor ca ON ca.descendant_concept_id = d.drug_concept_id + JOIN @cdm_schema.concept c ON ca.ancestor_concept_id = c.concept_id + WHERE c.vocabulary_id = 'RxNorm' ---8 selects RxNorm from the vocabulary_id + AND c.concept_class_id = 'Ingredient' + AND d.drug_concept_id != 0 ---Our unmapped drug_concept_id's are set to 0, so we don't want different drugs wrapped up in the same era + AND coalesce(d.days_supply,0) >= 0 ---We have cases where days_supply is negative, and this can set the end_date before the start_date, which we don't want. So we're just looking over those rows. This is a data-quality issue. +) + +, cteSubExposureEndDates (person_id, ingredient_concept_id, end_date) AS --- A preliminary sorting that groups all of the overlapping exposures into one exposure so that we don't double-count non-gap-days +( + SELECT + person_id, + ingredient_concept_id, + event_date AS end_date + FROM + ( + SELECT + person_id, + ingredient_concept_id, + event_date, + event_type, + MAX(start_ordinal) OVER (PARTITION BY person_id, ingredient_concept_id + ORDER BY event_date, event_type ROWS unbounded preceding) AS start_ordinal, + -- this pulls the current START down from the prior rows so that the NULLs + -- from the END DATES will contain a value we can compare with + ROW_NUMBER() OVER (PARTITION BY person_id, ingredient_concept_id + ORDER BY event_date, event_type) AS overall_ord + -- this re-numbers the inner UNION so all rows are numbered ordered by the event date + FROM ( + -- select the start dates, assigning a row number to each + SELECT + person_id, + ingredient_concept_id, + drug_exposure_start_date AS event_date, + -1 AS event_type, + ROW_NUMBER() OVER (PARTITION BY person_id, ingredient_concept_id + ORDER BY drug_exposure_start_date) AS start_ordinal + FROM ctePreDrugTarget + + UNION ALL + + SELECT + person_id, + ingredient_concept_id, + drug_exposure_end_date, + 1 AS event_type, + NULL + FROM ctePreDrugTarget + ) RAWDATA + ) e + WHERE (2 * e.start_ordinal) - e.overall_ord = 0 +) + +, cteDrugExposureEnds (person_id, drug_concept_id, drug_exposure_start_date, drug_sub_exposure_end_date) AS +( +SELECT + dt.person_id, + dt.ingredient_concept_id, + dt.drug_exposure_start_date, + MIN(e.end_date) AS drug_sub_exposure_end_date +FROM ctePreDrugTarget dt +JOIN cteSubExposureEndDates e ON dt.person_id = e.person_id AND dt.ingredient_concept_id = e.ingredient_concept_id AND e.end_date >= dt.drug_exposure_start_date +GROUP BY + dt.drug_exposure_id + , dt.person_id + , dt.ingredient_concept_id + , dt.drug_exposure_start_date +) +-------------------------------------------------------------------------------------------------------------- +, cteSubExposures(row_number, person_id, drug_concept_id, drug_sub_exposure_start_date, drug_sub_exposure_end_date, drug_exposure_count) AS +( + SELECT + ROW_NUMBER() OVER (PARTITION BY person_id, drug_concept_id, drug_sub_exposure_end_date ORDER BY person_id), + person_id, + drug_concept_id, + MIN(drug_exposure_start_date) AS drug_sub_exposure_start_date, + drug_sub_exposure_end_date, + COUNT(*) AS drug_exposure_count + FROM cteDrugExposureEnds + GROUP BY person_id, drug_concept_id, drug_sub_exposure_end_date + --ORDER BY person_id, drug_concept_id +) +-------------------------------------------------------------------------------------------------------------- +/*Everything above grouped exposures into sub_exposures if there was overlap between exposures. + *So there was no persistence window. Now we can add the persistence window to calculate eras. + */ +-------------------------------------------------------------------------------------------------------------- +, cteFinalTarget(row_number, person_id, ingredient_concept_id, drug_sub_exposure_start_date, drug_sub_exposure_end_date, drug_exposure_count, days_exposed) AS +( + SELECT + row_number, + person_id, + drug_concept_id, + drug_sub_exposure_start_date, + drug_sub_exposure_end_date, + drug_exposure_count, + datediff(day,drug_sub_exposure_start_date,drug_sub_exposure_end_date) AS days_exposed + FROM cteSubExposures +) +-------------------------------------------------------------------------------------------------------------- +, cteEndDates (person_id, ingredient_concept_id, end_date) AS -- the magic +( + SELECT + person_id, + ingredient_concept_id, + dateadd(day,-30,event_date) AS end_date -- unpad the end date + FROM + ( + SELECT + person_id, + ingredient_concept_id, + event_date, + event_type, + MAX(start_ordinal) OVER (PARTITION BY person_id, ingredient_concept_id + ORDER BY event_date, event_type ROWS UNBOUNDED PRECEDING) AS start_ordinal, + -- this pulls the current START down from the prior rows so that the NULLs + -- from the END DATES will contain a value we can compare with + ROW_NUMBER() OVER (PARTITION BY person_id, ingredient_concept_id + ORDER BY event_date, event_type) AS overall_ord + -- this re-numbers the inner UNION so all rows are numbered ordered by the event date + FROM ( + -- select the start dates, assigning a row number to each + SELECT + person_id, + ingredient_concept_id, + drug_sub_exposure_start_date AS event_date, + -1 AS event_type, + ROW_NUMBER() OVER (PARTITION BY person_id, ingredient_concept_id + ORDER BY drug_sub_exposure_start_date) AS start_ordinal + FROM cteFinalTarget + + UNION ALL + + -- pad the end dates by 30 to allow a grace period for overlapping ranges. + SELECT + person_id, + ingredient_concept_id, + dateadd(day,30,drug_sub_exposure_end_date), + 1 AS event_type, + NULL + FROM cteFinalTarget + ) RAWDATA + ) e + WHERE (2 * e.start_ordinal) - e.overall_ord = 0 + +) +, cteDrugEraEnds (person_id, drug_concept_id, drug_sub_exposure_start_date, drug_era_end_date, drug_exposure_count, days_exposed) AS +( + SELECT + ft.person_id, + ft.ingredient_concept_id, + ft.drug_sub_exposure_start_date, + MIN(e.end_date) AS era_end_date, + drug_exposure_count, + days_exposed + FROM cteFinalTarget ft + JOIN cteEndDates e ON ft.person_id = e.person_id AND ft.ingredient_concept_id = e.ingredient_concept_id AND e.end_date >= ft.drug_sub_exposure_start_date + GROUP BY + ft.person_id + , ft.ingredient_concept_id + , ft.drug_sub_exposure_start_date + , drug_exposure_count + , days_exposed +) +SELECT + row_number()over(order by person_id) drug_era_id, + person_id, + drug_concept_id, + MIN(drug_sub_exposure_start_date) AS drug_era_start_date, + drug_era_end_date, + SUM(drug_exposure_count) AS drug_exposure_count, + datediff(day,MIN(drug_sub_exposure_start_date),drug_era_end_date)-SUM(days_exposed) AS gap_days +INTO #tmp_de +FROM cteDrugEraEnds dee +GROUP BY person_id, drug_concept_id, drug_era_end_date; + +INSERT INTO @cdm_schema.drug_era(drug_era_id,person_id, drug_concept_id, drug_era_start_date, drug_era_end_date, drug_exposure_count, gap_days) +SELECT + * +FROM #tmp_de; diff --git a/man/buildDrugEra.Rd b/man/buildDrugEra.Rd new file mode 100644 index 00000000..9ec44045 --- /dev/null +++ b/man/buildDrugEra.Rd @@ -0,0 +1,43 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/buildDrugEra.R +\name{buildDrugEra} +\alias{buildDrugEra} +\title{Build the DRUG_ERA table from the DRUG_EXPOSURE table} +\usage{ +buildDrugEra( + connectionDetails, + cdmDatabaseSchema, + tempEmulationSchema = getOption("sqlRenderTempEmulationSchema"), + ... +) +} +\arguments{ +\item{connectionDetails}{An object of class connectionDetails as created by the DatabaseConnector::createConnectionDetails function.} + +\item{cdmDatabaseSchema}{The schema of the CDM instance that holds the DRUG_EXPOSURE, CONCEPT, CONCEPT_ANCESTOR and DRUG_ERA tables. For example, this would be "ohdsi.dbo" when testing on sql server.} + +\item{tempEmulationSchema}{The schema used to emulate temp tables on dialects that do not support them, see SqlRender::translate.} + +\item{...}{Other arguments passed on to DatabaseConnector::executeSql. (This allows the user to set the path to errorReportFile.)} +} +\value{ +Called for its side effect of populating the DRUG_ERA table; returns NULL invisibly. +} +\description{ +Runs the drug era script that is shown on the "SQL Scripts" page of the CDM website +(\code{inst/sql/sql_server/OMOP_CDM_drug_era.sql}) on a database. The script strings together the +periods of time that a person is exposed to an active drug ingredient, allowing for gaps of up to 30 +days, and inserts the resulting eras into the DRUG_ERA table. +} +\details{ +The script reads DRUG_EXPOSURE, CONCEPT and CONCEPT_ANCESTOR (RxNorm ingredients) from the CDM schema and +inserts into DRUG_ERA without deleting existing rows, so DRUG_ERA is expected to be empty. It uses a +temp table, so on dialects that emulate temp tables (for example Oracle, BigQuery, Spark and Snowflake) +\code{tempEmulationSchema} has to be set. +} +\examples{ +\dontrun{ +buildDrugEra(connectionDetails = connectionDetails, + cdmDatabaseSchema = "myCdm") +} +} diff --git a/site/sqlScripts.qmd b/site/sqlScripts.qmd index 085dee24..e7a251c1 100644 --- a/site/sqlScripts.qmd +++ b/site/sqlScripts.qmd @@ -1,5 +1,6 @@ --- title: 'SQL Scripts' +engine: knitr format: html: toc: true @@ -303,212 +304,7 @@ GROUP BY person_id If the DRUG_EXPOSURE table is populated this script will string together periods of time that a person is exposed to an active drug ingredient, allowing for 30 gaps in between. It will then insert the resulting era records into the DRUG_ERA table. **NOTE** This query only works with the **version 5** series and below. -```sql - --- Code taken from: --- https://github.com/OHDSI/ETL-CMS/blob/master/SQL/create_CDMv5_drug_era_non_stockpile.sql - -if object_id('tempdb..#tmp_de', 'U') is not null drop table #tmp_de; - -WITH -ctePreDrugTarget(drug_exposure_id, person_id, ingredient_concept_id, drug_exposure_start_date, days_supply, drug_exposure_end_date) AS -(-- Normalize DRUG_EXPOSURE_END_DATE to either the existing drug exposure end date, or add days supply, or add 1 day to the start date - SELECT - d.drug_exposure_id, - d.person_id, - c.concept_id AS ingredient_concept_id, - d.drug_exposure_start_date AS drug_exposure_start_date, - d.days_supply AS days_supply, - COALESCE( - ---NULLIF returns NULL if both values are the same, otherwise it returns the first parameter - NULLIF(drug_exposure_end_date, NULL), - ---If drug_exposure_end_date != NULL, return drug_exposure_end_date, otherwise go to next case - NULLIF(dateadd(day,days_supply,drug_exposure_start_date), drug_exposure_start_date), - ---If days_supply != NULL or 0, return drug_exposure_start_date + days_supply, otherwise go to next case - dateadd(day,1,drug_exposure_start_date) - ---Add 1 day to the drug_exposure_start_date since there is no end_date or INTERVAL for the days_supply - ) AS drug_exposure_end_date - FROM @cdm_schema.drug_exposure d - JOIN @cdm_schema.concept_ancestor ca ON ca.descendant_concept_id = d.drug_concept_id - JOIN @cdm_schema.concept c ON ca.ancestor_concept_id = c.concept_id - WHERE c.vocabulary_id = 'RxNorm' ---8 selects RxNorm from the vocabulary_id - AND c.concept_class_id = 'Ingredient' - AND d.drug_concept_id != 0 ---Our unmapped drug_concept_id's are set to 0, so we don't want different drugs wrapped up in the same era - AND coalesce(d.days_supply,0) >= 0 ---We have cases where days_supply is negative, and this can set the end_date before the start_date, which we don't want. So we're just looking over those rows. This is a data-quality issue. -) - -, cteSubExposureEndDates (person_id, ingredient_concept_id, end_date) AS --- A preliminary sorting that groups all of the overlapping exposures into one exposure so that we don't double-count non-gap-days -( - SELECT - person_id, - ingredient_concept_id, - event_date AS end_date - FROM - ( - SELECT - person_id, - ingredient_concept_id, - event_date, - event_type, - MAX(start_ordinal) OVER (PARTITION BY person_id, ingredient_concept_id - ORDER BY event_date, event_type ROWS unbounded preceding) AS start_ordinal, - -- this pulls the current START down from the prior rows so that the NULLs - -- from the END DATES will contain a value we can compare with - ROW_NUMBER() OVER (PARTITION BY person_id, ingredient_concept_id - ORDER BY event_date, event_type) AS overall_ord - -- this re-numbers the inner UNION so all rows are numbered ordered by the event date - FROM ( - -- select the start dates, assigning a row number to each - SELECT - person_id, - ingredient_concept_id, - drug_exposure_start_date AS event_date, - -1 AS event_type, - ROW_NUMBER() OVER (PARTITION BY person_id, ingredient_concept_id - ORDER BY drug_exposure_start_date) AS start_ordinal - FROM ctePreDrugTarget - - UNION ALL - - SELECT - person_id, - ingredient_concept_id, - drug_exposure_end_date, - 1 AS event_type, - NULL - FROM ctePreDrugTarget - ) RAWDATA - ) e - WHERE (2 * e.start_ordinal) - e.overall_ord = 0 -) - -, cteDrugExposureEnds (person_id, drug_concept_id, drug_exposure_start_date, drug_sub_exposure_end_date) AS -( -SELECT - dt.person_id, - dt.ingredient_concept_id, - dt.drug_exposure_start_date, - MIN(e.end_date) AS drug_sub_exposure_end_date -FROM ctePreDrugTarget dt -JOIN cteSubExposureEndDates e ON dt.person_id = e.person_id AND dt.ingredient_concept_id = e.ingredient_concept_id AND e.end_date >= dt.drug_exposure_start_date -GROUP BY - dt.drug_exposure_id - , dt.person_id - , dt.ingredient_concept_id - , dt.drug_exposure_start_date -) --------------------------------------------------------------------------------------------------------------- -, cteSubExposures(row_number, person_id, drug_concept_id, drug_sub_exposure_start_date, drug_sub_exposure_end_date, drug_exposure_count) AS -( - SELECT - ROW_NUMBER() OVER (PARTITION BY person_id, drug_concept_id, drug_sub_exposure_end_date ORDER BY person_id), - person_id, - drug_concept_id, - MIN(drug_exposure_start_date) AS drug_sub_exposure_start_date, - drug_sub_exposure_end_date, - COUNT(*) AS drug_exposure_count - FROM cteDrugExposureEnds - GROUP BY person_id, drug_concept_id, drug_sub_exposure_end_date - --ORDER BY person_id, drug_concept_id -) --------------------------------------------------------------------------------------------------------------- -/*Everything above grouped exposures into sub_exposures if there was overlap between exposures. - *So there was no persistence window. Now we can add the persistence window to calculate eras. - */ --------------------------------------------------------------------------------------------------------------- -, cteFinalTarget(row_number, person_id, ingredient_concept_id, drug_sub_exposure_start_date, drug_sub_exposure_end_date, drug_exposure_count, days_exposed) AS -( - SELECT - row_number, - person_id, - drug_concept_id, - drug_sub_exposure_start_date, - drug_sub_exposure_end_date, - drug_exposure_count, - datediff(day,drug_sub_exposure_start_date,drug_sub_exposure_end_date) AS days_exposed - FROM cteSubExposures -) --------------------------------------------------------------------------------------------------------------- -, cteEndDates (person_id, ingredient_concept_id, end_date) AS -- the magic -( - SELECT - person_id, - ingredient_concept_id, - dateadd(day,-30,event_date) AS end_date -- unpad the end date - FROM - ( - SELECT - person_id, - ingredient_concept_id, - event_date, - event_type, - MAX(start_ordinal) OVER (PARTITION BY person_id, ingredient_concept_id - ORDER BY event_date, event_type ROWS UNBOUNDED PRECEDING) AS start_ordinal, - -- this pulls the current START down from the prior rows so that the NULLs - -- from the END DATES will contain a value we can compare with - ROW_NUMBER() OVER (PARTITION BY person_id, ingredient_concept_id - ORDER BY event_date, event_type) AS overall_ord - -- this re-numbers the inner UNION so all rows are numbered ordered by the event date - FROM ( - -- select the start dates, assigning a row number to each - SELECT - person_id, - ingredient_concept_id, - drug_sub_exposure_start_date AS event_date, - -1 AS event_type, - ROW_NUMBER() OVER (PARTITION BY person_id, ingredient_concept_id - ORDER BY drug_sub_exposure_start_date) AS start_ordinal - FROM cteFinalTarget - - UNION ALL - - -- pad the end dates by 30 to allow a grace period for overlapping ranges. - SELECT - person_id, - ingredient_concept_id, - dateadd(day,30,drug_sub_exposure_end_date), - 1 AS event_type, - NULL - FROM cteFinalTarget - ) RAWDATA - ) e - WHERE (2 * e.start_ordinal) - e.overall_ord = 0 - -) -, cteDrugEraEnds (person_id, drug_concept_id, drug_sub_exposure_start_date, drug_era_end_date, drug_exposure_count, days_exposed) AS -( - SELECT - ft.person_id, - ft.ingredient_concept_id, - ft.drug_sub_exposure_start_date, - MIN(e.end_date) AS era_end_date, - drug_exposure_count, - days_exposed - FROM cteFinalTarget ft - JOIN cteEndDates e ON ft.person_id = e.person_id AND ft.ingredient_concept_id = e.ingredient_concept_id AND e.end_date >= ft.drug_sub_exposure_start_date - GROUP BY - ft.person_id - , ft.ingredient_concept_id - , ft.drug_sub_exposure_start_date - , drug_exposure_count - , days_exposed -) -SELECT - row_number()over(order by person_id) drug_era_id, - person_id, - drug_concept_id, - MIN(drug_sub_exposure_start_date) AS drug_era_start_date, - drug_era_end_date, - SUM(drug_exposure_count) AS drug_exposure_count, - datediff(day,MIN(drug_sub_exposure_start_date),drug_era_end_date)-SUM(days_exposed) AS gap_days -INTO #tmp_de -FROM cteDrugEraEnds dee -GROUP BY person_id, drug_concept_id, drug_era_end_date; - -INSERT INTO @cdm_schema.drug_era(drug_era_id,person_id, drug_concept_id, drug_era_start_date, drug_era_end_date, drug_exposure_count, gap_days) -SELECT - * -FROM #tmp_de; +```{sql, file="../inst/sql/sql_server/OMOP_CDM_drug_era.sql", eval=FALSE} ``` ## Example ETL Script diff --git a/tests/testthat/test-buildDrugEra.R b/tests/testthat/test-buildDrugEra.R new file mode 100644 index 00000000..532c4e17 --- /dev/null +++ b/tests/testthat/test-buildDrugEra.R @@ -0,0 +1,144 @@ +# Runs buildDrugEra() (inst/sql/sql_server/OMOP_CDM_drug_era.sql, shown on the +# "SQL Scripts" page of the website) against a SQLite CDM and checks the +# resulting eras. Scenarios taken from +# https://github.com/OHDSI/CommonDataModel/issues/761 + +skip_if_not_installed("RSQLite") + +# Day 1 of the scenarios below is 2020-01-01 +scenarioDay <- function(day) { + as.Date("2020-01-01") + (day - 1) +} + +# Date literal in the yyyymmdd form that SqlRender translates for every dialect +dateLiteral <- function(date) { + paste0("CAST('", format(date, "%Y%m%d"), "' AS DATE)") +} + +# Create an empty CDM in a new SQLite database and load one ingredient, one +# drug mapped to it and the drug exposures. `exposures` is a data frame with +# columns `person_id`, `start_day` and `end_day` (inclusive, see scenarioDay). +# Returns the connection details of the database. +createDrugEraTestCdm <- function(cdmVersion, exposures, envir = parent.frame()) { + dbFile <- withr::local_tempfile(fileext = ".sqlite", .local_envir = envir) + connectionDetails <- DatabaseConnector::createConnectionDetails(dbms = "sqlite", server = dbFile) + + con <- DatabaseConnector::connect(connectionDetails) + on.exit(DatabaseConnector::disconnect(con)) + executeOhdsiSql <- function(sql, ...) { + sql <- SqlRender::translate(SqlRender::render(sql, ...), targetDialect = "sqlite") + DatabaseConnector::executeSql(con, sql, progressBar = FALSE, reportOverallTime = FALSE) + } + + executeOhdsiSql(createDdl(cdmVersion), cdmDatabaseSchema = "main") + + executeOhdsiSql( + "INSERT INTO @cdm_schema.concept + (concept_id, concept_name, domain_id, vocabulary_id, concept_class_id, + standard_concept, concept_code, valid_start_date, valid_end_date) + VALUES + (1, 'test ingredient', 'Drug', 'RxNorm', 'Ingredient', 'S', 'ING', + CAST('19700101' AS DATE), CAST('20991231' AS DATE)), + (2, 'test clinical drug', 'Drug', 'RxNorm', 'Clinical Drug', 'S', 'DRUG', + CAST('19700101' AS DATE), CAST('20991231' AS DATE)); + INSERT INTO @cdm_schema.concept_ancestor + (ancestor_concept_id, descendant_concept_id, + min_levels_of_separation, max_levels_of_separation) + VALUES (1, 1, 0, 0), (1, 2, 1, 1);", + cdm_schema = "main" + ) + + for (i in seq_len(nrow(exposures))) { + executeOhdsiSql( + "INSERT INTO @cdm_schema.drug_exposure + (drug_exposure_id, person_id, drug_concept_id, + drug_exposure_start_date, drug_exposure_end_date, drug_type_concept_id) + VALUES (@id, @person_id, 2, @start_date, @end_date, 0);", + cdm_schema = "main", + id = i, + person_id = exposures$person_id[i], + start_date = dateLiteral(scenarioDay(exposures$start_day[i])), + end_date = dateLiteral(scenarioDay(exposures$end_day[i])) + ) + } + + return(connectionDetails) +} + +getDrugEras <- function(connectionDetails) { + con <- DatabaseConnector::connect(connectionDetails) + on.exit(DatabaseConnector::disconnect(con)) + eras <- DatabaseConnector::querySql( + con, + "SELECT person_id, drug_concept_id, drug_era_start_date, drug_era_end_date, + drug_exposure_count, gap_days + FROM main.drug_era + ORDER BY person_id, drug_era_start_date", + snakeCaseToCamelCase = TRUE + ) + return(eras) +} + +for (cdmVersion in listSupportedVersions()) { + test_that(paste("buildDrugEra collapses overlapping and nearby exposures, CDM", cdmVersion), { + # day: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 + # exposure 1: |-----------| + # exposure 2: |-----------| + # exposure 3: |-----| + # exposure 4: |-----------| + exposures <- data.frame( + person_id = 1, + start_day = c(1, 3, 11, 16), + end_day = c(5, 7, 13, 20) + ) + connectionDetails <- createDrugEraTestCdm(cdmVersion, exposures) + + buildDrugEra(connectionDetails, cdmDatabaseSchema = "main") + eras <- getDrugEras(connectionDetails) + + expect_equal(nrow(eras), 1) + expect_equal(eras$personId, 1) + expect_equal(eras$drugConceptId, 1) + expect_equal(eras$drugEraStartDate, scenarioDay(1)) + expect_equal(eras$drugEraEndDate, scenarioDay(20)) + expect_equal(eras$drugExposureCount, 4) + }) + + test_that(paste("buildDrugEra joins consecutive exposures, CDM", cdmVersion), { + # day: 1 2 3 4 5 6 7 8 9 10 + # exposure 1: |-----------| + # exposure 2: |-----------| + exposures <- data.frame( + person_id = 1, + start_day = c(1, 6), + end_day = c(5, 10) + ) + connectionDetails <- createDrugEraTestCdm(cdmVersion, exposures) + + buildDrugEra(connectionDetails, cdmDatabaseSchema = "main") + eras <- getDrugEras(connectionDetails) + + expect_equal(nrow(eras), 1) + expect_equal(eras$drugEraStartDate, scenarioDay(1)) + expect_equal(eras$drugEraEndDate, scenarioDay(10)) + expect_equal(eras$drugExposureCount, 2) + }) + + test_that(paste("buildDrugEra starts a new era after more than 30 days, CDM", cdmVersion), { + exposures <- data.frame( + person_id = c(1, 1, 2), + start_day = c(1, 40, 1), + end_day = c(5, 45, 1) + ) + connectionDetails <- createDrugEraTestCdm(cdmVersion, exposures) + + buildDrugEra(connectionDetails, cdmDatabaseSchema = "main") + eras <- getDrugEras(connectionDetails) + + expect_equal(nrow(eras), 3) + expect_equal(eras$personId, c(1, 1, 2)) + expect_equal(eras$drugEraStartDate, scenarioDay(c(1, 40, 1))) + expect_equal(eras$drugEraEndDate, scenarioDay(c(5, 45, 1))) + expect_equal(eras$drugExposureCount, c(1, 1, 1)) + }) +}