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
fix(databases): distinguish a connection failure from an empty database
Juan Denisa6f66b2976c2
diff --git a/backend/app/api/databases.py b/backend/app/api/databases.pyindex b795fdad..60ce2565 100644--- a/backend/app/api/databases.py+++ b/backend/app/api/databases.py@@ -686,8 +686,12 @@ def get_docker_database_tables(container, database):user = request.args.get('user', 'root')password = request.headers.get('X-DB-Password')- tables = DatabaseService.docker_mysql_get_tables(container, database, user, password)- return jsonify({'tables': tables}), 200+ result = DatabaseService.docker_mysql_get_tables(container, database, user, password)+ return jsonify({+ 'tables': result['tables'],+ 'connected': result['connected'],+ 'error': result['error'],+ }), 200@databases_bp.route('/docker/<container>/<database>/query', methods=['POST'])diff --git a/backend/app/services/database_service.py b/backend/app/services/database_service.pyindex 76819bb0..af45e828 100644--- a/backend/app/services/database_service.py+++ b/backend/app/services/database_service.py@@ -1249,7 +1249,13 @@ class DatabaseService:@staticmethoddef docker_mysql_get_tables(container_name, database, user='root', password=None):- """Get tables in a Docker MySQL database."""+ """List tables in a Docker MySQL database.++ Returns ``{'connected': bool, 'tables': [...], 'error': str|None}`` so+ callers can tell a genuinely empty database apart from a container/auth+ failure. Both used to collapse to ``[]`` and the explorer rendered+ "Empty" either way, silently hiding a broken connection.+ """result = DatabaseService.docker_mysql_execute(container_name,"SHOW TABLES;",@@ -1258,7 +1264,11 @@ class DatabaseService:password=password)if not result['success']:- return []+ return {+ 'connected': False,+ 'tables': [],+ 'error': result.get('error') or 'Could not connect to the database container',+ }tables = []for line in result['output'].strip().split('\n')[1:]:@@ -1283,7 +1293,7 @@ class DatabaseService:'name': table_name,'rows': rows})- return tables+ return {'connected': True, 'tables': tables, 'error': None}@staticmethoddef docker_mysql_execute_query(container_name, database, query, user='root', password=None,diff --git a/backend/tests/test_db_explorer_honesty.py b/backend/tests/test_db_explorer_honesty.pynew file mode 100644index 00000000..94e44bc5--- /dev/null+++ b/backend/tests/test_db_explorer_honesty.py@@ -0,0 +1,53 @@+"""Phase 0 proving tests.++The Database Explorer must tell a genuinely empty database apart from a+container/auth failure. Both used to collapse to an empty table list and render+"Empty", silently hiding a broken connection.+"""+++def test_docker_get_tables_reports_connection_failure(monkeypatch):+ from app.services.database_service import DatabaseService+ monkeypatch.setattr(DatabaseService, 'docker_mysql_execute',+ staticmethod(lambda *a, **k: {'success': False, 'error': 'No such container: ghost'}))+ res = DatabaseService.docker_mysql_get_tables('ghost', 'wordpress')+ assert res['connected'] is False+ assert res['tables'] == []+ assert 'ghost' in res['error']+++def test_docker_get_tables_empty_db_is_connected(monkeypatch):+ from app.services.database_service import DatabaseService+ monkeypatch.setattr(DatabaseService, 'docker_mysql_execute',+ staticmethod(lambda *a, **k: {'success': True, 'output': '', 'error': None}))+ res = DatabaseService.docker_mysql_get_tables('c', 'wordpress')+ # Connected but no tables — the case the UI now renders as "No tables yet".+ assert res['connected'] is True+ assert res['tables'] == []+++def test_docker_get_tables_lists_tables_with_counts(monkeypatch):+ from app.services.database_service import DatabaseService++ def fake_exec(container, query, database=None, user='root', password=None):+ if 'SHOW TABLES' in query:+ return {'success': True, 'output': 'Tables_in_wordpress\nwp_posts\nwp_options\n', 'error': None}+ return {'success': True, 'output': 'COUNT(*)\n7\n', 'error': None}++ monkeypatch.setattr(DatabaseService, 'docker_mysql_execute', staticmethod(fake_exec))+ res = DatabaseService.docker_mysql_get_tables('c', 'wordpress')+ assert res['connected'] is True+ assert [t['name'] for t in res['tables']] == ['wp_posts', 'wp_options']+ assert res['tables'][0]['rows'] == 7+++def test_docker_tables_api_surfaces_connection_state(app, client, auth_headers, monkeypatch):+ from app.services.database_service import DatabaseService+ monkeypatch.setattr(DatabaseService, 'docker_mysql_get_tables',+ staticmethod(lambda *a, **k: {'connected': False, 'tables': [], 'error': 'boom'}))+ r = client.get('/api/v1/databases/docker/ghost/wordpress/tables', headers=auth_headers)+ assert r.status_code == 200+ body = r.get_json()+ assert body['connected'] is False+ assert body['error'] == 'boom'+ assert body['tables'] == []diff --git a/frontend/src/components/databases/SourceTree.jsx b/frontend/src/components/databases/SourceTree.jsxindex fd358d13..9150f443 100644--- a/frontend/src/components/databases/SourceTree.jsx+++ b/frontend/src/components/databases/SourceTree.jsx@@ -22,7 +22,12 @@ function TreeRow({ node, depth, expanded, childrenCache, loading, activeKey, selconst isOpen = expanded.has(node.id);const isLoading = loading.has(node.id);const kids = childrenCache.get(node.id);- const hadError = kids === 'error';+ // Error cache entries are either the legacy 'error' sentinel or+ // `{ __error: message }` carrying a specific reason (e.g. a dead container).+ const errorMsg = kids === 'error'+ ? "Couldn't load. Right-click to retry."+ : (kids && !Array.isArray(kids) && kids.__error) || null;+ const hadError = errorMsg != null;const childNodes = Array.isArray(kids) ? kids : [];const visibleChildren = childNodes.filter((c) => c.expandable || matches(c, filter));@@ -102,11 +107,13 @@ function TreeRow({ node, depth, expanded, childrenCache, loading, activeKey, sel)}{hadError && (<li className="dbx-tree-leaf-msg is-error" style={{ paddingLeft: `${(depth + 1) * 14 + 22}px` }}>- Couldn't load. Right-click to retry.+ {errorMsg}</li>)}{!isLoading && !hadError && childNodes.length === 0 && (- <li className="dbx-tree-leaf-msg" style={{ paddingLeft: `${(depth + 1) * 14 + 22}px` }}>Empty</li>+ <li className="dbx-tree-leaf-msg" style={{ paddingLeft: `${(depth + 1) * 14 + 22}px` }}>+ {node.kind === 'database' ? 'No tables yet' : 'Empty'}+ </li>)}{visibleChildren.map((child) => (<TreeRowdiff --git a/frontend/src/pages/Databases.jsx b/frontend/src/pages/Databases.jsxindex df9f4e02..d2c3073e 100644--- a/frontend/src/pages/Databases.jsx+++ b/frontend/src/pages/Databases.jsx@@ -164,6 +164,16 @@ export default function Databases() {}if (node.kind === 'database') {const d = await listTables(node.conn);+ // A docker database reports `connected: false` when the container+ // exec/auth fails — surface that as an error row instead of letting+ // it masquerade as an empty database.+ if (d && d.connected === false) {+ const e = new Error(d.error || 'connection failed');+ e.userMessage = d.error+ ? `Couldn't connect: ${d.error}`+ : `Couldn't connect to ${connLabel(node.conn)}. Is the container running?`;+ throw e;+ }return (d.tables || []).map((t) => ({id: `${node.id}:t:${t.name}`, kind: 'table', engine: node.engine, label: t.name,expandable: false, conn: node.conn, table: t.name,@@ -180,7 +190,7 @@ export default function Databases() {setChildrenCache((c) => new Map(c).set(node.id, kids));} catch (err) {console.error('Failed to load tree node:', err);- setChildrenCache((c) => new Map(c).set(node.id, 'error'));+ setChildrenCache((c) => new Map(c).set(node.id, { __error: err.userMessage || "Couldn't load. Right-click to retry." }));} finally {setLoadingNodes((s) => { const n = new Set(s); n.delete(node.id); return n; });}