From b59c996c9a7d3742132b195b8ac6740778ee880b Mon Sep 17 00:00:00 2001 From: Robrecht Cannoodt Date: Fri, 11 Oct 2024 11:14:03 +0200 Subject: [PATCH] Return `NULL` when a record's related field is empty (#28) * Add a simple unit test which queries laminlabs/lamindata * update changelog * Return `NULL` when a record's related field is empty * update changelog * add checks to test --- CHANGELOG.md | 2 ++ R/Record.R | 9 ++++++++- tests/testthat/test-connect_lamindata.R | 8 +++++++- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8689639..bd67e92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,8 @@ * Fixed the parsing of the env files in `~/.lamin` due to changes in the lamindb-setup Python package (PR #12). +* Return `NULL` when a record's related field is empty (PR #28). + # laminr v0.0.1 Initial POC implementation of the LaminDB API client for R. diff --git a/R/Record.R b/R/Record.R index cfc9b1d..415c578 100644 --- a/R/Record.R +++ b/R/Record.R @@ -163,7 +163,7 @@ Record <- R6::R6Class( # nolint object_name_linter } else if (key %in% private$.registry$get_field_names()) { field <- private$.registry$get_field(key) - ## TODO: use related_registry_class$get_records instead + # refetch the record to get the related data related_data <- private$.api$get_record( module_name = field$module_name, registry_name = field$registry_name, @@ -171,10 +171,17 @@ Record <- R6::R6Class( # nolint object_name_linter select = key )[[key]] + # return NULL if the related data is NULL + if (is.null(related_data)) { + return(NULL) + } + + # if the related data is not NULL, create a record class for it related_module <- private$.instance$get_module(field$related_module_name) related_registry <- related_module$get_registry(field$related_registry_name) related_registry_class <- related_registry$get_record_class() + # if the relation type is one-to-many or many-to-many, iterate over the list if (field$relation_type %in% c("one-to-one", "many-to-one")) { related_registry_class$new(related_data) } else { diff --git a/tests/testthat/test-connect_lamindata.R b/tests/testthat/test-connect_lamindata.R index e27bc47..126ac79 100644 --- a/tests/testthat/test-connect_lamindata.R +++ b/tests/testthat/test-connect_lamindata.R @@ -15,7 +15,13 @@ test_that("Connecting to lamindata works", { expect_equal(artifact$uid, "mePviem4DGM4SFzvLXf3") expect_equal(artifact$suffix, ".csv") - # try to fetch linked records + # try to fetch related field created_by <- artifact$created_by expect_equal(created_by$handle, "sunnyosun") + + # access a related field which is empty for this record + expect_null(artifact$type) # one to one + + expect_type(artifact$wells, "list") # one-to-many + expect_length(artifact$wells, 0) })