Skip to main content

kysera debug

Debug and performance analysis tools for SQL queries and database operations.

:::warning Pass queries with --query, not -q The short -q is consumed by the global quiet flag, so kysera debug profile -q "SELECT 1" fails with "too many arguments". Always use the long form --query (the examples below do). :::

Commands​

CommandDescription
sqlReal-time SQL query monitoring and debugging
profileQuery profiling and performance analysis
errorsError analysis and diagnostics
circuit-breakerCircuit breaker status and management
analyzerQuery pattern analyzer

sql​

Real-time SQL query monitoring and debugging.

kysera debug sql [options]

Options​

OptionDescription
-w, --watchWatch mode - monitor queries in real-time
-f, --filter <pattern>Filter queries by pattern (regex)
-h, --highlight <keyword>Highlight specific keywords
--show-paramsShow query parameters
--show-durationShow query execution time
-l, --limit <n>Limit number of queries to show (default: 50)
-c, --config <path>Path to configuration file

Examples​

# Watch queries in real-time
kysera debug sql --watch

# Watch with duration display
kysera debug sql --watch --show-duration

# Filter queries by pattern
kysera debug sql --watch --filter "SELECT.*users"

# Highlight specific keywords
kysera debug sql --watch --highlight "JOIN"

# Show query parameters
kysera debug sql --watch --show-params

# Analyze recent queries from logs
kysera debug sql --limit 100

Output​

In watch mode, each query is displayed with:

  • Timestamp
  • Query ID and status (✓ success / ✗ error)
  • Duration (if --show-duration)
  • Row count
  • SQL with syntax highlighting
  • Parameters (if --show-params)

The command also provides summary statistics:

  • Top query patterns by frequency
  • Slow queries (>1s)
  • Failed queries with errors
  • Success rate, average duration, P95 duration

profile​

Query profiling and performance analysis with statistical metrics.

kysera debug profile [options]

Options​

OptionDescription
-q, --query <sql>SQL query to profile
-t, --table <name>Profile queries on specific table
-o, --operation <type>Operation type: select, insert, update, delete
-i, --iterations <n>Number of iterations (default: 100)
-w, --warmup <n>Number of warmup runs (default: 10)
--show-planShow query execution plan
--compare <query>Compare with another query
--jsonOutput as JSON
-c, --config <path>Path to configuration file

Examples​

# Profile a specific query
kysera debug profile --query "SELECT * FROM users WHERE status = 'active'"

# Profile table operations
kysera debug profile --table users --operation select

# Profile with execution plan
kysera debug profile --query "SELECT * FROM orders" --show-plan

# Compare two queries
kysera debug profile \
--query "SELECT * FROM users WHERE id = 1" \
--compare "SELECT * FROM users WHERE email = 'test@example.com'"

# Custom iterations
kysera debug profile --query "SELECT 1" --iterations 1000 --warmup 50

Output​

Profile results include:

Performance Metrics:

  • Average duration
  • Minimum/Maximum duration
  • P50 (Median), P95, P99 percentiles
  • Standard deviation

Response Time Distribution:

  • Histogram showing timing distribution

Execution Plan (with --show-plan):

  • PostgreSQL: EXPLAIN ANALYZE output
  • MySQL: EXPLAIN output
  • SQLite: EXPLAIN QUERY PLAN output

Analysis:

  • Performance rating (Excellent/Good/Moderate/Poor)
  • Consistency rating based on standard deviation

errors​

Error analysis and diagnostics.

kysera debug errors [options]

Options​

OptionDescription
-s, --since <datetime>Show errors since datetime (ISO 8601)
--until <datetime>Show errors until datetime (ISO 8601)
-l, --limit <n>Limit number of results (default: 100)
-p, --pattern <regex>Filter errors by pattern
-g, --group-by <field>Group by: error, table, operation, user (default: error)
--show-queriesShow failing queries
--jsonOutput as JSON
-c, --config <path>Path to configuration file

Examples​

# Show recent errors
kysera debug errors

# Show errors in a time window
kysera debug errors --since "2025-01-01T00:00:00" --until "2025-01-31T23:59:59"

# Filter by pattern and show the failing queries
kysera debug errors --pattern "unique" --show-queries

# Group errors by table
kysera debug errors --group-by table

circuit-breaker​

Circuit breaker status and management.

kysera debug circuit-breaker [options]

Options​

OptionDescription
-a, --action <type>Action: status, reset, open, close (default: status)
-s, --service <name>Service name: database, cache, api
-w, --watchWatch mode - monitor in real-time
--forceConfirm reset without prompting
--jsonOutput as JSON
-c, --config <path>Path to configuration file

Examples​

# Check circuit breaker status
kysera debug circuit-breaker --action status

# Check specific service
kysera debug circuit-breaker --service database

# Reset circuit breaker
kysera debug circuit-breaker --action reset

# Manually open circuit breaker
kysera debug circuit-breaker --action open --service database

# Close circuit breaker
kysera debug circuit-breaker --action close --service database

# Watch mode - real-time monitoring
kysera debug circuit-breaker --watch

# Configure threshold and timeout
kysera debug circuit-breaker --threshold 10 --timeout 60000

Circuit Breaker States​

StateDescription
CLOSEDNormal operation, requests pass through
OPENCircuit is open, requests fail fast
HALF_OPENTesting if service recovered

Reset requires explicit --force in non-interactive or JSON mode. Reads and writes use the same --config database; only selected services are changed. Success is reported after persistence completes. Missing state is reported as an empty observation, and connection or write errors fail the command rather than manufacturing healthy defaults.

--watch is an interactive status view. It re-reads the selected database one second after each completed refresh, so queries never overlap and a slow or failed read cannot be displayed as a fresh healthy snapshot. Ctrl+C or SIGTERM stops the view after any in-flight read is cleaned up. JSON automation uses individual --json snapshots; combining JSON or a mutation with --watch is rejected before connecting. Error thresholds and retry intervals are observed from the persisted runtime state; this command does not configure them.

analyzer​

Query analyzer for identifying optimization opportunities, index usage, and performance insights.

kysera debug analyzer [options]

Options​

OptionDescription
-q, --query <sql>SQL query to analyze
-t, --table <name>Analyze queries for specific table
-e, --explainShow execution plan
-s, --suggestionsShow optimization suggestions (default: true)
-i, --indexesAnalyze index usage
--statisticsShow table statistics
--jsonOutput as JSON
-c, --config <path>Path to configuration file

Examples​

# Analyze a specific query
kysera debug analyzer --query "SELECT * FROM users WHERE email = 'test@example.com'"

# Analyze with execution plan
kysera debug analyzer --query "SELECT * FROM orders" --explain

# Analyze table indexes
kysera debug analyzer --table users --indexes

# Show table statistics
kysera debug analyzer --table orders --statistics

# Get optimization suggestions
kysera debug analyzer --query "SELECT * FROM users" --suggestions

# Full analysis with all features
kysera debug analyzer --table users --indexes --statistics --suggestions

# Output as JSON
kysera debug analyzer --table users --json

Output​

Query Analysis:

  • Estimated cost and rows
  • Index recommendations
  • Missing indexes detection
  • Query complexity score

Index Analysis (with --indexes):

  • Index usage statistics
  • Unused indexes
  • Duplicate indexes
  • Recommended indexes

Table Statistics (with --statistics):

  • Row count
  • Table size
  • Index size
  • Average row size

Configuration​

Debug commands use the database configuration from kysera.config.ts:

export default {
database: {
dialect: 'postgres',
connection: '${DATABASE_URL}'
}
}

Requirements​

Some debug features require additional setup:

Query Logging Table​

For debug sql without watch mode:

CREATE TABLE query_logs (
id SERIAL PRIMARY KEY,
query_text TEXT NOT NULL,
duration_ms INTEGER,
error TEXT,
executed_at TIMESTAMP DEFAULT NOW()
);

Kysera Debug Plugin​

For automatic query logging, wrap your database with withDebug from @kysera/debug:

import { withDebug } from '@kysera/debug'

const db = withDebug(baseDb, {
logQuery: true, // Log every query (default: true)
logParams: false, // Include bound parameters
slowQueryThreshold: 1000, // ms; slower queries are flagged
onSlowQuery: (sql, duration) => {
console.warn(`Slow query (${duration}ms): ${sql}`)
},
maxMetrics: 1000 // Metrics buffer size
})

A custom logger can also be supplied to route output through your own logging.

See Also​