|
| 1 | +<script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/sql-wasm.js"></script> |
| 2 | + |
| 3 | +<script> |
| 4 | + const tableName = 'input'; |
| 5 | + |
| 6 | + async function query(tableElement, sqlQuery) { |
| 7 | + // First, convert HTML table to array of objects |
| 8 | + function tableToJson(table) { |
| 9 | + const headers = [...table.querySelectorAll('th')].map(th => th.textContent.trim()); |
| 10 | + const rows = [...table.querySelectorAll('tr')].slice(1); |
| 11 | + |
| 12 | + return rows.map(row => { |
| 13 | + const cells = [...row.querySelectorAll('td')]; |
| 14 | + return headers.reduce((obj, header, i) => { |
| 15 | + obj[header] = cells[i] ? cells[i].innerHTML.trim() : null; |
| 16 | + return obj; |
| 17 | + }, {}); |
| 18 | + }); |
| 19 | + } |
| 20 | + |
| 21 | + // Convert result back to HTML table |
| 22 | + function createResultTable(results) { |
| 23 | + const table = document.createElement('table'); |
| 24 | + |
| 25 | + // Copy class attribute from input table |
| 26 | + if (tableElement.hasAttribute('class')) { |
| 27 | + table.setAttribute('class', tableElement.getAttribute('class')); |
| 28 | + } |
| 29 | + |
| 30 | + // Create header row if we have results |
| 31 | + if (results.length > 0) { |
| 32 | + const thead = document.createElement('thead'); |
| 33 | + const headerRow = document.createElement('tr'); |
| 34 | + |
| 35 | + Object.keys(results[0]).forEach(key => { |
| 36 | + const th = document.createElement('th'); |
| 37 | + th.innerHTML = key; |
| 38 | + headerRow.appendChild(th); |
| 39 | + }); |
| 40 | + |
| 41 | + thead.appendChild(headerRow); |
| 42 | + table.appendChild(thead); |
| 43 | + } |
| 44 | + |
| 45 | + // Create data rows |
| 46 | + const tbody = document.createElement('tbody'); |
| 47 | + results.forEach(row => { |
| 48 | + const tr = document.createElement('tr'); |
| 49 | + Object.values(row).forEach(value => { |
| 50 | + const td = document.createElement('td'); |
| 51 | + td.innerHTML = value; |
| 52 | + tr.appendChild(td); |
| 53 | + }); |
| 54 | + tbody.appendChild(tr); |
| 55 | + }); |
| 56 | + |
| 57 | + table.appendChild(tbody); |
| 58 | + return table; |
| 59 | + } |
| 60 | + |
| 61 | + |
| 62 | + try { |
| 63 | + // Initialize SQL.js |
| 64 | + const SQL = await initSqlJs({ |
| 65 | + locateFile: file => `https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/${file}` |
| 66 | + }); |
| 67 | + |
| 68 | + // Create a database |
| 69 | + const db = new SQL.Database(); |
| 70 | + |
| 71 | + // Convert table to JSON |
| 72 | + const data = tableToJson(tableElement); |
| 73 | + |
| 74 | + // Create table and insert data |
| 75 | + if (data.length > 0) { |
| 76 | + // Generate CREATE TABLE statement |
| 77 | + const columns = Object.keys(data[0]) |
| 78 | + .map(col => `"${col}" TEXT`) |
| 79 | + .join(', '); |
| 80 | + |
| 81 | + db.run(`CREATE TABLE ${tableName} (${columns})`); |
| 82 | + |
| 83 | + // Insert data |
| 84 | + data.forEach(row => { |
| 85 | + const columns = Object.keys(row).map(col => `"${col}"`).join(', '); |
| 86 | + const values = Object.values(row).map(val => `'${val}'`).join(', '); |
| 87 | + db.run(`INSERT INTO ${tableName} (${columns}) VALUES (${values})`); |
| 88 | + }); |
| 89 | + |
| 90 | + // Execute query |
| 91 | + const results = db.exec(sqlQuery); |
| 92 | + |
| 93 | + // Convert results to array of objects |
| 94 | + if (results.length > 0) { |
| 95 | + const columns = results[0].columns; |
| 96 | + const rows = results[0].values.map(row => { |
| 97 | + return columns.reduce((obj, col, i) => { |
| 98 | + obj[col] = row[i]; |
| 99 | + return obj; |
| 100 | + }, {}); |
| 101 | + }); |
| 102 | + |
| 103 | + // Convert to HTML table and return |
| 104 | + return createResultTable(rows); |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + // Return empty table if no results |
| 109 | + return createResultTable([]); |
| 110 | + |
| 111 | + } catch (error) { |
| 112 | + console.error('Error executing query:', error); |
| 113 | + const errorTable = document.createElement('table'); |
| 114 | + // Copy class attribute from input table |
| 115 | + if (tableElement.hasAttribute('class')) { |
| 116 | + errorTable.setAttribute('class', tableElement.getAttribute('class')); |
| 117 | + } |
| 118 | + errorTable.innerHTML = `<tr><td>Error executing query: ${error.message}</td></tr>`; |
| 119 | + return errorTable; |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | +const template = ` |
| 124 | +<div class="mb-4"> |
| 125 | + <div class="field"> |
| 126 | + <div class="control is-expanded"> |
| 127 | + <textarea class="textarea" rows="5" placeholder="Enter SQL query. the following table name is input..."></textarea> |
| 128 | + </div> |
| 129 | + <div class="control"> |
| 130 | + <button class="button mt-2">Run Query</button> |
| 131 | + </div> |
| 132 | + </div> |
| 133 | + <div class="help is-danger mt-2"></div> |
| 134 | +</div> |
| 135 | +`; |
| 136 | + |
| 137 | +function initializeTableQueries() { |
| 138 | + const tables = document.getElementsByTagName('table'); |
| 139 | + |
| 140 | + Array.from(tables).forEach((table) => { |
| 141 | + if(table.querySelectorAll('tbody tr').length < sqlTableThreshold){ |
| 142 | + return |
| 143 | + } |
| 144 | + |
| 145 | + // Create template element and parse HTML |
| 146 | + const templateEl = document.createElement('template'); |
| 147 | + templateEl.innerHTML = template.trim(); |
| 148 | + |
| 149 | + // Clone the template content |
| 150 | + const queryInterface = templateEl.content.cloneNode(true); |
| 151 | + |
| 152 | + // Get references to elements |
| 153 | + const wrapper = queryInterface.querySelector('.mb-4'); |
| 154 | + const input = queryInterface.querySelector('.textarea'); |
| 155 | + const button = queryInterface.querySelector('.button'); |
| 156 | + const errorContainer = queryInterface.querySelector('.help'); |
| 157 | + |
| 158 | + let resultTable = null; |
| 159 | + |
| 160 | + // Add input event listener |
| 161 | + input.addEventListener('input', (e) => { |
| 162 | + if (e.target.value.trim() === '') { |
| 163 | + table.style.display = ''; |
| 164 | + if (resultTable) { |
| 165 | + resultTable.remove(); |
| 166 | + resultTable = null; |
| 167 | + } |
| 168 | + errorContainer.textContent = ''; |
| 169 | + } |
| 170 | + }); |
| 171 | + |
| 172 | + // Add button click listener |
| 173 | + button.addEventListener('click', async () => { |
| 174 | + const sqlQuery = input.value.trim(); |
| 175 | + |
| 176 | + if (sqlQuery === '') { |
| 177 | + errorContainer.textContent = 'Please enter a SQL query'; |
| 178 | + return; |
| 179 | + } |
| 180 | + |
| 181 | + try { |
| 182 | + button.classList.add('is-loading'); |
| 183 | + |
| 184 | + if (resultTable) { |
| 185 | + resultTable.remove(); |
| 186 | + } |
| 187 | + |
| 188 | + resultTable = await query(table, sqlQuery); |
| 189 | + table.style.display = 'none'; |
| 190 | + wrapper.after(resultTable); |
| 191 | + errorContainer.textContent = ''; |
| 192 | + |
| 193 | + } catch (error) { |
| 194 | + errorContainer.textContent = `Error: ${error.message}`; |
| 195 | + console.error('Query error:', error); |
| 196 | + |
| 197 | + table.style.display = ''; |
| 198 | + if (resultTable) { |
| 199 | + resultTable.remove(); |
| 200 | + resultTable = null; |
| 201 | + } |
| 202 | + } finally { |
| 203 | + button.classList.remove('is-loading'); |
| 204 | + } |
| 205 | + }); |
| 206 | + |
| 207 | + // Insert the query interface before the table |
| 208 | + table.parentNode.insertBefore(queryInterface, table); |
| 209 | + }); |
| 210 | +} |
| 211 | + |
| 212 | + // Initialize when DOM is ready |
| 213 | + if (document.readyState === 'loading') { |
| 214 | + document.addEventListener('DOMContentLoaded', initializeTableQueries); |
| 215 | + } else { |
| 216 | + initializeTableQueries(); |
| 217 | + } |
| 218 | +</script> |
0 commit comments