|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + "strings" |
| 9 | + |
| 10 | + "github.com/boringsql/qshape" |
| 11 | + "github.com/jackc/pgx/v5" |
| 12 | + "github.com/spf13/cobra" |
| 13 | +) |
| 14 | + |
| 15 | +func captureCmd() *cobra.Command { |
| 16 | + var ( |
| 17 | + minCalls int64 |
| 18 | + limit int |
| 19 | + database string |
| 20 | + ) |
| 21 | + cmd := &cobra.Command{ |
| 22 | + Use: "capture <conn-string>", |
| 23 | + Short: "Fetch pg_stat_statements (with timing) from a live PG and cluster it", |
| 24 | + Long: `Connect to a PostgreSQL node, read pg_stat_statements directly, |
| 25 | +and emit JSON clusters on stdout. |
| 26 | +
|
| 27 | +Requires the pg_stat_statements extension to be loaded and created |
| 28 | +in the target database. Requires PostgreSQL 13+ for the *_exec_time |
| 29 | +columns; older releases use the legacy total_time naming and are not |
| 30 | +supported. |
| 31 | +
|
| 32 | +Connection string accepts libpq URLs (postgres://user:pass@host/db) |
| 33 | +or keyword/value form (host=... user=... dbname=...).`, |
| 34 | + Args: cobra.ExactArgs(1), |
| 35 | + RunE: func(_ *cobra.Command, args []string) error { |
| 36 | + return runCapture(args[0], minCalls, limit, database) |
| 37 | + }, |
| 38 | + } |
| 39 | + cmd.Flags().Int64Var(&minCalls, "min-calls", 0, "exclude queries with calls <= this value") |
| 40 | + cmd.Flags().IntVar(&limit, "limit", 0, "limit to top N by total_exec_time (0 = no limit)") |
| 41 | + cmd.Flags().StringVar(&database, "database", "", "filter to a specific database name (default: all)") |
| 42 | + return cmd |
| 43 | +} |
| 44 | + |
| 45 | +func runCapture(connStr string, minCalls int64, limit int, database string) error { |
| 46 | + ctx := context.Background() |
| 47 | + conn, err := pgx.Connect(ctx, connStr) |
| 48 | + if err != nil { |
| 49 | + return fmt.Errorf("connect: %w", err) |
| 50 | + } |
| 51 | + defer conn.Close(ctx) |
| 52 | + |
| 53 | + var sb strings.Builder |
| 54 | + sb.WriteString(`SELECT s.queryid, s.calls, s.query, |
| 55 | + s.total_exec_time, s.mean_exec_time, s.stddev_exec_time, s.rows |
| 56 | +FROM pg_stat_statements s`) |
| 57 | + args := []any{} |
| 58 | + where := []string{} |
| 59 | + if database != "" { |
| 60 | + sb.WriteString("\nJOIN pg_database d ON d.oid = s.dbid") |
| 61 | + where = append(where, fmt.Sprintf("d.datname = $%d", len(args)+1)) |
| 62 | + args = append(args, database) |
| 63 | + } |
| 64 | + where = append(where, fmt.Sprintf("s.calls > $%d", len(args)+1)) |
| 65 | + args = append(args, minCalls) |
| 66 | + sb.WriteString("\nWHERE ") |
| 67 | + sb.WriteString(strings.Join(where, " AND ")) |
| 68 | + sb.WriteString("\nORDER BY s.total_exec_time DESC") |
| 69 | + if limit > 0 { |
| 70 | + sb.WriteString(fmt.Sprintf("\nLIMIT %d", limit)) |
| 71 | + } |
| 72 | + |
| 73 | + rows, err := conn.Query(ctx, sb.String(), args...) |
| 74 | + if err != nil { |
| 75 | + return fmt.Errorf("query pg_stat_statements (extension installed? PG 13+?): %w", err) |
| 76 | + } |
| 77 | + defer rows.Close() |
| 78 | + |
| 79 | + var queries []qshape.Query |
| 80 | + for rows.Next() { |
| 81 | + var ( |
| 82 | + qid, calls, rowCount int64 |
| 83 | + raw string |
| 84 | + totalExec, meanExec, stddevExec float64 |
| 85 | + ) |
| 86 | + if err := rows.Scan(&qid, &calls, &raw, &totalExec, &meanExec, &stddevExec, &rowCount); err != nil { |
| 87 | + return fmt.Errorf("scan: %w", err) |
| 88 | + } |
| 89 | + queries = append(queries, qshape.Query{ |
| 90 | + QueryID: qid, |
| 91 | + Calls: calls, |
| 92 | + Raw: raw, |
| 93 | + TotalExecTimeMs: totalExec, |
| 94 | + MeanExecTimeMs: meanExec, |
| 95 | + StddevExecTimeMs: stddevExec, |
| 96 | + Rows: rowCount, |
| 97 | + }) |
| 98 | + } |
| 99 | + if err := rows.Err(); err != nil { |
| 100 | + return err |
| 101 | + } |
| 102 | + |
| 103 | + clusters, err := qshape.Group(queries) |
| 104 | + if err != nil { |
| 105 | + return err |
| 106 | + } |
| 107 | + |
| 108 | + fmt.Fprintf(os.Stderr, "captured %d queries → %d clusters\n", len(queries), len(clusters)) |
| 109 | + |
| 110 | + enc := json.NewEncoder(os.Stdout) |
| 111 | + enc.SetIndent("", " ") |
| 112 | + return enc.Encode(map[string]any{"clusters": clusters}) |
| 113 | +} |
0 commit comments