CandySql
Terminal SQL client
Composer-installable multi-driver SQL TUI: connect to SQLite, MySQL, or PostgreSQL, browse tables, peek at row data, run ad-hoc queries, and explore a full MySQL-Workbench-style admin dashboard — all on the SugarCraft stack. SQLite-first; MySQL and PostgreSQL drivers plus a Performance Dashboard, Server Status, Variables, Connections, Reports, and Performance Schema Setup ship on dev-master (rolling prerelease tag candy-sql/latest). 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
type IN (table, view) in sqlite_master excluding sqlite_* internals.:memory: driving in tests covers the full transition surface without fixture files.SchemaProviderInterface (SqliteSchemaProvider, MysqlSchemaProvider, PostgresSchemaProvider) based on Flavor. Returns immutable SchemaTable/SchemaColumn/SchemaIndex/SchemaForeignKey value objects.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.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.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.5.5.5- prefix. isAtLeast($major, $minor = 0, $release = 0) compares versions safely.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.scrollLeft()/scrollRight()/render()/renderPlain().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.$Set sentinels for nullability.SHOW GLOBAL STATUS: threads-connected/running/cached, connections, aborted-connects, connection-errors. Computes connectionUsageRatio() lazily (0.0–1.0); isConnectionUsageCritical() returns true ≥80%.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).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).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.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.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.[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.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.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).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.flavor(), fetchStatusVariables(), fetchServerVariables(), fetchProcesslist(), maxConnections(), statusVariablesTs(), wasReset(), refresh(). Implemented by MysqlAdminProvider (MySQL) and PostgresAdminProvider (PostgreSQL via pg_stat_database, pg_settings, pg_stat_activity).AdminProviderInterface adapter over ServerContext — the context issues SHOW GLOBAL STATUS, SHOW GLOBAL VARIABLES, and SHOW PLUGINS; the provider adds fetchProcesslist() (prefers performance_schema.threads, falls back to SHOW FULL PROCESSLIST).AdminProviderInterface via pg_stat_database, pg_settings, pg_stat_activity. checkAllMetrics() / checkConnectionUsage() compute PostgreSQL metrics (connection usage, cache hit rate, transaction rates, throughput); the dashboard widgets are defined in PostgresWidgetCatalog over the provider's pg_stat_database.* keys. Graceful degradation on any PDOException (returns null/stub for inaccessible panels) — Postgres privilege denials surface as SQLSTATE 42501, not MySQL error codes.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.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().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.ConnectionConfig, retries via attemptReconnect(), throws ReconnectException on failure.PDOStatement::execute() via pcntl_alarm(). Gracefully degrades when pcntl is unavailable. Cancels query via KILL CONNECTION_ID() on timeout, throws StatementTimeoutException.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.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.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.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.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).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.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.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.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.--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
- In the Tables pane, select a table and press
Enterto load it into the Rows pane. - Move the cell cursor with
←/→orh/l, and presse. Type the new value.Ctrl+Nstores NULL. - Press
Enterto show theUPDATEstatement, and pressEnteragain to commit it. Nothing is written before the secondEnter.
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.
| Class | Method | Description |
|---|---|---|
| Database ⚠️ | — | Deprecated thin alias to SqliteDatabase. Use DatabaseInterface instead. |
| MysqlDatabase | — | DatabaseInterface implementation via PDO mysql. Implements serverVersion(), driverName(), ping(), databases(). |
| PostgresDatabase | — | DatabaseInterface implementation via PDO pgsql. Implements serverVersion(), driverName(), ping(), databases(). |
| DatabaseInterface | serverVersion() | Get database server version |
| DatabaseInterface | driverName() | Get driver name (e.g., sqlite, mysql) |
| DatabaseInterface | ping() | Check connection is alive |
| DatabaseInterface | databases() | List available databases |
| DatabaseInterface | tables() | List all tables |
| DatabaseInterface | rows(table, limit, offset) | Get table rows |
| DatabaseInterface | query(sql) | Execute SQL query; returns list<array>|null — null signals a reconnectable connection error (2002/2003/2013), empty array means no rows |
| DatabaseInterface | prepare(sql) | Prepare SQL; returns PreparedStatementInterface|null — driver-neutral statement wrapper |
| PreparedStatementInterface | execute(params?) | Execute with bound params; returns bool |
| PreparedStatementInterface | fetch() | Fetch next row; returns array<string,mixed>|false |
| PreparedStatementInterface | fetchAll() | Fetch all rows; returns list<array<string,mixed>> |
| PreparedStatementInterface | rowCount() | Rows affected by last query |
| PreparedStatementInterface | closeCursor() | Close cursor, enabling re-execution |
| PdoPreparedStatement | — | PreparedStatementInterface via PDOStatement. All database implementations (MysqlDatabase, PostgresDatabase, SqliteDatabase) wrap their PDOStatement in this before returning from prepare(). |
| App | start(database, flavor = Flavor::Sqlite, ?historyRecorder = null, ?sslMode = null) | Create the app model (MySQL TLS doctrine folds to the async-off path when TLS is verifying) |
| SchemaBrowser | refresh() | Load schema via driver-specific SchemaProviderInterface |
| SchemaBrowser | new(db, flavor) | Static factory: browser bound to a Database and its Flavor |
| SchemaProviderInterface | tables(pdo) | List all tables/views |
| SchemaProviderInterface | columns(pdo, table) | Get columns for a table |
| SchemaProviderInterface | indexes(pdo, table) | Get indexes for a table |
| SchemaProviderInterface | foreignKeys(pdo, table) | Get foreign keys for a table |
| SqliteSchemaProvider | — | SchemaProviderInterface via PRAGMA queries |
| MysqlSchemaProvider | — | SchemaProviderInterface via INFORMATION_SCHEMA |
| PostgresSchemaProvider | — | SchemaProviderInterface via pg_catalog |
| SchemaBrowser | dropTable(name) | DROP table and re-refresh |
| SchemaTable | column(name) | Find a column by name |
| ExplainView | run(db, sql) | Static: execute EXPLAIN through the driver-specific ExplainProviderInterface and return the view |
| ExplainProviderInterface | explain(pdo, sql) | Execute EXPLAIN and return explain rows |
| SqliteExplainProvider | — | ExplainProviderInterface via EXPLAIN QUERY PLAN |
| MysqlExplainProvider | — | ExplainProviderInterface via EXPLAIN |
| PostgresExplainProvider | — | ExplainProviderInterface via EXPLAIN (ANALYZE, FORMAT JSON) |
| AdminProviderInterface | flavor() | Which database flavor this provider targets |
| AdminProviderInterface | fetchStatusVariables() | All status variables (equivalent to SHOW GLOBAL STATUS; prefixed pg_stat_database.* keys on PostgreSQL) |
| AdminProviderInterface | fetchServerVariables() | All server variables (equivalent to SHOW GLOBAL VARIABLES; pg_settings on PostgreSQL) |
| AdminProviderInterface | fetchProcesslist() | Active server processes/connections — pg_stat_activity on PostgreSQL; prefers performance_schema.threads on MySQL, falls back to SHOW FULL PROCESSLIST |
| AdminProviderInterface | maxConnections() | The server's max_connections value (or equivalent) |
| AdminProviderInterface | statusVariablesTs() | Unix timestamp (float) when status variables were last fetched |
| AdminProviderInterface | wasReset() | True when the server has restarted since the last poll (MySQL via Uptime going backwards; PostgreSQL always false — detection not implemented) |
| AdminProviderInterface | refresh() | Force a refresh of all cached values |
| MysqlAdminProvider | — | AdminProviderInterface adapter over ServerContext (SHOW GLOBAL STATUS/VARIABLES/PLUGINS issued by the context); fetchProcesslist prefers performance_schema.threads, falls back to SHOW FULL PROCESSLIST |
| ConnectionsPage | new(context, maxConnections?) | Factory creating fully-wired instance with ProcesslistProvider, ConnectionActions, ConnectionDetailTabs, ConnectionCounters |
| ConnectionsPage | update(Msg) | Handle keyboard: j/k/↑/↓ navigate, f toggle filter, r refresh, y confirms a pending kill (any other key cancels). 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. |
| ConnectionsPage | table() | Get the sugar-table Table with columns: Id, User, Host, DB, Command, Time, State, Info |
| ConnectionsPage | filters() / counters() / detailTab() / selectedThread() | Read current filter state, counters, active detail tab, and selected process thread |
| ConnectionFilters | new() | Default filters: no hiding, no auto-refresh |
| ConnectionFilters | withHideSleeping(bool) / withHideBackground(bool) / withSkipFullInfo(bool) / withRefreshRate(float|null) | Fluent filter setters — all return new immutable instance |
| ConnectionCounters | fromSnapshot(snapshot, maxConnections) | Factory from StatusSnapshot: reads Threads_*, Connections, Aborted_* variables |
| ConnectionCounters | connectionUsageRatio() | Lazy-computed ratio (0.0–1.0) of threads_connected / max_connections |
| ConnectionCounters | isConnectionUsageCritical() | True when usage ≥80% (red threshold) |
| ConnectionDetailTabs | details(processId) | Basic thread info from performance_schema.threads — returns null on 1142/1146/1227 |
| ConnectionDetailTabs | attributes(processId) | Session connect attrs from performance_schema.session_connect_attrs — returns null if no attrs or access denied |
| ConnectionDetailTabs | mdlLocks(processId) | Metadata locks from performance_schema.metadata_locks (primary) with fallback to information_schema.metadata_lock_info |
| ConnectionDetailTabs | threadStack(processId) | Stack dump via sys.ps_thread_stack() — returns null if sys schema unavailable |
| ConnectionDetailTabs | explain(processId) | Runs EXPLAIN on the selected thread's current query — returns null if no query or explain fails |
| PostgresAdminProvider | — | AdminProviderInterface via pg_stat_database, pg_settings, pg_stat_activity. Dashboard widgets defined in PostgresWidgetCatalog over the provider's pg_stat_database.* keys; checkAllMetrics()/checkConnectionUsage() compute PostgreSQL metrics and threshold alerts; graceful null on SQLSTATE 42501 / any PDO failure (the provider catches PDOException generically — 1142/1146 are MySQL codes, attributed to the MySQL paths only). |
| ReportsPage | new(context, ?db) | Factory. validate() only loads Catalog (file I/O) — no blocking db->query() on render path. report queries routed through AdminQueryCache async. |
| ReportsPage | update(Msg) | Handles ReloadReportMsg (triggers loadCurrentReport), j/k navigate, r refresh, x export (CSV string into page state — not written to disk), c unit toggle, q back to Tables. |
| ReportsPage | exportToCsv() | Export current report as RFC-4180 CSV string via CsvExporter::exportReportResultsToString(). Returns '' if no report loaded. |
| ReportRunner | run(viewName, ?limit) | Execute SELECT * FROM sys.<view> with unit formatting. Throws \InvalidArgumentException if view not in catalog, \RuntimeException if view not available on server. |
| ReportRunner | runRaw(viewName, ?limit) | Execute report without unit formatting — returns raw numeric values for sorting/calculation. |
| ReportRunner | canRun(viewName) | True if report exists in catalog and its view is available on this server. |
| AvailabilityChecker | discoverViews() | Runs SHOW FULL TABLES FROM sys WHERE Table_type='VIEW'. Caches result. Catches \Throwable (not just \PDOException) because React/cached connections can surface non-PDO errors. |
| AvailabilityChecker | sysSchemaExists() | True if sys schema is accessible (runs discoverViews() internally). |
| AvailabilityChecker | isViewAvailable(viewName) | True if the named sys schema view exists on this server. |
| AvailabilityChecker | availableFromCatalog(catalog) | Return catalog reports whose views exist on this server. |
| AvailabilityChecker | missingFromCatalog(catalog) | Return catalog reports whose views are missing on this server. |
| AvailabilityChecker | reset() | Clear cached view list — force re-discovery on next call. |
| ReloadReportMsg | — | Dispatched by App after AdminDataLoadedMsg. ReportsPage handles this in update() to queue the report query via AdminQueryCache for the next tick. |
| VariablesPage | new(context, ?catalog, ?editor) | Factory. Optional Catalog (eagerly loaded variable metadata) and VariableEditor enable category tree, [rw] indicators, and inline editing. Missing catalog/editor is non-fatal — page renders without those features. |
| VariablesPage | update(Msg) | Handles keyboard: j/k navigate rows, w toggle rw filter, s focus search, e open edit dialog (dynamic vars only), q back to Tables. The [tab] Status/System toggle is page-level — in-app Tab is consumed by pane cycling first. When the edit dialog is active, delegates to updateDialog(). Returns [newPage, ?Closure]. All with*() methods return new immutable instances. |
| VariableEditor | edit(variableName, newValue) | Execute SET GLOBAL via prepared statement. Backtick-escapes variable name (from catalog), uses ? placeholder for value. Returns ['success' => bool, 'errorCode' => ?int, 'errorMessage' => ?string]. Error 1238 = variable not dynamic; 1142/1227 = privilege; 3680 = persisted_variables restriction. |
| VariableEditor | persist(variableName, newValue) | Execute SET PERSIST (MySQL 8.0+) — sets the variable globally and writes to mysqld-auto.cnf. Version-gated. Uses prepared statement with backtick-quoted name. |
| VariableEditor | persistOnly(variableName, newValue) | Execute SET PERSIST_ONLY (MySQL 8.0+) — writes to mysqld-auto.cnf without affecting the running value. Use for static variables (error 1238). Version-gated. |
| VariableEditor | resetPersist(?variableName) | Execute RESET PERSIST [x] (MySQL 8.0+). Without argument clears all persisted vars. With argument removes only that variable. No isEditable() check (it removes, not sets). Version-gated. |
| VariableEditor | editPreview(variableName, newValue, mode='global') | Return a preview string of the SET statement that would be executed. mode is 'global'|'persist'|'persist_only' (e.g. SET PERSIST `max_connections` = '200'). |
| VariableEditor | isEditable(variableName) | True if the variable has editable=true in the metadata catalog. Returns false when catalog is absent (safer default). |
| VariableMetadata | isDynamic() | True if the variable has Dynamic=true in metadata (can be changed at runtime via SET GLOBAL). Non-dynamic variables hit MySQL error 1238. |
| VariableMetadata | inGroup(group) | True if the variable belongs to the given group name. |
| Catalog | load() | Load variable metadata from data/variable_metadata.json. Throws \RuntimeException on corrupt/missing file. |
| Catalog | get(variableName) | Return VariableMetadata for a variable, or null if not in catalog. |
| Catalog | all() | Return all VariableMetadata entries keyed by variable name. |
| Catalog | groups() | Return sorted list of all group names in the catalog. |
| Catalog | isEditable(variableName) | True if variable exists in catalog and VariableMetadata.editable is true. |
| Catalog | isDynamic(variableName) | True if variable exists in catalog and VariableMetadata.isDynamic() is true. |
| ExplainView | render() | Render plan as ANSI-colored string |
| ExplainView | toArray() | Return JSON-serializable plan rows (depth, tag, detail, indent) |
| ConnectionActions | setInstrumentation(bool $enabled, int|string $threadId) | Enable/disable performance_schema instrumentation per-thread via UPDATE performance_schema.threads SET INSTRUMENTED=?. Requires MySQL 8.0+; returns false on permission errors. |
| ConnectionActions | kill(int|string $threadId, bool $isBackground) | KILL a thread (disconnect). Refuses to kill background threads (no user or NULL user). MySQL's KILL does not accept placeholders; ID is int-cast directly (injection-safe). Returns true on success, false on refusal or error. |
| ConnectionActions | killQuery(int|string $threadId, bool $isBackground) | KILL QUERY a thread (cancel statement, keep connection). Refuses to kill query on background threads. MySQL's KILL QUERY does not accept placeholders; ID is int-cast directly (injection-safe). Returns true on success, false on refusal or error. |
| ConnectionDetailTabs | explain(processId) | Runs EXPLAIN on the selected thread's current query. Accepts single SELECT statements only — rejects multi-statement queries (containing ;) and any non-SELECT statement (INSERT/UPDATE/DELETE/DROP/etc.) before running. Returns null if no query, explain fails, or query is not a single SELECT. |
| ConnectionConfig | — | Readonly value object: driver, host, port, user, pass, dbname, sslMode, dsn |
| ConnectionFactory | fromDsn(dsn) | Parse DSN string via parse_url() (mysql/pgsql) or regex (sqlite) and build a ConnectionConfig. Handles URL-encoded passwords, passwordless users, and IPv6 hosts. The ?ssl-mode= query param is parsed and stored in ConnectionConfig.sslMode; SSL is applied as PDO driver options in MysqlDatabase::connect(), not embedded in the DSN string. Examples: mysql://u:p%40ss@[::1]:3306/db, mysql://root@localhost/db. |
| ConnectionFactory | fromConfig(config) | Connect using a ConnectionConfig and return the driver's DatabaseInterface (sqlite, mysql or pgsql; any other driver throws InvalidArgumentException) |
| ConnectionFactory | fromArgv(argv) | Build a connection from CLI flags: --dsn= alone, or --driver= --db= with optional --host= --port= --user= --pass= --ssl-mode=. Equals-form only; unknown or valueless flags are refused with an InvalidArgumentException. |
| Flavor | detectFromDriver(driver, version?, versionComment?) | Detect flavor from PDO driver name ('mysql', 'pgsql', 'sqlite') + optional version string. Uses detectFromVersionString() for MySQL refinement. Ensures mysql/pgsql never falls back to SQLite for an unparseable version. |
| ServerVersion | isAtLeast($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. |
| ResultTable | fromRows(rows) | Factory from a list of associative row arrays |
| ResultTable | scrollLeft() / scrollRight() | Scroll viewport by one column |
| ResultTable | withVisibleWidth(n) / withJsonPretty(bool) / withNullToken(s) | Fluent configuration builders |
| ResultTable | render() / renderPlain() | Render ANSI string or plain text |
| CsvExporter | exportCsv(path, table) | Export a table to a CSV file (RFC-4180, formula guard on headers+values, driver-neutral column detection via LIMIT 0/LIMIT 1) |
| CsvExporter | exportReportResults(path, columns, rows) | Write a result set to a CSV file with formula guard |
| CsvExporter | exportReportResultsToString(columns, rows) | Return a result set as an RFC-4180 CSV string (used by ReportsPage [x] export) |
| CsvExporter | importCsv(path, table) | Import a CSV file into a table (backtick-quoted columns, safe VALUES) |
| SqlExporter | exportSql(path) | Dump all tables as INSERT statements to a SQL file. No CREATE TABLE (not driver-neutral). Uses LIMIT 1 for column detection. |
| ReconnectManager | shouldReconnect(pdoException) | Check if error code is 2002/2003/2013 |
| ReconnectManager | attemptReconnect(callable) | Retry connection using stored ConnectionConfig |
| ReconnectManager | setConnectionConfig(config) / lastConnectionConfig() | Store/retrieve connection config for reconnection |
| ReconnectException | — | Thrown when reconnection fails after MySQL connection error |
| StatementTimeout | execute(stmt, values) | Execute with wall-clock timeout via pcntl_alarm() |
| StatementTimeout | didTimeout() | Check if last execution timed out |
| StatementTimeoutException | — | Thrown when statement exceeds timeout and is canceled |
| Severity | toToastType() | Map to ToastType: Info→Info, Warning→Warning, Critical→Error |
| Alert | warning() / critical() / info() | Factory helpers for alert creation |
| Alert | isCritical() / isWarning() / isInfo() | Severity predicates |
| Alert | toToastMessage() | Format as "metric: message (X% > Y%)" |
| AlertThresholds | new() / standard() / strict() | Factory presets: bare, 60%/80% (standard), 50%/70% |
| AlertThresholds | connectionWarningThreshold() / connectionCriticalThreshold() | Connection usage ratio thresholds |
| AlertThresholds | withConnectionWarningThreshold() / withConnectionCriticalThreshold() | Fluent threshold setters (0.0–1.0) |
| AlertThresholds | abortedRateThreshold() / withAbortedRateThreshold() | Aborted connection rate threshold |
| AlertThresholds | slowQueryThreshold() / withSlowQueryThreshold() | Slow query time threshold in seconds |
| AlertThresholds | threadRunningThreshold() / withThreadRunningThreshold() | Thread running ratio threshold |
| AlertThresholds | connectionErrorsThreshold() / withConnectionErrorsThreshold() | Absolute connection error count threshold |
| AlertThresholds | watchedMetrics() / withWatchedMetrics() / watches() | Filter which metrics are actively watched |
| AlertThresholds | toastEnabled() / withToastEnabled() / toastPosition() / toastDuration() | Toast notification settings |
| AlertNotifier | new() / withDefaults() | Factory (muted by default when no factory provided) |
| AlertNotifier | notify(Alert) / notifyWarning() / notifyCritical() / notifyInfo() | Send notifications (all return new instance) |
| AlertNotifier | withMuted() / isMuted() | Mute state control |
| AlertNotifier | withToastFactory() | Late-bind toast factory |
| AlertNotifier | view(background, width, height) | Compose toast over viewport string |
| AlertNotifier | toast() / hasActiveAlert() | Direct toast access and state query |
| AlertManager | new() | Fresh manager with default thresholds |
| AlertManager | withThresholds() / withNotifier() | Attach threshold config and notifier |
| AlertManager | checkConnectionUsage(ConnectionCounters) | Evaluate connection counters, return array<string, Alert> |
| AlertManager | checkAllMetrics(statusVars, serverVars) | Evaluate SHOW GLOBAL STATUS/VARIABLES, return array<string, Alert> |
| AlertManager | checkAndDispatch(ConnectionCounters) | Combined check + notify, returns ['alerts', 'notifier'] |
| HistoryStoreInterface | save(snapshot) | Persist a status-variable snapshot (ts, recorded_at, variables JSON) |
| HistoryStoreInterface | query(since, until) | Retrieve snapshots within a DateTimeImmutable range |
| HistoryStoreInterface | prune(before) | Delete entries older than given DateTimeImmutable |
| HistoryStoreInterface | count() | Return total number of stored entries |
| HistoryStoreInterface | close() | Release held resources (e.g. close the SQLite database) |
| SqliteHistoryStore | __construct(dbPath) | Open or create the SQLite store: WAL, 5s busy timeout, private 0600 file / 0700 dir (a pre-existing loose file is tightened). An unusable store raises here: the launcher catches that at boot and runs history-less with a loud history recording DISABLED stderr warning; a store that dies only mid-session instead degrades per-write to the in-app query log via HistoryRecorder::record(). |
| SqliteHistoryStore | — | HistoryStoreInterface via SQLite. Schema: id, ts, recorded_at, variables (JSON). 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). |
| HistoryRecorder | record(snapshot) / recordFromProvider() | Persist snapshots directly or pulled from a wrapped StatusSnapshotProviderInterface; implements the same interface (currentSnapshot() / statusVariablesTs() / wasReset()) for downstream readers. |
| HistoryQuery | query(sinceTs, untilTs) | Raw snapshot rows in an epoch-seconds range |
| HistoryQuery | querySince(sinceTs) | Snapshots at or after a point in time |
| HistoryQuery | rate(variable, sinceTs, untilTs) | Per-second delta rate for one status variable across two snapshots (null on insufficient data) |
| PerfSchemaPage | new(context, ?detector, ?commitPlanner) | Factory. Validates PS accessibility via SELECT COUNT(*) FROM performance_schema.setup_instruments. 7 tabs: Easy Setup, Instruments, Consumers, Actors, Objects, Threads, Options. |
| PerfSchemaPage | update(Msg) | Handles keyboard: j/k nav rows, h/l and arrow keys cycle tabs, Space/Enter toggle, [ ] . easy-setup actions (enable full/disable/reset) on the Easy Setup tab, c commit (when dirty), r revert (when dirty), q back to Tables (App intercepts q in-app). Tab/Shift+Tab are page-level handlers that fire only in standalone use — in-app App consumes Tab (pane cycle) first. Returns [newPage, ?Closure]. |
| PerfSchemaPage | instruments() / consumers() / actors() / objects() / threads() / timers() | Read current tab's model list. |
| PerfSchemaPage | activeTab() / selectedRowIndex() / isReadOnly() / setupState() | Read page state: active tab name, cursor index, privilege status, detected PS setup state (fully/default/custom/disabled). |
| SetupTimers | new(name, timerName) | Factory. |
| SetupTimers | withTimerName(timerName) | Return new instance with updated timer. Marks dirty and sets changeType to CHANGE_UPDATE. No-op when timer name is unchanged. |
| SetupTimers | isDirty() | True if timer has been modified since load. |
| SetupTimers | changeType() | Returns CHANGE_UPDATE or CHANGE_NONE. |
| SetupTimers | commitStatements() | Returns ['UPDATE performance_schema.setup_timers SET `TIMER_NAME` = 'NANOSECOND' WHERE `NAME` = 'wait''] when dirty and changeType is CHANGE_UPDATE. Returns [] otherwise (including on MySQL ≥8.0 where instances are clean from performance_timers). |
| SetupTimers | nameUpper() / isCycle() | Helpers: timer name in uppercase, true if CYCLE timer. |
| SetupThreads | new(threadId, name, type, ?processlistId, ?processlistUser, ?processlistCommand, ?processlistInfo, instrumented=true) | Factory. instrumented defaults to true. |
| SetupThreads | withInstrumented(bool) | Return new instance with updated INSTRUMENTED flag. Marks dirty. No-op when state is unchanged. |
| SetupThreads | isDirty() | True if thread's INSTRUMENTED state has been modified. |
| SetupThreads | isForeground() / isBackground() / hasProcesslist() | Type predicates. |
| SetupThreads | instrumentedFragment() | Returns SQL fragment: THREAD_ID = 123 AND INSTRUMENTED = 'YES' (or 'NO'). Used by CommitPlanner to build a batch UPDATE ... WHERE IN() clause. |
| SetupThreads | commitStatements() | Returns [] — individual threads delegate to CommitPlanner for the batch IN() update. Stub for interface compatibility. |
| CommitPlanner | new(instruments, consumers, actors, objects) | Factory. Takes arrays of dirty-tracking model instances. |
| CommitPlanner | commitAll() | Generate all SQL statements for dirty instruments (anchored RLIKE), consumers (IN), actors (INSERT/UPDATE/DELETE), and objects (INSERT/UPDATE/DELETE). Returns list<array{sql:string, params:list<mixed>}> — fully parameterized with ? placeholders and bound values, no string interpolation. Returns [] when nothing is dirty. SetupTimers/SetupThreads wiring deferred to a planned follow-up. |
| CommitPlanner | commitInstruments() | Group dirty instruments by (enabled, timed) bucket; emit one UPDATE ... WHERE NAME RLIKE '^...$' per bucket. Pattern is anchored (^name$) and regex-escaped via preg_quote(); metacharacters like . / ( ) are matched literally. Returns list<array{sql:string, params:list<mixed>}>. |
| CommitPlanner | commitConsumers() | Group dirty consumers by enabled state; emit one UPDATE ... WHERE NAME IN (?,?,...) per group. All names bound as ? placeholders. Returns list<array{sql:string, params:list<mixed>}>. |
| CommitPlanner | commitActors() | Emit parameterized INSERT/UPDATE/DELETE for actors based on changeType(). All string values (HOST, USER, ROLE, ENABLED) bound as ?. Returns list<array{sql:string, params:list<mixed>}>. |
| CommitPlanner | commitObjects() | Emit parameterized INSERT/UPDATE/DELETE for objects based on changeType(). All string values (OBJECT_TYPE, OBJECT_SCHEMA, OBJECT_NAME, ENABLED, TIMED) bound as ?. Returns list<array{sql:string, params:list<mixed>}>. |
| CommitPlanner | isDirty() | True if any tracked model is dirty. |
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/.
| Method | Summary |
|---|---|
__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): self | SQL-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(): AppBuilder | Create an App via a fluent builder. |
update(Msg $msg): array | |
view(): string | |
frameMouseMode(): MouseMode | The 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(): PageBase | Lazily 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.
| Method | Summary |
|---|---|
static display(mixed $val): string | Turn 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): string | Strip 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 (...)).
| Method | Summary |
|---|---|
static complete(string $sql, int $caret, array $tables = [], ?\Closure $columnsOf = null, ?Flavor $flavor = null): Completion | Classify the caret position in $sql and gather its candidates. |
static candidates(string $prefix): array | Keywords completing $prefix (case-insensitive substring up to the caret), roster order. Empty array when nothing matches. |
static longestCommonPrefix(array $words): string | Longest 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): string | Text 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): string | The 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.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
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.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
__construct(array $raw) | |
static run(DatabaseInterface $db, string $sql): self | Run EXPLAIN against $db and return a new ExplainView. |
render(): string | Render the plan as an ANSI string for TUI display. |
toArray(): array | Return a JSON-serialisable array of the plan rows. |
Lang final class
Per-library translation facade for candy-sql.
| Method | Summary |
|---|---|
static caption(string $english): string | Localized 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().
| Method | Summary |
|---|---|
next(): self |
QueryParams final class
SQL-O23 (once-030): placeholder detection for the run-path bind prompt.
| Method | Summary |
|---|---|
static detect(string $sql): array | Ordered placeholder kinds: null = positional, string = name. |
static isMixed(array $detected): bool | True when the list mixes positional and named placeholders. |
Renderer final class
Stateless renderer for the candy-sql TUI shell.
| Method | Summary |
|---|---|
static setSize(int $cols, int $rows): void | Record the authoritative terminal size handed to us by the framework. |
static terminalSize(): array | Get 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(): array | BC forwarder for the pre-rename accessor name. |
static resetSizeCache(): void | Reset the cached terminal size (call when the terminal may have resized). |
static adminContentWidth(int $cols): int | Width 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): array | Screen 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:
| Method | Summary |
|---|---|
__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(): self | Scroll left by one column. |
scrollRight(): self | Scroll right by one column. |
withRows(array $rows): self | |
withRowOffset(int $rowOffset): self | Move 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): self | Hand 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): self | Scroll 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): self | Highlight 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(): int | Number of visible columns given current offset and width. |
canScrollLeft(): bool | Whether left-scroll is possible. |
canScrollRight(): bool | Whether right-scroll is possible. |
columns(): array | All column names (full set, not just visible). |
colWidths(): array | Width of each column in characters. |
visibleColumns(): array | Visible columns given current scroll offset. |
render(): string | Render the table as ANSI-coloured string. |
renderPlain(): string | Render the table to a plain-text string (no ANSI) for export/copy. |
SchemaBrowser final class
Schema browser with driver-aware schema introspection.
| Method | Summary |
|---|---|
__construct(private readonly DatabaseInterface $db, private readonly Flavor $flavor, private readonly SchemaProviderInterface $provider, public readonly array $tables = []) | |
static new(DatabaseInterface $db, Flavor $flavor): self | Create a new SchemaBrowser with automatic provider selection based on flavor. |
static providerFor(DatabaseInterface $db, Flavor $flavor): SchemaProviderInterface | The 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(): self | Refresh schema for all user tables. |
dropTable(string $name): self | Drop a table and return a refreshed browser. |
SqlTokenizer final class
Tiny lossless SQL lexer for the completion context classifier (SQL-O04).
| Method | Summary |
|---|---|
static tokenize(string $sql): array | |
static unquote(array $tok): string | Identifier text with its quotes stripped (word passes through). |
Version final class
The --version answer, phar-aware (the DST-1 lesson from candy-code).
| Method | Summary |
|---|---|
static current(): string | |
static resolve(string $archive, string $composerAnswer): string | The 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): ?string | The 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(): string | The 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(): string | The 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().
| Method | Summary |
|---|---|
label(): string | |
section(): AdminSection | |
static orderedCases(): array | Get all panes in the order they are displayed in the sidebar. |
AdminProviderInterface interface
Definitive interface for database-agnostic admin data access.
| Method | Summary |
|---|---|
flavor(): Flavor | Which database flavor this provider targets. |
fetchStatusVariables(): array | All status variables (equivalent to SHOW GLOBAL STATUS). |
fetchServerVariables(): array | All server variables (equivalent to SHOW GLOBAL VARIABLES). |
fetchProcesslist(): array | Active server processes/connections. |
maxConnections(): int | The server's max_connections value (or equivalent). |
statusVariablesTs(): float | Unix timestamp (float) when statusVariables was last fetched. |
wasReset(): bool | True when the server has restarted or variables were reset since last poll. |
refresh(): void | Force 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.
| Method | Summary |
|---|---|
static instance(): self | |
static reset(): void | Reset all state — intended for tests. |
lookup(string $sql): ?array | Return cached rows for a query, or null when no usable value exists yet. |
store(string $sql, array $rows): void | Cache the rows a drain leg fetched for $sql. |
markError(string $sql, string $message): void | Mark a query leg as errored WITHOUT caching an empty result (client-012). |
errorFor(string $sql): ?string | The last known failure for $sql, or null when none. Cleared by a subsequent success (self::store()) or a self::invalidateConnection()/self::forget(). |
takePending(): array | Remove and return the set of queries awaiting a fetch. |
hasPending(): bool | |
forget(): void | Drop all cached results (e.g. on an explicit refresh). |
storedAt(string $key): ?float | When 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): AsyncConnection | Lazily 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): ServerContextInterface | Single-slot memo for the synchronous-side ServerContext, keyed by the identity of the database handle it wraps. |
invalidateConnection(): void | Drop the cached async connection so the next connection() call rebuilds it via its factory. |
statusVariables(): ?array | The flattened SHOW GLOBAL STATUS map from the last async fetch, or null when nothing usable is cached. |
storeStatusSnapshot(array $vars): void | |
statusSnapshotAt(): ?float | When the current status snapshot arrived — the payload's TRUE stamp for MINOR-1 honest adoption — or null when no snapshot was ever stored. |
getStatusVariables(): ?array | BC forwarder for the pre-rename accessor name. |
serverVariables(): ?array | The 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(): ?float | When the current server snapshot arrived, or null when never stored. |
getServerVariables(): ?array | BC 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().
| Method | Summary |
|---|---|
label(): string |
AsyncCachedConnection final class
A read-through DatabaseInterface that serves query() results from the async AdminQueryCache instead of hitting the database synchronously.
| Method | Summary |
|---|---|
__construct(private readonly DatabaseInterface $inner, private readonly ?AdminQueryCache $cache = null) | |
query(string $sql): array | Serve 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.
| Method | Summary |
|---|---|
__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(): void | Re-pull the snapshot fields from the live AdminQueryCache. |
hasCachedData(): bool |
AsyncConnection interface
A non-blocking SQL connection that returns a ReactPHP promise of rows.
| Method | Summary |
|---|---|
query(string $sql, ?CancellationToken $cancellation = null): PromiseInterface | Execute a query asynchronously. |
close(): void | Retire 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.
| Method | Summary |
|---|---|
static wrap(PromiseInterface $promise, ?CancellationToken $cancellation, ?callable $onServerCancel = null): PromiseInterface |
DsnParser final class
Shared DSN value extractor for PDO-style connection strings.
| Method | Summary |
|---|---|
static extract(string $dsn, string $key): ?string | Extract 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.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
static scaleValue(float|int $value, int $decimals = 1): string | Binary (1024) scale with bare K/M/G/T suffix. |
static siBytes(float|int $bytes, int $decimals = 1): string | Decimal (1000) SI bytes (B/KB/MB/GB/TB/PB). |
static picoseconds(float|int $picoseconds): string | Picoseconds → human-readable duration. |
static duration(float|int $seconds): string | Seconds → compact human-readable duration. |
static plural(int $count, string $singular, ?string $plural = null): string | Count with a correctly pluralised noun: "1 instrument", "2 instruments". |
PageBase abstract class
Base class for admin dashboard pages.
| Method | Summary |
|---|---|
__construct(public readonly ServerContextInterface $context) | |
refresh(): self | Refresh data and return new instance. |
isModal(): bool | Whether the page currently owns an open modal editing surface. |
claimsKey(KeyMsg $msg): bool | Whether 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(): self | This 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.
| Method | Summary |
|---|---|
__construct(private readonly PostgresAdminProvider $provider, private readonly DatabaseInterface $connection, private readonly string $versionString = '') | |
static new(DatabaseInterface $connection, PostgresAdminProvider $provider): self | Create a new PostgresServerContext from a database connection. |
connection(): DatabaseInterface | |
serverVariables(): array | pg_settings with an in-window TTL cache (fail-open). |
statusVariables(): array | pg_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.
| Method | Summary |
|---|---|
static log(string $type, string $sql, int $rows, ?string $error = null): void | Log a query execution. |
static entries(): array | Get all logged entries. |
static errorEntries(): array | The error-pinned lane: every entry that carried an error, immune to housekeeping scroll-out from the main ring (client-032). |
static getEntries(): array | BC forwarder for the pre-rename accessor name. |
static clear(): void | Clear all log entries. |
static displayLines(): array | Get entries formatted for display. |
static getDisplayLines(): array | BC forwarder for the pre-rename accessor name. |
QueryTimeout final class
Deadline wrapper for async admin/query promises.
| Method | Summary |
|---|---|
static wrap(PromiseInterface $promise, float $seconds, ?LoopInterface $loop = null, ?callable $onTimeout = null): PromiseInterface | Apply a deadline to a query promise. |
ReactMysqlConnection final class
Async MySQL connection wrapper using react/mysql.
| Method | Summary |
|---|---|
__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): PromiseInterface | Execute a query asynchronously. |
close(): void | Retire the server session (admindata-004). |
ReactPostgresConnection final class
Async PostgreSQL connection wrapper using voryx/pgasync.
| Method | Summary |
|---|---|
__construct(string $dsn, string $username = '', string $password = '', ?LoopInterface $loop = null, private readonly float $queryTimeout = QueryTimeout::DEFAULT_SECONDS) | |
query(string $sql, ?CancellationToken $cancellation = null): PromiseInterface | Execute a query asynchronously. |
close(): void | Retire 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.
| Method | Summary |
|---|---|
__construct(private readonly StatusSnapshotProviderInterface $provider) | |
sample(): ?array | Compute rates from the latest polled snapshot. |
resetAll(): void | Reset state on detected server restart. |
wasReset(): bool | Check if a server restart was detected since last check. |
isFirstSample(): bool | Check if this is the first sample (no prior data). |
ServerContext final class
MySQL-focused ServerContext implementation.
| Method | Summary |
|---|---|
__construct(private readonly DatabaseInterface $connection, private readonly ?Flavor $flavor = null) | |
connection(): DatabaseInterface | |
serverVariables(): array | SHOW GLOBAL VARIABLES with an in-window TTL cache (fail-open). |
statusVariables(): array | SHOW 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): void | Adopt a snapshot the async admin pipeline fetched elsewhere (SQL-A03). |
lastUptime(): ?int | Get the last known server uptime. |
refresh(): void | Force a refresh of all cached values. |
ServerContextInterface interface
Read-only context for a database server's runtime state.
| Method | Summary |
|---|---|
connection(): \SugarCraft\Sql\Db\DatabaseInterface | Get the database connection this context is bound to. |
serverVariables(): array | All SHOW GLOBAL VARIABLES as key => value. |
statusVariables(): array | All SHOW GLOBAL STATUS as key => value. |
statusVariablesTs(): float | Unix timestamp (float) when statusVariables was last fetched. |
plugins(): array | All SHOW PLUGINS as list of row arrays. |
version(): \SugarCraft\Sql\Db\ServerVersion | Parsed server version. |
flavor(): \SugarCraft\Sql\Db\Flavor | Detected database flavor. |
versionString(): string | Raw version string as returned by the server. |
password(): string | Get the database password for async connection creation. |
wasReset(): bool | True when SHOW GLOBAL STATUS returned different Uptime than last poll (server was restarted or variables were reset). |
refresh(): void | Force a refresh of all cached values. |
ServerStatusSnapshotAdapter final class
Adapter that wraps a ServerContextInterface to provide StatusSnapshotProviderInterface.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
__construct(public array $variables, public float $ts) | |
get(string $key): ?string | Get a variable value or null if not present. |
int(string $key): ?int | Get a variable as int, or null if not present or not numeric. |
getInt(string $key): ?int | BC forwarder for the pre-rename accessor name. |
float(string $key): ?float | Get a variable as float, or null if not present or not numeric. |
getFloat(string $key): ?float | BC forwarder for the pre-rename accessor name. |
has(string $key): bool | Check if a variable exists in this snapshot. |
elapsedSince(StatusSnapshot $older): float | Compute elapsed time between this snapshot and another. |
delta(StatusSnapshot $previous): array | Create a delta snapshot (current - previous) for numeric values. |
StatusSnapshotProviderInterface interface
Provides status snapshots for polling and rate sampling.
| Method | Summary |
|---|---|
currentSnapshot(): ?array | Get the most recent status snapshot. |
statusVariablesTs(): float | Get the timestamp of the most recent snapshot. |
wasReset(): bool | Check if the server was restarted since last poll. |
SugarCraft\Sql\Admin\Alerts
Alert final class
Represents a fired alert threshold notification.
| Method | Summary |
|---|---|
__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): self | Create a warning-level alert. |
static critical(string $metric, string $message, float $value, float $threshold, MetricKind $kind = MetricKind::Ratio): self | Create a critical-level alert. |
static info(string $metric, string $message, float $value, float $threshold, MetricKind $kind = MetricKind::Ratio): self | Create an info-level alert. |
isCritical(): bool | True when this is a critical-severity alert. |
isWarning(): bool | True when this is a warning-severity alert. |
isInfo(): bool | True when this is an info-severity alert. |
toToastMessage(): string | Format alert as a short one-liner suitable for toast display. |
AlertManager final class
Stateless alert checker — evaluates metrics against thresholds.
| Method | Summary |
|---|---|
static new(): self | Fresh AlertManager with default thresholds and no notifier. |
withThresholds(AlertThresholds $t): self | Return a new AlertManager with the given threshold configuration. |
withFlavor(?Flavor $flavor): self | Return a new AlertManager that reads the given flavor's metric keys. |
flavor(): ?Flavor | |
withNotifier(AlertNotifierInterface $n): self | Return a new AlertManager with the given notifier. |
checkConnectionUsage(ConnectionCounters $counters): array | Check connection counters and fire alerts for any thresholds exceeded. |
checkAllMetrics(array $statusVariables, array $serverVariables): array | Check status and server variables for threshold violations. |
thresholds(): AlertThresholds | Get the current thresholds. |
notifier(): ?AlertNotifierInterface | Get the current notifier, if set. |
checkAndDispatch(ConnectionCounters $counters): array | Dispatch all alerts to the notifier and return a new notifier with all alerts sent. |
AlertNotifier final class
Sends alert notifications via SugarCraft\Toast\Toast.
| Method | Summary |
|---|---|
static new(?\Closure $toastFactory = null): self | Create 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): self | Create a notifier with a default Toast factory using standard position/duration. |
notify(Alert $alert): self | Notify with a pre-built Alert. |
notifyWarning(string $message): self | Send a warning notification. |
notifyCritical(string $message): self | Send a critical notification. |
notifyError(string $message): self | Send an error notification. |
notifyInfo(string $message): self | Send an info notification. |
isMuted(): bool | True when notifications are muted. |
withMuted(bool $muted): self | Return a new notifier with the given mute state. |
withToastFactory(\Closure $factory): self | Return a new notifier with an updated toast factory. |
view(string $background, int $viewportWidth = 80, int $viewportHeight = 24): string | Compose the current toast state over a background viewport string. |
toast(): ?Toast | Get the underlying Toast instance for direct manipulation. |
hasActiveAlert(): bool | True if any alerts have been queued. |
AlertNotifierInterface interface
Contract for dispatching alert notifications.
| Method | Summary |
|---|---|
notify(Alert $alert): self | Dispatch 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(): bool | True when notifications are suppressed. |
withMuted(bool $muted): self | |
view(string $background, int $viewportWidth = 80, int $viewportHeight = 24): string | Compose the current toast state over a background viewport string. |
toast(): ?Toast | The underlying Toast, or null if none has been created. |
hasActiveAlert(): bool | True if any alert is currently queued. |
AlertThresholds final class
Immutable threshold configuration for alert conditions.
| Method | Summary |
|---|---|
static new(): self | Fresh instance with no explicit thresholds set. |
static standard(): self | Standard thresholds suitable for most environments. |
static strict(): self | Stricter thresholds for sensitive/production environments. |
connectionWarningThreshold(): float | Warning threshold for connection usage ratio (0.0–1.0). |
withConnectionWarningThreshold(float $value): self | |
connectionCriticalThreshold(): float | Critical threshold for connection usage ratio (0.0–1.0). |
withConnectionCriticalThreshold(float $value): self | |
abortedRateThreshold(): float | Aborted connection rate threshold (0.0–1.0+). |
withAbortedRateThreshold(float $value): self | |
slowQueryThreshold(): float | Slow query time threshold in seconds. |
withSlowQueryThreshold(float $value): self | |
threadRunningThreshold(): float | Thread running threshold as ratio of max_connections (0.0–1.0). |
withThreadRunningThreshold(float $value): self | |
connectionErrorsThreshold(): int | Connection errors threshold (absolute count). |
withConnectionErrorsThreshold(int $value): self | |
watchedMetrics(): array | Which metrics to actively watch. |
withWatchedMetrics(array $metrics): self | |
watches(string $metric): bool | True if this threshold watches the given metric name. |
toastEnabled(): bool | True when toast notifications are enabled. |
withToastEnabled(bool $enabled): self | |
toastPosition(): Position | Screen position for toast notifications. |
withToastPosition(Position $pos): self | |
toastDuration(): ?float | Auto-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().
| Method | Summary |
|---|---|
toToastType(): \SugarCraft\Toast\ToastType | Convert to sugar-toast ToastType. |
SugarCraft\Sql\Admin\Calc
CacheHitRate final class
Computes cache hit rate as a percentage: hits / (hits + reads) * 100.
| Method | Summary |
|---|---|
__construct(private readonly string $hitKey, private readonly string $readKey) | |
compute(array $current, array $previous, float $elapsed): float | Compute 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.
| Method | Summary |
|---|---|
static local(?string $loadavgPath = null, ?string $statPath = null, ?\Closure $wallClock = null): self | Sample the machine's own /proc counters. |
static proxy(?\Closure $wallClock = null): self | Remote server: busy-proxy only, never touches the filesystem. |
static forDsn(string $dsn, ?\Closure $wallClock = null): self | Choose 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): void | Append 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.
| Method | Summary |
|---|---|
__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): float | Compute the buffer pool usage percentage. |
MakeTuple final class
Factory for creating tuple rate computations.
| Method | Summary |
|---|---|
__construct(private readonly string $separator = ',') | |
addRate(string $key): self | Add a simple rate computation. |
addTupleRate(string $key): self | Add a tuple rate computation. |
addRateAs(string $alias, string $key): self | Add 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): self | Add 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): array | Compute all rates from a current and previous snapshot. |
updateLast(array $snapshot): void | Update internal state from a snapshot. |
RatePerSecond final class
Computes the rate of change (per second) for a status variable.
| Method | Summary |
|---|---|
__construct(public readonly string $key) | |
compute(array $current, array $previous, float $elapsed): float | Compute the rate using precompiled closure. |
updateLast(array $snapshot): void | Update last known value from a snapshot. |
isInitialized(): bool | Check if this rate has been initialized with a value. |
lastValue(): float | Get the last known value. |
StatusVar final class
Looks up a raw status variable value from the current snapshot.
| Method | Summary |
|---|---|
__construct(public readonly string $key) | |
compute(array $current, array $previous, float $elapsed): string | Look up the current value of the status variable. |
computeInt(array $current, array $previous, float $elapsed): int | Get the raw value as an integer. |
computeFloat(array $current, array $previous, float $elapsed): float | Get the raw value as a float. |
exists(array $current): bool | Check if the key exists in the current snapshot. |
TableOpenCacheHitRate final class
Computes the Table Open Cache hit ratio as a percentage.
| Method | Summary |
|---|---|
__construct(private readonly string $hitKey = 'Table_open_cache_hits', private readonly string $missKey = 'Table_open_cache_misses') | |
compute(array $current, array $previous, float $elapsed): float | Compute the cache hit percentage. |
TupleRatePerSecond final class
Computes per-second rates for tuple-structured status variables.
| Method | Summary |
|---|---|
__construct(private readonly string $key, private readonly string $separator = ',') | |
compute(array $current, array $previous, float $elapsed): array | Compute tuple rates using precompiled closure. |
updateLast(array $snapshot): void | Update 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.
| Method | Summary |
|---|---|
__construct(private readonly ServerContextInterface $context) | |
static new(ServerContextInterface $context): self | Create a new instance with default context. |
kill(int|string $threadId, bool $isBackground): bool | KILL a thread (disconnect). |
killQuery(int|string $threadId, bool $isBackground): bool | KILL QUERY a thread (cancel running statement, keep connection). |
setInstrumentation(bool $enabled, int|string $threadId): bool | Enable or disable performance_schema instrumentation for a specific thread. |
isInstrumentationEnabled(): ?bool | Check if instrumentation is currently enabled. |
ConnectionCounters final class
Connection-related counters from SHOW GLOBAL STATUS.
| Method | Summary |
|---|---|
__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): self | Create from a StatusSnapshot. |
connectionUsageRatio(): float | Connection usage ratio (0.0-1.0) computed lazily. |
isConnectionUsageCritical(): bool | True when connection usage is above 80% (critical threshold). |
abortedConnectionRate(): float | Aborted connection rate per connection (0.0-1.0+). |
ConnectionDetailTabs final class
Detail tabs for a processlist thread: Details, Attributes, MDL locks.
| Method | Summary |
|---|---|
__construct(private readonly ServerContextInterface $context) | |
static new(ServerContextInterface $context): self | Create a new instance with default context. |
details(int|string $processId): ?array | Tab: basic thread details for a processlist ID. |
getDetails(int|string $processId): ?array | BC forwarder for the pre-rename accessor name. |
attributes(int|string $processId): ?array | Tab: session connect attributes for a processlist ID. |
getAttributes(int|string $processId): ?array | BC forwarder for the pre-rename accessor name. |
mdlLocks(int|string $processId): ?array | Tab: metadata locks held by a processlist ID. |
getMdlLocks(int|string $processId): ?array | BC forwarder for the pre-rename accessor name. |
threadStack(int|string $processId): ?string | Get thread stack dump via sys.ps_thread_stack(). |
getThreadStack(int|string $processId): ?string | BC forwarder for the pre-rename accessor name. |
explain(int|string $processId): ?array | Get EXPLAIN output for a thread's current query. |
getExplain(int|string $processId): ?array | BC forwarder for the pre-rename accessor name. |
ConnectionFilters final class
User-configurable filters for the connections view.
| Method | Summary |
|---|---|
static new(): self | Create with default settings (no filtering, no auto-refresh). |
withHideSleeping(bool $hide): self | Return a new instance with hide-sleeping toggled. |
withHideBackground(bool $hide): self | Return a new instance with hide-background toggled. |
withSkipFullInfo(bool $skip): self | Return a new instance with skip-full-info toggled. |
withRefreshRate(?float $rate): self | Return a new instance with refresh rate set. |
isRefreshEnabled(): bool | True when refresh is enabled (non-null rate). |
ConnectionsPage final class
Connections page component integrating processlist, counters, filters, and actions.
| Method | Summary |
|---|---|
isModal(): bool | The kill confirmation is armed — it owns every keystroke. |
__construct(ServerContextInterface $context, private readonly ?int $maxConnections = 151) | |
static new(ServerContextInterface $context, ?int $maxConnections = 151): self | Create a new connections page with standard dependencies. |
table(): Table | Get the processlist table with current filters applied. |
getTable(): Table | BC forwarder for the pre-rename accessor name. |
counters(): ConnectionCounters | Get connection counters. |
filters(): ConnectionFilters | Get current filters. |
withFilters(ConnectionFilters $filters): self | Return a new instance with updated filters. |
detailTab(): string | Get the current detail tab. |
withDetailTab(string $tab): self | Return 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(): Tabs | The 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(): ?array | The open detail panel's lines (the active tab's data for the selected thread), or null while the panel is closed. |
releaseKeys(): self | Blur 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(): bool | True while the detail-tab bar owns the tab keys (after Enter, until Esc). |
claimsKey(KeyMsg $msg): bool | While 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): array | Handle keyboard shortcuts for connection navigation and filtering. |
selectedThread(): ?ProcesslistResult | Get the selected thread for detail view. |
selectedIndex(): int | Get the current selected index in the filtered processlist. |
withSelectedIndex(int $index): self | Select a thread by index in the current filtered list. |
filteredProcesslist(): array | Get the processlist rows with current filters applied. |
refresh(): self | Refresh processlist data. |
withHeightBudget(?int $rows): self | The 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.
| Method | Summary |
|---|---|
static processlistSql(): string | The 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): self | Create a new instance with default context. |
fetchAll(): array | Fetch all processlist rows. |
refresh(): self | Clear cached PS availability and force re-detection on next fetch. |
ProcesslistResult final class
Value object holding a single processlist row.
| Method | Summary |
|---|---|
__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): self | Create from a performance_schema.threads row. |
static fromShowProcesslist(array $row): self | Create from SHOW FULL PROCESSLIST row. |
static fromPostgresRow(array $row): self | Create from a normalized Postgres processlist row. |
isBackground(): bool |
SugarCraft\Sql\Admin\Dashboard
CounterCell final class
Renders a counter widget with K/M/G scaling.
| Method | Summary |
|---|---|
__construct(private readonly Widget $widget, private readonly int $decimals = 1) | |
ingest(array $current, array $previous, float $elapsed): self | Ingest a new value from the widget's calc. |
ingestFromSnapshot(\SugarCraft\Sql\Admin\StatusSnapshot $current, \SugarCraft\Sql\Admin\StatusSnapshot $previous): self | Ingest from status snapshots. |
reset(): self | Reset the counter (call on server restart). |
hasValue(): bool | Check if the counter has a value. |
lastValue(): float | Get the last ingested value. |
rawFormatted(): string | Get the raw formatted value using the widget's format. |
scaledFormatted(string $unit = ''): string | Format the value with K/M/G scaling applied. |
view(): string | Render the counter as a string (alias for scaledFormatted). |
__toString(): string | Render as string. |
widget(): Widget | Get the associated widget. |
DashboardPage final class
Performance Dashboard page with 3-column layout.
| Method | Summary |
|---|---|
__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): self | Return a new DashboardPage with the given alert notifier. |
isPaused(): bool | |
pendingAlerts(): array | |
alertCount(): int | |
alertNotifier(): AlertNotifierInterface | |
refresh(): self | Refresh data and return new instance. |
isModal(): bool | Whether the page currently owns an open modal editing surface. |
claimsKey(KeyMsg $msg): bool | Whether 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(): self | This 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.
| Method | Summary |
|---|---|
__construct(private readonly Widget $widget, private readonly ?float $maxOverride = null) | |
ingest(array $current, array $previous, float $elapsed, ?array $serverVars = null): self | Ingest a new value, computing ratio if max is available. |
ingestFromSnapshot(\SugarCraft\Sql\Admin\StatusSnapshot $current, \SugarCraft\Sql\Admin\StatusSnapshot $previous, ?array $serverVars = null): self | Ingest from status snapshots with server variables. |
withRatio(float $ratio, ?float $value = null, ?float $max = null): self | Set the ratio directly (for level meters that get ratio from a different source). |
reset(): self | Reset the meter (call on server restart). |
hasValue(): bool | Check if the meter has a value. |
ratio(): float | Get the current ratio (0.0 to 1.0). |
percentage(): int | Get the percentage (0 to 100). |
value(): float | Get the current raw value. |
max(): float | Get the resolved maximum. |
viewRound(int $size = 14): string | Render as a round meter (donut ring with the percentage in the hole). |
viewLevel(int $width = 20): string | Render as a level/horizontal meter (Gauge). |
viewMeter(int $height = 12): string | Render as a vertical meter (Meter). |
view(): string | Render using the appropriate method based on widget kind. |
__toString(): string | Render as string. |
widget(): Widget | Get the associated widget. |
MultiSeriesCell final class
Renders a timeline widget as a multi-series braille line graph.
| Method | Summary |
|---|---|
__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): self | Ingest one sample per series from the current/previous snapshots. |
ingestFromSnapshot(StatusSnapshot $current, StatusSnapshot $previous): self | Ingest from a StatusSnapshot pair (mirrors TimeSeriesCell). |
view(?int $maxCells = null): string | Render the graph (plus a legend line when it fits). |
seriesNames(): array | |
count(): int | Total samples across all series (the dashboard-reload pin). |
isEmpty(): bool | |
latest(string $name): ?float | Latest sample of one series, or null when it has none yet. |
ceiling(): float | Current auto-scale ceiling (shared by all series). |
maxSeen(): float | |
widget(): Widget | |
reset(): self | Clear every window and scale (call on [r] reset / server restart). |
__toString(): string |
PostgresWidgetCatalog final class
PostgreSQL widget catalog for the Performance Dashboard.
| Method | Summary |
|---|---|
io(): array | I/O panel widgets (10 widgets). |
transactions(): array | Transactions panel widgets (7 widgets). |
cache(): array | Cache panel widgets (4 widgets). |
TimeSeriesCell final class
Renders a timeline (time-series) widget as a sparkline using Streamline.
| Method | Summary |
|---|---|
__construct(private readonly Widget $widget, int $windowSize = 160, int $width = 40, int $height = 8) | |
ingest(array $current, array $previous, float $elapsed): self | Ingest a new data point computed from the current and previous snapshots. |
ingestFromSnapshot(\SugarCraft\Sql\Admin\StatusSnapshot $current, \SugarCraft\Sql\Admin\StatusSnapshot $previous): self | Ingest from a StatusSnapshot and the previous one. |
reset(): self | Reset all history (call on server restart). |
ceiling(): float | Get the current ceiling value (auto-scaled "nice ceiling"). |
maxSeen(): float | Get the max seen value. |
isEmpty(): bool | Check if the cell has any data. |
count(): int | Get the number of data points in the window. |
view(): string | Render the timeline as a string. |
__toString(): string | Render as string (magic method). |
widget(): Widget | Get the associated widget. |
Widget final readonly class
Immutable dashboard widget descriptor.
| Method | Summary |
|---|---|
__construct(public string $caption, public string $kind, public object $calc, public string $format, public array $color, public string $tooltip = '', public ?array $serverVarsKeys = null) | |
title(): string | Localized 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|string | Compute the widget's current value. |
isTuple(): bool | Check if this widget's calc is a tuple (multi-series) type. |
renderTooltip(array $vars): string | Fill the tooltip template with values (SQL-P17, adminpages-018). |
formatValue(float|array $value): string | Format a value using the widget's format string. |
WidgetCatalog final class
Declarative widget tables for the Performance Dashboard.
| Method | Summary |
|---|---|
network(): array | Network panel widgets. |
mysqlPre80(): array | MySQL widgets for versions before 8.0. |
mysqlPost80(): array | MySQL widgets for version 8.0 and later. |
innodb(): array | InnoDB panel widgets. |
WidgetRegistry final class
Widget kind constants and version-gated widget assembly.
| Method | Summary |
|---|---|
static build(ServerVersion $version): array | Assemble the full widget list for a given MySQL version. |
static network(): array | Get only the Network panel widgets. |
static mysql(ServerVersion $version): array | Get only the MySQL panel widgets for a given version. |
static innodb(): array | Get only the InnoDB panel widgets. |
static buildForPostgres(): array | Assemble the full widget list for PostgreSQL. |
static postgresIo(): array | Get only the I/O panel widgets for PostgreSQL. |
static postgresTransactions(): array | Get only the Transactions panel widgets for PostgreSQL. |
static postgresCache(): array | Get only the Cache panel widgets for PostgreSQL. |
static isValidKind(string $kind): bool | Validate that a kind string is a known widget kind. |
static validKinds(): array | Get all valid widget kind constants. |
SugarCraft\Sql\Admin\Debug
DebugPage final class
Debug pane displaying the query/action log from QueryLogger.
| Method | Summary |
|---|---|
__construct(ServerContextInterface $context) | |
static new(ServerContextInterface $context): self | Create a new DebugPage from the server context. |
update(Msg $msg): array | Handle keyboard shortcuts for navigation and clearing. |
withQuit(): self | Return a clone (quit is handled by parent controller). |
cursor(): int | |
refresh(): self | Refresh data and return new instance. |
isModal(): bool | Whether the page currently owns an open modal editing surface. |
claimsKey(KeyMsg $msg): bool | Whether 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(): self | This 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.
| Method | Summary |
|---|---|
__construct(private readonly HistoryStoreInterface $store) | |
query(float $sinceTs, float $untilTs): array | Retrieve snapshots within a Unix-timestamp range (inclusive). |
querySince(float $sinceTs): array | Retrieve snapshots from a given timestamp up to now. |
rate(string $variable, float $sinceTs, float $untilTs): ?float | Compute the per-second rate of a variable over a time range. |
getRate(string $variable, float $sinceTs, float $untilTs): ?float | BC forwarder for the pre-rename accessor name. |
HistoryRecorder final class
Passive recorder that persists StatusSnapshots to a HistoryStore.
| Method | Summary |
|---|---|
__construct(private readonly HistoryStoreInterface $store, private readonly ?StatusSnapshotProviderInterface $provider = null) | |
record(StatusSnapshot $snapshot): void | Persist a snapshot to the store. |
recordFromProvider(): void | Fetch a snapshot from the injected provider and persist it. |
pruneOlderThan(\DateTimeImmutable $cutoff): int | Remove all snapshots older than the given cutoff. |
historyQuery(): HistoryQuery | SQL-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.
| Method | Summary |
|---|---|
save(StatusSnapshot $snapshot): void | Persist a single snapshot. |
query(\DateTimeImmutable $since, \DateTimeImmutable $until): array | Retrieve snapshots within a time range (inclusive). |
queryBoundaries(\DateTimeImmutable $since, \DateTimeImmutable $until): array | Boundary-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(): int | Total number of stored snapshots. |
prune(\DateTimeImmutable $before): int | Delete all snapshots older than the cutoff. |
close(): void | Release any held resources (e.g. close the SQLite database). |
SqliteHistoryStore final class
SQLite-backed HistoryStore.
| Method | Summary |
|---|---|
__construct(private readonly string $dbPath, ?int $maxRows = null, ?float $maxAgeSeconds = null) | |
save(StatusSnapshot $snapshot): void | |
queryBoundaries(\DateTimeImmutable $since, \DateTimeImmutable $until): array | SQL-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.
| Method | Summary |
|---|---|
__construct(array $items = []) | |
static fromInstruments(array $instruments): self | Create a new tracker from SetupInstruments. |
static fromConsumers(array $consumers): self | Create a new tracker from SetupConsumers. |
static fromActors(array $actors): self | Create a new tracker from SetupActors. |
static fromObjects(array $objects): self | Create a new tracker from SetupObjects. |
add(object $item): void | Add an item to the tracker. |
original(string $key): mixed | Get the original value of an item by key. |
current(string $key): mixed | Get the current value of an item by key. |
replace(string $key, object $modified): void | Replace an item's current value with a modified copy. |
isDirty(): bool | Check if there are any unsaved changes. |
diff(): array | Get the keys of all changed items. |
reset(): void | Reset all changes by reverting current values to original. |
commit(): void | Commit changes by marking current values as the new original. |
all(): array | Get all current items. |
CommitPlanner final class
Generates SQL statements to commit Performance Schema configuration changes.
| Method | Summary |
|---|---|
__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 = []): self | Factory method to create a new CommitPlanner. |
commitAll(): array | Generate parameterized SQL statements to commit all changes. |
commitInstruments(): array | Generate parameterized SQL statements for instrument changes. |
commitConsumers(): array | Generate parameterized SQL statements for consumer changes. |
commitActors(): array | Generate parameterized SQL statements for actor changes. |
commitObjects(): array | Generate parameterized SQL statements for object changes. |
isDirty(): bool | Check if any tracked models have changes. |
EasySetup final class
Performance Schema easy setup utility providing toggle statements and defaults.
| Method | Summary |
|---|---|
static defaultInstrumentsForVersion(ServerVersion $version): array | Get default instruments for a given version. |
static defaultConsumersForVersion(ServerVersion $version): array | Get default consumers for a given version. |
__construct(?ServerVersion $version = null) | |
static new(?ServerVersion $version = null): self | Factory method to create a new EasySetup instance. |
static fromContext(ServerContextInterface $context): self | Factory method to create from a server context. |
enableStatements(): array | Generate statements to enable Performance Schema (fully enabled). |
disableStatements(): array | Generate statements to disable Performance Schema (fully disabled). |
resetToDefaultStatements(): array | Generate statements to reset Performance Schema to defaults. |
defaultInstruments(): array | Get the default instrument patterns for this version. |
defaultConsumers(): array | Get the default consumer names for this version. |
EasySetupDetector final class
Detects the current Performance Schema setup state via COUNT/SUM queries.
| Method | Summary |
|---|---|
__construct(private readonly DatabaseInterface $db, ?ServerVersion $version = null) | |
static new(DatabaseInterface $db, ?ServerVersion $version = null): self | Factory method to create a new detector. |
static fromContext(ServerContextInterface $context): self | Create a detector from a server context. |
detect(): string | Detect the current PS setup state via server-side aggregates. |
classifyFromData(array $instruments, array $consumers): string | The 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(): bool | Check if PS is disabled (no access to setup_instruments). |
isFullyEnabled(): bool | Check if all instruments and consumers are fully enabled (enabled='YES' AND timed='YES'). |
isFullyDisabled(): bool | Check if PS is fully disabled. |
isDefaultSetup(): bool | Check if the current setup matches the MySQL default profile for this version. |
enabledPercentage(): int | Get the percentage of fully-enabled (enabled AND timed) instruments (0-100). |
totalCount(): int | Get the total number of non-memory instruments. |
enabledCount(): int | Get the number of enabled non-memory instruments. |
InstrumentTree final class
Hierarchical view of Performance Schema instruments organized by name path.
| Method | Summary |
|---|---|
static new(): self | Create a new root node for building a tree. |
static fromInstruments(array $instruments): self | Factory method to create a new tree from a list of instruments. |
insert(SetupInstruments $instrument): void | Insert an instrument into the tree. |
instrument(): ?SetupInstruments | Get the instrument at this node, if any. |
name(): string | Get the name of this node. |
child(string $name): ?InstrumentTree | Get a child node by name. |
children(): array | Get all child nodes. |
hasChildren(): bool | Check if this node has any children. |
path(): string | Get the full path of this node from the root. |
state(): int | Compute the aggregate enabled state of this subtree. |
timedState(): int | Compute the aggregate timed state of this subtree. |
enabled(): bool | Get the enabled state as a boolean. |
timed(): bool | Get the timed state as a boolean. |
find(string $path): ?InstrumentTree | Find a node by instrument name path. |
allInstruments(): array | Get all instruments at or below this node. |
dump(int $depth = 0): string | Get a representation of the tree structure for debugging. |
depth(): int | Get the depth of this node in the tree. |
pathDepth(): int | Get the full depth of this node from root (used for indent calculation). |
setChildrenEnabled(bool $enabled): array | Set the enabled state for this node and cascade to all descendants. |
setChildrenTimed(bool $timed): array | Set the timed state for this node and cascade to all descendants. |
PerfSchemaPage final class
Performance Schema configuration page with tabbed interface.
| Method | Summary |
|---|---|
__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): self | Factory method to create a new PerfSchemaPage. |
update(Msg $msg): array | Handle keyboard shortcuts for navigation and actions. |
withNextTab(): self | Return a new instance with the next tab active. |
withPrevTab(): self | Return a new instance with the previous tab active. |
withTab(string $tab): self | Return a new instance with a specific tab active. |
withQuit(): self | Return a clone (quit is handled by parent controller). |
withRevert(): self | Return a new instance with reverted changes. |
isModal(): bool | |
forgetPrivilegeProbe(): void | SQL-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(): self | Refresh data and return new instance. |
claimsKey(KeyMsg $msg): bool | Whether 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(): self | This 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/.
| Method | Summary |
|---|---|
__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): self | Factory method to create a new instance. |
withEnabled(bool $enabled): static | Return a new instance with the enabled state changed. |
markForDeletion(): static | Mark this actor for deletion. |
markForInsertion(): static | Mark this actor as a new insertion. |
isDirty(): bool | Check if this actor has unsaved changes. |
markClean(): void | Mark this actor as clean (no pending changes). |
asClean(): static | Return a clean copy of this actor. |
changeType(): string | Get the type of change this actor has. |
getChangeType(): string | BC forwarder for the pre-rename accessor name. |
isGlobalHost(): bool | Check if this actor matches all hosts. |
isGlobalUser(): bool | Check if this actor matches all users. |
isGlobalRole(): bool | Check if this actor matches all roles. |
isCatchAll(): bool | Check if this is a catch-all actor (matches everything). |
commitStatements(): array | Generate 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/.
| Method | Summary |
|---|---|
__construct(public string $name, public bool $enabled, private bool $dirty = false) | |
static new(string $name = '', bool $enabled = false): self | Factory method to create a new instance. |
withEnabled(bool $enabled): static | Return a new instance with the enabled state changed. |
isDirty(): bool | Check if this consumer has unsaved changes. |
markClean(): void | Mark this consumer as clean (no pending changes). |
asClean(): static | Return a clean copy of this consumer. |
commitStatements(): array | Generate 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/.
| Method | Summary |
|---|---|
__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 = ''): self | Factory method to create a new instance. |
withEnabled(bool $enabled): static | Return a new instance with the enabled state changed. |
withTimed(bool $timed): static | Return a new instance with the timed state changed. |
isDirty(): bool | Check if this instrument has unsaved changes. |
markClean(): void | Mark this instrument as clean (no pending changes). |
asClean(): static | Return a clean copy of this instrument. |
hasProperty(string $property): bool | Check if this instrument has a specific property. |
isAbstract(): bool | Check if this instrument is an abstract (pseudo) instrument. |
isGlobal(): bool | Check if this instrument is a global-level instrument. |
commitStatements(): array | Generate 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/.
| Method | Summary |
|---|---|
__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): self | Factory method to create a new instance. |
withEnabled(bool $enabled): static | Return a new instance with the enabled state changed. |
withTimed(bool $timed): static | Return a new instance with the timed state changed. |
markForDeletion(): static | Mark this object for deletion. |
markForInsertion(): static | Mark this object as a new insertion. |
isDirty(): bool | Check if this object has unsaved changes. |
markClean(): void | Mark this object as clean (no pending changes). |
asClean(): static | Return a clean copy of this object. |
changeType(): string | Get the type of change this object has. |
getChangeType(): string | BC forwarder for the pre-rename accessor name. |
isGlobalSchema(): bool | Check if this applies to all schemas. |
isGlobalObject(): bool | Check if this applies to all objects. |
isCatchAll(): bool | Check if this is a catch-all entry (matches everything). |
commitStatements(): array | Generate 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/.
| Method | Summary |
|---|---|
__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): self | Factory method to create a new instance. |
withInstrumented(bool $instrumented): static | Return a new instance with the instrumented state changed. |
isDirty(): bool | Check if this thread has unsaved changes. |
isForeground(): bool | Check if this is a foreground thread (user connection). |
isBackground(): bool | Check if this is a background thread (internal server thread). |
hasProcesslist(): bool | Check if this thread has an active processlist entry. |
commitStatements(): array | Generate SQL statement(s) to commit changes. |
instrumentedFragment(): string | Generate 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/.
| Method | Summary |
|---|---|
__construct(public string $name, public string $timerName, private bool $dirty = false, private string $changeType = self::CHANGE_NONE) | |
static new(string $name = '', string $timerName = ''): self | Factory method to create a new instance. |
withTimerName(string $timerName): static | Return a new instance with a different timer selected. |
isDirty(): bool | Check if this timer has unsaved changes. |
changeType(): string | Get the type of change this timer has. |
getChangeType(): string | BC forwarder for the pre-rename accessor name. |
nameUpper(): string | Get the timer name in uppercase. |
isCycle(): bool | Check if this is the CYCLE timer (uses CPU cycles). |
commitStatements(): array | Generate SQL statement(s) to commit changes. |
SugarCraft\Sql\Admin\Providers
MysqlAdminProvider final class
MySQL implementation of AdminProviderInterface wrapping ServerContext.
| Method | Summary |
|---|---|
__construct(private readonly ServerContextInterface $context) | |
static new(ServerContextInterface $context): self | Create 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.
| Method | Summary |
|---|---|
__construct(private readonly DatabaseInterface $connection) | |
static new(DatabaseInterface $connection): self | Create a new instance from a PostgreSQL database connection. |
flavor(): Flavor | |
fetchStatusVariables(): array | Fetch pg_stat_database metrics for the current database as "status variables". |
fetchServerVariables(): array | Fetch all pg_settings as server variables. |
fetchProcesslist(): array | Fetch 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.
| Method | Summary |
|---|---|
static new(DatabaseInterface $db): self | Factory method to create a new AvailabilityChecker. |
discoverViews(): array | Discover available sys schema views. |
sysSchemaExists(): bool | Check if the sys schema exists and is accessible. |
isViewAvailable(string $viewName): bool | Check if a specific sys schema view is available. |
availableFromCatalog(Catalog $catalog): array | Get all views that are available from the catalog. |
missingFromCatalog(Catalog $catalog): array | Get missing views from the catalog. |
availableInCategory(Catalog $catalog, string $category): array | Get reports available for a specific category. |
reset(): void | Reset the cached view list. |
Catalog final class
Catalog loader for performance report metadata.
| Method | Summary |
|---|---|
static new(string $basePath = __DIR__ . '/../../../data'): self | Factory method to create a new Catalog instance. |
load(): void | Load and parse the report metadata JSON file. |
get(string $name): ?ReportDefinition | Get a report by its view name. |
all(): array | Get all available reports. |
byCategory(string $category): array | Get all reports belonging to a specific category. |
categories(): array | List all available categories. |
groupedByCategory(): array | Get all reports grouped by category. |
has(string $name): bool | Check if a report exists in the catalog. |
count(): int | Get the number of reports in the catalog. |
ColumnDefinition final readonly class
Immutable metadata for a single report column.
| Method | Summary |
|---|---|
__construct(public string $name, public ColumnType $type, public int $width) | |
isTime(): bool | Whether this column represents a time value (picoseconds) that needs unit formatting. |
isBytes(): bool | Whether this column represents a byte value that needs unit formatting. |
isNumeric(): bool | Whether 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.
| Method | Summary |
|---|---|
__construct(public string $name, public string $category, public string $caption, public string $description, public string $query, public array $columns) | |
hasColumn(string $columnName): bool | Check if a column exists in this report. |
column(string $columnName): ?ColumnDefinition | Get a column definition by name. |
columnNames(): array | Get all column names in order. |
timeColumns(): array | Get column names that should be formatted as time (picoseconds). |
byteColumns(): array | Get column names that should be formatted as bytes. |
ReportResult final readonly class
Immutable result of executing a performance report.
| Method | Summary |
|---|---|
__construct(public ReportDefinition $report, public array $rows, public int $rowCount, public bool $limited) | |
columnNames(): array | Get the column names from the report definition. |
timeColumns(): array | Get time column names that need unit formatting. |
byteColumns(): array | Get byte column names that need unit formatting. |
firstRow(): ?array | Get the first row, or null if there are no rows. |
isEmpty(): bool | Check if the result is empty. |
ReportRunner final class
Executes performance report queries against the MySQL sys schema.
| Method | Summary |
|---|---|
static new(DatabaseInterface $db, Catalog $catalog, AvailabilityChecker $availability, int $defaultLimit = 1000): self | Factory method to create a new ReportRunner. |
run(string $viewName, ?int $limit = null): ReportResult | Execute a report and return formatted results. |
assertAvailable(string $viewName): void | The 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): ReportResult | Format 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): ReportResult | Execute a report and return raw (unformatted) results. |
canRun(string $viewName): bool | Check if a report can be executed. |
ReportsPage final class
Performance Reports page with left category/report tree and right sortable/exportable grid.
| Method | Summary |
|---|---|
__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): self | Create a new ReportsPage from the server context. |
static seedCategoryFor(AdminPane $pane): ?string | |
update(Msg $msg): array | Handle 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(): self | Select the previous category, wrapping to the last if already at the first. |
withSelectNextCategory(): self | Select the next category, wrapping to the first if already at the last. |
withSelectPrevReport(): self | Select the previous report within the current category, wrapping to the last report if already at the first. |
withSelectNextReport(): self | Select the next report within the current category, wrapping to the first report if already at the last. |
withSelectPrevColumn(): self | Select the previous column for unit display targeting. |
withSelectNextColumn(): self | Select the next column for unit display targeting. |
withExport(): self | |
exportToCsv(): string | Export the current report result to CSV format. |
selectedCategory(): ?string | |
selectedReport(): ?string | |
selectedRowIndex(): int | |
currentResult(): ?ReportResult | |
showRawValues(): bool | |
selectedColumnIndex(): int | |
catalog(): ?Catalog | |
runner(): ?ReportRunner | |
lastExportCsv(): ?string | Get the CSV from the most recent export. |
refresh(): self | Refresh data and return new instance. |
isModal(): bool | Whether the page currently owns an open modal editing surface. |
claimsKey(KeyMsg $msg): bool | Whether 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(): self | This 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.
| Method | Summary |
|---|---|
static format(mixed $value, string $type): string | Format a value according to its column type. |
static formatTime(mixed $picoseconds): string | Format a picosecond value as human-readable duration. |
static formatBytes(mixed $bytes): string | Format bytes using IEC binary units (KiB, MiB, GiB). |
static formatInteger(mixed $value): string | Format an integer value with thousands separator. |
static formatFloat(mixed $value): string | Format a float value with appropriate precision. |
SugarCraft\Sql\Admin\Resilience
ReconnectManager final class
Manages reconnection logic for MySQL connection errors.
| Method | Summary |
|---|---|
__construct(private readonly ?AdminQueryCache $cache = null) | |
shouldReconnect(\PDOException $e): bool | Check if the given PDOException indicates a reconnectable error. |
attemptReconnect(callable $connect): bool | Attempt to reconnect using the last known connection config. |
setConnectionConfig(ConnectionConfig $config): void | Remember the connection config for reconnection attempts. |
lastConnectionConfig(): ?ConnectionConfig | Get the last known connection config. |
StatementTimeout final class
Enforces a wall-clock timeout on synchronous DB work.
| Method | Summary |
|---|---|
__construct(private readonly int $timeoutSeconds = self::DEFAULT_SECONDS, ?bool $pcntlAvailable = null, private readonly ?\Closure $alarm = null) | |
run(callable $work): mixed | Run arbitrary synchronous work under the wall-clock budget. |
execute(\PDOStatement $stmt, array $values = []): bool | Execute a prepared statement with timeout enforcement. |
didTimeout(): bool | Check if the last execution timed out. |
StatementTimeoutException final class
Thrown when a statement exceeds its wall-clock timeout.
| Method | Summary |
|---|---|
__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().
| Method | Summary |
|---|---|
static values(): array | All modes in cycling order for the dialog 'c' key. |
requiresGtidOn(): bool | True 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).
| Method | Summary |
|---|---|
__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): void | Advance every rolling window at most once per second. |
forcePoll(): void | Drop 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): string | Render 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).
| Method | Summary |
|---|---|
__construct(private readonly ServerContextInterface $context) | |
static new(ServerContextInterface $context): self | Create a new instance with default context. |
fetchStatus(): array | Fetch all replica status rows from the server. |
lastFetchKind(): ReplicaStatusKind | The specific condition last encountered when fetching status. |
isReplicaConfigured(): bool | True when replica status is configured on this server. |
refresh(): self | Clear 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.
| Method | Summary |
|---|---|
__construct(private readonly ServerContextInterface $context) | |
static new(ServerContextInterface $context): self | Create a new ServerInfoCard from the current server context. |
render(): string | Render the info card via a sugar-dashboard Card + DefinitionList. |
ServerStatusPage final class
Server Status page displaying connection info, features, directories, SSL, replication, and firewall.
| Method | Summary |
|---|---|
isModal(): bool | The GTID dialog is open — it owns every keystroke. |
__construct(ServerContextInterface $context, ?ReplicaStatusProvider $replicaProvider = null, ?Sampler $sampler = null) | |
static new(ServerContextInterface $context, ?Sampler $sampler = null): self | Create a new ServerStatusPage from the server context. |
view(): string | Render 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): array | Handle keyboard shortcuts for refresh, quit, and GTID mode selector. |
tristate(bool|string|null $value): string | Convert bool|string|null to a Yes/No/Unknown badge. |
withRefresh(): self | Return a refreshed instance. |
withQuit(): self | Return a clone (quit is handled by the parent controller). |
replicaProvider(): ReplicaStatusProvider | |
refresh(): self | Refresh data and return new instance. |
claimsKey(KeyMsg $msg): bool | Whether 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(): self | This 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.
| Method | Summary |
|---|---|
static new(GaugeType $type, float $ratio): self | Create a new sidebar gauge. |
view(): string | Render the gauge as an ANSI string. |
label(): string | Get the human-readable label for this gauge type. |
static thresholdColor(float $ratio): Color | Determine the threshold color based on ratio. |
withRatio(float $ratio): self | Return a new instance with an updated ratio. |
type(): GaugeType | Accessor for the gauge type. |
ratio(): float | Accessor for the current ratio. |
SidebarGaugeSet final class
Collection of all sidebar gauges for the Server Status page.
| Method | Summary |
|---|---|
static new(ServerContextInterface $context, ?Sampler $sampler = null): self | Create a new gauge set from the server context. |
poll(): self | Poll the context/sampler and refresh all gauge ratios. |
view(): string | Render all gauges as a sidebar panel string. |
gauges(): array | Accessor for all gauges. |
previousRates(): ?array | Accessor for the previous rates. |
static computeKeyEfficiencyRatio(array $statusVars): float | Compute key efficiency ratio: Key_reads / (Key_reads + Key_write_requests). |
static computeInnoDBRatio(array $statusVars): float | Compute InnoDB buffer pool utilization ratio. |
StatusGraphCell final class
One rolling time-series frame on the Server Status column.
| Method | Summary |
|---|---|
__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): void | Append 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(): array | Latest recorded value per series name. |
series(string $name): array | |
view(int $width, int $height): string | Paint 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.
| Method | Summary |
|---|---|
static new(string $basePath = __DIR__ . '/../../../data'): self | Factory method to create a new Catalog instance. |
load(): void | Load and parse the variable metadata JSON file. |
get(string $name): ?VariableMetadata | Get a variable by name. |
all(): array | Get all variables. |
byGroup(string $group): array | Get all variables belonging to a specific group. |
groups(): array | List all available groups. |
isEditable(string $name): bool | Check if a variable is editable. |
isDynamic(string $name): bool | Check 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.
| Method | Summary |
|---|---|
static new(ServerContextInterface $context, ?Catalog $catalog = null): self | Factory method to create a new VariableEditor. |
edit(string $variableName, string $newValue): array | Edit a variable using SET GLOBAL. |
editPersistent(string $variableName, string $newValue): array | Edit a variable using SET PERSIST (vendor-gated; see persist()). |
persist(string $variableName, string $newValue): array | Persist a variable using SET PERSIST (MySQL 8.0+). |
persistOnly(string $variableName, string $newValue): array | Persist a variable using SET PERSIST_ONLY (MySQL 8.0+). |
resetPersist(?string $variableName = null): array | Reset persisted variables using RESET PERSIST (MySQL 8.0+). |
editPreview(string $variableName, string $newValue, string $mode = 'global'): string | Get a preview of what the SET statement would look like. |
getEditPreview(string $variableName, string $newValue, string $mode = 'global'): string | BC forwarder for the pre-rename accessor name. |
isEditable(string $variableName): bool | Check if a variable is editable per its metadata. |
lastError(): ?string | Get the last error message from the most recent operation. |
isPrivilegeError(): bool | Check if the last error was a privilege error (1142 or 1227). |
isPersistedVariablesError(): bool | Check if the last error was related to persisted_variables (3680). |
VariableMetadata final readonly class
Immutable metadata descriptor for a MySQL system variable.
| Method | Summary |
|---|---|
__construct(public string $name, public string $description, public bool $editable, public bool $dynamic = true, public array $groups = []) | |
inGroup(string $group): bool | Check if the variable belongs to a given group. |
isDynamic(): bool | Check if the variable is runtime-dynamic (can be changed without restart). |
VariablesPage final class
Variables page displaying SHOW GLOBAL STATUS / SHOW GLOBAL VARIABLES.
| Method | Summary |
|---|---|
__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): self | Create a new VariablesPage from the server context. |
update(Msg $msg): array | Handle keyboard shortcuts for navigation and editing. |
withToggleTab(): self | Return a new instance with the tab toggled. |
withTab(string $tab): self | Return a new instance with a specific tab. |
withSearch(string $search): self | Return a new instance with search filter applied. |
withCategory(?string $category): self | Return a new instance with category filter applied. |
withQuit(): self | Return a clone (quit is handled by parent controller). |
activeTab(): string | |
searchQuery(): string | |
activeCategory(): ?string | |
showReadWriteOnly(): bool | |
selectedRowIndex(): int | |
catalog(): ?Catalog | |
isModal(): bool | The edit/confirm dialog is open — it owns every keystroke. |
editor(): ?VariableEditor | |
refresh(): self | Refresh data and return new instance. |
claimsKey(KeyMsg $msg): bool | Whether 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(): self | This 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/.
| Method | Summary |
|---|---|
__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): self | Install the sync-leg wall-clock cap override (see the constructor note). |
static new(): self | |
withPane(AdminPane $pane): self | Selecting 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.
| Method | Summary |
|---|---|
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): self | Seed 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): self | Enable history recording with the specified SQLite file path. When set, admin fetch results are persisted for later rate analysis. |
withSslMode(?string $sslMode): self | Override 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/.
| Method | Summary |
|---|---|
__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): self | The live /-filter string typed over the Tables pane (jorgerojas26/lazysql parity). |
withFilterMode(bool $filterMode): self | Whether the / filter line is currently open and eating key input. |
withPageOffset(int $pageOffset): self | Server-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(): array | Table 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(): bool | The 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(): self | Advance 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).
| Method | Summary |
|---|---|
__construct(array $entries, private readonly int $cursor = 0, private readonly ?string $picked = null) | |
init(): ?\Closure | |
pickedName(): ?string | The 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/.
| Method | Summary |
|---|---|
__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?
| Method | Summary |
|---|---|
static pkColumns(array $schema): array | Primary-key columns of the table, in column order. |
static key(Flavor $flavor, array $schema, array $row): array | The 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): ?string | Refusal 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/.
| Method | Summary |
|---|---|
__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(): bool | Whether an edit line is open and should own the keyboard. |
closed(): self | |
withStage(string $stage): self | |
withBuffer(string $buffer): self | Replace 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/.
| Method | Summary |
|---|---|
__construct(public readonly string $stage = self::STAGE_CLOSED, public readonly string $buffer = '', public readonly string $path = '') | |
static new(): self | |
isPromptOpen(): bool | Whether 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.
| Method | Summary |
|---|---|
static rowsFor(Pane $pane): array | Rows 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.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
__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): array | The 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/.
| Method | Summary |
|---|---|
__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): self | Record 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): self | Track 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(): self | Advance 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): self | ANSI 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): self | SQL-O23: open/close the per-parameter prompt line. |
withParamValues(?array $values): self | SQL-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/.
| Method | Summary |
|---|---|
__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): self | SQL-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.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
__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'): self | Create a ConnectionConfig from individual components. |
ConnectionFactory final class
Factory for creating DatabaseInterface instances from various config sources.
| Method | Summary |
|---|---|
static fromDsn(string $dsn): ConnectionConfig | Parse a DSN string into a ConnectionConfig. |
static fromConfig(ConnectionConfig $config): DatabaseInterface | Create a DatabaseInterface from a ConnectionConfig. |
static fromArgv(array $argv): DatabaseInterface | Create a DatabaseInterface from CLI argv arguments. |
static fromPath(string $path): SqliteDatabase | Create a DatabaseInterface from a bare SQLite path. |
ConnectionStore final class
On-disk registry of named connections (SQL-O02, candy-sql-once-002).
| Method | Summary |
|---|---|
__construct(private readonly string $path) | |
static defaultPath(): ?string | The 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(): ?self | Open 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(): array | All entries keyed by connection name, sorted by name for stable picker and refusal output. |
names(): array | |
argv(string $name): array | Expand 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): void | Write (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.
| Method | Summary |
|---|---|
tables(): array | Get all table/view names in the database. |
rows(string $table, int $limit = 100, int $offset = 0): array | Get rows from a specific table, paged. |
query(string $sql): array|null | Execute an arbitrary SQL query. |
lastInsertId(): string|int | Get the ID of the last inserted row. |
quote(string $value): string | Quote a string value for safe SQL inclusion. |
exec(string $sql): int | Execute a non-select SQL statement. |
close(): void | Close the database connection. |
serverVersion(): string | Get the database server version string. |
driverName(): string | Get the driver name. |
ping(): bool | Check if the database connection is alive. |
databases(): array | Get list of database names (for multi-database drivers). |
prepare(string $sql): ?PreparedStatementInterface | Prepare a SQL statement for execution. |
dsn(): string | Get the DSN connection string. |
username(): string | Get the database username. |
DmlBuilder final class
Builds the single-row writes behind the Rows pane's cell editor (SQL-O03).
| Method | Summary |
|---|---|
static new(Flavor $flavor): self | |
update(string $table, array $key, string $column, ?string $value): DmlStatement | UPDATE one column of the row addressed by $key. |
insert(string $table, array $values): DmlStatement | INSERT one row. Columns absent from $values take their DEFAULT. |
delete(string $table, array $key): DmlStatement | DELETE the row addressed by $key. |
DmlRunner final class
Runs one DmlStatement with transaction semantics (SQL-O03).
| Method | Summary |
|---|---|
static run(DatabaseInterface $db, DmlStatement $s): int |
DmlStatement final class
One parameterised write the in-grid editor is about to run (SQL-O03).
| Method | Summary |
|---|---|
__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().
| Method | Summary |
|---|---|
static detectFromVersionString(string $version, string $versionComment = ''): self | Detect the database flavor from version string and optional version comment. |
static detectFromDriver(string $driverName, string $version = '', string $versionComment = ''): self | Detect the database flavor from driver name. |
Identifier final class
Centralized SQL identifier quoting for multi-driver support.
| Method | Summary |
|---|---|
static quote(Flavor $flavor, string $name): string | Quote 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): string | Quote 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.
| Method | Summary |
|---|---|
static connect(ConnectionConfig $config): self | Connect to a MySQL database using connection configuration. |
static requiresVerifiedTls(string $sslMode): bool | Whether 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|null | Run 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(): ?float | Get the last known server uptime. |
trackUptime(?float $uptime): void | Update the tracked server uptime. |
setReconnectManager(ReconnectManagerInterface $reconnectManager): void | Inject a ReconnectManager for connection error handling. |
setSampler(SamplerInterface $sampler): void | Inject a Sampler for reset signaling after server restarts. |
dsn(): string | |
username(): string | |
password(): string | WHY 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(): string | The 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.
| Method | Summary |
|---|---|
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.
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
static connect(ConnectionConfig $config): self | Connect to a PostgreSQL database using connection configuration. |
tables(): array | |
rows(string $table, int $limit = 100, int $offset = 0): array | |
query(string $sql): array|null | Run 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(): string | PostgresServerContext::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.
| Method | Summary |
|---|---|
execute(?array $params = null): bool | Execute the prepared statement with optional parameters. |
fetch(): array|false | Fetch the next row from the result set. |
fetchAll(): array | Fetch all rows from the result set. |
rowCount(): int | Get the number of rows affected by the last query. |
closeCursor(): bool | Close the cursor, enabling the statement to be executed again. |
PreviewQuery final class
Builds blob-safe "row preview" SQL for the TUI table browser.
| Method | Summary |
|---|---|
static columnsSql(Flavor $flavor, string $table): string | The 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): array | Normalise 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): string | Assemble 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): bool | Whether 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.
| Method | Summary |
|---|---|
__construct(string $message, private readonly \PDOException $original, int $code = 0, ?\Throwable $previous = null) | |
original(): \PDOException | Get the original PDO exception that triggered the reconnect attempt. |
getOriginal(): \PDOException | BC forwarder for the pre-rename accessor name. |
ReconnectManagerInterface interface
Db-layer seam for connection-reconnect policy.
| Method | Summary |
|---|---|
shouldReconnect(\PDOException $e): bool | Decide whether the given PDO error warrants a reconnect attempt. |
attemptReconnect(callable $connect): bool | Attempt a reconnect using the supplied connection factory. |
setConnectionConfig(ConnectionConfig $config): void | Remember the config to use for reconnection attempts. |
SamplerInterface interface
Db-layer seam for the metric sampler.
| Method | Summary |
|---|---|
resetAll(): void | Clear all accumulated sampling state (e.g. after a reconnect). |
ServerVersion final readonly class
Immutable value object representing a database server version.
| Method | Summary |
|---|---|
__construct(public int $major, public int $minor, public int $release, public string $raw) | |
static parse(string $version): self | Parse a version string into a Version value object. |
isMariaDb(): bool | True when the raw version string carries the MariaDB identity marker. |
isAtLeast(int $major, int $minor = 0, int $release = 0): bool | Check if this version is at least the specified version. |
__toString(): string | Return the raw version string. |
SqliteDatabase final class
SQLite implementation of DatabaseInterface.
| Method | Summary |
|---|---|
__construct(\PDO $pdo, string $path = ':memory:') | |
static open(string $path): self | Open a SQLite database file. |
tables(): array | |
rows(string $table, int $limit = 100, int $offset = 0): array | |
query(string $sql): array|null | Run 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.
| Method | Summary |
|---|---|
__construct(private readonly DatabaseInterface $db) | |
importCsv(string $path, string $table): void | Import a CSV file into a table. |
exportReportResults(string $path, array $columns, array $rows): void | Export report results to a CSV file. |
exportReportResultsToString(array $columns, array $rows): string | Export report results to a CSV string. |
exportCsv(string $path, string $table): void | Export a table to a CSV file. |
SqlExporter final class
SQL export service using a DatabaseInterface instance.
| Method | Summary |
|---|---|
__construct(private readonly DatabaseInterface $db) | |
exportSql(string $path): void | Export the entire database to a SQL dump file. |
SugarCraft\Sql\Explain
ExplainProviderInterface interface
Driver-aware interface for EXPLAIN output.
| Method | Summary |
|---|---|
explain(string $sql): array | Execute EXPLAIN and return parsed output as an array. |
driverName(): string | The driver name this provider handles. |
MysqlExplainProvider final class
MySQL EXPLAIN provider.
| Method | Summary |
|---|---|
__construct(private readonly DatabaseInterface $db) | |
explain(string $sql): array | Execute EXPLAIN FORMAT=JSON and return parsed tree structure. |
driverName(): string | |
getDriverName(): string | BC forwarder for the pre-rename accessor name. |
PostgresExplainProvider final class
PostgreSQL EXPLAIN provider.
| Method | Summary |
|---|---|
__construct(private readonly DatabaseInterface $db) | |
explain(string $sql): array | Execute EXPLAIN (FORMAT JSON) and return parsed tree structure. |
driverName(): string | |
getDriverName(): string | BC forwarder for the pre-rename accessor name. |
SqliteExplainProvider final class
SQLite EXPLAIN QUERY PLAN provider.
| Method | Summary |
|---|---|
__construct(private readonly DatabaseInterface $db) | |
explain(string $sql): array | Execute EXPLAIN QUERY PLAN and return raw rows. |
driverName(): string | |
getDriverName(): string | BC forwarder for the pre-rename accessor name. |
SugarCraft\Sql\Schema
MysqlSchemaProvider final class
MySQL schema provider using information_schema queries.
| Method | Summary |
|---|---|
__construct(private readonly DatabaseInterface $db) | |
tables(): array | List all user tables (non-system tables). |
columns(string $table): array | List all columns for a given table. |
indexes(string $table): array | List all indexes for a given table. |
foreignKeys(string $table): array | List all foreign keys for a given table. |
dropTable(string $table): void | Drop a table by name. |
withFlavor(Flavor $flavor): self | Return a new instance with the specified flavor. |
PostgresSchemaProvider final class
PostgreSQL schema provider using information_schema and pg_catalog.
| Method | Summary |
|---|---|
__construct(private readonly DatabaseInterface $db) | |
tables(): array | List all user tables (non-system tables). |
columns(string $table): array | List all columns for a given table. |
indexes(string $table): array | List all indexes for a given table. |
foreignKeys(string $table): array | List all foreign keys for a given table. |
dropTable(string $table): void | Drop a table by name. |
withFlavor(Flavor $flavor): self | Return a new instance with the specified flavor. |
SchemaColumn final class
| Method | Summary |
|---|---|
__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
| Method | Summary |
|---|---|
__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
| Method | Summary |
|---|---|
__construct(public readonly string $name, public readonly bool $unique, public readonly array $columns) |
SchemaProviderInterface interface
Interface for driver-aware schema introspection.
| Method | Summary |
|---|---|
tables(): array | List all user tables (non-system tables). |
columns(string $table): array | List all columns for a given table. |
indexes(string $table): array | List all indexes for a given table. |
foreignKeys(string $table): array | List all foreign keys for a given table. |
dropTable(string $table): void | Drop a table by name. |
withFlavor(Flavor $flavor): self | Return a new instance with the specified flavor. |
SchemaTable final class
| Method | Summary |
|---|---|
__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.
| Method | Summary |
|---|---|
__construct(private readonly DatabaseInterface $db) | |
tables(): array | List all user tables (non-system tables). |
columns(string $table): array | List all columns for a given table. |
indexes(string $table): array | List all indexes for a given table. |
foreignKeys(string $table): array | List all foreign keys for a given table. |
dropTable(string $table): void | Drop a table by name. |
withFlavor(Flavor $flavor): self | Return 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
| Flag | Effect |
|---|---|
--dsn=URL | A DSN for sqlite://, mysql:// or pgsql://. The same string also works as the positional argument. sqlite://:memory: gives a throwaway database. |
--driver=NAME | sqlite, mysql or pgsql. Used with --db when no DSN is given. |
--host=HOST, --port=PORT | Server address and port. |
--user=USER | Database user. |
--pass=PASS | Password on the command line. Prefer CANDY_SQL_PASS, which keeps it out of the process list. |
--db=NAME | Database name, or the SQLite file path. |
--ssl-mode=MODE | TLS mode for the server connection. See the DSN and MySQL SSL notes in the README. |
--connect=NAME | Dial a saved connection. It cannot be combined with explicit connection arguments. |
--read-only | Turns the in-grid edit chords off for the session. |
--history=PATH | Store the status-snapshot history at PATH instead of the default. |
--no-history | Turn off status-snapshot recording. |
--help, --version | Print 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
| Name | Default | Effect |
|---|---|---|
CANDY_SQL_PASS | unset | Password fallback for an individual flag connection, or for a saved connection with no pass-env. |
pass-env (in a saved connection) | none | Names the environment variable that holds the password. It is read at dial time. A pass field in the file is refused. |
XDG_CONFIG_HOME, HOME | first set | The saved connections live in candy-sql/connections.json under the config directory. The directory is created with mode 0700 and the file with 0600. |
HOME | required for history | The default history is $HOME/.candy-sql/history.db. If HOME is unset, recording stays disabled. |
NO_COLOR, TERM, COLORTERM | detected | Read 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.
| Key | Action |
|---|---|
Tab | Cycle the pane: Tables, Rows, Query, Admin |
↑/↓, j/k | Move the cursor in the active list. In the Query pane the arrows move between lines. |
←/→, h/l | Move 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+Enter | Run the SQL in the Query pane |
Ctrl+F | Save the Query pane's text to the favorites list. Ctrl+Shift+F removes it |
x, i | Open the export or import line (Tables or Rows) |
Ctrl+S | Open the export line from any pane while rows are on screen |
H | Read the recorded status history |
:tx, :tx begin, :tx commit, :tx rollback | Transaction 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, Esc | Cancel 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+C | Cancel 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.
Appholds the panes, the query state and the admin pages. It returns a new model for each message. - Database.
DatabaseInterfaceand its PDO adapters,SqliteDatabase,MysqlDatabaseandPostgresDatabase.ConnectionFactoryparses a DSN, andFlavornames the server type. - Strategies.
SchemaBrowserandExplainViewpick the driver-specific SQL for schema introspection and plan output. - Edits.
DmlBuilderbuilds statements from the full primary key, andDmlRunnerwraps each write in a transaction that rolls back unless the promised row count changed. - Admin.
AdminProviderInterfacegives one port for admin data, with a MySQL and a PostgreSQL adapter. The pages sit on top of it. - History.
HistoryRecorderwrites snapshots throughSqliteHistoryStore.
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.
ReactMysqlConnectionandReactPostgresConnectionrun single statements. ABEGINandCOMMITthat 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.
Related
- 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
- Source on GitHub
- Full README
- Runnable examples
- Originally inspired by lazysql (Go); SugarCraft is developed as a native PHP project.
Demos.
VHS-recorded GIF of the dashboard on a seeded in-memory database, regenerated automatically on every push that touches the source.