File size: 11,370 Bytes
8eeb77a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
/**

 * @fileoverview Chahua Database Manager - Query Editor Module

 * @description SQL Query Editor พร้อมคุณสมบัติ syntax highlighting และ keyboard shortcuts

 * คุณสมบัติ: SQL editing, Query execution, Results display, Line numbers

 * @author ทีมพัฒนา Chahua

 * @version 1.0.0

 * @since 2024-01-01

 * @calledBy app.js, renderer/index.html

 * @dependencies

 * - DOM elements: queryTextarea, executeQueryBtn, resultsContent

 * - app.js: Query execution and results handling

 * @features

 * - SQL syntax highlighting (basic)

 * - Line number display

 * - Keyboard shortcuts (Ctrl+Enter for execution)

 * - Tab indentation support

 * - Query execution with timing

 * - Results display and formatting

 * @security

 * - Input sanitization for SQL queries

 * - XSS protection in results display

 * @example

 * // Initialize query editor

 * const editor = new QueryEditor();

 * 

 * // Set query text

 * editor.setQuery('SELECT * FROM users');

 * 

 * // Execute current query

 * await editor.executeQuery();

 */

// Query Editor functionality
/**

 * Query Editor - Class for managing SQL query editing and execution

 * @class QueryEditor

 * @description Provides SQL editing capabilities with syntax highlighting, shortcuts, and execution

 * @features

 * - Basic SQL syntax highlighting

 * - Line numbers and editor enhancements

 * - Keyboard shortcuts for common operations

 * - Query execution with timing display

 * - Results formatting and display

 */
class QueryEditor {
    /**

     * Create a QueryEditor instance

     * @constructor

     * @description Initializes the query editor with DOM elements and event listeners

     * @features

     * - Textarea and button element binding

     * - Event listener setup

     * - Editor enhancement initialization

     */
    constructor() {
        this.textarea = document.getElementById('queryTextarea');
        this.executeBtn = document.getElementById('executeQueryBtn');
        this.resultsContainer = document.getElementById('resultsContent');
        this.executionTimeDisplay = document.getElementById('executionTime');
        
        this.initializeEditor();
    }

    /**

     * Initialize editor functionality

     * @function initializeEditor

     * @description Sets up event listeners and editor enhancements

     * @features

     * - Line number updates on input

     * - Tab key handling for indentation

     * - Keyboard shortcuts setup

     * - Ctrl+Enter for query execution

     */
    initializeEditor() {
        if (!this.textarea) return;

        // Add basic syntax highlighting (simple approach)
        this.textarea.addEventListener('input', () => {
            this.updateLineNumbers();
        });

        // Handle tab key for indentation
        this.textarea.addEventListener('keydown', (e) => {
            if (e.key === 'Tab') {
                e.preventDefault();
                const start = this.textarea.selectionStart;
                const end = this.textarea.selectionEnd;
                
                // Insert tab character
                this.textarea.value = this.textarea.value.substring(0, start) + 
                    '\t' + this.textarea.value.substring(end);
                
                // Restore cursor position
                this.textarea.selectionStart = this.textarea.selectionEnd = start + 1;
            }
        });

        // Keyboard shortcuts for editor
        this.textarea.addEventListener('keydown', (e) => {
            // Ctrl+Enter: Execute Query
            if (e.ctrlKey && e.key === 'Enter') {
                e.preventDefault();
                this.executeQuery();
            }
            // Ctrl+A: Select All
            if (e.ctrlKey && e.key === 'a') {
                // Let default behavior work
                return;
            }
            // Ctrl+Z: Undo (browser default)
            if (e.ctrlKey && e.key === 'z') {
                // Let default behavior work
                return;
            }
            // Ctrl+Y: Redo (browser default)
            if (e.ctrlKey && e.key === 'y') {
                // Let default behavior work
                return;
            }
            // Ctrl+F: Find
            if (e.ctrlKey && e.key === 'f') {
                // Let default browser find work
                return;
            }
            // Ctrl+/: Toggle comment
            if (e.ctrlKey && e.key === '/') {
                e.preventDefault();
                this.toggleComment();
            }
            // Shift+Tab: Decrease indentation
            if (e.shiftKey && e.key === 'Tab') {
                e.preventDefault();
                this.decreaseIndentation();
            }
        });
    }

    updateLineNumbers() {
        // Simple line numbers implementation
        const lines = this.textarea.value.split('\n').length;
        // This would be where line numbers are updated
        console.log(`Lines: ${lines}`);
    }

    async executeQuery() {
        // เรียกใช้ฟังก์ชันหลักที่อยู่ใน dbManager (จากไฟล์ app.js) แทน
        if (window.dbManager && typeof window.dbManager.executeQuery === 'function') {
            console.log('Executing query via dbManager...');
            window.dbManager.executeQuery();
        } else {
            console.error('dbManager not found or executeQuery method not available');
        }
    }

    renderResults(data, executionTime) {
        if (!this.resultsContainer) return;

        // Update execution time
        if (this.executionTimeDisplay) {
            this.executionTimeDisplay.textContent = `Executed in ${executionTime}ms`;
        }

        if (data.type === 'select' && data.rows && data.rows.length > 0) {
            // Create table for SELECT results
            const table = UIHelpers.createTable(data.columns, data.rows);
            
            // Add results info
            const resultsInfo = document.createElement('div');
            resultsInfo.className = 'results-info';
            resultsInfo.innerHTML = `

                <span>Rows: ${data.rowCount}</span>

                <span>Execution time: ${executionTime}ms</span>

            `;
            
            this.resultsContainer.innerHTML = '';
            this.resultsContainer.appendChild(resultsInfo);
            this.resultsContainer.appendChild(table);
        } else {
            // Show message for non-SELECT queries
            this.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>

            `;
        }
    }

    renderError(errorMessage) {
        if (!this.resultsContainer) return;
        
        this.resultsContainer.innerHTML = `

            <div class="results-error">

                <h4>Query Error</h4>

                <pre>${errorMessage}</pre>

            </div>

        `;
    }

    clearQuery() {
        if (this.textarea) {
            this.textarea.value = '';
        }
    }

    setQuery(query) {
        if (this.textarea) {
            this.textarea.value = query;
        }
    }

    getQuery() {
        return this.textarea ? this.textarea.value : '';
    }

    toggleComment() {
        const start = this.textarea.selectionStart;
        const end = this.textarea.selectionEnd;
        const text = this.textarea.value;
        
        // Get current line(s)
        const beforeCursor = text.substring(0, start);
        const afterCursor = text.substring(end);
        const selectedText = text.substring(start, end);
        
        // Find line boundaries
        const lineStart = beforeCursor.lastIndexOf('\n') + 1;
        const lineEnd = text.indexOf('\n', end);
        const actualLineEnd = lineEnd === -1 ? text.length : lineEnd;
        
        const currentLine = text.substring(lineStart, actualLineEnd);
        
        // Toggle comment
        let newLine;
        if (currentLine.trim().startsWith('--')) {
            // Remove comment
            newLine = currentLine.replace(/^\s*--\s?/, '');
        } else {
            // Add comment
            const indent = currentLine.match(/^\s*/)[0];
            newLine = indent + '-- ' + currentLine.substring(indent.length);
        }
        
        // Replace the line
        this.textarea.value = text.substring(0, lineStart) + newLine + text.substring(actualLineEnd);
        
        // Restore cursor position
        this.textarea.selectionStart = start;
        this.textarea.selectionEnd = end;
    }

    decreaseIndentation() {
        const start = this.textarea.selectionStart;
        const end = this.textarea.selectionEnd;
        const text = this.textarea.value;
        
        // Get selected lines
        const beforeCursor = text.substring(0, start);
        const lineStart = beforeCursor.lastIndexOf('\n') + 1;
        const lineEnd = text.indexOf('\n', end);
        const actualLineEnd = lineEnd === -1 ? text.length : lineEnd;
        
        const selectedLines = text.substring(lineStart, actualLineEnd);
        const lines = selectedLines.split('\n');
        
        // Remove one tab or 4 spaces from each line
        const newLines = lines.map(line => {
            if (line.startsWith('\t')) {
                return line.substring(1);
            } else if (line.startsWith('    ')) {
                return line.substring(4);
            }
            return line;
        });
        
        // Replace the lines
        const newSelectedText = newLines.join('\n');
        this.textarea.value = text.substring(0, lineStart) + newSelectedText + text.substring(actualLineEnd);
        
        // Restore selection
        this.textarea.selectionStart = start;
        this.textarea.selectionEnd = start + newSelectedText.length;
    }

    // Basic SQL syntax highlighting
    applySyntaxHighlighting() {
        // This would be a more complex implementation
        // For now, just return the text as-is
        return this.textarea.value;
    }

    // Format SQL query
    formatQuery() {
        const query = this.getQuery();
        if (!query) return;

        // Basic SQL formatting
        const formatted = query
            .replace(/\s+/g, ' ')
            .replace(/\s*,\s*/g, ', ')
            .replace(/\s*\(\s*/g, ' (')
            .replace(/\s*\)\s*/g, ') ')
            .replace(/\bSELECT\b/gi, 'SELECT')
            .replace(/\bFROM\b/gi, '\nFROM')
            .replace(/\bWHERE\b/gi, '\nWHERE')
            .replace(/\bORDER BY\b/gi, '\nORDER BY')
            .replace(/\bGROUP BY\b/gi, '\nGROUP BY')
            .replace(/\bHAVING\b/gi, '\nHAVING')
            .replace(/\bLIMIT\b/gi, '\nLIMIT');

        this.setQuery(formatted);
    }
}

// Make it available globally
if (typeof window !== 'undefined') {
    window.QueryEditor = QueryEditor;
}