/** * @fileoverview Chahua Database Manager - Main Application Controller * @description คลาสหลักสำหรับจัดการอินเทอร์เฟซ database management application * คุณสมบัติ: Database connections, Query execution, Table management, Multi-language support * @author ทีมพัฒนา Chahua * @version 1.0.0 * @since 2024-01-01 * @calledBy renderer/index.html, UI components * @dependencies * - window.electronAPI: Electron IPC bridge * - database.js: Database operations module * - query-editor.js: SQL editor functionality * - ui.js: User interface utilities * @features * - Multi-database connection management * - SQL query editor with syntax highlighting * - Table data visualization and editing * - Plugin system for database templates * - Export functionality (JSON, CSV, SQL) * - Multi-language interface (Thai/English) * - Real-time query execution * @security * - Input validation for queries * - Connection parameter sanitization * - Safe DOM manipulation * @example * // Initialize application * const dbManager = new DatabaseManager(); * await dbManager.init(); */ // Main Application Controller /** * Database Manager - Main application class for database management interface * @class DatabaseManager * @description Handles database connections, query execution, table management, and user interface interactions * @features * - Connection management with persistence * - Real-time query execution and results * - Table data CRUD operations * - Plugin system integration * - Multi-language support * - Export capabilities */ class DatabaseManager { /** * Create a DatabaseManager instance * @constructor * @description Initializes the database manager with default settings and translation support * @features * - Default language setup (Thai) * - Connection state management * - Tab system initialization * - Translation dictionary setup */ constructor() { this.serverPort = null; this.currentConnection = null; this.connections = []; this.availablePlugins = []; // Database Templates System this.tabs = new Map(); this.activeTab = 'query'; this.language = 'th'; // Default to Thai this.primaryKeyByTable = new Map(); // Cache primary keys by table this.translations = { th: { // Connection related 'No connection selected': 'ยังไม่ได้เลือกการเชื่อมต่อ', 'No database connection available': 'ไม่มีการเชื่อมต่อฐานข้อมูล', 'Please select a database connection first': 'กรุณาเลือกการเชื่อมต่อฐานข้อมูลก่อน', 'Please connect to a database first': 'กรุณาเชื่อมต่อฐานข้อมูลก่อน', 'Connection successful': 'เชื่อมต่อสำเร็จ', 'Connection failed': 'การเชื่อมต่อล้มเหลว', 'Testing connection...': 'กำลังทดสอบการเชื่อมต่อ...', 'Connecting to': 'กำลังเชื่อมต่อไปยัง', 'Connected to': 'เชื่อมต่อแล้วไปยัง', 'Failed to connect': 'ไม่สามารถเชื่อมต่อได้', 'Saving connection...': 'กำลังบันทึกการเชื่อมต่อ...', 'Deleting connection...': 'กำลังลบการเชื่อมต่อ...', // Query related 'No Query': 'ไม่มีคำสั่ง SQL', 'Please enter a SQL query to execute': 'กรุณาใส่คำสั่ง SQL ที่ต้องการรัน', 'Executing query...': 'กำลังรันคำสั่ง SQL...', 'Query Executed': 'รันคำสั่ง SQL เสร็จแล้ว', 'Query completed in': 'รันคำสั่งเสร็จใน', 'Query execution failed': 'การรันคำสั่ง SQL ล้มเหลว', 'Query Error': 'ข้อผิดพลาดในคำสั่ง SQL', 'Execute a query to see results here': 'รันคำสั่ง SQL เพื่อดูผลลัพธ์ที่นี่', 'Query executed successfully': 'รันคำสั่ง SQL สำเร็จ', 'rows affected': 'แถวที่ได้รับผลกระทบ', // Export related 'Export Complete': 'ส่งออกเสร็จแล้ว', 'data exported to': 'ข้อมูลถูกส่งออกเป็น', 'SQL file': 'ไฟล์ SQL', 'No data available to export': 'ไม่มีข้อมูลให้ส่งออก', 'No Grid': 'ไม่มีตารางข้อมูล', 'No grid data to export': 'ไม่มีข้อมูลในตารางให้ส่งออก', 'No Data': 'ไม่มีข้อมูล', 'No data to export': 'ไม่มีข้อมูลให้ส่งออก', // Import related 'SQL Imported': 'นำเข้า SQL แล้ว', 'SQL file imported': 'นำเข้าไฟล์ SQL แล้ว', 'SQL file imported to tab': 'นำเข้าไฟล์ SQL ไปยังแท็บแล้ว', 'Import Error': 'ข้อผิดพลาดในการนำเข้า', 'Failed to import SQL file': 'ไม่สามารถนำเข้าไฟล์ SQL ได้', 'Failed to import SQL file to tab': 'ไม่สามารถนำเข้าไฟล์ SQL ไปยังแท็บได้', // UI Elements 'Tools': 'เครื่องมือ', 'SQL Query': 'คำสั่ง SQL', 'Tables': 'ตาราง', 'Execute': 'รัน', 'Cancel': 'ยกเลิก', 'Format': 'จัดรูปแบบ', 'Explain': 'อธิบาย', 'Commit': 'ยืนยัน', 'Rollback': 'ย้อนกลับ', 'Save': 'บันทึก', 'Load': 'โหลด', 'Clear': 'ล้าง', 'Import SQL File': 'นำเข้าไฟล์ SQL', 'Export SQL': 'ส่งออก SQL', 'rows': 'แถว', 'columns': 'คอลัมน์', // Context menu 'Copy': 'คัดลอก', 'Paste': 'วาง', 'Set NULL': 'กำหนดเป็น NULL', 'Edit': 'แก้ไข', 'Delete Row': 'ลบแถว', 'Copy Row': 'คัดลอกแถว', 'Insert Row': 'แทรกแถว', 'Duplicate Row': 'ทำสำเนาแถว', // Messages 'Success': 'สำเร็จ', 'Error': 'ข้อผิดพลาด', 'Warning': 'คำเตือน', 'Info': 'ข้อมูล', 'Copied': 'คัดลอกแล้ว', 'Cell value copied to clipboard': 'คัดลอกข้อมูลในเซลล์แล้ว', 'Loading database structure...': 'กำลังโหลดโครงสร้างฐานข้อมูล...', 'Structure Error': 'ข้อผิดพลาดในโครงสร้าง', 'No tables found': 'ไม่พบตาราง', 'Select a connection to view database structure': 'เลือกการเชื่อมต่อเพื่อดูโครงสร้างฐานข้อมูล', // Placeholder text 'Enter your SQL query here...': 'ใส่คำสั่ง SQL ที่นี่...' }, en: { // Keep original English text as fallback 'No connection selected': 'No connection selected', 'No database connection available': 'No database connection available', 'Please select a database connection first': 'Please select a database connection first' // ... and so on } }; } /** * Translate text based on current language setting * @param {string} key - Translation key to look up * @returns {string} Translated text or original key if translation not found * @description Returns translated text in current language or falls back to the key itself * @example * this.t('No connection selected') // Returns: 'ยังไม่ได้เลือกการเชื่อมต่อ' (in Thai) */ t(key) { return this.translations[this.language][key] || key; } /** * Get primary key for table (cached) * @param {string} tableName - Table name * @returns {string} Primary key column name */ getPrimaryKeyForTable(tableName) { return this.primaryKeyByTable.get(tableName) || 'id'; } /** * Set primary key for table * @param {string} tableName - Table name * @param {string} primaryKey - Primary key column name */ setPrimaryKeyForTable(tableName, primaryKey) { this.primaryKeyByTable.set(tableName, primaryKey); } /** * Normalize row data to ensure consistent ID types * @param {Object} row - Row data * @param {string} tableName - Table name * @returns {Object} Normalized row with string ID */ normalizeRowData(row, tableName) { if (!row) return row; const primaryKey = this.getPrimaryKeyForTable(tableName) || 'id'; return { ...row, [primaryKey]: String(row[primaryKey]) // Force string conversion }; } /** * Check if row exists in grid * @param {string} rowId - Row ID to check * @returns {boolean} True if row exists */ rowExistsInGrid(rowId) { if (!this.currentGridApi) return false; const node = this.currentGridApi.getRowNode(String(rowId)); return !!node; } /** * Initialize the application * @async * @returns {Promise} * @throws {Error} When initialization fails * @description Initializes server port, UI components, event listeners, and loads connections/plugins */ async init() { try { // Get server port from main process try { this.serverPort = await window.electronAPI.getServerPort(); console.log(' Database server running on port:', this.serverPort); } catch (error) { console.warn(' Failed to get server port from electronAPI, using default 3001:', error); this.serverPort = 3001; // Default fallback port } // Validate server port if (!this.serverPort) { console.warn(' Server port is null/undefined, using default 3001'); this.serverPort = 3001; } console.log(' Using server port:', this.serverPort); // Initialize UI components this.initializeEventListeners(); this.initializeMenuHandlers(); this.initializeResizableSplitter(); // Initialize license display this.initializeLicenseDisplay(); // Create default SQL Query tab this.openSQLQueryTab(); // Load saved connections await this.loadConnections(); // Load available plugins await this.loadAvailablePlugins(); // Set initial status this.updateStatus('disconnected', this.t('No connection selected')); console.log(' Application initialized successfully'); } catch (error) { console.error(' Failed to initialize application:', error); this.showToast('error', 'Initialization Error', error.message); } } /** * Initialize event listeners for UI interactions * @returns {void} * @description Sets up event handlers for buttons, keyboard shortcuts, modals, and user interactions */ initializeEventListeners() { // Connection management const newConnectionBtn = document.getElementById('newConnectionBtn'); if (newConnectionBtn) { newConnectionBtn.addEventListener('click', () => { console.log(' New Connection button clicked'); this.showConnectionModal(); }); } else { console.error(' New Connection button not found!'); } const connectionSelect = document.getElementById('connectionSelect'); if (connectionSelect) { connectionSelect.addEventListener('change', (e) => { const deleteBtn = document.getElementById('deleteConnectionBtn'); if (deleteBtn) { if (e.target.value) { this.selectConnection(e.target.value); deleteBtn.disabled = false; } else { deleteBtn.disabled = true; } } }); } // เพิ่ม Event Handler สำหรับปุ่มลบ Connection const deleteConnectionBtn = document.getElementById('deleteConnectionBtn'); if (deleteConnectionBtn) { deleteConnectionBtn.addEventListener('click', () => { this.deleteSelectedConnection(); }); } // Modal handlers const saveConnectionBtn = document.getElementById('saveConnectionBtn'); if (saveConnectionBtn) { saveConnectionBtn.addEventListener('click', () => { this.saveConnection(); }); } const testConnectionBtn = document.getElementById('testConnectionBtn'); if (testConnectionBtn) { testConnectionBtn.addEventListener('click', () => { this.testConnection(); }); } const cancelConnectionBtn = document.getElementById('cancelConnectionBtn'); if (cancelConnectionBtn) { cancelConnectionBtn.addEventListener('click', () => { this.hideConnectionModal(); }); } // Dialog close handlers (for native element) const connectionDialog = document.getElementById('connectionModal'); if (connectionDialog) { // Close button handler const modalClose = connectionDialog.querySelector('.modal-close'); if (modalClose) { modalClose.addEventListener('click', () => { this.hideConnectionModal(); }); } // Backdrop click handler (click outside dialog content) connectionDialog.addEventListener('click', (e) => { if (e.target === connectionDialog) { this.hideConnectionModal(); } }); // ESC key handler is built into native dialog connectionDialog.addEventListener('cancel', (e) => { e.preventDefault(); // Prevent default ESC behavior this.hideConnectionModal(); }); } else { console.warn(' Connection dialog not found'); } // Database type change handler const databaseType = document.getElementById('databaseType'); if (databaseType) { databaseType.addEventListener('change', (e) => { this.updateConnectionFormDefaults(e.target.value); }); } // Query execution const executeQueryBtn = document.getElementById('executeQueryBtn'); if (executeQueryBtn) { executeQueryBtn.addEventListener('click', () => { this.executeQuery(); }); } // Keyboard shortcuts document.addEventListener('keydown', (e) => { // Ctrl+Enter: Execute Query if (e.ctrlKey && e.key === 'Enter') { e.preventDefault(); this.executeQuery(); } // Ctrl+N: New Connection if (e.ctrlKey && e.key === 'n') { e.preventDefault(); this.showConnectionModal(); } // Ctrl+S: Save Query/Table Changes if (e.ctrlKey && e.key === 's') { e.preventDefault(); this.saveQuery(); // Also save table changes if there are any this.saveCurrentTableChanges(); } // Ctrl+O: Open/Load Query if (e.ctrlKey && e.key === 'o') { e.preventDefault(); this.loadQuery(); } // Ctrl+E: Export Results if (e.ctrlKey && e.key === 'e') { e.preventDefault(); this.exportResults(); } // F5: Refresh Structure/Table if (e.key === 'F5') { e.preventDefault(); if (this.currentConnection) { this.loadDatabaseStructure(this.currentConnection); } // Refresh current table if any this.refreshCurrentTable(); } // Ctrl+T: Test Connection if (e.ctrlKey && e.key === 't') { e.preventDefault(); if (document.getElementById('connectionModal').style.display !== 'none') { this.testConnection(); } } // Ctrl+W: Close Tab (if multiple tabs implemented) if (e.ctrlKey && e.key === 'w') { e.preventDefault(); // Close current tab logic (if implemented) console.log('Close tab shortcut pressed'); } // Escape: Close modals if (e.key === 'Escape') { this.closeModals(); } // Ctrl++: Zoom In if (e.ctrlKey && (e.key === '+' || e.key === '=')) { e.preventDefault(); this.zoomIn(); } // Ctrl+-: Zoom Out if (e.ctrlKey && e.key === '-') { e.preventDefault(); this.zoomOut(); } // Ctrl+0: Reset Zoom if (e.ctrlKey && e.key === '0') { e.preventDefault(); this.resetZoom(); } // F11: Toggle Fullscreen (let browser handle it) if (e.key === 'F11') { // Browser will handle fullscreen return; } // F2: Rename/Edit current row if (e.key === 'F2') { e.preventDefault(); this.editCurrentRow(); } // Delete: Delete current row if (e.key === 'Delete') { e.preventDefault(); this.deleteCurrentRow(); } // Ctrl+R: Refresh current table data if (e.ctrlKey && e.key === 'r') { e.preventDefault(); this.refreshCurrentTable(); } // Ctrl+A: Add new row if (e.ctrlKey && e.key === 'a') { e.preventDefault(); this.addNewRowToCurrentTable(); } // Ctrl+D: Duplicate current row if (e.ctrlKey && e.key === 'd') { e.preventDefault(); this.duplicateCurrentRow(); } // Ctrl+Z: Undo changes (if implemented) if (e.ctrlKey && e.key === 'z') { e.preventDefault(); this.undoTableChanges(); } }); // Refresh structure const refreshStructureBtn = document.getElementById('refreshStructureBtn'); if (refreshStructureBtn) { refreshStructureBtn.addEventListener('click', () => { if (this.currentConnection) { this.loadDatabaseStructure(this.currentConnection); } }); } // Other toolbar buttons const saveQueryBtn = document.getElementById('saveQueryBtn'); if (saveQueryBtn) { saveQueryBtn.addEventListener('click', () => { this.saveQuery(); }); } const loadQueryBtn = document.getElementById('loadQueryBtn'); if (loadQueryBtn) { loadQueryBtn.addEventListener('click', () => { this.loadQuery(); }); } const clearQueryBtn = document.getElementById('clearQueryBtn'); if (clearQueryBtn) { clearQueryBtn.addEventListener('click', () => { const queryTextarea = document.getElementById('queryTextarea'); if (queryTextarea) { queryTextarea.value = ''; } }); } const exportResultsBtn = document.getElementById('exportResultsBtn'); if (exportResultsBtn) { exportResultsBtn.addEventListener('click', () => { this.exportResults(); }); } } /** * Initialize resizable splitters and sidebar controls * @returns {void} * @description Sets up mouse event handlers for dragging splitters and sidebar collapse/expand */ initializeResizableSplitter() { // Initialize Vertical Splitter (between sidebar and content) this.initializeVerticalSplitter(); // Initialize Sidebar Collapse/Expand this.initializeSidebarControls(); // เช็คว่า horizontal splitter มีอยู่จริงหรือไม่ก่อน const splitter = document.getElementById('horizontalSplitter'); if (!splitter) { // ไม่แสดง error เพราะ splitter อาจยังไม่ได้ถูกสร้าง console.log('ℹ Horizontal splitter not found - will be initialized when SQL Query tab is created'); return; } console.log(' Initializing horizontal resizable splitter'); this.initializeHorizontalSplitter(splitter); } /** * Initialize vertical splitter between sidebar and content area * @returns {void} * @description Sets up mouse event handlers for dragging the vertical splitter to resize sidebar width * @example * this.initializeVerticalSplitter(); // Enables sidebar resizing functionality */ initializeVerticalSplitter() { const verticalSplitter = document.getElementById('verticalSplitter'); const sidebar = document.getElementById('sidebar'); const contentArea = document.getElementById('contentArea'); if (!verticalSplitter || !sidebar || !contentArea) { console.warn(' Vertical splitter elements not found'); return; } let isResizing = false; verticalSplitter.addEventListener('mousedown', (e) => { e.preventDefault(); isResizing = true; document.body.style.cursor = 'ew-resize'; document.body.style.userSelect = 'none'; const startX = e.clientX; const startWidth = sidebar.offsetWidth; const handleMouseMove = (e) => { if (!isResizing) return; const deltaX = e.clientX - startX; const newWidth = startWidth + deltaX; // Set min/max width for sidebar const minWidth = 200; const maxWidth = 600; if (newWidth >= minWidth && newWidth <= maxWidth) { sidebar.style.width = newWidth + 'px'; } }; const handleMouseUp = () => { isResizing = false; document.body.style.cursor = ''; document.body.style.userSelect = ''; document.removeEventListener('mousemove', handleMouseMove); document.removeEventListener('mouseup', handleMouseUp); }; document.addEventListener('mousemove', handleMouseMove); document.addEventListener('mouseup', handleMouseUp); }); console.log(' Vertical splitter initialized'); } /** * Initialize sidebar collapse/expand controls * @returns {void} * @description Sets up event handlers for sidebar collapse/expand buttons and manages sidebar visibility state * @example * this.initializeSidebarControls(); // Enables sidebar collapse/expand functionality * @see {@link toggleSidebar} For the toggle functionality implementation */ initializeSidebarControls() { const collapseSidebarBtn = document.getElementById('collapseSidebarBtn'); const showSidebarBtn = document.getElementById('showSidebarBtn'); const sidebar = document.getElementById('sidebar'); const verticalSplitter = document.getElementById('verticalSplitter'); if (!collapseSidebarBtn || !sidebar || !verticalSplitter) { console.warn(' Sidebar control elements not found'); return; } /** * Toggle sidebar expand/collapse state * @param {boolean} expand - True to expand sidebar, false to collapse * @returns {void} * @description Updates sidebar width, visibility, splitter display, and button icon/tooltip * @example * toggleSidebar(true); // Expands sidebar to default 300px width * toggleSidebar(false); // Collapses sidebar to 0px width and hides splitter */ const toggleSidebar = (expand) => { if (expand) { // Expand sidebar sidebar.classList.remove('collapsed'); sidebar.style.width = '300px'; // Default width verticalSplitter.style.display = 'block'; collapseSidebarBtn.title = 'Collapse Sidebar'; collapseSidebarBtn.innerHTML = ` `; } else { // Collapse sidebar sidebar.classList.add('collapsed'); sidebar.style.width = '0'; verticalSplitter.style.display = 'none'; collapseSidebarBtn.title = 'Expand Sidebar'; collapseSidebarBtn.innerHTML = ` `; } }; collapseSidebarBtn.addEventListener('click', () => { const isCollapsed = sidebar.classList.contains('collapsed'); toggleSidebar(isCollapsed); }); // Show sidebar button event (when collapsed) if (showSidebarBtn) { showSidebarBtn.addEventListener('click', () => { toggleSidebar(true); }); } console.log(' Sidebar controls initialized'); } /** * Initialize horizontal splitter for query/results panels * @param {HTMLElement} splitter - The horizontal splitter element * @returns {void} * @description Sets up mouse event handlers for dragging the horizontal splitter between query and results panels * @example * const splitter = document.getElementById('horizontalSplitter'); * this.initializeHorizontalSplitter(splitter); // Enables query/results panel resizing * @throws {Error} When required panel elements are not found in the DOM */ initializeHorizontalSplitter(splitter) { let isResizing = false; splitter.addEventListener('mousedown', (e) => { e.preventDefault(); isResizing = true; console.log(' Started resizing horizontal splitter'); // เพิ่ม visual feedback document.body.classList.add('resizing'); splitter.classList.add('resizing'); const container = splitter.closest('.vertical-split-container'); const resultsPanel = container.querySelector('.results-panel'); const queryPanel = container.querySelector('.query-panel'); if (!container || !resultsPanel || !queryPanel) { console.error(' Required panels not found'); return; } const containerHeight = container.offsetHeight; const startY = e.clientY; const startResultsHeight = resultsPanel.offsetHeight; const startQueryHeight = queryPanel.offsetHeight; console.log(` Container: ${containerHeight}px, Results: ${startResultsHeight}px, Query: ${startQueryHeight}px`); const handleMouseMove = (e) => { if (!isResizing) return; const deltaY = e.clientY - startY; const newResultsHeight = startResultsHeight + deltaY; const newQueryHeight = startQueryHeight - deltaY; // ป้องกันขนาดที่เล็กเกินไป const minPanelHeight = 150; const maxResultsHeight = containerHeight - minPanelHeight - 4; // -4 for splitter if (newResultsHeight >= minPanelHeight && newResultsHeight <= maxResultsHeight && newQueryHeight >= minPanelHeight) { resultsPanel.style.flex = `0 0 ${newResultsHeight}px`; queryPanel.style.flex = `0 0 ${newQueryHeight}px`; } }; const handleMouseUp = () => { if (!isResizing) return; isResizing = false; console.log(' Finished resizing horizontal splitter'); // ลบ visual feedback document.body.classList.remove('resizing'); splitter.classList.remove('resizing'); document.removeEventListener('mousemove', handleMouseMove); document.removeEventListener('mouseup', handleMouseUp); }; document.addEventListener('mousemove', handleMouseMove); document.addEventListener('mouseup', handleMouseUp); }); } /** * Initialize menu handlers for main process communication * @returns {void} * @description Sets up IPC handlers for menu actions from the main Electron process */ initializeMenuHandlers() { // Listen for menu actions from main process window.electronAPI.onMenuAction((event, action, data) => { switch (action) { case 'new-connection': this.showConnectionModal(); break; case 'import-sql': this.importSQLFile(data); break; case 'export-results': this.exportResults(); break; case 'test-connection': if (this.currentConnection) { this.testConnectionById(this.currentConnection); } break; case 'refresh-structure': if (this.currentConnection) { this.loadDatabaseStructure(this.currentConnection); } break; case 'execute-query': this.executeQuery(); break; } }); } /** * Load saved database connections from server * @async * @returns {Promise} * @description Fetches all saved connections from the server and updates the connection selector */ async loadConnections() { try { const response = await fetch(`http://localhost:${this.serverPort}/api/connections`); const data = await response.json(); if (data.success) { this.connections = data.connections; this.updateConnectionSelector(); } } catch (error) { console.error('Failed to load connections:', error); } } /** * Update the connection selector dropdown with available connections * @returns {void} * @description Populates the connection dropdown with loaded connections (excluding passwords) */ updateConnectionSelector() { const select = document.getElementById('connectionSelect'); select.innerHTML = ''; this.connections.forEach(conn => { const option = document.createElement('option'); option.value = conn.id; option.textContent = `${conn.name} (${conn.type})`; select.appendChild(option); }); } /** * Select and activate a database connection * @async * @param {string} connectionId - The ID of the connection to select * @returns {Promise} * @description Tests the connection and loads database structure if successful */ async selectConnection(connectionId) { const connection = this.connections.find(c => c.id === connectionId); if (!connection) return; this.currentConnection = connectionId; this.updateStatus('connecting', `Connecting to ${connection.name}...`); console.log(' Attempting connection with server port:', this.serverPort); console.log(' Connection URL:', `http://localhost:${this.serverPort}/api/connections/${connectionId}/test`); try { // Test connection first const testResponse = await fetch(`http://localhost:${this.serverPort}/api/connections/${connectionId}/test`, { method: 'POST' }); console.log(' Test response status:', testResponse.status); if (!testResponse.ok) { throw new Error(`HTTP ${testResponse.status}: ${testResponse.statusText}`); } const testData = await testResponse.json(); console.log(' Test response data:', testData); if (testData.success && testData.connectionTest.status === 'connected') { this.updateStatus('connected', `Connected to ${connection.name}`); await this.loadDatabaseStructure(connectionId); } else { this.updateStatus('error', `Failed to connect: ${testData.connectionTest.message}`); this.currentConnection = null; } } catch (error) { console.error(' Connection test failed:', error); console.error(' Server port used:', this.serverPort); this.updateStatus('error', `Connection failed: ${error.message}`); this.currentConnection = null; } } /** * Load available plugins from server * @async * @returns {Promise} * @description Fetches list of available plugins and stores them for use in the database tree */ async loadAvailablePlugins() { try { const response = await fetch(`http://localhost:${this.serverPort}/api/plugins`); const data = await response.json(); if (data.success) { this.availablePlugins = data.plugins; console.log(`Found ${this.availablePlugins.length} available plugins:`, this.availablePlugins.map(p => p.displayName).join(', ')); } else { console.warn('Could not load plugins:', data.error); this.availablePlugins = []; } } catch (error) { console.warn('Could not load plugins list:', error.message); this.availablePlugins = []; } } /** * Load database structure (tables, views) for the given connection * @async * @param {string} connectionId - The ID of the database connection * @returns {Promise} * @description Fetches database schema information and renders the database tree */ async loadDatabaseStructure(connectionId) { try { this.showLoading('Loading database structure...'); const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${connectionId}/structure`); const data = await response.json(); if (data.success) { this.renderDatabaseTree(data.structure); } else { throw new Error(data.error); } } catch (error) { console.error('Failed to load database structure:', error); this.showToast('error', 'Structure Error', error.message); } finally { this.hideLoading(); } } /** * Render the database tree with tools, plugins, and tables * @param {Object} structure - Database structure object * @param {string} structure.database - Database name * @param {Array} structure.tables - Array of table objects with name and rowCount * @param {Array} structure.views - Array of view objects * @returns {void} * @description Creates the interactive database tree UI with expandable sections */ renderDatabaseTree(structure) { const treeContainer = document.getElementById('databaseTree'); treeContainer.innerHTML = ''; // ===================== TOOLS SECTION ===================== const toolsSection = document.createElement('div'); toolsSection.className = 'tree-section tools-section'; const toolsHeader = document.createElement('div'); toolsHeader.className = 'tree-header section-header'; toolsHeader.innerHTML = `
Tools
`; toolsSection.appendChild(toolsHeader); const toolsContainer = document.createElement('div'); toolsContainer.className = 'section-content'; // SQL Query Item const sqlQueryItem = document.createElement('div'); sqlQueryItem.className = 'tree-item tool-item sql-query-item'; sqlQueryItem.innerHTML = ` ${this.t('SQL Query')} Editor `; sqlQueryItem.addEventListener('click', () => { this.openSQLQueryTab(); }); toolsContainer.appendChild(sqlQueryItem); // Export functionality moved to plugin actions // Removed to avoid duplication toolsSection.appendChild(toolsContainer); treeContainer.appendChild(toolsSection); // ===================== PLUGINS SECTION ===================== if (this.availablePlugins.length > 0) { const pluginsSection = document.createElement('div'); pluginsSection.className = 'tree-section plugins-section'; const pluginsHeader = document.createElement('div'); pluginsHeader.className = 'tree-header section-header'; pluginsHeader.innerHTML = `
Database Templates (${this.availablePlugins.length})
`; const pluginsContainer = document.createElement('div'); pluginsContainer.className = 'section-content'; this.availablePlugins.forEach(plugin => { const pluginItem = document.createElement('div'); pluginItem.className = 'tree-item plugin-item'; // เช็คว่าเป็น plugin ที่รองรับ drag & drop หรือไม่ const supportsDragDrop = plugin.ui && plugin.ui.allowDragDrop; const supportsDirectRun = plugin.ui && plugin.ui.allowDirectRun; const supportsSQLDump = plugin.ui && plugin.ui.allowSQLDump; pluginItem.innerHTML = `
${plugin.displayName} ${plugin.version}
${plugin.author}
${supportsSQLDump ? ` ` : ''} ${supportsDragDrop ? `
Drop database files here
` : ''}
`; // เพิ่ม event listeners สำหรับปุ่ม Setup const setupBtn = pluginItem.querySelector('.setup-btn'); if (setupBtn) { setupBtn.addEventListener('click', (e) => { e.stopPropagation(); console.log(' Setup button clicked for:', plugin.displayName); this.runPluginSetup(plugin); }); } // เพิ่ม event listeners สำหรับปุ่ม SQL Dump const dumpBtn = pluginItem.querySelector('.dump-btn'); if (dumpBtn && supportsSQLDump) { dumpBtn.addEventListener('click', (e) => { e.stopPropagation(); console.log(' Dump button clicked for:', plugin.displayName); this.runPluginSQLDump(plugin); }); } // เพิ่ม drag & drop functionality ถ้า plugin รองรับ if (supportsDragDrop) { this.setupPluginDragDrop(pluginItem, plugin); } pluginsContainer.appendChild(pluginItem); }); pluginsSection.appendChild(pluginsHeader); pluginsSection.appendChild(pluginsContainer); treeContainer.appendChild(pluginsSection); } // ===================== TABLES SECTION ===================== // ตรวจสอบว่ามีตารางหรือไม่ if (!structure.tables || structure.tables.length === 0) { const noTablesSection = document.createElement('div'); noTablesSection.className = 'tree-section tables-section empty'; noTablesSection.innerHTML = `
Tables (0)

No tables found

`; treeContainer.appendChild(noTablesSection); return; } // Create tables section const tablesSection = document.createElement('div'); tablesSection.className = 'tree-section tables-section'; const tablesHeader = document.createElement('div'); tablesHeader.className = 'tree-header section-header'; tablesHeader.innerHTML = `
Tables (${structure.tables.length})
`; const tablesContainer = document.createElement('div'); tablesContainer.className = 'section-content'; structure.tables.forEach(table => { const tableItem = document.createElement('div'); tableItem.className = 'tree-item table-item'; tableItem.innerHTML = `
${table.name} ${table.rowCount || 0} rows
`; // Left click to open table tableItem.addEventListener('click', () => { this.openTableTab(table.name); }); // Right click context menu (DBeaver style) tableItem.addEventListener('contextmenu', (e) => { e.preventDefault(); this.showTableContextMenu(e, table); }); tablesContainer.appendChild(tableItem); }); tablesSection.appendChild(tablesHeader); tablesSection.appendChild(tablesContainer); treeContainer.appendChild(tablesSection); // ลบ Views section ออกทั้งหมด - ไม่ต้องมีแล้ว } /** * Show context menu for table items in database tree * @param {MouseEvent} event - The right-click mouse event * @param {Object} table - Table object with name and metadata * @param {string} table.name - Name of the table * @param {number} [table.rowCount] - Number of rows in the table * @returns {void} * @description Displays a context menu with table operations like open data, edit structure, etc. */ showTableContextMenu(event, table) { // Remove existing context menu const existingMenu = document.querySelector('.table-context-menu'); if (existingMenu) { existingMenu.remove(); } const menu = document.createElement('div'); menu.className = 'context-menu table-context-menu'; menu.innerHTML = `
เปิดข้อมูล
ดูโครงสร้าง
เพิ่มแถวใหม่ Ctrl+A
แก้ไขแถวแรก F2
ลบแถวที่เลือก Del
สร้าง SELECT
สร้าง INSERT
สร้าง UPDATE
สร้าง DELETE
ส่งออกข้อมูล Ctrl+E
นำเข้าข้อมูล
บันทึกการเปลี่ยนแปลง Ctrl+S
ยกเลิกการเปลี่ยนแปลง Ctrl+Z
คัดลอกชื่อตาราง
รีเฟรช F5
`; // Position menu menu.style.position = 'fixed'; menu.style.left = event.pageX + 'px'; menu.style.top = event.pageY + 'px'; menu.style.zIndex = '10000'; document.body.appendChild(menu); // Handle menu actions menu.addEventListener('click', (e) => { const action = e.target.closest('.context-menu-item')?.getAttribute('data-action'); if (action) { this.handleTableContextAction(action, table); menu.remove(); } }); // Close menu when clicking outside setTimeout(() => { document.addEventListener('click', () => { if (document.body.contains(menu)) { menu.remove(); } }, { once: true }); }, 100); // Prevent menu from going outside viewport const rect = menu.getBoundingClientRect(); const viewportWidth = window.innerWidth; const viewportHeight = window.innerHeight; if (rect.right > viewportWidth) { menu.style.left = (event.pageX - rect.width) + 'px'; } if (rect.bottom > viewportHeight) { menu.style.top = (event.pageY - rect.height) + 'px'; } } /** * Handle context menu actions for tables * @param {string} action - The action to perform (e.g., 'openData', 'generateSelect') * @param {Object} table - Table object with name and metadata * @returns {void} * @description Executes the selected action from the table context menu */ handleTableContextAction(action, table) { switch (action) { case 'openData': this.openTableTab(table.name); break; case 'openStructure': this.openTableStructureTab(table.name); break; case 'addRow': this.showAddRowForm(table.name); break; case 'editFirstRow': this.editCurrentRow(); break; case 'deleteRows': this.deleteCurrentRow(); break; case 'generateSelect': this.generateSQLQuery('SELECT', table.name); break; case 'generateInsert': this.generateSQLQuery('INSERT', table.name); break; case 'generateUpdate': this.generateSQLQuery('UPDATE', table.name); break; case 'generateDelete': this.generateSQLQuery('DELETE', table.name); break; case 'exportData': this.exportTableData(null, table.name); break; case 'importData': this.importDataToTable(table.name); break; case 'saveChanges': this.saveCurrentTableChanges(); break; case 'undoChanges': this.undoTableChanges(); break; case 'copyTableName': navigator.clipboard.writeText(table.name); this.showToast('success', this.t('Copied'), `คัดลอกชื่อตาราง: ${table.name}`); break; case 'refreshTable': this.refreshTableData(table.name); break; } } /** * Generate SQL query template for a table * @async * @param {'SELECT'|'INSERT'|'UPDATE'|'DELETE'} type - Type of SQL query to generate * @param {string} tableName - Name of the table * @returns {Promise} * @description Creates SQL query templates and inserts them into the SQL Query tab * @example * await this.generateSQLQuery('SELECT', 'users') // Generates: SELECT * FROM users LIMIT 1000; */ async generateSQLQuery(type, tableName) { let query = ''; const dbType = this.getCurrentDatabaseType(); const formattedTableName = this.formatSQLIdentifier(tableName, dbType); try { // First, get table structure to generate proper column names const columnInfo = await this.getTableColumns(tableName); const columns = columnInfo.map(col => col.name); switch (type) { case 'SELECT': query = `-- ดึงข้อมูลจากตาราง ${tableName}\nSELECT * FROM ${formattedTableName}\nLIMIT 1000;`; break; case 'INSERT': const insertColumns = columns.slice(0, Math.min(5, columns.length)); // Max 5 columns for example const formattedInsertCols = insertColumns.map(col => this.formatSQLIdentifier(col, dbType)); const placeholderValues = insertColumns.map(() => "'value'"); query = `-- เพิ่มข้อมูลใหม่ลงในตาราง ${tableName}\nINSERT INTO ${formattedTableName} (\n ${formattedInsertCols.join(',\n ')}\n) VALUES (\n ${placeholderValues.join(',\n ')}\n);`; break; case 'UPDATE': const updateColumns = columns.slice(0, Math.min(3, columns.length - 1)); // Exclude first column (usually ID) const updateSetClause = updateColumns.map(col => `${this.formatSQLIdentifier(col, dbType)} = 'new_value'` ).join(',\n '); query = `-- อัปเดตข้อมูลในตาราง ${tableName}\nUPDATE ${formattedTableName}\nSET \n ${updateSetClause}\nWHERE \n -- ใส่เงื่อนไขที่นี่\n ${this.formatSQLIdentifier(columns[0] || 'id', dbType)} = 1;`; break; case 'DELETE': const primaryColumn = columns[0] || 'id'; query = `-- ลบข้อมูลจากตาราง ${tableName}\nDELETE FROM ${formattedTableName}\nWHERE \n -- ใส่เงื่อนไขที่นี่ (ระวัง: อย่าลืมใส่ WHERE ไม่งั้นข้อมูลจะหายหมด!)\n ${this.formatSQLIdentifier(primaryColumn, dbType)} = 1;`; break; } } catch (error) { console.warn('Could not get table columns, using generic query:', error); // Fallback to generic queries if column info is not available switch (type) { case 'SELECT': query = `-- ดึงข้อมูลจากตาราง ${tableName}\nSELECT * FROM ${formattedTableName}\nLIMIT 1000;`; break; case 'INSERT': query = `-- เพิ่มข้อมูลใหม่ลงในตาราง ${tableName}\n-- กรุณาแก้ไขชื่อคอลัมน์และค่าให้ถูกต้อง\nINSERT INTO ${formattedTableName} (\n column1, column2, column3\n) VALUES (\n 'value1', 'value2', 'value3'\n);`; break; case 'UPDATE': query = `-- อัปเดตข้อมูลในตาราง ${tableName}\n-- กรุณาแก้ไขชื่อคอลัมน์และเงื่อนไขให้ถูกต้อง\nUPDATE ${formattedTableName}\nSET \n column1 = 'new_value1',\n column2 = 'new_value2'\nWHERE \n id = 1;`; break; case 'DELETE': query = `-- ลบข้อมูลจากตาราง ${tableName}\n-- กรุณาแก้ไขเงื่อนไขให้ถูกต้อง\nDELETE FROM ${formattedTableName}\nWHERE \n id = 1;`; break; } } // Open SQL Query tab and insert the generated query this.openSQLQueryTab(); setTimeout(() => { const textarea = document.getElementById('queryTextarea_sql_query'); if (textarea) { // If there's existing content, add new query below if (textarea.value.trim()) { textarea.value += '\n\n' + query; } else { textarea.value = query; } textarea.focus(); // Move cursor to the end textarea.setSelectionRange(textarea.value.length, textarea.value.length); } }, 200); } /** * Get table columns information by querying database directly * @param {string} tableName - Name of the table to get columns for * @returns {Promise} Promise that resolves to array of column objects * @throws {Error} When no database connection or unsupported database type * @async */ async getTableColumns(tableName) { if (!this.currentConnection) { throw new Error('No database connection'); } try { const dbType = this.getCurrentDatabaseType(); let query = ''; switch (dbType) { case 'postgresql': query = ` SELECT column_name as name, data_type as type, is_nullable as nullable FROM information_schema.columns WHERE table_name = '${tableName}' ORDER BY ordinal_position; `; break; case 'mysql': case 'mariadb': query = ` SELECT COLUMN_NAME as name, DATA_TYPE as type, IS_NULLABLE as nullable FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '${tableName}' AND TABLE_SCHEMA = DATABASE() ORDER BY ORDINAL_POSITION; `; break; default: throw new Error('Database type not supported for column info'); } const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/query`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query }) }); const data = await response.json(); if (data.success && data.data && data.data.rows) { return data.data.rows; } else { throw new Error('Failed to get column information'); } } catch (error) { console.error('Error getting table columns:', error); throw error; } } /** * Show connection modal for creating new or editing existing connection * @param {Object|null} connection - Connection object to edit, or null for new connection * @param {string} connection.name - Connection name * @param {string} connection.type - Database type * @param {string} connection.host - Database hostname * @param {number} connection.port - Database port * @param {string} connection.database - Database name * @param {string} connection.username - Database username */ showConnectionModal(connection = null) { console.log(' showConnectionModal called with:', connection); try { const dialog = document.getElementById('connectionModal'); const form = document.getElementById('connectionForm'); console.log(' Dialog element:', dialog); console.log(' Form element:', form); if (!dialog) { console.error(' Dialog element not found!'); this.showToast('error', 'Error', 'Connection dialog not found in DOM'); return; } if (!form) { console.error(' Form element not found!'); this.showToast('error', 'Error', 'Connection form not found in DOM'); return; } if (connection) { // Edit mode console.log(' Edit mode - populating form with connection data'); document.getElementById('connectionName').value = connection.name; document.getElementById('databaseType').value = connection.type; document.getElementById('hostname').value = connection.host; document.getElementById('port').value = connection.port; document.getElementById('database').value = connection.database; document.getElementById('username').value = connection.username; document.getElementById('password').value = ''; } else { // New connection mode console.log(' New connection mode - resetting form'); form.reset(); this.updateConnectionFormDefaults('postgresql'); // Default to PostgreSQL } // Close any open context menus or loading overlays first document.querySelectorAll('.context-menu.active') .forEach(el => el.classList.remove('active')); const loadingOverlay = document.getElementById('loadingOverlay'); if (loadingOverlay && loadingOverlay.classList.contains('active')) { loadingOverlay.classList.remove('active'); } console.log(' Opening dialog with showModal()'); dialog.showModal(); document.body.classList.add('dialog-open'); // Focus first input for better UX const firstInput = dialog.querySelector('input[type="text"]'); if (firstInput) { firstInput.focus(); } console.log(' Dialog opened successfully'); } catch (error) { console.error(' Error in showConnectionModal:', error); this.showToast('error', 'Error', `Failed to show connection modal: ${error.message}`); } } /** * Hide the connection modal dialog */ hideConnectionModal() { console.log(' hideConnectionModal called'); try { const dialog = document.getElementById('connectionModal'); if (dialog && dialog.open) { dialog.close(); document.body.classList.remove('dialog-open'); console.log(' Dialog closed successfully'); // Clear form data const form = document.getElementById('connectionForm'); if (form) { form.reset(); console.log(' Form reset'); } } else { console.log(' Dialog was not open or not found'); } } catch (error) { console.error(' Error in hideConnectionModal:', error); } } /** * Close all open modals and hide loading overlay */ closeModals() { // Close all open modals this.hideConnectionModal(); // Hide loading overlay if active const loadingOverlay = document.getElementById('loadingOverlay'); if (loadingOverlay.classList.contains('active')) { loadingOverlay.classList.remove('active'); } } /** * Increase zoom level of the application (maximum 200%) */ zoomIn() { const currentZoom = parseFloat(document.body.style.zoom) || 1; const newZoom = Math.min(currentZoom + 0.1, 2.0); // Max 200% document.body.style.zoom = newZoom; this.showToast('info', 'Zoom', `Zoom: ${Math.round(newZoom * 100)}%`); } /** * Decrease zoom level of the application (minimum 50%) */ zoomOut() { const currentZoom = parseFloat(document.body.style.zoom) || 1; const newZoom = Math.max(currentZoom - 0.1, 0.5); // Min 50% document.body.style.zoom = newZoom; this.showToast('info', 'Zoom', `Zoom: ${Math.round(newZoom * 100)}%`); } /** * Reset zoom level to 100% */ resetZoom() { document.body.style.zoom = 1; this.showToast('info', 'Zoom', 'Zoom reset to 100%'); } /** * Enable inline editing for a table cell * @param {HTMLElement} cell - The table cell element to edit */ editCell(cell) { if (cell.classList.contains('editing')) return; const originalValue = cell.textContent; const isNull = cell.classList.contains('null-value'); cell.classList.add('editing'); const input = document.createElement('input'); input.type = 'text'; input.value = isNull ? '' : originalValue; cell.innerHTML = ''; cell.appendChild(input); input.focus(); input.select(); const saveEdit = () => { const newValue = input.value; cell.classList.remove('editing'); if (newValue === '') { cell.classList.add('null-value'); cell.textContent = 'NULL'; } else { cell.classList.remove('null-value'); cell.textContent = newValue; } // Mark as modified if value changed const originalVal = cell.getAttribute('data-original-value'); if (newValue !== originalVal) { cell.classList.add('modified'); this.markTableAsModified(cell.closest('table')); } }; const cancelEdit = () => { cell.classList.remove('editing'); if (isNull) { cell.classList.add('null-value'); cell.textContent = 'NULL'; } else { cell.textContent = originalValue; } }; input.addEventListener('blur', saveEdit); input.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); saveEdit(); } else if (e.key === 'Escape') { e.preventDefault(); cancelEdit(); } }); } /** * Sort table rows by specified column * @param {HTMLElement} table - The table element to sort * @param {number} columnIndex - Zero-based index of column to sort by */ sortTable(table, columnIndex) { const tbody = table.querySelector('tbody'); const rows = Array.from(tbody.querySelectorAll('tr')); const header = table.querySelector(`th:nth-child(${columnIndex + 1})`); // Determine sort direction let sortDirection = 'asc'; if (header.classList.contains('sort-asc')) { sortDirection = 'desc'; } // Clear all sort classes table.querySelectorAll('th').forEach(th => { th.classList.remove('sort-asc', 'sort-desc'); }); // Add sort class to current header header.classList.add(`sort-${sortDirection}`); // Sort rows rows.sort((a, b) => { const aValue = a.querySelector(`td:nth-child(${columnIndex + 1})`).textContent; const bValue = b.querySelector(`td:nth-child(${columnIndex + 1})`).textContent; // Handle NULL values if (aValue === 'NULL' && bValue === 'NULL') return 0; if (aValue === 'NULL') return sortDirection === 'asc' ? 1 : -1; if (bValue === 'NULL') return sortDirection === 'asc' ? -1 : 1; // Try numeric comparison first const aNum = parseFloat(aValue); const bNum = parseFloat(bValue); if (!isNaN(aNum) && !isNaN(bNum)) { return sortDirection === 'asc' ? aNum - bNum : bNum - aNum; } // String comparison const result = aValue.localeCompare(bValue); return sortDirection === 'asc' ? result : -result; }); // Re-append sorted rows rows.forEach(row => tbody.appendChild(row)); // Update row numbers this.updateRowNumbers(table); } /** * Update row numbers in table after sorting or filtering * @param {HTMLElement} table - The table element to update row numbers for */ updateRowNumbers(table) { const rows = table.querySelectorAll('tbody tr'); rows.forEach((row, index) => { const rowNumCell = row.querySelector('.row-number'); if (rowNumCell) { rowNumCell.textContent = index + 1; } }); } /** * Mark table as having pending changes and update UI indicators * @param {HTMLElement} table - The table element that has been modified */ markTableAsModified(table) { const saveBtn = document.getElementById('saveChangesBtn'); const changesStatus = document.getElementById('changesStatus'); if (saveBtn) { saveBtn.disabled = false; saveBtn.textContent = 'Save Changes'; } if (changesStatus) { const modifiedCells = table.querySelectorAll('td.modified').length; changesStatus.textContent = `${modifiedCells} changes`; changesStatus.style.color = 'var(--warning-color)'; } } /** * Attach event listeners to table control buttons * @param {HTMLElement} table - The table element to attach listeners for */ attachTableEventListeners(table) { // Filter functionality const filterInput = document.getElementById('tableFilter'); if (filterInput) { filterInput.addEventListener('input', (e) => { this.filterTable(table, e.target.value); }); } // Clear filter const clearFilterBtn = document.getElementById('clearFilter'); if (clearFilterBtn) { clearFilterBtn.addEventListener('click', () => { filterInput.value = ''; this.filterTable(table, ''); }); } // Add row const addRowBtn = document.getElementById('addRowBtn'); if (addRowBtn) { addRowBtn.addEventListener('click', () => { this.addNewRow(table); }); } // Save changes const saveChangesBtn = document.getElementById('saveChangesBtn'); if (saveChangesBtn) { saveChangesBtn.addEventListener('click', () => { this.saveTableChanges(table); }); } // Refresh table const refreshBtn = document.getElementById('refreshTableBtn'); if (refreshBtn) { refreshBtn.addEventListener('click', () => { this.executeQuery(); // Re-run the query }); } // Export table const exportBtn = document.getElementById('exportTableBtn'); if (exportBtn) { exportBtn.addEventListener('click', () => { this.exportTableData(table); }); } } /** * Filter table rows based on search text * @param {HTMLElement} table - The table element to filter * @param {string} filterValue - The text to filter by */ filterTable(table, filterValue) { const rows = table.querySelectorAll('tbody tr'); const filter = filterValue.toLowerCase(); rows.forEach(row => { const cells = row.querySelectorAll('td:not(.row-number)'); const rowText = Array.from(cells).map(cell => cell.textContent.toLowerCase()).join(' '); if (rowText.includes(filter)) { row.style.display = ''; } else { row.style.display = 'none'; } }); this.updateRowNumbers(table); } /** * Add a new empty row to the table * @param {HTMLElement} table - The table element to add a row to */ addNewRow(table) { const tbody = table.querySelector('tbody'); const headerRow = table.querySelector('thead tr'); const columnCount = headerRow.children.length - 1; // Exclude row number column const newRow = document.createElement('tr'); newRow.classList.add('new-row'); // Row number cell const rowNumCell = document.createElement('td'); rowNumCell.className = 'row-number'; rowNumCell.textContent = tbody.children.length + 1; newRow.appendChild(rowNumCell); // Data cells for (let i = 0; i < columnCount; i++) { const td = document.createElement('td'); td.classList.add('null-value', 'new-row'); td.textContent = 'NULL'; td.setAttribute('data-original-value', null); td.setAttribute('data-column', i); td.addEventListener('dblclick', () => this.editCell(td)); td.addEventListener('contextmenu', (e) => this.showCellContextMenu(e, td)); newRow.appendChild(td); } tbody.appendChild(newRow); this.markTableAsModified(table); // Focus first cell of new row const firstCell = newRow.querySelector('td:nth-child(2)'); if (firstCell) { this.editCell(firstCell); } } /** * Show context menu for table cell * @param {Event} event - The right-click event * @param {HTMLElement} cell - The table cell that was right-clicked */ showCellContextMenu(event, cell) { event.preventDefault(); // Remove existing context menu const existingMenu = document.querySelector('.context-menu'); if (existingMenu) { existingMenu.remove(); } const menu = document.createElement('div'); menu.className = 'context-menu'; menu.innerHTML = `
Copy
Paste
∅ Set NULL
Edit
Delete Row
`; menu.style.left = event.pageX + 'px'; menu.style.top = event.pageY + 'px'; document.body.appendChild(menu); // Handle menu actions menu.addEventListener('click', (e) => { const action = e.target.getAttribute('data-action'); if (action) { this.handleCellContextAction(action, cell); menu.remove(); } }); // Close menu when clicking outside setTimeout(() => { document.addEventListener('click', () => { menu.remove(); }, { once: true }); }, 100); } /** * Handle cell context menu actions * @param {string} action - The action to perform (copy, paste, setNull, edit, deleteRow) * @param {HTMLElement} cell - The table cell to perform action on */ handleCellContextAction(action, cell) { switch (action) { case 'copy': navigator.clipboard.writeText(cell.textContent); this.showToast('info', 'Copied', 'Cell value copied to clipboard'); break; case 'paste': navigator.clipboard.readText().then(text => { cell.textContent = text; cell.classList.remove('null-value'); cell.classList.add('modified'); this.markTableAsModified(cell.closest('table')); }); break; case 'setNull': cell.textContent = 'NULL'; cell.classList.add('null-value'); cell.classList.add('modified'); this.markTableAsModified(cell.closest('table')); break; case 'edit': this.editCell(cell); break; case 'deleteRow': const row = cell.closest('tr'); row.classList.add('deleted-row'); this.markTableAsModified(cell.closest('table')); break; } } /** * Save table changes to the database * @async * @param {HTMLElement} table - The table element with changes to save * @param {string} tableName - Name of the table being saved * @returns {Promise} * @description Collects and saves all modified cells, new rows, and deleted rows to the database */ async saveTableChanges(table, tableName) { if (!this.currentConnection) { this.showToast('error', 'No Connection', 'No database connection available'); return; } const changes = this.collectTableChanges(table); if (changes.length === 0) { this.showToast('info', 'No Changes', 'No changes to save'); return; } try { this.showLoading('Saving changes to database...'); // Show confirmation dialog for actual database changes const confirmed = confirm(`Save ${changes.length} changes to table ${tableName}?\n\nThis will modify the actual database.`); if (!confirmed) { this.hideLoading(); return; } // For now, just show a success message as backend implementation would be needed this.showToast('success', 'Changes Saved', `${changes.length} changes would be saved to ${tableName}`); // Reset modified states table.querySelectorAll('td.modified').forEach(cell => { cell.classList.remove('modified'); cell.setAttribute('data-original-value', cell.textContent); }); // Remove deleted rows table.querySelectorAll('tr.deleted-row').forEach(row => { row.remove(); }); // Reset new row states table.querySelectorAll('tr.new-row').forEach(row => { row.classList.remove('new-row'); }); const saveBtn = document.getElementById('saveChangesBtn'); const changesStatus = document.getElementById('changesStatus'); if (saveBtn) { saveBtn.disabled = true; saveBtn.textContent = ' Save Changes'; } if (changesStatus) { changesStatus.textContent = ' No changes'; changesStatus.style.color = 'var(--text-muted)'; } } catch (error) { console.error('Failed to save changes:', error); this.showToast('error', 'Save Error', error.message); } finally { this.hideLoading(); } } /** * Collect all changes made to table cells * @param {HTMLElement} table - The table element to collect changes from * @returns {Array} Array of change objects with row, column, and value information * @description Scans table for modified cells and returns structured change data */ collectTableChanges(table) { const changes = []; const modifiedCells = table.querySelectorAll('td.modified'); modifiedCells.forEach(cell => { const row = cell.closest('tr'); const rowIndex = row.getAttribute('data-row-index'); const columnIndex = cell.getAttribute('data-column'); const originalValue = cell.getAttribute('data-original-value'); const newValue = cell.classList.contains('null-value') ? null : cell.textContent; changes.push({ rowIndex, columnIndex, originalValue, newValue, type: 'update' }); }); return changes; } /** * Export table data to SQL file * @param {HTMLElement} table - The table element to export data from * @param {string} [tableName='table_data'] - Name of the table for SQL export * @returns {void} * @description Generates SQL INSERT statements and downloads as .sql file */ exportTableData(table, tableName = 'table_data') { const rows = table.querySelectorAll('tr:not(.deleted-row)'); const sqlStatements = []; // Get headers (excluding row number column) const headers = Array.from(table.querySelectorAll('thead th:not(.row-number-header)')) .map(th => { const columnName = th.querySelector('.column-name'); return columnName ? columnName.textContent : th.textContent; }); // Get current database connection type for proper SQL formatting const dbType = this.getCurrentDatabaseType(); // Create table comment header sqlStatements.push(`-- Exported data from table: ${tableName}`); sqlStatements.push(`-- Export date: ${new Date().toISOString()}`); sqlStatements.push(`-- Database type: ${dbType}`); sqlStatements.push(`-- Rows exported: ${rows.length - 1}`); // -1 for header row sqlStatements.push(''); // Add table structure comment sqlStatements.push(`-- Table structure for ${tableName}`); sqlStatements.push(`-- Columns: ${headers.join(', ')}`); sqlStatements.push(''); // Generate INSERT statements sqlStatements.push(`-- Data for table ${tableName}`); sqlStatements.push(''); // Get data rows (skip header row) const dataRows = Array.from(table.querySelectorAll('tbody tr')); if (dataRows.length > 0) { dataRows.forEach((row, index) => { const cells = Array.from(row.querySelectorAll('td:not(.row-number)')); const values = cells.map(cell => { let value = cell.textContent.trim(); if (value === 'NULL' || cell.classList.contains('null-value')) { return 'NULL'; } // Check if value is numeric if (!isNaN(value) && !isNaN(parseFloat(value)) && value !== '') { return value; } // Escape quotes based on database type return this.formatSQLValue(value, dbType); }); // Format table and column names based on database type const formattedTableName = this.formatSQLIdentifier(tableName, dbType); const columnsList = headers.map(h => this.formatSQLIdentifier(h, dbType)).join(', '); const valuesList = values.join(', '); sqlStatements.push(`INSERT INTO ${formattedTableName} (${columnsList}) VALUES (${valuesList});`); }); } else { sqlStatements.push(`-- No data found in table ${tableName}`); } // Add final comment sqlStatements.push(''); sqlStatements.push(`-- End of data export for ${tableName}`); // Create and download SQL file const sqlContent = sqlStatements.join('\n'); const blob = new Blob([sqlContent], { type: 'text/sql;charset=utf-8' }); const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `${tableName}_export_${dbType}_${new Date().toISOString().slice(0, 10)}.sql`; a.click(); window.URL.revokeObjectURL(url); this.showToast('success', 'Export Complete', `${tableName} data exported to ${dbType.toUpperCase()} SQL file`); } /** * Get current database type from active connection * @returns {string} Database type ('postgresql', 'mysql', 'mariadb', etc.) or 'generic' if no connection * @description Helper function to determine the current database type for SQL formatting */ getCurrentDatabaseType() { if (!this.currentConnection) { return 'generic'; } const connection = this.connections.find(c => c.id === this.currentConnection); return connection ? connection.type : 'generic'; } /** * Format SQL identifier with proper quotes based on database type * @param {string} identifier - The SQL identifier (table name, column name, etc.) * @param {string} dbType - Database type ('postgresql', 'mysql', 'sqlite', etc.) * @returns {string} Properly quoted identifier for the specified database type * @description Applies appropriate quoting for identifiers based on database syntax */ formatSQLIdentifier(identifier, dbType) { switch (dbType) { case 'postgresql': return `"${identifier}"`; case 'mysql': case 'mariadb': return `\`${identifier}\``; case 'sqlite': return `"${identifier}"`; case 'mssql': case 'sqlserver': return `[${identifier}]`; default: return `"${identifier}"`; } } /** * Format SQL value with proper escaping based on database type * @param {*} value - The value to format for SQL * @param {string} dbType - Database type for proper escaping * @returns {string} Properly formatted and escaped SQL value * @description Handles null values, numbers, booleans, and strings with appropriate escaping */ formatSQLValue(value, dbType) { // Handle null/undefined if (value === null || value === undefined || value === '') { return 'NULL'; } // Convert to string and clean const stringValue = String(value).trim(); // Handle special cases if (stringValue === '' || stringValue.toLowerCase() === 'null') { return 'NULL'; } // Detect numbers (don't quote them) if (/^-?\d+(\.\d+)?$/.test(stringValue)) { return stringValue; } // Detect booleans if (stringValue.toLowerCase() === 'true' || stringValue.toLowerCase() === 'false') { switch (dbType) { case 'postgresql': return stringValue.toLowerCase(); case 'mysql': case 'mariadb': return stringValue.toLowerCase() === 'true' ? '1' : '0'; default: return `'${stringValue}'`; } } // String values - escape properly let escapedValue = stringValue; switch (dbType) { case 'postgresql': case 'sqlite': case 'mssql': case 'sqlserver': // Standard SQL escaping - double single quotes escapedValue = escapedValue.replace(/'/g, "''"); return `'${escapedValue}'`; case 'mysql': case 'mariadb': // MySQL standard escaping - also double single quotes escapedValue = escapedValue.replace(/'/g, "''"); // Also escape backslashes for MySQL escapedValue = escapedValue.replace(/\\/g, '\\\\'); return `'${escapedValue}'`; default: // Generic escaping escapedValue = escapedValue.replace(/'/g, "''"); return `'${escapedValue}'`; } } /** * Update connection form with default values based on database type * @param {string} dbType - Database type to set defaults for * @returns {void} * @description Sets appropriate default ports and field states based on selected database type */ updateConnectionFormDefaults(dbType) { const portField = document.getElementById('port'); const hostField = document.getElementById('hostname'); // Set default ports const defaultPorts = { postgresql: 5432, mysql: 3306, mariadb: 3306, sqlite: '', // SQLite doesn't use ports mongodb: 27017, redis: 6379 }; portField.value = defaultPorts[dbType] || ''; // SQLite is file-based, so disable host/port if (dbType === 'sqlite') { hostField.disabled = true; portField.disabled = true; hostField.value = ''; document.getElementById('database').placeholder = 'Path to SQLite file'; } else { hostField.disabled = false; portField.disabled = false; hostField.value = 'localhost'; document.getElementById('database').placeholder = 'database_name'; } } /** * Save connection data to server * @async * @returns {Promise} * @description Validates and saves connection form data, then updates the connection list */ async saveConnection() { const form = document.getElementById('connectionForm'); const formData = new FormData(form); const connectionData = { name: formData.get('name'), type: formData.get('type'), host: formData.get('host'), port: parseInt(formData.get('port')) || null, database: formData.get('database'), username: formData.get('username'), password: formData.get('password') }; // Validation if (!connectionData.name || !connectionData.type || !connectionData.database || !connectionData.username) { this.showToast('error', 'Validation Error', 'Please fill in all required fields'); return; } try { this.showLoading('Saving connection...'); const response = await fetch(`http://localhost:${this.serverPort}/api/connections`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(connectionData) }); const data = await response.json(); if (data.success) { this.showToast('success', 'Success', 'Connection saved successfully'); this.hideConnectionModal(); await this.loadConnections(); } else { throw new Error(data.error); } } catch (error) { console.error('Failed to save connection:', error); this.showToast('error', 'Save Error', error.message); } finally { this.hideLoading(); } } /** * Delete selected database connection * @async * @returns {Promise} * @description Prompts for confirmation and deletes the currently selected connection */ async deleteSelectedConnection() { const connectionSelect = document.getElementById('connectionSelect'); const selectedConnectionId = connectionSelect.value; if (!selectedConnectionId) { this.showToast('warning', 'No Selection', 'Please select a connection to delete'); return; } const selectedConnection = this.connections.find(c => c.id === selectedConnectionId); if (!selectedConnection) { this.showToast('error', 'Not Found', 'Connection not found'); return; } // แสดง Confirmation Dialog const confirmed = confirm( `Are you sure you want to delete the connection "${selectedConnection.name}"?\n\n` + `This action cannot be undone.` ); if (!confirmed) { return; } try { this.showLoading('Deleting connection...'); const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${selectedConnectionId}`, { method: 'DELETE' }); const data = await response.json(); if (data.success) { this.showToast('success', 'Deleted', `Connection "${selectedConnection.name}" deleted successfully`); // Reset current connection if it was the deleted one if (this.currentConnection === selectedConnectionId) { this.currentConnection = null; this.updateStatus('disconnected', 'No connection selected'); // Clear database tree const treeContainer = document.getElementById('databaseTree'); treeContainer.innerHTML = '
Select a connection to view database structure
'; } // Reload connections list await this.loadConnections(); // Reset UI document.getElementById('deleteConnectionBtn').disabled = true; } else { throw new Error(data.error); } } catch (error) { console.error('Failed to delete connection:', error); this.showToast('error', 'Delete Error', error.message); } finally { this.hideLoading(); } } /** * Test database connection with form data * @async * @returns {Promise} * @description Tests connection using current form values without saving */ async testConnection() { const form = document.getElementById('connectionForm'); const formData = new FormData(form); const connectionData = { name: formData.get('name') || 'Test Connection', type: formData.get('type'), host: formData.get('host'), port: parseInt(formData.get('port')) || null, database: formData.get('database'), username: formData.get('username'), password: formData.get('password') }; if (!connectionData.type || !connectionData.database || !connectionData.username) { this.showToast('error', 'Validation Error', 'Please fill in database type, database name, and username'); return; } try { this.showLoading('Testing connection...'); // First create a temporary connection const createResponse = await fetch(`http://localhost:${this.serverPort}/api/connections`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(connectionData) }); const createData = await createResponse.json(); if (createData.success) { // Now test the connection const testResponse = await fetch(`http://localhost:${this.serverPort}/api/connections/${createData.connection.id}/test`, { method: 'POST' }); const testData = await testResponse.json(); if (testData.success && testData.connectionTest.status === 'connected') { this.showToast('success', 'Connection Test', 'Connection successful!'); } else { this.showToast('error', 'Connection Test', testData.connectionTest.message || 'Connection failed'); } // Clean up temporary connection await fetch(`http://localhost:${this.serverPort}/api/connections/${createData.connection.id}`, { method: 'DELETE' }); } else { throw new Error(createData.error); } } catch (error) { console.error('Connection test failed:', error); this.showToast('error', 'Test Error', error.message); } finally { this.hideLoading(); } } /** * Execute SQL query from the query textarea * @async * @returns {Promise} * @description Executes the SQL query and displays results or errors */ async executeQuery() { if (!this.currentConnection) { console.warn('No Connection: Please select a database connection first'); return; } // Get query from active tab or global textarea let query = ''; let queryTextarea = document.getElementById('queryTextarea'); // If no global textarea, check active tab if (!queryTextarea) { const activeTab = document.querySelector('.tab-pane.active'); if (activeTab) { const tabId = activeTab.id; queryTextarea = document.getElementById(`queryTextarea_${tabId}`); } } if (queryTextarea) { query = queryTextarea.value.trim(); } if (!query) { console.warn('No Query: Please enter a SQL query to execute'); return; } // Get parameters if provided - check both global and tab-specific let params = null; let paramsInput = document.getElementById('queryParams'); // If no global params input, check active tab if (!paramsInput) { const activeTab = document.querySelector('.tab-pane.active'); if (activeTab) { const tabId = activeTab.id; paramsInput = document.getElementById(`queryParams_${tabId}`); } } if (paramsInput && paramsInput.value.trim()) { try { params = JSON.parse(paramsInput.value.trim()); console.log(' Using query parameters:', params); } catch (error) { this.showToast('error', 'Parameter Error', 'Invalid JSON format in parameters field'); return; } } try { this.showLoading('Executing query...'); const startTime = Date.now(); // Check Smart Sync mode - ลองหา checkbox ทั้งแบบ tab และแบบ global let smartSyncCheckbox = document.getElementById('smartSyncMode'); if (!smartSyncCheckbox) { // หาจาก active tab const activeTab = document.querySelector('.tab-pane.active'); if (activeTab) { const tabId = activeTab.id; smartSyncCheckbox = document.getElementById(`smartSyncMode_${tabId}`); } } const smartSyncEnabled = smartSyncCheckbox ? smartSyncCheckbox.checked : false; const requestBody = { query }; // Add params if provided if (params) { requestBody.params = params; } if (smartSyncEnabled) { requestBody.smartSync = true; this.showLoading(' รันด้วย Smart Sync - ป้องกัน Error การสร้างซ้ำ...'); console.log(' Smart Sync Mode: ENABLED'); } else { console.log(' Normal Mode: Running without Smart Sync'); } const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/query`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(requestBody) }); const data = await response.json(); const executionTime = Date.now() - startTime; if (data.success) { this.renderQueryResults(data.data, executionTime); console.log(` Query Executed: Query completed in ${executionTime}ms`); } else { throw new Error(data.error); } } catch (error) { console.error(' Query execution failed:', error); this.renderQueryError(error.message); } finally { this.hideLoading(); } } /** * Render query execution results * @param {Object} data - Query result data * @param {number} executionTime - Time taken to execute the query in milliseconds * @returns {void} * @description Displays query results using AG Grid or fallback HTML table */ renderQueryResults(data, executionTime) { const resultsContainer = document.getElementById('resultsContent'); // Update execution time document.getElementById('executionTime').textContent = `Executed in ${executionTime}ms`; // Smart Sync Results if (data.command === 'SMART_SYNC' && data.smartSync) { this.renderSmartSyncResults(resultsContainer, data, executionTime); return; } if (data.type === 'select' && data.columns && data.columns.length > 0) { // Try AG Grid first, fallback to HTML table if fails try { this.renderTableWithAGGrid(resultsContainer, data, executionTime, 'Query Results'); console.log('Using AG Grid for results'); } catch (error) { console.error('AG Grid failed, using HTML table:', error); this.renderHTMLTable(resultsContainer, data, executionTime, 'Query Results'); } } else { // Show message for non-SELECT queries resultsContainer.innerHTML = `

${data.message || `Query executed successfully. ${data.rowCount || 0} rows affected.`}

Execution time: ${executionTime}ms

`; } } /** * Render Smart Sync query results with statistics * @param {HTMLElement} resultsContainer - Container element for results * @param {Object} data - Smart Sync result data * @param {number} executionTime - Time taken to execute in milliseconds * @returns {void} * @description Displays Smart Sync statistics and detailed results */ renderSmartSyncResults(resultsContainer, data, executionTime) { const smartSync = data.smartSync; resultsContainer.innerHTML = `

Smart Sync Results

${smartSync.created} สร้างใหม่
${smartSync.skipped} ข้าม
${smartSync.failed} ล้มเหลว
${smartSync.total} ทั้งหมด

เสร็จใน ${executionTime}ms

Log รายละเอียด:

${smartSync.logs.map(log => `
${log}
`).join('')}
${smartSync.errors.length > 0 ? `

Errors ที่เกิดขึ้น:

${smartSync.errors.map(error => `
${error.statement}
${error.error}
`).join('')}
` : ''}
`; } /** * Render query execution error * @param {string} errorMessage - Error message to display * @param {string|null} [tabId=null] - Optional tab ID for tab-specific error display * @returns {void} * @description Displays error message in results container with proper styling */ renderQueryError(errorMessage, tabId = null) { let resultsContainer; if (tabId) { // Find results container for specific tab const tab = this.tabs.get(tabId); if (tab && tab.content) { resultsContainer = tab.content.querySelector(`#resultsContent_${tabId}`); } } // Fallback to global results container if (!resultsContainer) { resultsContainer = document.getElementById('resultsContent'); } if (resultsContainer) { resultsContainer.innerHTML = `

Query Error

${errorMessage}
`; } else { console.error('Results container not found for error rendering'); } } // Tab Management openSQLQueryTab() { // สร้าง SQL Query Tab แบบใหม่ const tabId = 'sql_query'; // ถ้า Tab นี้เปิดอยู่แล้ว ให้สลับไปที่ Tab นั้น if (this.tabs.has(tabId)) { this.switchToTab(tabId); return; } // สร้าง Tab ใหม่สำหรับ SQL Query this.createSQLQueryTab(tabId); } createSQLQueryTab(tabId) { const tabBar = document.getElementById('tabBar'); // สร้าง Tab Element const tabElement = document.createElement('div'); tabElement.className = 'tab-item'; tabElement.dataset.tab = tabId; tabElement.innerHTML = ` ${this.t('SQL Query')} `; // Event Handlers tabElement.addEventListener('click', (e) => { if (!e.target.classList.contains('tab-close')) { console.log('SQL Query tab clicked:', tabId); this.switchToTab(tabId); } }); tabElement.querySelector('.tab-close').addEventListener('click', (e) => { e.stopPropagation(); console.log('Closing SQL Query tab:', tabId); this.closeTab(tabId); }); tabBar.appendChild(tabElement); // สร้าง Tab Content (รวม Query Editor + Results) const tabContent = document.createElement('div'); tabContent.className = 'tab-pane sql-query-tab'; tabContent.id = tabId; tabContent.innerHTML = `

Execute a query to see results here

`; document.querySelector('.tab-content').appendChild(tabContent); // เก็บข้อมูล Tab this.tabs.set(tabId, { title: 'SQL Query', type: 'sql-query', element: tabElement, content: tabContent }); // เพิ่ม Event Listeners สำหรับ SQL Query Tab // ใช้ setTimeout เพื่อให้ DOM ถูกสร้างเสร็จก่อน setTimeout(() => { this.initializeSQLQueryTabEvents(tabId); }, 100); // สลับไป Tab ใหม่ this.switchToTab(tabId); } initializeSQLQueryTabEvents(tabId) { console.log(` Initializing events for SQL Query tab: ${tabId}`); // Initialize splitter for this tab this.initializeSplitterForTab(tabId); // Initialize Dropdown Menus this.initializeDropdownMenus(tabId); // Import SQL File Button const importBtn = document.getElementById(`importSQLBtn_${tabId}`); console.log(`Import SQL button found:`, importBtn); if (importBtn) { importBtn.addEventListener('click', () => { console.log(` Import SQL button clicked for tab: ${tabId}`); this.importSQLFileInTab(tabId); }); } // Execute Query Button const executeBtn = document.getElementById(`executeQueryBtn_${tabId}`); console.log(`Execute button found:`, executeBtn); if (executeBtn) { executeBtn.addEventListener('click', () => { console.log(` Execute button clicked for tab: ${tabId}`); this.executeSQLQueryInTab(tabId); }); } // Cancel Query Button const cancelBtn = document.getElementById(`cancelQueryBtn_${tabId}`); console.log(`Cancel button found:`, cancelBtn); if (cancelBtn) { cancelBtn.addEventListener('click', () => { this.cancelQueryInTab(tabId); }); } // Format Query Button const formatBtn = document.getElementById(`formatQueryBtn_${tabId}`); console.log(`Format button found:`, formatBtn); if (formatBtn) { formatBtn.addEventListener('click', () => { console.log(` Format button clicked for tab: ${tabId}`); this.formatQueryInTab(tabId); }); } // Explain Query Button const explainBtn = document.getElementById(`explainQueryBtn_${tabId}`); console.log(`Explain button found:`, explainBtn); if (explainBtn) { explainBtn.addEventListener('click', () => { console.log(` Explain button clicked for tab: ${tabId}`); this.explainQueryInTab(tabId); }); } // Clear Query Button const clearBtn = document.getElementById(`clearQueryBtn_${tabId}`); console.log(`Clear button found:`, clearBtn); if (clearBtn) { clearBtn.addEventListener('click', () => { console.log(` Clear button clicked for tab: ${tabId}`); const textarea = document.getElementById(`queryTextarea_${tabId}`); if (textarea) { textarea.value = ''; } }); } console.log(` SQL Query tab events initialized for: ${tabId}`); // Save Query Button const saveBtn = document.getElementById(`saveQueryBtn_${tabId}`); if (saveBtn) { saveBtn.addEventListener('click', () => { this.saveQueryInTab(tabId); }); } // Load Query Button const loadBtn = document.getElementById(`loadQueryBtn_${tabId}`); if (loadBtn) { loadBtn.addEventListener('click', () => { this.loadQueryInTab(tabId); }); } // Import Data Button const importDataBtn = document.getElementById(`importDataBtn_${tabId}`); if (importDataBtn) { importDataBtn.addEventListener('click', () => { console.log(` Import Data button clicked for tab: ${tabId}`); this.showImportDataModal(tabId); }); } // Commit Transaction Button const commitBtn = document.getElementById(`commitBtn_${tabId}`); if (commitBtn) { commitBtn.addEventListener('click', () => { console.log(` Commit button clicked for tab: ${tabId}`); this.commitTransactionInTab(tabId); }); } // Rollback Transaction Button const rollbackBtn = document.getElementById(`rollbackBtn_${tabId}`); if (rollbackBtn) { rollbackBtn.addEventListener('click', () => { console.log(`↩ Rollback button clicked for tab: ${tabId}`); this.rollbackTransactionInTab(tabId); }); } // Keyboard shortcuts for this tab const textarea = document.getElementById(`queryTextarea_${tabId}`); if (textarea) { textarea.addEventListener('keydown', (e) => { if (e.ctrlKey && e.key === 'Enter') { e.preventDefault(); this.executeSQLQueryInTab(tabId); } // Ctrl+Shift+F for format if (e.ctrlKey && e.shiftKey && e.key === 'F') { e.preventDefault(); this.formatQueryInTab(tabId); } }); } } initializeSplitterForTab(tabId) { const splitterId = `horizontalSplitter_${tabId}`; const splitter = document.getElementById(splitterId); if (!splitter) { console.warn(` Horizontal splitter not found for tab: ${tabId} - retrying in 200ms`); // ลอง retry หลังจาก DOM ถูก render แล้ว setTimeout(() => { this.initializeSplitterForTab(tabId); }, 200); return; } const querySection = splitter.previousElementSibling; const resultsSection = splitter.nextElementSibling; if (!querySection || !resultsSection) { console.error(` Query or results section not found for tab: ${tabId}`); return; } let isResizing = false; splitter.addEventListener('mousedown', (e) => { isResizing = true; document.body.style.cursor = 'ns-resize'; document.body.style.userSelect = 'none'; const handleMouseMove = (e) => { if (!isResizing) return; const container = splitter.parentElement; const containerRect = container.getBoundingClientRect(); const mouseY = e.clientY - containerRect.top; // Calculate new heights const minHeight = 150; const maxHeight = containerRect.height - minHeight - splitter.offsetHeight; const newQueryHeight = Math.max(minHeight, Math.min(maxHeight, mouseY)); querySection.style.flex = `0 0 ${newQueryHeight}px`; resultsSection.style.flex = '1'; }; const handleMouseUp = () => { isResizing = false; document.body.style.cursor = ''; document.body.style.userSelect = ''; document.removeEventListener('mousemove', handleMouseMove); document.removeEventListener('mouseup', handleMouseUp); }; document.addEventListener('mousemove', handleMouseMove); document.addEventListener('mouseup', handleMouseUp); }); console.log(` Splitter initialized for tab: ${tabId}`); } async executeSQLQueryInTab(tabId) { if (!this.currentConnection) { console.warn('No Connection: Please select a database connection first'); return; } const textarea = document.getElementById(`queryTextarea_${tabId}`); const executeBtn = document.getElementById(`executeQueryBtn_${tabId}`); const cancelBtn = document.getElementById(`cancelQueryBtn_${tabId}`); const query = textarea ? textarea.value.trim() : ''; if (!query) { console.warn('No Query: Please enter a SQL query to execute'); return; } // Check if this is a complex PostgreSQL dump const isComplexDump = query.includes('CREATE FUNCTION') || query.includes('CREATE TRIGGER') || query.includes('$') || (query.length > 100000); if (isComplexDump) { console.log(' Detected complex PostgreSQL dump, splitting into smaller commands...'); // For very large dumps, warn user about potential issues if (query.length > 1000000) { const proceed = confirm('นี่เป็น SQL dump ขนาดใหญ่มาก (มากกว่า 1MB) อาจต้องใช้เวลานาน หรือเกิดข้อผิดพลาด\nคุณต้องการทำต่อหรือไม่?'); if (!proceed) { if (executeBtn) executeBtn.disabled = false; if (cancelBtn) cancelBtn.disabled = true; return; } } } // Update button states - disable execute, enable cancel if (executeBtn) executeBtn.disabled = true; if (cancelBtn) cancelBtn.disabled = false; try { this.showLoading('Executing query...'); const startTime = Date.now(); // Check Smart Sync mode - ใน Tab const smartSyncCheckbox = document.getElementById(`smartSyncMode_${tabId}`); const smartSyncEnabled = smartSyncCheckbox ? smartSyncCheckbox.checked : false; const requestBody = { query }; if (smartSyncEnabled) { requestBody.smartSync = true; this.showLoading(' รันด้วย Smart Sync - ป้องกัน Error การสร้างซ้ำ...'); console.log('� Smart Sync Mode: ENABLED for tab', tabId); } else { console.log(' Normal Mode: Running without Smart Sync for tab', tabId); } // Debug: ดู query และ parameters ก่อนส่ง console.log(' Query to execute:', query.substring(0, 200) + (query.length > 200 ? '...' : '')); console.log(' Query length:', query.length); console.log(' Smart Sync enabled:', smartSyncEnabled); const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/query`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(requestBody) }); const data = await response.json(); const executionTime = Date.now() - startTime; // Debug: ดู response ที่ได้รับ console.log(' Backend response:', data); console.log(' Response data.data:', data.data); if (data.data) { console.log(' Command:', data.data.command); console.log(' Smart Sync data:', data.data.smartSync); } if (data.success) { this.renderSQLQueryResults(tabId, data.data, executionTime); console.log(` Query Executed in tab ${tabId}: Query completed in ${executionTime}ms`); // Enable transaction buttons if it's a modifying query this.updateTransactionButtonsAfterQuery(query, tabId); } else { throw new Error(data.error); } } catch (error) { console.error(` Query execution failed in tab ${tabId}:`, error); this.renderSQLQueryError(tabId, error.message); } finally { this.hideLoading(); // Reset button states - enable execute, disable cancel if (executeBtn) executeBtn.disabled = false; if (cancelBtn) cancelBtn.disabled = true; } } updateTransactionButtonsAfterQuery(query, tabId) { const commitBtn = document.getElementById(`commitBtn_${tabId}`); const rollbackBtn = document.getElementById(`rollbackBtn_${tabId}`); // Enable transaction buttons for INSERT, UPDATE, DELETE queries const isModifyingQuery = /^\s*(INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)/i.test(query.trim()); if (commitBtn) commitBtn.disabled = !isModifyingQuery; if (rollbackBtn) rollbackBtn.disabled = !isModifyingQuery; } renderSQLQueryResults(tabId, data, executionTime) { const resultsContainer = document.getElementById(`resultsContent_${tabId}`); const executionTimeDisplay = document.getElementById(`executionTime_${tabId}`); // Update execution time if (executionTimeDisplay) { executionTimeDisplay.textContent = `Executed in ${executionTime}ms`; } // เช็คก่อนว่าเป็นผลลัพธ์จาก Smart Sync หรือไม่ if (data.command === 'SMART_SYNC' && data.smartSync) { this.renderSmartSyncResults(resultsContainer, data, executionTime); return; // ออกจากฟังก์ชันเลย } if (data.type === 'select' && data.columns && data.columns.length > 0) { // Try AG Grid first, fallback to HTML table if fails try { this.renderTableWithAGGrid(resultsContainer, data, executionTime, 'Query Results'); console.log('Using AG Grid for SQL Query results'); } catch (error) { console.error('AG Grid failed, using HTML table:', error); this.renderHTMLTable(resultsContainer, data, executionTime, 'Query Results'); } } else { // Enhanced message display for different query types let messageContent = ''; // Check if this is a complex dump with summary if (data.summary) { const { total, succeeded, failed, rowsAffected, errors } = data.summary; messageContent = `

Database Import Summary

Statements Executed: ${succeeded} successful / ${failed} failed / ${total} total
${rowsAffected > 0 ? `
Data Imported: ${rowsAffected} rows affected
` : ''}
${errors && errors.length > 0 ? `
View Errors (${errors.length})
    ${errors.map(error => `
  • ${error}
  • `).join('')}
` : ''}

Execution time: ${executionTime}ms

`; } else { // Standard message for regular queries const rowsText = data.rowCount === 1 ? 'row' : 'rows'; messageContent = `

${data.message || `Query executed successfully. ${data.rowCount || 0} ${rowsText} affected.`}

Execution time: ${executionTime}ms

`; } resultsContainer.innerHTML = messageContent; } } renderSQLQueryError(tabId, errorMessage) { const resultsContainer = document.getElementById(`resultsContent_${tabId}`); resultsContainer.innerHTML = `

Query Error

${errorMessage}
`; } // New Enhanced Query Functions async cancelQueryInTab(tabId) { console.log(` Cancel query requested for tab: ${tabId}`); // Note: This would require backend support for query cancellation // For now, just update UI const executeBtn = document.getElementById(`executeQueryBtn_${tabId}`); const cancelBtn = document.getElementById(`cancelQueryBtn_${tabId}`); const executionTime = document.getElementById(`executionTime_${tabId}`); if (executeBtn) executeBtn.disabled = false; if (cancelBtn) cancelBtn.disabled = true; if (executionTime) executionTime.textContent = 'Query cancelled'; } /** * Format SQL query in specified tab using basic formatting rules * @param {string} tabId - The ID of the SQL Query tab * @returns {void} * @description Applies basic SQL formatting to the query text including keyword capitalization, line breaks, and indentation * @example * this.formatQueryInTab('query_tab_1'); // Formats the SQL query in the specified tab * @see {@link formatSQL} For the underlying SQL formatting logic */ formatQueryInTab(tabId) { const textarea = document.getElementById(`queryTextarea_${tabId}`); if (!textarea) { console.error(` Query textarea not found for tab: ${tabId}`); return; } const query = textarea.value.trim(); if (!query) { console.warn('No query to format'); return; } try { // Basic SQL formatting (can be enhanced with sql-formatter library) const formattedQuery = this.formatSQL(query); textarea.value = formattedQuery; console.log(' Query formatted successfully'); } catch (error) { console.error('Format Error:', error); console.warn(' Failed to format query - invalid SQL syntax'); } } /** * Format SQL query string with basic formatting rules * @param {string} sql - The SQL query string to format * @returns {string} Formatted SQL query with proper spacing, line breaks, and keyword capitalization * @description Applies basic SQL formatting including whitespace cleanup, comma formatting, and keyword capitalization * @example * const formatted = this.formatSQL('select * from users where id=1'); * // Returns: "SELECT *\nFROM users\nWHERE id=1" * @todo Consider integrating with sql-formatter library for advanced formatting */ formatSQL(sql) { // Basic SQL formatter - can be enhanced with sql-formatter library return sql .replace(/\s+/g, ' ') // Remove extra whitespace .replace(/\s*,\s*/g, ',\n ') // Format commas .replace(/\bSELECT\b/gi, 'SELECT') .replace(/\bFROM\b/gi, '\nFROM') .replace(/\bWHERE\b/gi, '\nWHERE') .replace(/\bAND\b/gi, '\n AND') .replace(/\bOR\b/gi, '\n OR') .replace(/\bORDER BY\b/gi, '\nORDER BY') .replace(/\bGROUP BY\b/gi, '\nGROUP BY') .replace(/\bHAVING\b/gi, '\nHAVING') .replace(/\bJOIN\b/gi, '\nJOIN') .replace(/\bLEFT JOIN\b/gi, '\nLEFT JOIN') .replace(/\bRIGHT JOIN\b/gi, '\nRIGHT JOIN') .replace(/\bINNER JOIN\b/gi, '\nINNER JOIN') .trim(); } /** * Execute EXPLAIN command for query in specified tab * @async * @param {string} tabId - The ID of the SQL Query tab * @returns {Promise} * @description Prepends EXPLAIN to the current query and executes it to show query execution plan * @throws {Error} When no database connection is available or query execution fails * @example * await this.explainQueryInTab('query_tab_1'); // Shows execution plan for the current query * @see {@link displayExplainResultsInTab} For results rendering */ async explainQueryInTab(tabId) { if (!this.currentConnection) { console.warn('No Connection: Please select a database connection first'); return; } const textarea = document.getElementById(`queryTextarea_${tabId}`); if (!textarea) { console.error(` Query textarea not found for tab: ${tabId}`); return; } let query = textarea.value.trim(); if (!query) { console.warn('No query to explain'); return; } // Prepend EXPLAIN to the query if (!query.toUpperCase().startsWith('EXPLAIN')) { query = `EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)\n${query}`; } const explainBtn = document.getElementById(`explainQueryBtn_${tabId}`); if (explainBtn) explainBtn.disabled = true; try { this.showLoading('Generating execution plan...'); const startTime = Date.now(); const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/query`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query }) }); const data = await response.json(); const executionTime = Date.now() - startTime; if (data.success) { this.displayExplainResultsInTab(data.data, tabId); console.log(' Query plan generated successfully'); } else { throw new Error(data.error); } } catch (error) { console.error('Explain Error:', error); this.renderSQLQueryError(tabId, error.message); } finally { this.hideLoading(); if (explainBtn) explainBtn.disabled = false; } } /** * Display EXPLAIN query results in specified tab * @param {Object} results - The query execution plan results from the database * @param {string} tabId - The ID of the SQL Query tab * @returns {void} * @description Renders the query execution plan in a formatted table with columns and performance information * @example * this.displayExplainResultsInTab(explainData, 'query_tab_1'); // Shows execution plan in results panel * @see {@link explainQueryInTab} For the EXPLAIN command execution */ displayExplainResultsInTab(results, tabId) { const resultsContainer = document.getElementById(`resultsContent_${tabId}`); if (!resultsContainer) { console.error(` Results container not found for tab: ${tabId}`); return; } // Create a container for the explain plan resultsContainer.innerHTML = `

Query Execution Plan

${JSON.stringify(results, null, 2)}
`; } /** * Commit transaction in specified SQL Query tab * @async * @param {string} tabId - The ID of the SQL Query tab * @returns {Promise} * @description Executes a COMMIT transaction command and updates transaction button states * @example * await this.commitTransactionInTab('query_tab_1'); // Commits transaction for specified tab * @see {@link executeTransactionCommand} For the underlying transaction execution */ async commitTransactionInTab(tabId) { await this.executeTransactionCommand('COMMIT', tabId); } /** * Rollback transaction in specified SQL Query tab * @async * @param {string} tabId - The ID of the SQL Query tab * @returns {Promise} * @description Executes a ROLLBACK transaction command and updates transaction button states * @example * await this.rollbackTransactionInTab('query_tab_1'); // Rolls back transaction for specified tab * @see {@link executeTransactionCommand} For the underlying transaction execution */ async rollbackTransactionInTab(tabId) { await this.executeTransactionCommand('ROLLBACK', tabId); } /** * Execute transaction command (COMMIT or ROLLBACK) in specified tab * @async * @param {'COMMIT'|'ROLLBACK'} command - The transaction command to execute * @param {string} tabId - The ID of the SQL Query tab * @returns {Promise} * @description Executes a transaction control command and displays results, with error handling and UI updates * @throws {Error} When no database connection is available or query execution fails * @example * await this.executeTransactionCommand('COMMIT', 'query_tab_1'); // Commits transaction * await this.executeTransactionCommand('ROLLBACK', 'query_tab_1'); // Rolls back transaction */ async executeTransactionCommand(command, tabId) { if (!this.currentConnection) { console.warn('No Connection: Please select a database connection first'); return; } const btn = document.getElementById(`${command.toLowerCase()}Btn_${tabId}`); if (btn) btn.disabled = true; try { this.showLoading(`Executing ${command}...`); const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/query`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: `${command};` }) }); const data = await response.json(); if (data.success) { console.log(` ${command} executed successfully`); // Display success message const resultsContainer = document.getElementById(`resultsContent_${tabId}`); if (resultsContainer) { resultsContainer.innerHTML = `

${command} executed successfully

`; } // Update transaction buttons state this.updateTransactionButtonsState(tabId); } else { throw new Error(data.error); } } catch (error) { console.error(`${command} Error:`, error); this.renderSQLQueryError(tabId, error.message); } finally { this.hideLoading(); if (btn) btn.disabled = false; } } /** * Update transaction button states in specified tab * @param {string} tabId - The ID of the SQL Query tab * @returns {void} * @description Manages the enabled/disabled state of commit and rollback buttons based on transaction state * @example * this.updateTransactionButtonsState('query_tab_1'); // Updates button states for the specified tab * @see {@link executeTransactionCommand} For transaction command execution */ updateTransactionButtonsState(tabId) { // For simplicity, enable both buttons after any transaction command const commitBtn = document.getElementById(`commitBtn_${tabId}`); const rollbackBtn = document.getElementById(`rollbackBtn_${tabId}`); if (commitBtn) commitBtn.disabled = false; if (rollbackBtn) rollbackBtn.disabled = false; } /** * Save current query from specified tab to localStorage * @param {string} tabId - The ID of the SQL Query tab * @returns {void} * @description Prompts user for query name and saves the current query text to browser localStorage * @example * this.saveQueryInTab('query_tab_1'); // Saves current query with user-provided name * @see {@link loadQueryInTab} For loading saved queries */ saveQueryInTab(tabId) { const textarea = document.getElementById(`queryTextarea_${tabId}`); if (!textarea) { console.error(` Query textarea not found for tab: ${tabId}`); return; } const query = textarea.value.trim(); if (!query) { console.warn('No query to save'); return; } // Simple save to localStorage for now (can be enhanced with file system) const savedQueries = JSON.parse(localStorage.getItem('savedQueries') || '[]'); const queryName = prompt('Enter a name for this query:', `Query_${Date.now()}`); if (queryName) { savedQueries.push({ name: queryName, query: query, saved: new Date().toISOString() }); localStorage.setItem('savedQueries', JSON.stringify(savedQueries)); console.log(` Query saved as: ${queryName}`); } } /** * Load a saved query from localStorage into specified tab * @param {string} tabId - The ID of the SQL Query tab * @returns {void} * @description Shows list of saved queries and allows user to select one to load into the current tab * @example * this.loadQueryInTab('query_tab_1'); // Shows saved queries dialog for selection * @see {@link saveQueryInTab} For saving queries */ loadQueryInTab(tabId) { const textarea = document.getElementById(`queryTextarea_${tabId}`); if (!textarea) { console.error(` Query textarea not found for tab: ${tabId}`); return; } // Simple load from localStorage (can be enhanced with file system) const savedQueries = JSON.parse(localStorage.getItem('savedQueries') || '[]'); if (savedQueries.length === 0) { console.warn('No saved queries found'); return; } // Show a simple selection dialog const queryNames = savedQueries.map((q, i) => `${i + 1}. ${q.name}`).join('\n'); const selection = prompt(`Select a query to load:\n\n${queryNames}\n\nEnter number:`); if (selection) { const index = parseInt(selection) - 1; if (index >= 0 && index < savedQueries.length) { textarea.value = savedQueries[index].query; console.log(` Query loaded: ${savedQueries[index].name}`); } } } openTableTab(tableName, type = 'table') { // สร้าง Table Tab ใหม่แทนการใช้ Query Tab const tabId = `table_${tableName}`; // ถ้า Tab นี้เปิดอยู่แล้ว ให้สลับไปที่ Tab นั้น if (this.tabs.has(tabId)) { this.switchToTab(tabId); return; } // สร้าง Tab ใหม่สำหรับตาราง this.createTableTab(tabId, tableName, type); // โหลดข้อมูลตาราง this.loadTableData(tabId, tableName, type); } // สร้าง Tab สำหรับตารางที่แสดงแค่ Results อย่างเดียว createTableTab(tabId, tableName, type) { const tabBar = document.getElementById('tabBar'); // สร้าง Tab Element const tabElement = document.createElement('div'); tabElement.className = 'tab-item'; tabElement.dataset.tab = tabId; tabElement.innerHTML = ` ${tableName} `; // Event Handlers tabElement.addEventListener('click', (e) => { if (!e.target.classList.contains('tab-close')) { console.log('Tab clicked:', tabId); this.switchToTab(tabId); } }); tabElement.querySelector('.tab-close').addEventListener('click', (e) => { e.stopPropagation(); console.log('Closing tab:', tabId); this.closeTab(tabId); }); tabBar.appendChild(tabElement); // สร้าง Tab Content (แค่ Results อย่างเดียว) const tabContent = document.createElement('div'); tabContent.className = 'tab-pane table-only-tab'; tabContent.id = tabId; tabContent.innerHTML = `

Loading ${tableName} data...

`; document.querySelector('.tab-content').appendChild(tabContent); // เก็บข้อมูล Tab this.tabs.set(tabId, { title: tableName, type, element: tabElement, content: tabContent, tableName: tableName }); // สลับไป Tab ใหม่ this.switchToTab(tabId); } async loadTableInQueryTab(tableName, type = 'table') { if (!this.currentConnection) { this.showToast('error', 'No Connection', 'Please connect to a database first'); return; } try { // Create or switch to table tab const tableTabId = `table_${tableName}`; // Create table tab if it doesn't exist if (!this.tabs.has(tableTabId)) { this.createTableTab(tableTabId, tableName, type); } else { this.switchToTab(tableTabId); } // Show loading this.showLoading(`Loading ${type} ${tableName}...`); // Build SELECT query to get table structure and data let query = `SELECT * FROM ${tableName} LIMIT 100;`; // Execute the query to show table data in the specific tab await this.executeTableQuery(tableName, query, tableTabId); } catch (error) { console.error('Failed to load table:', error); this.showToast('error', 'Table Error', error.message); } finally { this.hideLoading(); } } async executeTableQuery(tableName, query, tabId = null) { try { const startTime = Date.now(); const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/query`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query }) }); const data = await response.json(); const executionTime = Date.now() - startTime; if (data.success) { // Enhanced rendering for table view with DBeaver-like interface this.renderTableView(tableName, data.data, executionTime, tabId); this.showToast('success', 'Table Loaded', `${tableName} loaded successfully`); } else { throw new Error(data.error); } } catch (error) { console.error('Query execution failed:', error); this.showToast('error', 'Query Error', error.message); this.renderQueryError(error.message, tabId); } } renderTableView(tableName, data, executionTime, tabId = null) { let resultsContainer; let executionTimeElement; if (tabId) { // Find elements for specific tab const tab = this.tabs.get(tabId); if (tab && tab.content) { resultsContainer = tab.content.querySelector(`#resultsContent_${tabId}`); executionTimeElement = tab.content.querySelector('.execution-time, #executionTime'); } } // Fallback to global elements if (!resultsContainer) { resultsContainer = document.getElementById('resultsContent'); } if (!executionTimeElement) { executionTimeElement = document.getElementById('executionTime'); } if (!resultsContainer) { console.error('Results container not found for table view rendering'); return; } // Update execution time if element exists if (executionTimeElement) { executionTimeElement.textContent = `Loaded in ${executionTime}ms`; } // Try AG Grid first, fallback to HTML table try { this.renderTableWithAGGrid(resultsContainer, data, executionTime, tableName); console.log('Using AG Grid for table view'); } catch (error) { console.error('AG Grid failed for table view, using HTML table:', error); this.renderHTMLTable(resultsContainer, data, executionTime, tableName); } } attachEnhancedTableEventListeners(table, tableName) { // Filter functionality const filterInput = document.getElementById('tableFilter'); if (filterInput) { filterInput.addEventListener('input', (e) => { this.filterTable(table, e.target.value); }); } // Clear filter const clearFilterBtn = document.getElementById('clearFilter'); if (clearFilterBtn) { clearFilterBtn.addEventListener('click', () => { filterInput.value = ''; this.filterTable(table, ''); }); } // Add row const addRowBtn = document.getElementById('addRowBtn'); if (addRowBtn) { addRowBtn.addEventListener('click', () => { this.addNewRow(table); }); } // Save changes - enhanced for table operations const saveChangesBtn = document.getElementById('saveChangesBtn'); if (saveChangesBtn) { saveChangesBtn.addEventListener('click', () => { this.saveTableChanges(table, tableName); }); } // Refresh table const refreshBtn = document.getElementById('refreshTableBtn'); if (refreshBtn) { refreshBtn.addEventListener('click', () => { this.refreshTableData(tableName); // Use proper refresh function }); } // Export table const exportBtn = document.getElementById('exportTableBtn'); if (exportBtn) { exportBtn.addEventListener('click', () => { this.exportTableData(table, tableName); }); } // Enhanced keyboard navigation table.addEventListener('keydown', (e) => { const activeCell = document.activeElement; if (activeCell.tagName === 'TD') { this.handleTableKeyNavigation(e, activeCell, table); } }); } handleTableKeyNavigation(e, cell, table) { const row = cell.parentElement; const cellIndex = Array.from(row.children).indexOf(cell); const rowIndex = Array.from(table.querySelectorAll('tbody tr')).indexOf(row); switch (e.key) { case 'ArrowRight': e.preventDefault(); const nextCell = row.children[cellIndex + 1]; if (nextCell) nextCell.focus(); break; case 'ArrowLeft': e.preventDefault(); const prevCell = row.children[cellIndex - 1]; if (prevCell && cellIndex > 1) prevCell.focus(); // Skip row number break; case 'ArrowDown': e.preventDefault(); const nextRow = table.querySelectorAll('tbody tr')[rowIndex + 1]; if (nextRow) { const targetCell = nextRow.children[cellIndex]; if (targetCell) targetCell.focus(); } break; case 'ArrowUp': e.preventDefault(); const prevRow = table.querySelectorAll('tbody tr')[rowIndex - 1]; if (prevRow) { const targetCell = prevRow.children[cellIndex]; if (targetCell) targetCell.focus(); } break; case 'Enter': case 'F2': e.preventDefault(); this.editCell(cell); break; case 'Delete': e.preventDefault(); this.setCellNull(cell); break; } } setCellNull(cell) { cell.classList.add('null-value', 'modified'); cell.innerHTML = 'NULL'; cell.setAttribute('data-original-value', null); this.markTableAsModified(cell.closest('table')); } createTab(tabId, title, type = 'table') { const tabBar = document.getElementById('tabBar'); // Create tab element const tabElement = document.createElement('div'); tabElement.className = 'tab-item'; tabElement.dataset.tab = tabId; tabElement.innerHTML = ` ${title} `; // Add click handlers tabElement.addEventListener('click', (e) => { if (!e.target.classList.contains('tab-close')) { this.switchToTab(tabId); } }); tabElement.querySelector('.tab-close').addEventListener('click', (e) => { e.stopPropagation(); this.closeTab(tabId); }); tabBar.appendChild(tabElement); // Create tab content const tabContent = document.getElementById('tableTabTemplate').cloneNode(true); tabContent.id = tabId; tabContent.style.display = 'none'; tabContent.querySelector('.table-name').textContent = title; document.querySelector('.tab-content').appendChild(tabContent); // Store tab info this.tabs.set(tabId, { title, type, element: tabElement, content: tabContent }); // Switch to new tab this.switchToTab(tabId); } switchToTab(tabId) { console.log('Switching to tab:', tabId); // ซ่อน Tab ทั้งหมดก่อน document.querySelectorAll('.tab-item').forEach(tab => { tab.classList.remove('active'); }); document.querySelectorAll('.tab-pane').forEach(pane => { pane.classList.remove('active'); pane.style.display = 'none'; }); // แสดง Tab ที่เลือก if (this.tabs.has(tabId)) { // Dynamic Tab (SQL Query หรือ Table Tab) const tab = this.tabs.get(tabId); if (tab && tab.element) { tab.element.classList.add('active'); } if (tab && tab.content) { tab.content.classList.add('active'); tab.content.style.display = 'flex'; } } else if (tabId === 'query') { // Fallback: สร้าง SQL Query tab ถ้ายังไม่มี console.log('Query tab not found, creating new SQL Query tab'); this.openSQLQueryTab(); return; // openSQLQueryTab จะเรียก switchToTab อีกรอบ } else { console.warn(`Tab ${tabId} not found`); } this.activeTab = tabId; } closeTab(tabId) { if (this.tabs.has(tabId)) { const tab = this.tabs.get(tabId); tab.element.remove(); tab.content.remove(); this.tabs.delete(tabId); // ถ้าปิด tab ที่ active อยู่ ให้สร้าง SQL Query tab ใหม่ if (this.activeTab === tabId) { // ถ้าไม่มี tab อื่น ให้สร้าง SQL Query tab ใหม่ if (this.tabs.size === 0) { this.openSQLQueryTab(); } else { // สลับไป tab แรกที่มี const firstTabId = this.tabs.keys().next().value; this.switchToTab(firstTabId); } } } } async loadTableData(tabId, tableName, type = 'table') { if (!this.currentConnection) return; try { this.showLoading(`Loading data from ${tableName}...`); // ปรับปรุง Query ให้เรียงลำดับตาม ID อัตโนมัติ let orderByClause = ''; // ดึงข้อมูล columns ก่อนเพื่อหา ID column try { const columnsResponse = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/tables/${tableName}/columns`); const columnsResult = await columnsResponse.json(); if (columnsResult.success && columnsResult.columns) { // หา column ที่มี "id" ในชื่อ const idColumn = columnsResult.columns.find(col => col.name.toLowerCase().includes('id') || col.name.toLowerCase() === 'id' ); if (idColumn) { orderByClause = ` ORDER BY "${idColumn.name}" ASC`; console.log(` Adding ORDER BY: ${idColumn.name}`); } } } catch (colError) { console.warn('Could not get columns for ordering:', colError); } // ใช้ Query API เพื่อดึงข้อมูลตาราง พร้อม ORDER BY const query = `SELECT * FROM ${tableName}${orderByClause} LIMIT 100;`; console.log(` Executing query: ${query}`); const startTime = Date.now(); const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/query`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query }) }); const result = await response.json(); const executionTime = Date.now() - startTime; if (result.success) { this.renderTableDataInTab(tabId, result.data, executionTime, tableName); } else { throw new Error(result.error); } } catch (error) { console.error('Failed to load table data:', error); this.showToast('error', 'Data Error', error.message); } finally { this.hideLoading(); } } // แสดงข้อมูลตารางใน Tab ที่มีแค่ Results อย่างเดียว renderTableDataInTab(tabId, data, executionTime, tableName) { const tab = this.tabs.get(tabId); if (!tab) return; const resultsContainer = tab.content.querySelector(`#resultsContent_${tabId}`); if (!resultsContainer) return; // Set current table for CRUD operations this.currentTable = tableName; // ใช้ AG Grid หรือ HTML Table fallback try { this.renderTableWithAGGrid(resultsContainer, data, executionTime, tableName); console.log(`Using AG Grid for table: ${tableName}`); } catch (error) { console.error('AG Grid failed for table, using HTML table:', error); this.renderHTMLTable(resultsContainer, data, executionTime, tableName); } } renderTableData(tabId, data) { const tab = this.tabs.get(tabId); if (!tab) return; const tableContainer = tab.content.querySelector('.table-container'); const paginationInfo = tab.content.querySelector('.page-info'); if (data.rows.length === 0) { tableContainer.innerHTML = '

No data found

'; paginationInfo.textContent = 'No data'; return; } // Create table const table = document.createElement('table'); table.className = 'data-table'; // Create header const thead = document.createElement('thead'); const headerRow = document.createElement('tr'); data.columns.forEach(column => { const th = document.createElement('th'); th.textContent = column; headerRow.appendChild(th); }); thead.appendChild(headerRow); table.appendChild(thead); // Create body const tbody = document.createElement('tbody'); data.rows.forEach(row => { const tr = document.createElement('tr'); row.forEach(cell => { const td = document.createElement('td'); if (cell === 'NULL') { td.className = 'null-value'; td.textContent = 'NULL'; } else { td.textContent = cell; td.title = cell; // Tooltip for long content } tr.appendChild(td); }); tbody.appendChild(tr); }); table.appendChild(tbody); tableContainer.innerHTML = ''; tableContainer.appendChild(table); // Update pagination info paginationInfo.textContent = `Showing ${((data.page - 1) * data.limit) + 1}-${Math.min(data.page * data.limit, data.total)} of ${data.total} rows`; } // Utility Methods updateStatus(status, message) { const indicator = document.getElementById('statusIndicator'); const dot = indicator.querySelector('.status-dot'); const text = indicator.querySelector('.status-text'); dot.className = `status-dot ${status}`; text.textContent = message; } showLoading(message = 'Loading...') { const overlay = document.getElementById('loadingOverlay'); const text = overlay.querySelector('.loading-text'); text.textContent = message; overlay.classList.add('active'); } hideLoading() { document.getElementById('loadingOverlay').classList.remove('active'); } showToast(type, title, message) { // แทนที่ป๊อปอัพด้วย console.log const logMessage = `[${type.toUpperCase()}] ${title}: ${message}`; switch (type) { case 'error': console.error(logMessage); break; case 'warning': console.warn(logMessage); break; case 'success': console.log(` ${logMessage}`); break; case 'info': console.info(`ℹ ${logMessage}`); break; default: console.log(logMessage); } } removeToast(toast) { // ฟังก์ชันนี้ไม่ใช้แล้ว - เก็บไว้เพื่อความเข้ากันได้ console.log('removeToast called - no longer used'); } // File Operations async saveQuery() { const query = document.getElementById('queryTextarea').value; if (!query.trim()) { this.showToast('warning', 'No Query', 'No query to save'); return; } try { const result = await window.electronAPI.showSaveDialog({ filters: [ { name: 'SQL Files', extensions: ['sql'] }, { name: 'Text Files', extensions: ['txt'] }, { name: 'All Files', extensions: ['*'] } ] }); if (!result.canceled && result.filePath) { const writeResult = await window.electronAPI.writeFile(result.filePath, query); if (writeResult.success) { this.showToast('success', 'Query Saved', `Query saved to ${result.filePath}`); } else { throw new Error(writeResult.error); } } } catch (error) { console.error('Failed to save query:', error); this.showToast('error', 'Save Error', error.message); } } async loadQuery() { try { const result = await window.electronAPI.showOpenDialog({ filters: [ { name: 'SQL Files', extensions: ['sql'] }, { name: 'Text Files', extensions: ['txt'] }, { name: 'All Files', extensions: ['*'] } ] }); if (!result.canceled && result.filePaths.length > 0) { const readResult = await window.electronAPI.readFile(result.filePaths[0]); if (readResult.success) { document.getElementById('queryTextarea').value = readResult.content; this.showToast('success', 'Query Loaded', `Query loaded from ${result.filePaths[0]}`); } else { throw new Error(readResult.error); } } } catch (error) { console.error('Failed to load query:', error); this.showToast('error', 'Load Error', error.message); } } async exportResults() { // Check if AG Grid is available if (this.currentGridApi) { this.exportGridDataAsSQL('query_results'); } else { // Try to find HTML table in results const resultsContainer = document.querySelector('.results-content'); const table = resultsContainer ? resultsContainer.querySelector('table') : null; if (table) { this.exportTableData(table, 'query_results'); } else { this.showToast('warning', 'No Data', 'No data available to export'); } } } async testConnectionById(connectionId) { try { this.showLoading('Testing connection...'); const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${connectionId}/test`, { method: 'POST' }); const data = await response.json(); if (data.success && data.connectionTest.status === 'connected') { this.showToast('success', 'Connection Test', 'Connection is healthy'); } else { this.showToast('error', 'Connection Test', data.connectionTest.message || 'Connection failed'); } } catch (error) { console.error('Connection test failed:', error); this.showToast('error', 'Test Error', error.message); } finally { this.hideLoading(); } } async importSQLFile(filePath) { try { const readResult = await window.electronAPI.readFile(filePath); if (readResult.success) { document.getElementById('queryTextarea').value = readResult.content; this.showToast('success', 'SQL Imported', `SQL file imported: ${filePath}`); // Switch to query tab this.switchToTab('query'); } else { throw new Error(readResult.error); } } catch (error) { console.error('Failed to import SQL file:', error); this.showToast('error', 'Import Error', error.message); } } async importSQLFileInTab(tabId) { try { // Use Electron's file dialog to select SQL file const fileResult = await window.electronAPI.showOpenDialog({ title: 'Select SQL File', filters: [ { name: 'SQL Files', extensions: ['sql'] }, { name: 'Text Files', extensions: ['txt'] }, { name: 'All Files', extensions: ['*'] } ], properties: ['openFile'] }); if (fileResult.canceled || fileResult.filePaths.length === 0) { return; } const filePath = fileResult.filePaths[0]; // Read the file content const readResult = await window.electronAPI.readFile(filePath); if (readResult.success) { // Load content into the specific tab's textarea const textarea = document.getElementById(`queryTextarea_${tabId}`); if (textarea) { textarea.value = readResult.content; this.showToast('success', 'SQL Imported', `SQL file imported to tab: ${filePath}`); // Focus on the textarea textarea.focus(); } else { throw new Error(`Textarea not found for tab: ${tabId}`); } } else { throw new Error(readResult.error); } } catch (error) { console.error('Failed to import SQL file to tab:', error); this.showToast('error', 'Import Error', error.message); } } // AG Grid Integration Functions renderTableWithAGGrid(container, data, executionTime, tableName = 'Query Results') { // Clear container container.innerHTML = ''; // Create wrapper for AG Grid const gridWrapper = document.createElement('div'); gridWrapper.className = 'ag-grid-wrapper'; // Create toolbar (DBeaver-style) const toolbar = document.createElement('div'); toolbar.className = 'table-toolbar ag-grid-toolbar'; // Check if this is a table view (not query results) to show CRUD controls const isTableView = tableName !== 'Query Results'; const crudControls = isTableView ? `
No changes
` : `
`; toolbar.innerHTML = `
� ${tableName} ${data.rowCount || data.rows?.length || 0} rows • ${(data.columns || []).length} columns
${crudControls}
`; // Create AG Grid container const gridContainer = document.createElement('div'); gridContainer.className = 'ag-theme-balham-dark'; // ใช้ flex สำหรับทุก Tab เพื่อให้ใช้พื้นที่เต็ม if (container.closest('.table-only-tab')) { // สำหรับ Table Tab ให้ใช้ flex gridContainer.style.flex = '1'; gridContainer.style.height = 'auto'; } else { // สำหรับ Query Tab ใช้ flex เต็มพื้นที่ gridContainer.style.flex = '1'; gridContainer.style.height = 'auto'; gridContainer.style.minHeight = '300px'; } gridContainer.style.width = '100%'; // Prepare column definitions const columnDefs = []; // Add row number column columnDefs.push({ headerName: '#', valueGetter: 'node.rowIndex + 1', width: 60, pinned: 'left', suppressMovable: true, suppressResize: true, cellClass: 'row-number-cell' }); // Add data columns if (data.columns && data.columns.length > 0) { data.columns.forEach(column => { const columnDef = { headerName: column, field: column, editable: true, cellEditor: 'agTextCellEditor', sortable: true, filter: true, resizable: true, minWidth: 100, cellClass: 'data-cell', // --- SOLUTION --- เพิ่ม cellClassRules เพื่อแสดงสถานะการเปลี่ยนแปลง cellClassRules: { 'cell-dirty': params => { // เซลล์ที่ถูกแก้ไข (ไม่ใช่แถวใหม่) return params.data && params.data._isDirty && !params.data._isNew; } }, cellRenderer: (params) => { if (params.value === null || params.value === undefined || params.value === 'NULL') { return 'NULL'; } if (typeof params.value === 'string' && params.value.length > 100) { return `${params.value.substring(0, 100)}...`; } return params.value; }, valueSetter: (params) => { // Handle NULL values properly if (params.newValue === '' || params.newValue === 'NULL') { params.data[params.colDef.field] = null; } else { params.data[params.colDef.field] = params.newValue; } return true; } }; // สำหรับ column ที่เป็น id ให้ใช้ numeric sorting if (column.toLowerCase() === 'id' || column.toLowerCase().endsWith('_id')) { columnDef.comparator = (valueA, valueB) => { const numA = parseInt(valueA); const numB = parseInt(valueB); // ถ้าแปลงเป็นตัวเลขได้ ให้เปรียบเทียบแบบตัวเลข if (!isNaN(numA) && !isNaN(numB)) { return numA - numB; } // ถ้าแปลงไม่ได้ ให้เปรียบเทียบแบบ string if (valueA < valueB) return -1; if (valueA > valueB) return 1; return 0; }; // กำหนด default sort เป็น ascending สำหรับ id column if (column.toLowerCase() === 'id') { columnDef.sort = 'asc'; } } columnDefs.push(columnDef); }); } // Prepare row data with normalized IDs const rowData = []; if (data.rows && data.rows.length > 0) { data.rows.forEach(row => { const rowObject = {}; data.columns.forEach((column, index) => { rowObject[column] = row[index]; }); // Normalize row data for consistent IDs rowData.push(this.normalizeRowData(rowObject, tableName)); }); } else if (data.columns && data.columns.length > 0) { // Add empty row to show structure when no data const emptyRow = {}; data.columns.forEach(column => { emptyRow[column] = null; }); rowData.push(this.normalizeRowData(emptyRow, tableName)); } // AG Grid options (DBeaver-style) const gridOptions = { columnDefs: columnDefs, rowData: rowData, getRowId: (params) => { // Use primary key for row identification - ALWAYS STRING const primaryKey = this.getPrimaryKeyForTable(tableName) || 'id'; const id = params.data[primaryKey]; return String(id); // Force string conversion for consistency }, defaultColDef: { sortable: true, filter: true, resizable: true, editable: true, cellClass: 'ag-cell-data' }, // DEFAULT SORTING: เรียงตาม ID เสมอ sortingOrder: ['asc', 'desc'], // DBeaver-like features enableRangeSelection: true, enableCellTextSelection: true, enableFillHandle: true, suppressRowClickSelection: false, rowSelection: 'multiple', animateRows: false, // Disable for better performance suppressCellFocus: false, suppressColumnVirtualisation: false, suppressRowVirtualisation: false, // เพิ่ม Context Menu (คลิกขวา) สำหรับ AG Grid getContextMenuItems: (params) => { const result = []; // ตรวจสอบให้แน่ใจว่า params.node มีค่า if (params.node && params.node.data) { result.push({ name: ' แก้ไขแถว', action: () => { // เลือกแถวนี้และเรียกฟังก์ชันแก้ไข this.currentGridApi.deselectAll(); params.node.setSelected(true); this.editSelectedRow(); } }); result.push({ name: ' ลบแถว', action: () => { // เลือกแถวนี้และเรียกฟังก์ชันลบ this.currentGridApi.deselectAll(); params.node.setSelected(true); this.deleteSelectedRows(); } }); result.push('separator'); result.push({ name: ' คัดลอกแถว', action: () => { this.copyRowData(params.node); } }); result.push({ name: ' ทำสำเนาแถว', action: () => { this.duplicateRowData(params.node); } }); result.push('separator'); } result.push({ name: ' รีเฟรชตาราง', action: () => { if (tableName !== 'Query Results') { this.refreshTableData(tableName); } else { this.showToast('info', 'ไม่สามารถรีเฟรชได้', 'ไม่สามารถรีเฟรช Query Results ได้'); } } }); return result; }, // --- SOLUTION --- เพิ่ม rowClassRules สำหรับแถวใหม่และแถวที่แก้ไข rowClassRules: { 'ag-row-new': params => { // แถวใหม่ที่เพิ่งสร้าง return params.data && params.data._isNew; }, 'ag-row-modified': params => { // แถวเก่าที่ถูกแก้ไข return params.data && params.data._isDirty && !params.data._isNew; }, 'ag-row-deleted': params => { // แถวที่ถูกมาร์คให้ลบ return params.data && params.data._isDeleted; } }, // Grid events onCellValueChanged: (event) => { // --- SOLUTION --- // ถ้าไม่ใช่แถวใหม่ ให้เพิ่ม flag ว่าถูกแก้ไข // ใช้ setTimeout เพื่อหลีกเลี่ยง conflict ในขณะที่ AG Grid กำลังประมวลผล setTimeout(() => { if (event.node && event.data && !event.data._isNew) { // แก้ไขข้อมูลโดยตรงแทนการใช้ setDataValue event.data._isDirty = true; event.node.setData(event.data); } this.markGridAsModified(); // รีเฟรช AG Grid เพื่อให้ CSS ทำงาน if (event.api && event.node) { event.api.refreshCells({ rowNodes: [event.node], force: true }); } }, 10); console.log('Cell value changed:', event.oldValue, '->', event.newValue); }, onSelectionChanged: (event) => { // อัปเดตสถานะปุ่มตามการเลือกแถว this.updateActionButtonStates(); }, onGridReady: (params) => { console.log('AG Grid ready'); params.api.sizeColumnsToFit(); // Auto-focus first cell for editing like DBeaver if (rowData.length > 0) { setTimeout(() => { params.api.setFocusedCell(0, data.columns[0]); }, 100); } }, onCellClicked: (event) => { console.log('Cell clicked:', event.value); }, onCellDoubleClicked: (event) => { console.log('Cell double clicked - start editing'); event.api.startEditingCell({ rowIndex: event.rowIndex, colKey: event.column.getColId() }); } }; // Create AG Grid (v31 syntax) console.log(' Creating AG Grid with columns:', columnDefs.length); console.log(' Is Table View:', isTableView); console.log(' Actions column exists:', columnDefs.some(col => col.field === 'actions')); const gridApi = agGrid.createGrid(gridContainer, gridOptions); // Store grid API reference this.currentGridApi = gridApi; console.log(' AG Grid created successfully:', gridApi); // INITIAL SORTING: เรียงตาม ID หรือคอลัมน์แรกที่มี "id" ในชื่อ setTimeout(() => { if (this.currentGridApi && data.columns) { // หาคอลัมน์ที่มี "id" ในชื่อ (เช่น id, user_id, plugin_id) const idColumn = data.columns.find(col => col.toLowerCase().includes('id') || col.toLowerCase() === 'id' ); if (idColumn) { console.log(` Setting initial sort by column: ${idColumn}`); this.currentGridApi.applyColumnState({ state: [{ colId: idColumn, sort: 'asc' }] }); } else { // ถ้าไม่มี ID column ให้เรียงตามคอลัมน์แรก console.log(` Setting initial sort by first column: ${data.columns[0]}`); this.currentGridApi.applyColumnState({ state: [{ colId: data.columns[0], sort: 'asc' }] }); } } }, 100); // รอให้ grid โหลดเสร็จก่อน // Results info const resultsInfo = document.createElement('div'); resultsInfo.className = 'results-info enhanced'; resultsInfo.innerHTML = `
Rows: ${data.rowCount || data.rows?.length || 0} ⏱ Load time: ${executionTime}ms No changes
Table: ${tableName} Columns: ${(data.columns || []).length}
`; // Assemble everything gridWrapper.appendChild(toolbar); gridWrapper.appendChild(gridContainer); gridWrapper.appendChild(resultsInfo); container.appendChild(gridWrapper); // Store grid reference for later use this.currentGrid = gridOptions; this.currentGridApi = gridApi; // Attach event listeners this.attachAGGridEventListeners(tableName); return gridOptions; } attachAGGridEventListeners(tableName) { // Global filter functionality (DBeaver-style) const globalFilter = document.getElementById('globalFilter'); if (globalFilter && this.currentGridApi) { globalFilter.addEventListener('input', (e) => { this.currentGridApi.setQuickFilter(e.target.value); }); } // Clear filter const clearFilterBtn = document.getElementById('clearFilter'); if (clearFilterBtn && this.currentGridApi) { clearFilterBtn.addEventListener('click', () => { if (globalFilter) { globalFilter.value = ''; this.currentGridApi.setQuickFilter(''); } }); } // Add row functionality const addRowBtn = document.getElementById('addRowBtn'); if (addRowBtn) { addRowBtn.addEventListener('click', () => { if (tableName !== 'Query Results') { this.showAddRowForm(tableName); } else { this.addRowToGrid(); } }); } // Delete selected rows const deleteSelectedBtn = document.getElementById('deleteSelectedBtn'); if (deleteSelectedBtn) { deleteSelectedBtn.addEventListener('click', () => { this.deleteSelectedRows(); }); } // Edit selected row const editSelectedBtn = document.getElementById('editSelectedBtn'); if (editSelectedBtn) { editSelectedBtn.addEventListener('click', () => { this.editSelectedRow(); }); } // Save changes const saveChangesBtn = document.getElementById('saveChangesBtn'); if (saveChangesBtn) { saveChangesBtn.addEventListener('click', () => { this.saveGridChanges(tableName); }); } // Cancel changes const cancelChangesBtn = document.getElementById('cancelChangesBtn'); if (cancelChangesBtn) { cancelChangesBtn.addEventListener('click', () => { this.cancelGridChanges(tableName); }); } // Refresh const refreshBtn = document.getElementById('refreshTableBtn'); if (refreshBtn) { refreshBtn.addEventListener('click', () => { if (tableName !== 'Query Results') { // Use refreshTableData instead of loadTableInQueryTab this.refreshTableData(tableName); } else { this.executeQuery(); } }); } // Export const exportBtn = document.getElementById('exportTableBtn'); if (exportBtn) { exportBtn.addEventListener('click', () => { this.exportGridDataAsSQL(tableName); }); } } /** * Mark grid as modified and update UI indicators (DBeaver-style) * @description Updates save button state and shows change count */ markGridAsModified() { console.log(' markGridAsModified called'); const saveBtn = document.getElementById('saveChangesBtn'); const cancelBtn = document.getElementById('cancelChangesBtn'); const changesStatus = document.getElementById('changesStatus'); if (this.currentGridApi) { // Count changes with safety checks let newRows = 0; let modifiedRows = 0; let deletedRows = 0; try { this.currentGridApi.forEachNode(node => { if (node && node.data) { if (node.data._isDeleted) { deletedRows++; } else if (node.data._isNew) { newRows++; } else if (node.data._isDirty) { modifiedRows++; } } }); } catch (error) { console.warn('Error counting grid changes:', error); return; // Exit early if there's an error } const totalChanges = newRows + modifiedRows + deletedRows; console.log(` Changes count: new=${newRows}, modified=${modifiedRows}, deleted=${deletedRows}, total=${totalChanges}`); // Update save button if (saveBtn) { saveBtn.disabled = totalChanges === 0; saveBtn.classList.toggle('save-changes', totalChanges > 0); console.log(` Save button: disabled=${saveBtn.disabled}, totalChanges=${totalChanges}`); } else { console.warn(' Save button not found (ID: saveChangesBtn)'); } // Update cancel button if (cancelBtn) { cancelBtn.disabled = totalChanges === 0; cancelBtn.classList.toggle('cancel-changes', totalChanges > 0); console.log(` Cancel button: disabled=${cancelBtn.disabled}, totalChanges=${totalChanges}`); } else { console.warn(' Cancel button not found (ID: cancelChangesBtn)'); } if (changesStatus) { if (totalChanges > 0) { let statusParts = []; if (newRows > 0) statusParts.push(`${newRows} เพิ่ม`); if (modifiedRows > 0) statusParts.push(`${modifiedRows} แก้ไข`); if (deletedRows > 0) statusParts.push(`${deletedRows} ลบ`); changesStatus.textContent = ` ${statusParts.join(', ')}`; changesStatus.className = 'changes-status has-changes'; } else { changesStatus.textContent = ' No changes'; changesStatus.className = 'changes-status no-changes'; } } // Update action button states this.updateActionButtonStates(); } } addRowToGrid() { if (this.currentGridApi) { const newRow = {}; // Initialize with empty values based on existing column definitions const columnDefs = this.currentGridApi.getColumnDefs(); if (columnDefs && columnDefs.length > 0) { columnDefs.forEach(col => { if (col.field && col.field !== 'actions') { newRow[col.field] = null; } }); } // --- SOLUTION --- // เพิ่ม flag เพื่อบอกว่านี่คือแถวใหม่ newRow._isNew = true; // Normalize new row data for consistent IDs const activeTab = document.querySelector('.tab-pane.active'); const tableName = activeTab ? activeTab.getAttribute('data-table') : 'unknown'; const normalizedNewRow = this.normalizeRowData(newRow, tableName); this.currentGridApi.applyTransaction({ add: [normalizedNewRow] }); this.markGridAsModified(); // Scroll to and select the new row with auto-focus setTimeout(() => { const rowCount = this.currentGridApi.getDisplayedRowCount(); this.currentGridApi.ensureIndexVisible(rowCount - 1); const rowNode = this.currentGridApi.getDisplayedRowAtIndex(rowCount - 1); if (rowNode) { rowNode.setSelected(true); // Auto-focus first editable cell const columnDefs = this.currentGridApi.getColumnDefs(); const firstEditableColumn = columnDefs.find(col => col.field && col.field !== 'actions' && col.editable !== false); if (firstEditableColumn) { this.currentGridApi.setFocusedCell(rowCount - 1, firstEditableColumn.field); } } }, 100); } else { this.showToast('error', 'Error', 'ไม่สามารถเพิ่มแถวได้ กรุณาโหลดตารางก่อน'); } } // Get current database type getCurrentDatabaseType() { return 'postgresql'; // Default for this app } // Format SQL identifier based on database type formatSQLIdentifier(identifier, dbType) { if (!identifier) return identifier; switch (dbType.toLowerCase()) { case 'postgresql': return `"${identifier}"`; case 'mysql': return `\`${identifier}\``; case 'sqlite': return `"${identifier}"`; default: return identifier; } } // Format SQL value based on type formatSQLValue(value, dbType) { if (value === null || value === undefined) { return 'NULL'; } if (typeof value === 'string') { // Escape single quotes const escaped = value.replace(/'/g, "''"); return `'${escaped}'`; } if (typeof value === 'number') { return value.toString(); } if (typeof value === 'boolean') { return value ? 'TRUE' : 'FALSE'; } // For dates or other objects, convert to string return `'${String(value).replace(/'/g, "''")}'`; } /** * Get table columns information via API call to server * @param {string} tableName - Name of the table to get columns for * @returns {Promise} Promise that resolves to array of column objects or empty array on error * @async */ async getTableColumns(tableName) { try { const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/tables/${tableName}/structure`); if (response.ok) { const result = await response.json(); return result.columns || []; } } catch (error) { console.warn('Could not fetch table columns:', error); } return []; } /** * Save AG Grid changes to database with INSERT and UPDATE operations * @async * @param {string} tableName - Name of the table to save changes to * @returns {Promise} * @description Processes new rows (INSERT) and modified rows (UPDATE) from AG Grid and saves them to database * @throws {Error} When save operation fails */ async saveGridChanges(tableName) { if (!this.currentGridApi) { this.showToast('error', 'ไม่มี Grid', 'ไม่มีข้อมูลให้บันทึก'); return; } if (!this.currentConnection) { this.showToast('error', 'ไม่มีการเชื่อมต่อ', 'กรุณาเชื่อมต่อฐานข้อมูลก่อน'); return; } const confirmed = confirm(`คุณต้องการบันทึกการเปลี่ยนแปลงทั้งหมดในตาราง ${tableName} หรือไม่?\n\nการกระทำนี้จะแก้ไขข้อมูลในฐานข้อมูลจริง`); if (!confirmed) return; this.showLoading('กำลังบันทึกการเปลี่ยนแปลง...'); const rowsToInsert = []; const rowsToUpdate = []; const rowsToDelete = []; // เพิ่ม Array สำหรับเก็บข้อมูลที่จะลบ // 1. วน loop เพื่อแยกแถวใหม่และแถวที่แก้ไข this.currentGridApi.forEachNode(node => { if (node && node.data) { // ข้ามข้อมูลที่ไม่สมบูรณ์หรือไม่มีการเปลี่ยนแปลง if (node.data._isDeleted) { // ตรวจจับแถวที่ถูกมาร์คให้ลบ rowsToDelete.push(node.data); } else if (node.data._isNew) { const cleanData = { ...node.data }; // ลบ internal flags และข้อมูลที่ไม่จำเป็นออกก่อนส่ง delete cleanData._isNew; delete cleanData._isDirty; delete cleanData.actions; delete cleanData._isDeleted; rowsToInsert.push(cleanData); } else if (node.data._isDirty) { const cleanData = { ...node.data }; delete cleanData._isNew; delete cleanData._isDirty; delete cleanData.actions; delete cleanData._isDeleted; rowsToUpdate.push(cleanData); } } }); if (rowsToInsert.length === 0 && rowsToUpdate.length === 0 && rowsToDelete.length === 0) { this.showToast('info', 'ไม่มีการเปลี่ยนแปลง', 'ไม่มีข้อมูลให้บันทึก'); this.hideLoading(); return; } try { let successCount = 0; let failedCount = 0; const errors = []; // ดึงข้อมูลโครงสร้างตารางเพื่อหา Primary Key *ก่อน* ทำการ Update/Delete const columns = await this.getTableColumns(tableName); const primaryKeyName = this.findPrimaryKey(columns); if ((rowsToUpdate.length > 0 || rowsToDelete.length > 0) && !primaryKeyName) { throw new Error(`ไม่สามารถหา Primary Key ของตาราง ${tableName} ได้ ไม่สามารถทำการแก้ไข/ลบข้อมูลได้`); } // จัดการกับการเพิ่มข้อมูล (INSERT) for (const rowData of rowsToInsert) { try { const normalizedRow = this.normalizeRowData(rowData, tableName); await this.insertTableRow(tableName, normalizedRow); successCount++; } catch (e) { failedCount++; errors.push(`INSERT FAILED: ${e.message}`); } } // จัดการกับการแก้ไขข้อมูล (UPDATE) for (const rowData of rowsToUpdate) { const normalizedRow = this.normalizeRowData(rowData, tableName); const rowId = normalizedRow[primaryKeyName]; if (rowId === undefined) { failedCount++; errors.push(`UPDATE FAILED: ไม่พบค่าในคอลัมน์ Primary Key '${primaryKeyName}'`); continue; } try { // ส่งชื่อ PK ที่ถูกต้องไปด้วย await this.updateTableRow(tableName, rowId, normalizedRow, primaryKeyName); successCount++; } catch (e) { failedCount++; errors.push(`UPDATE FAILED for row ID ${rowId}: ${e.message}`); } } // จัดการกับการลบข้อมูล (DELETE) for (const rowData of rowsToDelete) { const normalizedRow = this.normalizeRowData(rowData, tableName); const rowId = normalizedRow[primaryKeyName]; if (normalizedRow._isNew) { // แถวใหม่ที่ถูกลบ ไม่ต้องส่งไปยัง server แค่นับเป็น success console.log(`Skipping delete for new row (not yet saved)`); successCount++; } else if (rowId !== undefined && rowId !== null && rowId !== 'null' && String(rowId).toLowerCase() !== 'null') { // แถวเก่าที่มี Primary Key ที่ valid try { console.log(`Attempting to delete row with ID: ${rowId}`); await this.deleteTableRow(tableName, rowId, primaryKeyName); successCount++; console.log(`Successfully deleted row ID: ${rowId}`); } catch (e) { console.error(`Failed to delete row ID ${rowId}:`, e); // แยกประเภท error if (e.message.includes('Row not found') || e.message.includes('not found') || e.message.includes('already deleted')) { // ถ้าแถวไม่อยู่ในฐานข้อมูลแล้ว ให้ถือว่าสำเร็จ console.log(`Row ID ${rowId} already deleted or not found, marking as success`); successCount++; } else { // Error อื่นๆ ให้นับเป็น failure failedCount++; errors.push(`DELETE FAILED for row ID ${rowId}: ${e.message}`); } } } else { // แถวที่ไม่มี Primary Key ที่ valid - ข้ามไป console.warn(`Skipping delete for row with invalid Primary Key: ${rowId}`); successCount++; // นับเป็น success เพราะไม่ต้องลบจริงๆ } } if (failedCount > 0) { // แม้มี error บางส่วน แต่ถ้ามี success ด้วยให้แสดงผลแบบ mixed if (successCount > 0) { const errorDetails = errors.length > 3 ? errors.slice(0, 3).join('\n') + `\n... และอีก ${errors.length - 3} รายการ` : errors.join('\n'); this.showToast('warning', 'บันทึกบางส่วนสำเร็จ', `สำเร็จ ${successCount} รายการ, ล้มเหลว ${failedCount} รายการ\n\nรายละเอียดข้อผิดพลาด:\n${errorDetails}`); } else { // ล้มเหลวทั้งหมด const errorDetails = errors.length > 3 ? errors.slice(0, 3).join('\n') + `\n... และอีก ${errors.length - 3} รายการ` : errors.join('\n'); this.showToast('error', 'บันทึกล้มเหลว', `การบันทึกล้มเหลวทั้งหมด ${failedCount} รายการ\n\nรายละเอียด:\n${errorDetails}`); } // รีเฟรชข้อมูลเพื่อให้ sync กับฐานข้อมูล await this.refreshTableData(tableName); } else { // สำเร็จทั้งหมด this.showToast('success', 'บันทึกสำเร็จ', `บันทึกข้อมูล ${successCount} รายการเรียบร้อย`); // ลบแถวที่ถูกมาร์คให้ลบออกจาก Grid if (rowsToDelete.length > 0) { const primaryKey = this.getPrimaryKeyForTable(tableName) || 'id'; const rowsToRemove = []; // Check if rows exist in grid before removing rowsToDelete.forEach(row => { if (!row._isNew) { // เฉพาะแถวเก่าที่ลบจริง const idStr = String(row[primaryKey]); const node = this.currentGridApi.getRowNode(idStr); if (node) { rowsToRemove.push(this.normalizeRowData(row, tableName)); } else { console.log(`Row ${idStr} already removed from grid`); } } }); if (rowsToRemove.length > 0) { this.currentGridApi.applyTransaction({ remove: rowsToRemove }); console.log(`Removed ${rowsToRemove.length} deleted rows from grid`); } } await this.refreshTableData(tableName); // รีเฟรชข้อมูลล่าสุด } } catch (error) { console.error('Failed to save grid changes:', error); this.showToast('error', 'บันทึกล้มเหลว', error.message); } finally { this.hideLoading(); } } exportGridDataAsSQL(tableName) { if (!this.currentGridApi) { this.showToast('error', 'No Grid', 'No grid data to export'); return; } try { // Get all row data from AG Grid const rowData = []; this.currentGridApi.forEachNode(node => { if (node.data) { rowData.push(node.data); } }); // Get column definitions const columnDefs = this.currentGridApi.getColumnDefs(); const columns = columnDefs.map(col => col.field || col.colId).filter(field => field); if (rowData.length === 0) { this.showToast('warning', 'No Data', 'No data to export'); return; } // Get current database type for proper SQL formatting const dbType = this.getCurrentDatabaseType(); // Generate SQL statements const sqlStatements = []; // Create table comment header sqlStatements.push(`-- Exported data from: ${tableName}`); sqlStatements.push(`-- Export date: ${new Date().toISOString()}`); sqlStatements.push(`-- Database type: ${dbType}`); sqlStatements.push(`-- Rows exported: ${rowData.length}`); sqlStatements.push(''); // Add table structure comment sqlStatements.push(`-- Table structure for ${tableName}`); sqlStatements.push(`-- Columns: ${columns.join(', ')}`); sqlStatements.push(''); // Generate INSERT statements sqlStatements.push(`-- Data for table ${tableName}`); sqlStatements.push(''); rowData.forEach((row, index) => { const values = columns.map(column => { let value = row[column]; if (value === null || value === undefined || value === '') { return 'NULL'; } // Check if value is numeric if (!isNaN(value) && !isNaN(parseFloat(value)) && value !== '') { return value; } // Format value based on database type return this.formatSQLValue(String(value), dbType); }); // Format table and column names based on database type const formattedTableName = this.formatSQLIdentifier(tableName, dbType); const columnsList = columns.map(col => this.formatSQLIdentifier(col, dbType)).join(', '); const valuesList = values.join(', '); sqlStatements.push(`INSERT INTO ${formattedTableName} (${columnsList}) VALUES (${valuesList});`); }); // Add final comment sqlStatements.push(''); sqlStatements.push(`-- End of data export for ${tableName}`); // Create and download SQL file const sqlContent = sqlStatements.join('\n'); const blob = new Blob([sqlContent], { type: 'text/sql;charset=utf-8' }); const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `${tableName}_export_${dbType}_${new Date().toISOString().slice(0, 10)}.sql`; a.click(); window.URL.revokeObjectURL(url); this.showToast('success', 'Export Complete', `${tableName} data exported to ${dbType.toUpperCase()} SQL file`); } catch (error) { console.error('Failed to export grid data:', error); this.showToast('error', 'Export Error', error.message); } } /** * Format SQL value based on database type * @param {string} value - The value to format * @param {string} dbType - Database type (postgresql, mysql, etc.) * @returns {string} Formatted SQL value */ formatSQLValue(value, dbType) { if (!value) return 'NULL'; // Escape single quotes in the value const escapedValue = value.replace(/'/g, "''"); // Return formatted value based on database type switch (dbType.toLowerCase()) { case 'postgresql': return `'${escapedValue}'`; case 'mysql': return `'${escapedValue}'`; default: return `'${escapedValue}'`; } } /** * Format SQL identifier (table/column names) based on database type * @param {string} identifier - The identifier to format * @param {string} dbType - Database type (postgresql, mysql, etc.) * @returns {string} Formatted SQL identifier */ formatSQLIdentifier(identifier, dbType) { switch (dbType.toLowerCase()) { case 'postgresql': return `"${identifier}"`; case 'mysql': return `\`${identifier}\``; default: return `"${identifier}"`; } } /** * Get current database type from active connection * @returns {string} Database type */ getCurrentDatabaseType() { // Try to get from current connection info if (this.currentConnection && this.currentConnection.type) { return this.currentConnection.type; } // Default fallback return 'postgresql'; } /** * Debug function to diagnose save button issues */ debugSaveButton() { console.log(' DEBUG SAVE BUTTON - Starting diagnostics...'); const saveBtn = document.getElementById('saveChangesBtn'); console.log(' Save button element:', saveBtn); console.log(' Save button disabled:', saveBtn ? saveBtn.disabled : 'Button not found'); if (this.currentGridApi) { console.log(' Grid API exists:', !!this.currentGridApi); // Count changes let newRows = 0; let modifiedRows = 0; let deletedRows = 0; let totalRows = 0; this.currentGridApi.forEachNode(node => { totalRows++; if (node && node.data) { console.log(' Row data:', node.data); if (node.data._isDeleted) deletedRows++; else if (node.data._isNew) newRows++; else if (node.data._isDirty) modifiedRows++; } }); const totalChanges = newRows + modifiedRows + deletedRows; console.log(` Grid stats: total=${totalRows}, new=${newRows}, modified=${modifiedRows}, deleted=${deletedRows}, changes=${totalChanges}`); // Force enable button if there are changes or for testing if (saveBtn) { saveBtn.disabled = false; saveBtn.classList.add('save-changes'); console.log(' FORCED ENABLE: Save button enabled for testing'); this.showToast('info', 'Debug', `Save button force enabled. Changes: ${totalChanges}`); } } else { console.log(' No grid API available'); } console.log(' Current connection:', this.currentConnection); console.log(' DEBUG SAVE BUTTON - Diagnostics complete'); } /** * Debug function to diagnose modal issues */ debugModal() { console.log(' DEBUG MODAL - Starting diagnostics...'); const modal = document.getElementById('connectionModal'); const form = document.getElementById('connectionForm'); const newConnectionBtn = document.getElementById('newConnectionBtn'); console.log(' Modal element:', modal); console.log(' Form element:', form); console.log(' New Connection button:', newConnectionBtn); if (modal) { const computedStyle = window.getComputedStyle(modal); console.log(' Modal classes:', modal.className); console.log(' Modal display:', computedStyle.display); console.log(' Modal visibility:', computedStyle.visibility); console.log(' Modal z-index:', computedStyle.zIndex); console.log(' Modal position:', computedStyle.position); // Try to force show modal console.log(' Force showing modal...'); modal.classList.add('active'); setTimeout(() => { const newStyle = window.getComputedStyle(modal); console.log(' After adding active - Display:', newStyle.display); if (newStyle.display === 'flex') { console.log(' Modal should be visible now'); this.showToast('success', 'Debug', 'Modal force shown'); } else { console.error(' Modal still not visible'); this.showToast('error', 'Debug', 'Modal failed to show - check CSS'); } }, 100); } else { console.error(' Modal element not found'); this.showToast('error', 'Debug', 'Modal element not found in DOM'); } console.log(' DEBUG MODAL - Diagnostics complete'); } // HTML Table fallback (DBeaver-style) renderHTMLTable(container, data, executionTime, tableName = 'Query Results') { console.log('Rendering HTML table fallback'); // Clear container container.innerHTML = ''; // Create wrapper const tableWrapper = document.createElement('div'); tableWrapper.className = 'table-wrapper dbeaver-style'; // Create toolbar const toolbar = document.createElement('div'); toolbar.className = 'table-toolbar enhanced'; toolbar.innerHTML = `
${tableName} ${data.rowCount || data.rows?.length || 0} rows • ${(data.columns || []).length} columns
`; // Create table container const tableContainer = document.createElement('div'); tableContainer.className = 'table-container scrollable'; const table = document.createElement('table'); table.className = 'data-table dbeaver-table'; table.setAttribute('data-table-name', tableName); table.setAttribute('data-editable', 'true'); // Create header const thead = document.createElement('thead'); const headerRow = document.createElement('tr'); // Row number column const rowNumHeader = document.createElement('th'); rowNumHeader.className = 'row-number-header sticky-column'; rowNumHeader.innerHTML = '#'; rowNumHeader.style.width = '60px'; headerRow.appendChild(rowNumHeader); // Data columns if (data.columns && data.columns.length > 0) { data.columns.forEach((column, index) => { const th = document.createElement('th'); th.className = 'sortable column-header'; th.setAttribute('data-column', index); th.innerHTML = `
${column}
`; th.addEventListener('click', () => this.sortTable(table, index + 1)); headerRow.appendChild(th); }); } thead.appendChild(headerRow); table.appendChild(thead); // Create body const tbody = document.createElement('tbody'); if (data.rows && data.rows.length > 0) { data.rows.forEach((row, rowIndex) => { const tr = document.createElement('tr'); tr.className = 'data-row'; tr.setAttribute('data-row-index', rowIndex); // Row number const rowNumCell = document.createElement('td'); rowNumCell.className = 'row-number sticky-column'; rowNumCell.textContent = rowIndex + 1; tr.appendChild(rowNumCell); // Data cells row.forEach((cell, cellIndex) => { const td = document.createElement('td'); td.className = 'data-cell'; td.setAttribute('data-column', cellIndex); td.setAttribute('data-column-name', data.columns[cellIndex]); td.setAttribute('data-original-value', cell); if (cell === null || cell === 'NULL' || cell === undefined) { td.className += ' null-value'; td.innerHTML = 'NULL'; } else if (typeof cell === 'string' && cell.length > 100) { td.className += ' long-text'; td.textContent = cell.substring(0, 100) + '...'; td.title = cell; } else { td.textContent = cell; } // Make cell editable td.addEventListener('dblclick', () => this.editCell(td)); td.addEventListener('contextmenu', (e) => this.showCellContextMenu(e, td)); tr.appendChild(td); }); tbody.appendChild(tr); }); } else if (data.columns && data.columns.length > 0) { // Empty row to show structure const emptyRow = document.createElement('tr'); emptyRow.className = 'empty-row'; const rowNumCell = document.createElement('td'); rowNumCell.className = 'row-number sticky-column'; rowNumCell.textContent = '1'; emptyRow.appendChild(rowNumCell); data.columns.forEach((column, cellIndex) => { const td = document.createElement('td'); td.className = 'data-cell null-value empty-cell'; td.setAttribute('data-column', cellIndex); td.setAttribute('data-column-name', column); td.setAttribute('data-original-value', null); td.innerHTML = 'NULL'; td.addEventListener('dblclick', () => this.editCell(td)); td.addEventListener('contextmenu', (e) => this.showCellContextMenu(e, td)); emptyRow.appendChild(td); }); tbody.appendChild(emptyRow); } table.appendChild(tbody); tableContainer.appendChild(table); // Results info const resultsInfo = document.createElement('div'); resultsInfo.className = 'results-info enhanced'; resultsInfo.innerHTML = `
Rows: ${data.rowCount || data.rows?.length || 0} ⏱ Load time: ${executionTime}ms No changes
Table: ${tableName} Columns: ${(data.columns || []).length}
`; // Assemble everything tableWrapper.appendChild(toolbar); tableWrapper.appendChild(tableContainer); tableWrapper.appendChild(resultsInfo); container.appendChild(tableWrapper); // Attach event listeners this.attachHTMLTableEventListeners(table, tableName); } attachHTMLTableEventListeners(table, tableName) { // Filter functionality const filterInput = document.getElementById('tableFilter'); if (filterInput) { filterInput.addEventListener('input', (e) => { this.filterTable(table, e.target.value); }); } // Clear filter const clearFilterBtn = document.getElementById('clearFilter'); if (clearFilterBtn) { clearFilterBtn.addEventListener('click', () => { if (filterInput) { filterInput.value = ''; this.filterTable(table, ''); } }); } // Other buttons const addRowBtn = document.getElementById('addRowBtn'); if (addRowBtn) { addRowBtn.addEventListener('click', () => { this.addNewRow(table); }); } const saveChangesBtn = document.getElementById('saveChangesBtn'); if (saveChangesBtn) { saveChangesBtn.addEventListener('click', () => { this.saveTableChanges(table, tableName); }); } const refreshBtn = document.getElementById('refreshTableBtn'); if (refreshBtn) { refreshBtn.addEventListener('click', () => { if (tableName !== 'Query Results') { // Use refreshTableData instead of loadTableInQueryTab this.refreshTableData(tableName); } else { this.executeQuery(); } }); } const exportBtn = document.getElementById('exportTableBtn'); if (exportBtn) { exportBtn.addEventListener('click', () => { this.exportTableData(table, tableName); }); } } // DBeaver-style functions for table management async refreshTableData(tableName) { if (!this.currentConnection) { this.showToast('error', this.t('No connection selected'), this.t('Please connect to a database first')); return; } try { this.showLoading(`กำลังรีเฟรชข้อมูลตาราง ${tableName}...`); // Check if there's an active table tab const tableTabId = `table_${tableName}`; if (this.tabs && this.tabs.has(tableTabId)) { // Refresh the table tab await this.loadTableData(tableTabId, tableName, 'table'); } else { // If no table tab, open a new one this.openTableTab(tableName); } this.showToast('success', 'รีเฟรชสำเร็จ', `ข้อมูลตาราง ${tableName} ถูกรีเฟรชแล้ว`); } catch (error) { console.error('Refresh table failed:', error); this.showToast('error', 'รีเฟรชล้มเหลว', error.message); } finally { this.hideLoading(); } } async importDataToTable(tableName) { if (!this.currentConnection) { this.showToast('error', this.t('No connection selected'), this.t('Please connect to a database first')); return; } // Create file input const fileInput = document.createElement('input'); fileInput.type = 'file'; fileInput.accept = '.sql,.csv,.json,.dump,.backup'; fileInput.style.display = 'none'; fileInput.addEventListener('change', async (event) => { const file = event.target.files[0]; if (!file) return; try { this.showLoading(`กำลังนำเข้าข้อมูลไปยังตาราง ${tableName}...`); const fileContent = await this.readFileContent(file); const fileExtension = file.name.split('.').pop().toLowerCase(); // Check if it's a PostgreSQL dump file const looksLikePgDump = fileContent.includes('PostgreSQL database dump') || fileContent.includes('SET statement_timeout') || ['dump', 'backup'].includes(fileExtension); if (looksLikePgDump) { // Use universal restore for PostgreSQL dumps this.showLoading('Restoring database via PostgreSQL tools...'); const buf = await file.arrayBuffer(); const contentBase64 = btoa(String.fromCharCode(...new Uint8Array(buf))); const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/restore`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ filename: file.name, contentBase64: contentBase64 }) }); const data = await response.json(); if (!data.success) { throw new Error(data.error || 'Restore failed'); } this.showToast('success', 'ใส่กลับสำเร็จ', 'นำเข้าไฟล์สำรองเรียบร้อย'); this.loadDatabaseStructure(this.currentConnection); return; } // Handle CSV/JSON files (existing logic) let importQuery = ''; switch (fileExtension) { case 'sql': // Simple SQL - still use query endpoint for INSERT statements if (!looksLikePgDump) { importQuery = fileContent; break; } // If it's a dump, fall through to error case 'csv': importQuery = await this.convertCSVToSQL(fileContent, tableName); break; case 'json': importQuery = await this.convertJSONToSQL(fileContent, tableName); break; default: throw new Error('ไม่รองรับไฟล์ประเภทนี้ กรุณาใช้ไฟล์ .sql, .csv, .json, .dump หรือ .backup'); } // Show confirmation before executing const confirmed = confirm(`คุณต้องการนำเข้าไฟล์ ${file.name} ไปยังตาราง ${tableName} หรือไม่?\n\nการดำเนินการนี้อาจเปลี่ยนแปลงข้อมูลในฐานข้อมูล`); if (!confirmed) { this.showToast('info', 'ยกเลิก', 'การนำเข้าข้อมูลถูกยกเลิก'); return; } // Execute import query for CSV/JSON/simple SQL const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/query`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: importQuery }) }); const data = await response.json(); if (data.success) { this.showToast('success', 'นำเข้าสำเร็จ', `นำเข้าข้อมูลไปยังตาราง ${tableName} เสร็จแล้ว`); this.refreshTableData(tableName); } else { throw new Error(data.error); } } catch (error) { console.error('Import failed:', error); this.showToast('error', 'นำเข้าล้มเหลว', error.message); } finally { this.hideLoading(); document.body.removeChild(fileInput); } }); document.body.appendChild(fileInput); fileInput.click(); } // Helper function to read file content readFileContent(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = e => resolve(e.target.result); reader.onerror = reject; reader.readAsText(file); }); } // Convert CSV to SQL with better parsing async convertCSVToSQL(csvContent, tableName) { const lines = csvContent.split('\n').filter(line => line.trim()); if (lines.length === 0) throw new Error('ไฟล์ CSV ว่างเปล่า'); // Better CSV parsing that handles quotes properly const parseCSVLine = (line) => { const result = []; let current = ''; let inQuotes = false; for (let i = 0; i < line.length; i++) { const char = line[i]; const nextChar = line[i + 1]; if (char === '"') { if (inQuotes && nextChar === '"') { // Escaped quote current += '"'; i++; // Skip next quote } else { // Toggle quote state inQuotes = !inQuotes; } } else if (char === ',' && !inQuotes) { // End of field result.push(current.trim()); current = ''; } else { current += char; } } // Add last field result.push(current.trim()); return result; }; const headers = parseCSVLine(lines[0]); const dbType = this.getCurrentDatabaseType(); const formattedTableName = this.formatSQLIdentifier(tableName, dbType); let sql = `-- CSV Import to ${tableName}\n-- Generated on: ${new Date().toISOString()}\n\n`; for (let i = 1; i < lines.length; i++) { const values = parseCSVLine(lines[i]).map(v => { if (v === '' || v === null || v === undefined) { return 'NULL'; } // ส่งค่าจริงไป formatSQLValue ไม่ใช่ string ที่ escape แล้ว return this.formatSQLValue(String(v), dbType); }); const columnsList = headers.map(h => this.formatSQLIdentifier(h, dbType)).join(', '); sql += `INSERT INTO ${formattedTableName} (${columnsList}) VALUES (${values.join(', ')});\n`; } return sql; } // Show modal for importing data to table showImportDataModal(tabId) { if (!this.currentConnection) { this.showToast('error', 'ไม่มีการเชื่อมต่อ', 'กรุณาเชื่อมต่อกับฐานข้อมูลก่อน'); return; } // Get available tables for selection const tables = this.getAvailableTables(); if (tables.length === 0) { this.showToast('warning', 'ไม่มีตาราง', 'ไม่พบตารางในฐานข้อมูล'); return; } // Create modal HTML const modalHTML = ` `; // Remove existing modal if present const existingModal = document.getElementById('importDataModal'); if (existingModal) { existingModal.remove(); } // Add modal to DOM document.body.insertAdjacentHTML('beforeend', modalHTML); // Add event listeners this.setupImportDataModalEvents(tabId); } // Get available tables from current database structure getAvailableTables() { const treeContainer = document.getElementById('databaseTree'); if (!treeContainer) return []; // Find all tree sections const sections = treeContainer.querySelectorAll('.tree-section'); for (const section of sections) { const header = section.querySelector('.tree-header strong'); if (header && header.textContent.startsWith('Tables')) { // This is the tables section const tableItems = section.querySelectorAll('.tree-item'); return Array.from(tableItems).map(item => { const labelElement = item.querySelector('.tree-label'); return labelElement ? labelElement.textContent.trim() : ''; }).filter(name => name.length > 0); } } return []; } // Setup event listeners for import data modal setupImportDataModalEvents(tabId) { const modal = document.getElementById('importDataModal'); const tableSelect = document.getElementById('targetTable'); const proceedBtn = document.getElementById('proceedImportBtn'); const optionCards = modal.querySelectorAll('.option-card'); let selectedTable = ''; let selectedMethod = ''; // Table selection tableSelect.addEventListener('change', (e) => { selectedTable = e.target.value; checkCanProceed(); }); // Method selection optionCards.forEach(card => { card.addEventListener('click', () => { // Remove active class from all cards optionCards.forEach(c => c.classList.remove('active')); // Add active class to selected card card.classList.add('active'); selectedMethod = card.dataset.method; checkCanProceed(); }); }); // Check if can proceed function checkCanProceed() { proceedBtn.disabled = !(selectedTable && selectedMethod); } // Proceed button proceedBtn.addEventListener('click', () => { this.executeImportMethod(tabId, selectedTable, selectedMethod); }); // Close modal handlers modal.querySelector('.modal-close').addEventListener('click', () => { this.hideImportDataModal(); }); // Cancel button modal.querySelector('#cancelImportBtn').addEventListener('click', () => { this.hideImportDataModal(); }); // Click outside to close modal.addEventListener('click', (e) => { if (e.target === modal) { this.hideImportDataModal(); } }); } // Hide import data modal hideImportDataModal() { const modal = document.getElementById('importDataModal'); if (modal) { modal.remove(); } } // Execute the selected import method async executeImportMethod(tabId, tableName, method) { this.hideImportDataModal(); switch (method) { case 'sql': this.generateInsertSQLTemplate(tabId, tableName); break; case 'csv': this.importDataFromCSV(tableName); break; case 'json': this.importDataFromJSON(tableName); break; case 'manual': this.openManualDataEntry(tableName); break; default: this.showToast('error', 'วิธีการไม่ถูกต้อง', 'วิธีการนำเข้าข้อมูลไม่ถูกต้อง'); } } // Generate SQL INSERT template for selected table async generateInsertSQLTemplate(tabId, tableName) { try { this.showLoading(`กำลังสร้างแม่แบบ SQL สำหรับตาราง ${tableName}...`); // Get table columns const columns = await this.getTableColumns(tableName); const textarea = document.getElementById(`queryTextarea_${tabId}`); if (!textarea) { throw new Error('ไม่พบ SQL Editor'); } // Generate INSERT template const columnNames = columns.join(', '); const valuePlaceholders = columns.map(() => 'NULL').join(', '); const insertTemplate = `-- เพิ่มข้อมูลเข้าตาราง ${tableName} -- แก้ไขค่า NULL เป็นข้อมูลจริงที่ต้องการเพิ่ม INSERT INTO ${this.formatSQLIdentifier(tableName, this.getCurrentDatabaseType())} (${columnNames}) VALUES (${valuePlaceholders}); -- ตัวอย่างการเพิ่มหลายแถว: -- INSERT INTO ${this.formatSQLIdentifier(tableName, this.getCurrentDatabaseType())} -- (${columnNames}) -- VALUES -- (${valuePlaceholders}), -- (${valuePlaceholders}), -- (${valuePlaceholders});`; // Add to existing query or replace if empty const currentQuery = textarea.value.trim(); if (currentQuery) { textarea.value = currentQuery + '\n\n' + insertTemplate; } else { textarea.value = insertTemplate; } // Focus and scroll to the template textarea.focus(); textarea.scrollTop = textarea.scrollHeight; this.showToast('success', 'สำเร็จ', `สร้างแม่แบบ SQL INSERT สำหรับตาราง ${tableName} แล้ว`); } catch (error) { console.error('Failed to generate SQL template:', error); this.showToast('error', 'ข้อผิดพลาด', error.message); } finally { this.hideLoading(); } } // Import data from CSV file async importDataFromCSV(tableName) { // Create file input const fileInput = document.createElement('input'); fileInput.type = 'file'; fileInput.accept = '.csv'; fileInput.style.display = 'none'; fileInput.addEventListener('change', async (event) => { const file = event.target.files[0]; if (!file) return; try { this.showLoading(`กำลังนำเข้าไฟล์ CSV เข้าตาราง ${tableName}...`); const fileContent = await this.readFileContent(file); const importQuery = await this.convertCSVToSQL(fileContent, tableName); // Show confirmation const confirmed = confirm(`คุณต้องการนำเข้าไฟล์ ${file.name} เข้าตาราง ${tableName} หรือไม่?\n\nการดำเนินการนี้จะเพิ่มข้อมูลใหม่เข้าไปในตาราง`); if (!confirmed) { this.showToast('info', 'ยกเลิก', 'การนำเข้าข้อมูลถูกยกเลิก'); return; } // Execute import query const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/query`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: importQuery }) }); const data = await response.json(); if (data.success) { // แสดงข้อมูลการ import ที่ละเอียดขึ้น const rowsAffected = data.data.rowCount || 0; this.showToast('success', 'นำเข้าสำเร็จ', `นำเข้าข้อมูลจากไฟล์ CSV เข้าตาราง ${tableName} สำเร็จ (${rowsAffected} แถว)`); // Refresh table data immediately after import await this.refreshTableIfOpen(tableName); // Also refresh the database tree to update row counts await this.loadDatabaseStructure(); } else { throw new Error(data.error); } } catch (error) { console.error('CSV import failed:', error); this.showToast('error', 'นำเข้าล้มเหลว', error.message); } finally { this.hideLoading(); document.body.removeChild(fileInput); } }); document.body.appendChild(fileInput); fileInput.click(); } // Import data from JSON file async importDataFromJSON(tableName) { // Create file input const fileInput = document.createElement('input'); fileInput.type = 'file'; fileInput.accept = '.json'; fileInput.style.display = 'none'; fileInput.addEventListener('change', async (event) => { const file = event.target.files[0]; if (!file) return; try { this.showLoading(`กำลังนำเข้าไฟล์ JSON เข้าตาราง ${tableName}...`); const fileContent = await this.readFileContent(file); const importQuery = await this.convertJSONToSQL(fileContent, tableName); // Show confirmation const confirmed = confirm(`คุณต้องการนำเข้าไฟล์ ${file.name} เข้าตาราง ${tableName} หรือไม่?\n\nการดำเนินการนี้จะเพิ่มข้อมูลใหม่เข้าไปในตาราง`); if (!confirmed) { this.showToast('info', 'ยกเลิก', 'การนำเข้าข้อมูลถูกยกเลิก'); return; } // Execute import query const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/query`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: importQuery }) }); const data = await response.json(); if (data.success) { // แสดงข้อมูลการ import ที่ละเอียดขึ้น const rowsAffected = data.data.rowCount || 0; this.showToast('success', 'นำเข้าสำเร็จ', `นำเข้าข้อมูลจากไฟล์ JSON เข้าตาราง ${tableName} สำเร็จ (${rowsAffected} แถว)`); // Refresh table data immediately after import await this.refreshTableIfOpen(tableName); // Also refresh the database tree to update row counts await this.loadDatabaseStructure(); } else { throw new Error(data.error); } } catch (error) { console.error('JSON import failed:', error); this.showToast('error', 'นำเข้าล้มเหลว', error.message); } finally { this.hideLoading(); document.body.removeChild(fileInput); } }); document.body.appendChild(fileInput); fileInput.click(); } // Open manual data entry form openManualDataEntry(tableName) { this.showToast('info', 'เร็วๆ นี้', 'ฟีเจอร์เพิ่มข้อมูลด้วยมือจะมาเร็วๆ นี้'); // TODO: Implement manual data entry form } // Refresh table if it's currently open in a tab async refreshTableIfOpen(tableName) { const tableTabId = `table_${tableName}`; if (this.tabs && this.tabs.has(tableTabId)) { console.log(` Refreshing table data for: ${tableName}`); await this.loadTableData(tableTabId, tableName, 'table'); this.showToast('info', 'ข้อมูลอัปเดต', `ข้อมูลตาราง ${tableName} ได้รับการอัปเดตแล้ว`); } else { console.log(`ℹ Table ${tableName} is not currently open in any tab`); } } // Convert JSON to SQL async convertJSONToSQL(jsonContent, tableName) { try { const data = JSON.parse(jsonContent); const dbType = this.getCurrentDatabaseType(); const formattedTableName = this.formatSQLIdentifier(tableName, dbType); let sql = `-- JSON Import to ${tableName}\n-- Generated on: ${new Date().toISOString()}\n\n`; if (Array.isArray(data)) { data.forEach((row, index) => { const columns = Object.keys(row); const values = Object.values(row).map(v => this.formatSQLValue(v, dbType)); const columnsList = columns.map(h => this.formatSQLIdentifier(h, dbType)).join(', '); sql += `INSERT INTO ${formattedTableName} (${columnsList}) VALUES (${values.join(', ')});\n`; }); } else { // Single object const columns = Object.keys(data); const values = Object.values(data).map(v => this.formatSQLValue(v, dbType)); const columnsList = columns.map(h => this.formatSQLIdentifier(h, dbType)).join(', '); sql += `INSERT INTO ${formattedTableName} (${columnsList}) VALUES (${values.join(', ')});\n`; } return sql; } catch (error) { throw new Error('ไฟล์ JSON ไม่ถูกต้อง: ' + error.message); } } /** * Database Template System - Initialize database schema */ async runPluginSetup(plugin) { if (!this.currentConnection) { this.showToast('error', 'ไม่ได้เลือกการเชื่อมต่อ', 'กรุณาเลือกการเชื่อมต่อฐานข้อมูลก่อน'); return; } const connection = this.connections.find(c => c.id === this.currentConnection); if (!connection) { this.showToast('error', 'Connection Error', 'Connection details not found'); return; } // ตรวจสอบว่าปลั๊กอินรองรับประเภทฐานข้อมูลนี้หรือไม่ if (!plugin.supportedDatabases.includes(connection.type)) { this.showToast('error', 'Unsupported Database', `Plugin '${plugin.displayName}' does not support ${connection.type} database.\n\n` + `Supported databases: ${plugin.supportedDatabases.join(', ')}` ); return; } // ให้เลือกว่าจะเพิ่มไฟล์ SQL หรือไม่ const setupMode = confirm( `Initialize Database Schema: ${plugin.displayName}\n\n` + `Step 1: Create database structure (modules)\n` + `Step 2: Import additional data (optional)\n\n` + `Database: ${connection.database}\n` + `Server: ${connection.host}:${connection.port}\n\n` + `[OK] = Create structure + ask for data file\n` + `[Cancel] = Create structure only\n\n` + `Continue?` ); if (setupMode === null) return; // User cancelled completely const shouldImportData = setupMode; // true = ask for file, false = structure only try { this.showLoading(`Creating database structure: ${plugin.displayName}...`); // Step 1: สร้างโครงสร้างด้วย modules scripts const response = await fetch(`http://localhost:${this.serverPort}/api/plugins/${plugin.name}/setup`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ connectionId: this.currentConnection }) }); const result = await response.json(); if (result.success) { const summary = result.summary || {}; this.showToast('success', ` Schema Created: ${plugin.displayName}`, `${result.message}\n\n` + ` Total Tables: ${summary.totalTables || 'N/A'}\n` + ` New Tables: ${summary.newTables || 'N/A'}` ); // รีเฟรช database structure if (this.currentConnection) { setTimeout(() => { this.loadDatabaseStructure(this.currentConnection); }, 1000); } // Step 2: ถ้าเลือกจะ import ข้อมูลเสริม if (shouldImportData) { setTimeout(() => { const importConfirm = confirm( ` Database schema created successfully!\n\n` + `Step 2: Import additional data from backup SQL file?\n\n` + ` Select a .sql file that was previously exported\n` + `� This will add data to the existing tables\n\n` + `Continue with file import?` ); if (importConfirm) { this.showFileImportDialog(plugin); } }, 2000); } } else { throw new Error(result.error || 'Plugin execution failed'); } } catch (error) { console.error('Plugin setup failed:', error); this.showToast('error', ' Plugin Failed', `Plugin '${plugin.displayName}' failed to execute:\n\n${error.message}` ); } finally { this.hideLoading(); } } /** * Database Export System - Export database to SQL file */ async runPluginSQLDump(plugin) { if (!this.currentConnection) { this.showToast('error', 'ไม่ได้เลือกการเชื่อมต่อ', 'กรุณาเลือกการเชื่อมต่อฐานข้อมูลก่อน'); return; } const connection = this.connections.find(c => c.id === this.currentConnection); if (!connection) { this.showToast('error', 'Connection Error', 'Connection details not found'); return; } // ตรวจสอบว่าปลั๊กอินรองรับ SQL dump หรือไม่ if (!plugin.ui || !plugin.ui.allowSQLDump) { this.showToast('error', 'ฟีเจอร์ไม่รองรับ', `Plugin '${plugin.displayName}' does not support SQL dump functionality.` ); return; } const confirmed = confirm( ` SQL Dump: ${plugin.displayName}\n\n` + `Description: ${plugin.description}\n` + `Version: ${plugin.version}\n` + `Author: ${plugin.author}\n\n` + `This will dump database tables to SQL files from:\n` + ` Database: ${connection.database}\n` + ` Server: ${connection.host}:${connection.port}\n\n` + ` This operation will read table data and generate INSERT statements.\n` + `Continue?` ); if (!confirmed) return; try { this.showLoading(`กำลัง Dump ข้อมูล: ${plugin.displayName}...`); const response = await fetch(`http://localhost:${this.serverPort}/api/plugins/${plugin.name}/dump-sql`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ connectionId: this.currentConnection // tableName: null // dump all tables }) }); const result = await response.json(); if (result.success) { const data = result.data || {}; const message = data.filesCreated ? `สร้างไฟล์ SQL สำเร็จ:\n${data.filesCreated.join('\n')}` : data.message || 'SQL dump completed successfully'; this.showToast('success', ` SQL Dump Success: ${plugin.displayName}`, `${message}\n\n` + ` Files created: ${data.filesCreated?.length || 0}` ); } else { throw new Error(result.error || 'SQL dump failed'); } } catch (error) { console.error('SQL dump failed:', error); this.showToast('error', ' SQL Dump Failed', `SQL dump for '${plugin.displayName}' failed:\n\n${error.message}` ); } finally { this.hideLoading(); } } /** * � Get Active Tab */ getActiveTab() { const activeTabElement = document.querySelector('.tab-button.active'); if (activeTabElement) { const tabId = activeTabElement.getAttribute('data-tab-id'); return this.tabs.get(tabId); } return null; } /** * Render Table CRUD Actions Bar */ renderTableCRUDActions(container, tableName) { const actionsBar = document.createElement('div'); actionsBar.className = 'table-actions'; actionsBar.innerHTML = ` Table: ${tableName} `; container.insertBefore(actionsBar, container.firstChild); } /** * Show Add Row Form */ async showAddRowForm(tableName) { try { const columns = await this.getTableColumns(tableName); this.showRowEditForm(tableName, null, columns); } catch (error) { console.error('Failed to load table columns:', error); this.showToast('error', 'Error', 'Failed to load table structure'); } } /** * Show Edit Row Form */ async showEditRowForm(tableName, rowData) { try { const columns = await this.getTableColumns(tableName); this.showRowEditForm(tableName, rowData, columns); } catch (error) { console.error('Failed to load table columns:', error); this.showToast('error', 'Error', 'Failed to load table structure'); } } /** * Refresh Table Data */ // FIXED: แก้ไขฟังก์ชัน refreshTableData ให้ทำงานถูกต้อง async refreshTableData(tableName) { console.log(` Refreshing table data for: ${tableName}`); if (!this.currentConnection) { this.showToast('error', 'ไม่มีการเชื่อมต่อ', 'กรุณาเชื่อมต่อฐานข้อมูลก่อน'); return; } try { this.showLoading(` กำลังรีเฟรชตาราง ${tableName}...`); // หา active tab ปัจจุบัน const activeTab = this.getActiveTab(); if (activeTab && this.currentTable === tableName) { // รีเฟรชใน tab ที่มีอยู่ console.log(` Refreshing in active tab: ${activeTab.id}`); await this.loadTableData(activeTab.id, tableName, 'table'); } else { // หา table tab ที่เกี่ยวข้อง const tableTabId = `table_${tableName}`; if (this.tabs && this.tabs.has(tableTabId)) { console.log(` Refreshing in table tab: ${tableTabId}`); await this.loadTableData(tableTabId, tableName, 'table'); // เปลี่ยนไปที่ tab นั้น this.switchToTab(tableTabId); } else { // สร้าง tab ใหม่ console.log(` Creating new table tab for: ${tableName}`); this.openTableTab(tableName); } } this.showToast('success', 'รีเฟรชสำเร็จ', `ตาราง ${tableName} ถูกรีเฟรชแล้ว`); } catch (error) { console.error(' Refresh table failed:', error); this.showToast('error', 'รีเฟรชล้มเหลว', error.message); } finally { this.hideLoading(); } } /** * Table CRUD Operations - Get Table Columns */ async getTableColumns(tableName) { try { if (!this.currentConnection) { throw new Error('No active connection'); } const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/tables/${tableName}/columns`); const result = await response.json(); if (!response.ok || !result.success) { throw new Error(result.error || 'Failed to get table columns'); } return result.columns; } catch (error) { console.error('Get table columns failed:', error); throw error; } } /** * Find Primary Key column from table columns * @param {Array} columns - Array of column objects from getTableColumns * @returns {string|null} Primary key column name or null if not found * @description Finds the primary key column by checking isPrimaryKey property first, then fallback to 'id' column, then first column */ findPrimaryKey(columns) { if (!columns || !Array.isArray(columns)) return null; // หา column ที่มี isPrimaryKey = true ก่อน const pkColumn = columns.find(col => col.isPrimaryKey === true); if (pkColumn) return pkColumn.name; // ถ้าไม่เจอ ให้ลองหาจากชื่อ column ที่เป็น 'id' (เป็น Fallback) const idColumn = columns.find(col => col.name && col.name.toLowerCase() === 'id'); if (idColumn) return idColumn.name; // ถ้าไม่เจอเลยจริงๆ ให้ใช้คอลัมน์แรก return columns.length > 0 ? columns[0].name : null; } /** * Table CRUD Operations - Insert New Row */ async insertTableRow(tableName, rowData) { try { if (!this.currentConnection) { throw new Error('No active connection'); } const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/tables/${tableName}/rows`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ data: rowData }) }); const result = await response.json(); if (!response.ok || !result.success) { throw new Error(result.error || 'Failed to insert row'); } console.log(' Row inserted successfully:', result.data); return true; // สำเร็จ } catch (error) { console.error('Insert row failed:', error); return false; // ล้มเหลว } } /** * Table CRUD Operations - Update Existing Row */ async updateTableRow(tableName, rowId, rowData, primaryKey) { try { if (!this.currentConnection) { throw new Error('No active connection'); } if (!primaryKey) { throw new Error('Primary key name is required'); } const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/tables/${tableName}/rows/${rowId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ data: rowData, primaryKey }) }); const result = await response.json(); if (!response.ok || !result.success) { throw new Error(result.error || 'Failed to update row'); } return result.data; } catch (error) { console.error('Update row failed:', error); throw error; } } /** * Table CRUD Operations - Delete Row */ async deleteTableRow(tableName, rowId, primaryKey) { try { if (!this.currentConnection) { throw new Error('No active connection'); } if (!primaryKey) { throw new Error('Primary key name is required'); } const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/tables/${tableName}/rows/${rowId}`, { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ primaryKey }) }); const result = await response.json(); if (!response.ok || !result.success) { throw new Error(result.error || 'Failed to delete row'); } return result.data; } catch (error) { console.error('Delete row failed:', error); throw error; } } /** * Show Row Edit Form */ showRowEditForm(tableName, rowData = null, columns = []) { const isEdit = rowData !== null; const modalTitle = isEdit ? ` แก้ไขข้อมูลใน ${tableName}` : ` เพิ่มข้อมูลใหม่ใน ${tableName}`; // Calculate rowId if editing let rowId = ''; if (isEdit && rowData) { rowId = this.getRowId(rowData); } const formFields = columns.map(col => { const value = isEdit ? (rowData[col.name] || '') : ''; const required = !col.nullable ? 'required' : ''; return `
`; }).join(''); const modalHTML = ` `; document.body.insertAdjacentHTML('beforeend', modalHTML); } /** * Get Row ID from row data */ getRowId(rowData) { if (!rowData) return ''; // Try common primary key fields const pkCandidates = ['id', 'ID', 'pk', 'PK', 'primary_key']; for (const candidate of pkCandidates) { if (rowData[candidate] !== null && rowData[candidate] !== undefined) { return rowData[candidate]; } } // Fallback to first non-null field const keys = Object.keys(rowData); for (const key of keys) { if (rowData[key] !== null && rowData[key] !== undefined) { return rowData[key]; } } return ''; } /** * Close Row Edit Modal */ closeRowEditModal() { const modal = document.getElementById('rowEditModal'); if (modal) { modal.remove(); } } /** * Submit Row Form */ async submitRowForm(tableName, isEdit, rowId) { const form = document.getElementById('rowEditForm'); if (!form) { this.showToast('error', 'ข้อผิดพลาด', 'ไม่พบฟอร์ม'); return; } const formData = new FormData(form); try { this.showLoading(isEdit ? 'กำลังอัปเดตข้อมูล...' : 'กำลังเพิ่มข้อมูลใหม่...'); // Build the data object const data = {}; for (let [key, value] of formData.entries()) { // Handle empty values as NULL data[key] = value.trim() === '' ? null : value.trim(); } let query; const dbType = this.getCurrentDatabaseType(); const formattedTableName = this.formatSQLIdentifier(tableName, dbType); if (isEdit && rowId) { // Try to determine primary key column let primaryKeyColumn = 'id'; try { const columns = await this.getTableColumns(tableName); const pkCandidates = ['id', 'ID', 'pk', 'PK', 'primary_key']; for (const candidate of pkCandidates) { if (columns.find(col => col.name === candidate)) { primaryKeyColumn = candidate; break; } } } catch (error) { console.warn('Could not get table columns for primary key detection:', error); } // Update query const setClause = Object.keys(data).map(key => `${this.formatSQLIdentifier(key, dbType)} = ${this.formatSQLValue(data[key], dbType)}` ).join(', '); query = `UPDATE ${formattedTableName} SET ${setClause} WHERE ${this.formatSQLIdentifier(primaryKeyColumn, dbType)} = ${this.formatSQLValue(rowId, dbType)};`; } else { // Insert query const columns = Object.keys(data).map(k => this.formatSQLIdentifier(k, dbType)).join(', '); const values = Object.values(data).map(v => this.formatSQLValue(v, dbType)).join(', '); query = `INSERT INTO ${formattedTableName} (${columns}) VALUES (${values});`; } console.log('Executing query:', query); // Execute the query const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/query`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query }) }); const result = await response.json(); if (result.success) { this.showToast('success', isEdit ? 'อัปเดตสำเร็จ' : 'เพิ่มสำเร็จ', `${isEdit ? 'อัปเดต' : 'เพิ่ม'}ข้อมูลแถวเรียบร้อยแล้ว`); this.closeRowEditModal(); await this.refreshCurrentTable(); } else { throw new Error(result.error || 'เกิดข้อผิดพลาดในการบันทึก'); } } catch (error) { console.error('Failed to save row:', error); this.showToast('error', 'บันทึกล้มเหลว', error.message); } finally { this.hideLoading(); } } // ============================================= // NEW KEYBOARD SHORTCUT FUNCTIONS // ============================================= /** * Save current table changes (called by Ctrl+S) */ saveCurrentTableChanges() { if (this.currentGridApi) { // Try to get current table name from grid const tableName = this.currentTable || 'current_table'; this.saveGridChanges(tableName); } else { // Try to find current HTML table and save changes const table = document.querySelector('.data-table'); const tableName = this.currentTable || 'current_table'; if (table) { this.saveTableChanges(table, tableName); } } } /** * Refresh current table (called by F5 or Ctrl+R) */ refreshCurrentTable() { if (this.currentTable) { this.refreshTableData(this.currentTable); } else { // Find active table tab and refresh it for (const [tabId, tab] of this.tabs) { if (tabId.startsWith('table_') && tab.isActive) { const tableName = tabId.replace('table_', ''); this.refreshTableData(tableName); break; } } } } /** * Edit current row (called by F2) */ async editCurrentRow() { if (this.currentGridApi) { // Get focused cell in AG Grid const focusedCell = this.currentGridApi.getFocusedCell(); if (focusedCell) { const rowNode = this.currentGridApi.getDisplayedRowAtIndex(focusedCell.rowIndex); if (rowNode && rowNode.data) { await this.showEditRowForm(this.currentTable, rowNode.data); } } } else { // Handle HTML table const activeCell = document.activeElement; if (activeCell && activeCell.tagName === 'TD') { const row = activeCell.closest('tr'); if (row) { this.editCell(activeCell); } } } } /** * Update action button states based on selection * @returns {void} * @description Updates delete and edit button states based on row selection */ updateActionButtonStates() { if (!this.currentGridApi) return; const selectedNodes = this.currentGridApi.getSelectedNodes(); const deleteBtn = document.getElementById('deleteSelectedBtn'); const editBtn = document.getElementById('editSelectedBtn'); if (deleteBtn) { deleteBtn.disabled = selectedNodes.length === 0; } if (editBtn) { editBtn.disabled = selectedNodes.length !== 1; // Edit only works with single selection } } /** * Delete selected rows from grid * @returns {void} * @description Marks selected rows for deletion */ deleteSelectedRows() { if (!this.currentGridApi) { this.showToast('warning', 'ไม่มี Grid', 'ไม่พบตารางข้อมูล'); return; } const selectedNodes = this.currentGridApi.getSelectedNodes(); if (selectedNodes.length === 0) { this.showToast('warning', 'ไม่มีแถวที่เลือก', 'กรุณาเลือกแถวที่ต้องการลบก่อน'); return; } const confirmed = confirm(`คุณต้องการทำเครื่องหมายลบ ${selectedNodes.length} แถวนี้หรือไม่?\n\nแถวจะถูกลบจริงเมื่อกดปุ่ม " บันทึก"`); if (!confirmed) return; // ทำเครื่องหมายแถวที่เลือกไว้เพื่อรอการลบ selectedNodes.forEach(node => { if (node.data) { // เพิ่ม flag `_isDeleted` เพื่อบอกให้ `saveGridChanges` รู้ว่าต้องลบ const updatedData = { ...node.data, _isDeleted: true }; node.setData(updatedData); } }); // รีเฟรชแถวเพื่อให้ CSS ทำงาน this.currentGridApi.refreshCells({ rowNodes: selectedNodes, force: true }); // ใช้ setTimeout เพื่อให้ AG Grid มีเวลาอัปเดต data ก่อน setTimeout(() => { this.markGridAsModified(); // อัปเดตสถานะให้ปุ่ม Save กดได้ this.updateActionButtonStates(); // อัปเดตสถานะปุ่ม }, 10); this.showToast('info', 'ทำเครื่องหมายเพื่อลบ', `${selectedNodes.length} แถวถูกทำเครื่องหมายเพื่อลบ กรุณากด " บันทึก" เพื่อยืนยัน`); } /** * Edit selected row * @returns {void} * @description Start editing the selected row */ editSelectedRow() { if (!this.currentGridApi) { this.showToast('warning', 'ไม่มี Grid', 'ไม่พบตารางข้อมูล'); return; } const selectedNodes = this.currentGridApi.getSelectedNodes(); if (selectedNodes.length === 0) { this.showToast('warning', 'ไม่มีแถวที่เลือก', 'กรุณาเลือกแถวที่ต้องการแก้ไขก่อน'); return; } if (selectedNodes.length > 1) { this.showToast('warning', 'เลือกหลายแถว', 'กรุณาเลือกแถวเดียวเท่านั้นสำหรับการแก้ไข'); return; } const rowNode = selectedNodes[0]; // ถ้าเป็นแถวที่ถูกมาร์คให้ลบแล้ว ให้ยกเลิกการลบ if (rowNode.data._isDeleted) { const confirmed = confirm('แถวนี้ถูกมาร์คให้ลบแล้ว คุณต้องการยกเลิกการลบและแก้ไขหรือไม่?'); if (confirmed) { const updatedData = { ...rowNode.data }; delete updatedData._isDeleted; rowNode.setData(updatedData); this.currentGridApi.refreshCells({ rowNodes: [rowNode], force: true }); this.markGridAsModified(); this.showToast('info', 'ยกเลิกการลบ', 'ยกเลิกการลบแถวแล้ว สามารถแก้ไขได้'); } return; } // โฟกัสที่เซลล์แรกและเริ่มแก้ไข const columnDefs = this.currentGridApi.getColumnDefs(); const firstEditableColumn = columnDefs.find(col => col.field && col.editable !== false); if (firstEditableColumn) { this.currentGridApi.setFocusedCell(rowNode.rowIndex, firstEditableColumn.field); this.currentGridApi.startEditingCell({ rowIndex: rowNode.rowIndex, colKey: firstEditableColumn.field }); } } /** * Debug function to test AG Grid functions * @returns {void} * @description Function to test various AG Grid operations for debugging */ debugAGGridFeatures() { console.log(' Debug AG Grid Features'); if (!this.currentGridApi) { console.warn(' No current Grid API found'); this.showToast('warning', 'Debug', 'ไม่พบ AG Grid API'); return; } console.log(' Current Grid API:', this.currentGridApi); // Test row count const rowCount = this.currentGridApi.getDisplayedRowCount(); console.log(` Row count: ${rowCount}`); // Test selected rows const selectedNodes = this.currentGridApi.getSelectedNodes(); console.log(` Selected rows: ${selectedNodes.length}`); // Test changes let changeStats = { new: 0, modified: 0, deleted: 0 }; this.currentGridApi.forEachNode(node => { if (node && node.data) { if (node.data._isNew) changeStats.new++; if (node.data._isDirty) changeStats.modified++; if (node.data._isDeleted) changeStats.deleted++; } }); console.log(' Change stats:', changeStats); // Show results const message = `Grid Debug Info: Rows: ${rowCount} Selected: ${selectedNodes.length} Changes: ${changeStats.new} new, ${changeStats.modified} modified, ${changeStats.deleted} deleted`; this.showToast('info', 'Debug Results', message); } /** * Copy row data to clipboard (used by context menu) * @param {Object} rowNode - AG Grid row node * @returns {void} */ copyRowData(rowNode) { if (!rowNode || !rowNode.data) { this.showToast('error', 'Error', 'ไม่พบข้อมูลแถวที่ต้องการคัดลอก'); return; } // คัดลอกข้อมูลทั้งแถวเป็น JSON const rowDataCopy = { ...rowNode.data }; // ลบข้อมูล internal flags delete rowDataCopy._isNew; delete rowDataCopy._isDirty; delete rowDataCopy._isDeleted; const jsonString = JSON.stringify(rowDataCopy, null, 2); navigator.clipboard.writeText(jsonString).then(() => { this.showToast('success', 'คัดลอกแล้ว', 'คัดลอกข้อมูลแถวเป็น JSON แล้ว'); }).catch(err => { console.error('Failed to copy row data:', err); this.showToast('error', 'Error', 'ไม่สามารถคัดลอกข้อมูลได้'); }); } /** * Duplicate row data (used by context menu) * @param {Object} rowNode - AG Grid row node * @returns {void} */ duplicateRowData(rowNode) { if (!rowNode || !rowNode.data) { this.showToast('error', 'Error', 'ไม่พบข้อมูลแถวที่ต้องการทำสำเนา'); return; } // สร้างข้อมูลใหม่จากแถวที่เลือก const duplicatedData = { ...rowNode.data }; // ลบ ID และ internal flags delete duplicatedData.id; delete duplicatedData._isNew; delete duplicatedData._isDirty; delete duplicatedData._isDeleted; // เพิ่ม flag ว่าเป็นแถวใหม่ duplicatedData._isNew = true; // ได้ table name const activeTab = document.querySelector('.tab-pane.active'); const tableName = activeTab ? activeTab.getAttribute('data-table') : 'unknown'; const normalizedData = this.normalizeRowData(duplicatedData, tableName); // เพิ่มแถวใหม่ลงใน grid this.currentGridApi.applyTransaction({ add: [normalizedData] }); this.markGridAsModified(); // เลื่อนไปที่แถวใหม่และเลือก setTimeout(() => { const rowCount = this.currentGridApi.getDisplayedRowCount(); this.currentGridApi.ensureIndexVisible(rowCount - 1); const newRowNode = this.currentGridApi.getDisplayedRowAtIndex(rowCount - 1); if (newRowNode) { this.currentGridApi.deselectAll(); newRowNode.setSelected(true); // Auto-focus first editable cell const columnDefs = this.currentGridApi.getColumnDefs(); const firstEditableColumn = columnDefs.find(col => col.field && col.editable !== false); if (firstEditableColumn) { this.currentGridApi.setFocusedCell(rowCount - 1, firstEditableColumn.field); } } }, 100); this.showToast('success', 'ทำสำเนาแล้ว', 'ทำสำเนาแถวแล้ว กรุณาแก้ไขข้อมูลและกด " บันทึก"'); } /** * Cancel AG Grid changes and revert to original state * @param {string} tableName - Name of the table to cancel changes for * @returns {void} * @description Cancels all unsaved changes and refreshes the grid to original state */ cancelGridChanges(tableName) { if (!this.currentGridApi) { this.showToast('error', 'ไม่มี Grid', 'ไม่มีข้อมูลให้ยกเลิก'); return; } // Check if there are any changes to cancel let hasChanges = false; this.currentGridApi.forEachNode(node => { if (node && node.data && (node.data._isNew || node.data._isDirty || node.data._isDeleted)) { hasChanges = true; return false; // break the loop } }); if (!hasChanges) { this.showToast('info', 'ไม่มีการเปลี่ยนแปลง', 'ไม่มีการเปลี่ยนแปลงให้ยกเลิก'); return; } const confirmed = confirm(`คุณต้องการยกเลิกการเปลี่ยนแปลงทั้งหมดในตาราง ${tableName} หรือไม่?\n\nการเปลี่ยนแปลงทั้งหมดจะหายไป`); if (!confirmed) return; // Refresh table data to restore original state this.refreshTableData(tableName); this.showToast('success', 'ยกเลิกแล้ว', 'ยกเลิกการเปลี่ยนแปลงและรีเฟรชตารางแล้ว'); } /** * Delete row from grid by row ID (called from action button) */ deleteRowFromGrid(rowId) { if (!this.currentGridApi) { this.showToast('error', 'Error', 'ไม่พบตารางข้อมูล'); return; } const rowNode = this.currentGridApi.getRowNode(String(rowId)); if (!rowNode) { this.showToast('error', 'Error', 'ไม่พบแถวที่ต้องการลบ'); return; } const confirmed = confirm(`คุณต้องการลบแถวนี้หรือไม่?\n\nแถวจะถูกลบจริงเมื่อกดปุ่ม " บันทึก"`); if (!confirmed) return; // ทำเครื่องหมายแถวที่เลือกไว้เพื่อรอการลบ if (rowNode.data) { const updatedData = { ...rowNode.data, _isDeleted: true }; rowNode.setData(updatedData); } // รีเฟรชแถวเพื่อให้ CSS ทำงาน this.currentGridApi.refreshCells({ rowNodes: [rowNode], force: true }); // ใช้ setTimeout เพื่อให้ AG Grid มีเวลาอัปเดต data ก่อน setTimeout(() => { this.markGridAsModified(); // อัปเดตสถานะให้ปุ่ม Save กดได้ }, 10); this.showToast('info', 'ทำเครื่องหมายเพื่อลบ', 'แถวถูกทำเครื่องหมายเพื่อลบ กรุณากด " บันทึก" เพื่อยืนยัน'); } /** * Edit row from grid by row ID (called from action button) */ editRowFromGrid(rowId) { if (!this.currentGridApi) { this.showToast('error', 'Error', 'ไม่พบตารางข้อมูล'); return; } const rowNode = this.currentGridApi.getRowNode(String(rowId)); if (!rowNode || !rowNode.data) { this.showToast('error', 'Error', 'ไม่พบแถวที่ต้องการแก้ไข'); return; } // ถ้าเป็นแถวที่ถูกมาร์คให้ลบแล้ว ให้ยกเลิกการลบ if (rowNode.data._isDeleted) { const confirmed = confirm('แถวนี้ถูกมาร์คให้ลบแล้ว คุณต้องการยกเลิกการลบและแก้ไขหรือไม่?'); if (confirmed) { const updatedData = { ...rowNode.data }; delete updatedData._isDeleted; rowNode.setData(updatedData); this.currentGridApi.refreshCells({ rowNodes: [rowNode], force: true }); this.markGridAsModified(); this.showToast('info', 'ยกเลิกการลบ', 'ยกเลิกการลบแถวแล้ว สามารถแก้ไขได้'); } return; } // เลือกแถวและโฟกัสที่เซลล์แรก rowNode.setSelected(true); const columnDefs = this.currentGridApi.getColumnDefs(); const firstEditableColumn = columnDefs.find(col => col.field && col.field !== 'actions' && col.editable !== false); if (firstEditableColumn) { this.currentGridApi.setFocusedCell(rowNode.rowIndex, firstEditableColumn.field); this.currentGridApi.startEditingCell({ rowIndex: rowNode.rowIndex, colKey: firstEditableColumn.field }); } } /** * Copy row from grid by row ID (called from context menu) */ copyRowFromGrid(rowId) { if (!this.currentGridApi) { this.showToast('error', 'Error', 'ไม่พบตารางข้อมูล'); return; } const rowNode = this.currentGridApi.getRowNode(String(rowId)); if (!rowNode || !rowNode.data) { this.showToast('error', 'Error', 'ไม่พบแถวที่ต้องการคัดลอก'); return; } // คัดลอกข้อมูลทั้งแถวเป็น JSON const rowDataCopy = { ...rowNode.data }; // ลบข้อมูล internal flags delete rowDataCopy._isNew; delete rowDataCopy._isDirty; delete rowDataCopy._isDeleted; delete rowDataCopy.actions; const jsonString = JSON.stringify(rowDataCopy, null, 2); navigator.clipboard.writeText(jsonString).then(() => { this.showToast('success', 'คัดลอกแล้ว', 'คัดลอกข้อมูลแถวเป็น JSON แล้ว'); }).catch(err => { console.error('Failed to copy row data:', err); this.showToast('error', 'Error', 'ไม่สามารถคัดลอกข้อมูลได้'); }); } /** * Duplicate row from grid by row ID (called from context menu) */ duplicateRowFromGrid(rowId) { if (!this.currentGridApi) { this.showToast('error', 'Error', 'ไม่พบตารางข้อมูล'); return; } const rowNode = this.currentGridApi.getRowNode(String(rowId)); if (!rowNode || !rowNode.data) { this.showToast('error', 'Error', 'ไม่พบแถวที่ต้องการทำสำเนา'); return; } // สร้างข้อมูลใหม่จากแถวที่เลือก const duplicatedData = { ...rowNode.data }; // ลบ ID และ internal flags delete duplicatedData.id; delete duplicatedData._isNew; delete duplicatedData._isDirty; delete duplicatedData._isDeleted; delete duplicatedData.actions; // เพิ่ม flag ว่าเป็นแถวใหม่ duplicatedData._isNew = true; // ได้ table name const activeTab = document.querySelector('.tab-pane.active'); const tableName = activeTab ? activeTab.getAttribute('data-table') : 'unknown'; const normalizedData = this.normalizeRowData(duplicatedData, tableName); // เพิ่มแถวใหม่ลงใน grid this.currentGridApi.applyTransaction({ add: [normalizedData] }); this.markGridAsModified(); // เลื่อนไปที่แถวใหม่และเลือก setTimeout(() => { const rowCount = this.currentGridApi.getDisplayedRowCount(); this.currentGridApi.ensureIndexVisible(rowCount - 1); const newRowNode = this.currentGridApi.getDisplayedRowAtIndex(rowCount - 1); if (newRowNode) { newRowNode.setSelected(true); // Auto-focus first editable cell const columnDefs = this.currentGridApi.getColumnDefs(); const firstEditableColumn = columnDefs.find(col => col.field && col.field !== 'actions' && col.editable !== false); if (firstEditableColumn) { this.currentGridApi.setFocusedCell(rowCount - 1, firstEditableColumn.field); } } }, 100); this.showToast('success', 'ทำสำเนาแล้ว', 'ทำสำเนาแถวแล้ว กรุณาแก้ไขข้อมูลและกด " บันทึก"'); } /** * Delete current row (called by Delete key) */ async deleteCurrentRow() { if (!this.currentGridApi) { this.showToast('warning', 'ไม่มี Grid', 'ไม่พบตารางข้อมูล'); return; } const selectedNodes = this.currentGridApi.getSelectedNodes(); if (selectedNodes.length === 0) { this.showToast('warning', 'ไม่มีแถวที่เลือก', 'กรุณาเลือกแถวที่ต้องการลบก่อน'); return; } const confirmed = confirm(`คุณต้องการทำเครื่องหมายลบ ${selectedNodes.length} แถวนี้หรือไม่?\n\nแถวจะถูกลบจริงเมื่อกดปุ่ม " บันทึก"`); if (!confirmed) return; // ทำเครื่องหมายแถวที่เลือกไว้เพื่อรอการลบ selectedNodes.forEach(node => { if (node.data) { // เพิ่ม flag `_isDeleted` เพื่อบอกให้ `saveGridChanges` รู้ว่าต้องลบ const updatedData = { ...node.data, _isDeleted: true }; node.setData(updatedData); } }); // รีเฟรชแถวเพื่อให้ CSS ทำงาน this.currentGridApi.refreshCells({ rowNodes: selectedNodes, force: true }); // ใช้ setTimeout เพื่อให้ AG Grid มีเวลาอัปเดต data ก่อน setTimeout(() => { this.markGridAsModified(); // อัปเดตสถานะให้ปุ่ม Save กดได้ }, 10); this.showToast('info', 'ทำเครื่องหมายเพื่อลบ', `${selectedNodes.length} แถวถูกทำเครื่องหมายเพื่อลบ กรุณากด " บันทึก" เพื่อยืนยัน`); } /** * Add new row to current table (called by Ctrl+A) */ async addNewRowToCurrentTable() { if (this.currentTable) { await this.showAddRowForm(this.currentTable); } else if (this.currentGridApi) { this.addRowToGrid(); } else { // Handle HTML table const table = document.querySelector('.data-table'); if (table) { this.addNewRow(table); } } } /** * Duplicate current row (called by Ctrl+D) */ async duplicateCurrentRow() { if (this.currentGridApi) { const focusedCell = this.currentGridApi.getFocusedCell(); if (focusedCell) { const rowNode = this.currentGridApi.getDisplayedRowAtIndex(focusedCell.rowIndex); if (rowNode && rowNode.data) { // Create a copy of the row data const duplicatedData = { ...rowNode.data }; delete duplicatedData.id; // Remove ID so it creates a new row // Show edit form with duplicated data await this.showAddRowForm(this.currentTable, duplicatedData); } } } else { // Handle HTML table const activeCell = document.activeElement; if (activeCell && activeCell.tagName === 'TD') { const row = activeCell.closest('tr'); if (row) { const newRow = row.cloneNode(true); newRow.classList.add('new-row'); row.parentNode.appendChild(newRow); this.markTableAsModified(row.closest('table')); } } } } /** * ↩ Undo table changes (called by Ctrl+Z) */ undoTableChanges() { if (confirm('คุณต้องการยกเลิกการเปลี่ยนแปลงทั้งหมดและรีเฟรชตารางหรือไม่?')) { if (this.currentTable) { this.refreshTableData(this.currentTable); this.showToast('success', 'ยกเลิกแล้ว', 'ยกเลิกการเปลี่ยนแปลงและรีเฟรชตารางแล้ว'); } else { this.showToast('warning', 'ไม่มีตาราง', 'ไม่มีตารางที่เปิดอยู่ให้ยกเลิกการเปลี่ยนแปลง'); } } } /** * Show Add Row Form */ async showAddRowForm(tableName, initialData = null) { try { // Get table structure first const columns = await this.getTableColumns(tableName); this.showRowEditForm(tableName, initialData, columns); } catch (error) { console.error('Failed to get table structure:', error); this.showToast('error', 'Error', 'Failed to get table structure'); } } /** * Show Edit Row Form */ async showEditRowForm(tableName, rowData) { try { // Get table structure first const columns = await this.getTableColumns(tableName); this.showRowEditForm(tableName, rowData, columns); } catch (error) { console.error('Failed to get table structure:', error); this.showToast('error', 'Error', 'Failed to get table structure'); } } /** * Delete Row From Table */ async deleteRowFromTable(tableName, rowId) { // Validate rowId if (rowId === null || rowId === undefined || rowId === 'null' || rowId === 'undefined') { this.showToast('error', 'Delete Error', 'ไม่สามารถลบแถวได้: ไม่พบ ID ของแถว'); return; } if (!confirm(`คุณต้องการลบแถวนี้ออกจากตาราง ${tableName} ใช่หรือไม่? การกระทำนี้ไม่สามารถย้อนกลับได้`)) { return; } try { // ดึงข้อมูลคอลัมน์เพื่อหา Primary Key ที่แท้จริง const columns = await this.getTableColumns(tableName); const primaryKeyName = this.findPrimaryKey(columns); if (!primaryKeyName) { throw new Error('ไม่พบ Primary Key ในตารางนี้ ไม่สามารถลบข้อมูลได้'); } // เรียกใช้ฟังก์ชันลบของ Backend โดยระบุชื่อ PK ที่ถูกต้อง const result = await this.deleteTableRow(tableName, rowId, primaryKeyName); this.showToast('success', 'ลบสำเร็จ', 'ลบแถวข้อมูลเรียบร้อยแล้ว'); this.refreshTableData(tableName); // รีเฟรชตาราง } catch (error) { console.error('Delete row failed:', error); this.showToast('error', 'ลบล้มเหลว', error.message); } } /** * Save Row Changes */ async saveRowChanges(tableName, rowId) { try { if (this.currentGridApi) { // Get the row data from AG Grid const rowNode = this.currentGridApi.getRowNode(rowId); if (rowNode && rowNode.data) { const rowData = rowNode.data; // Build UPDATE query const setClause = Object.keys(rowData) .filter(key => key !== 'id' && key !== 'actions') .map(key => { const value = rowData[key]; if (value === null || value === undefined || value === '') { return `${key} = NULL`; } return `${key} = '${value}'`; }).join(', '); const query = `UPDATE ${tableName} SET ${setClause} WHERE id = '${rowId}';`; const response = await fetch(`http://localhost:${this.serverPort}/api/connections/${this.currentConnection}/query`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query }) }); const result = await response.json(); if (result.success) { this.showToast('success', 'Row Saved', 'Row changes saved successfully'); // Mark as saved by removing modified styling rowNode.setRowHeight(undefined); } else { throw new Error(result.error); } } } } catch (error) { console.error('Failed to save row changes:', error); this.showToast('error', 'Save Error', error.message); } } /** * Initialize dropdown menus for SQL Query tab toolbar * @param {string} tabId - The tab ID for the SQL Query tab * @returns {void} * @description Sets up event handlers for dropdown menus in the SQL Query toolbar including file operations, query tools, and transaction controls * @example * this.initializeDropdownMenus('query_tab_1'); // Initializes dropdowns for specified tab * @see {@link createSQLQueryTab} For the tab creation process that calls this function */ initializeDropdownMenus(tabId) { // Get all dropdown elements for this tab const dropdowns = [ `fileDropdown_${tabId}`, `toolsDropdown_${tabId}`, `transactionDropdown_${tabId}` ]; dropdowns.forEach(dropdownId => { const dropdown = document.getElementById(dropdownId); if (!dropdown) return; const button = dropdown.querySelector('.dropdown-button'); const menu = dropdown.querySelector('.dropdown-menu'); if (!button || !menu) return; // Toggle dropdown on button click button.addEventListener('click', (e) => { e.stopPropagation(); // Close other dropdowns dropdowns.forEach(otherId => { if (otherId !== dropdownId) { const otherDropdown = document.getElementById(otherId); if (otherDropdown) { otherDropdown.classList.remove('open'); } } }); // Toggle current dropdown dropdown.classList.toggle('open'); }); // Handle dropdown item clicks const items = menu.querySelectorAll('.dropdown-item'); items.forEach(item => { item.addEventListener('click', (e) => { e.stopPropagation(); dropdown.classList.remove('open'); // The individual button handlers will be triggered by their IDs // No need to handle specific actions here }); }); }); // Close dropdowns when clicking outside document.addEventListener('click', () => { dropdowns.forEach(dropdownId => { const dropdown = document.getElementById(dropdownId); if (dropdown) { dropdown.classList.remove('open'); } }); }); // Prevent dropdown menu clicks from bubbling dropdowns.forEach(dropdownId => { const dropdown = document.getElementById(dropdownId); if (dropdown) { const menu = dropdown.querySelector('.dropdown-menu'); if (menu) { menu.addEventListener('click', (e) => { e.stopPropagation(); }); } } }); } /** * Initialize license display in header * @returns {void} * @description Sets up license status display and periodic refresh */ initializeLicenseDisplay() { this.updateLicenseDisplay(); // รีเฟรชทุก 1 ชั่วโมง setInterval(() => { this.updateLicenseDisplay(); }, 60 * 60 * 1000); } /** * Update license status display * @returns {Promise} * @description Fetches license status and updates the header badge */ async updateLicenseDisplay() { const badge = document.getElementById('license-badge'); if (!badge) return; try { const res = await window.license.getStatus(); if (!res.ok) { badge.textContent = 'License: not activated'; badge.className = 'license-badge active error'; return; } const { expiresAt, daysRemaining, currentTier, pluginId } = res.data; const exp = new Date(expiresAt); const days = typeof daysRemaining === 'number' ? daysRemaining : Math.max(0, Math.ceil((exp - Date.now()) / 86400000)); // กำหนดสีตามจำนวนวันที่เหลือ let badgeClass = 'license-badge active safe'; if (days <= 7) { badgeClass = 'license-badge active danger'; } else if (days <= 30) { badgeClass = 'license-badge active warning'; } badge.className = badgeClass; badge.textContent = `License (${currentTier ?? 'N/A'}): หมดอายุ ${exp.toLocaleDateString('th-TH')} (เหลือ ${days} วัน)`; badge.title = `Plugin ID: ${pluginId}\nExpires: ${exp.toLocaleString('th-TH')}\nDays remaining: ${days}`; } catch (error) { console.warn('Failed to get license status:', error); badge.textContent = 'License: cannot check'; badge.className = 'license-badge active error'; } } /** * Setup drag & drop functionality for a plugin item * @param {HTMLElement} pluginItem - The plugin item element * @param {Object} plugin - Plugin configuration object */ setupPluginDragDrop(pluginItem, plugin) { const dropZone = pluginItem.querySelector('.simple-drop-area'); // อัปเดตเป็น simple-drop-area if (!dropZone) { console.log('No drop zone found for plugin:', plugin.displayName); return; } // Prevent default drag behaviors ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { dropZone.addEventListener(eventName, this.preventDefaults, false); document.body.addEventListener(eventName, this.preventDefaults, false); }); // Highlight drop zone when files are dragged over ['dragenter', 'dragover'].forEach(eventName => { dropZone.addEventListener(eventName, () => this.highlightPluginDropZone(dropZone), false); }); ['dragleave', 'drop'].forEach(eventName => { dropZone.addEventListener(eventName, () => this.unhighlightPluginDropZone(dropZone), false); }); // Handle dropped files dropZone.addEventListener('drop', (e) => this.handlePluginFileDrop(e, plugin), false); } /** * Prevent default drag behaviors * @param {Event} e - Drag event */ preventDefaults(e) { e.preventDefault(); e.stopPropagation(); } /** * Highlight plugin drop zone * @param {HTMLElement} dropZone - Drop zone element */ highlightPluginDropZone(dropZone) { if (dropZone) { dropZone.classList.add('drag-over'); dropZone.style.borderColor = '#4facfe'; dropZone.style.background = 'rgba(79, 172, 254, 0.2)'; } } /** * Remove highlight from plugin drop zone * @param {HTMLElement} dropZone - Drop zone element */ unhighlightPluginDropZone(dropZone) { if (dropZone) { dropZone.classList.remove('drag-over'); dropZone.style.borderColor = ''; dropZone.style.background = ''; } } /** * Handle files dropped on plugin * @param {Event} e - Drop event * @param {Object} plugin - Plugin configuration */ async handlePluginFileDrop(e, plugin) { const dt = e.dataTransfer; const files = Array.from(dt.files); if (files.length === 0) return; try { this.showLoading(`Processing ${files.length} files for ${plugin.displayName}...`); // Validate file types const supportedTypes = plugin.ui.supportedFileTypes || ['.sql', '.json']; const validFiles = files.filter(file => { const extension = '.' + file.name.split('.').pop().toLowerCase(); return supportedTypes.includes(extension); }); if (validFiles.length === 0) { throw new Error(`No supported files found. Supported types: ${supportedTypes.join(', ')}`); } // Show processing status this.showToast('info', 'Processing Files', `Processing ${validFiles.length} files with ${plugin.displayName}`); // Simulate file processing (replace with actual implementation) await this.processPluginFiles(validFiles, plugin); this.showToast('success', 'Files Processed', `Successfully processed ${validFiles.length} files`); } catch (error) { console.error('File drop processing failed:', error); this.showToast('error', 'Processing Failed', error.message); } finally { this.hideLoading(); } } /** * Process files for a plugin * @param {Array} files - Array of File objects * @param {Object} plugin - Plugin configuration */ async processPluginFiles(files, plugin) { try { // อ่านเนื้อหาไฟล์ const fileData = []; for (const file of files) { const content = await this.readFileAsText(file); // ตรวจสอบว่าเป็นไฟล์ JSON หรือไม่ if (file.name.toLowerCase().endsWith('.json')) { try { // ตรวจสอบว่า JSON ถูกต้องหรือไม่ JSON.parse(content); fileData.push({ name: file.name, size: file.size, type: 'application/json', content: content // ส่ง content เป็น string }); console.log(` Loaded JSON file: ${file.name}`); } catch (parseError) { console.error(` Invalid JSON in file ${file.name}:`, parseError); throw new Error(`Invalid JSON format in file: ${file.name}`); } } else { // สำหรับไฟล์อื่นๆ เช่น .sql fileData.push({ name: file.name, size: file.size, type: file.type || 'text/plain', content: content }); } } // ส่งข้อมูลไปยัง server const response = await fetch(`http://localhost:${this.serverPort}/api/plugins/${plugin.name}/drop-files`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ files: fileData, connectionId: this.currentConnection?.id }) }); const result = await response.json(); if (result.success) { console.log(' Files processed successfully:', result.data); // รีเฟรชโครงสร้างฐานข้อมูลหลังจากประมวลผลไฟล์สำเร็จ if (this.currentConnection) { await this.loadDatabaseStructure(this.currentConnection.id); } return result.data; } else { throw new Error(result.error); } } catch (error) { console.error(' File processing failed:', error); throw error; } } /** * Read file as text * @param {File} file - File object * @returns {Promise} File content as text */ readFileAsText(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = (e) => resolve(e.target.result); reader.onerror = (e) => reject(new Error('Failed to read file')); reader.readAsText(file); }); } showFileImportDialog(plugin) { const fileInput = document.createElement('input'); fileInput.type = 'file'; fileInput.accept = '.sql,.dump'; fileInput.style.display = 'none'; fileInput.addEventListener('change', async (e) => { const file = e.target.files[0]; if (!file) return; this.showMessage(` Importing data from ${file.name}...`, 'info'); try { const response = await fetch('/api/plugin/import-file', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ plugin: plugin.name, filePath: file.path }) }); const result = await response.json(); if (result.success) { this.showMessage(` Data imported successfully!`, 'success'); } else { this.showMessage(` Import failed: ${result.error}`, 'error'); } } catch (error) { console.error('Import error:', error); this.showMessage(` Import failed: ${error.message}`, 'error'); } }); document.body.appendChild(fileInput); fileInput.click(); document.body.removeChild(fileInput); } } // Initialize the application when the DOM is loaded document.addEventListener('DOMContentLoaded', async () => { window.dbManager = new DatabaseManager(); await window.dbManager.init(); // Make debug functions globally available window.debugModal = () => window.dbManager.debugModal(); window.debugSave = () => window.dbManager.debugSaveButton(); console.log(' Debug functions available:'); console.log(' - window.debugModal() - Debug connection modal'); console.log(' - window.debugSave() - Debug save button'); });