Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# climateData (development version)

- `latestHistoricalYear()` and the tile lookup in `ClimateNA_useTiles()` open the bundled tile index read-only
and set the SQLite busy timeout before any other statement. Before, many processes opening it together
(e.g. parallel hindcast jobs parsing fireSense modules on NFS) could fail with "database is locked".
`ClimateNA_sql()` gets a `readonly` argument; writing connections set WAL only when they create the file.

- Solar radiation variables now use the ClimateNA v7.60+ names: `rsds` (annual; was `MAR`), `rsds_wt`,
`rsds_sp`, `rsds_sm`, `rsds_at` (seasonal; were `Rad_*`) and `rsds01`-`rsds12` (monthly; were `Rad01`-`Rad12`).
ClimateNA v7.60 (April 2025) replaced its RAD variables with rsds, based on CHELSA. Only the historical
Expand Down
29 changes: 20 additions & 9 deletions R/ClimateNA_createTiles.R
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ ClimateNA_path <- function(dataPath, tile = NULL, type = NULL, msy = NULL, gcm =
#' @keywords internal
#' @importFrom DBI dbExecute
#' @importFrom RSQLite dbConnect SQLite
sqlite_connect_db <- function(dbfile) {
firstRun <- file.exists(dbfile)
sqlite_connect_db <- function(dbfile, readonly = FALSE) {
newDb <- !file.exists(dbfile)

## `extended_types = TRUE` makes RSQLite return DATETIME columns as hms /
## POSIXct, which requires the `hms` package AT RUNTIME. RSQLite declares hms
Expand All @@ -95,13 +95,21 @@ sqlite_connect_db <- function(dbfile) {
db <- RSQLite::dbConnect(
drv = RSQLite::SQLite(),
dbname = dbfile,
synchronous = "normal",
## `synchronous = NULL`: dbConnect would otherwise run `PRAGMA synchronous` before any busy timeout
## is set, which fails at once with "database is locked" when other processes have the file open.
synchronous = NULL,
flags = if (isTRUE(readonly)) RSQLite::SQLITE_RO else RSQLite::SQLITE_RWC,
extended_types = TRUE ## for DATETIME -- see note above re: hms
)

if (isTRUE(firstRun)) {
DBI::dbExecute(db, "PRAGMA journal_mode = WAL") ## using WAL allows concurrency
DBI::dbExecute(db, "PRAGMA busy_timeout = 60000") ## set busy timeout (ms); allows concurrency.
## must come first: every statement below waits (ms) for a lock instead of failing at once
DBI::dbExecute(db, "PRAGMA busy_timeout = 60000")

if (!isTRUE(readonly)) {
DBI::dbExecute(db, "PRAGMA synchronous = normal")
if (isTRUE(newDb)) {
DBI::dbExecute(db, "PRAGMA journal_mode = WAL") ## using WAL allows concurrency
}
}

return(db)
Expand All @@ -113,6 +121,9 @@ sqlite_connect_db <- function(dbfile) {
#'
#' @template ClimateNA_type
#'
#' @param readonly logical. If `TRUE`, open the database read-only (it is never written to, and a missing
#' table is not created). Use for lookups, so that many processes can read one database at once.
#'
#' @return named list containing:
#' - `db`, the database connection;
#' - `df`, a lazy `tbl_dbi` object (see `dbplyr`).
Expand All @@ -125,8 +136,8 @@ sqlite_connect_db <- function(dbfile) {
#' @rdname ClimateNA_sql
## dplyr::tbl() on a DBI connection needs dbplyr at run time (dplyr's check_dbplyr() stops without it), so
## dbplyr is an Import: without it every tile lookup fails, as R CMD check without Suggests showed.
ClimateNA_sql <- function(dbfile, type) {
db <- sqlite_connect_db(dbfile)
ClimateNA_sql <- function(dbfile, type, readonly = FALSE) {
db <- sqlite_connect_db(dbfile, readonly = readonly)

df_template <- switch(
type,
Expand Down Expand Up @@ -182,7 +193,7 @@ ClimateNA_sql <- function(dbfile, type) {

tbl <- type

if (!DBI::dbExistsTable(db, tbl)) {
if (!isTRUE(readonly) && !DBI::dbExistsTable(db, tbl)) {
DBI::dbCreateTable(db, tbl, df_template)
}

Expand Down
2 changes: 1 addition & 1 deletion R/ClimateNA_useTiles.R
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ getClimateTable <- function(
stopifnot(!is.null(years))
}

dbdf <- ClimateNA_sql(ClimateNA_tiles_sqlite(), type)
dbdf <- ClimateNA_sql(ClimateNA_tiles_sqlite(), type, readonly = TRUE)
climate_db <- dbdf[["db"]]
climate_df <- dbdf[["df"]]
on.exit(DBI::dbDisconnect(climate_db), add = TRUE)
Expand Down
2 changes: 1 addition & 1 deletion R/latestHistoricalYear.R
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
#' @examples
#' latestHistoricalYear()
latestHistoricalYear <- function(tile = NULL, msy = "MSY") {
dbdf <- ClimateNA_sql(ClimateNA_tiles_sqlite(), "historical")
dbdf <- ClimateNA_sql(ClimateNA_tiles_sqlite(), "historical", readonly = TRUE)
on.exit(DBI::dbDisconnect(dbdf[["db"]]), add = TRUE)

climate_df <- dplyr::filter(dbdf[["df"]], msy %in% !!msy) |>
Expand Down
5 changes: 4 additions & 1 deletion man/ClimateNA_sql.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

72 changes: 72 additions & 0 deletions tests/testthat/test-sqliteConcurrency.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
## latestHistoricalYear() and the tile lookup run in many processes at once (every parse of a
## fireSense module calls it). They must only read the index, so concurrent opens must not fail with
## "database is locked".

skip_on_os("windows") ## uses forked workers

dbCopy <- function() {
f <- tempfile(fileext = ".sqlite")
file.copy(ClimateNA_tiles_sqlite(), f)
f
}

test_that("parallel latestHistoricalYear() calls on one database do not fail", {
f <- dbCopy()
on.exit(unlink(paste0(f, c("", "-wal", "-shm"))), add = TRUE)
testthat::local_mocked_bindings(ClimateNA_tiles_sqlite = function() f)
expected <- latestHistoricalYear()

## R CMD check caps forked workers at 2 (_R_CHECK_LIMIT_CORES_)
nWorkers <- if (nzchar(Sys.getenv("_R_CHECK_LIMIT_CORES_"))) 2L else 8L
res <- parallel::mclapply(seq_len(nWorkers), function(i) {
t0 <- Sys.time()
out <- character()
while (difftime(Sys.time(), t0, units = "secs") < 10) {
r <- tryCatch(identical(latestHistoricalYear(), expected), error = function(e) conditionMessage(e))
if (!isTRUE(r)) out <- c(out, as.character(r))
}
out
}, mc.cores = nWorkers)

errs <- unlist(res)
expect_identical(unique(errs), character(0), info = paste(head(errs, 3), collapse = "; "))
})

test_that("a read-only lookup neither writes nor creates tables", {
f <- dbCopy()
on.exit(unlink(paste0(f, c("", "-wal", "-shm"))), add = TRUE)

dbdf <- ClimateNA_sql(f, "historical", readonly = TRUE)
expect_error(DBI::dbExecute(dbdf[["db"]], "DELETE FROM historical"), "readonly")
DBI::dbDisconnect(dbdf[["db"]])

## a table that does not exist is not created on a read path
con <- DBI::dbConnect(RSQLite::SQLite(), f)
DBI::dbExecute(con, "DROP TABLE IF EXISTS future_normals")
DBI::dbDisconnect(con)
expect_error(ClimateNA_sql(f, "future_normals", readonly = TRUE))
con <- DBI::dbConnect(RSQLite::SQLite(), f)
on.exit(DBI::dbDisconnect(con), add = TRUE)
expect_false(DBI::dbExistsTable(con, "future_normals"))
})

test_that("a lookup waits for a lock held by another process instead of failing", {
f <- dbCopy()
on.exit(unlink(paste0(f, c("", "-wal", "-shm"))), add = TRUE)
## rollback-journal mode, where a writer's lock blocks readers
con <- DBI::dbConnect(RSQLite::SQLite(), f)
DBI::dbExecute(con, "PRAGMA journal_mode = DELETE")
DBI::dbDisconnect(con)
testthat::local_mocked_bindings(ClimateNA_tiles_sqlite = function() f)

holder <- parallel::mcparallel({
con <- DBI::dbConnect(RSQLite::SQLite(), f)
DBI::dbExecute(con, "BEGIN EXCLUSIVE")
Sys.sleep(2)
DBI::dbExecute(con, "COMMIT")
DBI::dbDisconnect(con)
})
Sys.sleep(0.5) ## let the holder take its lock
expect_no_error(latestHistoricalYear())
parallel::mccollect(holder)
})
Loading