# Query production database

Run queries against the production qc_trace database. Uses `.prod.env` for credentials — never hardcode secrets.

**Auto-trigger**: Use this command whenever the user asks anything about production data, device status, org data, session counts, errors, or any database-related question — even if they don't explicitly type `/query`.

## Input

The user describes what they want in plain English, e.g.:
- `/query show all sessions for sagar-local`
- `/query how many messages per org`
- `/query delete all data for org zeeshan-test`
- `/query show devices that haven't been seen in 7 days`

If no argument: show a summary of orgs, session counts, and device counts.

## How to connect

```bash
source /Users/sagar/work/all-things-quickcall/trace/.prod.env
psql "$QC_TRACE_DSN" -c "<query>"
```

Never print or log the DSN or password. Always source `.prod.env` inline.

## Schema reference

The database has these tables (see `qc_trace/db/schema.sql` for full schema):

- **sessions** — one row per coding session. Has `org`, `device_id`, `device_name`, `source`, `repo_name`, `git_branch`, `user_email`, etc.
- **messages** — conversation messages. FK to `sessions(id)` with `ON DELETE CASCADE`.
- **token_usage** — token counts per message. FK to `messages(id)` with `ON DELETE CASCADE`.
- **tool_calls** — tool invocations per message. FK to `messages(id)` with `ON DELETE CASCADE`.
- **tool_results** — tool outputs per message. FK to `messages(id)` with `ON DELETE CASCADE`.
- **daemon_heartbeats** — daemon health per device. Has `org`, `device_id`, `status`, `recent_errors`, etc.
- **version_config** — key-value config (e.g., `latest_version`).
- **file_progress** — ingest tracking (internal).

Cascade hierarchy: deleting a session cascades to messages → token_usage, tool_calls, tool_results.

## Rules

### Read queries (SELECT)
- Run directly, no confirmation needed.
- Use `-t -A` flags for clean output, or default formatting for tables.

### Write queries (UPDATE, DELETE, INSERT)
1. **First**: run a SELECT to count affected rows.
2. **Then**: explain in plain simple English what will happen. Example:
   - "This will delete 7 sessions and all their messages (1,007), token usage (111), tool calls (194), and tool results (194) for the org 'zeeshan-test'."
   - "This will update 247 sessions, changing their org from 'local' to 'sagar-local'."
3. **Then**: ask the user for confirmation before executing.
4. **After**: run a verification query to confirm the operation succeeded.

### Safety
- Never run DROP TABLE, TRUNCATE, or schema-altering DDL without explicit user request.
- For DELETE operations, always use WHERE clauses — never delete without a filter.
- **ALL data-altering queries (UPDATE, DELETE, INSERT) require user confirmation — no exceptions, regardless of row count.**
- If the user's intent is ambiguous, ask for clarification before running anything.
