> ## Documentation Index
> Fetch the complete documentation index at: https://learn.nextedy.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Query Context

> The query context in Nextedy POWERSHEET is the runtime object that dynamic expressions and constraints resolve against when queries execute.

export const LastReviewed = ({date}) => {
  if (!date) return null;
  const formatted = new Date(`${date}T00:00:00Z`).toLocaleDateString("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric",
    timeZone: "UTC"
  });
  return <p className="mt-10 text-sm text-gray-400 dark:text-zinc-500 not-prose">
      Last reviewed on {formatted}
    </p>;
};

<Frame>
  <img src="https://mintcdn.com/none-17b4493f/-WiVljKlDztH36bB/powersheet/diagrams/reference/query-api/query-context/diagram-1.svg?fit=max&auto=format&n=-WiVljKlDztH36bB&q=85&s=f06fdba46a013c17d41016ca4204c2ce" alt="diagram" style={{ width: "560px", maxWidth: "100%" }} width="560" height="320" data-path="powersheet/diagrams/reference/query-api/query-context/diagram-1.svg" />
</Frame>

## Context Object Structure

The context object is a hierarchical namespace that Powersheet populates at runtime. Different properties become available depending on where the expression is evaluated.

```
context
+-- parameters          Configuration-supplied parameters
|   +-- model           Dynamic data model ID (e.g. context.parameters.model)
+-- user                Current logged-in user
|   +-- id, name
+-- sources             All configured data source definitions
+-- document            Current document information
|   +-- title, type, id, moduleName, moduleFolder, component
+-- tool                Current tool information
|   +-- type
+-- item                Current entity (available in per-cell contexts)
|   +-- {propertyName}  e.g. context.item.StoryPoints
+-- source              Parent/source entity (in relationship contexts)
|   +-- type, {propertyName}  e.g. context.source.type, context.source.document.component
+-- entity              Current entity as a plain object
+-- value               Current cell's display value
```

### Context Properties Reference

| Property                        | Type     | Description                                                                                       |
| ------------------------------- | -------- | ------------------------------------------------------------------------------------------------- |
| `context.parameters`            | `object` | Configuration-injected parameters surfaced to the runtime                                         |
| `context.parameters.model`      | `string` | Dynamic data model identifier used to select an RTM model at runtime                              |
| `context.user`                  | `object` | Current authenticated Polarion user                                                               |
| `context.user.id`               | `string` | Polarion user ID                                                                                  |
| `context.user.name`             | `string` | Display name of the current user                                                                  |
| `context.sources`               | `object` | All configured data source definitions from the sheet configuration                               |
| `context.document`              | `object` | Current Polarion LiveDoc document metadata                                                        |
| `context.document.title`        | `string` | Document title                                                                                    |
| `context.document.type`         | `string` | Document type identifier                                                                          |
| `context.document.id`           | `string` | Full document path in `folder/name` format                                                        |
| `context.document.moduleName`   | `string` | Document module name                                                                              |
| `context.document.moduleFolder` | `string` | Document folder path                                                                              |
| `context.document.component`    | `string` | Document component (e.g., `"Braking"`)                                                            |
| `context.tool`                  | `object` | Current tool information                                                                          |
| `context.tool.type`             | `string` | Tool type identifier                                                                              |
| `context.item`                  | `object` | Current row entity with all properties accessible by name                                         |
| `context.item.{propertyName}`   | `varies` | Any property of the current entity (e.g., `context.item.StoryPoints`, `context.item.Probability`) |
| `context.source`                | `object` | Parent/source entity in relationship navigation contexts                                          |
| `context.source.type`           | `string` | Parent entity's work item type (e.g., `"systemRequirement"`)                                      |
| `context.entity`                | `object` | Current entity as a plain JavaScript object                                                       |
| `context.value`                 | `varies` | Current cell's resolved display value                                                             |

## Two Expression Notations

Powersheet uses two distinct notations for dynamic expressions, each tied to a specific configuration context.

| Notation               | Syntax                   | Used In                                                                    |
| ---------------------- | ------------------------ | -------------------------------------------------------------------------- |
| **Context expression** | `$context.property.path` | Data model configuration (constraints)                                     |
| **Dynamic value**      | `() => expression`       | Sheet configuration (`where`, `formula`, `render`, `formatter`, `display`) |

<Tip title="Rule of Thumb">
  If you are editing a **data model** YAML file (`domainModelTypes`, `relationships`), use `$context`. If you are editing a **sheet configuration** YAML file (`sources`, `columns`, `formatters`), use `() =>`.
</Tip>

### Context Expression (`$context`)

Context expressions use dot-notation to access properties from the runtime context. They are used exclusively in data model constraint definitions. No JavaScript logic is supported --- only direct property access.

**Where it is used:**

* `domainModelTypes.*.constraints` --- entity type constraints
* `relationships.*.direct.constraints` / `relationships.*.back.constraints` --- relationship constraints

**Available `$context` paths:**

| Path                                    | Description                          | Example Value                       |
| --------------------------------------- | ------------------------------------ | ----------------------------------- |
| `$context.source.type`                  | Source entity's work item type       | `"sys_req"`                         |
| `$context.source.document.id`           | Source entity's document ID          | `"Requirements/SRS"`                |
| `$context.source.document.moduleName`   | Source entity's document module name | `"UserNeedSpecification"`           |
| `$context.source.document.moduleFolder` | Source entity's document folder      | `"Requirements"`                    |
| `$context.source.document.component`    | Source entity's document component   | `"Braking"`                         |
| `$context.source.document.type`         | Source entity's document type        | `"systemRequirementsSpecification"` |
| `$context.source.document.title`        | Source entity's document title       | `"System Requirements"`             |

<Note title="Per-Row Evaluation">
  Dynamic constraints with `$context` are evaluated **per-row**. Different rows can produce different constraint values depending on their source entity's properties.
</Note>

### Dynamic Value (`() => expression`)

Dynamic values use JavaScript arrow function syntax and are evaluated in sheet configuration contexts. They receive the `context` object and offer full JavaScript expressiveness for computing values, filtering data, and rendering content at runtime.

**Where it is used:**

| Sheet Configuration Property | Purpose                                          |
| ---------------------------- | ------------------------------------------------ |
| `sources.query.where`        | Filter data with dynamic predicates              |
| `sources.entityFactory`      | Set initial values for new items                 |
| `columns.*.formula`          | Calculate column values from other properties    |
| `columns.*.render`           | Custom HTML rendering for cells                  |
| `columns.*.display`          | Override display value for navigation properties |
| `renderers.*`                | Named renderer definitions                       |
| `formatters.*.expression`    | Conditional formatting expressions               |

## Context Availability Reference

Not all context properties are available in every expression location. The following reference shows which properties are accessible where:

| Usage Location         | `.user` | `.sources` | `.document` | `.item` | `.value` | `.source` | `.entity` |
| ---------------------- | ------- | ---------- | ----------- | ------- | -------- | --------- | --------- |
| `where`                | ✅       | ✅          | ✅           | ---     | ---      | ---       | ---       |
| `entityFactory`        | ✅       | ✅          | ---         | ---     | ---      | ✅         | ---       |
| `formula`              | ✅       | ✅          | ---         | ✅       | ✅        | ✅         | ✅         |
| `render` / `renderers` | ---     | ---        | ---         | ✅       | ✅        | ---       | ---       |
| `formatter`            | ---     | ---        | ✅           | ✅       | ✅        | ---       | ---       |
| `display`              | ---     | ---        | ---         | ✅       | ✅        | ✅         | ---       |

<Warning title="Accessing Unavailable Properties">
  Referencing a context property that is not available in the current location returns `undefined`. This does not produce an error but may cause unexpected behavior in your expressions. Always consult the table above.
</Warning>

## Document Context

Powersheet automatically provides document context information to queries and expressions. When a sheet is embedded in a Polarion LiveDoc, the `context.document` properties are populated from the hosting document. The two most commonly used properties in dynamic `where` clauses are `context.document.moduleName` and `context.document.moduleFolder`, which identify the hosting document by name and folder path.

### Document Scoping in Constraints

The `applyCurrentDocumentTo` constraint property controls whether queries are automatically filtered to the current document:

```yaml theme={null}
sources:
  - id: requirements
    model: rtm
    query:
      from: UserNeed
    constraints:
      applyCurrentDocumentTo: UserNeed
```

When `applyCurrentDocumentTo` matches the query's `from` entity type, the query engine injects predicates for `document.moduleFolder` and `document.moduleName` to restrict results to items within the current document.

### Document ID in Dynamic Expressions

The document ID is available as `context.document.id` in dynamic value expressions and as a query parameter for server-side resolution:

```yaml theme={null}
sources:
  - id: scoped-items
    query:
      from: SystemRequirement
      where:
        documentId:
          "==": "() => context.document.id"
```

For details on document constraint variants, see [Document Filtering](/powersheet/reference/query-api/document-filtering).

## Project Scoping

All queries executed through Powersheet are automatically scoped to the current Polarion project. The query engine adds a `project.id` filter to every Lucene query, ensuring results only include entities from the active project. This scoping is applied transparently and does not require explicit configuration.

## Dynamic Value Examples

### Filtering by Current Document (Module Name)

The most common dynamic `where` clause restricts a query to items in the hosting LiveDoc. Use `context.document.moduleName` to match the document by name:

```yaml theme={null}
sources:
  - id: in-document
    query:
      from: SystemRequirement
      where:
        moduleName:
          "==": "() => context.document.moduleName"
```

For a more precise match that also pins the folder path, combine `moduleName` with `moduleFolder`:

```yaml theme={null}
where:
  moduleName:
    "==": "() => context.document.moduleName"
  moduleFolder:
    "==": "() => context.document.moduleFolder"
```

### Using `column.display` for Document and Chapter References

The `column.display` option is the standard way to control how a navigation property is rendered in a cell. For document references, `display: titleOrName` renders the document's title when available and falls back to the module name:

```yaml theme={null}
columns:
  systemRequirement.document:
    display: titleOrName
```

For chapter references, `display: title` renders the chapter heading text:

```yaml theme={null}
columns:
  systemRequirement.chapter:
    display: title
```

These named display modes are preferred over dynamic expressions whenever a column simply needs a standard label for a linked entity.

### Filtering by Date

Dynamic date calculations use JavaScript date functions. The resulting value must match the data type format --- for dates, use `.toISOString()`:

```yaml theme={null}
sources:
  - id: upcoming
    query:
      from: Task
      where:
        DueDate:
          ">": "() => new Date().toISOString()"
```

### Setting Initial Values for New Entities

The `entityFactory` property sets default values when creating new work items. The factory re-evaluates dynamically based on the parent entity, so context-sensitive defaults are typically derived from `context.source`:

```yaml theme={null}
sources:
  - id: verification
    entityFactory:
      title: '() => context.source.type + "_VerificationTestCase"'
```

Here, the new test case title is composed from the parent entity's work item type, so creating a verification case under different sources produces different default titles.

### Calculated Column Values

The `formula` property computes a value from other properties on the current entity:

```yaml theme={null}
columns:
  totalPrice:
    formula: "() => context.item.quantity * context.item.unitPrice"
```

<Warning title="Formula Persists Data">
  The `formula` property writes the calculated value back to the data source. Use `render` if you only need to change how a value is displayed without modifying the underlying data.
</Warning>

### Custom Cell Rendering

The `render` property and named `renderers` produce custom HTML output:

```yaml theme={null}
renderers:
  linkedItems: "() => context.value.map((item) => `<b>${item.name}</b>`).join(', ')"
```

### Display Override for Navigation Properties

When the standard `display: titleOrName` / `display: title` shorthands are not sufficient, the `display` property accepts a dynamic expression that overrides what is shown for a linked entity column:

```yaml theme={null}
columns:
  systemRequirement.document:
    display: "() => context.document.title"
```

### Conditional Formatting

Formatter expressions use a simplified syntax without the `() =>` prefix. The expression is evaluated as a boolean condition:

```yaml theme={null}
formatters:
  criticalHighlight:
    expression: "context.item.Probability <= 99"
    style: warningStyle
```

<Note title="Formatter Syntax Difference">
  Formatter expressions do **not** start with `() =>`. They are evaluated directly as boolean conditions against the context object.
</Note>

## Context Expression Examples (Data Model)

### Filter by Source Document Component

Restrict linked items to the same document component as the source entity:

```yaml theme={null}
relationships:
  - from: DesignRequirement
    to: SystemRequirement
    back:
      name: designRequirements
      constraints:
        load:
          document:
            component: $context.source.document.component
```

When viewing a `SystemRequirement` from the "Braking" component, only `DesignRequirement` items from "Braking" documents are loaded.

### Filter by Source Document Identity

Restrict to the exact same document as the source entity:

```yaml theme={null}
constraints:
  load:
    document:
      moduleName: $context.source.document.moduleName
      moduleFolder: $context.source.document.moduleFolder
```

### Filter by Source Document Type

Restrict picker results to documents of the same type as the source entity's document:

```yaml theme={null}
constraints:
  pick:
    document:
      type: $context.source.document.type
```

## Quick Reference

| Goal                                   | Notation   | Example                                                          |
| -------------------------------------- | ---------- | ---------------------------------------------------------------- |
| Filter relationship by source document | `$context` | `component: $context.source.document.component`                  |
| Filter query by current document       | `() =>`    | `"==": "() => context.document.moduleName"`                      |
| Calculate column from other fields     | `() =>`    | `formula: "() => context.item.qty * context.item.price"`         |
| Render custom HTML in a cell           | `() =>`    | `render: "() => '<b>' + context.value + '</b>'"`                 |
| Display label for a linked entity      | shorthand  | `display: titleOrName`                                           |
| Set default value for new items        | `() =>`    | `entityFactory: { title: "() => context.source.type + '_VTC'" }` |
| Conditionally style a cell             | expression | `expression: "context.item.Risk > 50"`                           |

## Related Pages

* [EntityQuery](/powersheet/reference/query-api/entity-query) --- query construction and execution
* [Predicates](/powersheet/reference/query-api/predicates) --- filtering operators for `where` clauses
* [Expand Clause](/powersheet/reference/query-api/expand-clause) --- loading related entities in queries
* [Document Filtering](/powersheet/reference/query-api/document-filtering) --- document-scoping mechanisms
* [Baseline and Revision Queries](/powersheet/reference/query-api/baseline-and-revision-queries) --- querying historical data
* [Dynamic Value Expressions Reference](/powersheet/reference/sheet-config/dynamic-expressions) --- complete dynamic expression syntax
* [Context Expressions Reference](/powersheet/reference/data-model/context-expressions) --- `$context` path reference for data models
* [Constraints](/powersheet/reference/data-model/constraints) --- constraint configuration including stages and operators
* [Columns](/powersheet/reference/sheet-config/columns) --- column-level configuration for `formula`, `render`, and `display`
* [Formatters](/powersheet/reference/sheet-config/formatters) --- conditional formatting with expression syntax

<LastReviewed date="2026-06-08" />
