modified: frontend/src/components/SqlEditor.tsx

This commit is contained in:
GEgorov
2025-10-07 01:17:42 +03:00
parent 88e7d408f8
commit 634d220480

View File

@@ -13,6 +13,39 @@ interface SqlEditorProps {
height?: string; height?: string;
} }
// Cache for table names with 5-minute expiration
interface TableCache {
tables: string[];
timestamp: number;
}
const tablesCache = new Map<string, TableCache>();
const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes in milliseconds
const getCachedTables = async (databaseId: string): Promise<string[]> => {
const cached = tablesCache.get(databaseId);
const now = Date.now();
// Return cached data if it exists and is not expired
if (cached && (now - cached.timestamp) < CACHE_DURATION) {
return cached.tables;
}
// Fetch fresh data
try {
const { data } = await databasesApi.getTables(databaseId);
tablesCache.set(databaseId, {
tables: data.tables,
timestamp: now,
});
return data.tables;
} catch (error) {
console.error('Failed to fetch table names:', error);
// Return cached data if available, even if expired, as fallback
return cached?.tables || [];
}
};
export default function SqlEditor({ value, onChange, databaseId, height = '400px' }: SqlEditorProps) { export default function SqlEditor({ value, onChange, databaseId, height = '400px' }: SqlEditorProps) {
const editorRef = useRef<any>(null); const editorRef = useRef<any>(null);
const monacoRef = useRef<Monaco | null>(null); const monacoRef = useRef<Monaco | null>(null);
@@ -57,11 +90,10 @@ export default function SqlEditor({ value, onChange, databaseId, height = '400px
{ label: 'MIN', kind: monaco.languages.CompletionItemKind.Function, insertText: 'MIN()', range }, { label: 'MIN', kind: monaco.languages.CompletionItemKind.Function, insertText: 'MIN()', range },
]; ];
// Fetch table names from database if databaseId is provided // Fetch table names from database if databaseId is provided (with caching)
if (databaseId) { if (databaseId) {
try { const tables = await getCachedTables(databaseId);
const { data } = await databasesApi.getTables(databaseId); const tableSuggestions = tables.map(table => ({
const tableSuggestions = data.tables.map(table => ({
label: table, label: table,
kind: monaco.languages.CompletionItemKind.Class, kind: monaco.languages.CompletionItemKind.Class,
insertText: table, insertText: table,
@@ -69,9 +101,6 @@ export default function SqlEditor({ value, onChange, databaseId, height = '400px
range, range,
})); }));
suggestions = [...suggestions, ...tableSuggestions]; suggestions = [...suggestions, ...tableSuggestions];
} catch (error) {
console.error('Failed to fetch table names:', error);
}
} }
return { suggestions }; return { suggestions };