-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
738 lines (678 loc) · 34.7 KB
/
index.html
File metadata and controls
738 lines (678 loc) · 34.7 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DB Playground — Week 2</title>
<!-- Tailwind CDN -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
'db-bg': '#0f0f0f',
'db-surface': '#161616',
'db-s2': '#1e1e1e',
'db-line': '#2a2a2a',
'db-accent': '#e8ff5a',
'db-green': '#5affb8',
'db-muted': '#555555',
'db-text': '#d4d4d4',
'db-hi': '#f0f0f0',
'db-red': '#ff6b6b',
'db-blue': '#60a5fa',
},
fontFamily: {
mono: ['"IBM Plex Mono"', 'monospace'],
}
}
}
}
</script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=IBM+Plex+Sans:wght@300;400;500&display=swap" rel="stylesheet">
<style>
/* ── Things Tailwind can't express cleanly ── */
body { font-family: 'IBM Plex Sans', sans-serif; }
::-webkit-scrollbar { width: 5px; height: 5px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: #2a2a2a; border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: #555; }
#sql-editor { resize: vertical; tab-size: 2; }
/* Custom checkbox — too complex for Tailwind alone */
.q-chk {
width: 15px; height: 15px; flex-shrink: 0;
border: 1.5px solid #555; border-radius: 2px; cursor: pointer;
transition: all .15s; display: flex; align-items: center; justify-content: center;
font-size: 9px; font-weight: bold; color: #000; margin-top: 2px;
}
.q-chk:hover { border-color: #5affb8; }
.q-chk.done { background: #5affb8; border-color: #5affb8; }
.q-chk.done::after { content: '✓'; }
/* Results table */
.results-table { border-collapse: collapse; font-family: 'IBM Plex Mono', monospace; font-size: 12px; width: 100%; }
.results-table th { padding: 6px 14px; background: #1e1e1e; color: #e8ff5a; font-weight: 500; text-align: left; border-bottom: 1px solid #2a2a2a; white-space: nowrap; position: sticky; top: 0; }
.results-table td { padding: 5px 14px; color: #d4d4d4; border-bottom: 1px solid rgba(255,255,255,.04); white-space: nowrap; }
.results-table tr:hover td { background: rgba(255,255,255,.03); }
.results-table .null-val { color: #555; font-style: italic; }
/* Validation banner pass/fail colours — rgba values */
#val-banner.pass { background: rgba(90,255,184,.06); border-color: rgba(90,255,184,.3); color: #5affb8; }
#val-banner.fail { background: rgba(255,107,107,.06); border-color: rgba(255,107,107,.3); color: #ff6b6b; }
/* DB status dot active state */
#db-status.ok { background: #5affb8; }
/* Part progress pill when full */
.part-prog.full { color: #5affb8; }
/* Active question row highlight */
.q-row.active { background: #1e1e1e; border-left-color: #e8ff5a !important; }
.q-row { border-left: 2px solid transparent; transition: background .1s, border-color .1s; }
.q-row.done-row { opacity: 0.55; }
/* Part body collapsed */
.part-body.collapsed { display: none; }
/* Hint text toggle */
.hint-text { display: none; }
.hint-text.show { display: block; }
/* Expected output preview */
.exp-preview { display: none; }
.exp-preview.show { display: block; }
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.10.2/sql-wasm.js"></script>
</head>
<body class="bg-db-bg text-db-text text-sm h-screen overflow-hidden">
<div id="app" class="grid h-screen"
style="grid-template-columns: 240px 1fr 300px; grid-template-rows: 48px 1fr;">
<!-- ══ HEADER ══ -->
<header class="col-span-3 flex items-center gap-3.5 px-4 border-b border-db-line bg-db-surface">
<span class="font-mono text-[13px] font-medium text-db-accent tracking-[0.05em]">db.playground</span>
<span class="text-db-muted">/</span>
<span class="font-mono text-xs text-db-muted">Week 2</span>
<div class="flex-1"></div>
<span id="progress-pill"
class="font-mono text-[11px] px-2.5 py-0.5 rounded-full bg-db-s2 border border-db-line text-db-muted transition-all duration-300">
0 / 12 done
</span>
<div id="db-status" class="w-2 h-2 rounded-full bg-db-muted flex-shrink-0 transition-colors duration-300"></div>
<span id="db-name" class="font-mono text-[11px] text-db-green px-2.5 py-0.5 border border-db-green border-opacity-50 rounded opacity-70">no file</span>
<button onclick="newDatabase()"
class="font-mono text-[11px] tracking-widest px-3 py-1 rounded bg-db-s2 border border-db-line text-db-text hover:border-db-muted hover:text-db-hi cursor-pointer transition-all">
New DB
</button>
<button onclick="openFile()"
class="font-mono text-[11px] tracking-widest px-3 py-1 rounded bg-db-s2 border border-db-line text-db-text hover:border-db-muted hover:text-db-hi cursor-pointer transition-all">
Open .sqlite3
</button>
<button onclick="saveFile()"
class="font-mono text-[11px] tracking-widest px-3 py-1 rounded bg-db-accent text-black font-medium hover:opacity-85 cursor-pointer transition-all">
Save
</button>
</header>
<!-- ══ LEFT SIDEBAR: Schema ══ -->
<aside class="bg-db-surface border-r border-db-line overflow-y-auto flex flex-col">
<div class="font-mono text-[10px] font-medium tracking-widest text-db-muted uppercase px-3.5 pt-3 pb-2 flex-shrink-0">
Schema
</div>
<div id="schema-tree" class="flex-1"></div>
</aside>
<!-- ══ MAIN ══ -->
<main class="overflow-hidden bg-db-bg" style="display:grid; grid-template-rows: auto auto auto 1fr;">
<!-- Editor area -->
<div class="relative border-b border-db-line">
<textarea id="sql-editor" spellcheck="false"
class="w-full min-h-[160px] max-h-[260px] bg-db-surface text-db-hi font-mono text-[13px] leading-[1.7] border-none outline-none p-3.5 pb-10 block placeholder-db-muted"
placeholder="-- Click a question on the right to start -- Write your SQL here, then press ⌘/Ctrl + Enter to run"></textarea>
<!-- Toolbar -->
<div class="absolute bottom-0 left-0 right-0 flex items-center gap-2 px-3 py-1.5 bg-db-surface border-t border-db-line">
<button id="run-btn" onclick="runQuery()"
class="font-mono text-[11px] font-medium tracking-widest px-3.5 py-1 rounded-sm bg-db-accent text-black cursor-pointer hover:opacity-85 active:scale-95 transition-all">
▶ RUN
</button>
<span class="font-mono text-[10px] text-db-muted">⌘ + Enter</span>
<button id="check-btn" onclick="checkAnswer()"
style="display:none"
class="font-mono text-[11px] font-medium tracking-widest px-3 py-0.5 rounded-sm bg-transparent text-db-green border border-db-green hover:bg-db-green hover:text-black cursor-pointer transition-all">
✓ Check Answer
</button>
<span id="row-count" class="ml-auto font-mono text-[11px] text-db-muted"></span>
</div>
</div>
<!-- Last-run bar -->
<div id="last-run-bar" style="display:none"
class="flex items-start gap-2 px-3.5 py-2 border-b border-db-line bg-db-s2 min-h-0">
<span class="font-mono text-[10px] text-db-muted flex-shrink-0 mt-0.5">last run ›</span>
<span id="last-run-text" class="font-mono text-[11px] text-db-text leading-relaxed break-all"></span>
</div>
<!-- Validation banner -->
<div id="val-banner" style="display:none"
class="flex items-start gap-3 px-4 py-2.5 font-mono text-[12px] leading-snug border-b border-db-line">
<span id="val-icon" class="text-sm flex-shrink-0 mt-0.5"></span>
<span id="val-msg" class="flex-1"></span>
<button onclick="closeVal()" class="text-current opacity-40 hover:opacity-90 transition-opacity cursor-pointer bg-transparent border-none font-mono flex-shrink-0">✕</button>
</div>
<!-- Results area -->
<div id="results-area" class="overflow-auto">
<div id="results-msg" class="p-10 text-center font-mono text-xs text-db-muted">
Click <strong class="text-db-text">New DB</strong> to seed the schema and start the assignment.
</div>
</div>
</main>
<!-- ══ RIGHT SIDEBAR: Questions ══ -->
<aside class="bg-db-surface border-l border-db-line flex flex-col overflow-hidden">
<!-- Progress bar -->
<div class="px-3.5 py-3 border-b border-db-line flex-shrink-0">
<div class="flex items-center justify-between mb-1.5">
<span class="font-mono text-[10px] text-db-muted uppercase tracking-widest">Progress</span>
<span id="plabel" class="font-mono text-[10px] text-db-muted">0 of 12 completed</span>
</div>
<div class="h-1 bg-db-s2 rounded-full overflow-hidden">
<div id="pbar" class="h-full bg-db-green rounded-full transition-all duration-300" style="width:0%"></div>
</div>
</div>
<!-- Part sections (rendered by JS) -->
<div id="parts-container" class="flex-1 overflow-y-auto"></div>
<!-- Footer -->
<div class="px-3.5 py-2 border-t border-db-line flex-shrink-0">
<span class="font-mono text-[10px] text-db-muted">Chrome / Edge only · File System API</span>
</div>
</aside>
</div>
<!-- Toast -->
<div id="toast"
class="fixed bottom-5 left-1/2 -translate-x-1/2 bg-db-s2 border border-db-line font-mono text-xs text-db-hi px-4 py-2 rounded pointer-events-none z-50 transition-opacity duration-200"
style="opacity:0"></div>
<!-- ══════════════════════════════════════════════════════════
JAVASCRIPT
══════════════════════════════════════════════════════════ -->
<script>
// ── Seed SQL ──────────────────────────────────────────────────
const SEED = `
CREATE TABLE status(id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE user(id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT);
CREATE TABLE category(id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE task(
id INTEGER PRIMARY KEY, title TEXT NOT NULL, description TEXT,
user_id INTEGER REFERENCES user(id), status_id INTEGER REFERENCES status(id),
due_date TEXT, created_at TEXT
);
CREATE TABLE task_category(
task_id INTEGER REFERENCES task(id),
category_id INTEGER REFERENCES category(id),
PRIMARY KEY(task_id, category_id)
);
INSERT INTO status VALUES (1,'Open'),(2,'In Progress'),(3,'Done'),(4,'Blocked');
INSERT INTO user VALUES
(1,'Alice','alice@company.com'),(2,'Bob','bob@company.com'),
(3,'Charlie','charlie@company.com'),(4,'Diana','diana@company.com'),
(5,'Eve','eve@company.com'),(6,'Frank Larsen','frank@company.com');
INSERT INTO category VALUES
(1,'Development'),(2,'Design'),(3,'Documentation'),(4,'Testing'),(5,'Management');
INSERT INTO task VALUES
(1,'Fix login bug','Auth module crash',1,2,'2026-03-15','2026-03-01'),
(2,'Write test cases',NULL,2,1,'2026-03-18','2026-03-02'),
(3,'Update README','Docs need updating',3,1,'2026-03-20','2026-03-03'),
(4,'Implement search','Full text search',1,2,'2026-03-25','2026-03-04'),
(5,'Review PR',NULL,4,1,'2026-03-16','2026-03-05'),
(6,'Database migration','Schema changes',3,3,'2026-03-10','2026-03-06'),
(7,'UI redesign','New mockups',2,2,'2026-03-28','2026-03-07'),
(8,'Deploy to staging',NULL,3,4,'2026-03-20','2026-03-08'),
(9,'Performance testing','Load test with k6',5,1,'2026-04-10','2026-03-10'),
(10,'Mobile responsive fixes','iOS Safari issues',2,2,'2026-03-18','2026-03-01'),
(11,'Add dark mode',NULL,4,1,'2026-04-20','2026-03-12'),
(12,'Review pull requests',NULL,1,1,'2026-03-22','2026-03-14'),
(13,'Update dependencies','Security patches',3,1,'2026-03-30','2026-03-14'),
(14,'Write onboarding guide',NULL,2,1,'2026-04-05','2026-03-15');
INSERT INTO task_category(task_id,category_id) VALUES
(1,3),(2,4),(3,1),(4,1),(4,5),(5,1),(6,5),(7,1),(8,3),(9,5),(10,2),(11,2),(11,4),(12,1),(13,3);
`;
// ── Question definitions ───────────────────────────────────────
const PARTS = [
{
id: '1', title: 'Part 1 — Aggregates',
questions: [
{ id:'1-1', label:'Count the total number of tasks',
template:'-- Part 1, Q1\n-- Count the total number of tasks in the database.\n\n',
hint:'Use COUNT(*) or COUNT(id) on the task table.' },
{ id:'1-2', label:'Tasks per user (include users with 0 tasks)',
template:'-- Part 1, Q2\n-- Show each user\'s name and how many tasks they have.\n-- Make sure to include users with zero tasks.\n\n',
hint:'LEFT JOIN from user → task, then GROUP BY user.id, user.name.' },
{ id:'1-3', label:'Tasks per status (include all statuses)',
template:'-- Part 1, Q3\n-- Count tasks for each status.\n-- Include statuses that have 0 tasks.\n\n',
hint:'LEFT JOIN from status → task, GROUP BY status.id.' },
{ id:'1-4', label:'Rank users by task count (highest first)',
template:'-- Part 1, Q4\n-- List all users and their task counts, highest first.\n\n',
hint:'GROUP BY user, COUNT tasks, ORDER BY count DESC.' },
{ id:'1-5', label:'Users with more than 2 tasks',
template:'-- Part 1, Q5\n-- Show only users who have more than 2 tasks assigned to them.\n\n',
hint:'Use HAVING COUNT(...) > 2 after GROUP BY.' },
{ id:'1-6', label:'Most commonly used category',
template:'-- Part 1, Q6\n-- Which category has been assigned to the most tasks?\n\n',
hint:'JOIN task_category + category, GROUP BY category, ORDER BY count DESC LIMIT 1.' },
{ id:'1-7', label:'Tasks with no description',
template:'-- Part 1, Q7\n-- List all tasks that have no description set.\n\n',
hint:'WHERE description IS NULL.' },
{ id:'1-8', label:'Average tasks per active user',
template:'-- Part 1, Q8\n-- What is the average number of tasks per user?\n-- Only count users who have at least one task.\n\n',
hint:'Use a subquery or CTE to get per-user task counts, then AVG() over those counts.' },
]
},
{
id: '3', title: 'Part 3 — Transactions',
questions: [
{ id:'3-1', label:'Transfer tasks and delete user',
template:'-- Part 3, Q1\n-- Using a transaction:\n-- 1. Reassign all of Alice\'s tasks (user_id=1) to Bob (user_id=2)\n-- 2. Delete Alice from the user table\n-- Both steps must succeed or neither should apply.\n\n',
hint:'BEGIN; UPDATE task SET user_id=2 WHERE user_id=1; DELETE FROM user WHERE id=1; COMMIT;' },
{ id:'3-2', label:'Demonstrate a transaction rollback',
template:'-- Part 3, Q2\n-- Write a transaction that:\n-- 1. Tries to make two changes\n-- 2. One of them fails (e.g. constraint violation, duplicate PK)\n-- 3. Rolls back so neither change persists\n\n',
hint:'BEGIN; ... (first change) ... ; ... (failing operation) ... ; ROLLBACK; — or catch the error in application code.' },
]
},
{
id: '4', title: 'Part 4 — Subqueries',
questions: [
{ id:'4-1', label:'Users with above-average task count',
template:'-- Part 4, Q1\n-- List users who have more tasks than the average across all users.\n-- Use a subquery.\n\n',
hint:'HAVING COUNT(*) > (SELECT AVG(c) FROM (SELECT COUNT(*) AS c FROM task GROUP BY user_id))' },
{ id:'4-2', label:'Create "Urgent" and assign overdue tasks',
template:'-- Part 4, Q2\n-- Using a transaction:\n-- 1. Insert a new category called "Urgent"\n-- 2. Assign all tasks with a due_date before \'2026-03-26\' to this new category\n-- Use a subquery to get the new category\'s ID.\n\n',
hint:'INSERT INTO category(name) VALUES(\'Urgent\'); then INSERT INTO task_category SELECT id, last_insert_rowid() FROM task WHERE due_date < \'2026-03-26\'' },
]
}
];
const TOTAL = PARTS.reduce((s, p) => s + p.questions.length, 0);
// ── State ─────────────────────────────────────────────────────
let SQL, db, fileHandle;
let state = {};
let activeRow = null, activeId = null;
// ── Validators ───────────────────────────────────────────────
function pass(msg) { return { ok: true, msg }; }
function fail(msg) { return { ok: false, msg }; }
function tryExec(sql) {
try { return { res: db.exec(sql), err: null }; }
catch(e) { return { res: null, err: 'SQL error: ' + e.message }; }
}
function dbSnap() { return new SQL.Database(db.export()); }
const VALIDATORS = {
'1-1': sql => {
const r = tryExec(sql);
if (r.err) return fail(r.err);
if (!r.res.length || !r.res[0].values.length) return fail('No result returned — make sure you write a SELECT.');
const v = Number(r.res[0].values[0][0]);
return v === 14 ? pass('Correct! 14 tasks total.') : fail(`Expected 14, got ${v}.`);
},
'1-2': sql => {
const r = tryExec(sql);
if (r.err) return fail(r.err);
if (!r.res.length) return fail('No result returned.');
const rows = r.res[0].values;
if (rows.length !== 6) return fail(`Expected 6 rows (one per user), got ${rows.length}. Are you using LEFT JOIN?`);
const counts = rows.map(row => Number(row[1]));
if (!counts.includes(0)) return fail('Frank Larsen has 0 tasks — use LEFT JOIN so users with no tasks still appear.');
return pass('Correct! All 6 users shown, including Frank with 0 tasks.');
},
'1-3': sql => {
const r = tryExec(sql);
if (r.err) return fail(r.err);
if (!r.res.length) return fail('No result returned.');
const rows = r.res[0].values;
if (rows.length < 4) return fail(`Expected 4 rows (one per status), got ${rows.length}.`);
return pass('Correct! Task counts grouped by status.');
},
'1-4': sql => {
const r = tryExec(sql);
if (r.err) return fail(r.err);
if (!r.res.length) return fail('No result returned.');
const rows = r.res[0].values;
const counts = rows.map(row => Number(row[row.length - 1]));
if (counts[0] < counts[counts.length - 1]) return fail('Results should be ordered highest first (ORDER BY count DESC).');
if (!counts.some(c => c === 4)) return fail('Highest count should be 4 (Bob and Charlie each have 4 tasks).');
return pass('Correct! Users ranked by task count, highest first.');
},
'1-5': sql => {
const r = tryExec(sql);
if (r.err) return fail(r.err);
if (!r.res.length) return fail('No result returned.');
if (r.res[0].values.length !== 3) return fail(`Expected 3 users (Alice=3, Bob=4, Charlie=4), got ${r.res[0].values.length}.`);
return pass('Correct! Alice (3), Bob (4), and Charlie (4) all have more than 2 tasks.');
},
'1-6': sql => {
const r = tryExec(sql);
if (r.err) return fail(r.err);
if (!r.res.length) return fail('No result returned.');
const top = String(r.res[0].values[0][0]).toLowerCase();
return top.includes('development')
? pass('Correct! Development is the most common category (5 task assignments).')
: fail(`Expected "Development", got "${r.res[0].values[0][0]}".`);
},
'1-7': sql => {
const r = tryExec(sql);
if (r.err) return fail(r.err);
if (!r.res.length) return fail('No result returned.');
const n = r.res[0].values.length;
return n === 6 ? pass('Correct! 6 tasks have a NULL description.') : fail(`Expected 6, got ${n}.`);
},
'1-8': sql => {
const r = tryExec(sql);
if (r.err) return fail(r.err);
if (!r.res.length || !r.res[0].values.length) return fail('No result returned.');
const avg = parseFloat(r.res[0].values[0][0]);
return Math.abs(avg - 2.8) <= 0.05
? pass('Correct! 14 tasks ÷ 5 active users = 2.8 average.')
: fail(`Expected ≈ 2.8 (14 tasks / 5 users with tasks), got ${avg.toFixed(2)}.`);
},
'3-1': sql => {
const snap = dbSnap();
try {
snap.run(sql);
const u1 = snap.exec('SELECT id FROM user WHERE id=1');
if (u1.length && u1[0].values.length) { snap.close(); return fail('User 1 (Alice) should be deleted.'); }
const orphans = snap.exec('SELECT COUNT(*) FROM task WHERE user_id=1');
const n = Number(orphans[0].values[0][0]);
snap.close();
return n > 0
? fail(`${n} task(s) still assigned to user 1. Reassign them to user 2 first.`)
: pass("Correct! Alice's tasks moved to Bob, and Alice was deleted — all in one transaction.");
} catch(e) { snap.close(); return fail('Error: ' + e.message); }
},
'3-2': sql => {
const lower = sql.toLowerCase();
if (!lower.includes('begin')) return fail('Start with BEGIN to open a transaction.');
if (!lower.includes('rollback')) return fail('Your answer needs a ROLLBACK statement.');
const before = db.exec('SELECT COUNT(*) FROM task')[0].values[0][0];
try { db.run(sql); } catch(e) { /* expected error */ }
const after = db.exec('SELECT COUNT(*) FROM task')[0].values[0][0];
return before === after
? pass('Correct! The transaction rolled back cleanly — no changes persisted.')
: fail('Rollback did not work — the task count changed. Make sure ROLLBACK executes.');
},
'4-1': sql => {
const r = tryExec(sql);
if (r.err) return fail(r.err);
if (!r.res.length) return fail('No result returned.');
const n = r.res[0].values.length;
return n === 3
? pass('Correct! Bob (4), Charlie (4), and Alice (3) are all above the 2.8 average.')
: fail(`Expected 3 users above the average (2.8), got ${n}.`);
},
'4-2': sql => {
const snap = dbSnap();
try {
snap.run(sql);
const cat = snap.exec("SELECT id FROM category WHERE name='Urgent'");
if (!cat.length || !cat[0].values.length) { snap.close(); return fail('No "Urgent" category was created. Check your INSERT.'); }
const catId = cat[0].values[0][0];
const assigned = snap.exec(`SELECT COUNT(*) FROM task_category WHERE category_id=${catId}`);
const n = Number(assigned[0].values[0][0]);
snap.close();
return n >= 1
? pass(`Correct! "Urgent" created and ${n} overdue task(s) assigned to it.`)
: fail('"Urgent" category exists but no tasks were assigned. Check your subquery or WHERE clause.');
} catch(e) { snap.close(); return fail('Error: ' + e.message); }
},
};
// ── Render sidebar ────────────────────────────────────────────
function render() {
const container = document.getElementById('parts-container');
container.innerHTML = PARTS.map(part => `
<div class="border-b border-db-line">
<div class="flex items-center gap-2 px-3.5 py-2.5 cursor-pointer hover:bg-db-s2 select-none transition-colors"
onclick="togglePart(this)">
<span class="picon font-mono text-[10px] text-db-muted">▾</span>
<span class="text-[12px] font-medium text-db-hi flex-1">${part.title}</span>
<span id="pp${part.id}" class="part-prog font-mono text-[10px] text-db-muted">0/${part.questions.length}</span>
</div>
<div class="part-body" id="pb${part.id}">
${part.questions.map(q => `
<div class="q-row flex items-start gap-2.5 px-3.5 py-2.5 cursor-pointer hover:bg-db-s2 ${state[q.id] ? 'done-row' : ''}"
id="qr${q.id}" onclick="pick(this,'${q.id}',${JSON.stringify(q.template)})">
<div class="q-chk ${state[q.id] ? 'done' : ''}" id="c${q.id}" onclick="chk(event,'${q.id}')"></div>
<div class="flex-1 min-w-0">
<div class="font-mono text-[10px] text-db-muted">${q.id}</div>
<div class="text-[12px] text-db-text leading-snug mt-0.5">${q.label}</div>
${q.hint ? `
<button class="font-mono text-[10px] text-db-blue opacity-60 hover:opacity-100 mt-1 cursor-pointer bg-transparent border-none p-0"
onclick="toggleHint(event,this)">💡 hint</button>
<div class="hint-text font-mono text-[11px] text-db-blue mt-1.5 px-2 py-1.5 border-l-2 border-db-blue leading-snug"
style="background:rgba(96,165,250,.07)">${q.hint}</div>
` : ''}
</div>
</div>
`).join('')}
</div>
</div>
`).join('');
}
// ── DB functions ──────────────────────────────────────────────
async function init() {
SQL = await initSqlJs({ locateFile: f => `https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.10.2/${f}` });
render();
toast('Ready — click New DB to begin');
}
function newDatabase() {
if (db) db.close();
db = new SQL.Database();
db.run(SEED);
fileHandle = null;
setStatus(true, 'tasks.sqlite3');
refreshSchema();
showMsg('✓ Database seeded — 6 users · 14 tasks · 5 categories. Pick a question to start!', 'success');
toast('Schema ready');
}
async function openFile() {
if (!window.showOpenFilePicker) { toast('Requires Chrome or Edge'); return; }
try {
const [h] = await window.showOpenFilePicker({
types: [{ description: 'SQLite', accept: { 'application/x-sqlite3': ['.sqlite3', '.sqlite', '.db'] } }]
});
const f = await h.getFile();
const b = new Uint8Array(await f.arrayBuffer());
if (db) db.close();
db = new SQL.Database(b);
fileHandle = h;
setStatus(true, f.name);
refreshSchema();
showMsg(`✓ Opened ${f.name}`, 'success');
toast('File opened');
} catch(e) { if (e.name !== 'AbortError') toast('Error: ' + e.message); }
}
async function saveFile() {
if (!db) { toast('No database open'); return; }
if (!window.showSaveFilePicker) { toast('Requires Chrome or Edge'); return; }
try {
if (!fileHandle) {
fileHandle = await window.showSaveFilePicker({
suggestedName: 'tasks.sqlite3',
types: [{ description: 'SQLite', accept: { 'application/x-sqlite3': ['.sqlite3'] } }]
});
}
const w = await fileHandle.createWritable();
await w.write(db.export());
await w.close();
toast('Saved — ' + fileHandle.name);
} catch(e) { if (e.name !== 'AbortError') toast('Error: ' + e.message); }
}
function runQuery() {
if (!db) { showMsg('Create or open a database first.', ''); return; }
const sql = document.getElementById('sql-editor').value.trim();
if (!sql) return;
closeVal();
// Show last-run bar
const bar = document.getElementById('last-run-bar');
document.getElementById('last-run-text').textContent = sql.replace(/\s+/g, ' ').trim();
bar.style.display = 'flex';
try {
const res = db.exec(sql);
if (!res.length) {
const n = db.getRowsModified();
showMsg(`✓ OK — ${n} row${n !== 1 ? 's' : ''} affected`, 'success');
document.getElementById('row-count').textContent = '';
refreshSchema();
} else {
renderTable(res[res.length - 1]);
refreshSchema();
}
} catch(e) {
showMsg('Error: ' + e.message, 'error');
document.getElementById('row-count').textContent = '';
}
}
function renderTable({ columns, values }) {
const n = values.length;
document.getElementById('row-count').textContent = `${n} row${n !== 1 ? 's' : ''}`;
const thead = `<tr>${columns.map(c => `<th>${esc(c)}</th>`).join('')}</tr>`;
const tbody = values.length
? values.map(row => `<tr>${row.map(v => v === null
? '<td class="null-val">NULL</td>'
: `<td>${esc(String(v))}</td>`).join('')}</tr>`).join('')
: `<tr><td colspan="${columns.length}" style="text-align:center;padding:20px;color:#555">no rows</td></tr>`;
document.getElementById('results-area').innerHTML =
`<table class="results-table"><thead>${thead}</thead><tbody>${tbody}</tbody></table>`;
}
function esc(s) {
return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
function refreshSchema() {
if (!db) return;
const tree = document.getElementById('schema-tree');
const tables = db.exec("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name");
if (!tables.length) { tree.innerHTML = ''; return; }
tree.innerHTML = tables[0].values.map(([tbl]) => {
const cols = db.exec(`PRAGMA table_info("${tbl}")`);
const cnt = db.exec(`SELECT COUNT(*) FROM "${tbl}"`);
const n = cnt[0]?.values[0][0] ?? '?';
const colHtml = (cols[0]?.values ?? []).map(([,name,type,,, pk]) => `
<div class="flex gap-2 items-baseline font-mono py-0.5">
<span class="text-[11px] text-db-muted">${name}</span>
<span class="text-[10px] text-db-blue opacity-60">${type}</span>
${pk ? '<span class="text-[9px] text-db-accent">PK</span>' : ''}
</div>`).join('');
return `
<div class="mb-0.5">
<div class="flex items-center gap-1.5 px-3.5 py-1.5 cursor-pointer hover:bg-db-s2 transition-colors"
onclick="this.nextElementSibling.classList.toggle('hidden')">
<span class="text-db-accent font-mono text-[10px]">▸</span>
<span class="font-mono text-[12px] text-db-hi">${tbl}</span>
<span class="ml-auto font-mono text-[10px] text-db-muted">${n}</span>
</div>
<div class="hidden pl-7 pr-3.5 pb-1">${colHtml}</div>
</div>`;
}).join('');
}
function showMsg(text, type) {
const color = type === 'success' ? '#5affb8' : type === 'error' ? '#ff6b6b' : '#555';
document.getElementById('results-area').innerHTML =
`<div style="padding:40px 20px;text-align:center;font-family:'IBM Plex Mono',monospace;font-size:12px;color:${color}">${text}</div>`;
document.getElementById('row-count').textContent = '';
}
function setStatus(ok, name) {
document.getElementById('db-status').className =
`w-2 h-2 rounded-full flex-shrink-0 transition-colors duration-300 ${ok ? 'ok' : ''}`;
document.getElementById('db-name').textContent = name;
}
// ── Question UI ───────────────────────────────────────────────
function pick(row, id, sql) {
if (activeRow) activeRow.classList.remove('active');
row.classList.add('active');
activeRow = row;
activeId = id;
document.getElementById('sql-editor').value = sql;
document.getElementById('sql-editor').focus();
document.getElementById('check-btn').style.display = (id && VALIDATORS[id]) ? 'inline-block' : 'none';
closeVal();
}
function chk(e, id) {
e.stopPropagation();
if (!db) { toast('Open a database first'); return; }
if (VALIDATORS[id]) {
const sql = document.getElementById('sql-editor').value.trim();
const result = VALIDATORS[id](sql);
showVal(result);
if (result.ok) { state[id] = true; updateProgress(); }
} else {
state[id] = !state[id];
updateProgress();
}
}
function checkAnswer() {
if (!activeId) { toast('Select a question first'); return; }
if (!db) { toast('Open or create a database first'); return; }
const sql = document.getElementById('sql-editor').value.trim();
if (!sql) { showVal(fail('Write your SQL first, then check.')); return; }
const result = VALIDATORS[activeId]
? VALIDATORS[activeId](sql)
: { ok: true, msg: 'No automated check — mark it done manually.' };
showVal(result);
if (result.ok) { state[activeId] = true; updateProgress(); }
}
function showVal({ ok, msg }) {
const b = document.getElementById('val-banner');
b.className = ok ? 'pass' : 'fail';
b.style.display = 'flex';
b.className += ' flex items-start gap-3 px-4 py-2.5 font-mono text-xs leading-snug border-b border-db-line';
document.getElementById('val-icon').textContent = ok ? '✓' : '✗';
document.getElementById('val-msg').textContent = msg;
// Re-set class without conflicting display (handled by style)
b.className = `${ok ? 'pass' : 'fail'} flex items-start gap-3 px-4 py-2.5 font-mono text-xs leading-snug border-b border-db-line`;
}
function closeVal() {
const b = document.getElementById('val-banner');
b.style.display = 'none';
b.className = '';
}
function updateProgress() {
const done = Object.values(state).filter(Boolean).length;
PARTS.forEach(part => {
part.questions.forEach(q => {
const chkEl = document.getElementById('c' + q.id);
const rowEl = document.getElementById('qr' + q.id);
if (chkEl) chkEl.classList.toggle('done', !!state[q.id]);
if (rowEl) rowEl.classList.toggle('done-row', !!state[q.id]);
});
const partDone = part.questions.filter(q => state[q.id]).length;
const prog = document.getElementById('pp' + part.id);
if (prog) {
prog.textContent = `${partDone}/${part.questions.length}`;
prog.className = `part-prog font-mono text-[10px] ${partDone === part.questions.length ? 'full' : 'text-db-muted'}`;
}
});
const pill = document.getElementById('progress-pill');
pill.textContent = `${done} / ${TOTAL} done`;
pill.className = done === TOTAL
? 'font-mono text-[11px] px-2.5 py-0.5 rounded-full bg-db-s2 border border-db-green text-db-green transition-all duration-300'
: 'font-mono text-[11px] px-2.5 py-0.5 rounded-full bg-db-s2 border border-db-line text-db-muted transition-all duration-300';
document.getElementById('pbar').style.width = `${(done / TOTAL) * 100}%`;
document.getElementById('plabel').textContent = `${done} of ${TOTAL} completed`;
}
function togglePart(el) {
const body = el.nextElementSibling;
body.classList.toggle('collapsed');
el.querySelector('.picon').textContent = body.classList.contains('collapsed') ? '▸' : '▾';
}
function toggleHint(e, btn) {
e.stopPropagation();
const hint = btn.nextElementSibling;
hint.classList.toggle('show');
btn.textContent = hint.classList.contains('show') ? '▲ hide' : '💡 hint';
}
// ── Toast ─────────────────────────────────────────────────────
let toastTimer;
function toast(msg) {
const el = document.getElementById('toast');
el.textContent = msg;
el.style.opacity = '1';
clearTimeout(toastTimer);
toastTimer = setTimeout(() => { el.style.opacity = '0'; }, 2400);
}
// ── Keyboard shortcuts ────────────────────────────────────────
document.getElementById('sql-editor').addEventListener('keydown', e => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { e.preventDefault(); runQuery(); }
if (e.key === 'Tab') {
e.preventDefault();
const t = e.target, s = t.selectionStart;
t.value = t.value.slice(0, s) + ' ' + t.value.slice(t.selectionEnd);
t.selectionStart = t.selectionEnd = s + 2;
}
});
// ── Boot ──────────────────────────────────────────────────────
init().catch(console.error);
</script>
</body>
</html>