Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions cmd/sql-tapd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ func main() {
nplus1Threshold := fs.Int("nplus1-threshold", 5, "N+1 detection threshold (0 to disable)")
nplus1Window := fs.Duration("nplus1-window", time.Second, "N+1 detection time window")
nplus1Cooldown := fs.Duration("nplus1-cooldown", 10*time.Second, "N+1 alert cooldown per query template")
slowThreshold := fs.Duration("slow-threshold", 100*time.Millisecond, "slow query threshold (0 to disable)")
showVersion := fs.Bool("version", false, "show version and exit")

_ = fs.Parse(os.Args[1:])
Expand All @@ -62,7 +63,7 @@ func main() {

err := run(
*driver, *listen, *upstream, *grpcAddr, *dsnEnv, *httpAddr,
*nplus1Threshold, *nplus1Window, *nplus1Cooldown,
*nplus1Threshold, *nplus1Window, *nplus1Cooldown, *slowThreshold,
)
if err != nil {
log.Fatal(err)
Expand All @@ -71,7 +72,7 @@ func main() {

func run(
driver, listen, upstream, grpcAddr, dsnEnv, httpAddr string,
nplus1Threshold int, nplus1Window, nplus1Cooldown time.Duration,
nplus1Threshold int, nplus1Window, nplus1Cooldown, slowThreshold time.Duration,
) error {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
Expand Down Expand Up @@ -155,6 +156,10 @@ func run(
nplus1Threshold, nplus1Window, nplus1Cooldown)
}

if slowThreshold > 0 {
log.Printf("slow query detection enabled (threshold=%s)", slowThreshold)
}

go func() {
for ev := range p.Events() {
if ev.Query != "" {
Expand All @@ -168,6 +173,9 @@ func run(
r.Alert.Query, r.Alert.Count, nplus1Window)
}
}
if slowThreshold > 0 && ev.Duration >= slowThreshold {
ev.SlowQuery = true
}
b.Publish(ev)
}
}()
Expand Down
9 changes: 9 additions & 0 deletions example/postgres/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ func run() error {
if i%3 == 0 {
doNPlus1(ctx, db, i)
}
// Occasionally simulate slow query.
if i%5 == 0 {
doSlowQuery(ctx, db)
}

select {
case <-ctx.Done():
Expand Down Expand Up @@ -207,6 +211,11 @@ func doNPlus1(ctx context.Context, db *sql.DB, i int) {
fmt.Printf("[%d] N+1 simulation done (10 individual SELECTs)\n", i)
}

func doSlowQuery(ctx context.Context, db *sql.DB) {
_, _ = db.ExecContext(ctx, "SELECT pg_sleep(0.15)")
fmt.Println("slow query simulation done (150ms sleep)")
}

func doLongQuery(ctx context.Context, db *sql.DB, i int) {
var dummy int
_ = db.QueryRowContext(ctx, `
Expand Down
14 changes: 12 additions & 2 deletions gen/tap/v1/tap.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions proto/tap/v1/tap.proto
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ message QueryEvent {
string tx_id = 9;
bool n_plus_1 = 10;
string normalized_query = 11;
bool slow_query = 12;
}

message WatchRequest {}
Expand Down
1 change: 1 addition & 0 deletions proxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ type Event struct {
Error string
TxID string
NPlus1 bool
SlowQuery bool
NormalizedQuery string
}

Expand Down
1 change: 1 addition & 0 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ func eventToProto(ev proxy.Event) *tapv1.QueryEvent {
Error: sanitizeUTF8(ev.Error),
TxId: ev.TxID,
NPlus_1: ev.NPlus1,
SlowQuery: ev.SlowQuery,
Copy link

Copilot AI Feb 21, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The SlowQuery field is added to the Event struct, but there are no tests verifying that this field is properly serialized in the gRPC Watch stream. Existing tests in server_test.go only verify basic fields like ID, Query, and Op. Consider adding a test case that publishes an Event with SlowQuery set to true and verifies it's correctly transmitted through the gRPC stream.

Copilot uses AI. Check for mistakes.
NormalizedQuery: sanitizeUTF8(ev.NormalizedQuery),
}
}
Expand Down
4 changes: 4 additions & 0 deletions tui/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ func eventStatus(ev *tapv1.QueryEvent) string {
return lipgloss.NewStyle().
Foreground(lipgloss.Color("3")).Render("N+1")
}
if ev.GetSlowQuery() {
return lipgloss.NewStyle().
Foreground(lipgloss.Color("5")).Render("SLOW")
}
return ""
}

Expand Down
8 changes: 6 additions & 2 deletions tui/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,12 +173,16 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case eventMsg:
m.events = append(m.events, msg.Event)

if msg.Event.GetNPlus_1() {
if msg.Event.GetNPlus_1() || msg.Event.GetSlowQuery() {
q := msg.Event.GetQuery()
if len(q) > 60 {
q = q[:57] + "..."
}
m, alertCmd := m.showAlert("N+1 detected: " + q)
label := "N+1 detected: "
if msg.Event.GetSlowQuery() && !msg.Event.GetNPlus_1() {
label = "Slow query: "
}
m, alertCmd := m.showAlert(label + q)
if m.view != viewList {
return m, tea.Batch(alertCmd, recvEvent(m.stream))
}
Expand Down
7 changes: 5 additions & 2 deletions web/static/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -200,15 +200,16 @@ function renderTable() {
const fragment = document.createDocumentFragment();
for (const {ev, idx} of filtered) {
const tr = document.createElement('tr');
tr.className = 'row' + (idx === selectedIdx ? ' selected' : '') + (ev.error ? ' has-error' : '') + (ev.n_plus_1 ? ' n-plus-1' : '');
tr.className = 'row' + (idx === selectedIdx ? ' selected' : '') + (ev.error ? ' has-error' : '') + (ev.n_plus_1 ? ' n-plus-1' : '') + (ev.slow_query ? ' slow-query' : '');
Copy link

Copilot AI Feb 21, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The row className concatenation applies all matching classes simultaneously (has-error, n-plus-1, slow-query), which can cause CSS conflicts since all three color rules have the same specificity. When multiple classes are present, the last one defined in CSS (slow-query) will take precedence due to CSS cascade rules, potentially hiding more critical issues. Consider applying only the highest-priority class based on the same logic used for the status text (error > n_plus_1 > slow_query).

Suggested change
tr.className = 'row' + (idx === selectedIdx ? ' selected' : '') + (ev.error ? ' has-error' : '') + (ev.n_plus_1 ? ' n-plus-1' : '') + (ev.slow_query ? ' slow-query' : '');
tr.className = 'row' + (idx === selectedIdx ? ' selected' : '') + (ev.error ? ' has-error' : ev.n_plus_1 ? ' n-plus-1' : ev.slow_query ? ' slow-query' : '');

Copilot uses AI. Check for mistakes.
tr.dataset.idx = idx;
tr.onclick = () => selectRow(idx);
const status = ev.error ? 'E' : ev.n_plus_1 ? 'N+1' : ev.slow_query ? 'SLOW' : '';
tr.innerHTML =
`<td class="col-time">${escapeHTML(fmtTime(ev.start_time))}</td>` +
`<td class="col-op">${escapeHTML(ev.op)}</td>` +
`<td class="col-query">${highlightSQL(ev.query)}</td>` +
`<td class="col-dur">${escapeHTML(fmtDur(ev.duration_ms))}</td>` +
`<td class="col-err">${ev.error ? 'E' : ev.n_plus_1 ? 'N+1' : ''}</td>`;
`<td class="col-err">${status}</td>`;
fragment.appendChild(tr);
}
tbody.replaceChildren(fragment);
Expand Down Expand Up @@ -453,6 +454,8 @@ function connectSSE() {
events.push(ev);
if (ev.n_plus_1) {
showToast('N+1 detected: ' + (ev.query || '').substring(0, 80));
} else if (ev.slow_query) {
showToast('Slow query: ' + (ev.query || '').substring(0, 80));
}
render();
};
Expand Down
6 changes: 4 additions & 2 deletions web/static/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ tr.row:hover { background: #2a2d2e; }
tr.row.selected { background: #094771; }
tr.row.has-error td { color: #f44747; }
tr.row.n-plus-1 td { color: #e5c07b; }
tr.row.slow-query td { color: #c678dd; }

.col-time { width: 110px; }
.col-op { width: 80px; }
Expand Down Expand Up @@ -179,9 +180,10 @@ tr.row.n-plus-1 td { color: #e5c07b; }
.sql-num { color: #b5cea8; }
.sql-param { color: #9cdcfe; }

/* Disable highlight colors in error / N+1 rows to keep monochrome look */
/* Disable highlight colors in error / N+1 / slow rows to keep monochrome look */
tr.row.has-error .col-query span,
tr.row.n-plus-1 .col-query span { color: inherit; }
tr.row.n-plus-1 .col-query span,
tr.row.slow-query .col-query span { color: inherit; }

#toast {
position: fixed;
Expand Down
2 changes: 2 additions & 0 deletions web/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ type eventJSON struct {
Error string `json:"error,omitempty"`
TxID string `json:"tx_id,omitempty"`
NPlus1 bool `json:"n_plus_1,omitempty"`
SlowQuery bool `json:"slow_query,omitempty"`
NormalizedQuery string `json:"normalized_query,omitempty"`
}

Expand All @@ -96,6 +97,7 @@ func eventToJSON(ev proxy.Event) eventJSON {
Error: ev.Error,
TxID: ev.TxID,
NPlus1: ev.NPlus1,
SlowQuery: ev.SlowQuery,
Copy link

Copilot AI Feb 21, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The SlowQuery field is added to the eventJSON struct, but there are no tests verifying that this field is properly serialized in SSE responses. Existing tests in web_test.go verify basic fields like ID, Op, Query, and DurationMs. Consider adding a test case that publishes an Event with SlowQuery set to true and verifies it's correctly transmitted in the JSON SSE stream.

Copilot uses AI. Check for mistakes.
NormalizedQuery: ev.NormalizedQuery,
}
}
Expand Down