ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(databases): add Database Explorer building blocks
Juan Deniscaee88284465
diff --git a/frontend/src/components/databases/BackupsTab.jsx b/frontend/src/components/databases/BackupsTab.jsxnew file mode 100644index 00000000..86a69632--- /dev/null+++ b/frontend/src/components/databases/BackupsTab.jsx@@ -0,0 +1,120 @@+import { useEffect, useState } from 'react';+import { Archive, Trash2, RefreshCw } from 'lucide-react';+import api from '../../services/api';+import EmptyState from '../EmptyState';+import { useConfirm } from '../../hooks/useConfirm';+import { ConfirmDialog } from '../ConfirmDialog';++function formatBytes(bytes) {+ if (!bytes) return '0 B';+ const k = 1024;+ const sizes = ['B', 'KB', 'MB', 'GB'];+ const i = Math.floor(Math.log(bytes) / Math.log(k));+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];+}++const FILTERS = [+ { id: 'all', label: 'All' },+ { id: 'mysql', label: 'MySQL' },+ { id: 'postgresql', label: 'PostgreSQL' },+];++export default function BackupsTab() {+ const { confirm, confirmState, handleConfirm, handleCancel } = useConfirm();+ const [backups, setBackups] = useState([]);+ const [loading, setLoading] = useState(true);+ const [filter, setFilter] = useState('all');++ useEffect(() => { load(); }, [filter]); // eslint-disable-line react-hooks/exhaustive-deps++ async function load() {+ setLoading(true);+ try {+ const data = await api.getDatabaseBackups(filter === 'all' ? null : filter);+ setBackups(data.backups || []);+ } catch (err) {+ console.error('Failed to load backups:', err);+ } finally {+ setLoading(false);+ }+ }++ async function remove(filename) {+ const ok = await confirm({ title: 'Delete backup', message: `Delete backup "${filename}"? This cannot be undone.`, confirmText: 'Delete backup', variant: 'danger' });+ if (!ok) return;+ try {+ await api.deleteDatabaseBackup(filename);+ load();+ } catch (err) {+ console.error('Failed to delete backup:', err);+ }+ }++ return (+ <div className="dbx-backups">+ <div className="dbx-backups-toolbar">+ <div className="dbx-segmented">+ {FILTERS.map((f) => (+ <button key={f.id} type="button" className={filter === f.id ? 'is-active' : ''} onClick={() => setFilter(f.id)}>+ {f.label}+ </button>+ ))}+ </div>+ <div className="dbx-table-toolbar-spacer" />+ <button type="button" className="dbx-icon-btn" onClick={load} disabled={loading} aria-label="Refresh">+ <RefreshCw size={14} className={loading ? 'dbx-spin' : ''} aria-hidden="true" />+ </button>+ </div>++ <div className="dbx-backups-body">+ {loading ? (+ <EmptyState loading title="Loading backups…" />+ ) : backups.length === 0 ? (+ <EmptyState icon={Archive} title="No backups yet" description="Back up a database from its tree menu and it will appear here." />+ ) : (+ <table className="dbx-grid dbx-backups-table">+ <thead>+ <tr>+ <th scope="col">Database</th>+ <th scope="col">Engine</th>+ <th scope="col">File</th>+ <th scope="col">Size</th>+ <th scope="col">Created</th>+ <th scope="col" aria-label="Actions" />+ </tr>+ </thead>+ <tbody>+ {backups.map((b) => (+ <tr key={b.filename}>+ <td className="dbx-col-name">{b.database}</td>+ <td>+ <span className={`dbx-engine-tag is-${b.type}`}>{b.type === 'mysql' ? 'MySQL' : 'PostgreSQL'}</span>+ </td>+ <td className="dbx-mono">{b.filename}</td>+ <td className="dbx-mono">{formatBytes(b.size)}</td>+ <td className="dbx-mono">{new Date(b.created_at).toLocaleString()}</td>+ <td className="dbx-grid-actions">+ <button type="button" className="dbx-icon-btn is-danger" onClick={() => remove(b.filename)} aria-label={`Delete ${b.filename}`}>+ <Trash2 size={14} aria-hidden="true" />+ </button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>++ <ConfirmDialog+ isOpen={confirmState.isOpen}+ title={confirmState.title}+ message={confirmState.message}+ confirmText={confirmState.confirmText}+ cancelText={confirmState.cancelText}+ variant={confirmState.variant}+ onConfirm={handleConfirm}+ onCancel={handleCancel}+ />+ </div>+ );+}diff --git a/frontend/src/components/databases/ConsoleTab.jsx b/frontend/src/components/databases/ConsoleTab.jsxnew file mode 100644index 00000000..4ff1a62b--- /dev/null+++ b/frontend/src/components/databases/ConsoleTab.jsx@@ -0,0 +1,232 @@+import { useEffect, useRef, useState, useCallback } from 'react';+import { Play, History, Download, Eraser, Lock, Unlock, Clock } from 'lucide-react';+import { useToast } from '../../contexts/ToastContext';+import { runQuery, connKey } from './dbAdapter';+import ResultsGrid from './ResultsGrid';++const HISTORY_KEY = 'serverkit_query_history';+const MAX_HISTORY = 50;++// One SQL console bound to a single connection. Owns its editor text, results,+// readonly flag, and per-connection history. `active` gates keyboard handling so+// background (hidden) consoles don't steal Ctrl+Enter.+export default function ConsoleTab({ conn, tabId, active, isAdmin, initialQuery = '', onStatus }) {+ const toast = useToast();+ const editorRef = useRef(null);+ const key = connKey(conn);++ const [query, setQuery] = useState(initialQuery);+ const [results, setResults] = useState(null);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState('');+ const [readonly, setReadonly] = useState(true);+ const [history, setHistory] = useState([]);+ const [showHistory, setShowHistory] = useState(false);++ useEffect(() => {+ try {+ const stored = localStorage.getItem(HISTORY_KEY);+ if (stored) setHistory(JSON.parse(stored)[key] || []);+ } catch { /* ignore corrupt history */ }+ }, [key]);++ useEffect(() => {+ if (active && editorRef.current) editorRef.current.focus();+ }, [active]);++ const report = useCallback(() => {+ onStatus?.(tabId, {+ connText: `${conn.dbType} · ${conn.name || conn.path?.split('/').pop() || conn.container}`,+ readonly,+ rowCount: results?.row_count,+ execTime: results?.execution_time,+ truncated: results?.truncated,+ totalRows: results?.total_rows,+ });+ }, [onStatus, tabId, conn, readonly, results]);++ useEffect(() => { if (active) report(); }, [active, report]);++ function saveToHistory(sql) {+ try {+ const stored = localStorage.getItem(HISTORY_KEY);+ const all = stored ? JSON.parse(stored) : {};+ const list = (all[key] || []).filter((h) => h.query !== sql);+ list.unshift({ query: sql, timestamp: new Date().toISOString() });+ all[key] = list.slice(0, MAX_HISTORY);+ localStorage.setItem(HISTORY_KEY, JSON.stringify(all));+ setHistory(all[key]);+ } catch { /* storage full / blocked — non-fatal */ }+ }++ async function execute() {+ const sql = query.trim();+ if (!sql) { setError('Enter a query to run.'); return; }+ setLoading(true);+ setError('');+ setResults(null);+ try {+ const result = await runQuery(conn, sql, readonly);+ if (result.success) {+ setResults(result);+ saveToHistory(sql);+ toast.success(`${result.row_count} row${result.row_count === 1 ? '' : 's'} · ${result.execution_time}s`);+ } else {+ setError(result.error || 'Query failed.');+ }+ } catch (err) {+ setError(err.message || 'Failed to execute query.');+ } finally {+ setLoading(false);+ }+ }++ function handleKeyDown(e) {+ if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {+ e.preventDefault();+ execute();+ }+ }++ function exportCsv() {+ if (!results?.columns || !results?.rows) return;+ const esc = (v) => {+ if (v === null) return '';+ const s = String(v);+ return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;+ };+ const csv = [+ results.columns.map(esc).join(','),+ ...results.rows.map((r) => r.map(esc).join(',')),+ ].join('\n');+ const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv' }));+ const a = document.createElement('a');+ a.href = url;+ a.download = `${conn.name || 'query'}_${new Date().toISOString().slice(0, 10)}.csv`;+ a.click();+ URL.revokeObjectURL(url);+ toast.success('Exported results to CSV');+ }++ return (+ <div className="dbx-console">+ <div className="dbx-console-toolbar">+ <button+ type="button"+ className="dbx-run"+ onClick={execute}+ disabled={loading || !query.trim()}+ title="Run query (Ctrl+Enter)"+ >+ <Play size={14} aria-hidden="true" />+ {loading ? 'Running…' : 'Run'}+ <kbd>⌘↵</kbd>+ </button>++ {isAdmin && (+ <button+ type="button"+ className={`dbx-toggle ${readonly ? '' : 'is-write'}`}+ onClick={() => setReadonly((r) => !r)}+ aria-pressed={!readonly}+ title={readonly ? 'Read-only: only SELECT / SHOW / DESCRIBE' : 'Writes enabled — be careful'}+ >+ {readonly ? <Lock size={13} aria-hidden="true" /> : <Unlock size={13} aria-hidden="true" />}+ {readonly ? 'Read-only' : 'Writes on'}+ </button>+ )}++ <div className="dbx-console-toolbar-spacer" />++ <button+ type="button"+ className={`dbx-chip ${showHistory ? 'is-active' : ''}`}+ onClick={() => setShowHistory((s) => !s)}+ aria-pressed={showHistory}+ >+ <History size={14} aria-hidden="true" /> History+ </button>+ <button type="button" className="dbx-chip" onClick={() => { setQuery(''); editorRef.current?.focus(); }}>+ <Eraser size={14} aria-hidden="true" /> Clear+ </button>+ <button type="button" className="dbx-chip" onClick={exportCsv} disabled={!results?.rows?.length}>+ <Download size={14} aria-hidden="true" /> Export+ </button>+ </div>++ <div className="dbx-console-split">+ <div className="dbx-editor-wrap">+ <textarea+ ref={editorRef}+ className="dbx-editor"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ onKeyDown={handleKeyDown}+ placeholder={`SELECT * FROM … — querying ${conn.name || conn.path || conn.container}`}+ spellCheck={false}+ aria-label="SQL editor"+ />+ {readonly && (+ <span className="dbx-editor-badge">+ <Lock size={11} aria-hidden="true" /> Read-only+ </span>+ )}+ </div>++ {showHistory && (+ <aside className="dbx-history" aria-label="Query history">+ <div className="dbx-history-head">Recent queries</div>+ {history.length === 0 ? (+ <p className="dbx-history-empty">No queries yet.</p>+ ) : (+ <ul>+ {history.map((item, idx) => (+ <li key={idx}>+ <button+ type="button"+ onClick={() => { setQuery(item.query); setShowHistory(false); editorRef.current?.focus(); }}+ >+ <code>{item.query}</code>+ <span className="dbx-history-time">+ <Clock size={11} aria-hidden="true" />+ {new Date(item.timestamp).toLocaleString()}+ </span>+ </button>+ </li>+ ))}+ </ul>+ )}+ </aside>+ )}+ </div>++ <div className="dbx-results">+ {(results || loading || error) ? (+ <>+ {results && !error && (+ <div className="dbx-results-head">+ <span className="dbx-results-count">+ {results.row_count} row{results.row_count === 1 ? '' : 's'}+ {results.truncated && ` · truncated from ${results.total_rows}`}+ </span>+ <span className="dbx-results-time">{results.execution_time}s</span>+ </div>+ )}+ <ResultsGrid+ columns={results?.columns}+ rows={results?.rows}+ loading={loading}+ error={error}+ emptyTitle="Query ran"+ emptyDescription="No rows returned."+ />+ </>+ ) : (+ <div className="dbx-console-hint">+ <p>Write SQL above and press <kbd>Ctrl</kbd> + <kbd>Enter</kbd> to run.</p>+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/frontend/src/components/databases/ResultsGrid.jsx b/frontend/src/components/databases/ResultsGrid.jsxnew file mode 100644index 00000000..e4ef7e81--- /dev/null+++ b/frontend/src/components/databases/ResultsGrid.jsx@@ -0,0 +1,103 @@+import { useMemo, useState } from 'react';+import { ChevronUp, ChevronDown, Database } from 'lucide-react';+import EmptyState from '../EmptyState';++// Renders a query/data result set: columns + row arrays. Sorting is client-side+// over the rows already returned (a page), matching the old QueryRunner.+export default function ResultsGrid({ columns, rows, loading, error, emptyTitle = 'No rows', emptyDescription }) {+ const [sort, setSort] = useState({ col: null, dir: 'asc' });++ const sortedRows = useMemo(() => {+ if (!rows || sort.col === null) return rows || [];+ const dir = sort.dir === 'asc' ? 1 : -1;+ return [...rows].sort((a, b) => {+ const av = a[sort.col];+ const bv = b[sort.col];+ if (av === null && bv === null) return 0;+ if (av === null) return 1;+ if (bv === null) return -1;+ const an = Number(av);+ const bn = Number(bv);+ if (!Number.isNaN(an) && !Number.isNaN(bn) && av !== '' && bv !== '') {+ return (an - bn) * dir;+ }+ return String(av).localeCompare(String(bv)) * dir;+ });+ }, [rows, sort]);++ function toggleSort(idx) {+ setSort((prev) => ({+ col: idx,+ dir: prev.col === idx && prev.dir === 'asc' ? 'desc' : 'asc',+ }));+ }++ if (loading) {+ return (+ <div className="dbx-grid-status">+ <EmptyState loading title="Running query…" />+ </div>+ );+ }++ if (error) {+ return (+ <div className="dbx-grid-error" role="alert">+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2" aria-hidden="true">+ <circle cx="12" cy="12" r="10" />+ <line x1="12" y1="8" x2="12" y2="12" />+ <line x1="12" y1="16" x2="12.01" y2="16" />+ </svg>+ <pre>{error}</pre>+ </div>+ );+ }++ if (!columns || columns.length === 0) {+ return (+ <div className="dbx-grid-status">+ <EmptyState icon={Database} title={emptyTitle} description={emptyDescription} />+ </div>+ );+ }++ return (+ <div className="dbx-grid-scroll">+ <table className="dbx-grid">+ <thead>+ <tr>+ <th className="dbx-grid-rownum" aria-hidden="true" />+ {columns.map((col, idx) => (+ <th+ key={idx}+ scope="col"+ aria-sort={sort.col === idx ? (sort.dir === 'asc' ? 'ascending' : 'descending') : 'none'}+ >+ <button type="button" className="dbx-grid-th" onClick={() => toggleSort(idx)}>+ <span className="dbx-grid-th-name">{col}</span>+ {sort.col === idx && (+ sort.dir === 'asc'+ ? <ChevronUp size={13} aria-hidden="true" />+ : <ChevronDown size={13} aria-hidden="true" />+ )}+ </button>+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {sortedRows.map((row, rowIdx) => (+ <tr key={rowIdx}>+ <td className="dbx-grid-rownum">{rowIdx + 1}</td>+ {row.map((cell, cellIdx) => (+ <td key={cellIdx} className={cell === null ? 'is-null' : undefined} title={cell === null ? 'NULL' : String(cell)}>+ {cell === null ? 'NULL' : String(cell)}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}diff --git a/frontend/src/components/databases/SourceTree.jsx b/frontend/src/components/databases/SourceTree.jsxnew file mode 100644index 00000000..59acfaef--- /dev/null+++ b/frontend/src/components/databases/SourceTree.jsx@@ -0,0 +1,146 @@+import { ChevronRight, ChevronDown, Database, HardDrive, Box, Table2, Loader2, MoreHorizontal } from 'lucide-react';++// Icon per node kind / engine. Tint comes from `.is-<engine>` in SCSS.+function NodeIcon({ node }) {+ if (node.kind === 'engine' || node.kind === 'database') {+ if (node.engine === 'sqlite') return <HardDrive size={15} aria-hidden="true" />;+ if (node.engine === 'docker') return <Box size={15} aria-hidden="true" />;+ return <Database size={15} aria-hidden="true" />;+ }+ if (node.kind === 'app') return <Box size={15} aria-hidden="true" />;+ if (node.kind === 'table') return <Table2 size={14} aria-hidden="true" />;+ return <Database size={15} aria-hidden="true" />;+}++const STATUS_LABEL = { active: 'Running', inactive: 'Stopped', missing: 'Not installed' };++function matches(node, filter) {+ return !filter || node.label.toLowerCase().includes(filter.toLowerCase());+}++function TreeRow({ node, depth, expanded, childrenCache, loading, activeKey, selectedId, filter, handlers }) {+ const isOpen = expanded.has(node.id);+ const isLoading = loading.has(node.id);+ const kids = childrenCache.get(node.id);+ const hadError = kids === 'error';+ const childNodes = Array.isArray(kids) ? kids : [];+ const visibleChildren = childNodes.filter((c) => c.expandable || matches(c, filter));++ return (+ <li className="dbx-tree-node" role="none">+ <div+ className={`dbx-tree-row is-${node.engine || node.kind}`+ + (selectedId === node.id ? ' is-selected' : '')+ + (activeKey && activeKey === node.id ? ' is-active' : '')}+ style={{ paddingLeft: `${depth * 14 + 6}px` }}+ role="treeitem"+ aria-expanded={node.expandable ? isOpen : undefined}+ aria-selected={selectedId === node.id}+ tabIndex={0}+ onClick={() => handlers.onActivate(node)}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); handlers.onActivate(node); }+ if (e.key === 'ArrowRight' && node.expandable && !isOpen) handlers.onToggle(node);+ if (e.key === 'ArrowLeft' && node.expandable && isOpen) handlers.onToggle(node);+ }}+ onContextMenu={(e) => handlers.onContext(e, node)}+ >+ {node.expandable ? (+ <button+ type="button"+ className="dbx-tree-chevron"+ onClick={(e) => { e.stopPropagation(); handlers.onToggle(node); }}+ aria-label={isOpen ? 'Collapse' : 'Expand'}+ tabIndex={-1}+ >+ {isLoading+ ? <Loader2 size={13} className="dbx-spin" aria-hidden="true" />+ : isOpen ? <ChevronDown size={14} aria-hidden="true" /> : <ChevronRight size={14} aria-hidden="true" />}+ </button>+ ) : (+ <span className="dbx-tree-chevron dbx-tree-chevron--leaf" aria-hidden="true" />+ )}++ <span className="dbx-tree-icon"><NodeIcon node={node} /></span>+ <span className="dbx-tree-label">{node.label}</span>++ {node.kind === 'engine' && node.status && node.status !== 'available' && (+ <span className={`dbx-tree-status is-${node.status}`}>+ <span className="dbx-status-dot" aria-hidden="true" />+ {STATUS_LABEL[node.status]}+ </span>+ )}+ {node.kind === 'table' && node.rows != null && (+ <span className="dbx-tree-badge">{node.rows.toLocaleString()}</span>+ )}+ {node.kind === 'database' && node.sizeText && (+ <span className="dbx-tree-badge">{node.sizeText}</span>+ )}++ <button+ type="button"+ className="dbx-tree-more"+ onClick={(e) => { e.stopPropagation(); handlers.onContext(e, node); }}+ aria-label="Actions"+ tabIndex={-1}+ >+ <MoreHorizontal size={14} aria-hidden="true" />+ </button>+ </div>++ {node.expandable && isOpen && (+ <ul className="dbx-tree-children" role="group">+ {isLoading && childNodes.length === 0 && (+ <li className="dbx-tree-leaf-msg" style={{ paddingLeft: `${(depth + 1) * 14 + 22}px` }}>Loading…</li>+ )}+ {hadError && (+ <li className="dbx-tree-leaf-msg is-error" style={{ paddingLeft: `${(depth + 1) * 14 + 22}px` }}>+ Couldn't load. Right-click to retry.+ </li>+ )}+ {!isLoading && !hadError && childNodes.length === 0 && (+ <li className="dbx-tree-leaf-msg" style={{ paddingLeft: `${(depth + 1) * 14 + 22}px` }}>Empty</li>+ )}+ {visibleChildren.map((child) => (+ <TreeRow+ key={child.id}+ node={child}+ depth={depth + 1}+ expanded={expanded}+ childrenCache={childrenCache}+ loading={loading}+ activeKey={activeKey}+ selectedId={selectedId}+ filter={filter}+ handlers={handlers}+ />+ ))}+ {!isLoading && !hadError && childNodes.length > 0 && visibleChildren.length === 0 && (+ <li className="dbx-tree-leaf-msg" style={{ paddingLeft: `${(depth + 1) * 14 + 22}px` }}>No match</li>+ )}+ </ul>+ )}+ </li>+ );+}++export default function SourceTree({ roots, expanded, childrenCache, loading, activeKey, selectedId, filter, handlers }) {+ return (+ <ul className="dbx-tree" role="tree" aria-label="Database sources">+ {roots.map((node) => (+ <TreeRow+ key={node.id}+ node={node}+ depth={0}+ expanded={expanded}+ childrenCache={childrenCache}+ loading={loading}+ activeKey={activeKey}+ selectedId={selectedId}+ filter={filter}+ handlers={handlers}+ />+ ))}+ </ul>+ );+}diff --git a/frontend/src/components/databases/TableDataTab.jsx b/frontend/src/components/databases/TableDataTab.jsxnew file mode 100644index 00000000..a32d7f88--- /dev/null+++ b/frontend/src/components/databases/TableDataTab.jsx@@ -0,0 +1,193 @@+import { useEffect, useState, useCallback } from 'react';+import { ChevronLeft, ChevronRight, RefreshCw, Table2, Columns3, KeyRound, Terminal } from 'lucide-react';+import { runQuery, getStructure, buildBrowseQuery } from './dbAdapter';+import ResultsGrid from './ResultsGrid';++const PAGE_SIZE = 100;++// Browses one table: a paginated data grid (SELECT * LIMIT/OFFSET under the+// hood) plus a Structure view. `rowsEstimate` comes from the tree's table list+// so we can show a range without a COUNT(*) round-trip.+export default function TableDataTab({ conn, tabId, table, rowsEstimate, active, onStatus, onOpenConsole }) {+ const [view, setView] = useState('data');+ const [page, setPage] = useState(0);+ const [data, setData] = useState(null);+ const [dataLoading, setDataLoading] = useState(false);+ const [dataError, setDataError] = useState('');+ const [structure, setStructure] = useState(null);+ const [structureLoading, setStructureLoading] = useState(false);+ const [structureUnsupported, setStructureUnsupported] = useState(false);++ const loadData = useCallback(async (pageIdx) => {+ setDataLoading(true);+ setDataError('');+ try {+ const sql = buildBrowseQuery(conn, table, { limit: PAGE_SIZE, offset: pageIdx * PAGE_SIZE });+ const result = await runQuery(conn, sql, true);+ if (result.success) setData(result);+ else setDataError(result.error || 'Failed to load rows.');+ } catch (err) {+ setDataError(err.message || 'Failed to load rows.');+ } finally {+ setDataLoading(false);+ }+ }, [conn, table]);++ useEffect(() => { loadData(page); }, [loadData, page]);++ async function loadStructure() {+ if (structure || structureLoading || structureUnsupported) return;+ setStructureLoading(true);+ try {+ const result = await getStructure(conn, table);+ if (result.unsupported) setStructureUnsupported(true);+ else if (result.success) setStructure(result.columns || []);+ } catch { /* leave structure empty; the view shows a fallback */ }+ finally { setStructureLoading(false); }+ }++ useEffect(() => {+ if (view === 'structure') loadStructure();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [view]);++ useEffect(() => {+ if (!active) return;+ const start = rowsEstimate === 0 ? 0 : page * PAGE_SIZE + 1;+ const end = page * PAGE_SIZE + (data?.row_count || 0);+ onStatus?.(tabId, {+ connText: `${conn.dbType} · ${table}`,+ readonly: true,+ rangeText: data ? `${start}–${end}${rowsEstimate != null ? ` of ≈${rowsEstimate}` : ''}` : null,+ execTime: data?.execution_time,+ });+ }, [active, data, page, rowsEstimate, conn, table, onStatus, tabId]);++ const hasMore = (data?.row_count || 0) === PAGE_SIZE;++ return (+ <div className="dbx-table-tab">+ <div className="dbx-table-toolbar">+ <div className="dbx-segmented" role="tablist" aria-label="Table view">+ <button+ type="button"+ role="tab"+ aria-selected={view === 'data'}+ className={view === 'data' ? 'is-active' : ''}+ onClick={() => setView('data')}+ >+ <Table2 size={14} aria-hidden="true" /> Data+ </button>+ <button+ type="button"+ role="tab"+ aria-selected={view === 'structure'}+ className={view === 'structure' ? 'is-active' : ''}+ onClick={() => setView('structure')}+ >+ <Columns3 size={14} aria-hidden="true" /> Structure+ </button>+ </div>++ {view === 'data' && (+ <div className="dbx-pager">+ <button+ type="button"+ className="dbx-icon-btn"+ onClick={() => setPage((p) => Math.max(0, p - 1))}+ disabled={page === 0 || dataLoading}+ aria-label="Previous page"+ >+ <ChevronLeft size={15} aria-hidden="true" />+ </button>+ <span className="dbx-pager-label">+ {rowsEstimate === 0+ ? '0 rows'+ : `${page * PAGE_SIZE + 1}–${page * PAGE_SIZE + (data?.row_count || 0)}`}+ {rowsEstimate != null && rowsEstimate > 0 && <span className="dbx-pager-total"> of ≈{rowsEstimate.toLocaleString()}</span>}+ </span>+ <button+ type="button"+ className="dbx-icon-btn"+ onClick={() => setPage((p) => p + 1)}+ disabled={!hasMore || dataLoading}+ aria-label="Next page"+ >+ <ChevronRight size={15} aria-hidden="true" />+ </button>+ </div>+ )}++ <div className="dbx-table-toolbar-spacer" />++ <button type="button" className="dbx-chip" onClick={() => onOpenConsole?.(`SELECT * FROM ${table} LIMIT 100;`)}>+ <Terminal size={14} aria-hidden="true" /> Query+ </button>+ <button+ type="button"+ className="dbx-icon-btn"+ onClick={() => (view === 'data' ? loadData(page) : (setStructure(null), loadStructure()))}+ disabled={dataLoading || structureLoading}+ aria-label="Refresh"+ >+ <RefreshCw size={14} className={dataLoading || structureLoading ? 'dbx-spin' : ''} aria-hidden="true" />+ </button>+ </div>++ <div className="dbx-table-body">+ {view === 'data' ? (+ <ResultsGrid+ columns={data?.columns}+ rows={data?.rows}+ loading={dataLoading}+ error={dataError}+ emptyTitle="Empty table"+ emptyDescription="This table has no rows yet."+ />+ ) : structureUnsupported ? (+ <div className="dbx-structure-fallback">+ Column metadata isn't available for databases inside Docker containers. Use the Data view or a SQL console.+ </div>+ ) : structureLoading ? (+ <div className="dbx-structure-fallback">Loading structure…</div>+ ) : (+ <div className="dbx-grid-scroll">+ <table className="dbx-grid dbx-structure">+ <thead>+ <tr>+ <th scope="col">Column</th>+ <th scope="col">Type</th>+ <th scope="col">Nullable</th>+ <th scope="col">Key</th>+ <th scope="col">Default</th>+ </tr>+ </thead>+ <tbody>+ {(structure || []).map((col) => {+ const isPk = col.key === 'PRI' || col.primary_key;+ return (+ <tr key={col.name}>+ <td className="dbx-col-name">+ {isPk && <KeyRound size={12} className="dbx-pk" aria-label="Primary key" />}+ {col.name}+ </td>+ <td className="dbx-mono">{col.type}</td>+ <td>{col.nullable ? 'YES' : 'NO'}</td>+ <td className="dbx-mono">{isPk ? 'PRIMARY' : (col.key || '—')}</td>+ <td className={col.default == null ? 'is-null dbx-mono' : 'dbx-mono'}>+ {col.default == null ? 'NULL' : String(col.default)}+ </td>+ </tr>+ );+ })}+ {structure && structure.length === 0 && (+ <tr><td colSpan={5} className="dbx-structure-fallback">No columns reported.</td></tr>+ )}+ </tbody>+ </table>+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/frontend/src/components/databases/dbAdapter.js b/frontend/src/components/databases/dbAdapter.jsnew file mode 100644index 00000000..6d90026a--- /dev/null+++ b/frontend/src/components/databases/dbAdapter.js@@ -0,0 +1,81 @@+// Unifies the four database backends (MySQL, PostgreSQL, SQLite, Docker) behind+// one small interface so the explorer's tree and tabs don't branch on engine+// everywhere. A `conn` describes one queryable database:+// { dbType, name?, path?, container?, password?, user?, dockerType? }++import { api } from '../../services/api';++// Engine display metadata. Brand accents live in SCSS via `.is-<engine>` so the+// tree icons tint without inline styles.+export const ENGINE_META = {+ mysql: { label: 'MySQL / MariaDB', short: 'MySQL' },+ postgresql: { label: 'PostgreSQL', short: 'PostgreSQL' },+ sqlite: { label: 'SQLite', short: 'SQLite' },+ docker: { label: 'Docker apps', short: 'Docker' },+};++// A docker container can host either engine; everything else maps 1:1.+function quotingDialect(conn) {+ if (conn.dbType === 'postgresql' || conn.dbType === 'sqlite') return 'ansi';+ if (conn.dbType === 'docker' && conn.dockerType === 'postgresql') return 'ansi';+ return 'backtick';+}++// Quote an identifier so table names with mixed case or reserved words survive.+export function quoteIdent(conn, ident) {+ if (quotingDialect(conn) === 'ansi') {+ return '"' + String(ident).replace(/"/g, '""') + '"';+ }+ return '`' + String(ident).replace(/`/g, '``') + '`';+}++// Stable identity for a connection — used to key consoles and query history.+export function connKey(conn) {+ if (!conn) return '';+ if (conn.dbType === 'sqlite') return `sqlite:${conn.path}`;+ if (conn.dbType === 'docker') return `docker:${conn.container}:${conn.name || ''}`;+ return `${conn.dbType}:${conn.name}`;+}++export function connLabel(conn) {+ if (!conn) return '';+ if (conn.dbType === 'sqlite') return conn.name || conn.path?.split('/').pop() || 'database';+ return conn.name || conn.container || 'database';+}++export async function listTables(conn) {+ switch (conn.dbType) {+ case 'mysql': return api.getMySQLTables(conn.name);+ case 'postgresql': return api.getPostgreSQLTables(conn.name);+ case 'sqlite': return api.getSQLiteTables(conn.path);+ case 'docker': return api.getDockerDatabaseTables(conn.container, conn.name, conn.password);+ default: return { tables: [] };+ }+}++// Docker has no structure endpoint; callers should treat `unsupported` as+// "show data only" rather than an error.+export async function getStructure(conn, table) {+ switch (conn.dbType) {+ case 'mysql': return api.getMySQLTableStructure(conn.name, table);+ case 'postgresql': return api.getPostgreSQLTableStructure(conn.name, table);+ case 'sqlite': return api.getSQLiteTableStructure(conn.path, table);+ default: return { success: false, unsupported: true };+ }+}++export async function runQuery(conn, sql, readonly) {+ switch (conn.dbType) {+ case 'mysql': return api.executeMySQLQuery(conn.name, sql, readonly);+ case 'postgresql': return api.executePostgreSQLQuery(conn.name, sql, readonly);+ case 'sqlite': return api.executeSQLiteQuery(conn.path, sql, readonly);+ case 'docker': return api.executeDockerQuery(conn.container, conn.name, sql, conn.password, readonly);+ default: return { success: false, error: 'Unknown database type' };+ }+}++// Browse-a-table query, built per dialect. Docker MySQL/PostgreSQL both accept+// LIMIT/OFFSET so one shape covers every backend we target.+export function buildBrowseQuery(conn, table, { limit, offset }) {+ return `SELECT * FROM ${quoteIdent(conn, table)} LIMIT ${limit} OFFSET ${offset};`;+}diff --git a/frontend/src/components/databases/modals.jsx b/frontend/src/components/databases/modals.jsxnew file mode 100644index 00000000..d439cb20--- /dev/null+++ b/frontend/src/components/databases/modals.jsx@@ -0,0 +1,344 @@+import { useState } from 'react';+import api from '../../services/api';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';++// Create / credentials modals for the explorer. Logic is unchanged from the+// original Databases page; the explorer wires them to its toolbar and tree.++function CredentialsResult({ title, rows, onDone }) {+ return (+ <div className="modal-overlay" onClick={onDone}>+ <div className="modal" onClick={(e) => e.stopPropagation()}>+ <div className="modal-header">+ <h2>{title}</h2>+ <button className="modal-close" onClick={onDone}>×</button>+ </div>+ <div className="modal-body">+ <div className="credentials-box">+ <p>Save these credentials — the password won't be shown again.</p>+ {rows.map(([label, value]) => (+ <div className="credential-item" key={label}>+ <label>{label}:</label>+ <code>{value}</code>+ </div>+ ))}+ </div>+ </div>+ <div className="modal-actions">+ <Button onClick={onDone}>Done</Button>+ </div>+ </div>+ </div>+ );+}++export function CreateMySQLDatabaseModal({ onClose, onCreated }) {+ const [formData, setFormData] = useState({ name: '', charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci', create_user: true, user_password: '' });+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState('');+ const [createdInfo, setCreatedInfo] = useState(null);++ async function handleSubmit(e) {+ e.preventDefault();+ setError('');+ setLoading(true);+ try {+ const result = await api.createMySQLDatabase(formData);+ if (result.success) {+ if (result.password) setCreatedInfo({ database: formData.name, user: result.user, password: result.password });+ else { onCreated(); onClose(); }+ }+ } catch (err) {+ setError(err.message || 'Failed to create database');+ } finally {+ setLoading(false);+ }+ }++ if (createdInfo) {+ return (+ <CredentialsResult+ title="Database created"+ rows={[['Database', createdInfo.database], ['Username', createdInfo.user], ['Password', createdInfo.password]]}+ onDone={() => { onCreated(); onClose(); }}+ />+ );+ }++ return (+ <div className="modal-overlay" onClick={onClose}>+ <div className="modal" onClick={(e) => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Create MySQL database</h2>+ <button className="modal-close" onClick={onClose}>×</button>+ </div>+ {error && <div className="error-message">{error}</div>}+ <form onSubmit={handleSubmit}>+ <div className="form-group">+ <label>Database name *</label>+ <Input type="text" value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value })} placeholder="my_database" required pattern="[a-zA-Z0-9_]+" autoFocus />+ </div>+ <div className="form-row">+ <div className="form-group">+ <label>Character set</label>+ <select value={formData.charset} onChange={(e) => setFormData({ ...formData, charset: e.target.value })}>+ <option value="utf8mb4">utf8mb4</option>+ <option value="utf8">utf8</option>+ <option value="latin1">latin1</option>+ </select>+ </div>+ <div className="form-group">+ <label>Collation</label>+ <select value={formData.collation} onChange={(e) => setFormData({ ...formData, collation: e.target.value })}>+ <option value="utf8mb4_unicode_ci">utf8mb4_unicode_ci</option>+ <option value="utf8mb4_general_ci">utf8mb4_general_ci</option>+ <option value="utf8_general_ci">utf8_general_ci</option>+ </select>+ </div>+ </div>+ <div className="form-group">+ <label className="checkbox-label">+ <input type="checkbox" checked={formData.create_user} onChange={(e) => setFormData({ ...formData, create_user: e.target.checked })} />+ Create user with same name and full privileges+ </label>+ </div>+ <div className="modal-actions">+ <Button type="button" variant="outline" onClick={onClose}>Cancel</Button>+ <Button type="submit" disabled={loading}>{loading ? 'Creating…' : 'Create database'}</Button>+ </div>+ </form>+ </div>+ </div>+ );+}++export function CreateMySQLUserModal({ databases, onClose, onCreated }) {+ const [formData, setFormData] = useState({ username: '', password: '', host: 'localhost', database: '', privileges: 'ALL' });+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState('');+ const [createdInfo, setCreatedInfo] = useState(null);++ async function generatePassword() {+ try {+ const result = await api.generateDatabasePassword();+ setFormData({ ...formData, password: result.password });+ } catch (err) {+ console.error('Failed to generate password:', err);+ }+ }++ async function handleSubmit(e) {+ e.preventDefault();+ setError('');+ setLoading(true);+ try {+ const result = await api.createMySQLUser(formData);+ if (result.success) setCreatedInfo({ username: formData.username, password: result.password, host: formData.host });+ } catch (err) {+ setError(err.message || 'Failed to create user');+ } finally {+ setLoading(false);+ }+ }++ if (createdInfo) {+ return (+ <CredentialsResult+ title="User created"+ rows={[['Username', createdInfo.username], ['Password', createdInfo.password], ['Host', createdInfo.host]]}+ onDone={() => { onCreated(); onClose(); }}+ />+ );+ }++ return (+ <div className="modal-overlay" onClick={onClose}>+ <div className="modal" onClick={(e) => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Create MySQL user</h2>+ <button className="modal-close" onClick={onClose}>×</button>+ </div>+ {error && <div className="error-message">{error}</div>}+ <form onSubmit={handleSubmit}>+ <div className="form-group">+ <label>Username *</label>+ <Input type="text" value={formData.username} onChange={(e) => setFormData({ ...formData, username: e.target.value })} placeholder="db_user" required autoFocus />+ </div>+ <div className="form-group">+ <label>Password</label>+ <div className="input-with-button">+ <Input type="text" value={formData.password} onChange={(e) => setFormData({ ...formData, password: e.target.value })} placeholder="Leave empty to auto-generate" />+ <Button type="button" variant="outline" size="sm" onClick={generatePassword}>Generate</Button>+ </div>+ </div>+ <div className="form-group">+ <label>Host</label>+ <select value={formData.host} onChange={(e) => setFormData({ ...formData, host: e.target.value })}>+ <option value="localhost">localhost</option>+ <option value="%">% (any host)</option>+ <option value="127.0.0.1">127.0.0.1</option>+ </select>+ </div>+ <div className="form-group">+ <label>Grant privileges on database</label>+ <select value={formData.database} onChange={(e) => setFormData({ ...formData, database: e.target.value })}>+ <option value="">— None —</option>+ {databases.map((db) => <option key={db.name} value={db.name}>{db.name}</option>)}+ </select>+ </div>+ <div className="modal-actions">+ <Button type="button" variant="outline" onClick={onClose}>Cancel</Button>+ <Button type="submit" disabled={loading}>{loading ? 'Creating…' : 'Create user'}</Button>+ </div>+ </form>+ </div>+ </div>+ );+}++export function CreatePostgreSQLDatabaseModal({ onClose, onCreated }) {+ const [formData, setFormData] = useState({ name: '', encoding: 'UTF8', create_user: true });+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState('');+ const [createdInfo, setCreatedInfo] = useState(null);++ async function handleSubmit(e) {+ e.preventDefault();+ setError('');+ setLoading(true);+ try {+ const result = await api.createPostgreSQLDatabase(formData);+ if (result.success) {+ if (result.password) setCreatedInfo({ database: formData.name, user: result.user, password: result.password });+ else { onCreated(); onClose(); }+ }+ } catch (err) {+ setError(err.message || 'Failed to create database');+ } finally {+ setLoading(false);+ }+ }++ if (createdInfo) {+ return (+ <CredentialsResult+ title="Database created"+ rows={[['Database', createdInfo.database], ['Username', createdInfo.user], ['Password', createdInfo.password]]}+ onDone={() => { onCreated(); onClose(); }}+ />+ );+ }++ return (+ <div className="modal-overlay" onClick={onClose}>+ <div className="modal" onClick={(e) => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Create PostgreSQL database</h2>+ <button className="modal-close" onClick={onClose}>×</button>+ </div>+ {error && <div className="error-message">{error}</div>}+ <form onSubmit={handleSubmit}>+ <div className="form-group">+ <label>Database name *</label>+ <Input type="text" value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value })} placeholder="my_database" required autoFocus />+ </div>+ <div className="form-group">+ <label>Encoding</label>+ <select value={formData.encoding} onChange={(e) => setFormData({ ...formData, encoding: e.target.value })}>+ <option value="UTF8">UTF8</option>+ <option value="LATIN1">LATIN1</option>+ <option value="SQL_ASCII">SQL_ASCII</option>+ </select>+ </div>+ <div className="form-group">+ <label className="checkbox-label">+ <input type="checkbox" checked={formData.create_user} onChange={(e) => setFormData({ ...formData, create_user: e.target.checked })} />+ Create user with same name and full privileges+ </label>+ </div>+ <div className="modal-actions">+ <Button type="button" variant="outline" onClick={onClose}>Cancel</Button>+ <Button type="submit" disabled={loading}>{loading ? 'Creating…' : 'Create database'}</Button>+ </div>+ </form>+ </div>+ </div>+ );+}++export function CreatePostgreSQLUserModal({ databases, onClose, onCreated }) {+ const [formData, setFormData] = useState({ username: '', password: '', database: '' });+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState('');+ const [createdInfo, setCreatedInfo] = useState(null);++ async function generatePassword() {+ try {+ const result = await api.generateDatabasePassword();+ setFormData({ ...formData, password: result.password });+ } catch (err) {+ console.error('Failed to generate password:', err);+ }+ }++ async function handleSubmit(e) {+ e.preventDefault();+ setError('');+ setLoading(true);+ try {+ const result = await api.createPostgreSQLUser(formData);+ if (result.success) setCreatedInfo({ username: formData.username, password: result.password });+ } catch (err) {+ setError(err.message || 'Failed to create user');+ } finally {+ setLoading(false);+ }+ }++ if (createdInfo) {+ return (+ <CredentialsResult+ title="User created"+ rows={[['Username', createdInfo.username], ['Password', createdInfo.password]]}+ onDone={() => { onCreated(); onClose(); }}+ />+ );+ }++ return (+ <div className="modal-overlay" onClick={onClose}>+ <div className="modal" onClick={(e) => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Create PostgreSQL user</h2>+ <button className="modal-close" onClick={onClose}>×</button>+ </div>+ {error && <div className="error-message">{error}</div>}+ <form onSubmit={handleSubmit}>+ <div className="form-group">+ <label>Username *</label>+ <Input type="text" value={formData.username} onChange={(e) => setFormData({ ...formData, username: e.target.value })} placeholder="db_user" required autoFocus />+ </div>+ <div className="form-group">+ <label>Password</label>+ <div className="input-with-button">+ <Input type="text" value={formData.password} onChange={(e) => setFormData({ ...formData, password: e.target.value })} placeholder="Leave empty to auto-generate" />+ <Button type="button" variant="outline" size="sm" onClick={generatePassword}>Generate</Button>+ </div>+ </div>+ <div className="form-group">+ <label>Grant privileges on database</label>+ <select value={formData.database} onChange={(e) => setFormData({ ...formData, database: e.target.value })}>+ <option value="">— None —</option>+ {databases.map((db) => <option key={db.name} value={db.name}>{db.name}</option>)}+ </select>+ </div>+ <div className="modal-actions">+ <Button type="button" variant="outline" onClick={onClose}>Cancel</Button>+ <Button type="submit" disabled={loading}>{loading ? 'Creating…' : 'Create user'}</Button>+ </div>+ </form>+ </div>+ </div>+ );+}