---
name: opa-scripts
description: Write, review and fix scripts and dashboards for OPA-PA, the metadata-driven database performance analyzer (Oracle and PostgreSQL). Use when the user asks for an OPA-PA script, a `.sql` file with a `/*--- … ---*/` YAML header, an OPA-PA dashboard (`kind: container` YAML), drill-down between OPA-PA scripts, or a fix for an OPA-PA Diagnostics message.
---

# Writing OPA-PA scripts and dashboards

OPA-PA builds its whole UI from files: a `.sql` file (one SQL statement or several steps) with an optional YAML header is a catalog item that shows a table, tree, chart, text or document; a `.yaml` file with `kind: container` is a dashboard. You write these files; OPA-PA loads them from the user's scripts folder and reloads them when they change.

## Rules that are never broken

1. **Values are bind variables.** Use `:name` binds for every value. Never ask for or build SQL text from input values (no substitution, no string concatenation of inputs into SQL). A procedural block that must build dynamic SQL converts typed (`integer`) inputs explicitly with `to_char(:x)`.
2. **One engine per file.** Write Oracle SQL (19c+) for `scripts/oracle`, PostgreSQL SQL (13+) for `scripts/postgresql`. Ask which engine if it is not clear.
3. **Read-only by default.** A script that changes anything is `kind: action` with `safety: write` or `dangerous`, and `transaction` stated. Never make a query that modifies data.
4. **Licences (Oracle).** Any script reading ASH (`gv$active_session_history`, `v$active_session_history`), AWR (`dba_hist_*`, `dbms_workload_repository`) needs `requires: { licenses: [diagnostics] }`; SQL Monitor (`gv$sql_monitor`, `dbms_sql_monitor`, `dbms_sqltune`) needs `[tuning]`. Do not use these views in a script without them.
5. **Valid YAML, valid SQL.** The header is YAML inside `/*---` and `---*/` at the very start of the file. Quote strings that contain `:`, `#`, `{`, `[`, or start with `*`, `&`, `!`. Do not end a single SQL statement with `;` (a PL/SQL block ends with `end;`).
6. **Every declared input must appear as a bind** in a query or action (`:name`), and every bind should be declared. No `:1`, no `?` placeholders.

## File layout

```sql
/*---
id: area.name                 # lowercase [a-z0-9_.-]; default: path with / -> .
title: Human Title
category: Folder/Subfolder    # catalog path
description: One or two sentences: what it shows and when to use it.
inputs: [...]
ranges: [...]
columns: {...}
display: {...}
refresh: {...}
---*/
select ...
```

Header fields: `id`, `title`, `category`, `description`, `kind` (query | action | container | connection-init | sampler), `inputs`, `ranges`, `columns`, `steps`, `display`, `navigation`, `refresh`, `safety` (read | write | dangerous), `transaction` (rollback | commit | none), `confirm`, `requires`, `unless`, `source` (database | local), `timeout`, `maxRows`, `version`, `ai`, `client`, `layout` (containers). Durations: `500ms`, `5s`, `1m`, `2h`, `7d`.

## Inputs

```yaml
inputs:
  - { name: sql_id, semantic: oracle.sql.id, type: string, label: SQL ID }            # identity: must come from a selection
  - { name: t_from, semantic: perf.time.range.start, type: timestamp, default: now-15m, label: From }
  - { name: t_to,   semantic: perf.time.range.end,   type: timestamp, default: now,     label: To }
  - { name: wait_class, semantic: oracle.wait.class, required: false, label: Wait class }   # optional filter
  - { name: top_n, type: integer, default: 20, label: Top N }                           # local parameter
ranges:
  - { from: t_from, to: t_to, label: Period, presets: [5m, 15m, 1h, 1d] }
```

- Types: `string`, `integer`, `number`, `date`, `timestamp`, `boolean`, `enum` (+ `choices`).
- Required unless `default` or `required: false`. Optional filters: `(:x is null or col = :x)` (PostgreSQL: `(:x::text is null or col = :x)`).
- Roles: `semantic` + no default = identity (filled from the clicked row; the script is offered for drill-down only when it is available); `semantic` + default = contextual (from context, else default); no `semantic` = local (default or typed). `fromContext: false` keeps the default.
- Time defaults: `now`, `now-15m`, `now-7d/d` (truncate: `/d`, `/h`, `/m`, `/w`), absolute `2026-10-29 10:00`. `now` is the database clock. `precision: day` for date-only pickers.
- For periods always use the keys `perf.time.range.start` / `perf.time.range.end` (chart selections fill them). Dashboard windows use `perf.time.window.start` / `.end`.
- `showWhen: { capabilities: [cdb_root] }` shows an input only where the connection has it.

## Columns and semantic keys

```yaml
columns:
  sql_id: oracle.sql.id
  elapsed_s: { label: "Elapsed, s", unit: s, format: "#,##0.00", width: 90 }
  parent_id: { hidden: true }
  row_id:    { key: true }            # row identity across refresh
  bind_value: { sensitive: true }     # never sent to AI providers
```

Units: `s ms us bytes percent count`. Semantic keys make drill-down work; reuse the pack's keys. Oracle: `oracle.sql.id`, `oracle.sql.child_number`, `oracle.sql.plan_hash_value`, `oracle.instance.number`, `oracle.session.sid`, `oracle.session.serial`, `oracle.container.id`, `oracle.wait.class`, `oracle.wait.event`, `oracle.object.owner`, `oracle.object.table`, `oracle.object.index`, `oracle.object.column`. PostgreSQL: `postgresql.backend.pid`, `postgresql.backend.start`, `postgresql.query.id`, `postgresql.database.name`, `postgresql.schema.name`, `postgresql.table.name`, `postgresql.wait.event_type`, `postgresql.wait.event`. Columns `sql_id`, `inst_id`, `sid`, `serial#` (Oracle) and `pid`, `queryid`, `datname`, `relname` (PostgreSQL) get keys automatically. If unsure of a key, tell the user to check the same column in a shipped script (Help → Open shipped scripts).

In-cell graphics from text values: `bar(42)`, `bar(42,100)`, `stacked-bar(CPU=12;User I/O=30)`, `stacked-bar({"CPU":12})`, `sparkline(3,5,,8)`, `sparkline([3,5,null,8])`. Decimal point `.` only (Oracle: `to_char(v,'TM9','NLS_NUMERIC_CHARACTERS=''.,''')` or `json_arrayagg`). Styling: `cell: { palette, colors, scale: column|row, style: line|area|bars, color }`.

## Display

```yaml
display:
  renderer: table          # table | record | chart | text | document
  alternatives: [record]
```

Tree (rows forming a hierarchy; the table gets ▾/▸ toggles):

```yaml
display:
  tree: "(parent_col1, parent_col2) > (key_col1, key_col2)"     # parent columns > the row's own key columns
  # or: tree: { key: [inst_id, sid], parent: [blocking_instance, blocking_session], column: chain, expanded: all|none|N }
```

A row with NULL parent columns, or a parent not in the result, is a root. Same number of columns on both sides. Order children in SQL (`order siblings by`). A node that can appear twice needs a unique key (e.g. a path string). Hide the parent columns.

Chart:

```yaml
display:
  renderer: chart
  alternatives: [table]
  chart:
    type: stacked-area     # line | area | stacked-area | bar | stacked-bar
    x: sample_time
    series: wait_class     # long format, with value:
    value: aas
    # values: [a, b]       # wide format instead of series/value
    yLabel: Average active sessions
    palette: wait-classes
    xRange: { from: t_from, to: t_to }
    fill: { step: 1m, missing: zero }          # for sparse time series
    selection:
      range: { from: perf.time.range.start, to: perf.time.range.end }
      click: bucket        # point | bucket (needs range) | none
      bucket: 1m
      default: { from: now-5m, to: now }
      follow: true
```

Text: `display: { renderer: text, text: { format: sql } }` for a one-column result (plans). Document: `display: { renderer: document, document: { column: report, mime: text/html, open: external } }` for a CLOB report.

## Steps (several statements)

```yaml
steps:
  - { name: setup, type: session, output: none }
  - { name: main,  type: sql, output: result, label: Result }
  # type: sql | block | session; output: result | messages | none; serverOutput: true; continueOnError: true
```

Body separated by full lines `--@step setup`, `--@step main`, names and order exactly as in `steps`, nothing but comments before the first marker. All steps run on one session. Never rely on `;` to split.

## Actions

```yaml
kind: action
safety: dangerous            # write for reversible changes, dangerous for destructive ones
transaction: none            # or commit
confirm: "Kill session {sid},{serial} on instance {inst_id}?"
steps:
  - { name: run, type: block, output: messages }
```

Inputs of actions are typed (`integer` for ids). Actions are confirmed with the statement and values, never run by double-click, never offered to AI.

## Requirements and variants

```yaml
requires: { version: "12.2", licenses: [diagnostics], capabilities: [pg_stat_statements] }
unless: { licenses: [diagnostics] }
```

Capabilities: PostgreSQL `pg_stat_statements`, `pg_wait_sampling`, `pg_stat_kcache`, `pgstattuple`; Oracle `cdb_root`, `pdb`. Variants share an `id` and differ by file name: `name.sql`, `name@11.2.sql`, `name+tuning.sql`, `name+pgstattuple.sql`; the suffix must agree with `requires`. Oracle multitenant: in a CDB root use `cdb_*` views and a `con_id` column/input with `showWhen: { capabilities: [cdb_root] }`.

## Navigation

Automatic: a script is offered for a selected row when all its identity inputs are filled and at least one semantic input comes from the row. Steer with:

```yaml
navigation:
  priority: 100
  hidden: false
  links:
    - { target: sql.details, label: SQL details, default: true }
    - { target: my.plan, map: { sql_id: oracle.sql.id } }
```

## Dashboards

```yaml
id: my.dashboard
title: My Dashboard
category: Dashboards
kind: container
inputs:
  - { name: t_from, semantic: perf.time.window.start, type: timestamp, default: now-60m }
  - { name: t_to,   semantic: perf.time.window.end,   type: timestamp, default: now }
ranges: [ { from: t_from, to: t_to, label: Window, presets: [15m, 1h, 6h, 1d] } ]
refresh: { interval: 15s, choices: [5s, 15s, 1m] }
layout:
  type: split              # split (orientation vertical|horizontal, ratios) | tabs | grid (columns: N) | view
  orientation: vertical
  ratios: [0.55, 0.45]
  children:
    - view: ash.activity_by_wait_class
      publishSelectionAs: picked
    - type: tabs
      contextFrom: picked
      children:
        - view: ash.top_sql_for_range
        - view: ash.top_sessions_for_range
```

Children are script ids (shipped or the user's). A consumer waits for its channel; chart `selection.default` gives an initial value. Container inputs have no binds; they reach children by semantic key.

## Client scripts and local samples

- `client: sqlplus | sqlcl | psql` (or a list): the body is a client script run in a terminal by "Run in…"; client commands allowed; inputs become client variables (`:name`, `&name`; psql `:name`); default safety `write`.
- `source: local`: SQLite SQL over OPA-PA's session samples. Tables: `session_samples` (one row per sampled session: `sample_id`, `sample_time`, `weight` + sampler columns; Oracle from `gv$session` e.g. `username`, `sql_id`, `event`, `wait_class`; PostgreSQL from `pg_stat_activity` e.g. `usename`, `query_id`, `wait_event_type`) and `session_samples_samples` (one row per sample taken). Averages: `sum(weight)` of rows / `sum(weight)` of samples taken. Times compare as `yyyy-MM-dd HH:mm:ss.fff` text; `strftime('%Y-%m-%d %H:%M:00', sample_time)` gives minutes. Upper-case result column names.

## When writing a script

1. Ask (or infer) the engine and version, the question the script answers, and whether a licence is available.
2. Start from the closest shipped script when one exists; keep its ids and keys.
3. Declare inputs for every bind; give periods `perf.time.range.*` keys and time-expression defaults; add `ranges`.
4. Map result columns to semantic keys so drill-down works; label and format numbers.
5. Choose the display: table by default, `tree` for hierarchies, `chart` for time series (with `xRange`, `fill`, `selection`).
6. Add `refresh` for live views (15 s for activity, off for reports).
7. Check: YAML parses, every input is a bind, no `;` at the end of a single statement, licences declared, actions confirmed.
8. Tell the user where to save it: `scripts/<engine>/<subfolder>/<name>.sql` in OPA-PA's settings folder (Windows `%APPDATA%\OPA`, macOS `~/Library/Application Support/OPA`, Linux `~/.config/opa`); problems show in OPA-PA's Diagnostics panel with file and line.

## Fixing a Diagnostics message

- "inputs entry without a matching bind": add `:name` to the SQL or remove the input.
- "step markers that don't match steps": `--@step` names and order must equal `steps`.
- "unknown field": a typo in a key (warning only).
- "invalid time expression": use `now[-Nunit][/unit]` with units `s m h d w`.
- "uses an object of a licence it does not require": add `requires: { licenses: [...] }` or use non-licensed views.
- "tree parent and key must have the same number of columns": match both lists.
