# 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). The **Queries API** section of each data source shows the URL to call.

## List data sources

```http
GET /api/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://pulso.run/api/v1/data_sources/01JC2B7XQ1W2E3R4T5Y6U7I8OP/queries"
    }
  ]
}
```

`type` is `postgres`, `webhook` or `form`.

## Get a data source's queries

```http
GET /api/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://pulso.run/api/v1/data_sources/01JC2B…/queries",
  "queries": [
    {
      "kind": "monitor",
      "id": "01JC3D…",
      "name": "Stuck payments",
      "active": true,
      "url": "https://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://pulso.run/accounts/…",
      "sql": "SELECT …",
      "params": []
    }
  ]
}
```

`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. |

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://pulso.run/accounts/…/monitors/01JC6G…",
      "fields": [
        { "name": "refund.reason", "used_in": ["filter"], "ambiguous": false }
      ]
    }
  ]
}
```

## Check a schema change in CI

For a PostgreSQL source, the **Queries API** section of the data source shows a ready-made command for your database's CI. A MySQL or MariaDB source exports the same queries (its `type` is `mysql`), but the script below speaks PostgreSQL only. It runs `check-queries.sh`, below, after the migrations are applied. The script needs `curl`, `jq` and `psql`:

```bash
QUERIES_URL=https://pulso.run/api/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>/api/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://pulso.run/api/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`). It's cached for an hour, as in the editor.

## Run a query

```bash
curl -X POST https://pulso.run/api/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 at a time, and `{{vars.key}}` takes the account's [variables](https://pulso.run/docs/concepts/variables-and-address-book.md). `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.
