# SQLite Quick Reference (Flynn)

Operational SQLite queries for fast debugging and cache management.

## Setup

```bash
DB=~/.local/share/flynn/sessions.db
SID='telegram:8367012007'   # change per session
```

## 1) DB Health / Introspection

```bash
sqlite3 "$DB" ".tables"
sqlite3 "$DB" ".schema"
```

## 2) Global Row Counts

```bash
sqlite3 "$DB" "SELECT 'messages',COUNT(*) FROM messages
UNION ALL SELECT 'session_config',COUNT(*) FROM session_config
UNION ALL SELECT 'tool_executions',COUNT(*) FROM tool_executions;"
```

## 3) Most Recent Active Sessions

```bash
sqlite3 "$DB" "SELECT session_id, datetime(MAX(created_at),'unixepoch','localtime') AS last_seen, COUNT(*) AS msg_count
FROM messages GROUP BY session_id ORDER BY MAX(created_at) DESC LIMIT 20;"
```

## 4) Recent Messages for One Session

```bash
sqlite3 "$DB" "SELECT id, role, datetime(created_at,'unixepoch','localtime') AS ts, substr(content,1,200)
FROM messages WHERE session_id='$SID' ORDER BY id DESC LIMIT 30;"
```

## 5) Search Message History by Text

```bash
sqlite3 "$DB" "SELECT session_id,id,role,datetime(created_at,'unixepoch','localtime')
FROM messages WHERE content LIKE '%audio.transcribe%' ORDER BY id DESC LIMIT 50;"
```

## 6) List Session Config Keys

```bash
sqlite3 "$DB" "SELECT key, length(value) FROM session_config WHERE session_id='$SID' ORDER BY key;"
```

## 7) Inspect Cached Audio Across Sessions

```bash
sqlite3 "$DB" "SELECT session_id, key, length(value) FROM session_config WHERE key='lastAudioAttachment';"
```

## 8) Clear One Session's Cached Audio

```bash
sqlite3 "$DB" "DELETE FROM session_config WHERE session_id='$SID' AND key='lastAudioAttachment';"
```

Verify:

```bash
sqlite3 "$DB" "SELECT session_id, key, length(value) FROM session_config WHERE key='lastAudioAttachment';"
```

## 9) Tool Success/Failure Summary

```bash
sqlite3 "$DB" "SELECT tool_name, SUM(success=1) AS ok, SUM(success=0) AS fail, COUNT(*) AS total
FROM tool_executions GROUP BY tool_name ORDER BY total DESC;"
```

## 10) Recent Tool Failures for One Session

```bash
sqlite3 "$DB" "SELECT id, tool_name, datetime(created_at,'unixepoch','localtime') AS ts
FROM tool_executions WHERE session_id='$SID' AND success=0 ORDER BY id DESC LIMIT 50;"
```

## 11) Pairing Approvals

```bash
sqlite3 "$DB" "SELECT channel, sender_id, datetime(approved_at,'unixepoch','localtime')
FROM pairing_approved ORDER BY approved_at DESC;"
```

## 12) Safety Backup Before Manual Edits

```bash
sqlite3 "$DB" ".backup '/tmp/flynn-sessions.backup.db'"
```

## Notes

- `/reset` in a chat clears that session's messages/config/tool rows, including `lastAudioAttachment`.
- Prefer deleting one key for one session over broad deletes.
