| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
|
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| class DatabaseManager {
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| constructor() {
|
| this.serverPort = null;
|
| this.currentConnection = null;
|
| this.connections = [];
|
| this.availablePlugins = [];
|
| this.tabs = new Map();
|
| this.activeTab = 'query';
|
| this.language = 'th';
|
| this.primaryKeyByTable = new Map();
|
| this.translations = {
|
| th: {
|
|
|
| '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...': 'กำลังลบการเชื่อมต่อ...',
|
|
|
|
|
| '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 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': 'ไม่มีข้อมูลให้ส่งออก',
|
|
|
|
|
| '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 ไปยังแท็บได้',
|
|
|
|
|
| 'Tools': 'เครื่องมือ',
|
| 'SQL Query': 'คำสั่ง SQL',
|
| 'Tables': 'ตาราง',
|
| 'Execute': 'รัน',
|
| 'Cancel': 'ยกเลิก',
|
| 'Format': 'จัดรูปแบบ',
|
| 'Explain': 'อธิบาย',
|
| 'Commit': 'ยืนยัน',
|
| 'Rollback': 'ย้อนกลับ',
|
| 'Save': 'บันทึก',
|
| 'Load': 'โหลด',
|
| 'Clear': 'ล้าง',
|
| 'Import SQL File': 'นำเข้าไฟล์ SQL',
|
| 'Export SQL': 'ส่งออก SQL',
|
| 'rows': 'แถว',
|
| 'columns': 'คอลัมน์',
|
|
|
|
|
| 'Copy': 'คัดลอก',
|
| 'Paste': 'วาง',
|
| 'Set NULL': 'กำหนดเป็น NULL',
|
| 'Edit': 'แก้ไข',
|
| 'Delete Row': 'ลบแถว',
|
| 'Copy Row': 'คัดลอกแถว',
|
| 'Insert Row': 'แทรกแถว',
|
| 'Duplicate Row': 'ทำสำเนาแถว',
|
|
|
|
|
| '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': 'เลือกการเชื่อมต่อเพื่อดูโครงสร้างฐานข้อมูล',
|
|
|
|
|
| 'Enter your SQL query here...': 'ใส่คำสั่ง SQL ที่นี่...'
|
| },
|
| en: {
|
|
|
| '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'
|
|
|
| }
|
| };
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| t(key) {
|
| return this.translations[this.language][key] || key;
|
| }
|
|
|
| |
| |
| |
| |
|
|
| getPrimaryKeyForTable(tableName) {
|
| return this.primaryKeyByTable.get(tableName) || 'id';
|
| }
|
|
|
| |
| |
| |
| |
|
|
| setPrimaryKeyForTable(tableName, primaryKey) {
|
| this.primaryKeyByTable.set(tableName, primaryKey);
|
| }
|
|
|
| |
| |
| |
| |
| |
|
|
| normalizeRowData(row, tableName) {
|
| if (!row) return row;
|
| const primaryKey = this.getPrimaryKeyForTable(tableName) || 'id';
|
| return {
|
| ...row,
|
| [primaryKey]: String(row[primaryKey])
|
| };
|
| }
|
|
|
| |
| |
| |
| |
|
|
| rowExistsInGrid(rowId) {
|
| if (!this.currentGridApi) return false;
|
| const node = this.currentGridApi.getRowNode(String(rowId));
|
| return !!node;
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
|
|
| async init() {
|
| try {
|
|
|
| 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;
|
| }
|
|
|
|
|
| if (!this.serverPort) {
|
| console.warn(' Server port is null/undefined, using default 3001');
|
| this.serverPort = 3001;
|
| }
|
|
|
| console.log(' Using server port:', this.serverPort);
|
|
|
|
|
| this.initializeEventListeners();
|
| this.initializeMenuHandlers();
|
| this.initializeResizableSplitter();
|
|
|
|
|
| this.initializeLicenseDisplay();
|
|
|
|
|
| this.openSQLQueryTab();
|
|
|
|
|
| await this.loadConnections();
|
|
|
|
|
| await this.loadAvailablePlugins();
|
|
|
|
|
| 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);
|
| }
|
| }
|
|
|
| |
| |
| |
| |
|
|
| initializeEventListeners() {
|
|
|
| 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;
|
| }
|
| }
|
| });
|
| }
|
|
|
|
|
| const deleteConnectionBtn = document.getElementById('deleteConnectionBtn');
|
| if (deleteConnectionBtn) {
|
| deleteConnectionBtn.addEventListener('click', () => {
|
| this.deleteSelectedConnection();
|
| });
|
| }
|
|
|
|
|
| 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();
|
| });
|
| }
|
|
|
|
|
| const connectionDialog = document.getElementById('connectionModal');
|
| if (connectionDialog) {
|
|
|
| const modalClose = connectionDialog.querySelector('.modal-close');
|
| if (modalClose) {
|
| modalClose.addEventListener('click', () => {
|
| this.hideConnectionModal();
|
| });
|
| }
|
|
|
|
|
| connectionDialog.addEventListener('click', (e) => {
|
| if (e.target === connectionDialog) {
|
| this.hideConnectionModal();
|
| }
|
| });
|
|
|
|
|
| connectionDialog.addEventListener('cancel', (e) => {
|
| e.preventDefault();
|
| this.hideConnectionModal();
|
| });
|
| } else {
|
| console.warn(' Connection dialog not found');
|
| }
|
|
|
|
|
| const databaseType = document.getElementById('databaseType');
|
| if (databaseType) {
|
| databaseType.addEventListener('change', (e) => {
|
| this.updateConnectionFormDefaults(e.target.value);
|
| });
|
| }
|
|
|
|
|
| const executeQueryBtn = document.getElementById('executeQueryBtn');
|
| if (executeQueryBtn) {
|
| executeQueryBtn.addEventListener('click', () => {
|
| this.executeQuery();
|
| });
|
| }
|
|
|
|
|
| document.addEventListener('keydown', (e) => {
|
|
|
| if (e.ctrlKey && e.key === 'Enter') {
|
| e.preventDefault();
|
| this.executeQuery();
|
| }
|
|
|
| if (e.ctrlKey && e.key === 'n') {
|
| e.preventDefault();
|
| this.showConnectionModal();
|
| }
|
|
|
| if (e.ctrlKey && e.key === 's') {
|
| e.preventDefault();
|
| this.saveQuery();
|
|
|
| this.saveCurrentTableChanges();
|
| }
|
|
|
| if (e.ctrlKey && e.key === 'o') {
|
| e.preventDefault();
|
| this.loadQuery();
|
| }
|
|
|
| if (e.ctrlKey && e.key === 'e') {
|
| e.preventDefault();
|
| this.exportResults();
|
| }
|
|
|
| if (e.key === 'F5') {
|
| e.preventDefault();
|
| if (this.currentConnection) {
|
| this.loadDatabaseStructure(this.currentConnection);
|
| }
|
|
|
| this.refreshCurrentTable();
|
| }
|
|
|
| if (e.ctrlKey && e.key === 't') {
|
| e.preventDefault();
|
| if (document.getElementById('connectionModal').style.display !== 'none') {
|
| this.testConnection();
|
| }
|
| }
|
|
|
| if (e.ctrlKey && e.key === 'w') {
|
| e.preventDefault();
|
|
|
| console.log('Close tab shortcut pressed');
|
| }
|
|
|
| if (e.key === 'Escape') {
|
| this.closeModals();
|
| }
|
|
|
| if (e.ctrlKey && (e.key === '+' || e.key === '=')) {
|
| e.preventDefault();
|
| this.zoomIn();
|
| }
|
|
|
| if (e.ctrlKey && e.key === '-') {
|
| e.preventDefault();
|
| this.zoomOut();
|
| }
|
|
|
| if (e.ctrlKey && e.key === '0') {
|
| e.preventDefault();
|
| this.resetZoom();
|
| }
|
|
|
| if (e.key === 'F11') {
|
|
|
| return;
|
| }
|
|
|
| if (e.key === 'F2') {
|
| e.preventDefault();
|
| this.editCurrentRow();
|
| }
|
|
|
| if (e.key === 'Delete') {
|
| e.preventDefault();
|
| this.deleteCurrentRow();
|
| }
|
|
|
| if (e.ctrlKey && e.key === 'r') {
|
| e.preventDefault();
|
| this.refreshCurrentTable();
|
| }
|
|
|
| if (e.ctrlKey && e.key === 'a') {
|
| e.preventDefault();
|
| this.addNewRowToCurrentTable();
|
| }
|
|
|
| if (e.ctrlKey && e.key === 'd') {
|
| e.preventDefault();
|
| this.duplicateCurrentRow();
|
| }
|
|
|
| if (e.ctrlKey && e.key === 'z') {
|
| e.preventDefault();
|
| this.undoTableChanges();
|
| }
|
| });
|
|
|
|
|
| const refreshStructureBtn = document.getElementById('refreshStructureBtn');
|
| if (refreshStructureBtn) {
|
| refreshStructureBtn.addEventListener('click', () => {
|
| if (this.currentConnection) {
|
| this.loadDatabaseStructure(this.currentConnection);
|
| }
|
| });
|
| }
|
|
|
|
|
| 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();
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
| |
|
|
| initializeResizableSplitter() {
|
|
|
| this.initializeVerticalSplitter();
|
|
|
|
|
| this.initializeSidebarControls();
|
|
|
|
|
| const splitter = document.getElementById('horizontalSplitter');
|
| if (!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);
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
|
|
| 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;
|
|
|
|
|
| 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');
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| 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;
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| const toggleSidebar = (expand) => {
|
| if (expand) {
|
|
|
| sidebar.classList.remove('collapsed');
|
| sidebar.style.width = '300px';
|
| verticalSplitter.style.display = 'block';
|
| collapseSidebarBtn.title = 'Collapse Sidebar';
|
| collapseSidebarBtn.innerHTML = `
|
| <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
|
| <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
|
| </svg>
|
| `;
|
| } else {
|
|
|
| sidebar.classList.add('collapsed');
|
| sidebar.style.width = '0';
|
| verticalSplitter.style.display = 'none';
|
| collapseSidebarBtn.title = 'Expand Sidebar';
|
| collapseSidebarBtn.innerHTML = `
|
| <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
|
| <path d="M8.59 16.59L10 18l6-6-6-6-1.41 1.41L13.17 12z"/>
|
| </svg>
|
| `;
|
| }
|
| };
|
|
|
| collapseSidebarBtn.addEventListener('click', () => {
|
| const isCollapsed = sidebar.classList.contains('collapsed');
|
| toggleSidebar(isCollapsed);
|
| });
|
|
|
|
|
| if (showSidebarBtn) {
|
| showSidebarBtn.addEventListener('click', () => {
|
| toggleSidebar(true);
|
| });
|
| }
|
|
|
| console.log(' Sidebar controls initialized');
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| initializeHorizontalSplitter(splitter) {
|
| let isResizing = false;
|
|
|
| splitter.addEventListener('mousedown', (e) => {
|
| e.preventDefault();
|
| isResizing = true;
|
| console.log(' Started resizing horizontal splitter');
|
|
|
|
|
| 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;
|
|
|
| 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');
|
|
|
|
|
| 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);
|
| });
|
| }
|
|
|
| |
| |
| |
| |
|
|
| initializeMenuHandlers() {
|
|
|
| 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;
|
| }
|
| });
|
| }
|
|
|
| |
| |
| |
| |
| |
|
|
| 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);
|
| }
|
| }
|
|
|
| |
| |
| |
| |
|
|
| updateConnectionSelector() {
|
| const select = document.getElementById('connectionSelect');
|
| select.innerHTML = '<option value="">Select Connection...</option>';
|
|
|
| this.connections.forEach(conn => {
|
| const option = document.createElement('option');
|
| option.value = conn.id;
|
| option.textContent = `${conn.name} (${conn.type})`;
|
| select.appendChild(option);
|
| });
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
|
|
| 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 {
|
|
|
| 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;
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
|
|
| 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 = [];
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
|
|
| 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();
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| renderDatabaseTree(structure) {
|
| const treeContainer = document.getElementById('databaseTree');
|
| treeContainer.innerHTML = '';
|
|
|
|
|
| const toolsSection = document.createElement('div');
|
| toolsSection.className = 'tree-section tools-section';
|
|
|
| const toolsHeader = document.createElement('div');
|
| toolsHeader.className = 'tree-header section-header';
|
| toolsHeader.innerHTML = `
|
| <div class="section-title">
|
| <svg class="section-icon" viewBox="0 0 16 16" fill="currentColor">
|
| <path d="M1 0 0 1l2.2 3.081a1 1 0 0 0 .815.419h.07a1 1 0 0 1 .708.293L2.1 6.4a1 1 0 0 0-.274 1.047l.39 1.171a1 1 0 0 0 .892.646l.131.013a1 1 0 0 1 .71.292l.362.362a1 1 0 0 0 1.414 0l.101-.101a1 1 0 0 1 1.228-.234l.706.353a1 1 0 0 0 .894 0l.653-.326a1 1 0 0 1 .893 0L8.878 9.9a1 1 0 0 0 1.415-1.414l-.362-.362a1 1 0 0 1-.293-.71l-.013-.131a1 1 0 0 0-.646-.892L7.8 5.9a1 1 0 0 0-1.047.274L5.146 4.567a1 1 0 0 1-.293-.708V3.79a1 1 0 0 0-.419-.815L1 0zm9.646 10.646a.5.5 0 0 1 .708 0L15 14.293V13.5a.5.5 0 0 1 1 0v2a.5.5 0 0 1-.5.5h-2a.5.5 0 0 1 0-1h.793L10.646 11.354a.5.5 0 0 1 0-.708z"/>
|
| </svg>
|
| <strong>
|
| <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4 inline mr-1">
|
| <path stroke-linecap="round" stroke-linejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z" />
|
| <path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
| </svg>
|
| Tools
|
| </strong>
|
| </div>
|
| `;
|
| toolsSection.appendChild(toolsHeader);
|
|
|
| const toolsContainer = document.createElement('div');
|
| toolsContainer.className = 'section-content';
|
|
|
|
|
| const sqlQueryItem = document.createElement('div');
|
| sqlQueryItem.className = 'tree-item tool-item sql-query-item';
|
| sqlQueryItem.innerHTML = `
|
| <svg class="tree-icon" viewBox="0 0 16 16" fill="currentColor">
|
| <path d="M5.854 4.854a.5.5 0 1 0-.708-.708l-3.5 3.5a.5.5 0 0 0 0 .708l3.5 3.5a.5.5 0 0 0 .708-.708L2.707 8l3.147-3.146zm4.292 0a.5.5 0 0 1 .708-.708l3.5 3.5a.5.5 0 0 1 0 .708l-3.5 3.5a.5.5 0 0 1-.708-.708L13.293 8l-3.147-3.146z"/>
|
| </svg>
|
| <span class="tree-label">
|
| <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-3 h-3 inline mr-1">
|
| <path stroke-linecap="round" stroke-linejoin="round" d="M17.25 6.75L22.5 12l-5.25 5.25m-10.5 0L1.5 12l5.25-5.25m7.5-3l-4.5 16.5" />
|
| </svg>
|
| ${this.t('SQL Query')}
|
| </span>
|
| <span class="tree-badge">Editor</span>
|
| `;
|
|
|
| sqlQueryItem.addEventListener('click', () => {
|
| this.openSQLQueryTab();
|
| });
|
|
|
| toolsContainer.appendChild(sqlQueryItem);
|
|
|
|
|
|
|
|
|
| toolsSection.appendChild(toolsContainer);
|
| treeContainer.appendChild(toolsSection);
|
|
|
|
|
| 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 = `
|
| <div class="section-title">
|
| <svg class="section-icon" viewBox="0 0 16 16" fill="currentColor">
|
| <path d="M6 0a.5.5 0 0 1 .5.5V3h3V.5a.5.5 0 0 1 1 0V3h1a.5.5 0 0 1 .5.5v3A3.5 3.5 0 0 1 8.5 10c-.002.434-.01.845-.04 1.22-.041.514-.126 1.003-.317 1.424a2.083 2.083 0 0 1-.97 1.028C6.725 13.9 6.169 14 5.5 14c-.998 0-1.61.33-1.974.718A1.922 1.922 0 0 0 3 16H2c0-.616.232-1.367.797-1.968C3.374 13.42 4.261 13 5.5 13c.581 0 .962-.088 1.218-.219.241-.123.4-.3.514-.55.121-.266.193-.621.23-1.09.027-.34.035-.718.037-1.141A3.5 3.5 0 0 1 4 6.5v-3a.5.5 0 0 1 .5-.5h1V.5A.5.5 0 0 1 6 0z"/>
|
| </svg>
|
| <strong>Database Templates (${this.availablePlugins.length})</strong>
|
| </div>
|
| `;
|
|
|
| const pluginsContainer = document.createElement('div');
|
| pluginsContainer.className = 'section-content';
|
|
|
| this.availablePlugins.forEach(plugin => {
|
| const pluginItem = document.createElement('div');
|
| pluginItem.className = 'tree-item plugin-item';
|
|
|
|
|
| const supportsDragDrop = plugin.ui && plugin.ui.allowDragDrop;
|
| const supportsDirectRun = plugin.ui && plugin.ui.allowDirectRun;
|
| const supportsSQLDump = plugin.ui && plugin.ui.allowSQLDump;
|
|
|
| pluginItem.innerHTML = `
|
| <div class="plugin-main-info">
|
| <svg class="tree-icon" viewBox="0 0 16 16" fill="currentColor">
|
| <path d="M4.5 3a2.5 2.5 0 0 1 5 0v9a1.5 1.5 0 0 1-3 0V5a.5.5 0 0 0-1 0v7a2.5 2.5 0 0 1-5 0V3a3.5 3.5 0 1 1 7 0v8.5a1 1 0 0 0 2 0V3a5.5 5.5 0 0 0-11 0v8.5a3 3 0 0 0 6 0V3a1 1 0 1 0-2 0v8.5a.5.5 0 0 1-1 0V3z"/>
|
| </svg>
|
| <div class="plugin-info">
|
| <div class="plugin-title">
|
| <span class="tree-label">${plugin.displayName}</span>
|
| <span class="tree-badge version">${plugin.version}</span>
|
| </div>
|
| <div class="plugin-author">${plugin.author}</div>
|
| <div class="plugin-features">
|
| <!-- ลบ feature badges ที่ซับซ้อนออก -->
|
| </div>
|
| </div>
|
| </div>
|
| <div class="plugin-simple-actions">
|
| <button class="simple-btn primary setup-btn" title="Initialize Database Schema">
|
| <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-3 h-3 inline mr-1">
|
| <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 21v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21m0 0h4.5V3.545M12.75 21h7.5V10.75M2.25 21h1.5m18 0h-18M2.25 9l4.5-1.636M18.75 3l-1.5.545m0 6.205l3 1m1.5.5l-1.5-.5M6.75 7.364V3h-3v18m3-13.636l10.5-3.819" />
|
| </svg>
|
| Initialize Schema
|
| </button>
|
| ${supportsSQLDump ? `
|
| <button class="simple-btn secondary dump-btn" title="Export Database">
|
| <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-3 h-3 inline mr-1">
|
| <path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />
|
| </svg>
|
| Export Database
|
| </button>
|
| ` : ''}
|
| ${supportsDragDrop ? `
|
| <div class="simple-drop-area">
|
| <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4 inline mr-1">
|
| <path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
|
| </svg>
|
| Drop database files here
|
| </div>
|
| ` : ''}
|
| </div>
|
| `;
|
|
|
|
|
| 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);
|
| });
|
| }
|
|
|
|
|
| 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);
|
| });
|
| }
|
|
|
|
|
| if (supportsDragDrop) {
|
| this.setupPluginDragDrop(pluginItem, plugin);
|
| }
|
|
|
| pluginsContainer.appendChild(pluginItem);
|
| });
|
|
|
| pluginsSection.appendChild(pluginsHeader);
|
| pluginsSection.appendChild(pluginsContainer);
|
| treeContainer.appendChild(pluginsSection);
|
| }
|
|
|
|
|
|
|
| if (!structure.tables || structure.tables.length === 0) {
|
| const noTablesSection = document.createElement('div');
|
| noTablesSection.className = 'tree-section tables-section empty';
|
| noTablesSection.innerHTML = `
|
| <div class="tree-header section-header">
|
| <div class="section-title">
|
| <svg class="section-icon" viewBox="0 0 16 16" fill="currentColor">
|
| <path d="M0 2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V2zm15 2h-4v3h4V4zm0 4h-4v3h4V8zm0 4h-4v3h3a1 1 0 0 0 1-1v-2zM1 2v2h4V2H1zm4 3H1v3h4V5zm0 4H1v3h4V9zm0 4H1v2a1 1 0 0 0 1 1h3v-3zm5-12v2h4V2H6zm4 3H6v3h4V5zm0 4H6v3h4V9zm-4 4v3h4v-3H6z"/>
|
| </svg>
|
| <strong>Tables (0)</strong>
|
| </div>
|
| </div>
|
| <div class="section-content">
|
| <div class="tree-placeholder">
|
| <p>No tables found</p>
|
| </div>
|
| </div>
|
| `;
|
| treeContainer.appendChild(noTablesSection);
|
| return;
|
| }
|
|
|
|
|
| const tablesSection = document.createElement('div');
|
| tablesSection.className = 'tree-section tables-section';
|
|
|
| const tablesHeader = document.createElement('div');
|
| tablesHeader.className = 'tree-header section-header';
|
| tablesHeader.innerHTML = `
|
| <div class="section-title">
|
| <svg class="section-icon" viewBox="0 0 16 16" fill="currentColor">
|
| <path d="M0 2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V2zm15 2h-4v3h4V4zm0 4h-4v3h4V8zm0 4h-4v3h3a1 1 0 0 0 1-1v-2zM1 2v2h4V2H1zm4 3H1v3h4V5zm0 4H1v3h4V9zm0 4H1v2a1 1 0 0 0 1 1h3v-3zm5-12v2h4V2H6zm4 3H6v3h4V5zm0 4H6v3h4V9zm-4 4v3h4v-3H6z"/>
|
| </svg>
|
| <strong>Tables (${structure.tables.length})</strong>
|
| </div>
|
| `;
|
|
|
| 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 = `
|
| <svg class="tree-icon" viewBox="0 0 16 16" fill="currentColor">
|
| <path d="M0 2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V2zm15 2h-4v3h4V4zm0 4h-4v3h4V8zm0 4h-4v3h3a1 1 0 0 0 1-1v-2zM1 2v2h4V2H1zm4 3H1v3h4V5zm0 4H1v3h4V9zm0 4H1v2a1 1 0 0 0 1 1h3v-3zm5-12v2h4V2H6zm4 3H6v3h4V5zm0 4H6v3h4V9zm-4 4v3h4v-3H6z"/>
|
| </svg>
|
| <div class="table-info">
|
| <span class="tree-label">${table.name}</span>
|
| <span class="tree-badge rows">${table.rowCount || 0} rows</span>
|
| </div>
|
| `;
|
|
|
|
|
| tableItem.addEventListener('click', () => {
|
| this.openTableTab(table.name);
|
| });
|
|
|
|
|
| tableItem.addEventListener('contextmenu', (e) => {
|
| e.preventDefault();
|
| this.showTableContextMenu(e, table);
|
| });
|
|
|
| tablesContainer.appendChild(tableItem);
|
| });
|
|
|
| tablesSection.appendChild(tablesHeader);
|
| tablesSection.appendChild(tablesContainer);
|
| treeContainer.appendChild(tablesSection);
|
|
|
|
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| showTableContextMenu(event, table) {
|
|
|
| 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 = `
|
| <div class="context-menu-item" data-action="openData">
|
| <svg class="menu-icon w-3 h-3 inline mr-1" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24">
|
| <path stroke-linecap="round" stroke-linejoin="round" d="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 013 19.875v-6.75zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V8.625zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z"/>
|
| </svg>เปิดข้อมูล
|
| </div>
|
| <div class="context-menu-item" data-action="openStructure">
|
| <svg class="menu-icon w-3 h-3 inline mr-1" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24">
|
| <path stroke-linecap="round" stroke-linejoin="round" d="M2.25 7.125C2.25 6.504 2.754 6 3.375 6h6c.621 0 1.125.504 1.125 1.125v3.75c0 .621-.504 1.125-1.125 1.125h-6a1.125 1.125 0 01-1.125-1.125v-3.75zM14.25 8.625c0-.621.504-1.125 1.125-1.125h5.25c.621 0 1.125.504 1.125 1.125v8.25c0 .621-.504 1.125-1.125 1.125h-5.25a1.125 1.125 0 01-1.125-1.125v-8.25zM3.75 16.125c0-.621.504-1.125 1.125-1.125h5.25c.621 0 1.125.504 1.125 1.125v2.25c0 .621-.504 1.125-1.125 1.125h-5.25a1.125 1.125 0 01-1.125-1.125v-2.25z"/>
|
| </svg>ดูโครงสร้าง
|
| </div>
|
| <div class="context-menu-separator"></div>
|
| <div class="context-menu-item" data-action="addRow">
|
| <svg class="menu-icon w-3 h-3 inline mr-1" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24">
|
| <path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15"/>
|
| </svg>เพิ่มแถวใหม่ <span class="shortcut">Ctrl+A</span>
|
| </div>
|
| <div class="context-menu-item" data-action="editFirstRow">
|
| <svg class="menu-icon w-3 h-3 inline mr-1" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24">
|
| <path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L6.832 19.82a4.5 4.5 0 01-1.897 1.13l-2.685.8.8-2.685a4.5 4.5 0 011.13-1.897L16.863 4.487zm0 0L19.5 7.125"/>
|
| </svg>แก้ไขแถวแรก <span class="shortcut">F2</span>
|
| </div>
|
| <div class="context-menu-item" data-action="deleteRows">
|
| <span class="menu-icon"></span> ลบแถวที่เลือก <span class="shortcut">Del</span>
|
| </div>
|
| <div class="context-menu-separator"></div>
|
| <div class="context-menu-item" data-action="generateSelect">
|
| <span class="menu-icon"></span> สร้าง SELECT
|
| </div>
|
| <div class="context-menu-item" data-action="generateInsert">
|
| <span class="menu-icon"></span> สร้าง INSERT
|
| </div>
|
| <div class="context-menu-item" data-action="generateUpdate">
|
| <span class="menu-icon"></span> สร้าง UPDATE
|
| </div>
|
| <div class="context-menu-item" data-action="generateDelete">
|
| <span class="menu-icon"></span> สร้าง DELETE
|
| </div>
|
| <div class="context-menu-separator"></div>
|
| <div class="context-menu-item" data-action="exportData">
|
| <span class="menu-icon"></span> ส่งออกข้อมูล <span class="shortcut">Ctrl+E</span>
|
| </div>
|
| <div class="context-menu-item" data-action="importData">
|
| <span class="menu-icon"></span> นำเข้าข้อมูล
|
| </div>
|
| <div class="context-menu-separator"></div>
|
| <div class="context-menu-item" data-action="saveChanges">
|
| <span class="menu-icon"></span> บันทึกการเปลี่ยนแปลง <span class="shortcut">Ctrl+S</span>
|
| </div>
|
| <div class="context-menu-item" data-action="undoChanges">
|
| <span class="menu-icon">↩</span> ยกเลิกการเปลี่ยนแปลง <span class="shortcut">Ctrl+Z</span>
|
| </div>
|
| <div class="context-menu-separator"></div>
|
| <div class="context-menu-item" data-action="copyTableName">
|
| <span class="menu-icon"></span> คัดลอกชื่อตาราง
|
| </div>
|
| <div class="context-menu-item" data-action="refreshTable">
|
| <span class="menu-icon"></span> รีเฟรช <span class="shortcut">F5</span>
|
| </div>
|
| `;
|
|
|
|
|
| menu.style.position = 'fixed';
|
| menu.style.left = event.pageX + 'px';
|
| menu.style.top = event.pageY + 'px';
|
| menu.style.zIndex = '10000';
|
|
|
| document.body.appendChild(menu);
|
|
|
|
|
| menu.addEventListener('click', (e) => {
|
| const action = e.target.closest('.context-menu-item')?.getAttribute('data-action');
|
| if (action) {
|
| this.handleTableContextAction(action, table);
|
| menu.remove();
|
| }
|
| });
|
|
|
|
|
| setTimeout(() => {
|
| document.addEventListener('click', () => {
|
| if (document.body.contains(menu)) {
|
| menu.remove();
|
| }
|
| }, { once: true });
|
| }, 100);
|
|
|
|
|
| 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';
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
|
|
| 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;
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| async generateSQLQuery(type, tableName) {
|
| let query = '';
|
| const dbType = this.getCurrentDatabaseType();
|
| const formattedTableName = this.formatSQLIdentifier(tableName, dbType);
|
|
|
| try {
|
|
|
| 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));
|
| 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));
|
| 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);
|
|
|
|
|
| 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;
|
| }
|
| }
|
|
|
|
|
| this.openSQLQueryTab();
|
| setTimeout(() => {
|
| const textarea = document.getElementById('queryTextarea_sql_query');
|
| if (textarea) {
|
|
|
| if (textarea.value.trim()) {
|
| textarea.value += '\n\n' + query;
|
| } else {
|
| textarea.value = query;
|
| }
|
| textarea.focus();
|
|
|
| textarea.setSelectionRange(textarea.value.length, textarea.value.length);
|
| }
|
| }, 200);
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
|
|
| 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;
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| 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) {
|
|
|
| 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 {
|
|
|
| console.log(' New connection mode - resetting form');
|
| form.reset();
|
| this.updateConnectionFormDefaults('postgresql');
|
| }
|
|
|
|
|
| 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');
|
|
|
|
|
| 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}`);
|
| }
|
| }
|
|
|
| |
| |
|
|
| 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');
|
|
|
|
|
| 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);
|
| }
|
| }
|
|
|
| |
| |
|
|
| closeModals() {
|
|
|
| this.hideConnectionModal();
|
|
|
|
|
| const loadingOverlay = document.getElementById('loadingOverlay');
|
| if (loadingOverlay.classList.contains('active')) {
|
| loadingOverlay.classList.remove('active');
|
| }
|
| }
|
|
|
| |
| |
|
|
| zoomIn() {
|
| const currentZoom = parseFloat(document.body.style.zoom) || 1;
|
| const newZoom = Math.min(currentZoom + 0.1, 2.0);
|
| document.body.style.zoom = newZoom;
|
| this.showToast('info', 'Zoom', `Zoom: ${Math.round(newZoom * 100)}%`);
|
| }
|
|
|
| |
| |
|
|
| zoomOut() {
|
| const currentZoom = parseFloat(document.body.style.zoom) || 1;
|
| const newZoom = Math.max(currentZoom - 0.1, 0.5);
|
| document.body.style.zoom = newZoom;
|
| this.showToast('info', 'Zoom', `Zoom: ${Math.round(newZoom * 100)}%`);
|
| }
|
|
|
| |
| |
|
|
| resetZoom() {
|
| document.body.style.zoom = 1;
|
| this.showToast('info', 'Zoom', 'Zoom reset to 100%');
|
| }
|
|
|
| |
| |
| |
|
|
| 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;
|
| }
|
|
|
|
|
| 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();
|
| }
|
| });
|
| }
|
|
|
| |
| |
| |
| |
|
|
| sortTable(table, columnIndex) {
|
| const tbody = table.querySelector('tbody');
|
| const rows = Array.from(tbody.querySelectorAll('tr'));
|
| const header = table.querySelector(`th:nth-child(${columnIndex + 1})`);
|
|
|
|
|
| let sortDirection = 'asc';
|
| if (header.classList.contains('sort-asc')) {
|
| sortDirection = 'desc';
|
| }
|
|
|
|
|
| table.querySelectorAll('th').forEach(th => {
|
| th.classList.remove('sort-asc', 'sort-desc');
|
| });
|
|
|
|
|
| header.classList.add(`sort-${sortDirection}`);
|
|
|
|
|
| rows.sort((a, b) => {
|
| const aValue = a.querySelector(`td:nth-child(${columnIndex + 1})`).textContent;
|
| const bValue = b.querySelector(`td:nth-child(${columnIndex + 1})`).textContent;
|
|
|
|
|
| if (aValue === 'NULL' && bValue === 'NULL') return 0;
|
| if (aValue === 'NULL') return sortDirection === 'asc' ? 1 : -1;
|
| if (bValue === 'NULL') return sortDirection === 'asc' ? -1 : 1;
|
|
|
|
|
| const aNum = parseFloat(aValue);
|
| const bNum = parseFloat(bValue);
|
|
|
| if (!isNaN(aNum) && !isNaN(bNum)) {
|
| return sortDirection === 'asc' ? aNum - bNum : bNum - aNum;
|
| }
|
|
|
|
|
| const result = aValue.localeCompare(bValue);
|
| return sortDirection === 'asc' ? result : -result;
|
| });
|
|
|
|
|
| rows.forEach(row => tbody.appendChild(row));
|
|
|
|
|
| this.updateRowNumbers(table);
|
| }
|
|
|
| |
| |
| |
|
|
| updateRowNumbers(table) {
|
| const rows = table.querySelectorAll('tbody tr');
|
| rows.forEach((row, index) => {
|
| const rowNumCell = row.querySelector('.row-number');
|
| if (rowNumCell) {
|
| rowNumCell.textContent = index + 1;
|
| }
|
| });
|
| }
|
|
|
| |
| |
| |
|
|
| 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)';
|
| }
|
| }
|
|
|
| |
| |
| |
|
|
| attachTableEventListeners(table) {
|
|
|
| const filterInput = document.getElementById('tableFilter');
|
| if (filterInput) {
|
| filterInput.addEventListener('input', (e) => {
|
| this.filterTable(table, e.target.value);
|
| });
|
| }
|
|
|
|
|
| const clearFilterBtn = document.getElementById('clearFilter');
|
| if (clearFilterBtn) {
|
| clearFilterBtn.addEventListener('click', () => {
|
| filterInput.value = '';
|
| this.filterTable(table, '');
|
| });
|
| }
|
|
|
|
|
| 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);
|
| });
|
| }
|
|
|
|
|
| const refreshBtn = document.getElementById('refreshTableBtn');
|
| if (refreshBtn) {
|
| refreshBtn.addEventListener('click', () => {
|
| this.executeQuery();
|
| });
|
| }
|
|
|
|
|
| const exportBtn = document.getElementById('exportTableBtn');
|
| if (exportBtn) {
|
| exportBtn.addEventListener('click', () => {
|
| this.exportTableData(table);
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
| |
|
|
| 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);
|
| }
|
|
|
| |
| |
| |
|
|
| addNewRow(table) {
|
| const tbody = table.querySelector('tbody');
|
| const headerRow = table.querySelector('thead tr');
|
| const columnCount = headerRow.children.length - 1;
|
|
|
| const newRow = document.createElement('tr');
|
| newRow.classList.add('new-row');
|
|
|
|
|
| const rowNumCell = document.createElement('td');
|
| rowNumCell.className = 'row-number';
|
| rowNumCell.textContent = tbody.children.length + 1;
|
| newRow.appendChild(rowNumCell);
|
|
|
|
|
| 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);
|
|
|
|
|
| const firstCell = newRow.querySelector('td:nth-child(2)');
|
| if (firstCell) {
|
| this.editCell(firstCell);
|
| }
|
| }
|
|
|
| |
| |
| |
| |
|
|
| showCellContextMenu(event, cell) {
|
| event.preventDefault();
|
|
|
|
|
| const existingMenu = document.querySelector('.context-menu');
|
| if (existingMenu) {
|
| existingMenu.remove();
|
| }
|
|
|
| const menu = document.createElement('div');
|
| menu.className = 'context-menu';
|
| menu.innerHTML = `
|
| <div class="context-menu-item" data-action="copy"> Copy</div>
|
| <div class="context-menu-item" data-action="paste"> Paste</div>
|
| <div class="context-menu-separator"></div>
|
| <div class="context-menu-item" data-action="setNull">∅ Set NULL</div>
|
| <div class="context-menu-item" data-action="edit"> Edit</div>
|
| <div class="context-menu-separator"></div>
|
| <div class="context-menu-item" data-action="deleteRow"> Delete Row</div>
|
| `;
|
|
|
| menu.style.left = event.pageX + 'px';
|
| menu.style.top = event.pageY + 'px';
|
|
|
| document.body.appendChild(menu);
|
|
|
|
|
| menu.addEventListener('click', (e) => {
|
| const action = e.target.getAttribute('data-action');
|
| if (action) {
|
| this.handleCellContextAction(action, cell);
|
| menu.remove();
|
| }
|
| });
|
|
|
|
|
| setTimeout(() => {
|
| document.addEventListener('click', () => {
|
| menu.remove();
|
| }, { once: true });
|
| }, 100);
|
| }
|
|
|
| |
| |
| |
| |
|
|
| 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;
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| 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...');
|
|
|
|
|
| const confirmed = confirm(`Save ${changes.length} changes to table ${tableName}?\n\nThis will modify the actual database.`);
|
| if (!confirmed) {
|
| this.hideLoading();
|
| return;
|
| }
|
|
|
|
|
| this.showToast('success', 'Changes Saved', `${changes.length} changes would be saved to ${tableName}`);
|
|
|
|
|
| table.querySelectorAll('td.modified').forEach(cell => {
|
| cell.classList.remove('modified');
|
| cell.setAttribute('data-original-value', cell.textContent);
|
| });
|
|
|
|
|
| table.querySelectorAll('tr.deleted-row').forEach(row => {
|
| row.remove();
|
| });
|
|
|
|
|
| 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();
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
|
|
| 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;
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
|
|
| exportTableData(table, tableName = 'table_data') {
|
| const rows = table.querySelectorAll('tr:not(.deleted-row)');
|
| const sqlStatements = [];
|
|
|
|
|
| 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;
|
| });
|
|
|
|
|
| const dbType = this.getCurrentDatabaseType();
|
|
|
|
|
| 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}`);
|
| sqlStatements.push('');
|
|
|
|
|
| sqlStatements.push(`-- Table structure for ${tableName}`);
|
| sqlStatements.push(`-- Columns: ${headers.join(', ')}`);
|
| sqlStatements.push('');
|
|
|
|
|
| sqlStatements.push(`-- Data for table ${tableName}`);
|
| sqlStatements.push('');
|
|
|
|
|
| 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';
|
| }
|
|
|
|
|
| if (!isNaN(value) && !isNaN(parseFloat(value)) && value !== '') {
|
| return value;
|
| }
|
|
|
|
|
| return this.formatSQLValue(value, dbType);
|
| });
|
|
|
|
|
| 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}`);
|
| }
|
|
|
|
|
| sqlStatements.push('');
|
| sqlStatements.push(`-- End of data export for ${tableName}`);
|
|
|
|
|
| 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`);
|
| }
|
|
|
| |
| |
| |
| |
|
|
| getCurrentDatabaseType() {
|
| if (!this.currentConnection) {
|
| return 'generic';
|
| }
|
|
|
| const connection = this.connections.find(c => c.id === this.currentConnection);
|
| return connection ? connection.type : 'generic';
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
|
|
| 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}"`;
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
|
|
| formatSQLValue(value, dbType) {
|
|
|
| if (value === null || value === undefined || value === '') {
|
| return 'NULL';
|
| }
|
|
|
|
|
| const stringValue = String(value).trim();
|
|
|
|
|
| if (stringValue === '' || stringValue.toLowerCase() === 'null') {
|
| return 'NULL';
|
| }
|
|
|
|
|
| if (/^-?\d+(\.\d+)?$/.test(stringValue)) {
|
| return stringValue;
|
| }
|
|
|
|
|
| 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}'`;
|
| }
|
| }
|
|
|
|
|
| let escapedValue = stringValue;
|
| switch (dbType) {
|
| case 'postgresql':
|
| case 'sqlite':
|
| case 'mssql':
|
| case 'sqlserver':
|
|
|
| escapedValue = escapedValue.replace(/'/g, "''");
|
| return `'${escapedValue}'`;
|
| case 'mysql':
|
| case 'mariadb':
|
|
|
| escapedValue = escapedValue.replace(/'/g, "''");
|
|
|
| escapedValue = escapedValue.replace(/\\/g, '\\\\');
|
| return `'${escapedValue}'`;
|
| default:
|
|
|
| escapedValue = escapedValue.replace(/'/g, "''");
|
| return `'${escapedValue}'`;
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
|
|
| updateConnectionFormDefaults(dbType) {
|
| const portField = document.getElementById('port');
|
| const hostField = document.getElementById('hostname');
|
|
|
|
|
| const defaultPorts = {
|
| postgresql: 5432,
|
| mysql: 3306,
|
| mariadb: 3306,
|
| sqlite: '',
|
| mongodb: 27017,
|
| redis: 6379
|
| };
|
|
|
| portField.value = defaultPorts[dbType] || '';
|
|
|
|
|
| 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';
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
|
|
| 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')
|
| };
|
|
|
|
|
| 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();
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
|
|
| 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;
|
| }
|
|
|
|
|
| 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`);
|
|
|
|
|
| if (this.currentConnection === selectedConnectionId) {
|
| this.currentConnection = null;
|
| this.updateStatus('disconnected', 'No connection selected');
|
|
|
|
|
| const treeContainer = document.getElementById('databaseTree');
|
| treeContainer.innerHTML = '<div class="tree-placeholder">Select a connection to view database structure</div>';
|
| }
|
|
|
|
|
| await this.loadConnections();
|
|
|
|
|
| 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();
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
|
|
| 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...');
|
|
|
|
|
| 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) {
|
|
|
| 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');
|
| }
|
|
|
|
|
| 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();
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
|
|
| async executeQuery() {
|
| if (!this.currentConnection) {
|
| console.warn('No Connection: Please select a database connection first');
|
| return;
|
| }
|
|
|
|
|
| let query = '';
|
| let queryTextarea = document.getElementById('queryTextarea');
|
|
|
|
|
| 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;
|
| }
|
|
|
|
|
| let params = null;
|
| let paramsInput = document.getElementById('queryParams');
|
|
|
|
|
| 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();
|
|
|
|
|
| let smartSyncCheckbox = document.getElementById('smartSyncMode');
|
| if (!smartSyncCheckbox) {
|
|
|
| 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 };
|
|
|
|
|
| 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();
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
|
|
| renderQueryResults(data, executionTime) {
|
| const resultsContainer = document.getElementById('resultsContent');
|
|
|
|
|
| document.getElementById('executionTime').textContent = `Executed in ${executionTime}ms`;
|
|
|
|
|
| if (data.command === 'SMART_SYNC' && data.smartSync) {
|
| this.renderSmartSyncResults(resultsContainer, data, executionTime);
|
| return;
|
| }
|
|
|
| if (data.type === 'select' && data.columns && data.columns.length > 0) {
|
|
|
| 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 {
|
|
|
| resultsContainer.innerHTML = `
|
| <div class="results-message">
|
| <p>${data.message || `Query executed successfully. ${data.rowCount || 0} rows affected.`}</p>
|
| <p class="text-muted">Execution time: ${executionTime}ms</p>
|
| </div>
|
| `;
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| renderSmartSyncResults(resultsContainer, data, executionTime) {
|
| const smartSync = data.smartSync;
|
|
|
| resultsContainer.innerHTML = `
|
| <div class="smart-sync-results">
|
| <div class="smart-sync-header">
|
| <h3> Smart Sync Results</h3>
|
| <div class="smart-sync-summary">
|
| <div class="summary-stat success">
|
| <span class="stat-number">${smartSync.created}</span>
|
| <span class="stat-label">สร้างใหม่</span>
|
| </div>
|
| <div class="summary-stat warning">
|
| <span class="stat-number">${smartSync.skipped}</span>
|
| <span class="stat-label">ข้าม</span>
|
| </div>
|
| <div class="summary-stat error">
|
| <span class="stat-number">${smartSync.failed}</span>
|
| <span class="stat-label">ล้มเหลว</span>
|
| </div>
|
| <div class="summary-stat info">
|
| <span class="stat-number">${smartSync.total}</span>
|
| <span class="stat-label">ทั้งหมด</span>
|
| </div>
|
| </div>
|
| <p class="execution-info">เสร็จใน ${executionTime}ms</p>
|
| </div>
|
|
|
| <div class="smart-sync-logs">
|
| <h4> Log รายละเอียด:</h4>
|
| <div class="log-container">
|
| ${smartSync.logs.map(log => `<div class="log-entry">${log}</div>`).join('')}
|
| </div>
|
| </div>
|
|
|
| ${smartSync.errors.length > 0 ? `
|
| <div class="smart-sync-errors">
|
| <h4> Errors ที่เกิดขึ้น:</h4>
|
| <div class="error-container">
|
| ${smartSync.errors.map(error => `
|
| <div class="error-entry">
|
| <div class="error-statement">${error.statement}</div>
|
| <div class="error-message">${error.error}</div>
|
| </div>
|
| `).join('')}
|
| </div>
|
| </div>
|
| ` : ''}
|
| </div>
|
| `;
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
|
|
| renderQueryError(errorMessage, tabId = null) {
|
| let resultsContainer;
|
|
|
| if (tabId) {
|
|
|
| const tab = this.tabs.get(tabId);
|
| if (tab && tab.content) {
|
| resultsContainer = tab.content.querySelector(`#resultsContent_${tabId}`);
|
| }
|
| }
|
|
|
|
|
| if (!resultsContainer) {
|
| resultsContainer = document.getElementById('resultsContent');
|
| }
|
|
|
| if (resultsContainer) {
|
| resultsContainer.innerHTML = `
|
| <div class="results-error">
|
| <h4>Query Error</h4>
|
| <pre>${errorMessage}</pre>
|
| </div>
|
| `;
|
| } else {
|
| console.error('Results container not found for error rendering');
|
| }
|
| }
|
|
|
|
|
| openSQLQueryTab() {
|
|
|
| const tabId = 'sql_query';
|
|
|
|
|
| if (this.tabs.has(tabId)) {
|
| this.switchToTab(tabId);
|
| return;
|
| }
|
|
|
|
|
| this.createSQLQueryTab(tabId);
|
| }
|
|
|
| createSQLQueryTab(tabId) {
|
| const tabBar = document.getElementById('tabBar');
|
|
|
|
|
| const tabElement = document.createElement('div');
|
| tabElement.className = 'tab-item';
|
| tabElement.dataset.tab = tabId;
|
| tabElement.innerHTML = `
|
| <span> ${this.t('SQL Query')}</span>
|
| <button class="tab-close">×</button>
|
| `;
|
|
|
|
|
| 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);
|
|
|
|
|
| const tabContent = document.createElement('div');
|
| tabContent.className = 'tab-pane sql-query-tab';
|
| tabContent.id = tabId;
|
| tabContent.innerHTML = `
|
| <div class="sql-query-container">
|
| <!-- Query Editor -->
|
| <div class="query-section">
|
| <div class="query-editor-container">
|
| <div class="editor-toolbar">
|
| <!-- Primary Actions Group -->
|
| <div class="toolbar-group">
|
| <button id="executeQueryBtn_${tabId}" class="btn btn-success">
|
| <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
|
| <path d="M8 5v14l11-7z"/>
|
| </svg>
|
| รัน
|
| </button>
|
| <button id="cancelQueryBtn_${tabId}" class="btn btn-outline" disabled>
|
| <span></span> ยกเลิก
|
| </button>
|
| </div>
|
|
|
| <div class="toolbar-separator"></div>
|
|
|
| <!-- Smart Sync Toggle -->
|
| <div class="toolbar-group">
|
| <div class="toolbar-item">
|
| <label class="smart-sync-toggle">
|
| <input type="checkbox" id="smartSyncMode_${tabId}" class="smart-sync-checkbox">
|
| <span class="smart-sync-label"> Smart Sync</span>
|
| <span class="smart-sync-tooltip" title="ป้องกัน Error จากการสร้าง Object ซ้ำ - เหมาะสำหรับ SQL Dumps">ℹ</span>
|
| </label>
|
| </div>
|
| </div>
|
|
|
| <div class="toolbar-separator"></div>
|
|
|
| <!-- File Operations Dropdown -->
|
| <div class="dropdown" id="fileDropdown_${tabId}">
|
| <button class="dropdown-button" type="button">
|
| <span> ไฟล์</span>
|
| <span class="dropdown-arrow">▼</span>
|
| </button>
|
| <div class="dropdown-menu">
|
| <button class="dropdown-item" id="importSQLBtn_${tabId}">
|
| <span></span> นำเข้าไฟล์ SQL
|
| </button>
|
| <button class="dropdown-item" id="saveQueryBtn_${tabId}">
|
| <span></span> บันทึก Query
|
| </button>
|
| <button class="dropdown-item" id="loadQueryBtn_${tabId}">
|
| <span>�</span> โหลด Query
|
| </button>
|
| <div class="dropdown-separator"></div>
|
| <button class="dropdown-item" id="importDataBtn_${tabId}">
|
| <span></span> เพิ่มข้อมูล
|
| </button>
|
| </div>
|
| </div>
|
|
|
| <!-- Query Tools Dropdown -->
|
| <div class="dropdown" id="toolsDropdown_${tabId}">
|
| <button class="dropdown-button" type="button">
|
| <span> เครื่องมือ</span>
|
| <span class="dropdown-arrow">▼</span>
|
| </button>
|
| <div class="dropdown-menu">
|
| <button class="dropdown-item" id="formatQueryBtn_${tabId}">
|
| <span></span> จัดรูปแบบ
|
| </button>
|
| <button class="dropdown-item" id="explainQueryBtn_${tabId}">
|
| <span></span> อธิบาย Query
|
| </button>
|
| <button class="dropdown-item" id="clearQueryBtn_${tabId}">
|
| <span></span> ล้าง Query
|
| </button>
|
| </div>
|
| </div>
|
|
|
| <!-- Transaction Dropdown -->
|
| <div class="dropdown" id="transactionDropdown_${tabId}">
|
| <button class="dropdown-button" type="button">
|
| <span> Transaction</span>
|
| <span class="dropdown-arrow">▼</span>
|
| </button>
|
| <div class="dropdown-menu">
|
| <button class="dropdown-item" id="commitBtn_${tabId}" disabled>
|
| <span></span> ยืนยัน (Commit)
|
| </button>
|
| <button class="dropdown-item" id="rollbackBtn_${tabId}" disabled>
|
| <span>↩</span> ย้อนกลับ (Rollback)
|
| </button>
|
| </div>
|
| </div>
|
|
|
| <div class="toolbar-spacer"></div>
|
| <span class="execution-time" id="executionTime_${tabId}"></span>
|
| </div>
|
|
|
| <div class="query-editor">
|
| <textarea id="queryTextarea_${tabId}" class="sql-editor" placeholder="${this.t('Enter your SQL query here...')}"></textarea>
|
| <div class="params-section">
|
| <label for="queryParams_${tabId}" class="params-label">
|
| Parameters (JSON):
|
| <span class="params-help" title="Array: [42, 'test'] or Object: {"id": 42, "name": "test"}">ℹ</span>
|
| </label>
|
| <textarea id="queryParams_${tabId}" class="params-editor"
|
| placeholder='Optional: ["value1", "value2"] or {"name": "value", "id": 123}'
|
| rows="2"></textarea>
|
| </div>
|
| </div>
|
| </div>
|
| </div>
|
|
|
| <!-- Resizable Splitter -->
|
| <div class="splitter horizontal-splitter" id="horizontalSplitter_${tabId}"></div>
|
|
|
| <!-- Results -->
|
| <div class="results-section">
|
| <div class="results-container">
|
| <div class="results-content" id="resultsContent_${tabId}">
|
| <div class="results-placeholder">
|
| <p>Execute a query to see results here</p>
|
| </div>
|
| </div>
|
| </div>
|
| </div>
|
| </div>
|
| `;
|
|
|
| document.querySelector('.tab-content').appendChild(tabContent);
|
|
|
|
|
| this.tabs.set(tabId, {
|
| title: 'SQL Query',
|
| type: 'sql-query',
|
| element: tabElement,
|
| content: tabContent
|
| });
|
|
|
|
|
|
|
| setTimeout(() => {
|
| this.initializeSQLQueryTabEvents(tabId);
|
| }, 100);
|
|
|
|
|
| this.switchToTab(tabId);
|
| }
|
|
|
| initializeSQLQueryTabEvents(tabId) {
|
| console.log(` Initializing events for SQL Query tab: ${tabId}`);
|
|
|
|
|
| this.initializeSplitterForTab(tabId);
|
|
|
|
|
| this.initializeDropdownMenus(tabId);
|
|
|
|
|
| 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);
|
| });
|
| }
|
|
|
|
|
| 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);
|
| });
|
| }
|
|
|
|
|
| const cancelBtn = document.getElementById(`cancelQueryBtn_${tabId}`);
|
| console.log(`Cancel button found:`, cancelBtn);
|
| if (cancelBtn) {
|
| cancelBtn.addEventListener('click', () => {
|
| this.cancelQueryInTab(tabId);
|
| });
|
| }
|
|
|
|
|
| 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);
|
| });
|
| }
|
|
|
|
|
| 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);
|
| });
|
| }
|
|
|
|
|
| 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}`);
|
|
|
|
|
| const saveBtn = document.getElementById(`saveQueryBtn_${tabId}`);
|
| if (saveBtn) {
|
| saveBtn.addEventListener('click', () => {
|
| this.saveQueryInTab(tabId);
|
| });
|
| }
|
|
|
|
|
| const loadBtn = document.getElementById(`loadQueryBtn_${tabId}`);
|
| if (loadBtn) {
|
| loadBtn.addEventListener('click', () => {
|
| this.loadQueryInTab(tabId);
|
| });
|
| }
|
|
|
|
|
| const importDataBtn = document.getElementById(`importDataBtn_${tabId}`);
|
| if (importDataBtn) {
|
| importDataBtn.addEventListener('click', () => {
|
| console.log(` Import Data button clicked for tab: ${tabId}`);
|
| this.showImportDataModal(tabId);
|
| });
|
| }
|
|
|
|
|
| const commitBtn = document.getElementById(`commitBtn_${tabId}`);
|
| if (commitBtn) {
|
| commitBtn.addEventListener('click', () => {
|
| console.log(` Commit button clicked for tab: ${tabId}`);
|
| this.commitTransactionInTab(tabId);
|
| });
|
| }
|
|
|
|
|
| const rollbackBtn = document.getElementById(`rollbackBtn_${tabId}`);
|
| if (rollbackBtn) {
|
| rollbackBtn.addEventListener('click', () => {
|
| console.log(`↩ Rollback button clicked for tab: ${tabId}`);
|
| this.rollbackTransactionInTab(tabId);
|
| });
|
| }
|
|
|
|
|
| const textarea = document.getElementById(`queryTextarea_${tabId}`);
|
| if (textarea) {
|
| textarea.addEventListener('keydown', (e) => {
|
| if (e.ctrlKey && e.key === 'Enter') {
|
| e.preventDefault();
|
| this.executeSQLQueryInTab(tabId);
|
| }
|
|
|
| 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`);
|
|
|
| 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;
|
|
|
|
|
| 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;
|
| }
|
|
|
|
|
| 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...');
|
|
|
|
|
| if (query.length > 1000000) {
|
| const proceed = confirm('นี่เป็น SQL dump ขนาดใหญ่มาก (มากกว่า 1MB) อาจต้องใช้เวลานาน หรือเกิดข้อผิดพลาด\nคุณต้องการทำต่อหรือไม่?');
|
| if (!proceed) {
|
| if (executeBtn) executeBtn.disabled = false;
|
| if (cancelBtn) cancelBtn.disabled = true;
|
| return;
|
| }
|
| }
|
| }
|
|
|
|
|
| if (executeBtn) executeBtn.disabled = true;
|
| if (cancelBtn) cancelBtn.disabled = false;
|
|
|
| try {
|
| this.showLoading('Executing query...');
|
| const startTime = Date.now();
|
|
|
|
|
| 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);
|
| }
|
|
|
|
|
| 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;
|
|
|
|
|
| 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`);
|
|
|
|
|
| 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();
|
|
|
| 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}`);
|
|
|
|
|
| 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}`);
|
|
|
|
|
| if (executionTimeDisplay) {
|
| executionTimeDisplay.textContent = `Executed in ${executionTime}ms`;
|
| }
|
|
|
|
|
| if (data.command === 'SMART_SYNC' && data.smartSync) {
|
| this.renderSmartSyncResults(resultsContainer, data, executionTime);
|
| return;
|
| }
|
|
|
| if (data.type === 'select' && data.columns && data.columns.length > 0) {
|
|
|
| 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 {
|
|
|
| let messageContent = '';
|
|
|
|
|
| if (data.summary) {
|
| const { total, succeeded, failed, rowsAffected, errors } = data.summary;
|
|
|
| messageContent = `
|
| <div class="results-message">
|
| <h4> Database Import Summary</h4>
|
| <div class="import-stats">
|
| <div class="stat-row">
|
| <span class="stat-label">Statements Executed:</span>
|
| <span class="stat-value success">${succeeded} successful</span>
|
| <span class="stat-divider">/</span>
|
| <span class="stat-value ${failed > 0 ? 'error' : 'muted'}">${failed} failed</span>
|
| <span class="stat-divider">/</span>
|
| <span class="stat-value">${total} total</span>
|
| </div>
|
| ${rowsAffected > 0 ? `
|
| <div class="stat-row">
|
| <span class="stat-label">Data Imported:</span>
|
| <span class="stat-value success">${rowsAffected} rows affected</span>
|
| </div>
|
| ` : ''}
|
| </div>
|
|
|
| ${errors && errors.length > 0 ? `
|
| <details class="error-details">
|
| <summary> View Errors (${errors.length})</summary>
|
| <ul class="error-list">
|
| ${errors.map(error => `<li>${error}</li>`).join('')}
|
| </ul>
|
| </details>
|
| ` : ''}
|
|
|
| <p class="text-muted">Execution time: ${executionTime}ms</p>
|
| </div>
|
| `;
|
| } else {
|
|
|
| const rowsText = data.rowCount === 1 ? 'row' : 'rows';
|
| messageContent = `
|
| <div class="results-message">
|
| <p class="success-text"> ${data.message || `Query executed successfully. ${data.rowCount || 0} ${rowsText} affected.`}</p>
|
| <p class="text-muted">Execution time: ${executionTime}ms</p>
|
| </div>
|
| `;
|
| }
|
|
|
| resultsContainer.innerHTML = messageContent;
|
| }
|
| }
|
|
|
| renderSQLQueryError(tabId, errorMessage) {
|
| const resultsContainer = document.getElementById(`resultsContent_${tabId}`);
|
| resultsContainer.innerHTML = `
|
| <div class="results-error">
|
| <h4>Query Error</h4>
|
| <pre>${errorMessage}</pre>
|
| </div>
|
| `;
|
| }
|
|
|
|
|
|
|
| async cancelQueryInTab(tabId) {
|
| console.log(` Cancel query requested for tab: ${tabId}`);
|
|
|
|
|
| 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';
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| 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 {
|
|
|
| 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');
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| formatSQL(sql) {
|
|
|
| return sql
|
| .replace(/\s+/g, ' ')
|
| .replace(/\s*,\s*/g, ',\n ')
|
| .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();
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| 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;
|
| }
|
|
|
|
|
| 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;
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| displayExplainResultsInTab(results, tabId) {
|
| const resultsContainer = document.getElementById(`resultsContent_${tabId}`);
|
| if (!resultsContainer) {
|
| console.error(` Results container not found for tab: ${tabId}`);
|
| return;
|
| }
|
|
|
|
|
| resultsContainer.innerHTML = `
|
| <div class="explain-plan-container">
|
| <div class="explain-header">
|
| <h3> Query Execution Plan</h3>
|
| </div>
|
| <div class="explain-content">
|
| <pre class="explain-text">${JSON.stringify(results, null, 2)}</pre>
|
| </div>
|
| </div>
|
| `;
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| async commitTransactionInTab(tabId) {
|
| await this.executeTransactionCommand('COMMIT', tabId);
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| async rollbackTransactionInTab(tabId) {
|
| await this.executeTransactionCommand('ROLLBACK', tabId);
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| 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`);
|
|
|
|
|
| const resultsContainer = document.getElementById(`resultsContent_${tabId}`);
|
| if (resultsContainer) {
|
| resultsContainer.innerHTML = `
|
| <div class="results-message">
|
| <p> ${command} executed successfully</p>
|
| </div>
|
| `;
|
| }
|
|
|
|
|
| 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;
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| updateTransactionButtonsState(tabId) {
|
|
|
| const commitBtn = document.getElementById(`commitBtn_${tabId}`);
|
| const rollbackBtn = document.getElementById(`rollbackBtn_${tabId}`);
|
|
|
| if (commitBtn) commitBtn.disabled = false;
|
| if (rollbackBtn) rollbackBtn.disabled = false;
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| 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;
|
| }
|
|
|
|
|
| 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}`);
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| loadQueryInTab(tabId) {
|
| const textarea = document.getElementById(`queryTextarea_${tabId}`);
|
| if (!textarea) {
|
| console.error(` Query textarea not found for tab: ${tabId}`);
|
| return;
|
| }
|
|
|
|
|
| const savedQueries = JSON.parse(localStorage.getItem('savedQueries') || '[]');
|
|
|
| if (savedQueries.length === 0) {
|
| console.warn('No saved queries found');
|
| return;
|
| }
|
|
|
|
|
| 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') {
|
|
|
| const tabId = `table_${tableName}`;
|
|
|
|
|
| if (this.tabs.has(tabId)) {
|
| this.switchToTab(tabId);
|
| return;
|
| }
|
|
|
|
|
| this.createTableTab(tabId, tableName, type);
|
|
|
|
|
| this.loadTableData(tabId, tableName, type);
|
| }
|
|
|
|
|
| createTableTab(tabId, tableName, type) {
|
| const tabBar = document.getElementById('tabBar');
|
|
|
|
|
| const tabElement = document.createElement('div');
|
| tabElement.className = 'tab-item';
|
| tabElement.dataset.tab = tabId;
|
| tabElement.innerHTML = `
|
| <span> ${tableName}</span>
|
| <button class="tab-close">×</button>
|
| `;
|
|
|
|
|
| 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);
|
|
|
|
|
| const tabContent = document.createElement('div');
|
| tabContent.className = 'tab-pane table-only-tab';
|
| tabContent.id = tabId;
|
| tabContent.innerHTML = `
|
| <div class="table-only-container">
|
| <div class="results-content" id="resultsContent_${tabId}">
|
| <div class="results-placeholder">
|
| <p>Loading ${tableName} data...</p>
|
| </div>
|
| </div>
|
| </div>
|
| `;
|
|
|
| document.querySelector('.tab-content').appendChild(tabContent);
|
|
|
|
|
| this.tabs.set(tabId, {
|
| title: tableName,
|
| type,
|
| element: tabElement,
|
| content: tabContent,
|
| tableName: tableName
|
| });
|
|
|
|
|
| this.switchToTab(tabId);
|
| }
|
|
|
| async loadTableInQueryTab(tableName, type = 'table') {
|
| if (!this.currentConnection) {
|
| this.showToast('error', 'No Connection', 'Please connect to a database first');
|
| return;
|
| }
|
|
|
| try {
|
|
|
| const tableTabId = `table_${tableName}`;
|
|
|
|
|
| if (!this.tabs.has(tableTabId)) {
|
| this.createTableTab(tableTabId, tableName, type);
|
| } else {
|
| this.switchToTab(tableTabId);
|
| }
|
|
|
|
|
| this.showLoading(`Loading ${type} ${tableName}...`);
|
|
|
|
|
| let query = `SELECT * FROM ${tableName} LIMIT 100;`;
|
|
|
|
|
| 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) {
|
|
|
| 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) {
|
|
|
| const tab = this.tabs.get(tabId);
|
| if (tab && tab.content) {
|
| resultsContainer = tab.content.querySelector(`#resultsContent_${tabId}`);
|
| executionTimeElement = tab.content.querySelector('.execution-time, #executionTime');
|
| }
|
| }
|
|
|
|
|
| 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;
|
| }
|
|
|
|
|
| if (executionTimeElement) {
|
| executionTimeElement.textContent = `Loaded in ${executionTime}ms`;
|
| }
|
|
|
|
|
| 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) {
|
|
|
| const filterInput = document.getElementById('tableFilter');
|
| if (filterInput) {
|
| filterInput.addEventListener('input', (e) => {
|
| this.filterTable(table, e.target.value);
|
| });
|
| }
|
|
|
|
|
| const clearFilterBtn = document.getElementById('clearFilter');
|
| if (clearFilterBtn) {
|
| clearFilterBtn.addEventListener('click', () => {
|
| filterInput.value = '';
|
| this.filterTable(table, '');
|
| });
|
| }
|
|
|
|
|
| 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', () => {
|
| this.refreshTableData(tableName);
|
| });
|
| }
|
|
|
|
|
| const exportBtn = document.getElementById('exportTableBtn');
|
| if (exportBtn) {
|
| exportBtn.addEventListener('click', () => {
|
| this.exportTableData(table, tableName);
|
| });
|
| }
|
|
|
|
|
| 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();
|
| 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 = '<span class="null-indicator">NULL</span>';
|
| cell.setAttribute('data-original-value', null);
|
| this.markTableAsModified(cell.closest('table'));
|
| }
|
|
|
| createTab(tabId, title, type = 'table') {
|
| const tabBar = document.getElementById('tabBar');
|
|
|
|
|
| const tabElement = document.createElement('div');
|
| tabElement.className = 'tab-item';
|
| tabElement.dataset.tab = tabId;
|
| tabElement.innerHTML = `
|
| <span>${title}</span>
|
| <button class="tab-close">×</button>
|
| `;
|
|
|
|
|
| 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);
|
|
|
|
|
| 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);
|
|
|
|
|
| this.tabs.set(tabId, { title, type, element: tabElement, content: tabContent });
|
|
|
|
|
| this.switchToTab(tabId);
|
| }
|
|
|
| switchToTab(tabId) {
|
| console.log('Switching to tab:', tabId);
|
|
|
|
|
| document.querySelectorAll('.tab-item').forEach(tab => {
|
| tab.classList.remove('active');
|
| });
|
|
|
| document.querySelectorAll('.tab-pane').forEach(pane => {
|
| pane.classList.remove('active');
|
| pane.style.display = 'none';
|
| });
|
|
|
|
|
| if (this.tabs.has(tabId)) {
|
|
|
| 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') {
|
|
|
| console.log('Query tab not found, creating new SQL Query tab');
|
| this.openSQLQueryTab();
|
| return;
|
| } 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);
|
|
|
|
|
| if (this.activeTab === tabId) {
|
|
|
| if (this.tabs.size === 0) {
|
| this.openSQLQueryTab();
|
| } else {
|
|
|
| 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}...`);
|
|
|
|
|
| let orderByClause = '';
|
|
|
|
|
| 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) {
|
|
|
| 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);
|
| }
|
|
|
|
|
| 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();
|
| }
|
| }
|
|
|
|
|
| renderTableDataInTab(tabId, data, executionTime, tableName) {
|
| const tab = this.tabs.get(tabId);
|
| if (!tab) return;
|
|
|
| const resultsContainer = tab.content.querySelector(`#resultsContent_${tabId}`);
|
| if (!resultsContainer) return;
|
|
|
|
|
| this.currentTable = tableName;
|
|
|
|
|
| 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 = '<div class="table-placeholder"><p>No data found</p></div>';
|
| paginationInfo.textContent = 'No data';
|
| return;
|
| }
|
|
|
|
|
| const table = document.createElement('table');
|
| table.className = 'data-table';
|
|
|
|
|
| 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);
|
|
|
|
|
| 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;
|
| }
|
| tr.appendChild(td);
|
| });
|
|
|
| tbody.appendChild(tr);
|
| });
|
|
|
| table.appendChild(tbody);
|
| tableContainer.innerHTML = '';
|
| tableContainer.appendChild(table);
|
|
|
|
|
| paginationInfo.textContent = `Showing ${((data.page - 1) * data.limit) + 1}-${Math.min(data.page * data.limit, data.total)} of ${data.total} rows`;
|
| }
|
|
|
|
|
| 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) {
|
|
|
| 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');
|
| }
|
|
|
|
|
| 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() {
|
|
|
| if (this.currentGridApi) {
|
| this.exportGridDataAsSQL('query_results');
|
| } else {
|
|
|
| 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}`);
|
|
|
|
|
| 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 {
|
|
|
| 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];
|
|
|
|
|
| const readResult = await window.electronAPI.readFile(filePath);
|
| if (readResult.success) {
|
|
|
| const textarea = document.getElementById(`queryTextarea_${tabId}`);
|
| if (textarea) {
|
| textarea.value = readResult.content;
|
| this.showToast('success', 'SQL Imported', `SQL file imported to tab: ${filePath}`);
|
|
|
|
|
| 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);
|
| }
|
| }
|
|
|
|
|
| renderTableWithAGGrid(container, data, executionTime, tableName = 'Query Results') {
|
|
|
| container.innerHTML = '';
|
|
|
|
|
| const gridWrapper = document.createElement('div');
|
| gridWrapper.className = 'ag-grid-wrapper';
|
|
|
|
|
| const toolbar = document.createElement('div');
|
| toolbar.className = 'table-toolbar ag-grid-toolbar';
|
|
|
|
|
| const isTableView = tableName !== 'Query Results';
|
| const crudControls = isTableView ? `
|
| <div class="table-actions">
|
| <div class="changes-status no-changes" id="changesStatus"> No changes</div>
|
| <button class="btn btn-success btn-sm" id="addRowBtn" onclick="window.dbManager.addRowToGrid()"> เพิ่มแถว</button>
|
| <button class="btn btn-danger btn-sm" id="deleteSelectedBtn" disabled onclick="window.dbManager.deleteSelectedRows()"> ลบแถวที่เลือก</button>
|
| <button class="btn btn-info btn-sm" id="editSelectedBtn" disabled onclick="window.dbManager.editSelectedRow()"> แก้ไขแถวที่เลือก</button>
|
| <button class="btn btn-warning btn-sm save-changes" id="saveChangesBtn" disabled onclick="window.dbManager.saveGridChanges('${tableName}')"> บันทึก</button>
|
| <button class="btn btn-secondary btn-sm" id="cancelChangesBtn" disabled onclick="window.dbManager.cancelGridChanges('${tableName}')"> ยกเลิก</button>
|
| <button class="btn btn-info btn-sm" id="refreshTableBtn" onclick="window.dbManager.refreshTableData('${tableName}')"> รีเฟรช</button>
|
| <button class="btn btn-primary btn-sm" id="exportTableBtn"> Export SQL</button>
|
| </div>
|
| ` : `
|
| <div class="table-actions">
|
| <button class="btn btn-primary btn-sm" id="exportTableBtn"> Export SQL</button>
|
| </div>
|
| `;
|
|
|
| toolbar.innerHTML = `
|
| <div class="table-info">
|
| <span class="table-name">� ${tableName}</span>
|
| <span class="table-stats">${data.rowCount || data.rows?.length || 0} rows • ${(data.columns || []).length} columns</span>
|
| </div>
|
| <div class="table-controls">
|
| <div class="table-filter">
|
| <input type="text" placeholder=" Filter all columns..." id="globalFilter" class="filter-input">
|
| <button class="btn btn-outline btn-sm" id="clearFilter"></button>
|
| </div>
|
| ${crudControls}
|
| </div>
|
| `;
|
|
|
|
|
| const gridContainer = document.createElement('div');
|
| gridContainer.className = 'ag-theme-balham-dark';
|
|
|
|
|
| if (container.closest('.table-only-tab')) {
|
|
|
| gridContainer.style.flex = '1';
|
| gridContainer.style.height = 'auto';
|
| } else {
|
|
|
| gridContainer.style.flex = '1';
|
| gridContainer.style.height = 'auto';
|
| gridContainer.style.minHeight = '300px';
|
| }
|
| gridContainer.style.width = '100%';
|
|
|
|
|
| const columnDefs = [];
|
|
|
|
|
| columnDefs.push({
|
| headerName: '#',
|
| valueGetter: 'node.rowIndex + 1',
|
| width: 60,
|
| pinned: 'left',
|
| suppressMovable: true,
|
| suppressResize: true,
|
| cellClass: 'row-number-cell'
|
| });
|
|
|
|
|
| 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',
|
|
|
| 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 '<span class="null-value">NULL</span>';
|
| }
|
| if (typeof params.value === 'string' && params.value.length > 100) {
|
| return `<span title="${params.value}">${params.value.substring(0, 100)}...</span>`;
|
| }
|
| return params.value;
|
| },
|
| valueSetter: (params) => {
|
|
|
| if (params.newValue === '' || params.newValue === 'NULL') {
|
| params.data[params.colDef.field] = null;
|
| } else {
|
| params.data[params.colDef.field] = params.newValue;
|
| }
|
| return true;
|
| }
|
| };
|
|
|
|
|
| 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;
|
| }
|
|
|
|
|
| if (valueA < valueB) return -1;
|
| if (valueA > valueB) return 1;
|
| return 0;
|
| };
|
|
|
|
|
| if (column.toLowerCase() === 'id') {
|
| columnDef.sort = 'asc';
|
| }
|
| }
|
|
|
| columnDefs.push(columnDef);
|
| });
|
| }
|
|
|
|
|
| const rowData = [];
|
| if (data.rows && data.rows.length > 0) {
|
| data.rows.forEach(row => {
|
| const rowObject = {};
|
| data.columns.forEach((column, index) => {
|
| rowObject[column] = row[index];
|
| });
|
|
|
| rowData.push(this.normalizeRowData(rowObject, tableName));
|
| });
|
| } else if (data.columns && data.columns.length > 0) {
|
|
|
| const emptyRow = {};
|
| data.columns.forEach(column => {
|
| emptyRow[column] = null;
|
| });
|
| rowData.push(this.normalizeRowData(emptyRow, tableName));
|
| }
|
|
|
|
|
| const gridOptions = {
|
| columnDefs: columnDefs,
|
| rowData: rowData,
|
| getRowId: (params) => {
|
|
|
| const primaryKey = this.getPrimaryKeyForTable(tableName) || 'id';
|
| const id = params.data[primaryKey];
|
| return String(id);
|
| },
|
| defaultColDef: {
|
| sortable: true,
|
| filter: true,
|
| resizable: true,
|
| editable: true,
|
| cellClass: 'ag-cell-data'
|
| },
|
|
|
|
|
| sortingOrder: ['asc', 'desc'],
|
|
|
|
|
| enableRangeSelection: true,
|
| enableCellTextSelection: true,
|
| enableFillHandle: true,
|
| suppressRowClickSelection: false,
|
| rowSelection: 'multiple',
|
| animateRows: false,
|
| suppressCellFocus: false,
|
| suppressColumnVirtualisation: false,
|
| suppressRowVirtualisation: false,
|
|
|
|
|
| getContextMenuItems: (params) => {
|
| const result = [];
|
|
|
|
|
| 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;
|
| },
|
|
|
|
|
| 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;
|
| }
|
| },
|
|
|
|
|
| onCellValueChanged: (event) => {
|
|
|
|
|
|
|
| setTimeout(() => {
|
| if (event.node && event.data && !event.data._isNew) {
|
|
|
| event.data._isDirty = true;
|
| event.node.setData(event.data);
|
| }
|
| this.markGridAsModified();
|
|
|
|
|
| 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();
|
|
|
|
|
| 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()
|
| });
|
| }
|
| };
|
|
|
|
|
| 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);
|
|
|
|
|
| this.currentGridApi = gridApi;
|
|
|
| console.log(' AG Grid created successfully:', gridApi);
|
|
|
|
|
| setTimeout(() => {
|
| if (this.currentGridApi && data.columns) {
|
|
|
| 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 {
|
|
|
| console.log(` Setting initial sort by first column: ${data.columns[0]}`);
|
| this.currentGridApi.applyColumnState({
|
| state: [{ colId: data.columns[0], sort: 'asc' }]
|
| });
|
| }
|
| }
|
| }, 100);
|
|
|
|
|
| const resultsInfo = document.createElement('div');
|
| resultsInfo.className = 'results-info enhanced';
|
| resultsInfo.innerHTML = `
|
| <div class="info-left">
|
| <span class="info-item"> Rows: ${data.rowCount || data.rows?.length || 0}</span>
|
| <span class="info-item">⏱ Load time: ${executionTime}ms</span>
|
| <span class="info-item" id="changesStatus"> No changes</span>
|
| </div>
|
| <div class="info-right">
|
| <span class="info-item"> Table: ${tableName}</span>
|
| <span class="info-item"> Columns: ${(data.columns || []).length}</span>
|
| </div>
|
| `;
|
|
|
|
|
| gridWrapper.appendChild(toolbar);
|
| gridWrapper.appendChild(gridContainer);
|
| gridWrapper.appendChild(resultsInfo);
|
|
|
| container.appendChild(gridWrapper);
|
|
|
|
|
| this.currentGrid = gridOptions;
|
| this.currentGridApi = gridApi;
|
|
|
|
|
| this.attachAGGridEventListeners(tableName);
|
|
|
| return gridOptions;
|
| }
|
|
|
| attachAGGridEventListeners(tableName) {
|
|
|
| const globalFilter = document.getElementById('globalFilter');
|
| if (globalFilter && this.currentGridApi) {
|
| globalFilter.addEventListener('input', (e) => {
|
| this.currentGridApi.setQuickFilter(e.target.value);
|
| });
|
| }
|
|
|
|
|
| const clearFilterBtn = document.getElementById('clearFilter');
|
| if (clearFilterBtn && this.currentGridApi) {
|
| clearFilterBtn.addEventListener('click', () => {
|
| if (globalFilter) {
|
| globalFilter.value = '';
|
| this.currentGridApi.setQuickFilter('');
|
| }
|
| });
|
| }
|
|
|
|
|
| const addRowBtn = document.getElementById('addRowBtn');
|
| if (addRowBtn) {
|
| addRowBtn.addEventListener('click', () => {
|
| if (tableName !== 'Query Results') {
|
| this.showAddRowForm(tableName);
|
| } else {
|
| this.addRowToGrid();
|
| }
|
| });
|
| }
|
|
|
|
|
| const deleteSelectedBtn = document.getElementById('deleteSelectedBtn');
|
| if (deleteSelectedBtn) {
|
| deleteSelectedBtn.addEventListener('click', () => {
|
| this.deleteSelectedRows();
|
| });
|
| }
|
|
|
|
|
| const editSelectedBtn = document.getElementById('editSelectedBtn');
|
| if (editSelectedBtn) {
|
| editSelectedBtn.addEventListener('click', () => {
|
| this.editSelectedRow();
|
| });
|
| }
|
|
|
|
|
| const saveChangesBtn = document.getElementById('saveChangesBtn');
|
| if (saveChangesBtn) {
|
| saveChangesBtn.addEventListener('click', () => {
|
| this.saveGridChanges(tableName);
|
| });
|
| }
|
|
|
|
|
| const cancelChangesBtn = document.getElementById('cancelChangesBtn');
|
| if (cancelChangesBtn) {
|
| cancelChangesBtn.addEventListener('click', () => {
|
| this.cancelGridChanges(tableName);
|
| });
|
| }
|
|
|
|
|
| const refreshBtn = document.getElementById('refreshTableBtn');
|
| if (refreshBtn) {
|
| refreshBtn.addEventListener('click', () => {
|
| if (tableName !== 'Query Results') {
|
|
|
| this.refreshTableData(tableName);
|
| } else {
|
| this.executeQuery();
|
| }
|
| });
|
| }
|
|
|
|
|
| const exportBtn = document.getElementById('exportTableBtn');
|
| if (exportBtn) {
|
| exportBtn.addEventListener('click', () => {
|
| this.exportGridDataAsSQL(tableName);
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
|
|
| markGridAsModified() {
|
| console.log(' markGridAsModified called');
|
| const saveBtn = document.getElementById('saveChangesBtn');
|
| const cancelBtn = document.getElementById('cancelChangesBtn');
|
| const changesStatus = document.getElementById('changesStatus');
|
|
|
| if (this.currentGridApi) {
|
|
|
| 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;
|
| }
|
|
|
| const totalChanges = newRows + modifiedRows + deletedRows;
|
| console.log(` Changes count: new=${newRows}, modified=${modifiedRows}, deleted=${deletedRows}, total=${totalChanges}`);
|
|
|
|
|
| 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)');
|
| }
|
|
|
|
|
| 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';
|
| }
|
| }
|
|
|
|
|
| this.updateActionButtonStates();
|
| }
|
| }
|
|
|
| addRowToGrid() {
|
| if (this.currentGridApi) {
|
| const newRow = {};
|
|
|
| const columnDefs = this.currentGridApi.getColumnDefs();
|
|
|
| if (columnDefs && columnDefs.length > 0) {
|
| columnDefs.forEach(col => {
|
| if (col.field && col.field !== 'actions') {
|
| newRow[col.field] = null;
|
| }
|
| });
|
| }
|
|
|
|
|
|
|
| newRow._isNew = true;
|
|
|
|
|
| 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();
|
|
|
|
|
| setTimeout(() => {
|
| const rowCount = this.currentGridApi.getDisplayedRowCount();
|
| this.currentGridApi.ensureIndexVisible(rowCount - 1);
|
| const rowNode = this.currentGridApi.getDisplayedRowAtIndex(rowCount - 1);
|
| if (rowNode) {
|
| 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(rowCount - 1, firstEditableColumn.field);
|
| }
|
| }
|
| }, 100);
|
| } else {
|
| this.showToast('error', 'Error', 'ไม่สามารถเพิ่มแถวได้ กรุณาโหลดตารางก่อน');
|
| }
|
| }
|
|
|
|
|
| getCurrentDatabaseType() {
|
| return 'postgresql';
|
| }
|
|
|
|
|
| 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;
|
| }
|
| }
|
|
|
|
|
| formatSQLValue(value, dbType) {
|
| if (value === null || value === undefined) {
|
| return 'NULL';
|
| }
|
|
|
| if (typeof value === 'string') {
|
|
|
| const escaped = value.replace(/'/g, "''");
|
| return `'${escaped}'`;
|
| }
|
|
|
| if (typeof value === 'number') {
|
| return value.toString();
|
| }
|
|
|
| if (typeof value === 'boolean') {
|
| return value ? 'TRUE' : 'FALSE';
|
| }
|
|
|
|
|
| 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<Array>} 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<void>}
|
| * @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 = `
|
| <div class="table-info">
|
| <span class="table-name"> ${tableName}</span>
|
| <span class="table-stats">${data.rowCount || data.rows?.length || 0} rows • ${(data.columns || []).length} columns</span>
|
| </div>
|
| <div class="table-controls">
|
| <div class="table-filter">
|
| <input type="text" placeholder=" Filter data..." id="tableFilter" class="filter-input">
|
| <button class="btn btn-outline btn-sm" id="clearFilter"></button>
|
| </div>
|
| <div class="table-actions">
|
| <button class="btn btn-success btn-sm" id="addRowBtn"> Add Row</button>
|
| <button class="btn btn-warning btn-sm" id="saveChangesBtn" disabled> Save Changes</button>
|
| <button class="btn btn-info btn-sm" id="refreshTableBtn"> Refresh</button>
|
| <button class="btn btn-primary btn-sm" id="exportTableBtn"> Export SQL</button>
|
| </div>
|
| </div>
|
| `;
|
|
|
| // 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 = `
|
| <div class="column-header-content">
|
| <span class="column-name">${column}</span>
|
| <span class="sort-indicator"></span>
|
| </div>
|
| `;
|
| 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 = '<span class="null-indicator">NULL</span>';
|
| } 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 = '<span class="null-indicator">NULL</span>';
|
|
|
| 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 = `
|
| <div class="info-left">
|
| <span class="info-item"> Rows: ${data.rowCount || data.rows?.length || 0}</span>
|
| <span class="info-item">⏱ Load time: ${executionTime}ms</span>
|
| <span class="info-item" id="changesStatus"> No changes</span>
|
| </div>
|
| <div class="info-right">
|
| <span class="info-item"> Table: ${tableName}</span>
|
| <span class="info-item"> Columns: ${(data.columns || []).length}</span>
|
| </div>
|
| `;
|
|
|
| // 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 = `
|
| <div class="modal active" id="importDataModal">
|
| <div class="modal-content import-data-modal">
|
| <div class="modal-header">
|
| <h3> เพิ่มข้อมูลเข้าตาราง</h3>
|
| <button class="modal-close">×</button>
|
| </div>
|
| <div class="modal-body">
|
| <div class="form-group">
|
| <label for="targetTable">เลือกตาราง:</label>
|
| <select id="targetTable" class="form-control">
|
| <option value="">เลือกตารางที่ต้องการเพิ่มข้อมูล...</option>
|
| ${tables.map(table => `<option value="${table}">${table}</option>`).join('')}
|
| </select>
|
| </div>
|
|
|
| <div class="form-group">
|
| <label>วิธีการเพิ่มข้อมูล:</label>
|
| <div class="import-options">
|
| <div class="option-card" data-method="sql">
|
| <div class="option-icon"></div>
|
| <h4>เขียน SQL INSERT</h4>
|
| <p>เขียนคำสั่ง SQL INSERT เพื่อเพิ่มข้อมูลด้วยตัวเอง</p>
|
| </div>
|
| <div class="option-card" data-method="csv">
|
| <div class="option-icon"></div>
|
| <h4>นำเข้าจากไฟล์ CSV</h4>
|
| <p>อัพโหลดไฟล์ CSV เพื่อนำเข้าข้อมูลจำนวนมาก</p>
|
| </div>
|
| <div class="option-card" data-method="json">
|
| <div class="option-icon"></div>
|
| <h4>นำเข้าจากไฟล์ JSON</h4>
|
| <p>อัพโหลดไฟล์ JSON เพื่อนำเข้าข้อมูลโครงสร้าง</p>
|
| </div>
|
| <div class="option-card" data-method="manual">
|
| <div class="option-icon"></div>
|
| <h4>เพิ่มข้อมูลด้วยมือ</h4>
|
| <p>เพิ่มข้อมูลทีละแถวผ่านฟอร์ม</p>
|
| </div>
|
| </div>
|
| </div>
|
| </div>
|
| <div class="modal-footer">
|
| <button class="btn btn-outline" id="cancelImportBtn">ยกเลิก</button>
|
| <button class="btn btn-primary" id="proceedImportBtn" disabled>ดำเนินการต่อ</button>
|
| </div>
|
| </div>
|
| </div>
|
| `;
|
|
|
| // 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 = `
|
| <button class="btn-crud btn-add" onclick="window.dbManager.showAddRowForm('${tableName}')">
|
| Add Row
|
| </button>
|
| <button class="btn-crud" onclick="window.dbManager.refreshTableData('${tableName}')">
|
| Refresh
|
| </button>
|
| <span class="table-info" style="margin-left: auto; color: var(--text-secondary); font-size: 12px;">
|
| Table: ${tableName}
|
| </span>
|
| `;
|
|
|
| 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 `
|
| <div class="form-group">
|
| <label for="field_${col.name}">${col.name} (${col.type})${col.nullable ? '' : ' *'}</label>
|
| <input
|
| type="text"
|
| id="field_${col.name}"
|
| name="${col.name}"
|
| value="${value}"
|
| placeholder="ใส่ ${col.name}"
|
| ${required}
|
| class="form-control"
|
| >
|
| </div>
|
| `;
|
| }).join('');
|
|
|
| const modalHTML = `
|
| <div class="modal-overlay" id="rowEditModal">
|
| <div class="modal-dialog">
|
| <div class="modal-content">
|
| <div class="modal-header">
|
| <h3>${modalTitle}</h3>
|
| <button class="btn-close" onclick="window.dbManager.closeRowEditModal()">×</button>
|
| </div>
|
| <div class="modal-body">
|
| <form id="rowEditForm">
|
| ${formFields}
|
| </form>
|
| </div>
|
| <div class="modal-footer">
|
| <button class="btn btn-secondary" onclick="window.dbManager.closeRowEditModal()">ยกเลิก</button>
|
| <button class="btn btn-primary" onclick="window.dbManager.submitRowForm('${tableName}', ${isEdit}, '${rowId}')">${isEdit ? 'อัปเดต' : 'เพิ่ม'} แถว</button>
|
| </div>
|
| </div>
|
| </div>
|
| </div>
|
| `;
|
|
|
| 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<void>}
|
| * @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<string>} 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');
|
| });
|
|
|