Learn R Programming

commons (version 0.0.1)

semantic_layer: Create a semantic layer

Description

A semantic layer collects governed measures for a commons() agent. The agent searches these measures before writing SQL. When a measure matches, the agent runs the calculation defined by your data team.

Usage

semantic_layer(...)

Value

A commons_semantic_layer object.

Arguments

...

Paths to R scripts or directories containing functions marked with @measure.

Details

A measure is an ordinary R function documented with roxygen comments and marked with @measure. It can take model-supplied and injected arguments:

  • Arguments documented with @param are supplied by the model.

  • Undocumented arguments are hidden from the model. commons() supplies a matching data source's connection or keeps the argument's default. It errors if neither is available.

Because the measure receives its connection as an argument, the semantic layer can be defined before the connection is opened.

For another dependency, such as an API client, use a default expression that constructs it. Referring to a variable instead would make the measure depend on the environment where the semantic layer was created.

See Also

commons() to give a semantic layer to an agent.

Examples

Run this code
measure_file <- tempfile(fileext = ".R")
writeLines(
  c(
    "#' Revenue by region",
    "#'",
    "#' @param region `string` Sales region.",
    "#' @measure",
    "revenue_by_region <- function(region, warehouse) {",
    "  DBI::dbGetQuery(",
    "    warehouse,",
    "    'SELECT sum(revenue) AS revenue FROM sales WHERE region = ?',",
    "    params = list(region)",
    "  )",
    "}"
  ),
  measure_file
)

layer <- semantic_layer(measure_file)
unlink(measure_file)

Run the code above in your browser using DataLab