CandySql
Terminal SQL client
Composer-installable multi-driver SQL TUI: connect to SQLite, MySQL, or PostgreSQL, browse tables, peek at row data, run ad-hoc queries, and explore a full MySQL-Workbench-style admin dashboard — all on the SugarCraft stack. SQLite-first; MySQL and PostgreSQL drivers plus a Performance Dashboard, Server Status, Variables, Connections, Reports, and Performance Schema Setup ship on dev-master (rolling prerelease tag candy-sql/latest).
Install
composer require sugarcraft/candy-sql
Quickstart
# SQLite via bare path (inferred as Flavor::Sqlite)
vendor/bin/candy-sql app.sqlite
# Any DSN — SQLite, MySQL, PostgreSQL (flags are equals-form only)
vendor/bin/candy-sql --dsn=mysql://user:pass@localhost:3306/dbname
// Or wire it up programmatically:
use SugarCraft\Core\Program;
use SugarCraft\Core\ProgramOptions;
use SugarCraft\Sql\App;
use SugarCraft\Sql\Db\ConnectionFactory;
use SugarCraft\Sql\Db\Flavor;
// fromDsn() only parses the DSN into a ConnectionConfig; fromConfig() connects.
$db = ConnectionFactory::fromConfig(ConnectionFactory::fromDsn('mysql://user:pass@localhost:3306/dbname'));
(new Program(App::start($db, Flavor::MySQL), new ProgramOptions(useAltScreen: true)))->run();
What's in the box
Tables paneLists every
type IN (table, view) in sqlite_master excluding sqlite_* internals.Rows paneFirst 100 rows of the selected table, with header row + reverse-video cursor.
Query paneAd-hoc SQL editor — Ctrl+R runs, errors stash to a status line instead of crashing.
Tab / Backspace / SpacePane cycle, character delete, and space typing all respect the focused pane.
Cursor clampingLists never let the cursor escape their bounds; switching panes preserves per-pane positions.
PDO under the hood
:memory: driving in tests covers the full transition surface without fixture files.SchemaBrowserStrategy pattern for schema introspection — delegates to driver-specific
SchemaProviderInterface (SqliteSchemaProvider, MysqlSchemaProvider, PostgresSchemaProvider) based on Flavor. Returns immutable SchemaTable/SchemaColumn/SchemaIndex/SchemaForeignKey value objects.Exporters (CsvExporter, SqlExporter)Driver-agnostic export to CSV and SQL INSERT. CsvExporter produces RFC-4180 CSV via
fputcsv() with formula-injection guard (=+-@\t\r prefixed with ') on headers and cells. SqlExporter emits INSERT statements only (no CREATE TABLE — not driver-neutral). Both use SELECT * LIMIT 0/1 for column detection; exporting an empty table produces a blank file.ConnectionConfigReadonly value object: driver, host, port, user, pass, dbname, sslMode, dsn. Password never echoed.
ConnectionFactoryStatic factory:
fromDsn() parses a DSN into a ConnectionConfig without connecting; fromConfig() and fromArgv() connect and return a PDO-backed DatabaseInterface (SqliteDatabase, MysqlDatabase or PostgresDatabase); fromPath() opens a bare SQLite file path.FlavorEnum:
MySQL, MariaDB, Percona, Postgres, Sqlite. Identifies the database server flavor. Flavor::detectFromDriver() detects flavor from a PDO driver name + optional version string; Flavor::detectFromVersionString() refines MySQL to MariaDB/Percona using the version comment.VersionParser for server version strings. Handles MariaDB's
5.5.5- prefix. isAtLeast($major, $minor = 0, $release = 0) compares versions safely.ExplainViewStrategy pattern for
EXPLAIN output — delegates to driver-specific ExplainProviderInterface (SqliteExplainProvider, MysqlExplainProvider, PostgresExplainProvider) based on Flavor. run() executes against a Database; render() produces ANSI colored tree; toArray() returns JSON-serializable structure.ResultTableSQL result set renderer with horizontal scrolling, JSON pretty-print (2-space indent), styled NULL token, and column auto-sizing.
scrollLeft()/scrollRight()/render()/renderPlain().ConnectionsPageProcesslist browser with keyboard navigation (
j/k/↑/↓), detail tab cycling (Tab/1/2/3 — page-level handlers; in-app Tab cycles focus panes and digits pick admin pages, so these fire only in standalone use), hide-sleeping filter (f), and async refresh (r) via Cmd::send(). Memoized cachedFilteredProcesslist avoids 2–3× DB fetch per render.ConnectionFiltersImmutable filter config: hide-sleeping, hide-background, skip-full-info, refresh-rate (0.5–30s). All fields are readonly; paired
$Set sentinels for nullability.ConnectionCountersConnection metrics from
SHOW GLOBAL STATUS: threads-connected/running/cached, connections, aborted-connects, connection-errors. Computes connectionUsageRatio() lazily (0.0–1.0); isConnectionUsageCritical() returns true ≥80%.ConnectionDetailTabsThree detail tabs (Details/Attributes/MDL) per processlist thread. Details from
performance_schema.threads; Attributes from session_connect_attrs; MDL from performance_schema.metadata_locks with fallback to information_schema.metadata_lock_info. Returns null on permission errors (1142/1146/1227).ReportsPagePerformance Reports admin page: left category/report tree + right sortable/exportable grid.
validate() only loads Catalog (file I/O) — no DB queries on the render path. Navigation keys: h/l (prev/next category, wrap-around), [/] (prev/next report within category), ,/. (prev/next column index). All navigation triggers async report loading via loadCurrentReport(). selectedColumnIndex tracks focused column for future per-column unit cycling; [c] is currently a global unit toggle. Footer keybindings: [j/k] nav rows [h/l] category [/] cycle report [c] unit toggle [q] back (q returns to the Tables browser; it never quits from inside Admin).ReportRunnerExecutes
SELECT * FROM sys.<view> for performance report views. MySQL cannot parameterise table names, so the view name rides literal SQL escaped through Identifier::quote()'s MySQL arm (backticks and backslashes doubled) with the limit cast to int — the safety mechanism is escaping, not preparation. run() applies time/byte unit formatting via UnitFormatter; runRaw() returns unformatted values. Availability gating via AvailabilityChecker::isViewAvailable() before executing.AvailabilityCheckerChecks sys schema view availability via
SHOW FULL TABLES FROM sys WHERE Table_type='VIEW'. Caches result in-memory after first fetch. discoverViews() catches \Throwable (not just \PDOException) because React/cached connections can surface non-PDO error types. isViewAvailable(), availableFromCatalog(), missingFromCatalog() for filtering.Reports\CatalogLoads
data/sys_reports.json and provides get(), all(), byCategory(), categories(). Categories are sorted by a curated CATEGORY_ORDER constant (problems first, matching MySQL Workbench Appendix B) rather than alphabetically; unknown categories fall through to alphabetical ordering. Column type parsing uses ColumnType::tryFrom() instead of ColumnType::from() to gracefully handle unknown type strings (returns null instead of throwing ValueError). Unknown types fall back to ColumnType::String.VariablesPageDual-tab (Status/System) variable browser with category tree, search filtering, and inline edit.
[e] opens a two-phase dialog: type the new value (DLG_INPUT), press [Enter] to preview the SET statement (DLG_CONFIRM), then [Enter] again to execute or [Esc] to cancel. Self-write guard: setting a variable to its current value is a no-op — the dialog stays in input phase. Static (non-dynamic) variables show error 1238 ("requires server restart") at the confirm phase rather than silently refusing at the entry point. All state transitions return new immutable instances. Keybindings: [j/k] nav, [w] rw filter, [s] search, [tab] toggle tab (page-level: in-app Tab is consumed by pane cycling, so toggling fires only in standalone use), [e] edit (dynamic vars only), [q] back to Tables.VariableEditorInline editor for MySQL variables via
SET GLOBAL / SET PERSIST / SET PERSIST_ONLY / RESET PERSIST (all MySQL 8.0+). Uses prepared statements with backtick-quoted variable names (from catalog) and ? placeholders for values — value interpolation is injection-safe. Press [p] in the edit dialog to cycle through GLOBAL → PERSIST → PERSIST_ONLY modes; error 1238 prompts to use PERSIST_ONLY. Error codes surfaced: 1142 (no privilege), 1227 (access denied), 1238 (variable is not dynamic), 3680 (persisted_variables restriction). Mirrors mysql-workbench wb_admin_variable_editor.VariableMetadataImmutable descriptor for a single MySQL system variable: name, description, editable flag, dynamic flag, and group memberships.
editable = can be set at all (SET GLOBAL / SET PERSIST); dynamic = runtime-changeable without restart (static vars like innodb_log_file_size accept SET GLOBAL but error 1238). Constructed from data/variable_metadata.json (1563 entries, 67 groups).CatalogVariable metadata catalog loaded from
data/variable_metadata.json (1563 variables, 67 groups). Provides get(), all(), byGroup(), groups(), isEditable(), isDynamic(). isDynamic() returns false for static variables (e.g. innodb_log_file_size) — used by VariablesPage to gate inline editing so static vars hit error 1238 rather than silently declining. VariableMetadata carries both editable (can be set at all) and dynamic (runtime-changeable without restart). Missing metadata is non-fatal — the VariablesPage renders without categories or [rw] indicators.AdminProviderInterfaceFlavor-agnostic port for admin data:
flavor(), fetchStatusVariables(), fetchServerVariables(), fetchProcesslist(), maxConnections(), statusVariablesTs(), wasReset(), refresh(). Implemented by MysqlAdminProvider (MySQL) and PostgresAdminProvider (PostgreSQL via pg_stat_database, pg_settings, pg_stat_activity).MysqlAdminProvider
AdminProviderInterface adapter over ServerContext — the context issues SHOW GLOBAL STATUS, SHOW GLOBAL VARIABLES, and SHOW PLUGINS; the provider adds fetchProcesslist() (prefers performance_schema.threads, falls back to SHOW FULL PROCESSLIST).PostgresAdminProvider
AdminProviderInterface via pg_stat_database, pg_settings, pg_stat_activity. checkAllMetrics() / checkConnectionUsage() compute PostgreSQL metrics (connection usage, cache hit rate, transaction rates, throughput); the dashboard widgets are defined in PostgresWidgetCatalog over the provider's pg_stat_database.* keys. Graceful degradation on any PDOException (returns null/stub for inaccessible panels) — Postgres privilege denials surface as SQLSTATE 42501, not MySQL error codes.ServerStatusPage2-column admin page: left panel shows server info (host, socket, port, version, uptime + running-since), Features, Directories, SSL, Replication (
SHOW REPLICA STATUS for MySQL 8+ / SHOW SLAVE STATUS for MySQL 5.x/MariaDB, graceful 1227 handling), and Firewall (MySQL Enterprise Firewall via mysql_firewall_mode, with an AUDIT/firewall plugin fallback for managed instances); right panel shows SidebarGaugeSet with five sampled gauges (Connections, Traffic, Key Efficiency, QPS, InnoDB). r refreshes; q returns to the Tables browser.ServerStatusSnapshotAdapterAdapter wrapping
ServerContextInterface to satisfy StatusSnapshotProviderInterface, enabling Sampler to compute per-second rate deltas across poll cycles for the Traffic gauge. Caches the last snapshot internally; currentSnapshot() delegates to $this->context->statusVariables(). Created in App::adminPage() alongside the Sampler and passed to ServerStatusPage::new().SidebarGaugeSetCollection of 5 gauges: Connections (
threads_connected/max_connections), Traffic (sampled per-second bytes rate via Sampler using Bytes_received/Bytes_sent deltas, baseline-corrected against 10MB/s), Key Efficiency (Key_reads / (Key_reads + Key_read_requests)), QPS (Questions/Uptime), and InnoDB Buffer Pool utilization. No CPU gauge — MySQL provides no CPU status variable; the prior gauge was a mislabeled connections ratio. Sampler advances on each withRefresh() call via poll(). r key triggers withRefresh() to rebuild the gauge set and advance sampler state.ReconnectManagerDetects MySQL errors 2002/2003/2013 (connection lost). Stores
ConnectionConfig, retries via attemptReconnect(), throws ReconnectException on failure.StatementTimeoutWall-clock timeout on
PDOStatement::execute() via pcntl_alarm(). Gracefully degrades when pcntl is unavailable. Cancels query via KILL CONNECTION_ID() on timeout, throws StatementTimeoutException.PerfSchemaPagePerformance Schema configuration page with 7 tabs (Easy Setup, Instruments, Consumers, Actors, Objects, Threads, Options). Uses
EasySetupDetector (wired via EasySetupDetector::fromContext($context)) for four-state detection: fully (all consumers enabled AND all instruments enabled+timed; TIMED-off → custom), default (matches Appendix C profile), custom (user-modified), disabled (PS inaccessible). State shown as a color-coded badge in the header (green/yellow/blue/red). Falls back to detectSetupState() (instrument data only, less accurate) when no detector is wired. Version gating: setup_actors skipped on <5.6; setup_objects.ENABLED column omitted on <5.6.3; timers from setup_timers (mutable) on <8.0 and performance_timers (read-only) on ≥8.0. Threads tab shows INSTRUMENTED status from performance_schema.threads. Instruments tab renders an indented tree with group nodes showing tri-state badges ([x]/[~]/[ ]). Read-only mode when PROCESS privilege is absent (tested via no-op UPDATE). Keybindings: j/k nav, h/l or ←/→ cycle tabs, Space/Enter toggle, [ ] . enable-full/disable/reset on the Easy Setup tab, c commit, r revert, q back to Tables (App intercepts q in-app). Tab/Shift+Tab remain page-level handlers — in-app App consumes Tab (pane cycle) first, so they fire only in standalone use. Mirrors mysql-workbench wb_admin_performance_schema.EasySetupDetectorFour-state PS setup detector using COUNT/SUM queries against
setup_instruments and setup_consumers. Returns fully, default, custom, or disabled. Guard: enabledPercentage() < 100 prevents fully even when detailed counts appear zero (ambiguous with limited data). isFullyDisabled() exists but is NOT wired to detect() — available for future use. Version-gated defaults (Appendix C): 5.6 vs 5.7 instruments are identical; 5.7 adds statements_digest to consumers. Excludes memory/% from all calculations. Graceful degradation on PDOException (privilege/access/connection errors). Factory: ::new(db, ?version), ::fromContext(context). Mirrors mysql-workbench wb_admin_performance_schema easy_setup_detector.EasySetupPS easy-setup SQL toggle statements and Appendix C default sets. Provides
enableStatements() (all instruments+consumers to YES/YES), disableStatements() (all to NO/NO), resetToDefaultStatements() (applies version-appropriate defaults). Default instruments (5.6/5.7): wait/io/file/%, wait/io/table/%, wait/lock/table/sql/handler, statement/%, idle. Default consumers (5.6): four; (5.7+): adds statements_digest. Version-aware — defaultInstruments()/defaultConsumers() return the correct set. memory/% excluded from all operations. Factory: ::new(?version), ::fromContext(context). Mirrors mysql-workbench wb_admin_performance_schema easy_setup.SetupTimersMutable model for a PS timer entry. On MySQL <8.0, loaded from
performance_schema.setup_timers and editable via withTimerName(); isDirty() tracks unsaved changes; commitStatements() generates a fully-literal statement (e.g. UPDATE performance_schema.setup_timers SET TIMER_NAME = 'MICROSECOND' WHERE NAME = 'wait/cpu', identifiers backtick-quoted, values interpolated as escaped quoted literals — no ? placeholders). On MySQL ≥8.0, loaded from performance_schema.performance_timers as clean (read-only) instances — commitStatements() returns []. Uses the Mutable trait for immutable-with* semantics.SetupThreadsMutable model for a PS thread entry carrying the
INSTRUMENTED flag from performance_schema.threads. withInstrumented(bool) returns a new instance with dirty tracking; isDirty() reports unsaved changes; instrumentedFragment() generates a THREAD_ID=N AND INSTRUMENTED='YES'/'NO' SQL fragment for CommitPlanner's batch UPDATE (wiring deferred to a planned follow-up). Read-only by default (instrumented=true, dirty=false on initial load).CommitPlannerGenerates SQL statements to commit PS configuration changes. All statements are fully parameterized — returns
list<array{sql:string, params:list<mixed>}> tuples with all values bound as ? placeholders, none interpolated. Instruments use anchored RLIKE (^name$, regex-escaped via preg_quote()) bucketed by (enabled, timed); Consumers use UPDATE ... IN(?..) with bound names; Actors and Objects use keyed INSERT/UPDATE/DELETE with all values bound. isDirty() scans all tracked models. SetupTimers/SetupThreads commit wiring deferred to a planned follow-up.InstrumentTreeHierarchical view of PS instruments organized by name path (e.g.
wait/io/file/sql/binlog → 5-level tree). Tracks aggregate enabled/timed state of each subtree via tri-state values: 1=all-enabled, 0=mixed, -1=all-disabled. Provides setChildrenEnabled(bool) / setChildrenTimed(bool) cascade methods that recursively mark all instruments in a subtree with the same state and return the modified list. pathDepth() returns the number of path segments (root=0, wait=1, wait/io=2) for indent calculation. flattenTree() (in PerfSchemaPage) emits [nodeOrInstrument, depth, isGroup] triples for renderer consumption. Mirrors mysql-workbench wb_admin_performance_schema instrument_tree.Restart detection + SamplerRestart detection lives solely in
ServerContext::detectReset(), which compares the current Uptime status variable against the last observed value after each successful status fetch; Sampler consumes the verdict through provider->wasReset() on each sample() call, clearing cached rate state via resetAll(). Sampler also computes per-second rate deltas (Bytes_received, Bytes_sent, etc.) from two status snapshots, used by SidebarGaugeSet for baseline-corrected Traffic gauge ratios; the gauge set advances via poll() on each refresh cycle.AlertingStateless
AlertManager evaluates metrics against AlertThresholds presets (::default(), ::strict()). Alert value objects carry severity, metric, value, and threshold. AlertNotifier dispatches toasts via sugar-toast with mute-safe degradation when no factory is available. Maps Severity::Critical → ToastType::Error, Warning → Warning, Info → Info.Status-Snapshot History (default-on,
--no-history opt-out)SQLite persistence via SqliteHistoryStore — an implementation of the five-method HistoryStoreInterface port (save() / query() / count() / prune() / close()), with WAL mode, 0600 file / 0700 dir private modes; pruning is explicit — prune() / HistoryRecorder::pruneOlderThan(), no automatic size cap). Stores timestamped admin status-variable snapshots, not SQL text. HistoryRecorder implements StatusSnapshotProviderInterface and records via record() / recordFromProvider(); history faults never crash a session and degrade through two channels — at launch a corrupt or unwritable store warns loudly on stderr (history recording DISABLED) and the session runs history-less, while a mid-session persist failure drops to the in-app query log so the live dashboard and in-memory snapshots stay authoritative. HistoryQuery::query()/querySince()/rate() retrieve snapshots and compute per-variable rates over time ranges.Source & demos
- Source on GitHub
- Full README
- Runnable examples
- Originally inspired by lazysql (Go); SugarCraft is developed as a native PHP project.
API
| Class | Method | Description |
|---|---|---|
| Database ⚠️ | — | Deprecated thin alias to SqliteDatabase. Use DatabaseInterface instead. |
| MysqlDatabase | — | DatabaseInterface implementation via PDO mysql. Implements serverVersion(), driverName(), ping(), databases(). |
| PostgresDatabase | — | DatabaseInterface implementation via PDO pgsql. Implements serverVersion(), driverName(), ping(), databases(). |
| DatabaseInterface | serverVersion() | Get database server version |
| DatabaseInterface | driverName() | Get driver name (e.g., sqlite, mysql) |
| DatabaseInterface | ping() | Check connection is alive |
| DatabaseInterface | databases() | List available databases |
| DatabaseInterface | tables() | List all tables |
| DatabaseInterface | rows(table, limit, offset) | Get table rows |
| DatabaseInterface | query(sql) | Execute SQL query; returns list<array>|null — null signals a reconnectable connection error (2002/2003/2013), empty array means no rows |
| DatabaseInterface | prepare(sql) | Prepare SQL; returns PreparedStatementInterface|null — driver-neutral statement wrapper |
| PreparedStatementInterface | execute(params?) | Execute with bound params; returns bool |
| PreparedStatementInterface | fetch() | Fetch next row; returns array<string,mixed>|false |
| PreparedStatementInterface | fetchAll() | Fetch all rows; returns list<array<string,mixed>> |
| PreparedStatementInterface | rowCount() | Rows affected by last query |
| PreparedStatementInterface | closeCursor() | Close cursor, enabling re-execution |
| PdoPreparedStatement | — | PreparedStatementInterface via PDOStatement. All database implementations (MysqlDatabase, PostgresDatabase, SqliteDatabase) wrap their PDOStatement in this before returning from prepare(). |
| App | start(database, flavor = Flavor::Sqlite, ?historyRecorder = null, ?sslMode = null) | Create the app model (MySQL TLS doctrine folds to the async-off path when TLS is verifying) |
| SchemaBrowser | refresh() | Load schema via driver-specific SchemaProviderInterface |
| SchemaBrowser | new(db, flavor) | Static factory: browser bound to a Database and its Flavor |
| SchemaProviderInterface | tables(pdo) | List all tables/views |
| SchemaProviderInterface | columns(pdo, table) | Get columns for a table |
| SchemaProviderInterface | indexes(pdo, table) | Get indexes for a table |
| SchemaProviderInterface | foreignKeys(pdo, table) | Get foreign keys for a table |
| SqliteSchemaProvider | — | SchemaProviderInterface via PRAGMA queries |
| MysqlSchemaProvider | — | SchemaProviderInterface via INFORMATION_SCHEMA |
| PostgresSchemaProvider | — | SchemaProviderInterface via pg_catalog |
| SchemaBrowser | dropTable(name) | DROP table and re-refresh |
| SchemaTable | column(name) | Find a column by name |
| ExplainView | run(db, sql) | Static: execute EXPLAIN through the driver-specific ExplainProviderInterface and return the view |
| ExplainProviderInterface | explain(pdo, sql) | Execute EXPLAIN and return explain rows |
| SqliteExplainProvider | — | ExplainProviderInterface via EXPLAIN QUERY PLAN |
| MysqlExplainProvider | — | ExplainProviderInterface via EXPLAIN |
| PostgresExplainProvider | — | ExplainProviderInterface via EXPLAIN (ANALYZE, FORMAT JSON) |
| AdminProviderInterface | flavor() | Which database flavor this provider targets |
| AdminProviderInterface | fetchStatusVariables() | All status variables (equivalent to SHOW GLOBAL STATUS; prefixed pg_stat_database.* keys on PostgreSQL) |
| AdminProviderInterface | fetchServerVariables() | All server variables (equivalent to SHOW GLOBAL VARIABLES; pg_settings on PostgreSQL) |
| AdminProviderInterface | fetchProcesslist() | Active server processes/connections — pg_stat_activity on PostgreSQL; prefers performance_schema.threads on MySQL, falls back to SHOW FULL PROCESSLIST |
| AdminProviderInterface | maxConnections() | The server's max_connections value (or equivalent) |
| AdminProviderInterface | statusVariablesTs() | Unix timestamp (float) when status variables were last fetched |
| AdminProviderInterface | wasReset() | True when the server has restarted since the last poll (MySQL via Uptime going backwards; PostgreSQL always false — detection not implemented) |
| AdminProviderInterface | refresh() | Force a refresh of all cached values |
| MysqlAdminProvider | — | AdminProviderInterface adapter over ServerContext (SHOW GLOBAL STATUS/VARIABLES/PLUGINS issued by the context); fetchProcesslist prefers performance_schema.threads, falls back to SHOW FULL PROCESSLIST |
| ConnectionsPage | new(context, maxConnections?) | Factory creating fully-wired instance with ProcesslistProvider, ConnectionActions, ConnectionDetailTabs, ConnectionCounters |
| ConnectionsPage | update(Msg) | Handle keyboard: j/k/↑/↓ navigate, f toggle filter, r refresh, y confirms a pending kill (any other key cancels). Tab/1/2/3 detail-tab handlers are page-level: in-app App consumes Tab (pane cycle) and digits (page picker) first. Returns [newPage, ?Closure]. Mirrors mysql-workbench client connections panel. |
| ConnectionsPage | table() | Get the sugar-table Table with columns: Id, User, Host, DB, Command, Time, State, Info |
| ConnectionsPage | filters() / counters() / detailTab() / selectedThread() | Read current filter state, counters, active detail tab, and selected process thread |
| ConnectionFilters | new() | Default filters: no hiding, no auto-refresh |
| ConnectionFilters | withHideSleeping(bool) / withHideBackground(bool) / withSkipFullInfo(bool) / withRefreshRate(float|null) | Fluent filter setters — all return new immutable instance |
| ConnectionCounters | fromSnapshot(snapshot, maxConnections) | Factory from StatusSnapshot: reads Threads_*, Connections, Aborted_* variables |
| ConnectionCounters | connectionUsageRatio() | Lazy-computed ratio (0.0–1.0) of threads_connected / max_connections |
| ConnectionCounters | isConnectionUsageCritical() | True when usage ≥80% (red threshold) |
| ConnectionDetailTabs | details(processId) | Basic thread info from performance_schema.threads — returns null on 1142/1146/1227 |
| ConnectionDetailTabs | attributes(processId) | Session connect attrs from performance_schema.session_connect_attrs — returns null if no attrs or access denied |
| ConnectionDetailTabs | mdlLocks(processId) | Metadata locks from performance_schema.metadata_locks (primary) with fallback to information_schema.metadata_lock_info |
| ConnectionDetailTabs | threadStack(processId) | Stack dump via sys.ps_thread_stack() — returns null if sys schema unavailable |
| ConnectionDetailTabs | explain(processId) | Runs EXPLAIN on the selected thread's current query — returns null if no query or explain fails |
| PostgresAdminProvider | — | AdminProviderInterface via pg_stat_database, pg_settings, pg_stat_activity. Dashboard widgets defined in PostgresWidgetCatalog over the provider's pg_stat_database.* keys; checkAllMetrics()/checkConnectionUsage() compute PostgreSQL metrics and threshold alerts; graceful null on SQLSTATE 42501 / any PDO failure (the provider catches PDOException generically — 1142/1146 are MySQL codes, attributed to the MySQL paths only). |
| ReportsPage | new(context, ?db) | Factory. validate() only loads Catalog (file I/O) — no blocking db->query() on render path. report queries routed through AdminQueryCache async. |
| ReportsPage | update(Msg) | Handles ReloadReportMsg (triggers loadCurrentReport), j/k navigate, r refresh, x export (CSV string into page state — not written to disk), c unit toggle, q back to Tables. |
| ReportsPage | exportToCsv() | Export current report as RFC-4180 CSV string via CsvExporter::exportReportResultsToString(). Returns '' if no report loaded. |
| ReportRunner | run(viewName, ?limit) | Execute SELECT * FROM sys.<view> with unit formatting. Throws \InvalidArgumentException if view not in catalog, \RuntimeException if view not available on server. |
| ReportRunner | runRaw(viewName, ?limit) | Execute report without unit formatting — returns raw numeric values for sorting/calculation. |
| ReportRunner | canRun(viewName) | True if report exists in catalog and its view is available on this server. |
| AvailabilityChecker | discoverViews() | Runs SHOW FULL TABLES FROM sys WHERE Table_type='VIEW'. Caches result. Catches \Throwable (not just \PDOException) because React/cached connections can surface non-PDO errors. |
| AvailabilityChecker | sysSchemaExists() | True if sys schema is accessible (runs discoverViews() internally). |
| AvailabilityChecker | isViewAvailable(viewName) | True if the named sys schema view exists on this server. |
| AvailabilityChecker | availableFromCatalog(catalog) | Return catalog reports whose views exist on this server. |
| AvailabilityChecker | missingFromCatalog(catalog) | Return catalog reports whose views are missing on this server. |
| AvailabilityChecker | reset() | Clear cached view list — force re-discovery on next call. |
| ReloadReportMsg | — | Dispatched by App after AdminDataLoadedMsg. ReportsPage handles this in update() to queue the report query via AdminQueryCache for the next tick. |
| VariablesPage | new(context, ?catalog, ?editor) | Factory. Optional Catalog (eagerly loaded variable metadata) and VariableEditor enable category tree, [rw] indicators, and inline editing. Missing catalog/editor is non-fatal — page renders without those features. |
| VariablesPage | update(Msg) | Handles keyboard: j/k navigate rows, w toggle rw filter, s focus search, e open edit dialog (dynamic vars only), q back to Tables. The [tab] Status/System toggle is page-level — in-app Tab is consumed by pane cycling first. When the edit dialog is active, delegates to updateDialog(). Returns [newPage, ?Closure]. All with*() methods return new immutable instances. |
| VariableEditor | edit(variableName, newValue) | Execute SET GLOBAL via prepared statement. Backtick-escapes variable name (from catalog), uses ? placeholder for value. Returns ['success' => bool, 'errorCode' => ?int, 'errorMessage' => ?string]. Error 1238 = variable not dynamic; 1142/1227 = privilege; 3680 = persisted_variables restriction. |
| VariableEditor | persist(variableName, newValue) | Execute SET PERSIST (MySQL 8.0+) — sets the variable globally and writes to mysqld-auto.cnf. Version-gated. Uses prepared statement with backtick-quoted name. |
| VariableEditor | persistOnly(variableName, newValue) | Execute SET PERSIST_ONLY (MySQL 8.0+) — writes to mysqld-auto.cnf without affecting the running value. Use for static variables (error 1238). Version-gated. |
| VariableEditor | resetPersist(?variableName) | Execute RESET PERSIST [x] (MySQL 8.0+). Without argument clears all persisted vars. With argument removes only that variable. No isEditable() check (it removes, not sets). Version-gated. |
| VariableEditor | editPreview(variableName, newValue, mode='global') | Return a preview string of the SET statement that would be executed. mode is 'global'|'persist'|'persist_only' (e.g. SET PERSIST `max_connections` = '200'). |
| VariableEditor | isEditable(variableName) | True if the variable has editable=true in the metadata catalog. Returns false when catalog is absent (safer default). |
| VariableMetadata | isDynamic() | True if the variable has Dynamic=true in metadata (can be changed at runtime via SET GLOBAL). Non-dynamic variables hit MySQL error 1238. |
| VariableMetadata | inGroup(group) | True if the variable belongs to the given group name. |
| Catalog | load() | Load variable metadata from data/variable_metadata.json. Throws \RuntimeException on corrupt/missing file. |
| Catalog | get(variableName) | Return VariableMetadata for a variable, or null if not in catalog. |
| Catalog | all() | Return all VariableMetadata entries keyed by variable name. |
| Catalog | groups() | Return sorted list of all group names in the catalog. |
| Catalog | isEditable(variableName) | True if variable exists in catalog and VariableMetadata.editable is true. |
| Catalog | isDynamic(variableName) | True if variable exists in catalog and VariableMetadata.isDynamic() is true. |
| ExplainView | render() | Render plan as ANSI-colored string |
| ExplainView | toArray() | Return JSON-serializable plan rows (depth, tag, detail, indent) |
| ConnectionActions | setInstrumentation(bool $enabled, int|string $threadId) | Enable/disable performance_schema instrumentation per-thread via UPDATE performance_schema.threads SET INSTRUMENTED=?. Requires MySQL 8.0+; returns false on permission errors. |
| ConnectionActions | kill(int|string $threadId, bool $isBackground) | KILL a thread (disconnect). Refuses to kill background threads (no user or NULL user). MySQL's KILL does not accept placeholders; ID is int-cast directly (injection-safe). Returns true on success, false on refusal or error. |
| ConnectionActions | killQuery(int|string $threadId, bool $isBackground) | KILL QUERY a thread (cancel statement, keep connection). Refuses to kill query on background threads. MySQL's KILL QUERY does not accept placeholders; ID is int-cast directly (injection-safe). Returns true on success, false on refusal or error. |
| ConnectionDetailTabs | explain(processId) | Runs EXPLAIN on the selected thread's current query. Accepts single SELECT statements only — rejects multi-statement queries (containing ;) and any non-SELECT statement (INSERT/UPDATE/DELETE/DROP/etc.) before running. Returns null if no query, explain fails, or query is not a single SELECT. |
| ConnectionConfig | — | Readonly value object: driver, host, port, user, pass, dbname, sslMode, dsn |
| ConnectionFactory | fromDsn(dsn) | Parse DSN string via parse_url() (mysql/pgsql) or regex (sqlite) and build a ConnectionConfig. Handles URL-encoded passwords, passwordless users, and IPv6 hosts. The ?ssl-mode= query param is parsed and stored in ConnectionConfig.sslMode; SSL is applied as PDO driver options in MysqlDatabase::connect(), not embedded in the DSN string. Examples: mysql://u:p%40ss@[::1]:3306/db, mysql://root@localhost/db. |
| ConnectionFactory | fromConfig(config) | Connect using a ConnectionConfig and return the driver's DatabaseInterface (sqlite, mysql or pgsql; any other driver throws InvalidArgumentException) |
| ConnectionFactory | fromArgv(argv) | Build a connection from CLI flags: --dsn= alone, or --driver= --db= with optional --host= --port= --user= --pass= --ssl-mode=. Equals-form only; unknown or valueless flags are refused with an InvalidArgumentException. |
| Flavor | detectFromDriver(driver, version?, versionComment?) | Detect flavor from PDO driver name ('mysql', 'pgsql', 'sqlite') + optional version string. Uses detectFromVersionString() for MySQL refinement. Ensures mysql/pgsql never falls back to SQLite for an unparseable version. |
| Version | isAtLeast($major, $minor = 0, $release = 0) | Compare version integers (handles MariaDB 5.5.5- prefix) |
| ResultTable | fromRows(rows) | Factory from a list of associative row arrays |
| ResultTable | scrollLeft() / scrollRight() | Scroll viewport by one column |
| ResultTable | withVisibleWidth(n) / withJsonPretty(bool) / withNullToken(s) | Fluent configuration builders |
| ResultTable | render() / renderPlain() | Render ANSI string or plain text |
| CsvExporter | exportCsv(path, table) | Export a table to a CSV file (RFC-4180, formula guard on headers+values, driver-neutral column detection via LIMIT 0/LIMIT 1) |
| CsvExporter | exportReportResults(path, columns, rows) | Write a result set to a CSV file with formula guard |
| CsvExporter | exportReportResultsToString(columns, rows) | Return a result set as an RFC-4180 CSV string (used by ReportsPage [x] export) |
| CsvExporter | importCsv(path, table) | Import a CSV file into a table (backtick-quoted columns, safe VALUES) |
| SqlExporter | exportSql(path) | Dump all tables as INSERT statements to a SQL file. No CREATE TABLE (not driver-neutral). Uses LIMIT 1 for column detection. |
| ReconnectManager | shouldReconnect(pdoException) | Check if error code is 2002/2003/2013 |
| ReconnectManager | attemptReconnect(callable) | Retry connection using stored ConnectionConfig |
| ReconnectManager | setConnectionConfig(config) / lastConnectionConfig() | Store/retrieve connection config for reconnection |
| ReconnectException | — | Thrown when reconnection fails after MySQL connection error |
| StatementTimeout | execute(stmt, values) | Execute with wall-clock timeout via pcntl_alarm() |
| StatementTimeout | didTimeout() | Check if last execution timed out |
| StatementTimeoutException | — | Thrown when statement exceeds timeout and is canceled |
| Severity | toToastType() | Map to ToastType: Info→Info, Warning→Warning, Critical→Error |
| Alert | warning() / critical() / info() | Factory helpers for alert creation |
| Alert | isCritical() / isWarning() / isInfo() | Severity predicates |
| Alert | toToastMessage() | Format as "metric: message (X% > Y%)" |
| AlertThresholds | new() / default() / strict() | Factory presets: bare, 60%/80%, 50%/70% |
| AlertThresholds | connectionWarningThreshold() / connectionCriticalThreshold() | Connection usage ratio thresholds |
| AlertThresholds | withConnectionWarningThreshold() / withConnectionCriticalThreshold() | Fluent threshold setters (0.0–1.0) |
| AlertThresholds | abortedRateThreshold() / withAbortedRateThreshold() | Aborted connection rate threshold |
| AlertThresholds | slowQueryThreshold() / withSlowQueryThreshold() | Slow query time threshold in seconds |
| AlertThresholds | threadRunningThreshold() / withThreadRunningThreshold() | Thread running ratio threshold |
| AlertThresholds | connectionErrorsThreshold() / withConnectionErrorsThreshold() | Absolute connection error count threshold |
| AlertThresholds | watchedMetrics() / withWatchedMetrics() / watches() | Filter which metrics are actively watched |
| AlertThresholds | toastEnabled() / withToastEnabled() / toastPosition() / toastDuration() | Toast notification settings |
| AlertNotifier | new() / withDefaults() | Factory (muted by default when no factory provided) |
| AlertNotifier | notify(Alert) / notifyWarning() / notifyCritical() / notifyInfo() | Send notifications (all return new instance) |
| AlertNotifier | withMuted() / isMuted() | Mute state control |
| AlertNotifier | withToastFactory() | Late-bind toast factory |
| AlertNotifier | view(background, width, height) | Compose toast over viewport string |
| AlertNotifier | toast() / hasActiveAlert() | Direct toast access and state query |
| AlertManager | new() | Fresh manager with default thresholds |
| AlertManager | withThresholds() / withNotifier() | Attach threshold config and notifier |
| AlertManager | checkConnectionUsage(ConnectionCounters) | Evaluate connection counters, return array<string, Alert> |
| AlertManager | checkAllMetrics(statusVars, serverVars) | Evaluate SHOW GLOBAL STATUS/VARIABLES, return array<string, Alert> |
| AlertManager | checkAndDispatch(ConnectionCounters) | Combined check + notify, returns ['alerts', 'notifier'] |
| HistoryStoreInterface | save(snapshot) | Persist a status-variable snapshot (ts, recorded_at, variables JSON) |
| HistoryStoreInterface | query(since, until) | Retrieve snapshots within a DateTimeImmutable range |
| HistoryStoreInterface | prune(before) | Delete entries older than given DateTimeImmutable |
| HistoryStoreInterface | count() | Return total number of stored entries |
| HistoryStoreInterface | close() | Release held resources (e.g. close the SQLite database) |
| SqliteHistoryStore | __construct(dbPath) | Open or create the SQLite store: WAL, 5s busy timeout, private 0600 file / 0700 dir (a pre-existing loose file is tightened). An unusable store raises here: the launcher catches that at boot and runs history-less with a loud history recording DISABLED stderr warning; a store that dies only mid-session instead degrades per-write to the in-app query log via HistoryRecorder::record(). |
| SqliteHistoryStore | — | HistoryStoreInterface via SQLite. Schema: id, ts, recorded_at, variables (JSON). No automatic prune — call prune(before) or HistoryRecorder::pruneOlderThan(cutoff). |
| HistoryRecorder | record(snapshot) / recordFromProvider() | Persist snapshots directly or pulled from a wrapped StatusSnapshotProviderInterface; implements the same interface (currentSnapshot() / statusVariablesTs() / wasReset()) for downstream readers. |
| HistoryQuery | query(sinceTs, untilTs) | Raw snapshot rows in an epoch-seconds range |
| HistoryQuery | querySince(sinceTs) | Snapshots at or after a point in time |
| HistoryQuery | rate(variable, sinceTs, untilTs) | Per-second delta rate for one status variable across two snapshots (null on insufficient data) |
| PerfSchemaPage | new(context, ?detector, ?commitPlanner) | Factory. Validates PS accessibility via SELECT COUNT(*) FROM performance_schema.setup_instruments. 7 tabs: Easy Setup, Instruments, Consumers, Actors, Objects, Threads, Options. |
| PerfSchemaPage | update(Msg) | Handles keyboard: j/k nav rows, h/l and arrow keys cycle tabs, Space/Enter toggle, [ ] . easy-setup actions (enable full/disable/reset) on the Easy Setup tab, c commit (when dirty), r revert (when dirty), q back to Tables (App intercepts q in-app). Tab/Shift+Tab are page-level handlers that fire only in standalone use — in-app App consumes Tab (pane cycle) first. Returns [newPage, ?Closure]. |
| PerfSchemaPage | instruments() / consumers() / actors() / objects() / threads() / timers() | Read current tab's model list. |
| PerfSchemaPage | activeTab() / selectedRowIndex() / isReadOnly() / setupState() | Read page state: active tab name, cursor index, privilege status, detected PS setup state (fully/default/custom/disabled). |
| SetupTimers | new(name, timerName) | Factory. |
| SetupTimers | withTimerName(timerName) | Return new instance with updated timer. Marks dirty and sets changeType to CHANGE_UPDATE. No-op when timer name is unchanged. |
| SetupTimers | isDirty() | True if timer has been modified since load. |
| SetupTimers | changeType() | Returns CHANGE_UPDATE or CHANGE_NONE. |
| SetupTimers | commitStatements() | Returns ['UPDATE performance_schema.setup_timers SET `TIMER_NAME` = 'NANOSECOND' WHERE `NAME` = 'wait''] when dirty and changeType is CHANGE_UPDATE. Returns [] otherwise (including on MySQL ≥8.0 where instances are clean from performance_timers). |
| SetupTimers | nameUpper() / isCycle() | Helpers: timer name in uppercase, true if CYCLE timer. |
| SetupThreads | new(threadId, name, type, ?processlistId, ?processlistUser, ?processlistCommand, ?processlistInfo, instrumented=true) | Factory. instrumented defaults to true. |
| SetupThreads | withInstrumented(bool) | Return new instance with updated INSTRUMENTED flag. Marks dirty. No-op when state is unchanged. |
| SetupThreads | isDirty() | True if thread's INSTRUMENTED state has been modified. |
| SetupThreads | isForeground() / isBackground() / hasProcesslist() | Type predicates. |
| SetupThreads | instrumentedFragment() | Returns SQL fragment: THREAD_ID = 123 AND INSTRUMENTED = 'YES' (or 'NO'). Used by CommitPlanner to build a batch UPDATE ... WHERE IN() clause. |
| SetupThreads | commitStatements() | Returns [] — individual threads delegate to CommitPlanner for the batch IN() update. Stub for interface compatibility. |
| CommitPlanner | new(instruments, consumers, actors, objects) | Factory. Takes arrays of dirty-tracking model instances. |
| CommitPlanner | commitAll() | Generate all SQL statements for dirty instruments (anchored RLIKE), consumers (IN), actors (INSERT/UPDATE/DELETE), and objects (INSERT/UPDATE/DELETE). Returns list<array{sql:string, params:list<mixed>}> — fully parameterized with ? placeholders and bound values, no string interpolation. Returns [] when nothing is dirty. SetupTimers/SetupThreads wiring deferred to a planned follow-up. |
| CommitPlanner | commitInstruments() | Group dirty instruments by (enabled, timed) bucket; emit one UPDATE ... WHERE NAME RLIKE '^...$' per bucket. Pattern is anchored (^name$) and regex-escaped via preg_quote(); metacharacters like . / ( ) are matched literally. Returns list<array{sql:string, params:list<mixed>}>. |
| CommitPlanner | commitConsumers() | Group dirty consumers by enabled state; emit one UPDATE ... WHERE NAME IN (?,?,...) per group. All names bound as ? placeholders. Returns list<array{sql:string, params:list<mixed>}>. |
| CommitPlanner | commitActors() | Emit parameterized INSERT/UPDATE/DELETE for actors based on changeType(). All string values (HOST, USER, ROLE, ENABLED) bound as ?. Returns list<array{sql:string, params:list<mixed>}>. |
| CommitPlanner | commitObjects() | Emit parameterized INSERT/UPDATE/DELETE for objects based on changeType(). All string values (OBJECT_TYPE, OBJECT_SCHEMA, OBJECT_NAME, ENABLED, TIMED) bound as ?. Returns list<array{sql:string, params:list<mixed>}>. |
| CommitPlanner | isDirty() | True if any tracked model is dirty. |
Demos.
VHS-recorded GIF of the dashboard on a seeded in-memory database, regenerated automatically on every push that touches the source.