Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
932 lines (755 loc) · 26.5 KB
/
Copy pathindex.html
File metadata and controls
932 lines (755 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
924
925
926
927
928
929
930
931
932
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Database Viewer</title>
<style>
body {
font-family: Arial, sans-serif;
background: #0c0c0c;
color: #05ee93;
margin: 30px;
}
input, textarea, select {
padding: 8px;
background: #111;
color: #05ee93;
border: 1px solid #444;
border-radius: 6px;
font-family: inherit;
}
input#secret, input#globalSearch {
width: 300px;
}
button {
padding: 8px 14px;
cursor: pointer;
background: #1a1a1a;
color: #05ee93;
border: 1px solid #444;
border-radius: 6px;
margin-right: 6px;
}
button:hover {
background: #2a2a2a;
}
td {
cursor: pointer;
border-radius: 6px;
}
td:hover {
background: #2a2a2a;
}
td input {
width: 100%;
padding: 2px 4px;
}
table {
border-collapse: collapse;
width: 100%;
margin-top: 10px;
}
th, td {
border: 1px solid #444;
padding: 6px 10px;
text-align: left;
vertical-align: top;
border-radius: 6px;
}
th {
background: #222;
cursor: pointer;
user-select: none;
}
th:hover {
background: #2f2f2f;
}
thead th {
position: sticky;
top: 0;
background: #222;
z-index: 10;
}
tr:nth-child(even) {
background: #1a1a1a;
}
.section {
margin-top: 40px;
}
.section-header {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.collapse-toggle {
cursor: pointer;
user-select: none;
font-size: 14px;
color: #05ee93;
}
.error {
color: #ff6666;
margin-top: 20px;
}
.success {
color: #66ff99;
margin-top: 20px;
}
.schema-box, .insert-box {
display: none;
background: #151515;
border: 1px solid #444;
border-radius: 6px;
padding: 10px;
margin-top: 8px;
font-size: 13px;
}
.insert-box label {
display: inline-block;
margin: 4px 8px 4px 0;
}
.search-box {
width: 220px;
}
#sqlInput {
width: 500px;
max-width: 90%;
}
.small-note {
font-size: 12px;
color: #888;
}
.pager {
display: flex;
align-items: center;
gap: 10px;
margin-top: 8px;
}
#backupList div {
padding: 4px 0;
border-bottom: 1px solid #333;
}
#navBar {
margin-top: 10px;
font-size: 13px;
}
#navBar a {
color: #05ee93;
margin-right: 12px;
text-decoration: underline;
cursor: pointer;
}
.resolved-hint {
color: #888;
}
</style>
</head>
<body>
<h1>mcbCode admin</h1>
<input id="secret" placeholder="secret key">
<button id="loadBtn">Load Database</button>
<button id="autoRefreshBtn">Auto-refresh: OFF</button>
<button id="collapseAllBtn">Collapse All</button>
<br><br>
<input id="globalSearch" placeholder="search across every table...">
<label style="margin-left: 10px;">
<input type="checkbox" id="resolveUsersToggle" style="width:auto;">
show usernames instead of owner_id / user_id
</label>
<div id="status"></div>
<div id="lastLoaded" class="small-note"></div>
<div id="navBar"></div>
<div id="sqlSection" style="display:none; margin-top:40px;">
<h2>SQL Console</h2>
<textarea id="sqlInput" rows="4" placeholder="SELECT * FROM users LIMIT 10;"></textarea>
<div class="small-note">ctrl+enter (or cmd+enter) runs the query</div>
<br><br>
<button onclick="runSQL()">Run SQL</button>
<select id="historySelect" onchange="loadFromHistory()">
<option value="">-- query history --</option>
</select>
<pre id="sqlResult"></pre>
</div>
<div id="backupSection" style="display:none; margin-top:40px;">
<h2>Backups</h2>
<div class="small-note">auto-backs up every 48hrs (via cron trigger). list below refreshes each time you load the db.</div>
<br>
<button onclick="runBackupNow()">Run Backup Now</button>
<button onclick="loadBackupList()">Refresh List</button>
<div id="backupList" style="margin-top:10px;"></div>
</div>
<div id="content"></div>
<script>
const WORKER_URL = "https://mcbcadmin.mcbcode.com/";
let autoRefreshEnabled = false;
let refreshInterval = null;
let currentDB = {}; // last loaded data, kept so search/sort/page/collapse don't need a refetch
let allCollapsed = false;
const PAGE_SIZE = 25;
const USER_ID_COLUMNS = ["owner_id", "user_id"]; // column names that get resolved to usernames when the toggle is on
document.getElementById("loadBtn").onclick = () => loadDatabase(false);
document.getElementById("autoRefreshBtn").onclick = toggleAutoRefresh;
document.getElementById("collapseAllBtn").onclick = toggleCollapseAll;
document.getElementById("globalSearch").oninput = (e) => applyGlobalSearch(e.target.value);
document.getElementById("resolveUsersToggle").onchange = () => renderAll();
function getKey() {
return document.getElementById("secret").value.trim();
}
function authHeaders(extra = {}) {
return { "x-admin-key": getKey(), ...extra };
}
function toggleAutoRefresh() {
autoRefreshEnabled = !autoRefreshEnabled;
const btn = document.getElementById("autoRefreshBtn");
btn.textContent = "Auto-refresh: " + (autoRefreshEnabled ? "ON" : "OFF");
if (autoRefreshEnabled) startAutoRefresh();
else if (refreshInterval) clearInterval(refreshInterval);
}
function startAutoRefresh() {
if (refreshInterval) clearInterval(refreshInterval);
refreshInterval = setInterval(() => {
if (autoRefreshEnabled) loadDatabase(true);
}, 5000);
}
function toggleCollapseAll() {
allCollapsed = !allCollapsed;
document.getElementById("collapseAllBtn").textContent = allCollapsed ? "Expand All" : "Collapse All";
for (const table of Object.values(currentDB)) {
table._collapsed = allCollapsed;
}
renderAll();
}
async function loadDatabase(isRefresh = false) {
const key = getKey();
if (!key) return;
const status = document.getElementById("status");
if (!isRefresh) {
status.textContent = "Loading...";
status.className = "";
}
try {
const res = await fetch(WORKER_URL, { headers: authHeaders() });
if (!res.ok) throw new Error(await res.text());
const db = await res.json();
// keep existing per-table state (query/page/sort/collapse) across refreshes
for (const [name, table] of Object.entries(db)) {
const old = currentDB[name];
if (old) {
table._query = old._query;
table._page = old._page;
table._sortCol = old._sortCol;
table._sortDir = old._sortDir;
table._collapsed = old._collapsed;
}
}
currentDB = db;
if (!isRefresh) {
status.textContent = "Loaded successfully.";
status.className = "success";
document.getElementById("sqlSection").style.display = "block";
document.getElementById("backupSection").style.display = "block";
loadBackupList();
}
document.getElementById("lastLoaded").textContent =
"last loaded: " + new Date().toLocaleTimeString();
renderNavBar();
renderAll();
} catch (err) {
status.textContent = err.message;
status.className = "error";
}
}
function renderNavBar() {
const nav = document.getElementById("navBar");
nav.replaceChildren();
for (const tableName of Object.keys(currentDB)) {
const a = document.createElement("a");
a.textContent = tableName;
a.onclick = () => {
const section = document.querySelector(`.section[data-table="${tableName}"]`);
if (section) section.scrollIntoView({ behavior: "smooth" });
};
nav.appendChild(a);
}
}
function renderAll() {
const content = document.getElementById("content");
const newContent = document.createElement("div");
for (const [tableName, table] of Object.entries(currentDB)) {
newContent.appendChild(renderTable(tableName, table));
}
content.replaceChildren(...newContent.childNodes);
}
function applyGlobalSearch(query) {
for (const table of Object.values(currentDB)) {
table._query = query;
table._page = 1;
}
renderAll();
}
function matchesQuery(row, query) {
if (!query) return true;
const lower = query.toLowerCase();
return Object.values(row).some(v => (v ?? "").toString().toLowerCase().includes(lower));
}
// looks up a username for a given id by checking the "users" table already loaded.
// doesn't touch the actual db data, just used to decide what to display.
function resolveUsername(id) {
const usersTable = Object.entries(currentDB).find(([name]) => name.toLowerCase() === "users");
if (!usersTable) return null;
const [, table] = usersTable;
const pkCol = table.schema ? (table.schema.find(c => c.pk)?.name || "id") : "id";
const row = table.rows.find(r => String(r[pkCol]) === String(id));
if (!row) return null;
const labelCol = ["username", "name", "display_name", "email"].find(c => c in row);
if (labelCol) return row[labelCol];
// fallback: first column that isn't the pk
const fallbackCol = Object.keys(row).find(c => c !== pkCol);
return fallbackCol ? row[fallbackCol] : null;
}
function renderTable(tableName, table) {
const section = document.createElement("div");
section.className = "section";
section.dataset.table = tableName;
const header = document.createElement("div");
header.className = "section-header";
const collapseToggle = document.createElement("span");
collapseToggle.className = "collapse-toggle";
collapseToggle.textContent = table._collapsed ? "▶" : "▼";
collapseToggle.onclick = () => {
table._collapsed = !table._collapsed;
renderAll();
};
header.appendChild(collapseToggle);
const title = document.createElement("h2");
title.style.margin = "0";
title.textContent = `${tableName} (${table.rowCount} rows)`;
title.onclick = () => {
table._collapsed = !table._collapsed;
renderAll();
};
title.style.cursor = "pointer";
header.appendChild(title);
if (table._collapsed) {
section.appendChild(header);
return section;
}
const search = document.createElement("input");
search.className = "search-box";
search.placeholder = "filter this table...";
search.value = table._query || "";
search.oninput = () => {
table._query = search.value;
table._page = 1;
renderAll();
};
header.appendChild(search);
const schemaBtn = document.createElement("button");
schemaBtn.textContent = "Schema";
schemaBtn.onclick = () => {
const box = section.querySelector(".schema-box");
box.style.display = box.style.display === "block" ? "none" : "block";
};
header.appendChild(schemaBtn);
const addBtn = document.createElement("button");
addBtn.textContent = "Add Row";
addBtn.onclick = () => {
const box = section.querySelector(".insert-box");
box.style.display = box.style.display === "block" ? "none" : "block";
};
header.appendChild(addBtn);
const exportCsvBtn = document.createElement("button");
exportCsvBtn.textContent = "Export CSV";
exportCsvBtn.onclick = () => exportCSV(tableName, table);
header.appendChild(exportCsvBtn);
const exportJsonBtn = document.createElement("button");
exportJsonBtn.textContent = "Export JSON";
exportJsonBtn.onclick = () => exportJSON(tableName, table);
header.appendChild(exportJsonBtn);
section.appendChild(header);
// schema box
const schemaBox = document.createElement("div");
schemaBox.className = "schema-box";
if (table.schema) {
schemaBox.textContent = table.schema
.map(c => `${c.name} (${c.type})${c.pk ? " [PRIMARY KEY]" : ""}${c.notnull ? " NOT NULL" : ""}`)
.join("\n");
schemaBox.style.whiteSpace = "pre";
}
section.appendChild(schemaBox);
// insert row box
const insertBox = document.createElement("div");
insertBox.className = "insert-box";
if (table.schema) {
const form = document.createElement("div");
const inputs = {};
for (const col of table.schema) {
const label = document.createElement("label");
label.textContent = col.name + (col.pk ? " (pk, leave blank for auto)" : "") + ": ";
const input = document.createElement("input");
input.style.width = "140px";
inputs[col.name] = input;
label.appendChild(input);
form.appendChild(label);
}
const submitBtn = document.createElement("button");
submitBtn.textContent = "Insert";
submitBtn.style.marginTop = "8px";
submitBtn.onclick = () => insertRow(tableName, inputs);
insertBox.appendChild(form);
insertBox.appendChild(document.createElement("br"));
insertBox.appendChild(submitBtn);
}
section.appendChild(insertBox);
if (table.rows.length === 0) {
const p = document.createElement("p");
p.textContent = "No rows.";
section.appendChild(p);
return section;
}
const columns = Object.keys(table.rows[0]);
const pkColumn = table.schema ? (table.schema.find(c => c.pk)?.name || columns[0]) : columns[0];
const resolveUsers = document.getElementById("resolveUsersToggle").checked;
// filter + sort (over the full row set, before paging)
let matches = table.rows.filter(r => matchesQuery(r, table._query));
if (table._sortCol) {
const col = table._sortCol, dir = table._sortDir || 1;
matches = [...matches].sort((a, b) => {
const va = a[col], vb = b[col];
if (va === vb) return 0;
if (va === null || va === undefined) return 1;
if (vb === null || vb === undefined) return -1;
return (va > vb ? 1 : -1) * dir;
});
}
const totalPages = Math.max(1, Math.ceil(matches.length / PAGE_SIZE));
table._page = Math.min(table._page || 1, totalPages);
const pageRows = matches.slice((table._page - 1) * PAGE_SIZE, table._page * PAGE_SIZE);
const tableEl = document.createElement("table");
const thead = document.createElement("thead");
const headRow = document.createElement("tr");
for (const column of columns) {
const th = document.createElement("th");
th.textContent = column + (table._sortCol === column ? (table._sortDir === -1 ? " ▼" : " ▲") : "");
th.onclick = () => {
if (table._sortCol !== column) { table._sortCol = column; table._sortDir = 1; }
else table._sortDir *= -1;
renderAll();
};
headRow.appendChild(th);
}
const actionTh = document.createElement("th");
actionTh.textContent = "actions";
headRow.appendChild(actionTh);
thead.appendChild(headRow);
tableEl.appendChild(thead);
const tbody = document.createElement("tbody");
for (const row of pageRows) {
const tr = document.createElement("tr");
for (const column of columns) {
const td = document.createElement("td");
let value = row[column];
if (typeof value === "object" && value !== null) {
value = JSON.stringify(value, null, 2);
}
const rawText = value ?? "";
// display-only: show the username next to the id, never touches the real data
if (resolveUsers && USER_ID_COLUMNS.includes(column.toLowerCase()) && rawText !== "") {
const username = resolveUsername(rawText);
if (username) {
td.textContent = "";
td.appendChild(document.createTextNode(rawText + " "));
const hint = document.createElement("span");
hint.className = "resolved-hint";
hint.textContent = `(${username})`;
td.appendChild(hint);
} else {
td.textContent = rawText;
}
} else {
td.textContent = rawText;
}
// single click = copy the raw value (not the resolved username)
td.onclick = async () => {
await navigator.clipboard.writeText(rawText);
const old = td.innerHTML;
td.textContent = "copied!";
setTimeout(() => { td.innerHTML = old; }, 800);
};
// double click = edit inline
td.ondblclick = (e) => {
e.stopPropagation();
startCellEdit(td, tableName, pkColumn, row[pkColumn], column, rawText);
};
tr.appendChild(td);
}
const actionTd = document.createElement("td");
const delBtn = document.createElement("button");
delBtn.textContent = "delete";
delBtn.onclick = () => deleteRow(tableName, pkColumn, row[pkColumn]);
actionTd.appendChild(delBtn);
tr.appendChild(actionTd);
tbody.appendChild(tr);
}
tableEl.appendChild(tbody);
section.appendChild(tableEl);
// pager
const pager = document.createElement("div");
pager.className = "pager";
const prevBtn = document.createElement("button");
prevBtn.textContent = "Prev";
prevBtn.disabled = table._page <= 1;
prevBtn.onclick = () => { table._page--; renderAll(); };
const nextBtn = document.createElement("button");
nextBtn.textContent = "Next";
nextBtn.disabled = table._page >= totalPages;
nextBtn.onclick = () => { table._page++; renderAll(); };
const pageInfo = document.createElement("span");
pageInfo.textContent = `page ${table._page} of ${totalPages} (${matches.length} matching rows)`;
pager.appendChild(prevBtn);
pager.appendChild(nextBtn);
pager.appendChild(pageInfo);
section.appendChild(pager);
return section;
}
function startCellEdit(td, tableName, pkColumn, pkValue, column, currentValue) {
const input = document.createElement("input");
input.value = currentValue;
td.textContent = "";
td.appendChild(input);
input.focus();
const save = async () => {
const newValue = input.value;
if (newValue === currentValue) {
td.textContent = currentValue;
return;
}
await updateCell(tableName, pkColumn, pkValue, column, newValue);
};
input.onblur = save;
input.onkeydown = (e) => {
if (e.key === "Enter") input.blur();
if (e.key === "Escape") { td.textContent = currentValue; input.onblur = null; }
};
}
function sqlLiteral(v) {
if (v === "" || v === null || v === undefined) return "NULL";
if (!isNaN(v) && v.toString().trim() !== "") return v;
return `'${v.toString().replace(/'/g, "''")}'`;
}
async function updateCell(tableName, pkColumn, pkValue, column, newValue) {
const sql = `UPDATE "${tableName}" SET "${column}" = ${sqlLiteral(newValue)} WHERE "${pkColumn}" = ${sqlLiteral(pkValue)};`;
try {
const res = await fetch(WORKER_URL, {
method: "POST",
headers: authHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({ sql })
});
const data = await res.json();
if (data.error) throw new Error(data.error);
await loadDatabase(true);
} catch (err) {
alert("update failed: " + err.message);
await loadDatabase(true);
}
}
async function insertRow(tableName, inputs) {
const cols = [];
const vals = [];
for (const [col, input] of Object.entries(inputs)) {
if (input.value.trim() === "") continue; // skip blanks, lets autoincrement/defaults handle it
cols.push(`"${col}"`);
vals.push(sqlLiteral(input.value));
}
if (cols.length === 0) {
alert("fill in at least one field");
return;
}
const sql = `INSERT INTO "${tableName}" (${cols.join(", ")}) VALUES (${vals.join(", ")});`;
try {
const res = await fetch(WORKER_URL, {
method: "POST",
headers: authHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({ sql })
});
const data = await res.json();
if (data.error) throw new Error(data.error);
await loadDatabase(true);
} catch (err) {
alert("insert failed: " + err.message);
}
}
function exportCSV(tableName, table) {
if (table.rows.length === 0) return;
const columns = Object.keys(table.rows[0]);
const lines = [columns.join(",")];
for (const row of table.rows) {
const line = columns.map(c => {
let v = row[c];
if (typeof v === "object" && v !== null) v = JSON.stringify(v);
v = (v ?? "").toString().replace(/"/g, '""');
return `"${v}"`;
}).join(",");
lines.push(line);
}
downloadBlob(lines.join("\n"), `${tableName}.csv`, "text/csv");
}
function exportJSON(tableName, table) {
downloadBlob(JSON.stringify(table.rows, null, 2), `${tableName}.json`, "application/json");
}
function downloadBlob(content, filename, type) {
const blob = new Blob([content], { type });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = filename;
a.click();
}
async function deleteRow(tableName, pkColumn, pkValue) {
if (!confirm(`delete row where ${pkColumn} = ${pkValue} from ${tableName}? this cant be undone`)) return;
const sql = `DELETE FROM "${tableName}" WHERE "${pkColumn}" = ${sqlLiteral(pkValue)};`;
try {
const res = await fetch(WORKER_URL, {
method: "POST",
headers: authHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({ sql })
});
const data = await res.json();
if (data.error) throw new Error(data.error);
await loadDatabase(true);
} catch (err) {
alert("delete failed: " + err.message);
}
}
// --- SQL console ---
let queryHistory = JSON.parse(localStorage.getItem("mcbc_sql_history") || "[]");
function saveToHistory(sql) {
queryHistory = queryHistory.filter(q => q !== sql);
queryHistory.unshift(sql);
queryHistory = queryHistory.slice(0, 10);
localStorage.setItem("mcbc_sql_history", JSON.stringify(queryHistory));
renderHistory();
}
function renderHistory() {
const select = document.getElementById("historySelect");
select.innerHTML = '<option value="">-- query history --</option>';
queryHistory.forEach((q, i) => {
const opt = document.createElement("option");
opt.value = i;
opt.textContent = q.length > 50 ? q.slice(0, 50) + "..." : q;
select.appendChild(opt);
});
}
function loadFromHistory() {
const select = document.getElementById("historySelect");
if (select.value === "") return;
document.getElementById("sqlInput").value = queryHistory[select.value];
}
document.getElementById("sqlInput").addEventListener("keydown", (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === "Enter") runSQL();
});
async function runSQL() {
const sql = document.getElementById("sqlInput").value.trim();
const result = document.getElementById("sqlResult");
if (!sql) return;
result.textContent = "Running...";
saveToHistory(sql);
try {
const res = await fetch(WORKER_URL, {
method: "POST",
headers: authHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({ sql })
});
const data = await res.json();
if (data.error) throw new Error(data.error);
result.textContent = JSON.stringify(data, null, 2) + `\n\n(took ${data.ms}ms)`;
await loadDatabase(true);
} catch (err) {
result.textContent = err.message;
}
}
// --- backups ---
async function loadBackupList() {
const list = document.getElementById("backupList");
list.textContent = "loading...";
try {
const res = await fetch(`${WORKER_URL}?action=list_backups`, { headers: authHeaders() });
const backups = await res.json();
if (backups.error) throw new Error(backups.error);
if (backups.length === 0) {
list.textContent = "no backups yet.";
return;
}
list.replaceChildren();
for (const b of backups) {
const row = document.createElement("div");
const kb = (b.size / 1024).toFixed(1);
row.textContent = `#${b.id} — ${b.created_at} (${kb} KB) `;
const dlBtn = document.createElement("button");
dlBtn.textContent = "Download";
dlBtn.onclick = () => downloadBackup(b.id, b.created_at);
const delBtn = document.createElement("button");
delBtn.textContent = "Delete";
delBtn.onclick = () => deleteBackup(b.id);
row.appendChild(dlBtn);
row.appendChild(delBtn);
list.appendChild(row);
}
} catch (err) {
list.textContent = "error: " + err.message;
}
}
async function downloadBackup(id, createdAt) {
try {
const res = await fetch(`${WORKER_URL}?action=get_backup&id=${id}`, { headers: authHeaders() });
const backup = await res.json();
if (backup.error) throw new Error(backup.error);
downloadBlob(
JSON.stringify(backup.data, null, 2),
`backup-${id}-${createdAt.slice(0, 10)}.json`,
"application/json"
);
} catch (err) {
alert("download failed: " + err.message);
}
}
async function deleteBackup(id) {
if (!confirm(`delete backup #${id}? this cant be undone.`)) return;
if (!confirm(`really sure? this is your last chance to back out of deleting backup #${id}.`)) return;
try {
const res = await fetch(WORKER_URL, {
method: "POST",
headers: authHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({ action: "delete_backup", id })
});
const data = await res.json();
if (data.error) throw new Error(data.error);
await loadBackupList();
} catch (err) {
alert("delete failed: " + err.message);
}
}
async function runBackupNow() {
try {
const res = await fetch(WORKER_URL, {
method: "POST",
headers: authHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({ action: "backup_now" })
});
const data = await res.json();
if (data.error) throw new Error(data.error);
if (data.backup.skipped) {
alert("skipped: " + data.backup.reason);
} else {
alert("backup created at " + data.backup.created_at);
}
await loadBackupList();
} catch (err) {
alert("backup failed: " + err.message);
}
}
renderHistory();
</script>
</body>
</html>