-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathsqlite-file-browser.html
More file actions
923 lines (811 loc) · 26.5 KB
/
Copy pathsqlite-file-browser.html
File metadata and controls
923 lines (811 loc) · 26.5 KB
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Aura | SQLite Explorer</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Instrument+Sans:ital,wght@0,400;0,500;0,600;1,400&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet" />
<script src="https://unpkg.com/@phosphor-icons/web"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/sql-wasm.js"></script>
<style>
:root {
--bg-base: #f3f2ee;
--bg-surface: #fcfcfb;
--bg-surface-hover: #f8f7f4;
--border-light: #e6e4df;
--border-strong: #d1cfc8;
--text-main: #232220;
--text-muted: #73706b;
--text-disabled: #a6a39e;
--accent: #4a5d52;
--accent-hover: #37463d;
--accent-light: #e8ede9;
--error: #9c514a;
--error-bg: #f9ebea;
--font-ui: "Instrument Sans", sans-serif;
--font-mono: "JetBrains Mono", monospace;
--radius-sm: 4px;
--radius-md: 8px;
--radius-lg: 16px;
--shadow-subtle: 0 4px 20px rgba(0, 0, 0, 0.03);
--shadow-float: 0 12px 40px rgba(0, 0, 0, 0.06);
/* Layout */
--sidebar-width: 280px;
}
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: var(--font-ui);
background-color: var(--bg-base);
color: var(--text-main);
line-height: 1.5;
height: 100vh;
overflow: hidden;
display: flex;
flex-direction: column;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* Custom Scrollbars */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: var(--border-strong);
border-radius: var(--radius-sm);
}
::-webkit-scrollbar-thumb:hover {
background: var(--text-muted);
}
h1,
h2,
h3,
h4 {
font-weight: 500;
letter-spacing: -0.02em;
}
.text-mono {
font-family: var(--font-mono);
font-size: 0.85rem;
}
.flex {
display: flex;
}
.flex-col {
display: flex;
flex-direction: column;
}
.items-center {
align-items: center;
}
.justify-between {
justify-content: space-between;
}
.justify-center {
justify-content: center;
}
.gap-2 {
gap: 0.5rem;
}
.gap-4 {
gap: 1rem;
}
.p-4 {
padding: 1rem;
}
.p-6 {
padding: 1.5rem;
}
button {
font-family: var(--font-ui);
border: none;
background: none;
cursor: pointer;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
padding: 0.5rem 1rem;
border-radius: var(--radius-sm);
font-size: 0.9rem;
font-weight: 500;
transition: all 0.2s ease;
}
.btn-primary {
background-color: var(--accent);
color: white;
}
.btn-primary:hover {
background-color: var(--accent-hover);
transform: translateY(-1px);
}
.btn-secondary {
background-color: transparent;
color: var(--text-main);
border: 1px solid var(--border-strong);
}
.btn-secondary:hover {
background-color: var(--bg-surface-hover);
border-color: var(--text-muted);
}
.btn-ghost {
color: var(--text-muted);
}
.btn-ghost:hover {
color: var(--text-main);
background-color: var(--bg-surface-hover);
}
#drop-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: var(--bg-base);
z-index: 100;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
transition: all 0.3s ease;
border: 2px dashed transparent;
}
#drop-overlay.drag-active {
background-color: var(--bg-surface);
border: 2px dashed var(--accent);
}
.drop-content {
text-align: center;
max-width: 400px;
}
.drop-icon {
font-size: 3rem;
color: var(--text-muted);
margin-bottom: 1.5rem;
}
.drop-title {
font-size: 1.5rem;
color: var(--text-main);
margin-bottom: 0.5rem;
}
.drop-subtitle {
color: var(--text-muted);
font-size: 1rem;
margin-bottom: 2rem;
}
.file-input-wrapper {
position: relative;
display: inline-block;
}
.file-input-wrapper input[type="file"] {
position: absolute;
left: 0;
top: 0;
opacity: 0;
width: 100%;
height: 100%;
cursor: pointer;
}
#workspace {
display: none;
width: 100%;
height: 100%;
flex-direction: row;
}
.sidebar {
width: var(--sidebar-width);
background-color: var(--bg-surface);
border-right: 1px solid var(--border-light);
display: flex;
flex-direction: column;
height: 100%;
}
.sidebar-header {
padding: 1.5rem;
border-bottom: 1px solid var(--border-light);
}
.sidebar-header h2 {
font-size: 1rem;
color: var(--text-main);
display: flex;
align-items: center;
gap: 0.5rem;
}
.db-name {
font-size: 0.85rem;
color: var(--text-muted);
margin-top: 0.25rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.table-list {
flex: 1;
overflow-y: auto;
padding: 1rem 0;
}
.table-list-title {
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--text-muted);
padding: 0 1.5rem;
margin-bottom: 0.5rem;
}
.table-item {
padding: 0.5rem 1.5rem;
display: flex;
align-items: center;
gap: 0.75rem;
cursor: pointer;
color: var(--text-main);
transition: background 0.2s;
font-size: 0.9rem;
}
.table-item:hover {
background-color: var(--bg-surface-hover);
}
.table-item.active {
background-color: var(--accent-light);
color: var(--accent);
border-right: 2px solid var(--accent);
}
.table-item i {
color: var(--text-muted);
font-size: 1.1rem;
}
.table-item.active i {
color: var(--accent);
}
/* Main Content */
.main-content {
flex: 1;
display: flex;
flex-direction: column;
height: 100%;
background-color: var(--bg-base);
overflow: hidden;
}
/* Top Panel: Query Editor */
.query-panel {
background-color: var(--bg-surface);
border-bottom: 1px solid var(--border-light);
display: flex;
flex-direction: column;
height: 40%;
min-height: 200px;
}
.panel-header {
padding: 0.75rem 1.5rem;
border-bottom: 1px solid var(--border-light);
display: flex;
justify-content: space-between;
align-items: center;
background-color: var(--bg-surface);
}
.panel-title {
font-size: 0.85rem;
color: var(--text-muted);
font-weight: 500;
}
.editor-container {
flex: 1;
padding: 1.5rem;
position: relative;
}
textarea#sql-input {
width: 100%;
height: 100%;
border: none;
resize: none;
outline: none;
background: transparent;
color: var(--text-main);
font-family: var(--font-mono);
font-size: 0.95rem;
line-height: 1.6;
}
textarea#sql-input::placeholder {
color: var(--text-disabled);
}
/* Bottom Panel: Results */
.results-panel {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
background-color: var(--bg-base);
padding: 1.5rem;
}
.results-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
}
.results-meta {
font-size: 0.85rem;
color: var(--text-muted);
}
.table-container {
flex: 1;
background-color: var(--bg-surface);
border: 1px solid var(--border-light);
border-radius: var(--radius-md);
overflow: auto;
box-shadow: var(--shadow-subtle);
}
table {
width: 100%;
border-collapse: collapse;
font-family: var(--font-mono);
font-size: 0.85rem;
text-align: left;
}
th {
background-color: var(--bg-surface);
color: var(--text-muted);
font-weight: 500;
padding: 0.75rem 1rem;
border-bottom: 1px solid var(--border-light);
position: sticky;
top: 0;
z-index: 10;
white-space: nowrap;
}
td {
padding: 0.75rem 1rem;
border-bottom: 1px solid var(--border-light);
color: var(--text-main);
white-space: nowrap;
max-width: 300px;
overflow: hidden;
text-overflow: ellipsis;
}
tr:last-child td {
border-bottom: none;
}
tr:hover td {
background-color: var(--bg-surface-hover);
}
/* Empty State & Errors */
.status-message {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
color: var(--text-muted);
text-align: center;
padding: 2rem;
}
.status-message i {
font-size: 2rem;
margin-bottom: 1rem;
color: var(--border-strong);
}
.error-message {
background-color: var(--error-bg);
color: var(--error);
padding: 1rem;
border-radius: var(--radius-sm);
margin-bottom: 1rem;
font-family: var(--font-mono);
font-size: 0.85rem;
display: none;
border: 1px solid rgba(156, 81, 74, 0.2);
}
/* Loading Spinner */
.spinner {
animation: spin 1s linear infinite;
}
@keyframes spin {
100% {
transform: rotate(360deg);
}
}
</style>
</head>
<body>
<!-- Dropzone Overlay -->
<div id="drop-overlay">
<div class="drop-content">
<i class="ph ph-database drop-icon"></i>
<h1 class="drop-title">Aura Data Studio</h1>
<p class="drop-subtitle">A calm, local workspace for your SQLite files.</p>
<div class="file-input-wrapper">
<button class="btn-primary">
<i class="ph ph-upload-simple"></i>
Select Database File
</button>
<input type="file" id="file-input" accept=".sqlite,.db,.sqlite3,.db3" />
</div>
<p style="margin-top: 1rem; font-size: 0.85rem; color: var(--text-disabled)">or drag and drop here</p>
</div>
</div>
<!-- Main Workspace -->
<div id="workspace">
<!-- Sidebar -->
<aside class="sidebar">
<div class="sidebar-header">
<h2><i class="ph ph-layout"></i> Explorer</h2>
<div class="db-name" id="display-db-name">No file loaded</div>
</div>
<div class="table-list" id="sidebar-tables">
<div class="table-list-title">Tables & Views</div>
<div id="tables-container">
<!-- Populated via JS -->
</div>
</div>
<div style="padding: 1rem; border-top: 1px solid var(--border-light)">
<button class="btn-ghost" style="width: 100%; justify-content: flex-start" onclick="closeDatabase()"><i class="ph ph-sign-out"></i> Close Database</button>
</div>
</aside>
<!-- Main Area -->
<main class="main-content">
<!-- Query Editor Panel -->
<section class="query-panel">
<div class="panel-header">
<div class="panel-title flex items-center gap-2"><i class="ph ph-terminal-window"></i> Query Editor</div>
<div class="flex gap-2">
<button class="btn-secondary" id="btn-format" title="Format Query (Basic)">
<i class="ph ph-text-align-left"></i>
</button>
<button class="btn-primary" id="btn-run"><i class="ph ph-play"></i> Run Query</button>
</div>
</div>
<div class="editor-container">
<textarea id="sql-input" placeholder="Enter your SQL query here... (e.g., SELECT * FROM users LIMIT 100;)"></textarea>
</div>
</section>
<!-- Results Panel -->
<section class="results-panel">
<div class="results-header">
<div class="results-meta" id="results-meta">Ready</div>
<button class="btn-secondary" id="btn-export" style="display: none"><i class="ph ph-download-simple"></i> Export CSV</button>
</div>
<div id="error-box" class="error-message"></div>
<div class="table-container" id="table-container">
<div class="status-message" id="empty-state">
<i class="ph ph-table"></i>
<p>Run a query to view results here.</p>
</div>
<!-- Table rendered here -->
</div>
</section>
</main>
</div>
<script>
/**
* Application State & Initialization
*/
let SQL = null;
let db = null;
let currentFileName = "";
let currentResults = null; // Store latest query results for export
const elements = {
dropOverlay: document.getElementById("drop-overlay"),
fileInput: document.getElementById("file-input"),
workspace: document.getElementById("workspace"),
dbNameDisplay: document.getElementById("display-db-name"),
tablesContainer: document.getElementById("tables-container"),
sqlInput: document.getElementById("sql-input"),
btnRun: document.getElementById("btn-run"),
btnExport: document.getElementById("btn-export"),
resultsMeta: document.getElementById("results-meta"),
tableContainer: document.getElementById("table-container"),
emptyState: document.getElementById("empty-state"),
errorBox: document.getElementById("error-box")
};
// Initialize sql.js
async function initSQLite() {
try {
const sqlPromise = initSqlJs({
locateFile: (file) => `https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/${file}`
});
SQL = await sqlPromise;
console.log("SQL.js initialized successfully.");
} catch (err) {
console.error("Failed to load SQL.js", err);
alert("Failed to initialize SQLite engine. Please check your connection.");
}
}
// Run Init
initSQLite();
/**
* File Handling (Drag & Drop, Input)
*/
// Prevent default drag behaviors
["dragenter", "dragover", "dragleave", "drop"].forEach((eventName) => {
document.body.addEventListener(eventName, preventDefaults, false);
});
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
// Highlight drop zone
["dragenter", "dragover"].forEach((eventName) => {
elements.dropOverlay.addEventListener(
eventName,
() => {
elements.dropOverlay.classList.add("drag-active");
},
false
);
});
["dragleave", "drop"].forEach((eventName) => {
elements.dropOverlay.addEventListener(
eventName,
() => {
elements.dropOverlay.classList.remove("drag-active");
},
false
);
});
// Handle Drop
elements.dropOverlay.addEventListener("drop", handleDrop, false);
function handleDrop(e) {
let dt = e.dataTransfer;
let files = dt.files;
if (files.length) handleFile(files[0]);
}
// Handle Input
elements.fileInput.addEventListener("change", (e) => {
if (e.target.files.length) handleFile(e.target.files[0]);
});
function handleFile(file) {
if (!SQL) {
alert("SQLite engine is still loading. Please try again in a moment.");
return;
}
currentFileName = file.name;
elements.dbNameDisplay.textContent = currentFileName;
const reader = new FileReader();
reader.onload = function (e) {
const uInt8Array = new Uint8Array(e.target.result);
try {
// Close previous db if exists
if (db) db.close();
db = new SQL.Database(uInt8Array);
// Transition UI
elements.dropOverlay.style.display = "none";
elements.workspace.style.display = "flex";
loadSidebar();
resetWorkspace();
} catch (err) {
alert("Failed to open database. Ensure it is a valid SQLite file.");
console.error(err);
}
};
reader.readAsArrayBuffer(file);
}
function closeDatabase() {
if (db) {
db.close();
db = null;
}
elements.workspace.style.display = "none";
elements.dropOverlay.style.display = "flex";
elements.fileInput.value = ""; // Reset input
}
/**
* Database Operations & UI Updates
*/
function loadSidebar() {
elements.tablesContainer.innerHTML = "";
// Query tables and views
const query = `
SELECT name, type
FROM sqlite_master
WHERE type IN ('table', 'view')
AND name NOT LIKE 'sqlite_%'
ORDER BY name;
`;
try {
const res = db.exec(query);
if (res.length > 0) {
const rows = res[0].values;
rows.forEach((row) => {
const [name, type] = row;
const icon = type === "view" ? "ph-eye" : "ph-table";
const el = document.createElement("div");
el.className = "table-item";
const nameSpan = document.createElement("span");
nameSpan.textContent = name;
el.innerHTML = `<i class="ph ${icon}"></i> `;
el.appendChild(nameSpan);
el.addEventListener("click", () => {
// Highlight active
document.querySelectorAll(".table-item").forEach((n) => n.classList.remove("active"));
el.classList.add("active");
// Generate default query
const safeName = `"${name.replace(/"/g, '""')}"`;
elements.sqlInput.value = `SELECT * FROM ${safeName}\nLIMIT 100;`;
// Auto-run
executeQuery();
});
elements.tablesContainer.appendChild(el);
});
} else {
elements.tablesContainer.innerHTML = `<div style="padding: 1rem 1.5rem; color: var(--text-muted); font-size: 0.85rem;">No tables found.</div>`;
}
} catch (err) {
console.error("Error loading tables", err);
}
}
function resetWorkspace() {
elements.sqlInput.value = "";
elements.tableContainer.innerHTML = "";
elements.tableContainer.appendChild(elements.emptyState);
elements.emptyState.style.display = "flex";
elements.errorBox.style.display = "none";
elements.btnExport.style.display = "none";
elements.resultsMeta.textContent = "Ready";
currentResults = null;
}
/**
* Query Execution
*/
elements.btnRun.addEventListener("click", executeQuery);
// Allow Ctrl+Enter or Cmd+Enter to run query
elements.sqlInput.addEventListener("keydown", (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
executeQuery();
}
});
function executeQuery() {
if (!db) return;
const sql = elements.sqlInput.value.trim();
if (!sql) return;
// UI Loading state
elements.btnRun.innerHTML = `<i class="ph ph-spinner spinner"></i> Running...`;
elements.btnRun.disabled = true;
elements.errorBox.style.display = "none";
elements.emptyState.style.display = "none";
// Slight timeout to allow UI to update before blocking WASM execution
setTimeout(() => {
const startTime = performance.now();
try {
const results = db.exec(sql);
const endTime = performance.now();
const duration = (endTime - startTime).toFixed(2);
if (results.length === 0) {
// Query executed but no results returned (e.g., INSERT, UPDATE)
let rowsModified = db.getRowsModified();
renderSuccessNoData(rowsModified, duration);
currentResults = null;
} else {
// Data returned
renderTable(results[0].columns, results[0].values, duration);
currentResults = results[0]; // Store for export
}
} catch (err) {
renderError(err.message);
currentResults = null;
} finally {
// Restore UI
elements.btnRun.innerHTML = `<i class="ph ph-play"></i> Run Query`;
elements.btnRun.disabled = false;
}
}, 50);
}
function renderTable(columns, values, duration) {
elements.tableContainer.innerHTML = ""; // Clear current
const table = document.createElement("table");
// Thead
const thead = document.createElement("thead");
const trHead = document.createElement("tr");
columns.forEach((col) => {
const th = document.createElement("th");
th.textContent = col;
trHead.appendChild(th);
});
thead.appendChild(trHead);
table.appendChild(thead);
// Tbody
const tbody = document.createElement("tbody");
// Limit rendering to prevent browser freeze on massive datasets
const MAX_ROWS = 1000;
const displayValues = values.slice(0, MAX_ROWS);
displayValues.forEach((row) => {
const tr = document.createElement("tr");
row.forEach((val) => {
const td = document.createElement("td");
td.textContent = val !== null ? val : "NULL";
if (val === null) td.style.color = "var(--text-disabled)";
tr.appendChild(td);
});
tbody.appendChild(tr);
});
table.appendChild(tbody);
elements.tableContainer.appendChild(table);
// Update Meta & Export
let metaText = `${values.length} row${values.length !== 1 ? "s" : ""} returned in ${duration}ms.`;
if (values.length > MAX_ROWS) {
metaText += ` (Displaying first ${MAX_ROWS})`;
}
elements.resultsMeta.textContent = metaText;
elements.btnExport.style.display = "inline-flex";
}
function renderSuccessNoData(rowsModified, duration) {
elements.tableContainer.innerHTML = `
<div class="status-message">
<i class="ph ph-check-circle" style="color: var(--accent);"></i>
<p style="color: var(--text-main); font-weight: 500;">Query executed successfully.</p>
<p style="font-size: 0.85rem; margin-top: 0.5rem;">Rows modified: ${rowsModified} (${duration}ms)</p>
</div>
`;
elements.resultsMeta.textContent = `Success in ${duration}ms`;
elements.btnExport.style.display = "none";
}
function renderError(message) {
elements.tableContainer.innerHTML = "";
elements.tableContainer.appendChild(elements.emptyState);
elements.emptyState.style.display = "flex";
elements.errorBox.textContent = `Error: ${message}`;
elements.errorBox.style.display = "block";
elements.resultsMeta.textContent = "Error executing query";
elements.btnExport.style.display = "none";
}
/**
* Export to CSV
*/
elements.btnExport.addEventListener("click", () => {
if (!currentResults) return;
const { columns, values } = currentResults;
// Helper to escape CSV values
const escapeCSV = (val) => {
if (val === null || val === undefined) return "";
const str = String(val);
if (str.includes(",") || str.includes('"') || str.includes("\n")) {
return `"${str.replace(/"/g, '""')}"`;
}
return str;
};
// Build CSV string
const csvRows = [];
// Header
csvRows.push(columns.map(escapeCSV).join(","));
// Data
values.forEach((row) => {
csvRows.push(row.map(escapeCSV).join(","));
});
const csvString = csvRows.join("\n");
const blob = new Blob([csvString], { type: "text/csv;charset=utf-8;" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.setAttribute("href", url);
// Generate filename based on DB and time
const safeDbName = currentFileName.replace(/\.[^/.]+$/, "");
const dateStr = new Date().toISOString().slice(0, 19).replace(/[:T]/g, "-");
link.setAttribute("download", `${safeDbName}_export_${dateStr}.csv`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
});
document.getElementById("btn-format").addEventListener("click", () => {
let sql = elements.sqlInput.value;
if (!sql) return;
const keywords = ["SELECT", "FROM", "WHERE", "ORDER BY", "GROUP BY", "LIMIT", "LEFT JOIN", "INNER JOIN", "JOIN", "HAVING"];
keywords.forEach((kw) => {
const regex = new RegExp(`\\b${kw}\\b`, "gi");
sql = sql.replace(regex, `\n${kw}`);
});
sql = sql.trim().replace(/\n+/g, "\n").replace(/ {2,}/g, " ");
elements.sqlInput.value = sql;
});
</script>
</body>
</html>