Skip to content

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.

feat(databases): build the table builder and dump import that were deferred

Juan Denis42db5b80537c
diff --git a/frontend/src/components/databases/CreateTableModal.jsx b/frontend/src/components/databases/CreateTableModal.jsx
new file mode 100644
index 00000000..c5684c2f
--- /dev/null
+++ b/frontend/src/components/databases/CreateTableModal.jsx
@@ -0,0 +1,499 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import {
+ Plus, Trash2, Copy, Check, AlertTriangle, Loader2, Table2, ShieldAlert, RefreshCw, ChevronDown,
+} from 'lucide-react';
+import api from '../../services/api';
+import Modal from '@/components/Modal';
+import { Button } from '@/components/ui/button';
+import { EngineIcon } from '../icons/DatabaseBrands';
+import EngineGlyph from './EngineGlyph';
+import { runQuery, connKey, ENGINE_META } from './dbAdapter';
+import {
+ engineBrandKey, engineInitialDatabase, engineInstanceKey, engineMeta,
+ engineTreeStatus, engineUnit, singular,
+} from './engineHelpers';
+import {
+ DEFAULT_KEYWORD_LIST, SQL_DIALECTS, buildCreateTable, buildFamilyStatement,
+ dialectOf, emptyColumn, familyTypes, familyWording, starterColumns,
+ starterFields, validate,
+} from './ddlBuilder';
+
+// The column builder from the design mock, wired to the only thing that can
+// actually create a table here: `POST /databases/<engine>/<db>/query` with
+// `readonly: false`, which the backend gates on the admin role.
+//
+// Three honest states, never a fourth that pretends:
+//
+// * a MySQL / PostgreSQL / SQLite / containerised-MySQL database → the
+// statement is generated, shown, and run on demand;
+// * an engine ServerKit installed but has no client bridge for (MongoDB,
+// Redis, Meilisearch, InfluxDB, Neo4j…) → the statement is generated in
+// that engine's own syntax and offered for copying, with the reason;
+// * a non-admin operator → the builder still generates and copies, and says
+// why it will not run.
+
+const COPY_RESET_MS = 1800;
+
+function targetFromConn(conn, engine, label, sub) {
+ const dialect = dialectOf(conn);
+ return {
+ key: `db:${connKey(conn)}`,
+ kind: 'sql',
+ conn,
+ engine,
+ label,
+ sub,
+ dialect,
+ family: 'Relational',
+ unit: 'tables',
+ client: dialect ? SQL_DIALECTS[dialect].label : null,
+ // A containerised PostgreSQL is reached through the container's
+ // MySQL client, so there is no route for its DDL. Say so rather than
+ // offering a button that fails.
+ blockedReason: dialect
+ ? null
+ : 'ServerKit reaches containerised databases through the container\'s MySQL client, so it cannot run statements against a PostgreSQL container.',
+ };
+}
+
+function targetFromEngine(instance) {
+ const meta = engineMeta(instance);
+ const unit = engineUnit(instance);
+ return {
+ key: `engine:${engineInstanceKey(instance)}`,
+ kind: 'engine',
+ instance,
+ engine: engineBrandKey(instance),
+ label: instance.name || instance.template_id,
+ sub: meta.family || 'engine',
+ dialect: null,
+ family: meta.family || 'Relational',
+ unit,
+ client: meta.client || null,
+ database: engineInitialDatabase(instance),
+ blockedReason: `ServerKit runs ${instance.name || 'this engine'} but has no ${meta.client || 'client'} bridge, so it cannot create ${unit} for you.`,
+ };
+}
+
+export default function CreateTableModal({ preset, engines = [], isAdmin = false, onClose, onCreated }) {
+ const [targets, setTargets] = useState(null); // null while loading
+ const [loadFailed, setLoadFailed] = useState(false);
+ const [targetKey, setTargetKey] = useState('');
+ const [name, setName] = useState('');
+ const [cols, setCols] = useState([]);
+ const [busy, setBusy] = useState(false);
+ const [result, setResult] = useState(null); // { ok, message }
+ const [copied, setCopied] = useState(false);
+ const copyTimer = useRef(null);
+
+ // The page re-polls its engine list while an install is in flight, so the
+ // props change under us. Read them through refs: reloading the target list
+ // mid-edit would throw away the columns being typed.
+ const enginesRef = useRef(engines);
+ enginesRef.current = engines;
+ const presetRef = useRef(preset);
+ presetRef.current = preset;
+
+ useEffect(() => () => clearTimeout(copyTimer.current), []);
+
+ // The four listings the explorer's tree is built from. Each one is allowed
+ // to fail on its own — a stopped PostgreSQL must not hide a running MySQL.
+ const load = useCallback(async () => {
+ setTargets(null);
+ setLoadFailed(false);
+ const [my, pg, lite, dock] = await Promise.allSettled([
+ api.getMySQLDatabases(),
+ api.getPostgreSQLDatabases(),
+ api.getSQLiteDatabases(),
+ api.getAllDockerDatabases(),
+ ]);
+ const out = [];
+ if (my.status === 'fulfilled') {
+ (my.value?.databases || []).forEach((db) => out.push(
+ targetFromConn({ dbType: 'mysql', name: db.name }, 'mysql', db.name, ENGINE_META.mysql.short),
+ ));
+ }
+ if (pg.status === 'fulfilled') {
+ (pg.value?.databases || []).forEach((db) => out.push(
+ targetFromConn({ dbType: 'postgresql', name: db.name }, 'postgresql', db.name, ENGINE_META.postgresql.short),
+ ));
+ }
+ if (lite.status === 'fulfilled') {
+ (lite.value?.databases || []).forEach((db) => out.push(
+ targetFromConn({ dbType: 'sqlite', name: db.name, path: db.path }, 'sqlite', db.name, db.path),
+ ));
+ }
+ if (dock.status === 'fulfilled') {
+ (dock.value?.databases || []).forEach((db) => out.push(targetFromConn(
+ {
+ dbType: 'docker',
+ container: db.container,
+ name: db.database,
+ password: db.password || db.root_password,
+ user: db.user,
+ dockerType: db.type,
+ },
+ db.type || 'docker',
+ db.database || 'default',
+ db.app_name ? `${db.app_name} · container` : 'container',
+ )));
+ }
+
+ // Engines ServerKit installed but speaks no protocol for. Listed so the
+ // builder can still write their syntax — the mock's family awareness,
+ // without the mock's pretend execution.
+ enginesRef.current
+ .filter((e) => engineTreeStatus(e) === 'active')
+ .filter((e) => !['mysql', 'postgresql'].includes(engineMeta(e).protocol))
+ .forEach((e) => out.push(targetFromEngine(e)));
+
+ if (my.status === 'rejected' && pg.status === 'rejected'
+ && lite.status === 'rejected' && dock.status === 'rejected') {
+ setLoadFailed(true);
+ }
+
+ // A right-clicked node always works, even when its listing failed.
+ const seed = presetRef.current;
+ if (seed?.conn) {
+ const presetTarget = targetFromConn(
+ seed.conn, seed.engine, seed.label || 'database', 'selected in the tree',
+ );
+ const existing = out.find((t) => t.key === presetTarget.key);
+ if (!existing) out.unshift(presetTarget);
+ setTargetKey(presetTarget.key);
+ } else if (out.length) {
+ setTargetKey((cur) => (out.some((t) => t.key === cur) ? cur : out[0].key));
+ }
+ setTargets(out);
+ }, []);
+
+ useEffect(() => { load(); }, [load]);
+
+ const target = useMemo(
+ () => (targets || []).find((t) => t.key === targetKey) || null,
+ [targets, targetKey],
+ );
+
+ // Each engine shape gets its own starter rows — a document store opening on
+ // `id BIGINT AUTO_INCREMENT` would be nonsense. Keyed on the target's id,
+ // not the object, so a re-listing never wipes work in progress.
+ useEffect(() => {
+ const picked = (targets || []).find((t) => t.key === targetKey);
+ if (!picked) return;
+ setCols(picked.dialect ? starterColumns(picked.dialect) : starterFields(picked.family));
+ setResult(null);
+ }, [targetKey]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const unitOne = singular(target?.unit || 'tables');
+ const words = familyWording(target?.dialect ? 'Relational' : target?.family);
+ const types = target?.dialect ? SQL_DIALECTS[target.dialect].types : familyTypes(target?.family);
+ const canRun = Boolean(target && target.dialect && isAdmin && !result?.ok);
+
+ const issues = useMemo(
+ () => (target ? validate({ table: name, columns: cols, unitOne }) : []),
+ [target, name, cols, unitOne],
+ );
+
+ const statement = useMemo(() => {
+ if (!target) return '';
+ if (target.dialect) {
+ return buildCreateTable({
+ conn: target.conn, dialect: target.dialect, table: name, columns: cols,
+ });
+ }
+ return buildFamilyStatement({
+ family: target.family, name, database: target.database, fields: cols,
+ });
+ }, [target, name, cols]);
+
+ const setCol = (i, key, value) => setCols((prev) => prev.map((c, j) => (j === i ? { ...c, [key]: value } : c)));
+ const setKeyCol = (i) => setCols((prev) => prev.map((c, j) => ({ ...c, pk: j === i ? !c.pk : false })));
+ const addCol = () => setCols((prev) => [...prev, target?.dialect ? emptyColumn(target.dialect) : { name: '', type: types[0], pk: false, notNull: false, def: '' }]);
+ const removeCol = (i) => setCols((prev) => (prev.length > 1 ? prev.filter((_, j) => j !== i) : prev));
+
+ async function run() {
+ if (!canRun || issues.length) return;
+ setBusy(true);
+ setResult(null);
+ try {
+ const res = await runQuery(target.conn, statement, false);
+ if (res?.success) {
+ setResult({ ok: true, message: `${unitOne.charAt(0).toUpperCase()}${unitOne.slice(1)} "${name.trim()}" created in ${target.label}.` });
+ onCreated?.(target);
+ } else {
+ setResult({ ok: false, message: res?.error || 'The database rejected the statement.' });
+ }
+ } catch (err) {
+ setResult({
+ ok: false,
+ message: err?.status === 403
+ ? 'Your account is not an administrator, so ServerKit will not run write statements for it.'
+ : (err?.message || 'The request failed.'),
+ });
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ function copy() {
+ if (!navigator.clipboard) {
+ setResult({ ok: false, message: 'This browser will not give the page clipboard access. Select the statement and copy it manually.' });
+ return;
+ }
+ navigator.clipboard.writeText(statement).then(
+ () => {
+ setCopied(true);
+ clearTimeout(copyTimer.current);
+ copyTimer.current = setTimeout(() => setCopied(false), COPY_RESET_MS);
+ },
+ () => setResult({ ok: false, message: 'Could not copy to the clipboard.' }),
+ );
+ }
+
+ const footer = (
+ <>
+ <Button type="button" variant="outline" onClick={onClose}>
+ {result?.ok ? 'Done' : 'Cancel'}
+ </Button>
+ <Button type="button" variant="outline" onClick={copy} disabled={!statement}>
+ {copied ? <Check size={14} aria-hidden="true" /> : <Copy size={14} aria-hidden="true" />}
+ {copied ? 'Copied' : 'Copy statement'}
+ </Button>
+ {canRun && (
+ <Button type="button" onClick={run} disabled={busy || issues.length > 0}>
+ {busy
+ ? <Loader2 size={14} className="dbx-spin" aria-hidden="true" />
+ : <Plus size={14} aria-hidden="true" />}
+ {busy ? 'Running…' : `Create ${unitOne}`}
+ </Button>
+ )}
+ </>
+ );
+
+ return (
+ <Modal open onClose={onClose} title={`New ${unitOne}`} size="xl" footer={footer}>
+ {targets === null ? (
+ <p className="dbx-builder__loading">
+ <Loader2 size={15} className="dbx-spin" aria-hidden="true" /> Looking for databases…
+ </p>
+ ) : !targets.length ? (
+ <div className="dbx-notice dbx-notice--info">
+ <AlertTriangle size={15} aria-hidden="true" />
+ <div>
+ <strong>Nothing to create into yet.</strong>
+ <p>
+ {loadFailed
+ ? 'ServerKit could not reach any database server. Check that MySQL or PostgreSQL is running, then try again.'
+ : 'Create a database first — the builder writes into an existing one.'}
+ </p>
+ <button type="button" className="dbx-inline-link" onClick={load}>
+ <RefreshCw size={13} aria-hidden="true" /> Try again
+ </button>
+ </div>
+ </div>
+ ) : (
+ <div className="dbx-builder">
+ {loadFailed && (
+ <div className="dbx-notice dbx-notice--warn">
+ <AlertTriangle size={15} aria-hidden="true" />
+ <div><p>Some database servers did not answer, so this list may be incomplete.</p></div>
+ </div>
+ )}
+
+ <div className="dbx-field-row">
+ <div className="dbx-field">
+ <label className="dbx-field__label" htmlFor="dbx-builder-target">Database</label>
+ <div className="dbx-select">
+ <select
+ id="dbx-builder-target"
+ value={targetKey}
+ onChange={(e) => setTargetKey(e.target.value)}
+ >
+ {targets.some((t) => t.dialect) && (
+ <optgroup label="Databases ServerKit can write to">
+ {targets.filter((t) => t.dialect).map((t) => (
+ <option key={t.key} value={t.key}>{t.label} · {t.sub}</option>
+ ))}
+ </optgroup>
+ )}
+ {targets.some((t) => !t.dialect) && (
+ <optgroup label="Generate only — no client bridge">
+ {targets.filter((t) => !t.dialect).map((t) => (
+ <option key={t.key} value={t.key}>{t.label} · {t.sub}</option>
+ ))}
+ </optgroup>
+ )}
+ </select>
+ <ChevronDown size={14} aria-hidden="true" />
+ </div>
+ </div>
+ <div className="dbx-field">
+ <label className="dbx-field__label" htmlFor="dbx-builder-name">
+ {unitOne.charAt(0).toUpperCase() + unitOne.slice(1)} name
+ </label>
+ <div className="dbx-input">
+ <Table2 size={15} aria-hidden="true" />
+ <input
+ id="dbx-builder-name"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder={target?.dialect ? 'orders' : 'users'}
+ spellCheck="false"
+ autoFocus
+ />
+ </div>
+ </div>
+ </div>
+
+ {target && (
+ <p className="dbx-builder__target">
+ <span className="dbx-builder__target-ico">
+ {target.instance
+ ? <EngineGlyph entry={target.instance} size={15} />
+ : <EngineIcon engine={target.engine || 'database'} size={15} />}
+ </span>
+ {target.dialect
+ ? <>Statements run as {SQL_DIALECTS[target.dialect].label} against <code>{target.label}</code>.</>
+ : <>{target.blockedReason}</>}
+ </p>
+ )}
+
+ {target && !target.dialect && target.client && (
+ <div className="dbx-notice dbx-notice--info">
+ <AlertTriangle size={15} aria-hidden="true" />
+ <div>
+ <strong>Copy this into {target.client}.</strong>
+ <p>The builder writes the statement; running it is a step you take in the engine&apos;s own client.</p>
+ </div>
+ </div>
+ )}
+
+ {target?.dialect && !isAdmin && (
+ <div className="dbx-notice dbx-notice--warn">
+ <ShieldAlert size={15} aria-hidden="true" />
+ <div>
+ <strong>Read-only account.</strong>
+ <p>Creating a {unitOne} is a write statement, and only administrators may run those. You can still build and copy it.</p>
+ </div>
+ </div>
+ )}
+
+ <div className="dbx-field">
+ <span className="dbx-field__label">{words.fields}</span>
+ <div className="dbx-colgrid">
+ <div className="dbx-colgrid__head">
+ <span>Name</span>
+ <span>Type</span>
+ <span>{words.key}</span>
+ <span>{words.required}</span>
+ <span>Default</span>
+ <span aria-hidden="true" />
+ </div>
+ <div className="dbx-colgrid__rows">
+ {cols.map((c, i) => (
+ // Rows are positional and reorderable only by
+ // add/remove, so the index is their identity.
+ <div className="dbx-colgrid__row" key={i}>
+ <div className="dbx-input dbx-input--sm">
+ <input
+ value={c.name}
+ onChange={(e) => setCol(i, 'name', e.target.value)}
+ placeholder={target?.dialect ? 'column' : 'field'}
+ spellCheck="false"
+ aria-label={`Name of column ${i + 1}`}
+ />
+ </div>
+ <div className="dbx-select dbx-select--sm">
+ <select
+ value={c.type}
+ onChange={(e) => setCol(i, 'type', e.target.value)}
+ aria-label={`Type of column ${i + 1}`}
+ >
+ {types.map((t) => <option key={t} value={t}>{t}</option>)}
+ </select>
+ <ChevronDown size={12} aria-hidden="true" />
+ </div>
+ <button
+ type="button"
+ className={`dbx-cbox${c.pk ? ' is-on' : ''}`}
+ onClick={() => setKeyCol(i)}
+ aria-pressed={Boolean(c.pk)}
+ aria-label={`${words.key} on column ${i + 1}`}
+ >
+ {c.pk && <Check size={12} aria-hidden="true" />}
+ </button>
+ <button
+ type="button"
+ className={`dbx-cbox${c.notNull ? ' is-on' : ''}`}
+ onClick={() => setCol(i, 'notNull', !c.notNull)}
+ aria-pressed={Boolean(c.notNull)}
+ aria-label={`${words.required} on column ${i + 1}`}
+ >
+ {c.notNull && <Check size={12} aria-hidden="true" />}
+ </button>
+ <div className="dbx-input dbx-input--sm">
+ <input
+ value={c.def}
+ onChange={(e) => setCol(i, 'def', e.target.value)}
+ placeholder="—"
+ spellCheck="false"
+ aria-label={`Default for column ${i + 1}`}
+ />
+ </div>
+ <button
+ type="button"
+ className="dbx-icon-xs"
+ onClick={() => removeCol(i)}
+ disabled={cols.length < 2}
+ aria-label={`Remove column ${i + 1}`}
+ >
+ <Trash2 size={13} aria-hidden="true" />
+ </button>
+ </div>
+ ))}
+ </div>
+ <button type="button" className="dbx-inline-link dbx-colgrid__add" onClick={addCol}>
+ <Plus size={13} aria-hidden="true" /> Add {target?.dialect ? 'column' : 'field'}
+ </button>
+ </div>
+ <p className="dbx-field-hint">
+ {target?.dialect ? (
+ <>
+ A whole-number key becomes <code>{SQL_DIALECTS[target.dialect].keyNote}</code>.
+ Defaults: numbers stay numbers, {DEFAULT_KEYWORD_LIST.join(' / ')} stay keywords,
+ anything else is quoted as text.
+ </>
+ ) : (
+ <>Field names and types are written into the statement below exactly as typed.</>
+ )}
+ </p>
+ </div>
+
+ <div className="dbx-field">
+ <span className="dbx-field__label">
+ {target?.dialect ? 'Will run' : `${target?.client || 'Client'} statement`}
+ </span>
+ <pre className="dbx-sqlprev">{statement}</pre>
+ </div>
+
+ {issues.length > 0 && (
+ <ul className="dbx-issues">
+ {issues.map((issue) => (
+ <li key={issue}><AlertTriangle size={13} aria-hidden="true" /> {issue}</li>
+ ))}
+ </ul>
+ )}
+
+ {result && (
+ <div className={`dbx-notice ${result.ok ? 'dbx-notice--ok' : 'dbx-notice--error'}`}>
+ {result.ok
+ ? <Check size={15} aria-hidden="true" />
+ : <AlertTriangle size={15} aria-hidden="true" />}
+ <div><p>{result.message}</p></div>
+ </div>
+ )}
+ </div>
+ )}
+ </Modal>
+ );
+}
diff --git a/frontend/src/components/databases/DbBlankStates.jsx b/frontend/src/components/databases/DbBlankStates.jsx
index 4de29334..db375acf 100644
--- a/frontend/src/components/databases/DbBlankStates.jsx
+++ b/frontend/src/components/databases/DbBlankStates.jsx
@@ -1,7 +1,7 @@
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import {
- Loader2, Plus, Terminal, Table2, Activity, RefreshCw, ShieldAlert, Layers, Database,
+ Loader2, Plus, Terminal, Table2, Activity, RefreshCw, ShieldAlert, Layers, Database, Download,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import api from '../../services/api';
@@ -157,10 +157,10 @@ export function EngineReadyPanel({ instance, label, onNewDatabase, onOpenConsole
);
}
-// A database that exists but holds no tables/collections yet. The table builder
-// and dump import are deliberately out of scope for this round, so the honest
-// next step is the console.
-export function DatabaseEmptyPanel({ node, unit = 'tables', onOpenConsole }) {
+// A database that exists but holds no tables/collections yet. The two ways to
+// put something in it — build it column by column, or replay a dump — are the
+// primary actions; the console stays as the way to do anything else.
+export function DatabaseEmptyPanel({ node, unit = 'tables', onNewTable, onImport, onOpenConsole }) {
const unitOne = singular(unit);
return (
<div className="dbx-blank">
@@ -169,11 +169,22 @@ export function DatabaseEmptyPanel({ node, unit = 'tables', onOpenConsole }) {
</div>
<h2 className="dbx-blank__title">No {unit} in {node?.label}</h2>
<p className="dbx-blank__body">
- The database is connected and empty. Create your first {unitOne} from the console.
+ The database is connected and empty. Build your first {unitOne}, import a dump,
+ or write the statement yourself in the console.
</p>
<div className="dbx-blank__actions">
+ {onNewTable && (
+ <Button type="button" size="sm" onClick={onNewTable}>
+ <Plus size={14} aria-hidden="true" /> New {unitOne}
+ </Button>
+ )}
+ {onImport && (
+ <Button type="button" size="sm" variant="outline" onClick={onImport}>
+ <Download size={14} aria-hidden="true" /> Import dump
+ </Button>
+ )}
{onOpenConsole && (
- <Button type="button" size="sm" onClick={onOpenConsole}>
+ <Button type="button" size="sm" variant="outline" onClick={onOpenConsole}>
<Terminal size={14} aria-hidden="true" /> Open SQL console
</Button>
)}
diff --git a/frontend/src/components/databases/ImportDumpModal.jsx b/frontend/src/components/databases/ImportDumpModal.jsx
new file mode 100644
index 00000000..b4e1e502
--- /dev/null
+++ b/frontend/src/components/databases/ImportDumpModal.jsx
@@ -0,0 +1,353 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import {
+ AlertTriangle, Check, ChevronDown, Database, FileCode2, HardDrive, Loader2,
+ RefreshCw, ShieldAlert,
+} from 'lucide-react';
+import api from '../../services/api';
+import Modal from '@/components/Modal';
+import { Button } from '@/components/ui/button';
+import { EngineIcon } from '../icons/DatabaseBrands';
+import { formatBytes } from '@/utils/formatBytes';
+import { ENGINE_META } from './dbAdapter';
+
+// Import a SQL dump into an existing database.
+//
+// The backend contract this is built around (it is older than the design mock
+// and does not match it):
+//
+// POST /api/v1/databases/mysql/<name>/restore { backup_path }
+// POST /api/v1/databases/postgresql/<name>/restore { backup_path }
+//
+// `backup_path` is a path **on the server**. There is no upload endpoint, so a
+// file sitting in the operator's browser cannot be imported — this modal says
+// that rather than showing a file picker that would go nowhere. `.gz` is
+// decompressed server-side. Both routes are admin-only, and neither takes a
+// snapshot first, so the pre-import backup here is an explicit extra call.
+
+const SOURCES = [
+ { id: 'backup', label: 'A backup on this server' },
+ { id: 'path', label: 'A path on the server' },
+];
+
+// SQLite and containerised databases have no restore route at all.
+const RESTORABLE = ['mysql', 'postgresql'];
+
+export default function ImportDumpModal({ preset, isAdmin = false, onClose, onImported }) {
+ const [databases, setDatabases] = useState(null); // null while loading
+ const [loadFailed, setLoadFailed] = useState(false);
+ const [targetKey, setTargetKey] = useState('');
+ const [source, setSource] = useState('backup');
+ const [backups, setBackups] = useState([]);
+ const [backupsLoading, setBackupsLoading] = useState(true);
+ const [picked, setPicked] = useState('');
+ const [manualPath, setManualPath] = useState('');
+ const [backupFirst, setBackupFirst] = useState(true);
+ const [confirmText, setConfirmText] = useState('');
+ const [busy, setBusy] = useState(false);
+ const [step, setStep] = useState('');
+ const [result, setResult] = useState(null); // { ok, message, detail }
+
+ const presetName = preset?.conn?.dbType === 'mysql' || preset?.conn?.dbType === 'postgresql'
+ ? `${preset.conn.dbType}:${preset.conn.name}`
+ : '';
+
+ const load = useCallback(async () => {
+ setDatabases(null);
+ setLoadFailed(false);
+ const [my, pg] = await Promise.allSettled([
+ api.getMySQLDatabases(),
+ api.getPostgreSQLDatabases(),
+ ]);
+ const out = [];
+ if (my.status === 'fulfilled') {
+ (my.value?.databases || []).forEach((db) => out.push({ key: `mysql:${db.name}`, engine: 'mysql', name: db.name }));
+ }
+ if (pg.status === 'fulfilled') {
+ (pg.value?.databases || []).forEach((db) => out.push({ key: `postgresql:${db.name}`, engine: 'postgresql', name: db.name }));
+ }
+ if (my.status === 'rejected' && pg.status === 'rejected') setLoadFailed(true);
+ setDatabases(out);
+ setTargetKey((cur) => {
+ if (out.some((d) => d.key === cur)) return cur;
+ if (out.some((d) => d.key === presetName)) return presetName;
+ return out[0]?.key || '';
+ });
+ }, [presetName]);
+
+ const loadBackups = useCallback(async () => {
+ setBackupsLoading(true);
+ try {
+ const data = await api.getDatabaseBackups();
+ setBackups(data.backups || []);
+ } catch {
+ // A missing backup directory is not an error worth a red panel —
+ // the path field still works.
+ setBackups([]);
+ } finally {
+ setBackupsLoading(false);
+ }
+ }, []);
+
+ useEffect(() => { load(); }, [load]);
+ useEffect(() => { loadBackups(); }, [loadBackups]);
+
+ const target = useMemo(
+ () => (databases || []).find((d) => d.key === targetKey) || null,
+ [databases, targetKey],
+ );
+
+ const chosen = backups.find((b) => b.filename === picked) || null;
+ const backupPath = source === 'backup' ? (chosen?.path || '') : manualPath.trim();
+ const mismatch = Boolean(chosen && target && chosen.type !== target.engine);
+ const confirmed = Boolean(target) && confirmText.trim() === target.name;
+ const ready = Boolean(target && backupPath && confirmed && isAdmin && !result?.ok);
+
+ async function run() {
+ if (!ready || busy) return;
+ setBusy(true);
+ setResult(null);
+ try {
+ if (backupFirst) {
+ setStep(`Backing up ${target.name}…`);
+ const safety = target.engine === 'mysql'
+ ? await api.backupMySQLDatabase(target.name)
+ : await api.backupPostgreSQLDatabase(target.name);
+ if (!safety?.success) {
+ setResult({
+ ok: false,
+ message: 'The pre-import backup failed, so nothing was imported.',
+ detail: safety?.error || 'The backup endpoint did not report success.',
+ });
+ return;
+ }
+ }
+ setStep(`Importing into ${target.name}…`);
+ const res = target.engine === 'mysql'
+ ? await api.restoreMySQLDatabase(target.name, backupPath)
+ : await api.restorePostgreSQLDatabase(target.name, backupPath);
+ if (res?.success) {
+ setResult({ ok: true, message: res.message || `Dump imported into ${target.name}.` });
+ onImported?.(target);
+ } else {
+ setResult({ ok: false, message: 'The import failed.', detail: res?.error || 'The server did not say why.' });
+ }
+ } catch (err) {
+ setResult({
+ ok: false,
+ message: err?.status === 403
+ ? 'Your account is not an administrator, so ServerKit will not import dumps for it.'
+ : 'The import failed.',
+ detail: err?.status === 403 ? null : (err?.message || 'The request failed.'),
+ });
+ } finally {
+ setStep('');
+ setBusy(false);
+ }
+ }
+
+ const footer = (
+ <>
+ <Button type="button" variant="outline" onClick={onClose}>{result?.ok ? 'Done' : 'Cancel'}</Button>
+ <Button type="button" variant="danger" onClick={run} disabled={!ready || busy}>
+ {busy
+ ? <Loader2 size={14} className="dbx-spin" aria-hidden="true" />
+ : <FileCode2 size={14} aria-hidden="true" />}
+ {busy ? (step || 'Working…') : 'Import and overwrite'}
+ </Button>
+ </>
+ );
+
+ return (
+ <Modal open onClose={onClose} title="Import SQL dump" size="lg" footer={footer}>
+ {databases === null ? (
+ <p className="dbx-builder__loading">
+ <Loader2 size={15} className="dbx-spin" aria-hidden="true" /> Looking for databases…
+ </p>
+ ) : !databases.length ? (
+ <div className="dbx-notice dbx-notice--info">
+ <AlertTriangle size={15} aria-hidden="true" />
+ <div>
+ <strong>No database can accept a dump right now.</strong>
+ <p>
+ {loadFailed
+ ? 'Neither MySQL nor PostgreSQL answered. Check that the server is running, then try again.'
+ : `Importing is only wired for ${RESTORABLE.map((e) => ENGINE_META[e].short).join(' and ')} databases on this host — SQLite files and containerised databases have no restore route.`}
+ </p>
+ <button type="button" className="dbx-inline-link" onClick={load}>
+ <RefreshCw size={13} aria-hidden="true" /> Try again
+ </button>
+ </div>
+ </div>
+ ) : (
+ <div className="dbx-import">
+ {!isAdmin && (
+ <div className="dbx-notice dbx-notice--warn">
+ <ShieldAlert size={15} aria-hidden="true" />
+ <div>
+ <strong>Read-only account.</strong>
+ <p>Importing a dump rewrites a database, and only administrators may do that.</p>
+ </div>
+ </div>
+ )}
+
+ <div className="dbx-field">
+ <label className="dbx-field__label" htmlFor="dbx-import-target">Import into</label>
+ <div className="dbx-select">
+ <select id="dbx-import-target" value={targetKey} onChange={(e) => setTargetKey(e.target.value)}>
+ {databases.map((d) => (
+ <option key={d.key} value={d.key}>
+ {ENGINE_META[d.engine].short} · {d.name}
+ </option>
+ ))}
+ </select>
+ <ChevronDown size={14} aria-hidden="true" />
+ </div>
+ {target && (
+ <p className="dbx-field-hint">
+ <span className="dbx-builder__target-ico"><EngineIcon engine={target.engine} size={13} /></span>
+ {' '}The dump is piped into <code>{target.name}</code> on this server&apos;s
+ {' '}{ENGINE_META[target.engine].short} as the database superuser.
+ </p>
+ )}
+ </div>
+
+ <div className="dbx-field">
+ <span className="dbx-field__label">Dump file</span>
+ <div className="dbx-choice" role="group" aria-label="Where the dump lives">
+ {SOURCES.map((s) => (
+ <button
+ key={s.id}
+ type="button"
+ className={`dbx-choice__btn${source === s.id ? ' is-on' : ''}`}
+ onClick={() => setSource(s.id)}
+ aria-pressed={source === s.id}
+ >
+ {s.label}
+ </button>
+ ))}
+ </div>
+
+ {source === 'backup' ? (
+ <div className="dbx-dumps">
+ {backupsLoading ? (
+ <p className="dbx-dumps__empty">
+ <Loader2 size={14} className="dbx-spin" aria-hidden="true" /> Reading the backup directory…
+ </p>
+ ) : !backups.length ? (
+ <p className="dbx-dumps__empty">
+ <HardDrive size={14} aria-hidden="true" />
+ No dumps in ServerKit&apos;s backup directory yet. Back up a database, or point at a path below.
+ </p>
+ ) : backups.map((b) => (
+ <button
+ key={b.filename}
+ type="button"
+ className={`dbx-dump${picked === b.filename ? ' is-on' : ''}`}
+ onClick={() => setPicked(b.filename)}
+ aria-pressed={picked === b.filename}
+ >
+ <span className="dbx-dump__main">
+ <span className="dbx-dump__name">{b.filename}</span>
+ <span className="dbx-dump__meta">
+ {b.database} · {formatBytes(b.size, { decimals: 1, defaultValue: '0 B' })}
+ {' · '}{new Date(b.created_at).toLocaleString()}
+ </span>
+ </span>
+ <span className={`dbx-dump__tag is-${b.type}`}>
+ {ENGINE_META[b.type]?.short || b.type}
+ </span>
+ </button>
+ ))}
+ </div>
+ ) : (
+ <>
+ <div className="dbx-input">
+ <Database size={15} aria-hidden="true" />
+ <input
+ value={manualPath}
+ onChange={(e) => setManualPath(e.target.value)}
+ placeholder="/var/backups/serverkit/app_prod.sql.gz"
+ spellCheck="false"
+ aria-label="Path to the dump file on the server"
+ />
+ </div>
+ <p className="dbx-field-hint">
+ An absolute path on the server that runs ServerKit. There is no upload
+ endpoint, so a file on your own machine has to be copied across first
+ (scp, the file manager, or a backup taken here). <code>.gz</code> is
+ decompressed automatically.
+ </p>
+ </>
+ )}
+ </div>
+
+ {mismatch && (
+ <div className="dbx-notice dbx-notice--warn">
+ <AlertTriangle size={15} aria-hidden="true" />
+ <div>
+ <p>
+ That dump was taken from {ENGINE_META[chosen.type]?.short || chosen.type} and you are
+ importing into {ENGINE_META[target.engine].short}. The statements are unlikely to apply cleanly.
+ </p>
+ </div>
+ </div>
+ )}
+
+ <label className="dbx-check">
+ <input type="checkbox" checked={backupFirst} onChange={(e) => setBackupFirst(e.target.checked)} />
+ <span>
+ <span className="dbx-check__title">Back up {target?.name || 'the database'} first</span>
+ <span className="dbx-check__sub">
+ Takes a dump through ServerKit&apos;s own backup route before importing. If it fails, the import does not run.
+ </span>
+ </span>
+ </label>
+
+ <div className="dbx-notice dbx-notice--danger">
+ <AlertTriangle size={15} aria-hidden="true" />
+ <div>
+ <strong>This rewrites {target?.name || 'the database'}.</strong>
+ <p>
+ Every statement in the dump is executed against it. Tables the dump
+ recreates lose whatever they hold now, and there is no undo beyond the
+ backup above.
+ </p>
+ </div>
+ </div>
+
+ <div className="dbx-field">
+ <label className="dbx-field__label" htmlFor="dbx-import-confirm">
+ Type <code>{target?.name}</code> to confirm
+ </label>
+ <div className="dbx-input">
+ <Check size={15} aria-hidden="true" />
+ <input
+ id="dbx-import-confirm"
+ value={confirmText}
+ onChange={(e) => setConfirmText(e.target.value)}
+ placeholder={target?.name}
+ spellCheck="false"
+ autoComplete="off"
+ />
+ </div>
+ {!backupPath && (
+ <p className="dbx-field-hint">Pick a dump file above before importing.</p>
+ )}
+ </div>
+
+ {result && (
+ <div className={`dbx-notice ${result.ok ? 'dbx-notice--ok' : 'dbx-notice--error'}`}>
+ {result.ok
+ ? <Check size={15} aria-hidden="true" />
+ : <AlertTriangle size={15} aria-hidden="true" />}
+ <div>
+ <strong>{result.message}</strong>
+ {result.detail && <pre className="dbx-notice__detail">{result.detail}</pre>}
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </Modal>
+ );
+}
diff --git a/frontend/src/components/databases/ddlBuilder.js b/frontend/src/components/databases/ddlBuilder.js
new file mode 100644
index 00000000..d236b934
--- /dev/null
+++ b/frontend/src/components/databases/ddlBuilder.js
@@ -0,0 +1,301 @@
+// Statement builders for the "new table / collection / index" flow.
+//
+// Everything here is pure: given a target and a list of columns it returns the
+// exact text that will be sent to the database, so the modal can show the
+// operator the statement before anything runs. Nothing in this file talks to
+// the network.
+//
+// Two safety rules hold for every generator:
+//
+// * identifiers are validated against `IDENT_RE` and then quoted with
+// `quoteIdent()` — they are never concatenated raw;
+// * a default value is encoded as a *literal* (number, allow-listed keyword,
+// or a quoted string), so free text can never become SQL.
+
+import { quoteIdent } from './dbAdapter';
+
+// Longest identifier PostgreSQL accepts without silently truncating; MySQL
+// (64) and SQLite (unbounded) are both happy inside it.
+export const IDENT_MAX = 63;
+export const IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
+
+export function identError(value, what = 'Name') {
+ const v = String(value || '').trim();
+ if (!v) return `${what} is required.`;
+ if (v.length > IDENT_MAX) return `${what} is longer than ${IDENT_MAX} characters.`;
+ if (!IDENT_RE.test(v)) {
+ return `${what} may only contain letters, digits and underscores, and cannot start with a digit.`;
+ }
+ return null;
+}
+
+// ─── SQL dialects ────────────────────────────────────────────
+// Only the three ServerKit can actually execute against. `integers` drives the
+// auto-increment substitution: a primary key on one of these types becomes the
+// dialect's own generated-key form.
+export const SQL_DIALECTS = {
+ mysql: {
+ label: 'MySQL',
+ types: ['BIGINT', 'INT', 'SMALLINT', 'DECIMAL(10,2)', 'DOUBLE', 'VARCHAR(255)', 'VARCHAR(64)', 'TEXT', 'BOOLEAN', 'DATE', 'DATETIME', 'TIMESTAMP', 'JSON'],
+ integers: ['BIGINT', 'INT', 'SMALLINT'],
+ keyType: 'BIGINT',
+ textType: 'VARCHAR(255)',
+ stampType: 'TIMESTAMP',
+ keyNote: 'AUTO_INCREMENT',
+ },
+ postgresql: {
+ label: 'PostgreSQL',
+ types: ['BIGINT', 'INTEGER', 'SMALLINT', 'NUMERIC(10,2)', 'DOUBLE PRECISION', 'VARCHAR(255)', 'TEXT', 'BOOLEAN', 'DATE', 'TIMESTAMP', 'TIMESTAMPTZ', 'JSONB', 'UUID'],
+ integers: ['BIGINT', 'INTEGER', 'SMALLINT'],
+ keyType: 'BIGINT',
+ textType: 'VARCHAR(255)',
+ stampType: 'TIMESTAMPTZ',
+ keyNote: 'BIGSERIAL',
+ },
+ sqlite: {
+ label: 'SQLite',
+ types: ['INTEGER', 'TEXT', 'REAL', 'NUMERIC', 'BLOB'],
+ integers: ['INTEGER'],
+ keyType: 'INTEGER',
+ textType: 'TEXT',
+ stampType: 'TEXT',
+ keyNote: 'AUTOINCREMENT',
+ },
+};
+
+// Which dialect a connection speaks, or null when ServerKit has no way to run
+// a statement against it. A Docker connection is executed through the
+// container's mysql/mariadb client, so a containerised PostgreSQL has no path.
+export function dialectOf(conn) {
+ if (!conn) return null;
+ if (conn.dbType === 'mysql') return 'mysql';
+ if (conn.dbType === 'postgresql') return 'postgresql';
+ if (conn.dbType === 'sqlite') return 'sqlite';
+ if (conn.dbType === 'docker') {
+ return conn.dockerType === 'postgresql' ? null : 'mysql';
+ }
+ return null;
+}
+
+// Keywords that may appear in a DEFAULT unquoted. Deliberately short: every
+// entry has to be valid in all three dialects, which is why CURRENT_DATE is
+// absent (MySQL needs it parenthesised).
+const DEFAULT_KEYWORDS = new Map([
+ ['NULL', 'NULL'],
+ ['TRUE', 'TRUE'],
+ ['FALSE', 'FALSE'],
+ ['CURRENT_TIMESTAMP', 'CURRENT_TIMESTAMP'],
+ ['NOW()', 'CURRENT_TIMESTAMP'],
+ ['NOW', 'CURRENT_TIMESTAMP'],
+]);
+
+export const DEFAULT_KEYWORD_LIST = ['NULL', 'TRUE', 'FALSE', 'CURRENT_TIMESTAMP'];
+
+// MySQL treats a backslash as an escape inside a string literal, so a trailing
+// backslash would otherwise consume the closing quote. PostgreSQL and SQLite
+// take backslashes literally, and doubling them there would change the value.
+function quoteLiteral(dialect, value) {
+ const escaped = dialect === 'mysql'
+ ? value.replace(/\\/g, '\\\\').replace(/'/g, "''")
+ : value.replace(/'/g, "''");
+ return `'${escaped}'`;
+}
+
+// Free text in, a literal out — never an expression. This is what keeps the
+// "Default" cell from being an SQL injection point.
+export function encodeDefault(dialect, raw) {
+ const v = String(raw ?? '').trim();
+ if (!v) return null;
+ const keyword = DEFAULT_KEYWORDS.get(v.toUpperCase());
+ if (keyword) return keyword;
+ if (/^-?\d+(\.\d+)?$/.test(v)) return v;
+ return quoteLiteral(dialect, v);
+}
+
+export function emptyColumn(dialect) {
+ return { name: '', type: SQL_DIALECTS[dialect]?.textType || 'TEXT', pk: false, notNull: false, def: '' };
+}
+
+// Starter rows, so the grid opens on something shaped like a real table rather
+// than on one blank line.
+export function starterColumns(dialect) {
+ const d = SQL_DIALECTS[dialect] || SQL_DIALECTS.sqlite;
+ return [
+ { name: 'id', type: d.keyType, pk: true, notNull: true, def: '' },
+ { name: '', type: d.textType, pk: false, notNull: true, def: '' },
+ { name: 'created_at', type: d.stampType, pk: false, notNull: true, def: 'CURRENT_TIMESTAMP' },
+ ];
+}
+
+// What each family calls its key, and the type that key usually has. Opening a
+// document store on `id: String` would be a small lie about how it works.
+const FAMILY_STARTERS = {
+ Document: { name: '_id', type: 'ObjectId' },
+ 'Time-series': { name: 'time', type: 'timestamp' },
+ Search: { name: 'id', type: 'string' },
+ Graph: { name: 'id', type: 'String' },
+ 'Key-value': { name: 'id', type: 'string' },
+};
+
+export function starterFields(family) {
+ const types = familyTypes(family);
+ const key = FAMILY_STARTERS[family] || { name: 'id', type: types[0] };
+ return [
+ { name: key.name, type: types.includes(key.type) ? key.type : types[0], pk: true, notNull: true, def: '' },
+ { name: '', type: types[0], pk: false, notNull: false, def: '' },
+ ];
+}
+
+// ─── validation ──────────────────────────────────────────────
+// One list of human sentences, in the order an operator would fix them.
+export function validate({ table, columns, unitOne = 'table' }) {
+ const issues = [];
+ const nameIssue = identError(table, `${unitOne.charAt(0).toUpperCase()}${unitOne.slice(1)} name`);
+ if (nameIssue) issues.push(nameIssue);
+
+ const named = columns.filter((c) => String(c.name || '').trim());
+ if (!named.length) issues.push('Add at least one column.');
+
+ named.forEach((c, i) => {
+ const issue = identError(c.name, `Column ${i + 1} ("${String(c.name).trim()}")`);
+ if (issue) issues.push(issue);
+ });
+
+ const seen = new Set();
+ named.forEach((c) => {
+ const key = String(c.name).trim().toLowerCase();
+ if (seen.has(key)) issues.push(`Column "${String(c.name).trim()}" is listed twice.`);
+ seen.add(key);
+ });
+
+ if (named.filter((c) => c.pk).length > 1) issues.push('Only one column can be the primary key.');
+
+ return issues;
+}
+
+// ─── CREATE TABLE ────────────────────────────────────────────
+export function buildCreateTable({ conn, dialect, table, columns }) {
+ const d = SQL_DIALECTS[dialect] || SQL_DIALECTS.sqlite;
+ const q = (ident) => quoteIdent(conn || { dbType: dialect }, ident);
+ const named = columns.filter((c) => String(c.name || '').trim());
+ const pk = named.find((c) => c.pk);
+ const name = String(table || '').trim();
+
+ let inlinePk = false;
+ const lines = named.map((col) => {
+ const isPk = col === pk;
+ const generated = isPk && d.integers.includes(col.type);
+
+ let type = col.type;
+ let tail = '';
+ if (generated) {
+ if (dialect === 'postgresql') {
+ type = col.type === 'BIGINT' ? 'BIGSERIAL' : 'SERIAL';
+ } else if (dialect === 'sqlite') {
+ type = 'INTEGER';
+ tail = ' PRIMARY KEY AUTOINCREMENT';
+ inlinePk = true;
+ } else {
+ tail = ' AUTO_INCREMENT';
+ }
+ }
+
+ // A generated key never carries a DEFAULT. PostgreSQL's serial types and
+ // SQLite's rowid alias are not-null by construction, so spelling it out
+ // there only adds noise; MySQL's AUTO_INCREMENT is spelled out because
+ // that is what its own dumps do.
+ const impliedNotNull = generated && (dialect === 'postgresql' || dialect === 'sqlite');
+ const notNull = !impliedNotNull && (col.notNull || isPk) ? ' NOT NULL' : '';
+ const def = generated ? null : encodeDefault(dialect, col.def);
+ const defaultSql = def ? ` DEFAULT ${def}` : '';
+
+ return ` ${q(String(col.name).trim())} ${type}${notNull}${defaultSql}${tail}`;
+ });
+
+ if (pk && !inlinePk) lines.push(` PRIMARY KEY (${q(String(pk.name).trim())})`);
+
+ return `CREATE TABLE ${q(name || 'new_table')} (\n${lines.join(',\n') || ' …'}\n);`;
+}
+
+// ─── non-SQL families ────────────────────────────────────────
+// The engines ServerKit can install but has no client bridge for. The shapes
+// come from each engine's own client, so the operator can copy a statement that
+// actually works rather than a SQL-flavoured guess.
+const FAMILY_TYPES = {
+ Document: ['String', 'Number', 'Boolean', 'Date', 'ObjectId', 'Array', 'Object'],
+ Search: ['string', 'number', 'boolean', 'string[]'],
+ 'Time-series': ['field', 'tag', 'timestamp'],
+ Graph: ['String', 'Integer', 'Float', 'Boolean', 'DateTime'],
+ 'Key-value': ['string', 'hash', 'list', 'set', 'zset'],
+};
+
+export function familyTypes(family) {
+ return FAMILY_TYPES[family] || SQL_DIALECTS.postgresql.types;
+}
+
+export function familyHasTypes(family) {
+ return Boolean(FAMILY_TYPES[family]);
+}
+
+const BSON_TYPES = {
+ String: 'string', Number: 'double', Boolean: 'bool', Date: 'date',
+ ObjectId: 'objectId', Array: 'array', Object: 'object',
+};
+
+// The word each family uses for "the thing you are creating" and for its key
+// column, so the grid's headers speak the engine's language.
+export function familyWording(family) {
+ switch (family) {
+ case 'Document': return { fields: 'Fields', key: 'Key', required: 'Required' };
+ case 'Search': return { fields: 'Attributes', key: 'Primary', required: 'Searchable' };
+ case 'Time-series': return { fields: 'Fields', key: 'Time', required: 'Required' };
+ case 'Graph': return { fields: 'Properties', key: 'Unique', required: 'Required' };
+ case 'Key-value': return { fields: 'Fields', key: 'Key', required: 'Required' };
+ default: return { fields: 'Columns', key: 'PK', required: 'Not null' };
+ }
+}
+
+// Generates the create statement in the engine's own client syntax. Copy-only:
+// nothing in ServerKit can execute these today, which the modal says out loud.
+export function buildFamilyStatement({ family, name, database, fields }) {
+ const nm = String(name || '').trim() || 'new_collection';
+ const db = String(database || '').trim() || '<database>';
+ const named = fields.filter((f) => String(f.name || '').trim());
+ const key = named.find((f) => f.pk);
+ const list = (fn, sep = ', ') => named.map(fn).join(sep);
+
+ switch (family) {
+ case 'Document': {
+ const required = named.filter((f) => f.notNull).map((f) => `"${String(f.name).trim()}"`).join(', ');
+ const props = list((f) => ` ${String(f.name).trim()}: { bsonType: "${BSON_TYPES[f.type] || 'string'}" }`, ',\n') || ' …';
+ const index = key ? `\ndb.${nm}.createIndex({ ${String(key.name).trim()}: 1 }, { unique: true })` : '';
+ return `use ${db}\ndb.createCollection("${nm}", {\n validator: { $jsonSchema: {\n required: [${required}],\n properties: {\n${props}\n }\n }}\n})${index}`;
+ }
+ case 'Search': {
+ const primary = key ? `, "primaryKey": "${String(key.name).trim()}"` : '';
+ const searchable = named.filter((f) => f.notNull).map((f) => `"${String(f.name).trim()}"`).join(', ')
+ || list((f) => `"${String(f.name).trim()}"`);
+ return `curl -X POST '/indexes' \\\n -H 'Authorization: Bearer <master-key>' \\\n -d '{ "uid": "${nm}"${primary} }'\n\ncurl -X PATCH '/indexes/${nm}/settings' \\\n -H 'Authorization: Bearer <master-key>' \\\n -d '{ "searchableAttributes": [${searchable}] }'`;
+ }
+ case 'Time-series': {
+ const tags = named.filter((f) => f.type === 'tag').map((f) => String(f.name).trim()).join(', ') || '—';
+ const values = named.filter((f) => f.type !== 'tag').map((f) => String(f.name).trim()).join(', ') || '—';
+ return `influx bucket create --name ${nm} --retention 90d\n\n# tags: ${tags}\n# fields: ${values}`;
+ }
+ case 'Graph': {
+ const unique = key ? String(key.name).trim() : 'id';
+ const props = list((f) => String(f.name).trim()) || '…';
+ return `CREATE CONSTRAINT ${nm}_key IF NOT EXISTS\n FOR (n:${nm}) REQUIRE n.${unique} IS UNIQUE;\n\n// properties: ${props}`;
+ }
+ case 'Key-value': {
+ const pairs = list((f) => `${String(f.name).trim()} "<${f.type}>"`, ' ') || '<field> "<value>"';
+ return `# Redis-compatible engines create a key on first write\nHSET ${nm}:1 ${pairs}`;
+ }
+ default: {
+ // A relational engine we can't reach — plain ANSI SQL, copy-only.
+ const cols = named.map((f) => ` "${String(f.name).trim()}" ${f.type}${f.notNull ? ' NOT NULL' : ''}`).join(',\n') || ' …';
+ const pk = key ? `,\n PRIMARY KEY ("${String(key.name).trim()}")` : '';
+ return `CREATE TABLE "${nm}" (\n${cols}${pk}\n);`;
+ }
+ }
+}
diff --git a/frontend/src/pages/Databases.jsx b/frontend/src/pages/Databases.jsx
index 6588ad72..b7a3dbf2 100644
--- a/frontend/src/pages/Databases.jsx
+++ b/frontend/src/pages/Databases.jsx
@@ -22,13 +22,15 @@ import ConfigTunerPanel from '../components/databases/ConfigTunerPanel';
import {
CreateDatabaseModal, CreateMySQLUserModal, CreatePostgreSQLUserModal,
} from '../components/databases/modals';
+import CreateTableModal from '../components/databases/CreateTableModal';
+import ImportDumpModal from '../components/databases/ImportDumpModal';
import EngineCatalogDrawer from '../components/databases/EngineCatalogDrawer';
import EngineInstallDrawer from '../components/databases/EngineInstallDrawer';
import {
EngineInstallingPanel, EngineReadyPanel, DatabaseEmptyPanel,
} from '../components/databases/DbBlankStates';
import {
- engineBrandKey, engineInstanceKey, engineTreeStatus, engineUnit,
+ engineBrandKey, engineInstanceKey, engineTreeStatus, engineUnit, singular,
} from '../components/databases/engineHelpers';
import { listTables, connKey, connLabel, quoteIdent, ENGINE_META } from '../components/databases/dbAdapter';
@@ -534,6 +536,27 @@ export default function Databases() {
}
}
+ // A table builder or a dump import changes what a database holds, but the
+ // node it happened to is not always the one that is selected — resolve it
+ // from the connection so the tree reloads the right branch.
+ const refreshConn = useCallback((conn) => {
+ if (!conn) return;
+ const key = connKey(conn);
+ childrenCache.forEach((kids) => {
+ if (!Array.isArray(kids)) return;
+ kids.forEach((n) => {
+ if (n.kind === 'database' && n.conn && connKey(n.conn) === key) refresh(n);
+ });
+ });
+ }, [childrenCache, refresh]);
+
+ // What a database node hands to the builder / importer so they open on the
+ // thing that was right-clicked instead of on the first database they find.
+ function dbPreset(node) {
+ if (node?.kind !== 'database' || !node.conn) return null;
+ return { conn: node.conn, engine: node.engine, label: node.label };
+ }
+
function copyName(node) {
navigator.clipboard?.writeText(node.label).then(
() => toast.success('Copied name'),
@@ -579,9 +602,15 @@ export default function Databases() {
return [{ label: 'Refresh', icon: RefreshCw, onClick: () => refresh(node) }];
case 'database': {
const actions = [
+ { label: `New ${singular(engineUnit(node))}`, icon: Plus, onClick: () => setModal({ type: 'new-table', preset: dbPreset(node) }) },
{ label: 'Open SQL console', icon: Terminal, onClick: () => openConsole(node.conn, node.engine) },
{ label: 'Refresh tables', icon: RefreshCw, onClick: () => refresh(node) },
];
+ // Only host MySQL / PostgreSQL have a restore route; a SQLite
+ // file or a containerised database has nothing to import into.
+ if (node.conn?.dbType === 'mysql' || node.conn?.dbType === 'postgresql') {
+ actions.splice(2, 0, { label: 'Import SQL dump…', icon: Download, onClick: () => setModal({ type: 'import', preset: dbPreset(node) }) });
+ }
if (node.engine === 'mysql' || node.engine === 'postgresql') {
// Processes live at the server/container level; the db node
// is just the natural place to reach them from.
@@ -696,6 +725,20 @@ export default function Databases() {
<Terminal size={14} aria-hidden="true" /> SQL console
{!newConsoleConn && <span className="dbx-menu-hint">select a database</span>}
</button>
+ <button
+ type="button"
+ role="menuitem"
+ onClick={() => { setModal({ type: 'new-table', preset: dbPreset(selectedNode) }); setShowNewMenu(false); }}
+ >
+ <Table2 size={14} aria-hidden="true" /> Table or collection
+ </button>
+ <button
+ type="button"
+ role="menuitem"
+ onClick={() => { setModal({ type: 'import', preset: dbPreset(selectedNode) }); setShowNewMenu(false); }}
+ >
+ <Download size={14} aria-hidden="true" /> Import SQL dump…
+ </button>
<div className="dbx-menu-sep" />
<button type="button" role="menuitem" disabled={engineState('mysql', status) !== 'active'} onClick={() => { setModal({ type: 'mysql-db' }); setShowNewMenu(false); }}>
<Database size={14} aria-hidden="true" /> MySQL database
@@ -846,6 +889,12 @@ export default function Databases() {
<DatabaseEmptyPanel
node={blank.node}
unit={engineUnit(blank.node)}
+ onNewTable={() => setModal({ type: 'new-table', preset: dbPreset(blank.node) })}
+ onImport={
+ blank.node.conn?.dbType === 'mysql' || blank.node.conn?.dbType === 'postgresql'
+ ? () => setModal({ type: 'import', preset: dbPreset(blank.node) })
+ : null
+ }
onOpenConsole={() => openConsole(blank.node.conn, blank.node.engine)}
/>
)}
@@ -958,6 +1007,23 @@ export default function Databases() {
)}
{modal?.type === 'mysql-user' && <CreateMySQLUserModal databases={modal.databases} onClose={() => setModal(null)} onCreated={onModalCreated} />}
{modal?.type === 'pg-user' && <CreatePostgreSQLUserModal databases={modal.databases} onClose={() => setModal(null)} onCreated={onModalCreated} />}
+ {modal?.type === 'new-table' && (
+ <CreateTableModal
+ preset={modal.preset}
+ engines={engineData.installed}
+ isAdmin={isAdmin}
+ onClose={() => setModal(null)}
+ onCreated={(target) => refreshConn(target?.conn)}
+ />
+ )}
+ {modal?.type === 'import' && (
+ <ImportDumpModal
+ preset={modal.preset}
+ isAdmin={isAdmin}
+ onClose={() => setModal(null)}
+ onImported={(target) => refreshConn({ dbType: target.engine, name: target.name })}
+ />
+ )}
{/* ─── Engine catalog + install ───────────────── */}
<EngineCatalogDrawer
diff --git a/frontend/src/styles/pages/_databases.scss b/frontend/src/styles/pages/_databases.scss
index 90e2525c..a9eeaa32 100644
--- a/frontend/src/styles/pages/_databases.scss
+++ b/frontend/src/styles/pages/_databases.scss
@@ -1757,6 +1757,394 @@ $dbx-sqlite: #3d8fd1;
.dbx-engine-card__hit:hover { transform: none; }
}
+// ============================================
+// TABLE BUILDER & DUMP IMPORT (portalled modals)
+//
+// Both live in a Radix portal, like the catalog above — top-level rules only.
+// ============================================
+
+// ─── Shared: select, notices, statement preview ───────────
+.dbx-select {
+ position: relative;
+ display: flex;
+ align-items: center;
+
+ select {
+ appearance: none;
+ width: 100%;
+ padding: 8px 30px 8px 11px;
+ background: $bg-elevated;
+ border: 1px solid $border-default;
+ border-radius: $radius-md;
+ color: $text-primary;
+ font-family: inherit;
+ font-size: $font-size-sm;
+ cursor: pointer;
+
+ &:focus {
+ outline: none;
+ border-color: $accent-primary;
+ box-shadow: 0 0 0 3px $accent-glow;
+ }
+ }
+
+ > svg {
+ position: absolute;
+ right: 10px;
+ color: $text-tertiary;
+ pointer-events: none;
+ }
+
+ &--sm {
+ select {
+ padding: 5px 22px 5px 8px;
+ font-family: $font-mono;
+ font-size: 11.5px;
+ }
+ > svg { right: 6px; }
+ }
+}
+
+// Compact variant of the shared .dbx-input, for the column grid's cells.
+.dbx-input--sm {
+ padding: 5px 8px;
+ input {
+ font-family: $font-mono;
+ font-size: 11.5px;
+ }
+}
+
+// One notice shape, five tones. Every one of them says something the operator
+// has to act on, so none of them are decorative.
+.dbx-notice {
+ display: flex;
+ align-items: flex-start;
+ gap: $space-2;
+ margin-bottom: $space-4;
+ padding: 11px 13px;
+ border: 1px solid $border-default;
+ border-radius: $radius-md;
+ background: $bg-elevated;
+ color: $text-secondary;
+ font-size: $font-size-sm;
+ line-height: 1.55;
+
+ > svg { flex-shrink: 0; margin-top: 2px; color: $text-tertiary; }
+ > div { min-width: 0; }
+
+ strong {
+ display: block;
+ color: $text-primary;
+ font-weight: $font-weight-semibold;
+ }
+
+ p { margin: 2px 0 0; }
+ .dbx-inline-link { margin-top: 6px; }
+
+ &--info {
+ background: $info-bg;
+ border-color: $info-border;
+ > svg { color: $info; }
+ }
+
+ &--warn {
+ background: $warning-bg;
+ border-color: $warning-border;
+ > svg { color: $warning; }
+ }
+
+ &--danger,
+ &--error {
+ background: $danger-bg;
+ border-color: $danger-border;
+ > svg { color: $danger; }
+ }
+
+ &--ok {
+ background: $success-bg;
+ border-color: $success-border;
+ > svg { color: $success; }
+ }
+
+ &__detail {
+ margin: 6px 0 0;
+ padding: 8px 10px;
+ max-height: 160px;
+ overflow: auto;
+ background: var(--bg-code);
+ border-radius: $radius-sm;
+ color: var(--text-code);
+ font-family: $font-mono;
+ font-size: 11.5px;
+ line-height: 1.5;
+ white-space: pre-wrap;
+ word-break: break-word;
+ }
+}
+
+// The statement, exactly as it will be sent. Terminal surface on purpose: this
+// is the safety story of the whole builder, so it must not read as prose.
+.dbx-sqlprev {
+ margin: 0;
+ padding: 11px 13px;
+ max-height: 220px;
+ overflow: auto;
+ background: var(--bg-code);
+ border: 1px solid $border-default;
+ border-radius: $radius-md;
+ color: var(--text-code);
+ font-family: $font-mono;
+ font-size: 11.5px;
+ line-height: 1.65;
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+
+// Blocking problems, listed in the order they would be fixed.
+.dbx-issues {
+ list-style: none;
+ margin: 0 0 $space-4;
+ padding: 0;
+
+ li {
+ display: flex;
+ align-items: flex-start;
+ gap: 7px;
+ padding: 3px 0;
+ color: $danger;
+ font-size: $font-size-xs;
+ line-height: 1.5;
+
+ svg { flex-shrink: 0; margin-top: 2px; }
+ }
+}
+
+// ─── Table builder ────────────────────────────────────────
+.dbx-builder {
+ // The modal body owns the bottom padding; a trailing field margin would
+ // double it.
+ > *:last-child { margin-bottom: 0; }
+
+ .dbx-field-row {
+ margin-bottom: $space-4;
+ .dbx-field { margin-bottom: 0; }
+ }
+
+ &__loading {
+ display: flex;
+ align-items: center;
+ gap: $space-2;
+ margin: 0;
+ padding: $space-6 0;
+ color: $text-tertiary;
+ font-size: $font-size-sm;
+ }
+
+ &__target {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ margin: -$space-2 0 $space-4;
+ color: $text-tertiary;
+ font-size: $font-size-xs;
+ line-height: 1.5;
+
+ code {
+ padding: 1px 5px;
+ border-radius: $radius-sm;
+ background: $bg-tertiary;
+ font-family: $font-mono;
+ color: $text-secondary;
+ }
+ }
+
+ &__target-ico {
+ display: inline-flex;
+ flex-shrink: 0;
+ color: $text-secondary;
+ }
+}
+
+.dbx-colgrid {
+ &__head,
+ &__row {
+ display: grid;
+ grid-template-columns: 1.4fr 1.3fr 34px 52px 1fr 26px;
+ gap: 7px;
+ align-items: center;
+ }
+
+ &__head {
+ padding: 0 2px 6px;
+ color: $text-tertiary;
+ font-family: $font-mono;
+ font-size: 10px;
+ letter-spacing: 0.05em;
+ text-transform: uppercase;
+ }
+
+ &__rows {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+
+ &__add {
+ margin-top: $space-2;
+ font-size: $font-size-xs;
+ }
+}
+
+// Checkbox drawn as a square button, so a whole column of them lines up with
+// the grid's other cells instead of inheriting the browser's checkbox metrics.
+.dbx-cbox {
+ display: grid;
+ place-items: center;
+ width: 22px;
+ height: 22px;
+ padding: 0;
+ background: transparent;
+ border: 1.5px solid $border-active;
+ border-radius: $radius-sm;
+ color: $white;
+ cursor: pointer;
+ transition: background $transition-fast, border-color $transition-fast;
+
+ &:hover { border-color: $accent-primary; }
+ &:focus-visible { outline: 2px solid $accent-primary; outline-offset: 2px; }
+ &.is-on { background: $accent-primary; border-color: $accent-primary; }
+}
+
+// ─── Dump import ──────────────────────────────────────────
+.dbx-import {
+ > *:last-child { margin-bottom: 0; }
+}
+
+.dbx-choice {
+ display: flex;
+ gap: 4px;
+ margin-bottom: $space-3;
+ padding: 3px;
+ background: $bg-tertiary;
+ border-radius: $radius-md;
+
+ &__btn {
+ flex: 1;
+ padding: 6px 10px;
+ background: transparent;
+ border: none;
+ border-radius: $radius-sm;
+ color: $text-secondary;
+ font-family: inherit;
+ font-size: $font-size-xs;
+ cursor: pointer;
+ transition: background $transition-fast, color $transition-fast;
+
+ &:hover { color: $text-primary; }
+ &:focus-visible { outline: 2px solid $accent-primary; outline-offset: -2px; }
+ &.is-on {
+ background: $bg-card;
+ color: $accent-primary;
+ box-shadow: $shadow-sm;
+ }
+ }
+}
+
+.dbx-dumps {
+ display: flex;
+ flex-direction: column;
+ max-height: 210px;
+ overflow-y: auto;
+ border: 1px solid $border-default;
+ border-radius: $radius-md;
+
+ &__empty {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ margin: 0;
+ padding: $space-4;
+ color: $text-tertiary;
+ font-size: $font-size-xs;
+ line-height: 1.5;
+
+ svg { flex-shrink: 0; }
+ }
+}
+
+.dbx-dump {
+ display: flex;
+ align-items: center;
+ gap: $space-3;
+ padding: 9px 12px;
+ background: transparent;
+ border: none;
+ border-top: 1px solid $border-subtle;
+ text-align: left;
+ cursor: pointer;
+ transition: background $transition-fast;
+
+ &:first-child { border-top: none; }
+ &:hover { background: $bg-hover; }
+ &:focus-visible { outline: 2px solid $accent-primary; outline-offset: -2px; }
+ &.is-on { background: $accent-glow; }
+
+ &__main { display: flex; flex-direction: column; gap: 2px; min-width: 0; flex: 1; }
+
+ &__name {
+ color: $text-primary;
+ font-family: $font-mono;
+ font-size: 11.5px;
+ @include dbx-trunc;
+ }
+
+ &__meta {
+ color: $text-tertiary;
+ font-size: 10.5px;
+ @include dbx-trunc;
+ }
+
+ &__tag {
+ flex-shrink: 0;
+ padding: 2px 8px;
+ border-radius: $radius-sm;
+ font-family: $font-mono;
+ font-size: 10px;
+ background: $bg-tertiary;
+ color: $text-tertiary;
+
+ &.is-mysql { background: fade($color-mysql, 16%); color: $color-mysql; }
+ &.is-postgresql { background: fade($color-postgresql, 20%); color: $color-postgresql-secondary; }
+ }
+}
+
+.dbx-check {
+ display: flex;
+ align-items: flex-start;
+ gap: 9px;
+ margin-bottom: $space-4;
+ padding: 11px 13px;
+ border: 1px solid $border-default;
+ border-radius: $radius-md;
+ cursor: pointer;
+
+ input { margin-top: 2px; flex-shrink: 0; accent-color: $accent-primary; }
+ > span { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
+
+ &__title { color: $text-primary; font-size: $font-size-sm; font-weight: $font-weight-medium; }
+ &__sub { color: $text-tertiary; font-size: $font-size-xs; line-height: 1.45; }
+}
+
+// A label may name an identifier the operator has to retype — give it the same
+// code treatment the hints get.
+.dbx-field__label code {
+ padding: 1px 5px;
+ border-radius: $radius-sm;
+ background: $bg-tertiary;
+ font-family: $font-mono;
+ color: $text-secondary;
+}
+
// ============================================
// MANAGED DATABASES (modal panel)
// ============================================