# Data source queries

> List what each data source's monitors read, and check a schema or payload change against it before you ship.

These endpoints tell whoever maintains a data source what Pulso depends on:

- For a SQL database source, the SQL its monitors and saved queries run, and the columns the monitors use. Run it in your database's CI to catch a migration that would break a monitor.
- For a webhook source, the payload fields its monitors use, so whoever sends the events can check a payload change.

Both need an [API key](https://pulso.run/docs/api/overview.md#api-keys) or an [OAuth](https://pulso.run/docs/api/oauth.md) connection with the permission. [List data sources](https://pulso.run/docs/api/data-source-queries.md#list-data-sources) gives each one's `queries_url`; its id is also in the address of the data source's page.

## List data sources

```http
GET /v1/data_sources
Authorization: Bearer <api key>
```

Needs the `data_sources:list` permission. Returns the account's data sources, ordered by name:

```json
{
  "data_sources": [
    {
      "id": "01JC2B7XQ1W2E3R4T5Y6U7I8OP",
      "name": "Payments",
      "type": "postgres",
      "queries_url": "https://api.pulso.run/v1/data_sources/01JC2B7XQ1W2E3R4T5Y6U7I8OP/queries"
    }
  ]
}
```

`type` is `postgres`, `mysql` (MySQL and MariaDB), `webhook` or `form`.

## Get a data source's queries

```http
GET /v1/data_sources/:data_source_id/queries
Authorization: Bearer <api key>
```

Needs the `data_sources:read_queries` permission.

### SQL database source

```json
{
  "data_source": { "id": "01JC2B…", "name": "Payments", "type": "postgres" },
  "exported_at": "2026-11-22T10:05:00Z",
  "queries_url": "https://api.pulso.run/v1/data_sources/01JC2B…/queries",
  "queries": [
    {
      "kind": "monitor",
      "id": "01JC3D…",
      "name": "Stuck payments",
      "active": true,
      "url": "https://app.pulso.run/accounts/…/monitors/01JC3D…",
      "sql": "SELECT id, customer_email FROM payments WHERE status = $1 AND amount > $2",
      "params": [
        { "key": "pending_status", "kind": "string" },
        { "key": "min_amount", "kind": "number" }
      ],
      "fields": [
        { "name": "id", "used_in": ["row_identifier"], "ambiguous": false },
        { "name": "customer_email", "used_in": ["message", "playbook"], "ambiguous": false }
      ]
    },
    {
      "kind": "saved_query",
      "id": "01JC4E…",
      "name": "Refunds by day",
      "url": "https://app.pulso.run/accounts/…",
      "sql": "SELECT day, sum(amount) AS refunded FROM refunds GROUP BY day",
      "params": [],
      "chart": {
        "type": "line", "x": "day", "y": ["refunded"], "series": null, "bucket": "week", "aggregate": "sum",
        "stacked": false, "percent": false, "cumulative": false, "horizontal": false, "labels": false, "log": false, "sparkline": false,
        "sort": null, "limit": null, "legend": null, "goal": null, "decimals": null, "prefix": null, "suffix": null, "palette": null
      }
    }
  ]
}
```

`exported_at` is when the response was made, and `queries_url` where to get it again. `queries` holds the source's monitors (`kind: "monitor"`) and saved queries (`kind: "saved_query"`). Archived monitors are left out.

As in the app, monitors come with their `sql` and `params` only for admins and operators, who edit them, and saved queries are only for the roles that can explore. For other members, monitors have just their `fields`.

| Field | Meaning |
|---|---|
| `active` | Whether the monitor is active. Monitors only. |
| `url` | The monitor, or the saved query in the explorer. |
| `sql` | The query. [Account variables](https://pulso.run/docs/concepts/variables-and-address-book.md#variables) are replaced by positional parameters (`$1`, `$2`, …), one per distinct variable. |
| `params` | One entry per parameter, in order: the variable's `key` and its `kind` (`string`, `number` or `boolean`). `kind` is `null` if the account doesn't define that variable. Values are never included. |
| `fields` | The result columns the monitor reads. Monitors only. |
| `chart` | How the explorer charts the saved query's rows, when it was saved as a chart: `type` (`line`, `bar`, `area`, `combo`, `scatter`, `pie`, `donut` or `number`), the `x` column, the `y` columns and how they `aggregate` (`sum`, `count`, `avg`, `min` or `max`), a `series` column that splits the first `y` into one line or bar per value, a time `bucket` (`day`, `week` or `month`) when `x` is a date, and the options as in the explorer: `stacked`, `percent`, `cumulative`, `horizontal`, `sort` (`desc` or `asc`), `limit`, `labels`, `log`, `legend` (`top`, `bottom`, `right` or `none`), `goal`, `decimals`, `prefix`, `suffix`, `sparkline` and `palette` (`colorblind`, `cool`, `warm`, `pastel` or `mono`). The [OpenAPI document](https://pulso.run/docs/api/overview.md) describes each. Saved queries only. |

Each entry in `fields` has:

- `name`: the column.
- `used_in`: where the monitor reads it: `filter`, `row_identifier` (its uniq by columns), `message` or `playbook`, including linked templates.
- `ambiguous`: `true` when the column is only referenced without the `signal.` prefix, as `{{column}}`. Such a name could also refer to the answer of a playbook step, so treat a missing column as a warning rather than an error.

### Webhook source

Monitors come without `sql` and `params`, and there are no saved queries. `fields` lists keys of the flattened payload, such as `customer.email`.

```json
{
  "data_source": { "id": "01JC5F…", "name": "Orders webhook", "type": "webhook" },
  "queries": [
    {
      "kind": "monitor",
      "id": "01JC6G…",
      "name": "Refund without reason",
      "active": true,
      "url": "https://app.pulso.run/accounts/…/monitors/01JC6G…",
      "fields": [
        { "name": "refund.reason", "used_in": ["filter"], "ambiguous": false }
      ]
    }
  ]
}
```

## Check a schema change in CI

Run `check-queries.sh`, below, in your database's CI after the migrations are applied, with `QUERIES_URL` set to the data source's `queries_url`. The script needs `curl`, `jq` and `psql`. A MySQL or MariaDB source exports the same queries (its `type` is `mysql`), but the script speaks PostgreSQL only.

```bash
QUERIES_URL=https://api.pulso.run/v1/data_sources/<id>/queries \
API_KEY=$API_KEY DATABASE_URL=$DATABASE_URL \
bash check-queries.sh
```

It prepares each query wrapped in `SELECT * FROM (…) AS q LIMIT 0`, inside a read-only transaction, so PostgreSQL resolves its tables, columns, functions and types without reading rows. Then it compares the result's columns with the monitor's `fields`. A field like `meta.customer.email` is satisfied by a `meta` column.

- A broken active monitor, or one missing a field, fails the check (exit code 1).
- A broken inactive monitor or saved query, or a missing `ambiguous` field, is printed as a warning.

```bash
#!/usr/bin/env bash
# Checks that the queries a data source's monitors and saved queries run still
# work against a database. Meant for that database's CI, after applying the
# migrations:
#
#   QUERIES_URL=https://<host>/v1/data_sources/<id>/queries \
#   API_KEY=<api key> DATABASE_URL=postgres://… ./check-queries.sh
#
# Each query is prepared and run with LIMIT 0, so Postgres resolves its
# tables, columns and types without reading rows. A monitor also needs the
# columns its filters, row identifiers, message and playbook read.
#
# A broken active monitor fails the check. A broken inactive monitor or saved
# query is a warning, as is a missing column that a template names without the
# signal. prefix, which may be a playbook step's data instead. Needs curl, jq
# and psql.
set -euo pipefail

: "${QUERIES_URL:?set QUERIES_URL to the queries endpoint of the data source}"
: "${API_KEY:?set API_KEY to an API key that can read the queries}"
: "${DATABASE_URL:?set DATABASE_URL to the database to check against}"

for tool in curl jq psql; do
  command -v "$tool" >/dev/null || { echo "check-queries: $tool is required" >&2; exit 2; }
done

export PGCONNECT_TIMEOUT="${PGCONNECT_TIMEOUT:-10}"
export PGOPTIONS="${PGOPTIONS:-} -c default_transaction_read_only=on"
psql "$DATABASE_URL" -X -q -c "SELECT 1" >/dev/null

queries=$(curl -fsS -H "Authorization: Bearer $API_KEY" "$QUERIES_URL")

# The type a parameter is declared with when Postgres can't infer it from the
# query (SELECT $1): the kind of the account variable it stands for.
pg_type() {
  case "$1" in
    number) echo numeric ;;
    boolean) echo boolean ;;
    *) echo text ;;
  esac
}

# Prints the result's column names, tab-separated, or Postgres' error and
# fails. Wrapped in a subquery like the monitor's own run, which caps its rows.
describe() {
  local sql=$1 declaration="" arguments=""
  shift
  if [ $# -gt 0 ]; then
    declaration="($(IFS=,; echo "$*"))"
    arguments="($(printf 'NULL,%.0s' "$@" | sed 's/,$//'))"
  fi
  psql "$DATABASE_URL" -X -q -A -F $'\t' -P footer=off -v ON_ERROR_STOP=1 -c "
    PREPARE check_queries$declaration AS SELECT * FROM (
$sql
    ) AS q LIMIT 0;
    EXECUTE check_queries$arguments" 2>&1
}

checked=0 broken_monitors=0 warnings=0

# report <failure|warning> <message> [detail]
report() {
  if [ "$1" = failure ]; then
    broken_monitors=$((broken_monitors + 1))
    echo "FAIL    $2"
  else
    warnings=$((warnings + 1))
    echo "WARNING $2"
  fi
  if [ -n "${3:-}" ]; then sed 's/^/        /' <<<"$3"; fi
}

while IFS= read -r entry; do
  kind=$(jq -r .kind <<<"$entry")
  name=$(jq -r .name <<<"$entry")
  url=$(jq -r .url <<<"$entry")
  active=$(jq -r '.active // false' <<<"$entry")
  sql=$(jq -r '.sql // empty' <<<"$entry")
  # A monitor not set up yet has no query to check.
  [ -n "$sql" ] || continue

  if [ "$kind" = monitor ] && [ "$active" = true ]; then
    severity=failure label="monitor"
  elif [ "$kind" = monitor ]; then
    severity=warning label="inactive monitor"
  else
    severity=warning label="saved query"
  fi

  # Undeclared (unknown) parameters are inferred the way a quoted literal is,
  # which is what the variable becomes when the query runs.
  kinds=() types=()
  while IFS= read -r param_kind; do
    kinds+=("$param_kind")
    types+=(unknown)
  done < <(jq -r '.params[] | .kind // "string"' <<<"$entry")

  checked=$((checked + 1))
  while true; do
    if output=$(describe "$sql" ${types[@]+"${types[@]}"}); then
      break
    fi

    position=$(sed -n 's/.*could not determine data type of parameter \$\([0-9][0-9]*\).*/\1/p' <<<"$output" | head -n 1)
    if [ -n "$position" ] && [ "${types[position - 1]}" = unknown ]; then
      types[position - 1]=$(pg_type "${kinds[position - 1]}")
      continue
    fi

    report "$severity" "$label \"$name\" ($url)" "$output"
    continue 2
  done

  columns=()
  while IFS= read -r column; do
    columns+=("$column")
  done < <(head -n 1 <<<"$output" | tr '\t' '\n')

  # A field like customer.name may be a json column's key: its column is enough.
  missing="" ambiguous_missing=""
  while IFS=$'\t' read -r field ambiguous used_in; do
    found=false
    for column in ${columns[@]+"${columns[@]}"}; do
      case "$field" in
        "$column" | "$column".*) found=true; break ;;
      esac
    done
    [ "$found" = true ] && continue

    if [ "$ambiguous" = true ]; then
      ambiguous_missing+="column \"$field\" not in the result (used in $used_in, as {{$field}})"$'\n'
    else
      missing+="column \"$field\" not in the result (used in $used_in)"$'\n'
    fi
  done < <(jq -r '.fields[]? | [ .name, .ambiguous, (.used_in | join(", ")) ] | @tsv' <<<"$entry")

  if [ -n "$missing" ]; then
    report "$severity" "$label \"$name\" ($url)" "${missing%$'\n'}"
  fi
  if [ -n "$ambiguous_missing" ]; then
    report warning "$label \"$name\" ($url)" "${ambiguous_missing%$'\n'}"
  fi
done < <(jq -c '.queries[]' <<<"$queries")

echo "$checked queries checked: $broken_monitors broken active monitors, $warnings warnings"
[ "$broken_monitors" -eq 0 ]
```

## Read a database's schema

```bash
curl https://api.pulso.run/v1/data_sources/01M7ZJ3D…/schema \
  -H "Authorization: Bearer ak_..."
```

Needs `data_sources:query` and an admin or operator. For a SQL database source, `{ "dialect": "postgres", "tables": [ … ] }`, with `mysql` as the dialect for MySQL and MariaDB: the tables and views its user can read (on MySQL, each database is a schema), each with `schema`, `name`, `kind`, `estimated_rows` and `columns` (`name`, `type`, `nullable`, `primary_key`). A successful read is cached for an hour, as in the editor; one that fails returns `"tables": []` and isn't cached. It lists up to 500 tables, with up to 200 columns each. A webhook or form source answers `403`.

## Run a query

```bash
curl -X POST https://api.pulso.run/v1/data_sources/01M7ZJ3D…/query \
  -H "Authorization: Bearer ak_..." -H "Content-Type: application/json" \
  -d '{"sql": "select status, count(*) from orders group by 1", "limit": 50}'
```

Needs `data_sources:query` and an admin or operator, as the data source's **Explore** tab. The query runs in a read-only transaction with a 15-second timeout, one statement only, and `{{vars.key}}` takes the account's [variables](https://pulso.run/docs/concepts/variables-and-address-book.md). `filters` fills a saved query's [report filters](https://pulso.run/docs/concepts/signals.md#saved-query-charts), `{{filters.key}}`: `from` and `to` are dates, the last 6 months by default, and a key left out is `NULL`. `limit` caps the rows, 50 by default and 200 at most:

```json
{ "columns": ["status", "count"], "rows": [ { "status": "paid", "count": 1204 } ], "truncated": false }
```

`truncated` is `true` when the query had more rows. A query that fails answers `409` with the database's error. Each query is recorded in the audit log.

## Save a query

```http
POST /v1/saved_queries
Authorization: Bearer <api key>
Content-Type: application/json

{
  "data_source_id": "01JC2B7XQ1W2E3R4T5Y6U7I8OP",
  "name": "Refunds by day",
  "sql": "SELECT day, sum(amount) AS refunded FROM refunds WHERE amount > {{vars.min_amount}} GROUP BY day",
  "chart": { "type": "line", "x": "day", "y": ["refunded"], "bucket": "week" }
}
```

Saves a query of a SQL data source, as **Save** in the explorer does, so the account can open it there again. Needs the `data_sources:write` permission and an admin or operator. `name`, `data_source_id` and `sql` are required; `description` and `chart` are optional. `sql` takes [account variables](https://pulso.run/docs/concepts/variables-and-address-book.md#variables) as `{{vars.key}}`. Try it first with [`run_query`](https://pulso.run/docs/api/data-source-queries.md#run-a-query).

`chart` has the settings [listed above](https://pulso.run/docs/api/data-source-queries.md#sql-database-source); only `type` is required. A setting it doesn't know, or a value it doesn't take, is refused. Leave `chart` out, or send `null`, to show the rows as a table.

Answers `201` with the saved query:

```json
{
  "saved_query": {
    "id": "01JC4E…",
    "name": "Refunds by day",
    "description": null,
    "data_source_id": "01JC2B7XQ1W2E3R4T5Y6U7I8OP",
    "sql": "SELECT day, sum(amount) AS refunded FROM refunds WHERE amount > {{vars.min_amount}} GROUP BY day",
    "chart": {
      "type": "line", "x": "day", "y": ["refunded"], "series": null, "bucket": "week", "aggregate": "sum",
      "stacked": false, "percent": false, "cumulative": false, "horizontal": false, "labels": false, "log": false, "sparkline": false,
      "sort": null, "limit": null, "legend": null, "goal": null, "decimals": null, "prefix": null, "suffix": null, "palette": null
    },
    "updated_at": "2026-11-22T10:05:00Z",
    "url": "https://app.pulso.run/accounts/…"
  }
}
```

## Change a saved query

```http
PATCH /v1/saved_queries/:id
Authorization: Bearer <api key>
Content-Type: application/json

{ "chart": { "type": "bar", "x": "day", "y": ["refunded"], "stacked": true } }
```

Only the fields sent change. `chart` replaces the whole chart, and `null` shows the rows as a table again. The [queries](https://pulso.run/docs/api/data-source-queries.md#sql-database-source) list each saved query's `id`, with its variables as `$1`, `$2`…; when you change `sql`, write them as `{{vars.key}}`. Answers with the saved query, as when saving it.
