Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add table CRUD function with unit tests #2

Merged
merged 5 commits into from
Jun 17, 2024
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
6 changes: 3 additions & 3 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ Imports:
cli (>= 3.6.2),
tidyselect (>= 1.2.1),
purrr (>= 1.0.2),
RSQLite (>= 2.3.5),
rlang (>= 1.1.3)
RSQLite (>= 2.3.5)
Suggests:
devtools (>= 2.2.0),
testthat (>= 3.0.0)
testthat (>= 3.0.0),
withr (>= 3.0.0)
License: MIT + file LICENSE
Encoding: UTF-8
Roxygen: list(markdown = TRUE)
Expand Down
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
export(add_entry_tbl)
export(check_notnull_fields)
export(check_pkeys_fields)
export(delete_entry_tbl)
export(detect_cens)
export(get_tbl_fields_notnull)
export(get_tbl_fields_pkey)
export(get_tbl_info)
export(init_con)
export(modify_entry_tbl)
export(remove_cens)
export(search_tbl)
export(uncensored)
2 changes: 1 addition & 1 deletion R/db_con.R
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@
init_con <- function(){
db <- file.path(db_path(), db_name())
stopifnot(db |> file.exists())
DBI::dbConnect(RSQLite::SQLite(), db)
return(DBI::dbConnect(RSQLite::SQLite(), db))
}
42 changes: 23 additions & 19 deletions R/db_info_misc.R
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#' Check if pkeys presents
#'
#' @param con connexion object returned by DBI::dbConnect()
#' @param tbl a character name of the table
#' @param fields a vector of column names in the specified table
#'
Expand All @@ -8,12 +9,12 @@
#'
#' @examples
#' \dontrun{
#' check_pkeys_fields("species", fields = c("species_id"))
#' check_pkeys_fields(con, "species", fields = c("species_id"))
#' }
#' @export
#'
check_pkeys_fields <- function(tbl, fields){
pkeys <- get_tbl_fields_pkey(tbl)
check_pkeys_fields <- function(con, tbl, fields){
pkeys <- get_tbl_fields_pkey(con, tbl = tbl)

if(!all(pkeys %in% names(fields))){
missing_pkeys <- pkeys[which(!pkeys %in% fields)] |>
Expand All @@ -24,6 +25,7 @@ check_pkeys_fields <- function(tbl, fields){

#' Check if not null fields present
#'
#' @param con connexion object returned by DBI::dbConnect()
#' @param tbl a character name of the table
#' @param fields a vector of column names in the specified table
#'
Expand All @@ -32,14 +34,14 @@ check_pkeys_fields <- function(tbl, fields){
#'
#' @examples
#' \dontrun{
#' check_notnull_fields("species", fields = c("species_id"))
#' check_notnull_fields(con, "species", fields = c("species_id"))
#' }
#'
#' @export
check_notnull_fields <- function(tbl, fields){
notnulls <- get_tbl_fields_notnull(tbl)
check_notnull_fields <- function(con, tbl, fields){
notnulls <- get_tbl_fields_notnull(con, tbl = tbl)

if(!all(notnulls %in% fields)){
if(!all(notnulls %in% names(fields))){
missing_fields <- notnulls[which(!notnulls %in% fields)] |>
glue::glue_collapse(", ", last = "and")
cli::cli_abort("{ missing_fields } cannot be null(s)")
Expand All @@ -48,6 +50,7 @@ check_notnull_fields <- function(tbl, fields){

#' Get table fields properties (fkey, pkey, unique constraints etc.)
#'
#' @param con connexion object returned by DBI::dbConnect()
#' @param tbl a character name of the table
#'
#' @return
Expand All @@ -64,15 +67,15 @@ check_notnull_fields <- function(tbl, fields){
#' get_tbl_info("species")
#' }
#' @export
get_tbl_info <- function(tbl) {
con <- init_con()
res <- DBI::dbGetQuery(con, glue::glue("SELECT * FROM pragma_table_info('{ tbl }');"))
on.exit(DBI::dbDisconnect(con))
get_tbl_info <- function(con = NULL, tbl = NULL) {
q <- glue::glue_sql("SELECT * FROM pragma_table_info({tbl});", .con = con)
res <- DBI::dbGetQuery(con, q)
return(res)
}

#' Get table primary key fields
#'
#' @param con connexion object returned by DBI::dbConnect()
#' @param tbl a character name of the table
#'
#' @return
Expand All @@ -83,14 +86,15 @@ get_tbl_info <- function(tbl) {
#' get_tbl_fields_pkey("species")
#' }
#' @export
get_tbl_fields_pkey <- function(tbl){
get_tbl_info(tbl) |>
dplyr::filter(rlang::.data$pk == 1) |>
dplyr::pull(rlang::.data$name)
get_tbl_fields_pkey <- function(con, tbl){
get_tbl_info(con, tbl = tbl) |>
dplyr::filter(pk == 1) |>
dplyr::pull(name)
}

#' Get table not null fields
#'
#' @param con connexion object returned by DBI::dbConnect()
#' @param tbl a character name of the table
#'
#' @return
Expand All @@ -101,9 +105,9 @@ get_tbl_fields_pkey <- function(tbl){
#' get_tbl_fields_notnull("species")
#' }
#' @export
get_tbl_fields_notnull <- function(tbl){
get_tbl_info(tbl) |>
dplyr::filter(rlang::.data$notnull == 1) |>
dplyr::pull(rlang::.data$name)
get_tbl_fields_notnull <- function(con, tbl){
get_tbl_info(con, tbl = tbl) |>
dplyr::filter(notnull == 1) |>
dplyr::pull(name)
}

22 changes: 10 additions & 12 deletions R/db_search.R
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#' search_tbl
#'
#' @param con connexion object returned by DBI::dbConnect()
#' @param tbl a character name of the table
#' @param ... table fields with search value
#'
Expand All @@ -8,11 +9,11 @@
#'
#' @examples
#' \dontrun{
#' search_tbl("species", genus = "%Poo%")
#' search_tbl(con, "species", genus = "%Poo%")
#' }
#' @export
#'
search_tbl <- function(tbl,...){
search_tbl <- function(con = NULL, tbl = NULL,...){

fields <- list(...)
tbl_fields <- DBI::dbListFields(con, tbl)
Expand All @@ -22,29 +23,26 @@ search_tbl <- function(tbl,...){
stopifnot(all(names(fields) %in% tbl_fields))

search_criterias <- purrr::map2(names(fields), fields, \(n, p){
if(length(p) == 1L){
glue::glue("{n} LIKE ${n}")
if(length(p) > 1L){
glue::glue_sql("{`n`} IN ({ p* })", .con = con)
} else {
cli::cli_abort("{n} as more than one search criterias")
glue::glue_sql("{`n`} LIKE { p }", .con = con)
}
}) |> glue::glue_collapse(" OR ")
}) |> glue::glue_sql_collapse(" OR ")

query <- glue::glue("SELECT * FROM {tbl} WHERE {search_criterias};")

con <- init_con()
query <- glue::glue_sql("SELECT * FROM { tbl } WHERE { search_criterias };", .con = con)

res <- DBI::dbSendQuery(con, query)
DBI::dbBind(res, fields)

entries <- list()
while (!DBI::dbHasCompleted(res)) {
entries[[length(entries)+1]] <- DBI::dbFetch(res, 100)
}
entries <- dplyr::bind_rows(entries)

cli::cli_alert_info("Found {nrow(entries)} entries")
cli::cli_alert_info("Found { nrow(entries) } entries")

on.exit(DBI::dbClearResult(res))
on.exit(DBI::dbDisconnect(con), add=TRUE, after = TRUE)

return(entries)
}
Expand Down
70 changes: 31 additions & 39 deletions R/db_tbl.R
Original file line number Diff line number Diff line change
@@ -1,42 +1,37 @@
#' DB getters
#'
#' Retrieve specific information from our admin database.
#' Add entry within specified table
#'
#' @param con connexion object returned by DBI::dbConnect()
#' @param tbl a character name of the table
#' @param ... a vector of column names in the specified table
#'
#'
#' @describeIn get_column_elements Get species name list.
#' @export
#'
add_entry_tbl <- function(tbl, ...){
add_entry_tbl <- function(con = NULL, tbl = NULL, ...){
fields <- list(...)

check_pkeys_fields(tbl, fields)
check_notnull_fields(tbl, fields)
check_pkeys_fields(con, tbl, fields)
check_notnull_fields(con, tbl, fields)

columns <- glue::glue_collapse(names(fields), ", ")
values <- glue::glue_collapse(fields, ", ")

ddl <- glue::glue("INSERT INTO {tbl} ({columns}) VALUES ({glue::single_quote(values)});")
con <- init_con()
ddl <- glue::glue_sql("INSERT INTO { tbl } ({ names(fields)* }) VALUES ({ fields* });", .con = con)
res <- DBI::dbSendStatement(con, ddl)

if(DBI::dbHasCompleted(res)){
cli::cli_alert_info("{ DBI::dbGetRowsAffected(res) } row inserted in {tbl}")
cli::cli_alert_info("{ DBI::dbGetRowsAffected(res) } row inserted in { tbl }")
}

on.exit(DBI::dbClearResult(res))
on.exit(DBI::dbDisconnect(con), add=TRUE, after = TRUE)
}

modify_entry_tbl <- function(tbl, ...){
#' @describeIn add_entry_tbl Modify entry within specified table.
#' @export
#'
modify_entry_tbl <- function(con = NULL, tbl = NULL, ...){
fields <- list(...)

check_pkeys_fields(tbl, fields)
check_pkeys_fields(con, tbl, fields)

pkeys_tbl <- get_tbl_fields_pkey(tbl)
target_row <- do.call("search_tbl", list(tbl = tbl) |> append(fields[pkeys_tbl]))
pkeys_tbl <- get_tbl_fields_pkey(con, tbl)
target_row <- do.call("search_tbl", list(con = con, tbl = tbl) |> append(fields[pkeys_tbl]))

if(nrow(target_row) > 1L){
cli::cli_abort("Error: More than one row found with { fields[pkeys_tbl] }")
Expand All @@ -47,19 +42,18 @@ modify_entry_tbl <- function(tbl, ...){

update_entries <- purrr::map(names(update_values), \(n){
glue::glue("{n} = ${n}")
}) |> glue::glue_collapse(",")
}) |> glue::glue_sql_collapse(",")

criterias <- purrr::map(names(pkeys_values), \(n){
glue::glue("{n} = ${n}")
}) |> glue::glue_collapse(" AND ")
}) |> glue::glue_sql_collapse(" AND ")

ddl <- glue::glue("
UPDATE {tbl}
ddl <- glue::glue_sql("
UPDATE { tbl }
SET { update_entries }
WHERE { criterias };
")
", .con = con)

con <- init_con()
res <- DBI::dbSendStatement(con, ddl)
DBI::dbBind(res, fields)

Expand All @@ -68,31 +62,32 @@ modify_entry_tbl <- function(tbl, ...){
}

on.exit(DBI::dbClearResult(res))
on.exit(DBI::dbDisconnect(con), add=TRUE, after = TRUE)
}
}

delete_entry_tbl <- function(tbl, ...){
#' @describeIn add_entry_tbl Delete entry within specified table.
#' @export
#'
delete_entry_tbl <- function(con = NULL, tbl = NULL, ...){
fields <- list(...)

check_pkeys_fields(tbl, fields)
pkeys_tbl <- get_tbl_fields_pkey(tbl)
target_row <- do.call("search_tbl", list(tbl = tbl) |> append(fields[pkeys_tbl]))
check_pkeys_fields(con, tbl, fields)
pkeys_tbl <- get_tbl_fields_pkey(con, tbl)
target_row <- do.call("search_tbl", list(con = con, tbl = tbl) |> append(fields[pkeys_tbl]))

if(nrow(target_row) > 1L){
cli::cli_abort("Error: More than one row found with { fields[pkeys_tbl] }")
} else {
criterias <- purrr::map(names(fields[pkeys_tbl]), \(n){
glue::glue("{n} = ${n}")
}) |> glue::glue_collapse(" AND ")
}) |> glue::glue_sql_collapse(" AND ")

ddl <- glue::glue("
ddl <- glue::glue_sql("
DELETE
FROM {tbl}
FROM { tbl }
WHERE { criterias };
")
", .con = con)

con <- init_con()
res <- DBI::dbSendStatement(con, ddl)
DBI::dbBind(res, fields)

Expand All @@ -101,12 +96,9 @@ delete_entry_tbl <- function(tbl, ...){
}

on.exit(DBI::dbClearResult(res))
on.exit(DBI::dbDisconnect(con), add=TRUE, after = TRUE)
}
}

get_tbl <- function(tbl) {
con <- init_con()
get_tbl <- function(con = NULL, tbl = NULL) {
DBI::dbReadTable(con, tbl)
on.exit(DBI::dbDisconnect(con))
}
31 changes: 31 additions & 0 deletions man/add_entry_tbl.Rd

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

6 changes: 4 additions & 2 deletions man/check_notnull_fields.Rd

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

Loading