All 22 apps

CandySql

Terminal SQL client

inspired by jorgerojas26/lazysql sql sqlite mysql postgresql tui pdo

CandySql code coverage

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). The interaction model follows lazysql, a Go SQL terminal client; candy-sql is a native PHP project.

Install

composer require sugarcraft/candy-sql:@dev

Requires PHP 8.3 or newer, with ext-pdo_sqlite and ext-sqlite3, which the manifest requires. A MySQL target needs ext-pdo_mysql, and a PostgreSQL target needs ext-pdo_pgsql. Both are suggested rather than required, because a plain install may not need them. ext-pcntl is suggested as well: it arms the query timeout, and without it the timeout falls back to the driver's network timeout.

The :@dev suffix is needed while the release channel is dev-only. The sugar-* siblings track dev-master, and react/mysql is pinned to 0.7.x-dev, so a stable-only project cannot resolve the bare command.

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

# No database at hand: seed an in-memory SQLite and browse it
php examples/play.php
// 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();

A SQLite path must name an existing file. The launcher refuses a missing file rather than creating an empty database that would lose every write at exit. The :memory: form is the exception, and it gives a throwaway database.

Concepts

The app is a single model with four panes: Tables, Rows, Query and Admin. Tab cycles through them. The Tables pane lists tables and views. The Rows pane shows the first 100 rows of the selected table, and a table preview there is editable. The Query pane is an SQL editor. The Admin pane holds the server dashboards, and it is available only on MySQL and PostgreSQL. On SQLite the Admin pane answers through an empty-context fallback.

Every driver speaks one interface, DatabaseInterface, and the rest of the app works against that interface. The flavor, an enum of Flavor values, selects the schema queries, the explain output and the admin providers. Driver-specific behavior sits behind strategy objects such as SchemaBrowser, ExplainView and AdminProviderInterface.

Errors stay on the screen. A failed query writes its error to the status line and does not end the session. A connection lost mid-session is detected by its error code (2002, 2003 or 2013), and the session can reconnect. Strings from the server pass through CellValue::sanitize before they reach the terminal.

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.
ServerVersionParser 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/↑/↓), a sugar-widgets Tabs detail-tab bar (Details/Attributes/MDL, built with Tabs::interactive() so it publishes Mark zones for mouse clicks; Enter focuses it and opens a panel with the active tab's data for the selected thread, then Tab/Shift+Tab/1–3 switch tabs ahead of the pane cycle and page picker, Esc releases them; a left click on a tab label switches too, and the mouse is reported only while this page is on screen; the bar and panel are new UI — earlier releases had no detail-tab strip — and the panel stays inside the terminal height), 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).
MysqlAdminProviderAdminProviderInterface 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).
PostgresAdminProviderAdminProviderInterface 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 the private detectReset method of ServerContext, 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 (::standard(), ::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; retention is bounded automatically to the newest 10 000 rows and the last 72 hours, swept at open and after every insert; prune() / HistoryRecorder::pruneOlderThan() remain for an explicit cut). 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.

Tasks

Connect to a MySQL server with a password from the environment

Pass the password through CANDY_SQL_PASS rather than argv, so it stays out of /proc/<pid>/cmdline:

CANDY_SQL_PASS=secret vendor/bin/candy-sql --driver=mysql --user=root --db=mydb

Save a connection and dial it by name

Named connections live in $XDG_CONFIG_HOME/candy-sql/connections.json, or $HOME/.config/candy-sql/connections.json when XDG_CONFIG_HOME is unset. An entry names an environment variable with pass-env, and the password is read when the connection is dialed. Dial the entry with --connect=prod, or run with no arguments in a terminal to choose one from a picker. See Configuration for the fields.

Edit a cell in a table preview

  1. In the Tables pane, select a table and press Enter to load it into the Rows pane.
  2. Move the cell cursor with ←/→ or h/l, and press e. Type the new value. Ctrl+N stores NULL.
  3. Press Enter to show the UPDATE statement, and press Enter again to commit it. Nothing is written before the second Enter.

Row insert with o and row delete with D follow the same confirm-then-write flow. The Troubleshooting section lists the refusals.

Run a query and keep it as a favorite

Type SQL in the Query pane. Enter inserts a newline, and Ctrl+R, Ctrl+E or Ctrl+Enter runs the statement. Ctrl+F saves the text to the favorites list for the session. A statement with ? or :name placeholders opens a prompt for each parameter before it runs. An empty value binds NULL.

Export a table to CSV, or import a file

With rows on screen, press x in the Tables or Rows pane to open the export line, or press Ctrl+S from any pane to open the same line. Press i in the Tables or Rows pane to open the import line. In either line Enter submits and Esc closes it.

Read the recorded status history

Press H in the Tables, Rows or Admin pane to read the recorded status history. Its counter trend is folded into the Rows pane. Recording is on by default in the launcher. Pass --no-history to turn it off, or --history=PATH to choose the file. See Status-snapshot history.

Drive it from a script

The launcher is an interactive program. With stdout not a terminal it dials the connection and then refuses with exit status 2. To drive it from a script, run it under a pseudo-terminal, for example script -qec 'candy-sql app.sqlite' /dev/null. To render results from library code, use ResultTable::renderPlain(), which produces an escape-free grid.

API reference

The classes below are the public surface. App is the model. ConnectionFactory parses a DSN into a ConnectionConfig and opens a connection. The rest are strategy objects and value types the model calls.

ClassMethodDescription
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().
DatabaseInterfaceserverVersion()Get database server version
DatabaseInterfacedriverName()Get driver name (e.g., sqlite, mysql)
DatabaseInterfaceping()Check connection is alive
DatabaseInterfacedatabases()List available databases
DatabaseInterfacetables()List all tables
DatabaseInterfacerows(table, limit, offset)Get table rows
DatabaseInterfacequery(sql)Execute SQL query; returns list<array>|null — null signals a reconnectable connection error (2002/2003/2013), empty array means no rows
DatabaseInterfaceprepare(sql)Prepare SQL; returns PreparedStatementInterface|null — driver-neutral statement wrapper
PreparedStatementInterfaceexecute(params?)Execute with bound params; returns bool
PreparedStatementInterfacefetch()Fetch next row; returns array<string,mixed>|false
PreparedStatementInterfacefetchAll()Fetch all rows; returns list<array<string,mixed>>
PreparedStatementInterfacerowCount()Rows affected by last query
PreparedStatementInterfacecloseCursor()Close cursor, enabling re-execution
PdoPreparedStatement—PreparedStatementInterface via PDOStatement. All database implementations (MysqlDatabase, PostgresDatabase, SqliteDatabase) wrap their PDOStatement in this before returning from prepare().
Appstart(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)
SchemaBrowserrefresh()Load schema via driver-specific SchemaProviderInterface
SchemaBrowsernew(db, flavor)Static factory: browser bound to a Database and its Flavor
SchemaProviderInterfacetables(pdo)List all tables/views
SchemaProviderInterfacecolumns(pdo, table)Get columns for a table
SchemaProviderInterfaceindexes(pdo, table)Get indexes for a table
SchemaProviderInterfaceforeignKeys(pdo, table)Get foreign keys for a table
SqliteSchemaProvider—SchemaProviderInterface via PRAGMA queries
MysqlSchemaProvider—SchemaProviderInterface via INFORMATION_SCHEMA
PostgresSchemaProvider—SchemaProviderInterface via pg_catalog
SchemaBrowserdropTable(name)DROP table and re-refresh
SchemaTablecolumn(name)Find a column by name
ExplainViewrun(db, sql)Static: execute EXPLAIN through the driver-specific ExplainProviderInterface and return the view
ExplainProviderInterfaceexplain(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)
AdminProviderInterfaceflavor()Which database flavor this provider targets
AdminProviderInterfacefetchStatusVariables()All status variables (equivalent to SHOW GLOBAL STATUS; prefixed pg_stat_database.* keys on PostgreSQL)
AdminProviderInterfacefetchServerVariables()All server variables (equivalent to SHOW GLOBAL VARIABLES; pg_settings on PostgreSQL)
AdminProviderInterfacefetchProcesslist()Active server processes/connections — pg_stat_activity on PostgreSQL; prefers performance_schema.threads on MySQL, falls back to SHOW FULL PROCESSLIST
AdminProviderInterfacemaxConnections()The server's max_connections value (or equivalent)
AdminProviderInterfacestatusVariablesTs()Unix timestamp (float) when status variables were last fetched
AdminProviderInterfacewasReset()True when the server has restarted since the last poll (MySQL via Uptime going backwards; PostgreSQL always false — detection not implemented)
AdminProviderInterfacerefresh()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
ConnectionsPagenew(context, maxConnections?)Factory creating fully-wired instance with ProcesslistProvider, ConnectionActions, ConnectionDetailTabs, ConnectionCounters
ConnectionsPageupdate(Msg)Handle keyboard: j/k/↑/↓ navigate, f toggle filter, r refresh, y confirms a pending kill (any other key cancels). Enter focuses the detail-tab bar; while it is focused claimsKey() routes Tab/Shift+Tab/1–3 to it ahead of the pane cycle and page picker, and Esc releases them. A left-button press (page-relative coordinates) on a tab zone activates that tab. Returns [newPage, ?Closure]. Mirrors mysql-workbench client connections panel.
ConnectionsPagetable()Get the sugar-table Table with columns: Id, User, Host, DB, Command, Time, State, Info
ConnectionsPagefilters() / counters() / detailTab() / selectedThread()Read current filter state, counters, active detail tab, and selected process thread
ConnectionFiltersnew()Default filters: no hiding, no auto-refresh
ConnectionFilterswithHideSleeping(bool) / withHideBackground(bool) / withSkipFullInfo(bool) / withRefreshRate(float|null)Fluent filter setters — all return new immutable instance
ConnectionCountersfromSnapshot(snapshot, maxConnections)Factory from StatusSnapshot: reads Threads_*, Connections, Aborted_* variables
ConnectionCountersconnectionUsageRatio()Lazy-computed ratio (0.0–1.0) of threads_connected / max_connections
ConnectionCountersisConnectionUsageCritical()True when usage ≥80% (red threshold)
ConnectionDetailTabsdetails(processId)Basic thread info from performance_schema.threads — returns null on 1142/1146/1227
ConnectionDetailTabsattributes(processId)Session connect attrs from performance_schema.session_connect_attrs — returns null if no attrs or access denied
ConnectionDetailTabsmdlLocks(processId)Metadata locks from performance_schema.metadata_locks (primary) with fallback to information_schema.metadata_lock_info
ConnectionDetailTabsthreadStack(processId)Stack dump via sys.ps_thread_stack() — returns null if sys schema unavailable
ConnectionDetailTabsexplain(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).
ReportsPagenew(context, ?db)Factory. validate() only loads Catalog (file I/O) — no blocking db->query() on render path. report queries routed through AdminQueryCache async.
ReportsPageupdate(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.
ReportsPageexportToCsv()Export current report as RFC-4180 CSV string via CsvExporter::exportReportResultsToString(). Returns '' if no report loaded.
ReportRunnerrun(viewName, ?limit)Execute SELECT * FROM sys.<view> with unit formatting. Throws \InvalidArgumentException if view not in catalog, \RuntimeException if view not available on server.
ReportRunnerrunRaw(viewName, ?limit)Execute report without unit formatting — returns raw numeric values for sorting/calculation.
ReportRunnercanRun(viewName)True if report exists in catalog and its view is available on this server.
AvailabilityCheckerdiscoverViews()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.
AvailabilityCheckersysSchemaExists()True if sys schema is accessible (runs discoverViews() internally).
AvailabilityCheckerisViewAvailable(viewName)True if the named sys schema view exists on this server.
AvailabilityCheckeravailableFromCatalog(catalog)Return catalog reports whose views exist on this server.
AvailabilityCheckermissingFromCatalog(catalog)Return catalog reports whose views are missing on this server.
AvailabilityCheckerreset()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.
VariablesPagenew(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.
VariablesPageupdate(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.
VariableEditoredit(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.
VariableEditorpersist(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.
VariableEditorpersistOnly(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.
VariableEditorresetPersist(?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.
VariableEditoreditPreview(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').
VariableEditorisEditable(variableName)True if the variable has editable=true in the metadata catalog. Returns false when catalog is absent (safer default).
VariableMetadataisDynamic()True if the variable has Dynamic=true in metadata (can be changed at runtime via SET GLOBAL). Non-dynamic variables hit MySQL error 1238.
VariableMetadatainGroup(group)True if the variable belongs to the given group name.
Catalogload()Load variable metadata from data/variable_metadata.json. Throws \RuntimeException on corrupt/missing file.
Catalogget(variableName)Return VariableMetadata for a variable, or null if not in catalog.
Catalogall()Return all VariableMetadata entries keyed by variable name.
Cataloggroups()Return sorted list of all group names in the catalog.
CatalogisEditable(variableName)True if variable exists in catalog and VariableMetadata.editable is true.
CatalogisDynamic(variableName)True if variable exists in catalog and VariableMetadata.isDynamic() is true.
ExplainViewrender()Render plan as ANSI-colored string
ExplainViewtoArray()Return JSON-serializable plan rows (depth, tag, detail, indent)
ConnectionActionssetInstrumentation(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.
ConnectionActionskill(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.
ConnectionActionskillQuery(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.
ConnectionDetailTabsexplain(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
ConnectionFactoryfromDsn(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.
ConnectionFactoryfromConfig(config)Connect using a ConnectionConfig and return the driver's DatabaseInterface (sqlite, mysql or pgsql; any other driver throws InvalidArgumentException)
ConnectionFactoryfromArgv(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.
FlavordetectFromDriver(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.
ServerVersionisAtLeast($major, $minor = 0, $release = 0)Compare version integers (handles MariaDB 5.5.5- prefix). Lives on SugarCraft\Sql\Db\ServerVersion, not on the build-stamp SugarCraft\Sql\Version.
ResultTablefromRows(rows)Factory from a list of associative row arrays
ResultTablescrollLeft() / scrollRight()Scroll viewport by one column
ResultTablewithVisibleWidth(n) / withJsonPretty(bool) / withNullToken(s)Fluent configuration builders
ResultTablerender() / renderPlain()Render ANSI string or plain text
CsvExporterexportCsv(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)
CsvExporterexportReportResults(path, columns, rows)Write a result set to a CSV file with formula guard
CsvExporterexportReportResultsToString(columns, rows)Return a result set as an RFC-4180 CSV string (used by ReportsPage [x] export)
CsvExporterimportCsv(path, table)Import a CSV file into a table (backtick-quoted columns, safe VALUES)
SqlExporterexportSql(path)Dump all tables as INSERT statements to a SQL file. No CREATE TABLE (not driver-neutral). Uses LIMIT 1 for column detection.
ReconnectManagershouldReconnect(pdoException)Check if error code is 2002/2003/2013
ReconnectManagerattemptReconnect(callable)Retry connection using stored ConnectionConfig
ReconnectManagersetConnectionConfig(config) / lastConnectionConfig()Store/retrieve connection config for reconnection
ReconnectException—Thrown when reconnection fails after MySQL connection error
StatementTimeoutexecute(stmt, values)Execute with wall-clock timeout via pcntl_alarm()
StatementTimeoutdidTimeout()Check if last execution timed out
StatementTimeoutException—Thrown when statement exceeds timeout and is canceled
SeveritytoToastType()Map to ToastType: Info→Info, Warning→Warning, Critical→Error
Alertwarning() / critical() / info()Factory helpers for alert creation
AlertisCritical() / isWarning() / isInfo()Severity predicates
AlerttoToastMessage()Format as "metric: message (X% > Y%)"
AlertThresholdsnew() / standard() / strict()Factory presets: bare, 60%/80% (standard), 50%/70%
AlertThresholdsconnectionWarningThreshold() / connectionCriticalThreshold()Connection usage ratio thresholds
AlertThresholdswithConnectionWarningThreshold() / withConnectionCriticalThreshold()Fluent threshold setters (0.0–1.0)
AlertThresholdsabortedRateThreshold() / withAbortedRateThreshold()Aborted connection rate threshold
AlertThresholdsslowQueryThreshold() / withSlowQueryThreshold()Slow query time threshold in seconds
AlertThresholdsthreadRunningThreshold() / withThreadRunningThreshold()Thread running ratio threshold
AlertThresholdsconnectionErrorsThreshold() / withConnectionErrorsThreshold()Absolute connection error count threshold
AlertThresholdswatchedMetrics() / withWatchedMetrics() / watches()Filter which metrics are actively watched
AlertThresholdstoastEnabled() / withToastEnabled() / toastPosition() / toastDuration()Toast notification settings
AlertNotifiernew() / withDefaults()Factory (muted by default when no factory provided)
AlertNotifiernotify(Alert) / notifyWarning() / notifyCritical() / notifyInfo()Send notifications (all return new instance)
AlertNotifierwithMuted() / isMuted()Mute state control
AlertNotifierwithToastFactory()Late-bind toast factory
AlertNotifierview(background, width, height)Compose toast over viewport string
AlertNotifiertoast() / hasActiveAlert()Direct toast access and state query
AlertManagernew()Fresh manager with default thresholds
AlertManagerwithThresholds() / withNotifier()Attach threshold config and notifier
AlertManagercheckConnectionUsage(ConnectionCounters)Evaluate connection counters, return array<string, Alert>
AlertManagercheckAllMetrics(statusVars, serverVars)Evaluate SHOW GLOBAL STATUS/VARIABLES, return array<string, Alert>
AlertManagercheckAndDispatch(ConnectionCounters)Combined check + notify, returns ['alerts', 'notifier']
HistoryStoreInterfacesave(snapshot)Persist a status-variable snapshot (ts, recorded_at, variables JSON)
HistoryStoreInterfacequery(since, until)Retrieve snapshots within a DateTimeImmutable range
HistoryStoreInterfaceprune(before)Delete entries older than given DateTimeImmutable
HistoryStoreInterfacecount()Return total number of stored entries
HistoryStoreInterfaceclose()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). Bounded retention: the newest 10 000 rows and the last 72 hours, whichever discards more, swept at open and after every insert. Explicit pruning is still available through prune(before) and HistoryRecorder::pruneOlderThan(cutoff).
HistoryRecorderrecord(snapshot) / recordFromProvider()Persist snapshots directly or pulled from a wrapped StatusSnapshotProviderInterface; implements the same interface (currentSnapshot() / statusVariablesTs() / wasReset()) for downstream readers.
HistoryQueryquery(sinceTs, untilTs)Raw snapshot rows in an epoch-seconds range
HistoryQueryquerySince(sinceTs)Snapshots at or after a point in time
HistoryQueryrate(variable, sinceTs, untilTs)Per-second delta rate for one status variable across two snapshots (null on insufficient data)
PerfSchemaPagenew(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.
PerfSchemaPageupdate(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].
PerfSchemaPageinstruments() / consumers() / actors() / objects() / threads() / timers()Read current tab's model list.
PerfSchemaPageactiveTab() / selectedRowIndex() / isReadOnly() / setupState()Read page state: active tab name, cursor index, privilege status, detected PS setup state (fully/default/custom/disabled).
SetupTimersnew(name, timerName)Factory.
SetupTimerswithTimerName(timerName)Return new instance with updated timer. Marks dirty and sets changeType to CHANGE_UPDATE. No-op when timer name is unchanged.
SetupTimersisDirty()True if timer has been modified since load.
SetupTimerschangeType()Returns CHANGE_UPDATE or CHANGE_NONE.
SetupTimerscommitStatements()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).
SetupTimersnameUpper() / isCycle()Helpers: timer name in uppercase, true if CYCLE timer.
SetupThreadsnew(threadId, name, type, ?processlistId, ?processlistUser, ?processlistCommand, ?processlistInfo, instrumented=true)Factory. instrumented defaults to true.
SetupThreadswithInstrumented(bool)Return new instance with updated INSTRUMENTED flag. Marks dirty. No-op when state is unchanged.
SetupThreadsisDirty()True if thread's INSTRUMENTED state has been modified.
SetupThreadsisForeground() / isBackground() / hasProcesslist()Type predicates.
SetupThreadsinstrumentedFragment()Returns SQL fragment: THREAD_ID = 123 AND INSTRUMENTED = 'YES' (or 'NO'). Used by CommitPlanner to build a batch UPDATE ... WHERE IN() clause.
SetupThreadscommitStatements()Returns [] — individual threads delegate to CommitPlanner for the batch IN() update. Stub for interface compatibility.
CommitPlannernew(instruments, consumers, actors, objects)Factory. Takes arrays of dirty-tracking model instances.
CommitPlannercommitAll()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.
CommitPlannercommitInstruments()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>}>.
CommitPlannercommitConsumers()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>}>.
CommitPlannercommitActors()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>}>.
CommitPlannercommitObjects()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>}>.
CommitPlannerisDirty()True if any tracked model is dirty.

Only methods declared in candy-sql/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.

SugarCraft\Sql

App final class

SQL client as a SugarCraft Model - speaks SQLite, MySQL, MariaDB and PostgreSQL through the PDO drivers, with Workbench-style admin panels. Four focus panes:

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
__construct(public readonly ConnectionState $connection, public readonly BrowseState $browse = new BrowseState(), public readonly QueryState $query = new QueryState(), public readonly UiState $ui = new UiState(), public readonly AdminState $admin = new AdminState(), public readonly ExportState $io = new ExportState(), public readonly EditState $edit = new EditState())
withReadOnly(bool $readOnly): selfSQL-O03: browse-only session. The in-grid edit chords (e / o / D) refuse with a named status line while it is set. Query-pane statements are NOT filtered by it — for a hard guarantee connect as a read-only database user — so the flag is a guard rail against a slip, not a permission system.
static start(DatabaseInterface $db, Flavor $flavor = Flavor::Sqlite, ?HistoryRecorder $historyRecorder = null, ?string $sslMode = null): self
init(): ?\Closure
static builder(): AppBuilderCreate an App via a fluent builder.
update(Msg $msg): array
view(): string
frameMouseMode(): MouseModeThe mouse-tracking mode this frame wants: cell motion only while the Connections page is on screen (Admin pane, no help overlay), the one surface that answers clicks; off everywhere else.
adminPage(): PageBaseLazily create the admin page for the currently selected admin pane.
editor(): TextArea
subscriptions(): ?\SugarCraft\Core\Subscriptions

CellValue final class

Safe display formatting for arbitrary DB cell values.

MethodSummary
static display(mixed $val): stringTurn an arbitrary cell value into a safe, single-line display string: scalars cast, NULL labelled, arrays/objects JSON-encoded, then sanitize()d.
static sanitize(string $s): stringStrip everything that could corrupt the terminal from an already- stringified value: 1. repair invalid UTF-8 (binary data) so width/truncation stay sane, 2. collapse newlines to a visible marker (no extra rows), and 3. replace every other control byte (C0, DEL, C1) with a middle dot.

Completer final class

Completion for the Query pane (SQL-O04): keywords, plus the schema leg — table names after FROM/JOIN/INTO/UPDATE/TABLE, and columns in context (unqualified columns of the statement's tables, alias./table. qualified columns, the column list of INSERT INTO t (...)).

MethodSummary
static complete(string $sql, int $caret, array $tables = [], ?\Closure $columnsOf = null, ?Flavor $flavor = null): CompletionClassify the caret position in $sql and gather its candidates.
static candidates(string $prefix): arrayKeywords completing $prefix (case-insensitive substring up to the caret), roster order. Empty array when nothing matches.
static longestCommonPrefix(array $words): stringLongest common prefix of $words, compared case-insensitively and spelled as the first word writes it ('' when empty). The tab-completion courtesy: 'inse' -> 'INSERT' advances through several candidates in one press, and 'Users'/'users_old' advance to 'Users'.
static insertion(Completion $c): stringText to type for $c: the lone candidate, or the shared prefix when it is longer than what is already typed, or '' (ambiguous: list instead).
static wordAt(array $lines, int $row, int $col): stringThe word prefix at the caret: trailing [A-Za-z_] run of the text BEFORE column $col on line $lines[$row]. A word touching the caret must end at the caret (classic completion semantics: text after the caret is a different word).

Completion final class

One completion answer: what is being completed and what it can become.

MethodSummary
__construct(public readonly string $kind, public readonly string $prefix, public readonly array $candidates, public readonly string $qualifier = '', public readonly bool $inQuote = false, public readonly string $closeQuote = '')

Database final class

Deprecated thin alias over SqliteDatabase, kept for backwards compatibility with code written against this class before the driver implementations were extracted into DatabaseInterface.

MethodSummary
static open(string $path): self
__construct(private readonly \PDO $pdo)The PDO handle is deliberately private: exposing it publicly invited callers to bypass the DatabaseInterface contract (and public readonly on a mutable PDO only pretended to be immutable). Use the interface methods — query()/exec()/prepare()/quote()/lastInsertId() cover every former direct-PDO use in the repo.
csvExporter(): CsvExporter
sqlExporter(): SqlExporter
tables(): array
rows(string $table, int $limit = 100, int $offset = 0): array
query(string $sql): array|null
lastInsertId(): string|int
quote(string $value): string
exec(string $sql): int
close(): void
serverVersion(): string
driverName(): string
ping(): bool
databases(): array
prepare(string $sql): ?PreparedStatementInterface
importCsv(string $path, string $table): void
exportCsv(string $path, string $table): void
exportSql(string $path): void
dsn(): string
username(): string

ExplainRow final class

A single parsed row from EXPLAIN output.

MethodSummary
__construct(public readonly string $detail, public readonly int $depth, public readonly string $tag, public readonly string $indent, public readonly int $line)

ExplainView final class

Renders the output of database EXPLAIN commands as a readable ANSI tree with colour-coded operation types.

MethodSummary
__construct(array $raw)
static run(DatabaseInterface $db, string $sql): selfRun EXPLAIN against $db and return a new ExplainView.
render(): stringRender the plan as an ANSI string for TUI display.
toArray(): arrayReturn a JSON-serialisable array of the plan rows.

Lang final class

Per-library translation facade for candy-sql.

MethodSummary
static caption(string $english): stringLocalized display text for a metric caption. Captions are English identity tokens (counter ids, panel compositions and sampler series key on them), so the catalogs keep them verbatim and only the pixel-drawing call sites route through here; a caption with no caption.* entry (SQL verbs such as SELECT) renders as written.

Pane enum

Which of the four panes (tables list, rows preview, query editor, admin dashboard) has focus in the candy-sql shell. Tab cycles through them in the order returned by next().

Cases: Tables · Rows · Query · Admin

PHP also provides cases(), from() and tryFrom().

MethodSummary
next(): self

QueryParams final class

SQL-O23 (once-030): placeholder detection for the run-path bind prompt.

MethodSummary
static detect(string $sql): arrayOrdered placeholder kinds: null = positional, string = name.
static isMixed(array $detected): boolTrue when the list mixes positional and named placeholders.

Renderer final class

Stateless renderer for the candy-sql TUI shell.

MethodSummary
static setSize(int $cols, int $rows): voidRecord the authoritative terminal size handed to us by the framework.
static terminalSize(): arrayGet the terminal size. Once setSize() has been called with the framework's WindowSizeMsg, that value is authoritative. Otherwise detection is delegated to sugar-core's Tty façade, which selects the Posix/Windows backend and runs the full size ladder internally (FFI TIOCGWINSZ → COLUMNS/LINES → /dev/tty → stty → default). A hard default guards the unlikely case where the façade itself is unavailable.
static getTerminalSize(): arrayBC forwarder for the pre-rename accessor name.
static resetSizeCache(): voidReset the cached terminal size (call when the terminal may have resized).
static adminContentWidth(int $cols): intWidth of the admin page's content column — the region a full-screen admin page (e.g. the Performance Dashboard) renders into, to the right of the sidebar.
static render(App $a): string
static adminPageOrigin(App $a): arrayScreen offset of the admin page's frame: subtract it from a 1-based terminal (col, row) to get the page-relative 1-based cell App forwards to the page (App mouse routing).

ResultTable final class

Renders a SQL result set as a formatted table with:

MethodSummary
__construct(array $rows = [], int $offset = 0, int $visibleWidth = 120, int $maxCellWidth = self::DEFAULT_MAX_CELL, bool $jsonPretty = true, string $nullToken = self::NULL_TOKEN, int $colSpacing = 2, ?array $precomputedColWidths = null, int $rowOffset = 0)
static fromRows(array $rows): self
scrollLeft(): selfScroll left by one column.
scrollRight(): selfScroll right by one column.
withRows(array $rows): self
withRowOffset(int $rowOffset): selfMove the vertical render window (D-C2). The window always spans at most DEFAULT_PAGE_SIZE rows (or the viewport budget from self::withViewport(), whichever is tighter). D-C06: the live caller no longer page-aligns the offset — it hands the cursor to withViewport() so the window centres on it; a plain rowOffset still windows from the top of that page when no cursor is given.
withViewport(int $viewportRows, int $cursorRow = -1): selfHand the renderer the pane's height budget and the cursor's row index (D-C06). The unconditional 25-row page overflowed short panes: the sugar-cli Frame clipped everything below the budget away — the row counter, the help line and the query pane went dark, and the page-aligned window could park the cursor itself inside the clipped band. With a budget the window shrinks to fit (header, scroll hint and row counter all live inside the envelope) and slides to keep the cursor centred.
revealColumn(int $col): selfScroll just far enough that column $col is inside the visible window (SQL-O03: the cell cursor drives the horizontal scroll). A no-op when the column is already shown; the offset never overshoots it.
withCursorCol(int $col): selfHighlight column $col of the cursor row as the cell cursor (reverse video) and scroll it into view. Pass -1 for no highlight. Render-time state like the viewport: the other withers do not carry it, so the renderer re-applies it each frame from the browse state.
withOffset(int $offset): self
withVisibleWidth(int $width): self
withJsonPretty(bool $pretty): self
withNullToken(string $token): self
visibleColCount(): intNumber of visible columns given current offset and width.
canScrollLeft(): boolWhether left-scroll is possible.
canScrollRight(): boolWhether right-scroll is possible.
columns(): arrayAll column names (full set, not just visible).
colWidths(): arrayWidth of each column in characters.
visibleColumns(): arrayVisible columns given current scroll offset.
render(): stringRender the table as ANSI-coloured string.
renderPlain(): stringRender the table to a plain-text string (no ANSI) for export/copy.

SchemaBrowser final class

Schema browser with driver-aware schema introspection.

MethodSummary
__construct(private readonly DatabaseInterface $db, private readonly Flavor $flavor, private readonly SchemaProviderInterface $provider, public readonly array $tables = [])
static new(DatabaseInterface $db, Flavor $flavor): selfCreate a new SchemaBrowser with automatic provider selection based on flavor.
static providerFor(DatabaseInterface $db, Flavor $flavor): SchemaProviderInterfaceThe introspection provider for $flavor, for callers (the completer's lazy column lookup) that need one table's columns without a full refresh() of every table.
refresh(): selfRefresh schema for all user tables.
dropTable(string $name): selfDrop a table and return a refreshed browser.

SqlTokenizer final class

Tiny lossless SQL lexer for the completion context classifier (SQL-O04).

MethodSummary
static tokenize(string $sql): array
static unquote(array $tok): stringIdentifier text with its quotes stripped (word passes through).

Version final class

The --version answer, phar-aware (the DST-1 lesson from candy-code).

MethodSummary
static current(): string
static resolve(string $archive, string $composerAnswer): stringThe fused precedence as a pure function: an archive path (or '') and the composer-mode answer. Splitting it out lets the suite pin the chain — stamp wins, dev-build refuses, empty falls through — without minting an archive (the real build smoke covers the end-to-end shape).
static stampFrom(mixed $metadata): ?stringThe stamped version out of a build manifest, or null when the metadata carries no servable version (not an array, absent, empty, or the working-tree sentinel). Fail-closed: garbage metadata never prints.
static installedVersion(): stringThe composer-mode half: the installed package's own pretty version. Pinned by candy-sql/tests/BinWiringTest.php as the launcher's answer outside any archive (14a7e605a's contract, preserved through the phar fusion).
static hostArchive(): stringThe real-filesystem path of the phar archive hosting this install, or '' when this code is not running from an archive. Three identities, first answer wins (measured on PHP 8.3.6 while porting the candy-code DST-1 guard): Phar::running() names the archive for code executing inside it; in the stub region running() answers '' and __FILE__ names the self-naming archive; the phar:// prefix on this file's own __FILE__ covers shapes where a class was loaded from the archive but running() stayed empty. Delegated to the pure hostArchiveFrom() so every identity is pinable in-process (the candy-mail fusion shape).
static hostArchiveFrom(string $running, string $self): string

SugarCraft\Sql\Admin

AdminPane enum

Admin dashboard pages split into two sections: - Management: process list, variables, status, debug - Performance: query stats, dashboard, table stats, performance schema

Cases: ProcessList · Variables · Status · QueryStats · Dashboard · TableStats · PerfSchema · Debug

PHP also provides cases(), from() and tryFrom().

MethodSummary
label(): string
section(): AdminSection
static orderedCases(): arrayGet all panes in the order they are displayed in the sidebar.

AdminProviderInterface interface

Definitive interface for database-agnostic admin data access.

MethodSummary
flavor(): FlavorWhich database flavor this provider targets.
fetchStatusVariables(): arrayAll status variables (equivalent to SHOW GLOBAL STATUS).
fetchServerVariables(): arrayAll server variables (equivalent to SHOW GLOBAL VARIABLES).
fetchProcesslist(): arrayActive server processes/connections.
maxConnections(): intThe server's max_connections value (or equivalent).
statusVariablesTs(): floatUnix timestamp (float) when statusVariables was last fetched.
wasReset(): boolTrue when the server has restarted or variables were reset since last poll.
refresh(): voidForce a refresh of all cached values.

AdminQueryCache final class

Process-level coordinator bridging the synchronous render path to the asynchronous ReactPHP query layer for the admin panel.

MethodSummary
static instance(): self
static reset(): voidReset all state — intended for tests.
lookup(string $sql): ?arrayReturn cached rows for a query, or null when no usable value exists yet.
store(string $sql, array $rows): voidCache the rows a drain leg fetched for $sql.
markError(string $sql, string $message): voidMark a query leg as errored WITHOUT caching an empty result (client-012).
errorFor(string $sql): ?stringThe last known failure for $sql, or null when none. Cleared by a subsequent success (self::store()) or a self::invalidateConnection()/self::forget().
takePending(): arrayRemove and return the set of queries awaiting a fetch.
hasPending(): bool
forget(): voidDrop all cached results (e.g. on an explicit refresh).
storedAt(string $key): ?floatWhen the payload under a row-list SQL key last arrived, or null if never stored. The flattened snapshots have their own stamps — self::statusSnapshotAt()/self::serverSnapshotAt().
connection(string $key, \Closure $factory): AsyncConnectionLazily build and reuse the async connection for the given target so we don't open a fresh TCP/auth connection on every tick. The key encodes the flavor + DSN; a change rebuilds the connection.
serverContext(DatabaseInterface $db, \Closure $factory): ServerContextInterfaceSingle-slot memo for the synchronous-side ServerContext, keyed by the identity of the database handle it wraps.
invalidateConnection(): voidDrop the cached async connection so the next connection() call rebuilds it via its factory.
statusVariables(): ?arrayThe flattened SHOW GLOBAL STATUS map from the last async fetch, or null when nothing usable is cached.
storeStatusSnapshot(array $vars): void
statusSnapshotAt(): ?floatWhen the current status snapshot arrived — the payload's TRUE stamp for MINOR-1 honest adoption — or null when no snapshot was ever stored.
getStatusVariables(): ?arrayBC forwarder for the pre-rename accessor name.
serverVariables(): ?arrayThe flattened SHOW GLOBAL VARIABLES map from the last async fetch, or null when nothing usable is cached. Same staleness contract as self::statusVariables().
storeServerSnapshot(array $vars): void
serverSnapshotAt(): ?floatWhen the current server snapshot arrived, or null when never stored.
getServerVariables(): ?arrayBC forwarder for the pre-rename accessor name.

AdminSection enum

Sections for grouping admin dashboard pages.

Cases: Management · Performance

PHP also provides cases(), from() and tryFrom().

MethodSummary
label(): string

AsyncCachedConnection final class

A read-through DatabaseInterface that serves query() results from the async AdminQueryCache instead of hitting the database synchronously.

MethodSummary
__construct(private readonly DatabaseInterface $inner, private readonly ?AdminQueryCache $cache = null)
query(string $sql): arrayServe from the async cache; a miss is queued for background fetch.
tables(): array
rows(string $table, int $limit = 100, int $offset = 0): array
lastInsertId(): string|int
quote(string $value): string
exec(string $sql): int
close(): void
serverVersion(): string
driverName(): string
ping(): bool
databases(): array
prepare(string $sql): ?PreparedStatementInterface
dsn(): string
username(): string

AsyncCachingServerContext final class

ServerContext wrapper that returns cached status/server variables when available.

MethodSummary
__construct(private ServerContextInterface $inner, private ?array $cachedStatusVars = null, private ?array $cachedServerVars = null, private bool $isLoading = false, private ?AdminQueryCache $cache = null, ?float $statusVarsArrivedAt = null)
connection(): \SugarCraft\Sql\Db\DatabaseInterface
serverVariables(): array
statusVariables(): array
statusVariablesTs(): float
plugins(): array
version(): ServerVersion
flavor(): Flavor
versionString(): string
password(): string
wasReset(): bool
refresh(): void
isLoading(): bool
refreshFromLiveCache(): voidRe-pull the snapshot fields from the live AdminQueryCache.
hasCachedData(): bool

AsyncConnection interface

A non-blocking SQL connection that returns a ReactPHP promise of rows.

MethodSummary
query(string $sql, ?CancellationToken $cancellation = null): PromiseInterfaceExecute a query asynchronously.
close(): voidRetire the server session this wrapper holds.

CacheTtl final class

Shared cache-freshness windows for the admin data path.

CancellableQuery final class

Bridges sugar-async's CancellationToken onto a ReactPHP query promise.

MethodSummary
static wrap(PromiseInterface $promise, ?CancellationToken $cancellation, ?callable $onServerCancel = null): PromiseInterface

DsnParser final class

Shared DSN value extractor for PDO-style connection strings.

MethodSummary
static extract(string $dsn, string $key): ?stringExtract a value from a PDO-style DSN by key name.

EmptyServerContext final class

Placeholder context for unsupported database flavors (e.g., SQLite). Returns empty data for all queries to avoid render errors.

MethodSummary
__construct(private readonly ?\SugarCraft\Sql\Db\DatabaseInterface $db = null)
connection(): \SugarCraft\Sql\Db\DatabaseInterface
serverVariables(): array
statusVariables(): array
statusVariablesTs(): float
plugins(): array
version(): \SugarCraft\Sql\Db\ServerVersion
flavor(): \SugarCraft\Sql\Db\Flavor
versionString(): string
password(): string
wasReset(): bool
refresh(): void

Format final class

Formatting utilities for displaying database metrics.

MethodSummary
static scaleValue(float|int $value, int $decimals = 1): stringBinary (1024) scale with bare K/M/G/T suffix.
static siBytes(float|int $bytes, int $decimals = 1): stringDecimal (1000) SI bytes (B/KB/MB/GB/TB/PB).
static picoseconds(float|int $picoseconds): stringPicoseconds → human-readable duration.
static duration(float|int $seconds): stringSeconds → compact human-readable duration.
static plural(int $count, string $singular, ?string $plural = null): stringCount with a correctly pluralised noun: "1 instrument", "2 instruments".

PageBase abstract class

Base class for admin dashboard pages.

MethodSummary
__construct(public readonly ServerContextInterface $context)
refresh(): selfRefresh data and return new instance.
isModal(): boolWhether the page currently owns an open modal editing surface.
claimsKey(KeyMsg $msg): boolWhether this page claims $msg ahead of the App's own Admin-pane chords (the Tab pane cycle, the 1-{n} page picker, q, p, r).
releaseKeys(): selfThis page with every keyboard claim dropped (a focused component blurred), so claimsKey() answers false. App calls it when the user leaves the Admin pane; a page with no claims returns itself.
init(): ?\Closure
update(Msg $msg): array
view(): string
subscriptions(): ?\SugarCraft\Core\Subscriptions

PostgresServerContext final class

PostgreSQL adapter that implements ServerContextInterface.

MethodSummary
__construct(private readonly PostgresAdminProvider $provider, private readonly DatabaseInterface $connection, private readonly string $versionString = '')
static new(DatabaseInterface $connection, PostgresAdminProvider $provider): selfCreate a new PostgresServerContext from a database connection.
connection(): DatabaseInterface
serverVariables(): arraypg_settings with an in-window TTL cache (fail-open).
statusVariables(): arraypg_stat_database snapshot with an in-window TTL cache (fail-open).
statusVariablesTs(): float
plugins(): array
version(): ServerVersion
flavor(): Flavor
versionString(): string
password(): string
wasReset(): bool
refresh(): void

QueryCancelledException final class

Rejection reason for an async query aborted via a cancellation token.

QueryLogger final class

Simple query logger for debugging admin pane queries.

MethodSummary
static log(string $type, string $sql, int $rows, ?string $error = null): voidLog a query execution.
static entries(): arrayGet all logged entries.
static errorEntries(): arrayThe error-pinned lane: every entry that carried an error, immune to housekeeping scroll-out from the main ring (client-032).
static getEntries(): arrayBC forwarder for the pre-rename accessor name.
static clear(): voidClear all log entries.
static displayLines(): arrayGet entries formatted for display.
static getDisplayLines(): arrayBC forwarder for the pre-rename accessor name.

QueryTimeout final class

Deadline wrapper for async admin/query promises.

MethodSummary
static wrap(PromiseInterface $promise, float $seconds, ?LoopInterface $loop = null, ?callable $onTimeout = null): PromiseInterfaceApply a deadline to a query promise.

ReactMysqlConnection final class

Async MySQL connection wrapper using react/mysql.

MethodSummary
__construct(string $dsn, string $username, string $password, ?LoopInterface $loop = null, private readonly float $queryTimeout = QueryTimeout::DEFAULT_SECONDS, ?callable $killClientFactory = null, private readonly float $killTimeout = self::KILL_TIMEOUT_SECONDS, ?callable $clientFactory = null)
query(string $sql, ?CancellationToken $cancellation = null): PromiseInterfaceExecute a query asynchronously.
close(): voidRetire the server session (admindata-004).

ReactPostgresConnection final class

Async PostgreSQL connection wrapper using voryx/pgasync.

MethodSummary
__construct(string $dsn, string $username = '', string $password = '', ?LoopInterface $loop = null, private readonly float $queryTimeout = QueryTimeout::DEFAULT_SECONDS)
query(string $sql, ?CancellationToken $cancellation = null): PromiseInterfaceExecute a query asynchronously.
close(): voidRetire the server session (admindata-004).

RowNavigable interface

Marker for admin pages that own row-level j/k/Up/Down navigation.

Sampler final class

Computes rate-per-second deltas from successive status snapshots.

MethodSummary
__construct(private readonly StatusSnapshotProviderInterface $provider)
sample(): ?arrayCompute rates from the latest polled snapshot.
resetAll(): voidReset state on detected server restart.
wasReset(): boolCheck if a server restart was detected since last check.
isFirstSample(): boolCheck if this is the first sample (no prior data).

ServerContext final class

MySQL-focused ServerContext implementation.

MethodSummary
__construct(private readonly DatabaseInterface $connection, private readonly ?Flavor $flavor = null)
connection(): DatabaseInterface
serverVariables(): arraySHOW GLOBAL VARIABLES with an in-window TTL cache (fail-open).
statusVariables(): arraySHOW GLOBAL STATUS with an in-window TTL cache (fail-open).
statusVariablesTs(): float
plugins(): array
version(): ServerVersion
flavor(): Flavor
versionString(): string
password(): string
wasReset(): bool
seedStatusSnapshot(array $statusVars, float $fetchedAt): voidAdopt a snapshot the async admin pipeline fetched elsewhere (SQL-A03).
lastUptime(): ?intGet the last known server uptime.
refresh(): voidForce a refresh of all cached values.

ServerContextInterface interface

Read-only context for a database server's runtime state.

MethodSummary
connection(): \SugarCraft\Sql\Db\DatabaseInterfaceGet the database connection this context is bound to.
serverVariables(): arrayAll SHOW GLOBAL VARIABLES as key => value.
statusVariables(): arrayAll SHOW GLOBAL STATUS as key => value.
statusVariablesTs(): floatUnix timestamp (float) when statusVariables was last fetched.
plugins(): arrayAll SHOW PLUGINS as list of row arrays.
version(): \SugarCraft\Sql\Db\ServerVersionParsed server version.
flavor(): \SugarCraft\Sql\Db\FlavorDetected database flavor.
versionString(): stringRaw version string as returned by the server.
password(): stringGet the database password for async connection creation.
wasReset(): boolTrue when SHOW GLOBAL STATUS returned different Uptime than last poll (server was restarted or variables were reset).
refresh(): voidForce a refresh of all cached values.

ServerStatusSnapshotAdapter final class

Adapter that wraps a ServerContextInterface to provide StatusSnapshotProviderInterface.

MethodSummary
__construct(private readonly ServerContextInterface $context)
currentSnapshot(): ?array
statusVariablesTs(): float
wasReset(): bool

StatusSnapshot final readonly class

Immutable snapshot of SHOW GLOBAL STATUS at a point in time.

MethodSummary
__construct(public array $variables, public float $ts)
get(string $key): ?stringGet a variable value or null if not present.
int(string $key): ?intGet a variable as int, or null if not present or not numeric.
getInt(string $key): ?intBC forwarder for the pre-rename accessor name.
float(string $key): ?floatGet a variable as float, or null if not present or not numeric.
getFloat(string $key): ?floatBC forwarder for the pre-rename accessor name.
has(string $key): boolCheck if a variable exists in this snapshot.
elapsedSince(StatusSnapshot $older): floatCompute elapsed time between this snapshot and another.
delta(StatusSnapshot $previous): arrayCreate a delta snapshot (current - previous) for numeric values.

StatusSnapshotProviderInterface interface

Provides status snapshots for polling and rate sampling.

MethodSummary
currentSnapshot(): ?arrayGet the most recent status snapshot.
statusVariablesTs(): floatGet the timestamp of the most recent snapshot.
wasReset(): boolCheck if the server was restarted since last poll.

SugarCraft\Sql\Admin\Alerts

Alert final class

Represents a fired alert threshold notification.

MethodSummary
__construct(public readonly Severity $severity, public readonly string $metric, public readonly string $message, public readonly float $value, public readonly float $threshold, public readonly \DateTimeImmutable $firedAt = new \DateTimeImmutable(), public readonly MetricKind $metricKind = MetricKind::Ratio)
static warning(string $metric, string $message, float $value, float $threshold, MetricKind $kind = MetricKind::Ratio): selfCreate a warning-level alert.
static critical(string $metric, string $message, float $value, float $threshold, MetricKind $kind = MetricKind::Ratio): selfCreate a critical-level alert.
static info(string $metric, string $message, float $value, float $threshold, MetricKind $kind = MetricKind::Ratio): selfCreate an info-level alert.
isCritical(): boolTrue when this is a critical-severity alert.
isWarning(): boolTrue when this is a warning-severity alert.
isInfo(): boolTrue when this is an info-severity alert.
toToastMessage(): stringFormat alert as a short one-liner suitable for toast display.

AlertManager final class

Stateless alert checker — evaluates metrics against thresholds.

MethodSummary
static new(): selfFresh AlertManager with default thresholds and no notifier.
withThresholds(AlertThresholds $t): selfReturn a new AlertManager with the given threshold configuration.
withFlavor(?Flavor $flavor): selfReturn a new AlertManager that reads the given flavor's metric keys.
flavor(): ?Flavor
withNotifier(AlertNotifierInterface $n): selfReturn a new AlertManager with the given notifier.
checkConnectionUsage(ConnectionCounters $counters): arrayCheck connection counters and fire alerts for any thresholds exceeded.
checkAllMetrics(array $statusVariables, array $serverVariables): arrayCheck status and server variables for threshold violations.
thresholds(): AlertThresholdsGet the current thresholds.
notifier(): ?AlertNotifierInterfaceGet the current notifier, if set.
checkAndDispatch(ConnectionCounters $counters): arrayDispatch all alerts to the notifier and return a new notifier with all alerts sent.

AlertNotifier final class

Sends alert notifications via SugarCraft\Toast\Toast.

MethodSummary
static new(?\Closure $toastFactory = null): selfCreate a new notifier with no factory (mute-safe, no-op until factory set). Returns a muted notifier by default - use withMuted(false) to enable.
static withDefaults(?\Closure $toastFactory = null, Position $position = Position::TopRight, ?float $duration = 5.0, bool $muted = true): selfCreate a notifier with a default Toast factory using standard position/duration.
notify(Alert $alert): selfNotify with a pre-built Alert.
notifyWarning(string $message): selfSend a warning notification.
notifyCritical(string $message): selfSend a critical notification.
notifyError(string $message): selfSend an error notification.
notifyInfo(string $message): selfSend an info notification.
isMuted(): boolTrue when notifications are muted.
withMuted(bool $muted): selfReturn a new notifier with the given mute state.
withToastFactory(\Closure $factory): selfReturn a new notifier with an updated toast factory.
view(string $background, int $viewportWidth = 80, int $viewportHeight = 24): stringCompose the current toast state over a background viewport string.
toast(): ?ToastGet the underlying Toast instance for direct manipulation.
hasActiveAlert(): boolTrue if any alerts have been queued.

AlertNotifierInterface interface

Contract for dispatching alert notifications.

MethodSummary
notify(Alert $alert): selfDispatch a pre-built Alert; returns a new notifier carrying it.
notifyWarning(string $message): self
notifyCritical(string $message): self
notifyError(string $message): self
notifyInfo(string $message): self
isMuted(): boolTrue when notifications are suppressed.
withMuted(bool $muted): self
view(string $background, int $viewportWidth = 80, int $viewportHeight = 24): stringCompose the current toast state over a background viewport string.
toast(): ?ToastThe underlying Toast, or null if none has been created.
hasActiveAlert(): boolTrue if any alert is currently queued.

AlertThresholds final class

Immutable threshold configuration for alert conditions.

MethodSummary
static new(): selfFresh instance with no explicit thresholds set.
static standard(): selfStandard thresholds suitable for most environments.
static strict(): selfStricter thresholds for sensitive/production environments.
connectionWarningThreshold(): floatWarning threshold for connection usage ratio (0.0–1.0).
withConnectionWarningThreshold(float $value): self
connectionCriticalThreshold(): floatCritical threshold for connection usage ratio (0.0–1.0).
withConnectionCriticalThreshold(float $value): self
abortedRateThreshold(): floatAborted connection rate threshold (0.0–1.0+).
withAbortedRateThreshold(float $value): self
slowQueryThreshold(): floatSlow query time threshold in seconds.
withSlowQueryThreshold(float $value): self
threadRunningThreshold(): floatThread running threshold as ratio of max_connections (0.0–1.0).
withThreadRunningThreshold(float $value): self
connectionErrorsThreshold(): intConnection errors threshold (absolute count).
withConnectionErrorsThreshold(int $value): self
watchedMetrics(): arrayWhich metrics to actively watch.
withWatchedMetrics(array $metrics): self
watches(string $metric): boolTrue if this threshold watches the given metric name.
toastEnabled(): boolTrue when toast notifications are enabled.
withToastEnabled(bool $enabled): self
toastPosition(): PositionScreen position for toast notifications.
withToastPosition(Position $pos): self
toastDuration(): ?floatAuto-dismiss duration in seconds, or null for no auto-dismiss.
withToastDuration(?float $seconds): self

MetricKind enum

Describes the semantic kind of a metric, controlling how it is formatted in toast messages and other user-facing displays.

Cases: Ratio · Seconds · Count

PHP also provides cases().

Severity enum

Alert severity tiers.

Cases: Info · Warning · Critical

PHP also provides cases().

MethodSummary
toToastType(): \SugarCraft\Toast\ToastTypeConvert to sugar-toast ToastType.

SugarCraft\Sql\Admin\Calc

CacheHitRate final class

Computes cache hit rate as a percentage: hits / (hits + reads) * 100.

MethodSummary
__construct(private readonly string $hitKey, private readonly string $readKey)
compute(array $current, array $previous, float $elapsed): floatCompute the cache hit percentage.

HostLoadMode enum

Which source feeds the CPU/Load column.

Cases: HostProc · BusyProxy

PHP also provides cases(), from() and tryFrom().

HostLoadSampler final class

Collects the CPU/Load series for Workbench's Server Status parity.

MethodSummary
static local(?string $loadavgPath = null, ?string $statPath = null, ?\Closure $wallClock = null): selfSample the machine's own /proc counters.
static proxy(?\Closure $wallClock = null): selfRemote server: busy-proxy only, never touches the filesystem.
static forDsn(string $dsn, ?\Closure $wallClock = null): selfChoose the mode from a DSN — the boundary parse that keeps every later call trusted (no re-inspecting the DSN inside sample()).
sample(?array $statusVars, ?array $serverVars): voidAppend one sample. Local mode reads /proc; proxy mode consumes the latest status/server variable snapshots.
mode(): HostLoadMode
loadWindow(): array
busyWindow(): array
latestLoad(): ?float
latestBusy(): ?float
lastSampleAt(): ?float

InnoDBBufferPoolUsageBytes final class

Computes the InnoDB Buffer Pool usage as a percentage using byte-based values.

MethodSummary
__construct(private readonly string $bytesDataKey = 'Innodb_buffer_pool_bytes_data', private readonly string $pageSizeKey = 'Innodb_page_size', private readonly string $pagesTotalKey = 'Innodb_buffer_pool_pages_total')
compute(array $current, array $previous, float $elapsed): floatCompute the buffer pool usage percentage.

MakeTuple final class

Factory for creating tuple rate computations.

MethodSummary
__construct(private readonly string $separator = ',')
addRate(string $key): selfAdd a simple rate computation.
addTupleRate(string $key): selfAdd a tuple rate computation.
addRateAs(string $alias, string $key): selfAdd a rate under a display alias, decoupling the series name from the status key (e.g. 'select' for Com_select) so dashboard legends read like Workbench's 'select,insert,update,delete,… x/s' labels.
addRateSum(string $alias, string ...$keys): selfAdd one summed series over several keys (e.g. 'create' folding every Com_create_* command into a single DDL line, as Workbench does). Missing keys contribute 0.0 (RatePerSecond's contract), so a version lacking one member command simply plots the rest.
compute(array $current, array $previous, float $elapsed): arrayCompute all rates from a current and previous snapshot.
updateLast(array $snapshot): voidUpdate internal state from a snapshot.

RatePerSecond final class

Computes the rate of change (per second) for a status variable.

MethodSummary
__construct(public readonly string $key)
compute(array $current, array $previous, float $elapsed): floatCompute the rate using precompiled closure.
updateLast(array $snapshot): voidUpdate last known value from a snapshot.
isInitialized(): boolCheck if this rate has been initialized with a value.
lastValue(): floatGet the last known value.

StatusVar final class

Looks up a raw status variable value from the current snapshot.

MethodSummary
__construct(public readonly string $key)
compute(array $current, array $previous, float $elapsed): stringLook up the current value of the status variable.
computeInt(array $current, array $previous, float $elapsed): intGet the raw value as an integer.
computeFloat(array $current, array $previous, float $elapsed): floatGet the raw value as a float.
exists(array $current): boolCheck if the key exists in the current snapshot.

TableOpenCacheHitRate final class

Computes the Table Open Cache hit ratio as a percentage.

MethodSummary
__construct(private readonly string $hitKey = 'Table_open_cache_hits', private readonly string $missKey = 'Table_open_cache_misses')
compute(array $current, array $previous, float $elapsed): floatCompute the cache hit percentage.

TupleRatePerSecond final class

Computes per-second rates for tuple-structured status variables.

MethodSummary
__construct(private readonly string $key, private readonly string $separator = ',')
compute(array $current, array $previous, float $elapsed): arrayCompute tuple rates using precompiled closure.
updateLast(array $snapshot): voidUpdate internal tuple state from a snapshot.
isInitialized(): bool
lastTuples(): array

SugarCraft\Sql\Admin\Connections

ConnectionActions final class

Actions on processlist threads: KILL, KILL QUERY, instrumentation toggle.

MethodSummary
__construct(private readonly ServerContextInterface $context)
static new(ServerContextInterface $context): selfCreate a new instance with default context.
kill(int|string $threadId, bool $isBackground): boolKILL a thread (disconnect).
killQuery(int|string $threadId, bool $isBackground): boolKILL QUERY a thread (cancel running statement, keep connection).
setInstrumentation(bool $enabled, int|string $threadId): boolEnable or disable performance_schema instrumentation for a specific thread.
isInstrumentationEnabled(): ?boolCheck if instrumentation is currently enabled.

ConnectionCounters final class

Connection-related counters from SHOW GLOBAL STATUS.

MethodSummary
__construct(public readonly int $threadsConnected, public readonly int $threadsRunning, public readonly int $threadsCached, public readonly int $threadsCreated, public readonly int $connections, public readonly int $maxConnections, public readonly int $abortedClients, public readonly int $abortedConnects, public readonly int $connectionErrorsTotal, public readonly int $connectionErrorsMax, private readonly ?StatusSnapshot $snapshot)
static fromSnapshot(StatusSnapshot $snapshot, int $maxConnections = 151): selfCreate from a StatusSnapshot.
connectionUsageRatio(): floatConnection usage ratio (0.0-1.0) computed lazily.
isConnectionUsageCritical(): boolTrue when connection usage is above 80% (critical threshold).
abortedConnectionRate(): floatAborted connection rate per connection (0.0-1.0+).

ConnectionDetailTabs final class

Detail tabs for a processlist thread: Details, Attributes, MDL locks.

MethodSummary
__construct(private readonly ServerContextInterface $context)
static new(ServerContextInterface $context): selfCreate a new instance with default context.
details(int|string $processId): ?arrayTab: basic thread details for a processlist ID.
getDetails(int|string $processId): ?arrayBC forwarder for the pre-rename accessor name.
attributes(int|string $processId): ?arrayTab: session connect attributes for a processlist ID.
getAttributes(int|string $processId): ?arrayBC forwarder for the pre-rename accessor name.
mdlLocks(int|string $processId): ?arrayTab: metadata locks held by a processlist ID.
getMdlLocks(int|string $processId): ?arrayBC forwarder for the pre-rename accessor name.
threadStack(int|string $processId): ?stringGet thread stack dump via sys.ps_thread_stack().
getThreadStack(int|string $processId): ?stringBC forwarder for the pre-rename accessor name.
explain(int|string $processId): ?arrayGet EXPLAIN output for a thread's current query.
getExplain(int|string $processId): ?arrayBC forwarder for the pre-rename accessor name.

ConnectionFilters final class

User-configurable filters for the connections view.

MethodSummary
static new(): selfCreate with default settings (no filtering, no auto-refresh).
withHideSleeping(bool $hide): selfReturn a new instance with hide-sleeping toggled.
withHideBackground(bool $hide): selfReturn a new instance with hide-background toggled.
withSkipFullInfo(bool $skip): selfReturn a new instance with skip-full-info toggled.
withRefreshRate(?float $rate): selfReturn a new instance with refresh rate set.
isRefreshEnabled(): boolTrue when refresh is enabled (non-null rate).

ConnectionsPage final class

Connections page component integrating processlist, counters, filters, and actions.

MethodSummary
isModal(): boolThe kill confirmation is armed — it owns every keystroke.
__construct(ServerContextInterface $context, private readonly ?int $maxConnections = 151)
static new(ServerContextInterface $context, ?int $maxConnections = 151): selfCreate a new connections page with standard dependencies.
table(): TableGet the processlist table with current filters applied.
getTable(): TableBC forwarder for the pre-rename accessor name.
counters(): ConnectionCountersGet connection counters.
filters(): ConnectionFiltersGet current filters.
withFilters(ConnectionFilters $filters): selfReturn a new instance with updated filters.
detailTab(): stringGet the current detail tab.
withDetailTab(string $tab): selfReturn a new instance with the detail tab set. An open panel is refetched for the new tab, so the bar and the panel never disagree; a closed panel stays closed.
detailTabBar(): TabsThe detail-tab bar, zones attached. Its Tabs::view() carries the Mark zone markers a host scans; the page's own view() renders the same bar without them.
detailLines(): ?arrayThe open detail panel's lines (the active tab's data for the selected thread), or null while the panel is closed.
releaseKeys(): selfBlur the detail-tab bar and close its panel, so the page claims no key. App calls this when the user leaves the Admin pane: a bar left focused there would keep claiming Tab and 1-3 on the way back.
detailTabsFocused(): boolTrue while the detail-tab bar owns the tab keys (after Enter, until Esc).
claimsKey(KeyMsg $msg): boolWhile the detail-tab bar is focused the page claims the keys that drive it — Tab, Shift+Tab and the digits 1-3 — so App routes them here instead of cycling panes or picking an admin page. A blurred bar claims nothing, and neither does a focused bar the page does not paint: while view() shows the loading or error screen the bar is hidden, so Tab stays the pane cycle the status line advertises.
update(Msg $msg): arrayHandle keyboard shortcuts for connection navigation and filtering.
selectedThread(): ?ProcesslistResultGet the selected thread for detail view.
selectedIndex(): intGet the current selected index in the filtered processlist.
withSelectedIndex(int $index): selfSelect a thread by index in the current filtered list.
filteredProcesslist(): arrayGet the processlist rows with current filters applied.
refresh(): selfRefresh processlist data.
withHeightBudget(?int $rows): selfThe page with a height budget: the most rows its frame may take, or null for no limit (standalone use and tests).
init(): ?\Closure
view(): string
subscriptions(): ?\SugarCraft\Core\Subscriptions

ProcesslistProvider final class

Fetches server processlist via performance_schema or SHOW FULL PROCESSLIST.

MethodSummary
static processlistSql(): stringThe exact PS-path statement, exposed so consumers that key on it (the async-cache mirror in tests) share one source instead of re-typing.
__construct(private readonly ServerContextInterface $context)
static new(ServerContextInterface $context): selfCreate a new instance with default context.
fetchAll(): arrayFetch all processlist rows.
refresh(): selfClear cached PS availability and force re-detection on next fetch.

ProcesslistResult final class

Value object holding a single processlist row.

MethodSummary
__construct(public readonly int|string $processId, public readonly int|string $threadId, string $user, string $host, string $database, string $command, public readonly int $time, string $state, string $info, string $connectionAttr, public readonly bool $isPS, public readonly bool $isBackground, public readonly bool $infoTruncated)
static fromPSRow(array $row): selfCreate from a performance_schema.threads row.
static fromShowProcesslist(array $row): selfCreate from SHOW FULL PROCESSLIST row.
static fromPostgresRow(array $row): selfCreate from a normalized Postgres processlist row.
isBackground(): bool

SugarCraft\Sql\Admin\Dashboard

CounterCell final class

Renders a counter widget with K/M/G scaling.

MethodSummary
__construct(private readonly Widget $widget, private readonly int $decimals = 1)
ingest(array $current, array $previous, float $elapsed): selfIngest a new value from the widget's calc.
ingestFromSnapshot(\SugarCraft\Sql\Admin\StatusSnapshot $current, \SugarCraft\Sql\Admin\StatusSnapshot $previous): selfIngest from status snapshots.
reset(): selfReset the counter (call on server restart).
hasValue(): boolCheck if the counter has a value.
lastValue(): floatGet the last ingested value.
rawFormatted(): stringGet the raw formatted value using the widget's format.
scaledFormatted(string $unit = ''): stringFormat the value with K/M/G scaling applied.
view(): stringRender the counter as a string (alias for scaledFormatted).
__toString(): stringRender as string.
widget(): WidgetGet the associated widget.

DashboardPage final class

Performance Dashboard page with 3-column layout.

MethodSummary
__construct(ServerContextInterface $context, ?ServerVersion $version = null)
view(): string
update(\SugarCraft\Core\Msg $msg): array
withTogglePause(): self
withPaused(bool $paused): self
withReset(): self
withClearAlerts(): self
withAlertNotifier(AlertNotifierInterface $notifier): selfReturn a new DashboardPage with the given alert notifier.
isPaused(): bool
pendingAlerts(): array
alertCount(): int
alertNotifier(): AlertNotifierInterface
refresh(): selfRefresh data and return new instance.
isModal(): boolWhether the page currently owns an open modal editing surface.
claimsKey(KeyMsg $msg): boolWhether this page claims $msg ahead of the App's own Admin-pane chords (the Tab pane cycle, the 1-{n} page picker, q, p, r).
releaseKeys(): selfThis page with every keyboard claim dropped (a focused component blurred), so claimsKey() answers false. App calls it when the user leaves the Admin pane; a page with no claims returns itself.
init(): ?\Closure
subscriptions(): ?\SugarCraft\Core\Subscriptions

MeterCell final class

Renders round and level meter widgets using sugar-dashboard chart components.

MethodSummary
__construct(private readonly Widget $widget, private readonly ?float $maxOverride = null)
ingest(array $current, array $previous, float $elapsed, ?array $serverVars = null): selfIngest a new value, computing ratio if max is available.
ingestFromSnapshot(\SugarCraft\Sql\Admin\StatusSnapshot $current, \SugarCraft\Sql\Admin\StatusSnapshot $previous, ?array $serverVars = null): selfIngest from status snapshots with server variables.
withRatio(float $ratio, ?float $value = null, ?float $max = null): selfSet the ratio directly (for level meters that get ratio from a different source).
reset(): selfReset the meter (call on server restart).
hasValue(): boolCheck if the meter has a value.
ratio(): floatGet the current ratio (0.0 to 1.0).
percentage(): intGet the percentage (0 to 100).
value(): floatGet the current raw value.
max(): floatGet the resolved maximum.
viewRound(int $size = 14): stringRender as a round meter (donut ring with the percentage in the hole).
viewLevel(int $width = 20): stringRender as a level/horizontal meter (Gauge).
viewMeter(int $height = 12): stringRender as a vertical meter (Meter).
view(): stringRender using the appropriate method based on widget kind.
__toString(): stringRender as string.
widget(): WidgetGet the associated widget.

MultiSeriesCell final class

Renders a timeline widget as a multi-series braille line graph.

MethodSummary
__construct(private readonly Widget $widget, private readonly int $windowSize = self::DEFAULT_WINDOW, private readonly int $width = 40, private readonly int $height = 6)
ingest(array $current, array $previous, float $elapsed): selfIngest one sample per series from the current/previous snapshots.
ingestFromSnapshot(StatusSnapshot $current, StatusSnapshot $previous): selfIngest from a StatusSnapshot pair (mirrors TimeSeriesCell).
view(?int $maxCells = null): stringRender the graph (plus a legend line when it fits).
seriesNames(): array
count(): intTotal samples across all series (the dashboard-reload pin).
isEmpty(): bool
latest(string $name): ?floatLatest sample of one series, or null when it has none yet.
ceiling(): floatCurrent auto-scale ceiling (shared by all series).
maxSeen(): float
widget(): Widget
reset(): selfClear every window and scale (call on [r] reset / server restart).
__toString(): string

PostgresWidgetCatalog final class

PostgreSQL widget catalog for the Performance Dashboard.

MethodSummary
io(): arrayI/O panel widgets (10 widgets).
transactions(): arrayTransactions panel widgets (7 widgets).
cache(): arrayCache panel widgets (4 widgets).

TimeSeriesCell final class

Renders a timeline (time-series) widget as a sparkline using Streamline.

MethodSummary
__construct(private readonly Widget $widget, int $windowSize = 160, int $width = 40, int $height = 8)
ingest(array $current, array $previous, float $elapsed): selfIngest a new data point computed from the current and previous snapshots.
ingestFromSnapshot(\SugarCraft\Sql\Admin\StatusSnapshot $current, \SugarCraft\Sql\Admin\StatusSnapshot $previous): selfIngest from a StatusSnapshot and the previous one.
reset(): selfReset all history (call on server restart).
ceiling(): floatGet the current ceiling value (auto-scaled "nice ceiling").
maxSeen(): floatGet the max seen value.
isEmpty(): boolCheck if the cell has any data.
count(): intGet the number of data points in the window.
view(): stringRender the timeline as a string.
__toString(): stringRender as string (magic method).
widget(): WidgetGet the associated widget.

Widget final readonly class

Immutable dashboard widget descriptor.

MethodSummary
__construct(public string $caption, public string $kind, public object $calc, public string $format, public array $color, public string $tooltip = '', public ?array $serverVarsKeys = null)
title(): stringLocalized display label. caption stays the English identity token the dashboard keys counters, series and panel compositions on; only what is drawn is translated.
compute(array $current, array $previous, float $elapsed): float|array|stringCompute the widget's current value.
isTuple(): boolCheck if this widget's calc is a tuple (multi-series) type.
renderTooltip(array $vars): stringFill the tooltip template with values (SQL-P17, adminpages-018).
formatValue(float|array $value): stringFormat a value using the widget's format string.

WidgetCatalog final class

Declarative widget tables for the Performance Dashboard.

MethodSummary
network(): arrayNetwork panel widgets.
mysqlPre80(): arrayMySQL widgets for versions before 8.0.
mysqlPost80(): arrayMySQL widgets for version 8.0 and later.
innodb(): arrayInnoDB panel widgets.

WidgetRegistry final class

Widget kind constants and version-gated widget assembly.

MethodSummary
static build(ServerVersion $version): arrayAssemble the full widget list for a given MySQL version.
static network(): arrayGet only the Network panel widgets.
static mysql(ServerVersion $version): arrayGet only the MySQL panel widgets for a given version.
static innodb(): arrayGet only the InnoDB panel widgets.
static buildForPostgres(): arrayAssemble the full widget list for PostgreSQL.
static postgresIo(): arrayGet only the I/O panel widgets for PostgreSQL.
static postgresTransactions(): arrayGet only the Transactions panel widgets for PostgreSQL.
static postgresCache(): arrayGet only the Cache panel widgets for PostgreSQL.
static isValidKind(string $kind): boolValidate that a kind string is a known widget kind.
static validKinds(): arrayGet all valid widget kind constants.

SugarCraft\Sql\Admin\Debug

DebugPage final class

Debug pane displaying the query/action log from QueryLogger.

MethodSummary
__construct(ServerContextInterface $context)
static new(ServerContextInterface $context): selfCreate a new DebugPage from the server context.
update(Msg $msg): arrayHandle keyboard shortcuts for navigation and clearing.
withQuit(): selfReturn a clone (quit is handled by parent controller).
cursor(): int
refresh(): selfRefresh data and return new instance.
isModal(): boolWhether the page currently owns an open modal editing surface.
claimsKey(KeyMsg $msg): boolWhether this page claims $msg ahead of the App's own Admin-pane chords (the Tab pane cycle, the 1-{n} page picker, q, p, r).
releaseKeys(): selfThis page with every keyboard claim dropped (a focused component blurred), so claimsKey() answers false. App calls it when the user leaves the Admin pane; a page with no claims returns itself.
init(): ?\Closure
view(): string
subscriptions(): ?\SugarCraft\Core\Subscriptions

SugarCraft\Sql\Admin\History

HistoryQuery final class

Query historical snapshots and compute rate statistics.

MethodSummary
__construct(private readonly HistoryStoreInterface $store)
query(float $sinceTs, float $untilTs): arrayRetrieve snapshots within a Unix-timestamp range (inclusive).
querySince(float $sinceTs): arrayRetrieve snapshots from a given timestamp up to now.
rate(string $variable, float $sinceTs, float $untilTs): ?floatCompute the per-second rate of a variable over a time range.
getRate(string $variable, float $sinceTs, float $untilTs): ?floatBC forwarder for the pre-rename accessor name.

HistoryRecorder final class

Passive recorder that persists StatusSnapshots to a HistoryStore.

MethodSummary
__construct(private readonly HistoryStoreInterface $store, private readonly ?StatusSnapshotProviderInterface $provider = null)
record(StatusSnapshot $snapshot): voidPersist a snapshot to the store.
recordFromProvider(): voidFetch a snapshot from the injected provider and persist it.
pruneOlderThan(\DateTimeImmutable $cutoff): intRemove all snapshots older than the given cutoff.
historyQuery(): HistoryQuerySQL-O13: the read side of the store this recorder writes. Until now the full query API had zero production readers — every disk write paid for a file the user could not interpret in-app.
currentSnapshot(): ?array
statusVariablesTs(): float
wasReset(): bool

HistoryStoreInterface interface

Persistence layer for historical StatusSnapshot records.

MethodSummary
save(StatusSnapshot $snapshot): voidPersist a single snapshot.
query(\DateTimeImmutable $since, \DateTimeImmutable $until): arrayRetrieve snapshots within a time range (inclusive).
queryBoundaries(\DateTimeImmutable $since, \DateTimeImmutable $until): arrayBoundary-only read (SQL-P02): the oldest and newest snapshots in the range, ascending, without materializing the window. One row when the window holds a single snapshot; empty when none.
count(): intTotal number of stored snapshots.
prune(\DateTimeImmutable $before): intDelete all snapshots older than the cutoff.
close(): voidRelease any held resources (e.g. close the SQLite database).

SqliteHistoryStore final class

SQLite-backed HistoryStore.

MethodSummary
__construct(private readonly string $dbPath, ?int $maxRows = null, ?float $maxAgeSeconds = null)
save(StatusSnapshot $snapshot): void
queryBoundaries(\DateTimeImmutable $since, \DateTimeImmutable $until): arraySQL-P02: the two boundary rows of a window (oldest, newest) instead of materializing the whole range — rate() only ever reads these two.
query(\DateTimeImmutable $since, \DateTimeImmutable $until): array
count(): int
prune(\DateTimeImmutable $before): int
close(): void

SugarCraft\Sql\Admin\PerfSchema

ChangeTracker final class

Change-tracking overlay for Performance Schema configuration.

MethodSummary
__construct(array $items = [])
static fromInstruments(array $instruments): selfCreate a new tracker from SetupInstruments.
static fromConsumers(array $consumers): selfCreate a new tracker from SetupConsumers.
static fromActors(array $actors): selfCreate a new tracker from SetupActors.
static fromObjects(array $objects): selfCreate a new tracker from SetupObjects.
add(object $item): voidAdd an item to the tracker.
original(string $key): mixedGet the original value of an item by key.
current(string $key): mixedGet the current value of an item by key.
replace(string $key, object $modified): voidReplace an item's current value with a modified copy.
isDirty(): boolCheck if there are any unsaved changes.
diff(): arrayGet the keys of all changed items.
reset(): voidReset all changes by reverting current values to original.
commit(): voidCommit changes by marking current values as the new original.
all(): arrayGet all current items.

CommitPlanner final class

Generates SQL statements to commit Performance Schema configuration changes.

MethodSummary
__construct(private readonly array $instruments = [], private readonly array $consumers = [], private readonly array $actors = [], private readonly array $objects = [])
static new(array $instruments = [], array $consumers = [], array $actors = [], array $objects = []): selfFactory method to create a new CommitPlanner.
commitAll(): arrayGenerate parameterized SQL statements to commit all changes.
commitInstruments(): arrayGenerate parameterized SQL statements for instrument changes.
commitConsumers(): arrayGenerate parameterized SQL statements for consumer changes.
commitActors(): arrayGenerate parameterized SQL statements for actor changes.
commitObjects(): arrayGenerate parameterized SQL statements for object changes.
isDirty(): boolCheck if any tracked models have changes.

EasySetup final class

Performance Schema easy setup utility providing toggle statements and defaults.

MethodSummary
static defaultInstrumentsForVersion(ServerVersion $version): arrayGet default instruments for a given version.
static defaultConsumersForVersion(ServerVersion $version): arrayGet default consumers for a given version.
__construct(?ServerVersion $version = null)
static new(?ServerVersion $version = null): selfFactory method to create a new EasySetup instance.
static fromContext(ServerContextInterface $context): selfFactory method to create from a server context.
enableStatements(): arrayGenerate statements to enable Performance Schema (fully enabled).
disableStatements(): arrayGenerate statements to disable Performance Schema (fully disabled).
resetToDefaultStatements(): arrayGenerate statements to reset Performance Schema to defaults.
defaultInstruments(): arrayGet the default instrument patterns for this version.
defaultConsumers(): arrayGet the default consumer names for this version.

EasySetupDetector final class

Detects the current Performance Schema setup state via COUNT/SUM queries.

MethodSummary
__construct(private readonly DatabaseInterface $db, ?ServerVersion $version = null)
static new(DatabaseInterface $db, ?ServerVersion $version = null): selfFactory method to create a new detector.
static fromContext(ServerContextInterface $context): selfCreate a detector from a server context.
detect(): stringDetect the current PS setup state via server-side aggregates.
classifyFromData(array $instruments, array $consumers): stringThe zero-query twin of detect(): classify from row lists the page has ALREADY paid for, instead of re-asking the server up to seven aggregate scans (several recomputing exactly what the loaded setup_instruments/setup_consumers rows carry).
isDisabled(): boolCheck if PS is disabled (no access to setup_instruments).
isFullyEnabled(): boolCheck if all instruments and consumers are fully enabled (enabled='YES' AND timed='YES').
isFullyDisabled(): boolCheck if PS is fully disabled.
isDefaultSetup(): boolCheck if the current setup matches the MySQL default profile for this version.
enabledPercentage(): intGet the percentage of fully-enabled (enabled AND timed) instruments (0-100).
totalCount(): intGet the total number of non-memory instruments.
enabledCount(): intGet the number of enabled non-memory instruments.

InstrumentTree final class

Hierarchical view of Performance Schema instruments organized by name path.

MethodSummary
static new(): selfCreate a new root node for building a tree.
static fromInstruments(array $instruments): selfFactory method to create a new tree from a list of instruments.
insert(SetupInstruments $instrument): voidInsert an instrument into the tree.
instrument(): ?SetupInstrumentsGet the instrument at this node, if any.
name(): stringGet the name of this node.
child(string $name): ?InstrumentTreeGet a child node by name.
children(): arrayGet all child nodes.
hasChildren(): boolCheck if this node has any children.
path(): stringGet the full path of this node from the root.
state(): intCompute the aggregate enabled state of this subtree.
timedState(): intCompute the aggregate timed state of this subtree.
enabled(): boolGet the enabled state as a boolean.
timed(): boolGet the timed state as a boolean.
find(string $path): ?InstrumentTreeFind a node by instrument name path.
allInstruments(): arrayGet all instruments at or below this node.
dump(int $depth = 0): stringGet a representation of the tree structure for debugging.
depth(): intGet the depth of this node in the tree.
pathDepth(): intGet the full depth of this node from root (used for indent calculation).
setChildrenEnabled(bool $enabled): arraySet the enabled state for this node and cascade to all descendants.
setChildrenTimed(bool $timed): arraySet the timed state for this node and cascade to all descendants.

PerfSchemaPage final class

Performance Schema configuration page with tabbed interface.

MethodSummary
__construct(ServerContextInterface $context, ?EasySetupDetector $detector = null, ?CommitPlanner $commitPlanner = null, private readonly ?StatementTimeout $commitTimeout = null)
static new(ServerContextInterface $context, ?EasySetupDetector $detector = null, ?CommitPlanner $commitPlanner = null, ?StatementTimeout $commitTimeout = null): selfFactory method to create a new PerfSchemaPage.
update(Msg $msg): arrayHandle keyboard shortcuts for navigation and actions.
withNextTab(): selfReturn a new instance with the next tab active.
withPrevTab(): selfReturn a new instance with the previous tab active.
withTab(string $tab): selfReturn a new instance with a specific tab active.
withQuit(): selfReturn a clone (quit is handled by parent controller).
withRevert(): selfReturn a new instance with reverted changes.
isModal(): bool
forgetPrivilegeProbe(): voidSQL-P01 invalidation hook: drop the memoized privilege probe so the next frame re-checks. Call on any context/session identity change (a fresh page already re-probes because the memo is page-local). SQL-P07: a session identity change changes far more than the probe — rows, access visibility and the tree are all last-session facts — so the hook now re-arms the whole arrival-scoped state, not just the memo.
activeTab(): string
selectedRowIndex(): int
isReadOnly(): bool
setupState(): string
instruments(): array
consumers(): array
actors(): array
objects(): array
threads(): array
timers(): array
refresh(): selfRefresh data and return new instance.
claimsKey(KeyMsg $msg): boolWhether this page claims $msg ahead of the App's own Admin-pane chords (the Tab pane cycle, the 1-{n} page picker, q, p, r).
releaseKeys(): selfThis page with every keyboard claim dropped (a focused component blurred), so claimsKey() answers false. App calls it when the user leaves the Admin pane; a page with no claims returns itself.
init(): ?\Closure
view(): string
subscriptions(): ?\SugarCraft\Core\Subscriptions

SetupActors final readonly class

Immutable representation of a Performance Schema actor.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
__construct(public string $host, public string $user, public string $role, public bool $enabled, private bool $dirty = false, private string $changeType = self::CHANGE_NONE)
static new(string $host = '', string $user = '', string $role = '', bool $enabled = false): selfFactory method to create a new instance.
withEnabled(bool $enabled): staticReturn a new instance with the enabled state changed.
markForDeletion(): staticMark this actor for deletion.
markForInsertion(): staticMark this actor as a new insertion.
isDirty(): boolCheck if this actor has unsaved changes.
markClean(): voidMark this actor as clean (no pending changes).
asClean(): staticReturn a clean copy of this actor.
changeType(): stringGet the type of change this actor has.
getChangeType(): stringBC forwarder for the pre-rename accessor name.
isGlobalHost(): boolCheck if this actor matches all hosts.
isGlobalUser(): boolCheck if this actor matches all users.
isGlobalRole(): boolCheck if this actor matches all roles.
isCatchAll(): boolCheck if this is a catch-all actor (matches everything).
commitStatements(): arrayGenerate SQL statement(s) to commit changes.

SetupConsumers final readonly class

Immutable representation of a Performance Schema consumer.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
__construct(public string $name, public bool $enabled, private bool $dirty = false)
static new(string $name = '', bool $enabled = false): selfFactory method to create a new instance.
withEnabled(bool $enabled): staticReturn a new instance with the enabled state changed.
isDirty(): boolCheck if this consumer has unsaved changes.
markClean(): voidMark this consumer as clean (no pending changes).
asClean(): staticReturn a clean copy of this consumer.
commitStatements(): arrayGenerate SQL statement to commit changes.

SetupInstruments final readonly class

Immutable representation of a Performance Schema instrument.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
__construct(public string $name, public bool $enabled, public bool $timed, public string $properties, public string $flags, private bool $dirty = false)
static new(string $name = '', bool $enabled = false, bool $timed = false, string $properties = '', string $flags = ''): selfFactory method to create a new instance.
withEnabled(bool $enabled): staticReturn a new instance with the enabled state changed.
withTimed(bool $timed): staticReturn a new instance with the timed state changed.
isDirty(): boolCheck if this instrument has unsaved changes.
markClean(): voidMark this instrument as clean (no pending changes).
asClean(): staticReturn a clean copy of this instrument.
hasProperty(string $property): boolCheck if this instrument has a specific property.
isAbstract(): boolCheck if this instrument is an abstract (pseudo) instrument.
isGlobal(): boolCheck if this instrument is a global-level instrument.
commitStatements(): arrayGenerate SQL statement to commit changes.

SetupObjects final readonly class

Immutable representation of a Performance Schema object setup entry.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
__construct(public string $objectType, public string $objectSchema, public string $objectName, public bool $enabled, public bool $timed, private bool $dirty = false, private string $changeType = self::CHANGE_NONE)
static new(string $objectType = '', string $objectSchema = '', string $objectName = '', bool $enabled = false, bool $timed = false): selfFactory method to create a new instance.
withEnabled(bool $enabled): staticReturn a new instance with the enabled state changed.
withTimed(bool $timed): staticReturn a new instance with the timed state changed.
markForDeletion(): staticMark this object for deletion.
markForInsertion(): staticMark this object as a new insertion.
isDirty(): boolCheck if this object has unsaved changes.
markClean(): voidMark this object as clean (no pending changes).
asClean(): staticReturn a clean copy of this object.
changeType(): stringGet the type of change this object has.
getChangeType(): stringBC forwarder for the pre-rename accessor name.
isGlobalSchema(): boolCheck if this applies to all schemas.
isGlobalObject(): boolCheck if this applies to all objects.
isCatchAll(): boolCheck if this is a catch-all entry (matches everything).
commitStatements(): arrayGenerate SQL statement(s) to commit changes.

SetupThreads final readonly class

Mutable representation of a Performance Schema thread.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
__construct(public int $threadId, public string $name, public string $type, public ?int $processlistId = null, public ?string $processlistUser = null, public ?string $processlistCommand = null, public ?string $processlistInfo = null, public bool $instrumented = true, private bool $dirty = false)
static new(int $threadId = 0, string $name = '', string $type = 'FOREGROUND', ?int $processlistId = null, ?string $processlistUser = null, ?string $processlistCommand = null, ?string $processlistInfo = null, bool $instrumented = true): selfFactory method to create a new instance.
withInstrumented(bool $instrumented): staticReturn a new instance with the instrumented state changed.
isDirty(): boolCheck if this thread has unsaved changes.
isForeground(): boolCheck if this is a foreground thread (user connection).
isBackground(): boolCheck if this is a background thread (internal server thread).
hasProcesslist(): boolCheck if this thread has an active processlist entry.
commitStatements(): arrayGenerate SQL statement(s) to commit changes.
instrumentedFragment(): stringGenerate a partial SQL fragment for this thread's INSTRUMENTED update.

SetupTimers final readonly class

Mutable representation of a Performance Schema timer entry from setup_timers.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
__construct(public string $name, public string $timerName, private bool $dirty = false, private string $changeType = self::CHANGE_NONE)
static new(string $name = '', string $timerName = ''): selfFactory method to create a new instance.
withTimerName(string $timerName): staticReturn a new instance with a different timer selected.
isDirty(): boolCheck if this timer has unsaved changes.
changeType(): stringGet the type of change this timer has.
getChangeType(): stringBC forwarder for the pre-rename accessor name.
nameUpper(): stringGet the timer name in uppercase.
isCycle(): boolCheck if this is the CYCLE timer (uses CPU cycles).
commitStatements(): arrayGenerate SQL statement(s) to commit changes.

SugarCraft\Sql\Admin\Providers

MysqlAdminProvider final class

MySQL implementation of AdminProviderInterface wrapping ServerContext.

MethodSummary
__construct(private readonly ServerContextInterface $context)
static new(ServerContextInterface $context): selfCreate a new instance from an existing ServerContext.
flavor(): Flavor
fetchStatusVariables(): array
fetchServerVariables(): array
fetchProcesslist(): array
maxConnections(): int
statusVariablesTs(): float
wasReset(): bool
refresh(): void

PostgresAdminProvider final class

PostgreSQL implementation of AdminProviderInterface.

MethodSummary
__construct(private readonly DatabaseInterface $connection)
static new(DatabaseInterface $connection): selfCreate a new instance from a PostgreSQL database connection.
flavor(): Flavor
fetchStatusVariables(): arrayFetch pg_stat_database metrics for the current database as "status variables".
fetchServerVariables(): arrayFetch all pg_settings as server variables.
fetchProcesslist(): arrayFetch active connections from pg_stat_activity.
maxConnections(): int
statusVariablesTs(): float
wasReset(): bool
refresh(): void

SugarCraft\Sql\Admin\Reports

AvailabilityChecker final class

Checks availability of the MySQL sys schema views.

MethodSummary
static new(DatabaseInterface $db): selfFactory method to create a new AvailabilityChecker.
discoverViews(): arrayDiscover available sys schema views.
sysSchemaExists(): boolCheck if the sys schema exists and is accessible.
isViewAvailable(string $viewName): boolCheck if a specific sys schema view is available.
availableFromCatalog(Catalog $catalog): arrayGet all views that are available from the catalog.
missingFromCatalog(Catalog $catalog): arrayGet missing views from the catalog.
availableInCategory(Catalog $catalog, string $category): arrayGet reports available for a specific category.
reset(): voidReset the cached view list.

Catalog final class

Catalog loader for performance report metadata.

MethodSummary
static new(string $basePath = __DIR__ . '/../../../data'): selfFactory method to create a new Catalog instance.
load(): voidLoad and parse the report metadata JSON file.
get(string $name): ?ReportDefinitionGet a report by its view name.
all(): arrayGet all available reports.
byCategory(string $category): arrayGet all reports belonging to a specific category.
categories(): arrayList all available categories.
groupedByCategory(): arrayGet all reports grouped by category.
has(string $name): boolCheck if a report exists in the catalog.
count(): intGet the number of reports in the catalog.

ColumnDefinition final readonly class

Immutable metadata for a single report column.

MethodSummary
__construct(public string $name, public ColumnType $type, public int $width)
isTime(): boolWhether this column represents a time value (picoseconds) that needs unit formatting.
isBytes(): boolWhether this column represents a byte value that needs unit formatting.
isNumeric(): boolWhether this column represents a numeric value (int, bigint, float).

ColumnType enum

Column type enumeration for report columns.

Cases: Int · Bigint · Float · Time · Bytes · String

PHP also provides cases(), from() and tryFrom().

ReportDefinition final readonly class

Immutable descriptor for a single performance report.

MethodSummary
__construct(public string $name, public string $category, public string $caption, public string $description, public string $query, public array $columns)
hasColumn(string $columnName): boolCheck if a column exists in this report.
column(string $columnName): ?ColumnDefinitionGet a column definition by name.
columnNames(): arrayGet all column names in order.
timeColumns(): arrayGet column names that should be formatted as time (picoseconds).
byteColumns(): arrayGet column names that should be formatted as bytes.

ReportResult final readonly class

Immutable result of executing a performance report.

MethodSummary
__construct(public ReportDefinition $report, public array $rows, public int $rowCount, public bool $limited)
columnNames(): arrayGet the column names from the report definition.
timeColumns(): arrayGet time column names that need unit formatting.
byteColumns(): arrayGet byte column names that need unit formatting.
firstRow(): ?arrayGet the first row, or null if there are no rows.
isEmpty(): boolCheck if the result is empty.

ReportRunner final class

Executes performance report queries against the MySQL sys schema.

MethodSummary
static new(DatabaseInterface $db, Catalog $catalog, AvailabilityChecker $availability, int $defaultLimit = 1000): selfFactory method to create a new ReportRunner.
run(string $viewName, ?int $limit = null): ReportResultExecute a report and return formatted results.
assertAvailable(string $viewName): voidThe catalog+availability guard behind run(), public so a caller that formats elsewhere (ReportsPage's SQL-P10 single-query reuse) keeps the same failure vocabulary: unknown report / view-not-available throw before any query rides.
formatResult(ReportResult $raw): ReportResultFormat a raw ReportResult through the report's column types without re-querying (SQL-P10: the arrival-identity reuse path holds the raw generation once and pays formatRows at most once per generation).
runRaw(string $viewName, ?int $limit = null): ReportResultExecute a report and return raw (unformatted) results.
canRun(string $viewName): boolCheck if a report can be executed.

ReportsPage final class

Performance Reports page with left category/report tree and right sortable/exportable grid.

MethodSummary
__construct(ServerContextInterface $context, ?DatabaseInterface $db = null, private readonly ?string $initialCategory = null, private readonly ?string $paneLabel = null)
static new(ServerContextInterface $context, ?DatabaseInterface $db = null, ?string $initialCategory = null, ?string $paneLabel = null): selfCreate a new ReportsPage from the server context.
static seedCategoryFor(AdminPane $pane): ?string
update(Msg $msg): arrayHandle keyboard shortcuts for navigation and actions.
withNavigateDown(): self
withNavigateUp(): self
withRefresh(): self
withQuit(): self
withToggleUnitDisplay(): self
withSelectCategory(string $category): self
withSelectReport(string $reportName): self
withSelectPrevCategory(): selfSelect the previous category, wrapping to the last if already at the first.
withSelectNextCategory(): selfSelect the next category, wrapping to the first if already at the last.
withSelectPrevReport(): selfSelect the previous report within the current category, wrapping to the last report if already at the first.
withSelectNextReport(): selfSelect the next report within the current category, wrapping to the first report if already at the last.
withSelectPrevColumn(): selfSelect the previous column for unit display targeting.
withSelectNextColumn(): selfSelect the next column for unit display targeting.
withExport(): self
exportToCsv(): stringExport the current report result to CSV format.
selectedCategory(): ?string
selectedReport(): ?string
selectedRowIndex(): int
currentResult(): ?ReportResult
showRawValues(): bool
selectedColumnIndex(): int
catalog(): ?Catalog
runner(): ?ReportRunner
lastExportCsv(): ?stringGet the CSV from the most recent export.
refresh(): selfRefresh data and return new instance.
isModal(): boolWhether the page currently owns an open modal editing surface.
claimsKey(KeyMsg $msg): boolWhether this page claims $msg ahead of the App's own Admin-pane chords (the Tab pane cycle, the 1-{n} page picker, q, p, r).
releaseKeys(): selfThis page with every keyboard claim dropped (a focused component blurred), so claimsKey() answers false. App calls it when the user leaves the Admin pane; a page with no claims returns itself.
init(): ?\Closure
view(): string
subscriptions(): ?\SugarCraft\Core\Subscriptions

UnitFormatter final class

Unit formatter for performance report column values.

MethodSummary
static format(mixed $value, string $type): stringFormat a value according to its column type.
static formatTime(mixed $picoseconds): stringFormat a picosecond value as human-readable duration.
static formatBytes(mixed $bytes): stringFormat bytes using IEC binary units (KiB, MiB, GiB).
static formatInteger(mixed $value): stringFormat an integer value with thousands separator.
static formatFloat(mixed $value): stringFormat a float value with appropriate precision.

SugarCraft\Sql\Admin\Resilience

ReconnectManager final class

Manages reconnection logic for MySQL connection errors.

MethodSummary
__construct(private readonly ?AdminQueryCache $cache = null)
shouldReconnect(\PDOException $e): boolCheck if the given PDOException indicates a reconnectable error.
attemptReconnect(callable $connect): boolAttempt to reconnect using the last known connection config.
setConnectionConfig(ConnectionConfig $config): voidRemember the connection config for reconnection attempts.
lastConnectionConfig(): ?ConnectionConfigGet the last known connection config.

StatementTimeout final class

Enforces a wall-clock timeout on synchronous DB work.

MethodSummary
__construct(private readonly int $timeoutSeconds = self::DEFAULT_SECONDS, ?bool $pcntlAvailable = null, private readonly ?\Closure $alarm = null)
run(callable $work): mixedRun arbitrary synchronous work under the wall-clock budget.
execute(\PDOStatement $stmt, array $values = []): boolExecute a prepared statement with timeout enforcement.
didTimeout(): boolCheck if the last execution timed out.

StatementTimeoutException final class

Thrown when a statement exceeds its wall-clock timeout.

MethodSummary
__construct(?string $message = null, int $code = 0, ?\Throwable $previous = null)

SugarCraft\Sql\Admin\ServerStatus

GaugeType enum

Gauge types supported in the sidebar.

Cases: Connections · Traffic · KeyEfficiency · Qps · InnoDB

PHP also provides cases(), from() and tryFrom().

GtidMode enum

Valid GTID_MODE values for SET @@GLOBAL.GTID_MODE.

Cases: Off · OffPermissive · OnPermissive · On

PHP also provides cases(), from() and tryFrom().

MethodSummary
static values(): arrayAll modes in cycling order for the dialog 'c' key.
requiresGtidOn(): boolTrue if this mode requires GTID to be enabled (ON or ON_PERMISSIVE).

MetricsColumn final class

Right-hand metric column of the Server Status page — the Workbench Management :: Server Status parity target (query_dashboard.md 42-69).

MethodSummary
__construct(private readonly ServerContextInterface $context, private readonly ?Sampler $sampler, ?HostLoadSampler $hostLoad = null)
static forContext(ServerContextInterface $context, ?Sampler $sampler, ?HostLoadSampler $hostLoad = null): self
poll(?float $now = null): voidAdvance every rolling window at most once per second.
forcePoll(): voidDrop the throttle so the next poll() reads immediately (fresh data arrived through the shared async cache, or the user hit [r]). Opening the cadence gate does not fabricate data: a poll that still sees the identical status frame stays a no-op for rates and windows.
hostLoadSampler(): HostLoadSampler
cell(string $name): StatusGraphCell
view(int $width, int $rows = 24): stringRender the whole column inside $width cells, sized for $rows of vertical space.

ReplicaStatusKind enum

The specific condition encountered when fetching replica status.

Cases: Configured · NotConfigured · PermissionDenied · Error

PHP also provides cases().

ReplicaStatusProvider final class

Provides replica status by executing SHOW REPLICA STATUS (MySQL 8+), SHOW SLAVE STATUS (MySQL 5.x), or SHOW ALL SLAVES STATUS (MariaDB).

MethodSummary
__construct(private readonly ServerContextInterface $context)
static new(ServerContextInterface $context): selfCreate a new instance with default context.
fetchStatus(): arrayFetch all replica status rows from the server.
lastFetchKind(): ReplicaStatusKindThe specific condition last encountered when fetching status.
isReplicaConfigured(): boolTrue when replica status is configured on this server.
refresh(): selfClear cached status, forcing a fresh query on next access.

RunState enum

Liveness of the admin data feed backing the Server Status page.

Cases: Running · Stopped · Unreachable

PHP also provides cases(), from() and tryFrom().

ServerInfoCard final class

Info card displaying server connection details and uptime.

MethodSummary
__construct(private readonly ServerContextInterface $context)
static new(ServerContextInterface $context): selfCreate a new ServerInfoCard from the current server context.
render(): stringRender the info card via a sugar-dashboard Card + DefinitionList.

ServerStatusPage final class

Server Status page displaying connection info, features, directories, SSL, replication, and firewall.

MethodSummary
isModal(): boolThe GTID dialog is open — it owns every keystroke.
__construct(ServerContextInterface $context, ?ReplicaStatusProvider $replicaProvider = null, ?Sampler $sampler = null)
static new(ServerContextInterface $context, ?Sampler $sampler = null): selfCreate a new ServerStatusPage from the server context.
view(): stringRender the page, keeping the Workbench liveness label visible even when there is no data to build the panels from: Workbench greys the whole Server Status tab but still shows the stopped indicator, and without the header the user cannot tell "connection died" from "page still loading".
update(\SugarCraft\Core\Msg $msg): arrayHandle keyboard shortcuts for refresh, quit, and GTID mode selector.
tristate(bool|string|null $value): stringConvert bool|string|null to a Yes/No/Unknown badge.
withRefresh(): selfReturn a refreshed instance.
withQuit(): selfReturn a clone (quit is handled by the parent controller).
replicaProvider(): ReplicaStatusProvider
refresh(): selfRefresh data and return new instance.
claimsKey(KeyMsg $msg): boolWhether this page claims $msg ahead of the App's own Admin-pane chords (the Tab pane cycle, the 1-{n} page picker, q, p, r).
releaseKeys(): selfThis page with every keyboard claim dropped (a focused component blurred), so claimsKey() answers false. App calls it when the user leaves the Admin pane; a page with no claims returns itself.
init(): ?\Closure
subscriptions(): ?\SugarCraft\Core\Subscriptions

SidebarGauge final class

A single sidebar gauge displaying a metric with threshold coloring.

MethodSummary
static new(GaugeType $type, float $ratio): selfCreate a new sidebar gauge.
view(): stringRender the gauge as an ANSI string.
label(): stringGet the human-readable label for this gauge type.
static thresholdColor(float $ratio): ColorDetermine the threshold color based on ratio.
withRatio(float $ratio): selfReturn a new instance with an updated ratio.
type(): GaugeTypeAccessor for the gauge type.
ratio(): floatAccessor for the current ratio.

SidebarGaugeSet final class

Collection of all sidebar gauges for the Server Status page.

MethodSummary
static new(ServerContextInterface $context, ?Sampler $sampler = null): selfCreate a new gauge set from the server context.
poll(): selfPoll the context/sampler and refresh all gauge ratios.
view(): stringRender all gauges as a sidebar panel string.
gauges(): arrayAccessor for all gauges.
previousRates(): ?arrayAccessor for the previous rates.
static computeKeyEfficiencyRatio(array $statusVars): floatCompute key efficiency ratio: Key_reads / (Key_reads + Key_write_requests).
static computeInnoDBRatio(array $statusVars): floatCompute InnoDB buffer pool utilization ratio.

StatusGraphCell final class

One rolling time-series frame on the Server Status column.

MethodSummary
__construct(public readonly string $caption, private readonly array $seriesNames, private readonly array $colors, private readonly bool $stacked, private readonly int $window = HostLoadSampler::WINDOW)
ingest(array $samples): voidAppend one frame of samples; keys missing from $samples record 0.0 so the trace keeps one point per poll instead of drifting sideways.
hasSamples(): bool
latest(): arrayLatest recorded value per series name.
series(string $name): array
view(int $width, int $height): stringPaint the window as exactly $width x $height cells (plus nothing else: captions and labels are the column's job so the width budget stays arithmetic, not string-geometry, at the caller).

SugarCraft\Sql\Admin\Variables

Catalog final class

Catalog loader for MySQL variable metadata.

MethodSummary
static new(string $basePath = __DIR__ . '/../../../data'): selfFactory method to create a new Catalog instance.
load(): voidLoad and parse the variable metadata JSON file.
get(string $name): ?VariableMetadataGet a variable by name.
all(): arrayGet all variables.
byGroup(string $group): arrayGet all variables belonging to a specific group.
groups(): arrayList all available groups.
isEditable(string $name): boolCheck if a variable is editable.
isDynamic(string $name): boolCheck if a variable is runtime-dynamic (can be changed without restart).

VariableEditor final class

Inline editor for modifying MySQL variables via SET GLOBAL / SET PERSIST.

MethodSummary
static new(ServerContextInterface $context, ?Catalog $catalog = null): selfFactory method to create a new VariableEditor.
edit(string $variableName, string $newValue): arrayEdit a variable using SET GLOBAL.
editPersistent(string $variableName, string $newValue): arrayEdit a variable using SET PERSIST (vendor-gated; see persist()).
persist(string $variableName, string $newValue): arrayPersist a variable using SET PERSIST (MySQL 8.0+).
persistOnly(string $variableName, string $newValue): arrayPersist a variable using SET PERSIST_ONLY (MySQL 8.0+).
resetPersist(?string $variableName = null): arrayReset persisted variables using RESET PERSIST (MySQL 8.0+).
editPreview(string $variableName, string $newValue, string $mode = 'global'): stringGet a preview of what the SET statement would look like.
getEditPreview(string $variableName, string $newValue, string $mode = 'global'): stringBC forwarder for the pre-rename accessor name.
isEditable(string $variableName): boolCheck if a variable is editable per its metadata.
lastError(): ?stringGet the last error message from the most recent operation.
isPrivilegeError(): boolCheck if the last error was a privilege error (1142 or 1227).
isPersistedVariablesError(): boolCheck if the last error was related to persisted_variables (3680).

VariableMetadata final readonly class

Immutable metadata descriptor for a MySQL system variable.

MethodSummary
__construct(public string $name, public string $description, public bool $editable, public bool $dynamic = true, public array $groups = [])
inGroup(string $group): boolCheck if the variable belongs to a given group.
isDynamic(): boolCheck if the variable is runtime-dynamic (can be changed without restart).

VariablesPage final class

Variables page displaying SHOW GLOBAL STATUS / SHOW GLOBAL VARIABLES.

MethodSummary
__construct(ServerContextInterface $context, private readonly ?Catalog $catalog = null, private readonly ?VariableEditor $editor = null, ?string $editDialogPhase = null, ?string $editVarName = null, ?string $editNewValue = null, ?string $editCurrentValue = null, ?string $editErrorMessage = null, ?string $editPersistMode = null)
static new(ServerContextInterface $context, ?Catalog $catalog = null, ?VariableEditor $editor = null): selfCreate a new VariablesPage from the server context.
update(Msg $msg): arrayHandle keyboard shortcuts for navigation and editing.
withToggleTab(): selfReturn a new instance with the tab toggled.
withTab(string $tab): selfReturn a new instance with a specific tab.
withSearch(string $search): selfReturn a new instance with search filter applied.
withCategory(?string $category): selfReturn a new instance with category filter applied.
withQuit(): selfReturn a clone (quit is handled by parent controller).
activeTab(): string
searchQuery(): string
activeCategory(): ?string
showReadWriteOnly(): bool
selectedRowIndex(): int
catalog(): ?Catalog
isModal(): boolThe edit/confirm dialog is open — it owns every keystroke.
editor(): ?VariableEditor
refresh(): selfRefresh data and return new instance.
claimsKey(KeyMsg $msg): boolWhether this page claims $msg ahead of the App's own Admin-pane chords (the Tab pane cycle, the 1-{n} page picker, q, p, r).
releaseKeys(): selfThis page with every keyboard claim dropped (a focused component blurred), so claimsKey() answers false. App calls it when the user leaves the Admin pane; a page with no claims returns itself.
init(): ?\Closure
view(): string
subscriptions(): ?\SugarCraft\Core\Subscriptions

SugarCraft\Sql\App

AdminState final class

Admin/monitoring slice of the \SugarCraft\Sql\App model: the selected admin pane + sidebar cursor, the lazily-built page instance, the async-fetched status/server variable caches, and the polling/loading bookkeeping. Grouped out of App's constructor per plan 3.3.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
__construct(public readonly AdminPane $pane = AdminPane::ProcessList, public readonly int $cursor = 0, public readonly bool $paused = false, public readonly ?PageBase $page = null, public readonly ?array $cachedStatusVars = null, public readonly ?array $cachedServerVars = null, public readonly float $cacheTs = 0.0, public readonly bool $loading = false, public readonly float $lastFetchAt = 0.0, public readonly ?HistoryRecorder $historyRecorder = null, public readonly ?\SugarCraft\Sql\Admin\Resilience\StatementTimeout $syncTimeoutGuard = null)
withSyncTimeoutGuard(?\SugarCraft\Sql\Admin\Resilience\StatementTimeout $guard): selfInstall the sync-leg wall-clock cap override (see the constructor note).
static new(): self
withPane(AdminPane $pane): selfSelecting a pane resets the lazily-built page so it is recreated against the new pane; this is the ONLY transition that drops page state (loading ticks must preserve it — see App::withAdminLoading()).
withCursor(int $cursor): self
withPaused(bool $paused): self
withPage(?PageBase $page): self
withCachedData(array $statusVars, array $serverVars, float $ts): self
withLoading(bool $loading): self
withLastFetchAt(float $lastFetchAt): self
withHistoryRecorder(?HistoryRecorder $historyRecorder): self

AppBuilder final class

Fluent builder for App.

MethodSummary
withDb(DatabaseInterface $db): self
withFlavor(Flavor $flavor): self
withTables(array $tables): self
withTableCursor(int $tableCursor): self
withSelectedTable(?string $selectedTable): self
withRows(array $rows): self
withRowCursor(int $rowCursor): self
withResultTable(?ResultTable $resultTable): self
withQueryEditor(?TextArea $queryEditor): self
withPane(Pane $pane): self
withAdminPage(?\SugarCraft\Sql\Admin\PageBase $page): selfSeed the admin layer with a concrete page instance (tests reach for this to drive modal routing without driving the whole pane UI).
withError(?string $error): self
withStatus(?string $status): self
withQueryHistory(array $queryHistory): self
withQueryFavorites(array $queryFavorites): self
withHistoryDbPath(?string $path): selfEnable history recording with the specified SQLite file path. When set, admin fetch results are persisted for later rate analysis.
withSslMode(?string $sslMode): selfOverride the MySQL ssl-mode carried into ConnectionState. Unset, the builder derives it from a real MysqlDatabase handle (mirroring \SugarCraft\Sql\App::start()); a non-MySQL db carries ''.
build(): \SugarCraft\Sql\App

BrowseState final class

Table/rows-browsing slice of the \SugarCraft\Sql\App model: the table list + cursor, the selected table's row preview, and the query-result grid. Grouped out of App's constructor per plan 3.3.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
__construct(public readonly array $tables = [], public readonly int $tableCursor = 0, public readonly ?string $selectedTable = null, public readonly array $rows = [], public readonly int $rowCursor = 0, public readonly ?ResultTable $resultTable = null, public readonly bool $rowsLoading = false, public readonly int $loadGen = 0, public readonly string $filterText = '', public readonly bool $filterMode = false, public readonly int $pageOffset = 0, public readonly int $colCursor = 0)
static new(): self
withTables(array $tables): self
withTableCursor(int $tableCursor): self
withFilterText(string $filterText): selfThe live /-filter string typed over the Tables pane (jorgerojas26/lazysql parity).
withFilterMode(bool $filterMode): selfWhether the / filter line is currently open and eating key input.
withPageOffset(int $pageOffset): selfServer-side row window of the current table preview (SQL-O11): the OFFSET part of the browse LIMIT/OFFSET pair, always a multiple of \SugarCraft\Sql\Db\PreviewQuery::DEFAULT_LIMIT.
visibleTables(): arrayTable names the cursor can reach right now: the filter is a lowercase substring match, so /ord leaves orders, OrdLog, xORDy — and the cursor indexes THIS list, never the raw one.
withSelectedTable(?string $selectedTable): self
holdsSyntheticResult(): boolThe Rows pane shows a computed result (query answer / history trend), not a table preview.
withRows(array $rows): self
withRowCursor(int $rowCursor): self
withColCursor(int $colCursor): self
withResultTable(?ResultTable $resultTable): self
withRowsLoading(bool $rowsLoading): self
withIncrementedLoadGen(): selfAdvance the async browse generation (client-012 companion of QueryState::withIncrementedQueryGen). A re-selection of the SAME table leaves selectedTable unchanged, so the table-name guard in the fold cannot see that the older leg is now superseded; the generation can.

ConnectionPicker final class

Launch-time picker over the saved connections (SQL-O02b, candy-sql-once-002).

MethodSummary
__construct(array $entries, private readonly int $cursor = 0, private readonly ?string $picked = null)
init(): ?\Closure
pickedName(): ?stringThe chosen connection name, or null when the picker was cancelled.
update(Msg $msg): array
view(): string
subscriptions(): ?Subscriptions

ConnectionState final class

Connection/environment slice of the \SugarCraft\Sql\App model: which database the app talks to, its flavor, and the (optional) admin server context override. Grouped out of App's constructor per plan 3.3.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
__construct(public readonly DatabaseInterface $db, public readonly Flavor $flavor = Flavor::Sqlite, public readonly ?ServerContextInterface $serverContext = null, public readonly string $sslMode = '', public readonly bool $readOnly = false)
static new(DatabaseInterface $db, Flavor $flavor = Flavor::Sqlite, ?ServerContextInterface $serverContext = null, string $sslMode = '', bool $readOnly = false): self
withReadOnly(bool $readOnly): self
withServerContext(?ServerContextInterface $serverContext): self
withSslMode(string $sslMode): self

EditPlanner final class

The refusal ladder in front of every in-grid write (SQL-O03): can THIS row be addressed safely, and may THIS cell be overwritten from the grid?

MethodSummary
static pkColumns(array $schema): arrayPrimary-key columns of the table, in column order.
static key(Flavor $flavor, array $schema, array $row): arrayThe full primary key of $row, or the refusal that explains why the row cannot be addressed (no key at all; a key value that is missing, NULL, or the binary-preview placeholder instead of the real bytes).
static cellRefusal(Flavor $flavor, array $schema, string $column): ?stringRefusal for overwriting $column from the grid, or null when allowed: the column must exist in the schema and must not be one the browse preview shows as a size placeholder instead of its bytes.

EditState final class

The in-grid editing slice of the \SugarCraft\Sql\App model (SQL-O03).

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
__construct(public readonly string $stage = self::STAGE_CLOSED, public readonly string $table = '', public readonly string $column = '', public readonly array $key = [], public readonly string $buffer = '', public readonly bool $isNull = false, public readonly ?string $original = null, public readonly array $insertColumns = [], public readonly array $insertTypes = [], public readonly int $insertIndex = 0, public readonly array $values = [], public readonly ?DmlStatement $statement = null)
static new(): self
isOpen(): boolWhether an edit line is open and should own the keyboard.
closed(): self
withStage(string $stage): self
withBuffer(string $buffer): selfReplace the typed value; typing always leaves the NULL toggle.
withNull(bool $isNull): self
withStatement(?DmlStatement $statement): self
withValues(array $values): self
withInsertIndex(int $insertIndex): self

ExportState final class

The file-line slice of the \SugarCraft\Sql\App model (SQL-O07): the Ctrl+S / x CSV export prompt and the i import prompt the exporters finally got in front of. Exporters complete since SQL-C04 were a library with zero TUI callers; this state is the missing user half.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
__construct(public readonly string $stage = self::STAGE_CLOSED, public readonly string $buffer = '', public readonly string $path = '')
static new(): self
isPromptOpen(): boolWhether a file line is open and should own the keyboard.
closed(): self
withStage(string $stage): self
withBuffer(string $buffer): self
withPath(string $path): self

KeyMap final class

SQL-O21 (once-028): the key binding roster as ONE machine-readable source. The legends draw from the lang strings, README is the human mirror, and KeysOverlayTest holds README and this table together cell-for-cell (one fact, one place). The cell strings are EXACTLY the README key tables' first columns (backticks stripped); text is the short help.* lang key per row.

MethodSummary
static rowsFor(Pane $pane): arrayRows the ? overlay lists for a pane: the full client roster always (pane scope is spelled out in each cell), admin chords on the Admin pane only — they are meaningless elsewhere.

MouseScopedApp final class

The model bin/candy-sql runs: App with a per-frame mouse-tracking mode.

MethodSummary
__construct(public readonly App $app)
init(): ?\Closure
update(Msg $msg): array
view(): View
subscriptions(): ?Subscriptions

ParamPrompt final class

SQL-O23 (once-030): the per-parameter prompt line's session slice.

MethodSummary
__construct(public readonly string $sql, public readonly array $labels, public readonly int $index = 0, public readonly string $buffer = '', public readonly array $values = [])
withBuffer(string $buffer): self
withStepped(array $values): self
bindForm(array $values): arrayThe PDO-shaped bind array for the completed walk: a positional list when every label is a #n slot, an association when the statement spoke :name placeholders (labels are the bare names then).

QueryState final class

SQL-editor slice of the \SugarCraft\Sql\App model: the sugar-forms TextArea plus executed-query history and favorites. Grouped out of App's constructor per plan 3.3.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
__construct(public readonly ?TextArea $editor = null, public readonly array $history = [], public readonly array $favorites = [], public readonly int $queryGen = 0, public readonly ?int $recallIndex = null, public readonly ?string $plan = null, public readonly ?ParamPrompt $paramPrompt = null, public readonly ?array $paramValues = null)
static new(): self
withEditor(?TextArea $editor): self
withHistory(array $history): self
withRecordedQuery(string $sql): selfRecord one executed statement at the front of the history (newest first): consecutive repeats dedupe and the list is capped at self::HISTORY_MAX (client-016). The single home for the rule keeps the sync run leg and the async pre-dispatch leg honest to the same shape.
withFavorites(array $favorites): self
withRecallIndex(?int $recallIndex): selfTrack the SQL-O01a recall walk: index into self::$history of the entry currently staged in the editor, or null when no walk is active. Any direct edit ends the walk; Up/Down then continue walking only while the editor still holds the recalled text verbatim.
withIncrementedQueryGen(): selfAdvance the async query generation (client-012). The old staleness arm compared SQL TEXT (history[0] === $msg->sql), so SELECT → write → re-SELECT admitted the older in-flight answer back over the newer one (pre-write data settled on screen). Bumped at each async dispatch, the generation rides the reply Msg and the fold only accepts its own — any superseded leg drops regardless of how the statements read.
withPlan(?string $plan): selfANSI tree of the last leading-EXPLAIN the user typed (SQL-O09). \SugarCraft\Sql\Renderer renders the Rows pane from this while it is set; the next query or table preview clears it.
withParamPrompt(?ParamPrompt $prompt): selfSQL-O23: open/close the per-parameter prompt line.
withParamValues(?array $values): selfSQL-O23: the bind array the next dispatch consumes (null = unbound).

UiState final class

Chrome slice of the \SugarCraft\Sql\App model: which pane has focus and the status-line error/info text. Grouped out of App's constructor per plan 3.3.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
__construct(public readonly Pane $pane = Pane::Tables, public readonly ?string $error = null, public readonly ?string $status = null, public readonly ?string $armedDestructive = null, public readonly ?CancellationSource $inFlight = null, public readonly bool $txOpen = false, public readonly bool $helpOverlay = false)
static new(): self
withPane(Pane $pane): self
withError(?string $error): self
withStatus(?string $status): self
withArmedDestructive(?string $sql): self
withInFlight(?CancellationSource $source): self
withTxOpen(bool $open): self
withHelpOverlay(bool $open): selfSQL-O21: open/close the ? key-help overlay.

SugarCraft\Sql\Core\Msg

AdminDataLoadedMsg final readonly class

Dispatched when async admin data fetch completes. Carries status vars, server vars, and fetch timestamp.

MethodSummary
__construct(public array $statusVars, public array $serverVars, public float $fetchedAt)

AdminDrainCompletedMsg final readonly class

Dispatched when a drain-only admin fetch settles: the page-registered pending queries (SHOW FULL PROCESSLIST, sys reports, availability probes) have landed in AdminQueryCache, while the status/server variable caches were intentionally NOT re-fetched (still inside their TTL window).

AdminFetchStartedMsg final readonly class

Dispatched when an async admin data fetch begins. Signals the UI to show a loading indicator.

AdminTickMsg final readonly class

Fired every second by the Admin pane's stable 'admin-fetch' tick.

QueryRowsLoadedMsg final readonly class

Dispatched when an async query execution completes.

MethodSummary
__construct(public string $sql, public array $rows, public ?string $error, public int $queryGen)

ReloadReportMsg final readonly class

Dispatched after AdminDataLoadedMsg to trigger async report reload. ReportsPage handles this by calling loadCurrentReport() which queues the report query via AsyncCachedConnection for the next tick.

TableRowsLoadedMsg final readonly class

Dispatched when an async table-row browse fetch completes.

MethodSummary
__construct(public string $table, public array $rows, public ?string $error, public int $loadGen)

SugarCraft\Sql\Db

ConnectionConfig final readonly class

Readonly value object representing database connection configuration.

MethodSummary
__construct(public string $driver, public string $host, public int $port, public string $user, public string $pass, public string $dbname, public string $sslMode, public string $dsn)
static new(string $driver, string $host, int $port, string $user, string $pass, string $dbname, string $sslMode = 'prefer'): selfCreate a ConnectionConfig from individual components.

ConnectionFactory final class

Factory for creating DatabaseInterface instances from various config sources.

MethodSummary
static fromDsn(string $dsn): ConnectionConfigParse a DSN string into a ConnectionConfig.
static fromConfig(ConnectionConfig $config): DatabaseInterfaceCreate a DatabaseInterface from a ConnectionConfig.
static fromArgv(array $argv): DatabaseInterfaceCreate a DatabaseInterface from CLI argv arguments.
static fromPath(string $path): SqliteDatabaseCreate a DatabaseInterface from a bare SQLite path.

ConnectionStore final class

On-disk registry of named connections (SQL-O02, candy-sql-once-002).

MethodSummary
__construct(private readonly string $path)
static defaultPath(): ?stringThe canonical config path: $XDG_CONFIG_HOME/candy-sql/connections.json, falling back to $HOME/.config/... — null when neither home resolves (a container without HOME has no well-known location to read or write).
static open(): ?selfOpen the store at the default location, or null when no location resolves. A missing file is an empty store, not an error — first-run is the common case this path serves.
path(): string
all(): arrayAll entries keyed by connection name, sorted by name for stable picker and refusal output.
names(): array
argv(string $name): arrayExpand one saved entry into the flag list ConnectionFactory::fromArgv accepts, resolving the entry's pass-env reference against the live environment at dial time.
save(string $name, array $fields): voidWrite (or replace) one named entry and persist atomically. Fields keep the same grammar the reader enforces, so a save can never mint a file its own loader would refuse.

DatabaseInterface interface

Database interface for candy-sql.

MethodSummary
tables(): arrayGet all table/view names in the database.
rows(string $table, int $limit = 100, int $offset = 0): arrayGet rows from a specific table, paged.
query(string $sql): array|nullExecute an arbitrary SQL query.
lastInsertId(): string|intGet the ID of the last inserted row.
quote(string $value): stringQuote a string value for safe SQL inclusion.
exec(string $sql): intExecute a non-select SQL statement.
close(): voidClose the database connection.
serverVersion(): stringGet the database server version string.
driverName(): stringGet the driver name.
ping(): boolCheck if the database connection is alive.
databases(): arrayGet list of database names (for multi-database drivers).
prepare(string $sql): ?PreparedStatementInterfacePrepare a SQL statement for execution.
dsn(): stringGet the DSN connection string.
username(): stringGet the database username.

DmlBuilder final class

Builds the single-row writes behind the Rows pane's cell editor (SQL-O03).

MethodSummary
static new(Flavor $flavor): self
update(string $table, array $key, string $column, ?string $value): DmlStatementUPDATE one column of the row addressed by $key.
insert(string $table, array $values): DmlStatementINSERT one row. Columns absent from $values take their DEFAULT.
delete(string $table, array $key): DmlStatementDELETE the row addressed by $key.

DmlRunner final class

Runs one DmlStatement with transaction semantics (SQL-O03).

MethodSummary
static run(DatabaseInterface $db, DmlStatement $s): int

DmlStatement final class

One parameterised write the in-grid editor is about to run (SQL-O03).

MethodSummary
__construct(public readonly string $kind, public readonly string $sql, public readonly array $params, public readonly string $display, public readonly int $expect = 1, public readonly bool $allowZero = false)

Flavor enum

Database flavor enumeration for multi-driver support.

Cases: MySQL · MariaDB · Percona · Postgres · Sqlite

PHP also provides cases(), from() and tryFrom().

MethodSummary
static detectFromVersionString(string $version, string $versionComment = ''): selfDetect the database flavor from version string and optional version comment.
static detectFromDriver(string $driverName, string $version = '', string $versionComment = ''): selfDetect the database flavor from driver name.

Identifier final class

Centralized SQL identifier quoting for multi-driver support.

MethodSummary
static quote(Flavor $flavor, string $name): stringQuote a SQL identifier (table name, column name, etc.) for safe inclusion in a query string, using the appropriate quote character for the given flavor.
static quoteLiteral(Flavor $flavor, string $value): stringQuote a database identifier-VALUED string literal — the correct genre for WHERE table_name = <here> comparisons against information_schema columns.

MysqlDatabase final class

MySQL implementation of DatabaseInterface using PDO.

MethodSummary
static connect(ConnectionConfig $config): selfConnect to a MySQL database using connection configuration.
static requiresVerifiedTls(string $sslMode): boolWhether an ssl-mode DEMANDS a verified TLS connection on the sync PDO path — the same table self::sslDriverOptions() honours, read as a security contract instead of a driver-options map.
tables(): array
rows(string $table, int $limit = 100, int $offset = 0): array
query(string $sql): array|nullRun a typed statement and materialise the complete result set.
lastInsertId(): string|int
quote(string $value): string
exec(string $sql): int
close(): void
serverVersion(): string
driverName(): string
ping(): bool
databases(): array
prepare(string $sql): ?PreparedStatementInterface
lastUptime(): ?floatGet the last known server uptime.
trackUptime(?float $uptime): voidUpdate the tracked server uptime.
setReconnectManager(ReconnectManagerInterface $reconnectManager): voidInject a ReconnectManager for connection error handling.
setSampler(SamplerInterface $sampler): voidInject a Sampler for reset signaling after server restarts.
dsn(): string
username(): string
password(): stringWHY this exists: ServerContext::password() delegates here through a method_exists() guard, and App's async admin fetch authenticates with it. Audit commit c22d8d31f deleted this as "unused" — static analysis missed the dynamic call, so every async admin query silently sent an empty password ("using password: NO") and the dashboard stayed empty.
sslMode(): stringThe ssl-mode this connection was opened with ('' before connect()). App reads it to decide whether the async transport must stand down — see self::requiresVerifiedTls().

NullDatabase final class

Null-object database that answers every read with empty data.

MethodSummary
tables(): array
rows(string $table, int $limit = 100, int $offset = 0): array
query(string $sql): array|null
lastInsertId(): string|int
quote(string $value): string
exec(string $sql): int
close(): void
serverVersion(): string
driverName(): string
ping(): bool
databases(): array
prepare(string $sql): ?PreparedStatementInterface
dsn(): string
username(): string

PdoPreparedStatement final class

Generic PDO prepared statement wrapper implementing PreparedStatementInterface.

MethodSummary
__construct(private readonly ?\PDOStatement $inner)
execute(?array $params = null): bool
fetch(): array|false
fetchAll(): array
rowCount(): int
closeCursor(): bool

PostgresDatabase final class

PostgreSQL implementation of DatabaseInterface using PDO.

MethodSummary
static connect(ConnectionConfig $config): selfConnect to a PostgreSQL database using connection configuration.
tables(): array
rows(string $table, int $limit = 100, int $offset = 0): array
query(string $sql): array|nullRun a typed statement and materialise the complete result set.
lastInsertId(): string|int
quote(string $value): string
exec(string $sql): int
close(): void
serverVersion(): string
driverName(): string
ping(): bool
databases(): array
prepare(string $sql): ?PreparedStatementInterface
dsn(): string
username(): string
password(): stringPostgresServerContext::password() delegates here through a method_exists() guard; the async admin fetch authenticates with it. Restored alongside MysqlDatabase::password() (see the WHY comment there — same dynamic-call miss), so the pg admin pane does not silently send an empty password.

PreparedStatementInterface interface

Driver-neutral prepared statement interface.

MethodSummary
execute(?array $params = null): boolExecute the prepared statement with optional parameters.
fetch(): array|falseFetch the next row from the result set.
fetchAll(): arrayFetch all rows from the result set.
rowCount(): intGet the number of rows affected by the last query.
closeCursor(): boolClose the cursor, enabling the statement to be executed again.

PreviewQuery final class

Builds blob-safe "row preview" SQL for the TUI table browser.

MethodSummary
static columnsSql(Flavor $flavor, string $table): stringThe introspection query listing a table's columns and their types. MySQL/Postgres read information_schema; SQLite uses PRAGMA table_info.
static classify(Flavor $flavor, array $rows): arrayNormalise raw introspection rows into a column list with an elide flag.
static build(Flavor $flavor, string $table, array $columns, int $limit = self::DEFAULT_LIMIT, int $offset = 0): stringAssemble the blob-safe preview SELECT. Falls back to SELECT * when the column list is empty (introspection failed / table not visible) so a preview still renders.
static elides(Flavor $flavor, string $type): boolWhether the browse preview shows a column of this declared type as a size placeholder instead of its bytes. Public because the cell editor (SQL-O03) must not treat a placeholder as the cell's real value — it would write [blob 12 bytes] over the data it stands in for.

ReconnectException final class

Thrown when reconnection to the database fails after a connection error.

MethodSummary
__construct(string $message, private readonly \PDOException $original, int $code = 0, ?\Throwable $previous = null)
original(): \PDOExceptionGet the original PDO exception that triggered the reconnect attempt.
getOriginal(): \PDOExceptionBC forwarder for the pre-rename accessor name.

ReconnectManagerInterface interface

Db-layer seam for connection-reconnect policy.

MethodSummary
shouldReconnect(\PDOException $e): boolDecide whether the given PDO error warrants a reconnect attempt.
attemptReconnect(callable $connect): boolAttempt a reconnect using the supplied connection factory.
setConnectionConfig(ConnectionConfig $config): voidRemember the config to use for reconnection attempts.

SamplerInterface interface

Db-layer seam for the metric sampler.

MethodSummary
resetAll(): voidClear all accumulated sampling state (e.g. after a reconnect).

ServerVersion final readonly class

Immutable value object representing a database server version.

MethodSummary
__construct(public int $major, public int $minor, public int $release, public string $raw)
static parse(string $version): selfParse a version string into a Version value object.
isMariaDb(): boolTrue when the raw version string carries the MariaDB identity marker.
isAtLeast(int $major, int $minor = 0, int $release = 0): boolCheck if this version is at least the specified version.
__toString(): stringReturn the raw version string.

SqliteDatabase final class

SQLite implementation of DatabaseInterface.

MethodSummary
__construct(\PDO $pdo, string $path = ':memory:')
static open(string $path): selfOpen a SQLite database file.
tables(): array
rows(string $table, int $limit = 100, int $offset = 0): array
query(string $sql): array|nullRun a typed statement and materialise the complete result set.
lastInsertId(): string|int
quote(string $value): string
exec(string $sql): int
close(): void
serverVersion(): string
driverName(): string
ping(): bool
databases(): array
prepare(string $sql): ?PreparedStatementInterface
dsn(): string
username(): string

SugarCraft\Sql\Db\Export

CsvExporter final class

CSV import/export service using a DatabaseInterface instance.

MethodSummary
__construct(private readonly DatabaseInterface $db)
importCsv(string $path, string $table): voidImport a CSV file into a table.
exportReportResults(string $path, array $columns, array $rows): voidExport report results to a CSV file.
exportReportResultsToString(array $columns, array $rows): stringExport report results to a CSV string.
exportCsv(string $path, string $table): voidExport a table to a CSV file.

SqlExporter final class

SQL export service using a DatabaseInterface instance.

MethodSummary
__construct(private readonly DatabaseInterface $db)
exportSql(string $path): voidExport the entire database to a SQL dump file.

SugarCraft\Sql\Explain

ExplainProviderInterface interface

Driver-aware interface for EXPLAIN output.

MethodSummary
explain(string $sql): arrayExecute EXPLAIN and return parsed output as an array.
driverName(): stringThe driver name this provider handles.

MysqlExplainProvider final class

MySQL EXPLAIN provider.

MethodSummary
__construct(private readonly DatabaseInterface $db)
explain(string $sql): arrayExecute EXPLAIN FORMAT=JSON and return parsed tree structure.
driverName(): string
getDriverName(): stringBC forwarder for the pre-rename accessor name.

PostgresExplainProvider final class

PostgreSQL EXPLAIN provider.

MethodSummary
__construct(private readonly DatabaseInterface $db)
explain(string $sql): arrayExecute EXPLAIN (FORMAT JSON) and return parsed tree structure.
driverName(): string
getDriverName(): stringBC forwarder for the pre-rename accessor name.

SqliteExplainProvider final class

SQLite EXPLAIN QUERY PLAN provider.

MethodSummary
__construct(private readonly DatabaseInterface $db)
explain(string $sql): arrayExecute EXPLAIN QUERY PLAN and return raw rows.
driverName(): string
getDriverName(): stringBC forwarder for the pre-rename accessor name.

SugarCraft\Sql\Schema

MysqlSchemaProvider final class

MySQL schema provider using information_schema queries.

MethodSummary
__construct(private readonly DatabaseInterface $db)
tables(): arrayList all user tables (non-system tables).
columns(string $table): arrayList all columns for a given table.
indexes(string $table): arrayList all indexes for a given table.
foreignKeys(string $table): arrayList all foreign keys for a given table.
dropTable(string $table): voidDrop a table by name.
withFlavor(Flavor $flavor): selfReturn a new instance with the specified flavor.

PostgresSchemaProvider final class

PostgreSQL schema provider using information_schema and pg_catalog.

MethodSummary
__construct(private readonly DatabaseInterface $db)
tables(): arrayList all user tables (non-system tables).
columns(string $table): arrayList all columns for a given table.
indexes(string $table): arrayList all indexes for a given table.
foreignKeys(string $table): arrayList all foreign keys for a given table.
dropTable(string $table): voidDrop a table by name.
withFlavor(Flavor $flavor): selfReturn a new instance with the specified flavor.

SchemaColumn final class

MethodSummary
__construct(public readonly int $cid, public readonly string $name, public readonly string $type, public readonly bool $notNull, public readonly mixed $defaultValue, public readonly bool $primaryKey)

SchemaForeignKey final class

MethodSummary
__construct(public readonly int $id, public readonly string $column, public readonly string $foreignTable, public readonly string $foreignColumn, public readonly string $onUpdate, public readonly string $onDelete)

SchemaIndex final class

MethodSummary
__construct(public readonly string $name, public readonly bool $unique, public readonly array $columns)

SchemaProviderInterface interface

Interface for driver-aware schema introspection.

MethodSummary
tables(): arrayList all user tables (non-system tables).
columns(string $table): arrayList all columns for a given table.
indexes(string $table): arrayList all indexes for a given table.
foreignKeys(string $table): arrayList all foreign keys for a given table.
dropTable(string $table): voidDrop a table by name.
withFlavor(Flavor $flavor): selfReturn a new instance with the specified flavor.

SchemaTable final class

MethodSummary
__construct(public readonly string $name, public readonly array $columns, public readonly array $indexes, public readonly array $foreignKeys)
column(string $name): ?SchemaColumn

SqliteSchemaProvider final class

SQLite schema provider using PRAGMA queries.

MethodSummary
__construct(private readonly DatabaseInterface $db)
tables(): arrayList all user tables (non-system tables).
columns(string $table): arrayList all columns for a given table.
indexes(string $table): arrayList all indexes for a given table.
foreignKeys(string $table): arrayList all foreign keys for a given table.
dropTable(string $table): voidDrop a table by name.
withFlavor(Flavor $flavor): selfReturn a new instance with the specified flavor.

Configuration

Connection details come from a DSN, from individual flags, or from a saved connection. Each one is a route into the same ConnectionFactory.

Command-line flags

FlagEffect
--dsn=URLA DSN for sqlite://, mysql:// or pgsql://. The same string also works as the positional argument. sqlite://:memory: gives a throwaway database.
--driver=NAMEsqlite, mysql or pgsql. Used with --db when no DSN is given.
--host=HOST, --port=PORTServer address and port.
--user=USERDatabase user.
--pass=PASSPassword on the command line. Prefer CANDY_SQL_PASS, which keeps it out of the process list.
--db=NAMEDatabase name, or the SQLite file path.
--ssl-mode=MODETLS mode for the server connection. See the DSN and MySQL SSL notes in the README.
--connect=NAMEDial a saved connection. It cannot be combined with explicit connection arguments.
--read-onlyTurns the in-grid edit chords off for the session.
--history=PATHStore the status-snapshot history at PATH instead of the default.
--no-historyTurn off status-snapshot recording.
--help, --versionPrint the usage or the build stamp, then exit 0.

Flags use the equals form only. The positional argument takes a DSN or a SQLite path.

Environment and files

NameDefaultEffect
CANDY_SQL_PASSunsetPassword fallback for an individual flag connection, or for a saved connection with no pass-env.
pass-env (in a saved connection)noneNames the environment variable that holds the password. It is read at dial time. A pass field in the file is refused.
XDG_CONFIG_HOME, HOMEfirst setThe saved connections live in candy-sql/connections.json under the config directory. The directory is created with mode 0700 and the file with 0600.
HOMErequired for historyThe default history is $HOME/.candy-sql/history.db. If HOME is unset, recording stays disabled.
NO_COLOR, TERM, COLORTERMdetectedRead through sugar-core's color detection. NO_COLOR and TERM=dumb remove the color.

Saved connections file

{
  "connections": {
    "prod":    {"driver": "mysql", "host": "db.example.com", "port": "3306",
                "user": "app", "db": "shop", "ssl-mode": "verify_identity",
                "pass-env": "PROD_DB_PASS"},
    "local":   {"driver": "pgsql", "host": "127.0.0.1", "port": "5432",
                "user": "pg", "db": "dev"},
    "scratch": {"driver": "sqlite", "db": "/tmp/scratch.sqlite"}
  }
}

Allowed fields are driver, host, port, user, db, ssl-mode and pass-env. An unknown field, an unsupported driver, a non-numeric port or a malformed name is refused by name, with one line and exit status 2. Passwords are never stored on disk.

Status-snapshot history

The launcher records the admin poll snapshots to SQLite by default. The file is $HOME/.candy-sql/history.db, or the path given to --history. It is created with mode 0600 inside a 0700 directory. A snapshot is a timestamped map of server status variables, and SQL statement text is never persisted.

Recording applies to MySQL and PostgreSQL only. A SQLite session has no status feed, so the history file stays empty for it. Retention is bounded by two caps, the newest 10 000 rows and the last 72 hours, and whichever discards more wins. The sweep runs at open and after every insert.

Keys

The ? overlay shows the bindings of the pane you are in, generated from the same routing table as the status-line legends. Any key closes it.

KeyAction
TabCycle the pane: Tables, Rows, Query, Admin
↑/↓, j/kMove the cursor in the active list. In the Query pane the arrows move between lines.
←/→, h/lMove the cell cursor between columns in the Rows pane, scrolling the grid to keep it in view
Enter, Space (Tables)Load the highlighted table into the Rows pane
e (Rows)Edit the cell under the cursor. Shows the UPDATE and writes on Enter
o (Rows)Insert a row. Prompts for each column, then shows the INSERT
D (Rows)Delete the row under the cursor. Shows the DELETE and writes on Enter
y (Rows)Yank the cell to the terminal clipboard over OSC 52. Dumb and Linux-console terminals never receive the sequence
Ctrl+R, Ctrl+E, Ctrl+EnterRun the SQL in the Query pane
Ctrl+FSave the Query pane's text to the favorites list. Ctrl+Shift+F removes it
x, iOpen the export or import line (Tables or Rows)
Ctrl+SOpen the export line from any pane while rows are on screen
HRead the recorded status history
:tx, :tx begin, :tx commit, :tx rollbackTransaction control on the sync session, typed in the Query pane. :tx and :tx begin open, commit closes, and rollback closes and discards the work
[p] (Admin)Pause or resume the admin auto-refresh
?Toggle the key-help overlay
q, EscCancel a running query first when one is in flight. Otherwise q and Esc quit from the Tables and Rows panes. Inside Admin, q returns to Tables and Esc closes an open dialog
Ctrl+CCancel the running query when one is in flight. Quits when idle

While a text line owns the keyboard, q, Tab and x are ordinary letters.

Theming and styling

candy-sql ships no theme file. Its colors come from the terminal profile that sugar-core detects, so NO_COLOR, TERM=dumb and COLORTERM decide what you see. The focus marker is a bold ▶ on the pane's frame title. That glyph survives NO_COLOR, where a hue change would vanish, and the status-line legends and the error: word stay readable without color.

The result grid uses a reverse-video cursor on styling terminals. JSON cells pretty-print with a two-space indent, and long rows scroll horizontally. The renderer does not offer a high-contrast mode or a reduced-motion toggle. The [p] key freezes the dashboard gauges at their last values until it is pressed again. The 1-second admin fetch keeps running while paused, so the cached server status still refreshes.

Examples

examples/play.php seeds an in-memory SQLite database with two tables, users and posts, and opens the dashboard over it. It takes no arguments. Run it in a terminal with php examples/play.php, and quit with q or Ctrl+C. Non-interactively, printf 'q' | php examples/play.php starts the app, reads the quit key and exits 0. With stdin at /dev/null it exits 0 at once, because end of file on stdin ends the run. It keeps running only while stdin is an open stream, so write a key to an open pipe to drive it.

The Admin pane needs a MySQL or PostgreSQL server, so on the example's SQLite database it shows the fallback. For the headless path, see ResultTable::renderPlain() under Tasks, in Drive it from a script.

Testing

Run the suite from the package root after composer install:

vendor/bin/phpunit

Most tests use an in-memory SQLite database, so they need no server. The live MySQL leg in tests/Db/MysqlConnectedPathTest.php runs only when CANDY_SQL_MYSQL_DSN names a reachable server, and it is skipped otherwise. tests/SiteBodyTruthTest.php checks that the API rows on this page name real classes and that the equals-form flags it lists still exist.

Troubleshooting

The launcher says "no such SQLite file"

The path names a file that does not exist. candy-sql does not create SQLite files, so an empty file cannot appear and lose writes at exit. Point it at an existing file, or create the file first, for example with sqlite3 fresh.sqlite < dump.sql. :memory: is exempt.

A MySQL or PostgreSQL connection fails because its PDO driver is missing

The matching PDO driver is not installed. Install ext-pdo_mysql for mysql:// DSNs and --driver=mysql, or ext-pdo_pgsql for pgsql:// DSNs and --driver=pgsql. Without pdo_mysql, a MySQL DSN stops with candy-sql: Undefined constant PDO::MYSQL_ATTR_SSL_CA and exit status 2. Without pdo_pgsql, a PostgreSQL DSN stops with PDO's could not find driver and exit status 2.

The launcher prints USAGE, or refuses a piped stdout, and exits 2

With no DSN, no flags and no saved connection, the launcher prints USAGE. Give a DSN, use --connect=NAME, or run the command in a terminal. A piped or redirected stdout is refused with this launcher drives an interactive terminal and refuses to stream ANSI onto a pipe (exit 2), even when a path is given, for example candy-sql app.sqlite | cat. Use a pseudo-terminal when scripting.

A warning says "history recording DISABLED"

The history file is corrupt or cannot be written. The session runs without history and says so on stderr. Relocate the file with --history=PATH, or turn recording off with --no-history.

A query timeout does not fire

The SIGALRM timeout needs ext-pcntl, which Windows and slim Docker php-cli images often lack. Without it the timeout falls back to the driver's network timeout. Install the extension, or run on a host that has it.

A saved connection is refused because of a pass field

A pass field in connections.json is a hard refusal, because passwords are never stored on disk. Move the password to an environment variable, and name that variable with pass-env.

Editing a cell is refused

Edits address rows by their full primary key. A table with no primary key, a NULL or binary key value, a binary or large cell, a query-result view, or a --read-only session all refuse with a named reason. A write that touches a different row count than promised is rolled back.

y copies nothing to the clipboard

The clipboard uses OSC 52. A terminal that reports TERM=dumb, TERM=linux or nothing never receives the sequence. Use a terminal that supports OSC 52.

Upstream mapping

lazysql is the design antecedent. Its Tables, Rows and Query layout, and its change-cell, new-row and delete-row flow, are the model for the editable Rows pane. The admin dashboard is modeled on MySQL Workbench. candy-sql is native PHP, and it is not a line-by-line port, so there is no class-for-class table. The README's Editing table data section names the lazysql flow it follows.

Architecture

The layers run from the terminal down to the server:

  • Model. App holds the panes, the query state and the admin pages. It returns a new model for each message.
  • Database. DatabaseInterface and its PDO adapters, SqliteDatabase, MysqlDatabase and PostgresDatabase. ConnectionFactory parses a DSN, and Flavor names the server type.
  • Strategies. SchemaBrowser and ExplainView pick the driver-specific SQL for schema introspection and plan output.
  • Edits. DmlBuilder builds statements from the full primary key, and DmlRunner wraps each write in a transaction that rolls back unless the promised row count changed.
  • Admin. AdminProviderInterface gives one port for admin data, with a MySQL and a PostgreSQL adapter. The pages sit on top of it.
  • History. HistoryRecorder writes snapshots through SqliteHistoryStore.

Known limitations

The gaps are pre-1.0, and most sit on the asynchronous ReactPHP query path.

  • No connection pooling. One async connection per flavor, DSN and user is cached and reused. Concurrent admin queries are serialized onto that connection.
  • No transactions on async connections. ReactMysqlConnection and ReactPostgresConnection run single statements. A BEGIN and COMMIT that spans several queries is not coordinated on that path.

Changelog and versioning

candy-sql is pre-1.0. The rolling prerelease is tagged candy-sql/latest, and it carries the MySQL, PostgreSQL and admin pages. The README's Deprecated: Database class section covers the move: Database is now a deprecated alias for SqliteDatabase, and DatabaseInterface is the name to use.

  • sugar-core provides the program loop, the color detection and the translation registry.
  • candy-git and candy-files are other SugarCraft apps on the same stack.

Source & demos

Try the quickstart →

Demos.

VHS-recorded GIF of the dashboard on a seeded in-memory database, regenerated automatically on every push that touches the source.

Play

Play

A seeded SQLite database opened in the dashboard — cycle tables, Tab to the query pane, run a SELECT, Ctrl+R to run.