---
title: "Work with reference catalogues"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Work with reference catalogues}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

## About this guide

> This guide prepares the survey references, finds matching rows and demonstrates private catalogue configuration.

Read the [Terminology](terminology.html) for the concepts used in this guide.

Find the schemas and example downloads in [Package resources](resources.html).


## Prepare references from a form model

```{r}
library(form.model)
# Load the survey form model.
form_model_definition <- read_form_model("examples/survey/form.yaml", "form.model")
# Read the survey catalogue sources and lookup settings.
reference_configuration <- read_reference_configuration(
  system.file("examples", "survey", "references.yaml", package = "form.model"))
# Use a temporary cache for all catalogue sources in this vignette.
reference_cache_directory <- tempfile("survey-cache-")
for (catalogue in names(reference_configuration$catalogues))
  reference_configuration$catalogues[[catalogue]]$source$cache <- reference_cache_directory
# Prepare the tables and lookups required by the form model using the configured sources.
reference_preparation <- prepare_model_references(
  form_model_definition, reference_configuration)
# Display the prepared reference identifiers.
names(reference_preparation$references)
```

Aliases belong to their catalogue and use its authentication, checksums and cache.
The catalogue row uses ID `_aliases_` and domain `catalogue`.
Its path is `catalogue_aliases.csv`, relative to its catalogue source directory.
Each row identifies a table, column, alias and canonical value; canonical targets must exist.

Aliases are grouped once by table and column, then applied automatically by each required lookup.
Consumers do not extract or pass alias mappings.
For inspection, a prepared lookup's `$aliases` contains only that lookup's mappings.

```{r}
# Select the prepared station lookup.
reference_station_snapshot <- reference_preparation$references[["code_lists/stations/code"]]
# Find the canonical station row using its alias.
reference_match_rows(reference_station_snapshot, "OLD-STATION")
```

## Retrieve tables explicitly

The survey form model declares the code lists `stations` and `observers` and the registry `contacts`.
The public example catalogues use those exact lowercase IDs.

This example uses the installed catalogues and reuses the temporary cache created above.

```{r}
# Configure the installed code-list source.
reference_source_configuration <- reference_source(
  system.file("examples", "survey", "catalogue", "code_lists", package = "form.model"), reference_cache_directory
)
# Retrieve the selected code-list tables and verify their checksums.
reference_values <- get_reference_tables(c("observers", "stations"), reference_source_configuration)
# Display the selected reference rows or values.
reference_values$data$stations
# Display the selected reference rows or values.
reference_values$data$observers
# Configure the reference catalogue sources.
reference_registry_source <- reference_source(
  system.file("examples", "survey", "catalogue", "registries", package = "form.model"), reference_cache_directory
)
# Retrieve the selected reference tables and verify their checksums.
reference_registry_tables <- get_reference_tables("contacts", reference_registry_source)
# Display the selected reference rows or values.
reference_registry_tables$data$contacts$email
```

All CSV columns remain text. Station code `001` keeps its leading zeros.

`reference_values$catalogue` contains versions, source dates, paths and checksums for the selected references.

`reference_values$paths` points to verified local files. `reference_values$publication` identifies the catalogue used.

## Use configured lookups

The survey configuration declares lookups for both catalogues.

See [Package resources](resources.html#reference-configuration-schema) for the fields and defaults.

```{r}
# Resolve reference lookups without changing the original form model.
reference_resolved_form_model <- resolve_reference_lookups(form_model_definition, reference_configuration)
# Group the downloaded tables by their configured catalogue names.
reference_catalogues <- list(code_lists = reference_values$data, registries = reference_registry_tables$data)

# Build every declared lookup using the downloaded tables.
reference_indexes <- lapply(names(reference_configuration$catalogues), function(catalogue) {
  # Read the table lookup definitions for this catalogue.
  reference_tables <- reference_configuration$catalogues[[catalogue]]$tables
  # Build the configured lookups for each table.
  lapply(names(reference_tables), function(table) {
    # Create a lookup index for each declared column.
    reference_table_lookups <- lapply(names(reference_tables[[table]]), function(column) {
      # Apply the column matching settings to the complete table.
      do.call(reference_index, c(
        list(data = reference_catalogues[[catalogue]][[table]], column = column),
        reference_tables[[table]][[column]][c("matching", "ignore_case")]
      ))
    })
    # Name the indexes after their lookup columns.
    names(reference_table_lookups) <- names(reference_tables[[table]])
    # Return the named indexes for this table.
    reference_table_lookups
  }) |> stats::setNames(names(reference_tables))
}) |> stats::setNames(names(reference_configuration$catalogues))

# Select the station-code lookup index.
reference_station_index <- reference_indexes$code_lists$stations$code
# Find the station rows matching the submitted code.
reference_station_rows <- reference_match_rows(reference_station_index, "001")
# Display the selected reference rows or values.
reference_station_index$data[reference_station_rows[[1]], , drop = FALSE]

# Select the observer-code lookup index.
reference_observer_index <- reference_indexes$code_lists$observers$code
# Find observer rows using case-insensitive comparison.
reference_observer_rows <- reference_match_rows(reference_observer_index, "alice")
# Display the selected reference rows or values.
reference_observer_index$data[reference_observer_rows[[1]], , drop = FALSE]

# Select the contact-email lookup index.
reference_email_index <- reference_indexes$registries$contacts$email
# Find contact rows matching the submitted email.
reference_email_rows <- reference_match_rows(reference_email_index, "ALICE@EXAMPLE.ORG")
# Display the selected reference rows or values.
reference_email_index$data[reference_email_rows[[1]], , drop = FALSE]

# Select the contact-name lookup index.
reference_name_index <- reference_indexes$registries$contacts$name
# Compare a reordered name and an unknown name.
reference_name_rows <- reference_match_rows(reference_name_index, c("Example Alice", "Unknown"))
# Display the number of matching rows for each submitted value.
lengths(reference_name_rows)
# Display the selected reference rows or values.
reference_name_index$data[reference_name_rows[[1]], , drop = FALSE]
```

The results retain canonical values and complete rows. Unknown values return no matching rows.

## Reuse the cache

Online calls fetch the YAML metadata first. CSVs are reused when their verified checksums match.

Changed files are downloaded temporarily, checked, then installed in the cache.

Missing HTTP files download concurrently, with four requests at a time by default.
Set `max_connections` in `reference_source()` to change that limit.

A failed download raises an error and leaves previous verified files intact. It never silently returns stale data.

Offline mode makes no source requests and fails if a required cached file is missing or corrupt.

```{r}
# Retrieve verified tables from the local cache without contacting the source.
reference_cached_tables <- get_reference_tables(c("observers", "stations"), reference_source_configuration, offline = TRUE)
# Display the selected reference rows or values.
reference_cached_tables$data$stations$code
```

Concurrent catalogue updates to the same cache are rejected with a busy-cache error.

If a process was killed, remove its `.catalogue-lock` directory only after confirming no process still uses that cache.

## Read references without a model

```{r}
# Configure the reference catalogue sources.
reference_station_tables <- get_reference_tables("stations", reference_source_configuration)
# Display the selected reference rows or values.
reference_station_tables$data$stations
```

IDs must match exactly; there is no prefix stripping, case conversion or inferred alias mapping.

## Authenticate a private registry source

This example loads the survey registries from an Apache directory protected by Basic authentication over HTTPS.

### 1. Publish and protect the survey registries

Copy the installed survey reference directory to your private HTTPS directory:

```{r, eval=FALSE}
# Locate the installed example resources.
system.file("examples", "survey", "catalogue", "registries", package = "form.model")
```

Keep its directory layout. Apache must protect the whole directory, including metadata, data and aliases.

Use the final HTTPS URL: authenticated downloads do not follow redirects.

### 2. Configure the source in YAML

Copy the installed example to your working directory:

```{r, eval=FALSE}
# Copy the installed example into the working directory.
file.copy(
  system.file("examples", "references.private.example.yaml", package = "form.model"),
  "references.yaml",
  overwrite = FALSE
)
```

Replace its contents with the private source settings:

```yaml
schema_version: "1.0.0"
catalogues:
  registries:
    source:
      url: https://references.example.org/registries/
      cache: cache/private-survey
      user: survey-reader
      password: !env REGISTRY_PASSWORD
    tables:
      contacts:
        email: {matching: exact, ignore_case: true}
```

Replace the URL and user. The `!env` value names a session variable; the password is not stored in the file.

### 3. Enter the password and download

Install `askpass` once for its secure password prompt:

```{r, eval=FALSE}
# Install the dependency needed for this example.
install.packages("askpass")
```

Enter the password and read the configuration:

```{r, eval=FALSE}
library(form.model)

# Read the private catalogue configuration, prompting for a missing password.
reference_private_configuration <- read_reference_configuration("references.yaml", prompt = TRUE)

# Retrieve the selected reference tables and verify their checksums.
reference_registry_tables <- get_reference_tables("contacts", reference_private_configuration$catalogues$registries$source)
# Display the selected reference rows or values.
reference_registry_tables$data$contacts$email
# "alice@example.org" "bob@example.org"
```

The loader uses the environment password if present; otherwise `prompt = TRUE` opens a secure password dialog.

The answer stays in memory without changing environment variables. Cancellation or an empty answer raises an error.

Credentials remain in the source object in memory. Do not save it to disk; they are not printed or cached.

For CI, supply `REGISTRY_PASSWORD` from the secret store and keep the default `prompt = FALSE`.

Use a separate cache for each authenticated identity. Downloaded registry data remains in that local cache.

### 4. Reuse the verified cache offline

After one successful download, use the same source and cache without contacting Apache:

```{r, eval=FALSE}
# Retrieve the selected reference tables and verify their checksums.
reference_registry_tables <- get_reference_tables(
  "contacts", reference_private_configuration$catalogues$registries$source, offline = TRUE)
# Display the selected reference rows or values.
reference_registry_tables$data$contacts$email
```

Offline mode needs no credentials. It fails if required cached files are missing or fail checksum verification.

```{r, include=FALSE}
# Remove the temporary files created by this example.
unlink(reference_cache_directory, recursive = TRUE)
```
