-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
559 lines (520 loc) · 30.6 KB
/
index.html
File metadata and controls
559 lines (520 loc) · 30.6 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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Database Viewer</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
background: #ffffff;
color: #222;
}
body.dark { background:#1e1f22; color:#ddd; }
table {
border-collapse: collapse;
width: 100%;
margin-top: 10px;
}
th, td {
border: 1px solid #ccc;
padding: 8px;
text-align: left;
}
th { background-color: #f2f2f2; position:sticky; top:0; z-index:2; cursor:pointer; }
body.dark th { background:#333; }
#controls {
margin-bottom: 20px;
}
#extraControls { margin:10px 0 20px; display:flex; flex-wrap:wrap; gap:12px; align-items:center; }
#columnToggles { max-height:140px; overflow:auto; border:1px solid #aaa; padding:6px; background:#fafafa; }
body.dark #columnToggles { background:#2a2d31; border-color:#555; }
.badge { display:inline-block; padding:2px 6px; border-radius:4px; background:#eee; margin-right:4px; font-size:12px; }
body.dark .badge { background:#444; }
mark { background: #ffe58a; padding:0 2px; }
body.dark mark { background:#665500; }
.sortable-indicator { font-size:10px; margin-left:4px; opacity:0.6; }
.btn { padding:4px 10px; cursor:pointer; border:1px solid #888; background:#f5f5f5; border-radius:4px; }
.btn:hover { background:#eaeaea; }
body.dark .btn { background:#333; border-color:#666; color:#ddd; }
body.dark .btn:hover { background:#3d3d3d; }
#stats { font-size:14px; margin-top:10px; white-space:pre; font-family:monospace; overflow:auto; max-height:200px; }
#statusLine { margin-top:6px; font-size:12px; opacity:.8; }
.flex-sep { flex:1 1 auto; }
a.download-link { text-decoration:none; }
</style>
</head>
<body>
<h1>Database Viewer</h1>
<p id="entriesCount">Entries in current table: 0</p>
<div id="controls">
<label for="databaseSelect">Select Database Snapshot:</label>
<select id="databaseSelect">
<option value="database.sql.gz" selected>database.sql.gz (legacy dump)</option>
<option value="database2.sql.gz">database2.sql.gz (v2 dump)</option>
<option value="currentAuctions.db">currentAuctions.db (raw db if present)</option>
</select>
<label for="tableSelect">Select Table:</label>
<select id="tableSelect">
<option disabled selected>Loading tables...</option>
</select>
<!-- Search input -->
<label for="searchInput" style="margin-left: 20px;">Search:</label>
<input type="text" id="searchInput" placeholder="Type to search..." />
</div>
<div id="extraControls">
<div>
<label style="font-weight:bold;">Columns:</label>
<div id="columnToggles"></div>
</div>
<div>
<button id="computeStats" class="btn">Compute Stats</button>
<button id="exportCsv" class="btn">Export CSV</button>
<button id="toggleDark" class="btn">Dark Mode</button>
</div>
<div>
<label>Jump to page:</label>
<input type="number" id="jumpPage" style="width:70px;" min="1" />
<button id="jumpBtn" class="btn">Go</button>
</div>
<div>
<label><input type="checkbox" id="formatTimestamp" checked /> Format timestamps</label>
</div>
<span class="flex-sep"></span>
<div id="statusLine"></div>
</div>
<div id="tableContainer"></div>
<div id="stats"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.6.2/sql-wasm.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pako/2.1.0/pako.min.js"></script>
<script>
(async function() {
// Configure sql.js to get the WASM file from the CDN.
const config = {
locateFile: file => `https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.6.2/${file}`
};
// Initialize SQL.js.
const SQL = await initSqlJs(config);
// Globals that change when a database is loaded
let db = null;
let tableNames = [];
let currentTableName = null;
let sortColumn = null;
let sortDir = 'ASC';
const hiddenColumns = new Set();
let lastSearchQuery = '';
const tableColumnsCache = {}; // cache per DB load
async function loadDatabase(dbFile) {
const statusEl = document.getElementById('statusLine');
statusEl.textContent = `Loading ${dbFile} ...`;
Object.keys(tableColumnsCache).forEach(k=>delete tableColumnsCache[k]);
sortColumn = null; sortDir='ASC'; hiddenColumns.clear(); lastSearchQuery='';
db = null;
try {
if (dbFile.endsWith('.sql.gz')) {
// Fetch compressed SQL dump, gunzip, execute statements to reconstruct DB in-memory.
if (typeof pako === 'undefined') {
throw new Error('pako library not loaded. Please check your internet connection and ensure the CDN is accessible.');
}
const res = await fetch(dbFile + '?_ts=' + Date.now());
if (!res.ok) throw new Error(`Fetch failed (${res.status})`);
const compressed = new Uint8Array(await res.arrayBuffer());
let sqlText;
try {
sqlText = new TextDecoder('utf-8').decode(pako.ungzip(compressed));
} catch (decompErr) {
throw new Error('Decompression failed: ' + decompErr.message);
}
db = new SQL.Database();
// Iterate statements using regex to avoid creating a massive array (OOM prevention)
// and execute in batches to avoid locking the UI or overflowing WASM stack.
const stmtEndRegex = /;\s*(?:\n|$)/g;
let match;
let lastIndex = 0;
let count = 0;
db.run('BEGIN TRANSACTION;');
while ((match = stmtEndRegex.exec(sqlText)) !== null) {
const stmt = sqlText.substring(lastIndex, match.index + 1).trim();
lastIndex = match.index + match[0].length;
if (!stmt) continue;
if (stmt.startsWith('--')) continue;
if (stmt.startsWith('{')) continue; // Skip JSON metadata lines
// Skip transaction/pragma control from the dump to manage our own batches
if (/^(BEGIN|COMMIT|ROLLBACK|PRAGMA)/i.test(stmt)) continue;
try {
db.run(stmt);
} catch (e) {
console.warn('Statement failed:', stmt.substring(0, 50) + '...', e);
}
count++;
// Commit every 2000 statements to manage memory/speed
if (count % 2000 === 0) {
db.run('COMMIT;');
db.run('BEGIN TRANSACTION;');
// Yield to UI thread periodically to prevent freeze
if (count % 10000 === 0) {
statusEl.textContent = `Loading ${dbFile} (${Math.floor(lastIndex/1024/1024)}MB processed)...`;
await new Promise(r => setTimeout(r, 0));
}
}
}
db.run('COMMIT;');
} else if (dbFile.endsWith('.db')) {
const response = await fetch(dbFile + '?_ts=' + Date.now());
if (!response.ok) throw new Error(`Fetch failed (${response.status})`);
const buffer = await response.arrayBuffer();
db = new SQL.Database(new Uint8Array(buffer));
} else {
throw new Error('Unsupported file type');
}
} catch (e) {
document.getElementById('tableContainer').innerHTML = `<p style='color:red;'>Error loading ${dbFile}: ${e.message}. If you intended to use the compressed dumps, keep the .sql.gz files produced by prepare_db_snapshots.py in the repo root.</p>`;
statusEl.textContent = '';
return;
}
const res = db.exec("SELECT name FROM sqlite_master WHERE type='table';");
tableNames = (res[0] && res[0].values.map(r=>r[0])) || [];
const tableSelect = document.getElementById('tableSelect');
tableSelect.innerHTML = '';
if (tableNames.length === 0) {
tableSelect.innerHTML = '<option disabled>No tables found</option>';
document.getElementById('tableContainer').innerHTML = `<p>No tables in ${dbFile}</p>`;
document.getElementById('entriesCount').textContent = 'Entries in current table: 0';
statusEl.textContent = '';
return;
}
tableNames.forEach(name => {
const opt = document.createElement('option');
opt.value = name; opt.textContent = name; tableSelect.appendChild(opt);
});
currentTableName = tableNames[0];
displayTable(currentTableName);
statusEl.textContent = `Loaded ${dbFile} (${tableNames.length} tables)`;
}
// Initialize records-per-page controls and pagination variables
let recordsPerPage = 25;
let currentPage = 1;
const recordsSelectHTML = `
<label for="recordsPerPageSelect" style="margin-left: 20px;">Records per page:</label>
<select id="recordsPerPageSelect">
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="300">300</option>
<option value="500">500</option>
<option value="custom">Custom</option>
</select>
<input type="number" id="customPerPage" placeholder="Custom number" style="display:none; margin-left:5px; width:100px;" />
`;
document.getElementById('controls').insertAdjacentHTML('beforeend', recordsSelectHTML);
const recordsPerPageSelect = document.getElementById('recordsPerPageSelect');
const customPerPageInput = document.getElementById('customPerPage');
recordsPerPageSelect.addEventListener('change', function() {
if (this.value === "custom") {
customPerPageInput.style.display = "inline-block";
let customVal = parseInt(customPerPageInput.value) || 25;
recordsPerPage = customVal;
} else {
customPerPageInput.style.display = "none";
recordsPerPage = parseInt(this.value);
}
currentPage = 1;
displayTable(currentTableName, document.getElementById('searchInput').value);
});
customPerPageInput.addEventListener('input', function() {
let val = parseInt(this.value);
if (!isNaN(val) && val > 0) {
recordsPerPage = val;
currentPage = 1;
displayTable(currentTableName, document.getElementById('searchInput').value);
}
});
const tableSelect = document.getElementById('tableSelect');
const databaseSelect = document.getElementById('databaseSelect');
function getTableColumns(tableName) {
if (tableColumnsCache[tableName]) return tableColumnsCache[tableName];
const pragma = db.exec(`PRAGMA table_info("${tableName}");`);
if (!pragma[0]) return [];
const cols = pragma[0].values.map(row => row[1]); // second field is name
tableColumnsCache[tableName] = cols;
return cols;
}
// Function to display table contents with optional global search filtering and pagination.
function generateColumnToggles(columns) {
const box = document.getElementById('columnToggles');
box.innerHTML = '';
columns.forEach(c => {
const id = 'colToggle_' + c;
const label = document.createElement('label');
label.style.display = 'inline-block';
label.style.marginRight = '8px';
label.innerHTML = `<input type="checkbox" id="${id}" data-col="${c}" ${hiddenColumns.has(c)?'':'checked'} /> ${c}`;
box.appendChild(label);
});
box.querySelectorAll('input[type=checkbox]').forEach(cb => {
cb.addEventListener('change', () => {
const col = cb.getAttribute('data-col');
if (cb.checked) hiddenColumns.delete(col); else hiddenColumns.add(col);
displayTable(currentTableName, document.getElementById('searchInput').value, false);
});
});
}
function formatCell(col, val) {
if (val === null || val === undefined) return '';
if (col === 'ench') {
try {
if (typeof val === 'string' && val.trim().startsWith('{')) {
const obj = JSON.parse(val);
if (obj && typeof obj === 'object') {
const parts = Object.keys(obj).sort().map(k => `${k}=${obj[k]}`);
return parts.join(', ');
}
}
} catch { /* ignore parse errors */ }
return val; // fallback raw
}
if (col === 'timestamp' && document.getElementById('formatTimestamp').checked) {
const num = Number(val);
if (!isNaN(num) && num > 1000000000) { // seconds or ms heuristic
let ms = num < 2e12 ? num : Math.floor(num/1000); // if > year 2033 treat as ms
const d = new Date(ms);
return d.toISOString().replace('T',' ').split('.')[0];
}
}
return val;
}
function highlight(text, query) {
if (!query) return text;
try {
const esc = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const re = new RegExp('(' + esc + ')', 'ig');
return text.toString().replace(re, '<mark>$1</mark>');
} catch { return text; }
}
function displayTable(tableName, searchQuery = "", refreshToggles = true) {
const container = document.getElementById('tableContainer');
container.innerHTML = "";
const escaped = searchQuery.replace(/'/g, "''").toLowerCase();
const hasSearch = escaped.trim() !== "";
let whereClause = "";
let columns = getTableColumns(tableName);
if (columns.length === 0) {
container.innerHTML = `<p>No data available in table "${tableName}"</p>`;
return;
}
if (refreshToggles) generateColumnToggles(columns);
if (hasSearch) {
// Build OR clause across all columns, casting to text & lower-casing
const likeExprs = columns.map(c => `LOWER(CAST("${c}" AS TEXT)) LIKE '%${escaped}%'`);
whereClause = 'WHERE ' + likeExprs.join(' OR ');
}
// Counts
const totalRecords = db.exec(`SELECT COUNT(*) FROM "${tableName}";`)[0].values[0][0];
const filteredRecords = hasSearch ? db.exec(`SELECT COUNT(*) FROM "${tableName}" ${whereClause};`)[0].values[0][0] : totalRecords;
// Pagination based on filtered set
let totalPages = Math.max(1, Math.ceil(filteredRecords / recordsPerPage));
if (currentPage > totalPages) currentPage = totalPages; // adjust if necessary
const offset = (currentPage - 1) * recordsPerPage;
const orderClause = sortColumn ? `ORDER BY "${sortColumn}" ${sortDir}` : '';
const query = `SELECT * FROM "${tableName}" ${whereClause} ${orderClause} LIMIT ${recordsPerPage} OFFSET ${offset};`;
const result = db.exec(query);
if (!result[0] || result[0].values.length === 0) {
container.innerHTML = `<p>No matching records found in table "${tableName}"</p>`;
const entriesCountElement = document.getElementById('entriesCount');
entriesCountElement.textContent = hasSearch
? `Entries in current table: 0 / ${totalRecords.toLocaleString()} (filtered)`
: `Entries in current table: ${totalRecords.toLocaleString()}`;
return;
}
const { values } = result[0];
// Build table
const table = document.createElement('table');
const thead = document.createElement('thead');
const headerRow = document.createElement('tr');
columns.forEach(col => {
if (hiddenColumns.has(col)) return;
const th = document.createElement('th');
th.innerHTML = col + (sortColumn === col ? ` <span class="sortable-indicator">${sortDir === 'ASC' ? '▲' : '▼'}</span>` : '');
th.addEventListener('click', () => {
if (sortColumn === col) { sortDir = (sortDir === 'ASC') ? 'DESC' : 'ASC'; }
else { sortColumn = col; sortDir = 'ASC'; }
displayTable(tableName, document.getElementById('searchInput').value, false);
});
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
table.appendChild(thead);
const tbody = document.createElement('tbody');
values.forEach(row => {
const tr = document.createElement('tr');
row.forEach((cell, idx) => {
const col = columns[idx];
if (hiddenColumns.has(col)) return;
const td = document.createElement('td');
const formatted = formatCell(col, cell);
td.innerHTML = hasSearch ? highlight(formatted, searchQuery) : formatted;
td.title = `${col}`;
td.addEventListener('dblclick', () => {
navigator.clipboard.writeText(cell === null ? '' : cell.toString());
const status = document.getElementById('statusLine');
status.textContent = `Copied ${col} value to clipboard.`;
setTimeout(()=>{ if (status.textContent.startsWith('Copied')) status.textContent=''; }, 2000);
});
tr.appendChild(td);
});
tbody.appendChild(tr);
});
table.appendChild(tbody);
container.appendChild(table);
// Update entries count
const entriesCountElement = document.getElementById('entriesCount');
if (hasSearch) {
entriesCountElement.textContent = `Entries in current table: ${filteredRecords.toLocaleString()} / ${totalRecords.toLocaleString()} (filtered)`;
} else {
entriesCountElement.textContent = `Entries in current table: ${totalRecords.toLocaleString()}`;
}
// Pagination controls
const paginationControls = document.createElement('div');
paginationControls.style.marginTop = '10px';
if (currentPage > 1) {
const prevButton = document.createElement('button');
prevButton.textContent = 'Previous';
prevButton.addEventListener('click', () => {
currentPage--;
displayTable(tableName, searchQuery);
});
paginationControls.appendChild(prevButton);
}
if (currentPage < totalPages) {
const nextButton = document.createElement('button');
nextButton.textContent = 'Next';
nextButton.style.marginLeft = '10px';
nextButton.addEventListener('click', () => {
currentPage++;
displayTable(tableName, searchQuery);
});
paginationControls.appendChild(nextButton);
}
// Page indicator
const pageInfo = document.createElement('span');
pageInfo.style.marginLeft = '15px';
pageInfo.textContent = `Page ${currentPage} of ${totalPages}`;
paginationControls.appendChild(pageInfo);
container.appendChild(paginationControls);
lastSearchQuery = searchQuery;
}
// Initial load of the default selected database
await loadDatabase(databaseSelect.value);
// Switch database
databaseSelect.addEventListener('change', async function() {
currentPage = 1;
await loadDatabase(this.value);
});
// When table is changed, clear search and display new table.
tableSelect.addEventListener('change', function() {
currentTableName = this.value;
document.getElementById('searchInput').value = "";
sortColumn = null; sortDir = 'ASC'; hiddenColumns.clear();
displayTable(currentTableName);
});
// Live search as the user types.
const searchInput = document.getElementById('searchInput');
searchInput.addEventListener('input', function() {
currentPage = 1; // reset to first page when starting a new search
displayTable(currentTableName, this.value);
});
// Jump to page
document.getElementById('jumpBtn').addEventListener('click', () => {
const val = parseInt(document.getElementById('jumpPage').value);
if (!isNaN(val) && val > 0) { currentPage = val; displayTable(currentTableName, document.getElementById('searchInput').value, false); }
});
// Timestamp formatting toggle
document.getElementById('formatTimestamp').addEventListener('change', () => {
displayTable(currentTableName, document.getElementById('searchInput').value, false);
});
// Dark mode
document.getElementById('toggleDark').addEventListener('click', () => {
document.body.classList.toggle('dark');
});
// Stats computation
document.getElementById('computeStats').addEventListener('click', () => {
const searchQuery = document.getElementById('searchInput').value;
const escaped = searchQuery.replace(/'/g, "''").toLowerCase();
let whereClause = '';
const columns = getTableColumns(currentTableName);
if (escaped.trim() !== '') {
const likeExprs = columns.map(c => `LOWER(CAST("${c}" AS TEXT)) LIKE '%${escaped}%'`);
whereClause = 'WHERE ' + likeExprs.join(' OR ');
}
const statsBox = document.getElementById('stats');
statsBox.textContent = 'Computing stats...';
// Determine numeric columns by sampling first 100 rows
const sample = db.exec(`SELECT * FROM "${currentTableName}" ${whereClause} LIMIT 100;`);
const numericCols = [];
if (sample[0]) {
const cols = columns;
for (let ci=0; ci<cols.length; ci++) {
let allNum = true;
for (const row of sample[0].values) {
const v = row[ci];
if (v === null || v === '') continue;
if (isNaN(Number(v))) { allNum = false; break; }
}
if (allNum) numericCols.push(cols[ci]);
}
}
// Build stats queries
let lines = [];
lines.push(`Table: ${currentTableName}`);
const total = db.exec(`SELECT COUNT(*) FROM "${currentTableName}";`)[0].values[0][0];
const filtered = whereClause ? db.exec(`SELECT COUNT(*) FROM "${currentTableName}" ${whereClause};`)[0].values[0][0] : total;
lines.push(`Row count: ${filtered}${whereClause? ' / '+total+' (filtered)' : ''}`);
numericCols.forEach(col => {
const q = db.exec(`SELECT MIN(CAST("${col}" AS REAL)), MAX(CAST("${col}" AS REAL)), AVG(CAST("${col}" AS REAL)) FROM "${currentTableName}" ${whereClause};`);
if (q[0]) {
const [minv, maxv, avgv] = q[0].values[0];
lines.push(`${col.padEnd(15)} min=${minv} max=${maxv} avg=${avgv}`);
}
});
// Distinct counts for first up to 5 columns (to limit cost)
columns.slice(0,5).forEach(col => {
const q = db.exec(`SELECT COUNT(DISTINCT "${col}") FROM "${currentTableName}" ${whereClause};`);
if (q[0]) lines.push(`distinct(${col})=${q[0].values[0][0]}`);
});
statsBox.textContent = lines.join('\n');
});
// CSV export
document.getElementById('exportCsv').addEventListener('click', () => {
const searchQuery = document.getElementById('searchInput').value;
const escaped = searchQuery.replace(/'/g, "''").toLowerCase();
let whereClause = '';
const columns = getTableColumns(currentTableName);
if (escaped.trim() !== '') {
const likeExprs = columns.map(c => `LOWER(CAST("${c}" AS TEXT)) LIKE '%${escaped}%'`);
whereClause = 'WHERE ' + likeExprs.join(' OR ');
}
const orderClause = sortColumn ? `ORDER BY "${sortColumn}" ${sortDir}` : '';
const all = db.exec(`SELECT * FROM "${currentTableName}" ${whereClause} ${orderClause};`);
if (!all[0]) { alert('No data to export'); return; }
const rows = [columns.filter(c=>!hiddenColumns.has(c))];
all[0].values.forEach(row => {
rows.push(row.filter((_,i)=>!hiddenColumns.has(columns[i])));
});
const csv = rows.map(r => r.map(v => {
if (v === null || v === undefined) return '';
const s = v.toString().replace(/"/g,'""');
return '"' + s + '"';
}).join(',')).join('\n');
const blob = new Blob([csv], {type:'text/csv'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${currentTableName}_export.csv`;
a.className='download-link';
a.click();
URL.revokeObjectURL(url);
});
})();
</script>
</body>
</html>