# Watch a MySQL query

The general method "scheduled query → ingest" for a count kept in MySQL: Amazon RDS or Aurora MySQL, Google Cloud SQL for MySQL, PlanetScale, or a server of your own. A cron job or a CI schedule you run counts with one query (the `mysql` client) and sends the result to CountWatch; CountWatch never connects to your database and never holds its password. Needs the `mysql` client and `curl`, MySQL 8.0 or later (recursive CTEs, `JSON_ARRAYAGG`), a database user that can only read the table, and a write key. The example counts paid orders in `orders`; replace the table, its time column `created_at` and the `status` filter. An index on the time column keeps the query cheap. This query runs in CI on a real MySQL 8. MariaDB is not run in CI and its SQL differs (it has no `cte_max_recursion_depth` and no `cast(… as json)`): adapt the two queries there.

## 1. A read-only user (once)

The person runs this as an administrator, in the database that holds the table, and keeps the password for the scheduler's secrets:

```sql
create user 'countwatch_reader'@'%' identified by '<a new password>';
grant select on orders to 'countwatch_reader'@'%';
```

The scheduler's secrets are `MYSQL_HOST`, `MYSQL_USER` (`countwatch_reader`), `MYSQL_PWD` (its password; the `mysql` client reads it from the environment, so it never appears in a command) and `MYSQL_DATABASE`. On PlanetScale, make a read-only password in its dashboard instead. The scheduler must reach the database: a CI schedule needs a database open to the internet over TLS (add `--ssl-mode=REQUIRED` to the `mysql` call); for one in a private network, run cron on a machine inside it.

## 2. The query

Save as `countwatch.sql`:

```sql
set time_zone = '+00:00';
with recursive span as (
  select unix_timestamp() div 300 * 300 as until),
windows as (
  -- Every 5-minute window of the last 2 hours, as its start in Unix seconds.
  select until - 7200 as b from span
  union all
  select w.b + 300 from windows w, span where w.b + 300 < span.until),
counted as (
  -- One pass over the rows: each paid order into its 5-minute window.
  select unix_timestamp(o.created_at) div 300 * 300 as b, count(*) as n
  from orders o, span
  where o.created_at >= from_unixtime(span.until - 7200) and o.created_at < from_unixtime(span.until) and o.status = 'paid'
  group by 1)
select json_object('recipe', 'mysql', 'points', json_arrayagg(json_object(
  'metric', 'orders',
  'ts', date_format(from_unixtime(w.b), '%Y-%m-%dT%H:%i:%sZ'),
  'set', coalesce(c.n, 0))))
from windows w left join counted c on c.b = w.b;
```

- **Every 5-minute window, zeros included.** The recursive CTE `windows` lists all 24 windows and an empty one is `0`, so the watch (mode `explicit`) can tell "no orders" from "the job stopped" (the no-data alert).
- **UTC.** The first line sets this session's time zone to UTC, and each window is counted in Unix seconds (300 is 5 minutes, 7200 is 2 hours), so each 5-minute window's start is written in UTC whatever the server's time zone. A `TIMESTAMP` column is read correctly as it is. A `DATETIME` column has no time zone: the query reads it as UTC, so if yours holds local times, write `convert_tz(o.created_at, 'Europe/Berlin', '+00:00')` (your zone) for `o.created_at`.
- **The last 2 hours, complete 5-minute windows only.** Each point `set`s its 5-minute window, so the overlap between runs only rewrites the same totals, and rows that arrive late are picked up by the next run.

## 3. Send it on a schedule

Save as `countwatch.sh` (bash):

```sh
# For a scheduler or a person at a terminal, never an agent's shell: it holds a source secret and calls CountWatch.
( # a subshell: pasted into a terminal, a failure stops only this block
set -euo pipefail
# A failed query stops here (nothing is sent), and the scheduler sees the error.
body=$(mysql --host="$MYSQL_HOST" --user="$MYSQL_USER" --batch --raw --skip-column-names "$MYSQL_DATABASE" < countwatch.sql)
curl -sS --fail-with-body -X POST https://countwatch.com/v1/ingest -H "Authorization: Bearer $COUNTWATCH_API_KEY" -H "Content-Type: application/json" --data-binary "$body"
)
```

Schedule it every 5 minutes (crontab `*/5 * * * *`), with a scheduler that lives as long as the database (cron on a server, a CI schedule), the four `MYSQL_` values and `COUNTWATCH_API_KEY` in its secrets, and start its first run there (for a CI schedule, `gh workflow run`), or a person runs `bash countwatch.sh` once: the first send creates the watch, or goes to the watch you made first (create_watch). An agent writes these files and the schedule, and never runs them in its own shell.

## 4. Import 89 days (once, right after the first send, where the send runs)

Save as `countwatch-import.sql`:

```sql
set time_zone = '+00:00';
set cte_max_recursion_depth = 30000;
set group_concat_max_len = 1000000;
with recursive span as (
  select unix_timestamp() div 300 * 300 - 7200 as until),
windows as (
  select until - 7689600 as b from span
  union all
  select w.b + 300 from windows w, span where w.b + 300 < span.until),
counted as (
  select unix_timestamp(o.created_at) div 300 * 300 as b, count(*) as n
  from orders o, span
  where o.created_at >= from_unixtime(span.until - 7689600) and o.created_at < from_unixtime(span.until) and o.status = 'paid'
  group by 1)
select json_object('recipe', 'mysql', 'watches', json_array(json_object(
  'metric', 'orders', 'resolution', '5m',
  'start', date_format(from_unixtime(min(w.b)), '%Y-%m-%dT%H:%i:%sZ'),
  'counts', cast(concat('[', group_concat(coalesce(c.n, 0) order by w.b separator ','), ']') as json))))
from windows w left join counted c on c.b = w.b;
```

```sh
# For a scheduler or a person at a terminal, never an agent's shell: it holds a source secret and calls CountWatch.
( # a subshell: pasted into a terminal, a failure stops only this block
set -euo pipefail
body=$(mysql --host="$MYSQL_HOST" --user="$MYSQL_USER" --batch --raw --skip-column-names "$MYSQL_DATABASE" < countwatch-import.sql)
curl -sS --fail-with-body -X POST https://countwatch.com/v1/import -H "Authorization: Bearer $COUNTWATCH_API_KEY" -H "Content-Type: application/json" --data-binary "$body"
)
```

The import is real 5-minute history (25,632 five-minute windows; 89 days are 7,689,600 seconds), zeros included, and ends where the scheduled sends begin (2 hours back), so it never replaces a 5-minute window the sends own. A recursive CTE stops at 1,000 rows unless `cte_max_recursion_depth` is raised, and `group_concat` cuts its result at 1,024 characters unless `group_concat_max_len` is: the file's second and third lines raise both for this session only. `group_concat` keeps the counts in window order, which `JSON_ARRAYAGG` does not promise. It answers `202` and an `import_id`.

## Check it works

1. **Data arrives.** `check_setup` (or `curl -s https://countwatch.com/v1/status -H "Authorization: Bearer $COUNTWATCH_API_KEY"`): the `orders` watch shows `last_request_at`, and `missing_buckets_24h` stays `0` (explicit watches). Do what `next_actions` says.
2. **History is in.** `GET /v1/imports/{import_id}` shows `status: done` and, with an admin key (or MCP `read {"action": "import_status", "id": "<import_id>"}`), the rules chosen for `orders` and the alerts they would have raised; a write key sees the status only. (Skipped the import? The watch learns from live data; starter rules apply meanwhile.)
3. **An alert reaches you.** A new account emails alerts to the person's sign-in address from sign-up; the person turns email alerts on or off in the dashboard (Destinations (Connect), https://countwatch.com/dashboard/connections?tab=destinations), or you add a webhook (`manage create_destination`, then `verify_destination`; the endpoint answers the challenge, see https://countwatch.com/agent). A write key cannot read alerts: read them with MCP `alerts`, or with `GET /v1/alerts` and an admin key. Then `manage {"action": "send_test_alert"}`: every active destination but email receives a test alert (`test: true`) within a few minutes; a confirmed email address needs no test. Real alerts go only where the watch's group chose (Alerts go to, or `manage update_group` with `destination_ids`; a new account's groups choose the sign-in email); with none chosen they stay in the app.
