diff --git a/NEWS.md b/NEWS.md index 6eeb08a18..297a7f42a 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,8 @@ # dbplyr (development version) +* Oracle: Added support for `str_replace()` and `str_replace_all()` via + `REGEXP_REPLACE()` (@thomashulst, #1402). + * Allow additional arguments to be passed from `compute()` all the way to `sql_query_save()`-method (@rsund). diff --git a/R/backend-oracle.R b/R/backend-oracle.R index e66ef1b52..9e2bfaa6e 100644 --- a/R/backend-oracle.R +++ b/R/backend-oracle.R @@ -133,6 +133,16 @@ sql_translation.Oracle <- function(con) { paste0 = sql_paste_infix("", "||", function(x) sql_expr(cast(!!x %as% text))), str_c = sql_paste_infix("", "||", function(x) sql_expr(cast(!!x %as% text))), + # https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/REGEXP_REPLACE.html + # 4th argument is starting position (default: 1 => first char of string) + # 5th argument is occurrence (default: 0 => match all occurrences) + str_replace = function(string, pattern, replacement){ + sql_expr(regexp_replace(!!string, !!pattern, !!replacement, 1L, 1L)) + }, + str_replace_all = function(string, pattern, replacement){ + sql_expr(regexp_replace(!!string, !!pattern, !!replacement)) + }, + # lubridate -------------------------------------------------------------- today = function() sql_expr(TRUNC(CURRENT_TIMESTAMP)), now = function() sql_expr(CURRENT_TIMESTAMP) diff --git a/tests/testthat/_snaps/backend-oracle.md b/tests/testthat/_snaps/backend-oracle.md index 5ede3c406..e50731905 100644 --- a/tests/testthat/_snaps/backend-oracle.md +++ b/tests/testthat/_snaps/backend-oracle.md @@ -1,3 +1,14 @@ +# string functions translate correctly + + Code + test_translate_sql(str_replace(col, "pattern", "replacement")) + Output + REGEXP_REPLACE(`col`, 'pattern', 'replacement', 1, 1) + Code + test_translate_sql(str_replace_all(col, "pattern", "replacement")) + Output + REGEXP_REPLACE(`col`, 'pattern', 'replacement') + # queries translate correctly Code diff --git a/tests/testthat/test-backend-oracle.R b/tests/testthat/test-backend-oracle.R index 5c299600f..9824c8245 100644 --- a/tests/testthat/test-backend-oracle.R +++ b/tests/testthat/test-backend-oracle.R @@ -16,6 +16,16 @@ test_that("paste and paste0 translate correctly", { expect_equal(test_translate_sql(str_c(x, y)), sql("`x` || `y`")) }) + +test_that("string functions translate correctly", { + local_con(simulate_oracle()) + + expect_snapshot({ + test_translate_sql(str_replace(col, "pattern", "replacement")) + test_translate_sql(str_replace_all(col, "pattern", "replacement")) + }) +}) + test_that("queries translate correctly", { mf <- lazy_frame(x = 1, con = simulate_oracle()) expect_snapshot(mf %>% head())