Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
},
"updateContentCommand": "[ -f packages.txt ] && sudo apt update && sudo apt upgrade -y && sudo xargs apt install -y <packages.txt; [ -f requirements.txt ] && pip3 install --user -r requirements.txt; pip3 install --user streamlit; echo '✅ Packages installed and Requirements met'",
"postAttachCommand": {
"server": "streamlit run app.py --server.enableCORS false --server.enableXsrfProtection false"
"server": "streamlit run app.py"
},
"portsAttributes": {
"8501": {
Expand Down
27 changes: 27 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: CI

on:
push:
branches: [main]
pull_request:

permissions:
contents: read

jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12", "3.13"]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
cache: pip
cache-dependency-path: requirements*.txt
- run: pip install -r requirements-dev.txt
- run: ruff check .
- run: pytest -v
5 changes: 3 additions & 2 deletions .streamlit/config.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
[server]
headless = true
enableCORS = false
enableXsrfProtection = false

[browser]
gatherUsageStats = false

[theme]
primaryColor = "#4dabf7"
Expand Down
1 change: 0 additions & 1 deletion Procfile

This file was deleted.

90 changes: 90 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# SQL Bomb Defusal Challenge

[![CI](https://github.com/Praso28/SQLBomb/actions/workflows/ci.yml/badge.svg)](https://github.com/Praso28/SQLBomb/actions/workflows/ci.yml)

A story-driven SQL puzzle game built with Streamlit. You play an analyst who has to write
SQL queries against a small investigation database to find the real bomb among decoys,
recover its defusal code and identify who planted it.

It is meant as a hands-on way to practise `SELECT`, filtering, `JOIN`s and CTEs.

**Play it live: https://sqlbomb.streamlit.app/**

## How it plays

| Stage | Goal | SQL you will likely need |
| --- | --- | --- |
| 1. Identify the real bomb | Pick the real device out of eight candidates | `WHERE`, `LIKE`, comparisons |
| 2. Defuse it | Find the activation code on the right component | `JOIN` between `bombs` and `bomb_components` |
| 3. Find the culprit | Trace who installed the device | Multi-table `JOIN` across `access_logs`, `suspects`, `bombs` |

Each stage has a story briefing, hints, example queries and a schema reference. When your
query returns the evidence for a stage, you are asked to confirm what you found before
moving on.

## Run it locally

Requires Python 3.10 or newer.

```bash
git clone https://github.com/Praso28/SQLBomb.git
cd SQLBomb
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
streamlit run app.py
```

Then open http://localhost:8501.

Want to explore the data outside the game? `python init_database.py` writes the same data to
`database/tictictomb.db`, which you can open with any SQLite client.

## How queries are sandboxed

Players type arbitrary SQL, so the query engine (`backend/db.py`) is locked down:

- Every query runs against a **fresh in-memory SQLite database** seeded from
`database/schema.sql` and `database/sample_data.sql`. Nothing a player does can affect
another query or another player.
- A SQLite **authorizer** permits reads only. Writes, `ATTACH`, `PRAGMA` and schema changes
are denied by the engine itself, not just by string matching.
- Only **one statement** per query is executed.
- A **2 second time limit** stops runaway queries such as unbounded recursive CTEs.
- Results are capped at **500 rows**.

`backend/game_logic.py` adds friendlier pre-checks so players get a clear message
(for example "Only SELECT queries are allowed") rather than a raw SQLite error.

## Project layout

```
app.py Streamlit entry point
frontend/streamlit_app.py UI, story and stage flow
backend/db.py Sandboxed query execution
backend/game_logic.py Query validation and game-state updates
backend/utils.py Stage completion rules
database/ Schema and seed data
tests/ Unit tests and an end-to-end UI playthrough
```

## Development

```bash
pip install -r requirements-dev.txt
ruff check .
pytest
```

The test suite covers the sandbox (blocked writes, timeouts, row cap), query validation,
the completion rule for every stage, and a full playthrough of the UI using Streamlit's
`AppTest` harness. CI runs lint and tests on Python 3.10 to 3.13 for every push and pull request.

## Deploy

The live app is hosted on [Streamlit Community Cloud](https://streamlit.io/cloud) and
redeploys from `main`. To host your own copy, create an app from this repository with
`app.py` as the main file and Python 3.10 or newer. No secrets or database server are needed.

## Tech

Python, Streamlit, SQLite, pytest, Ruff, GitHub Actions.
91 changes: 0 additions & 91 deletions Readme.md

This file was deleted.

1 change: 1 addition & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from frontend.streamlit_app import main_app


def main():
main_app()

Expand Down
134 changes: 86 additions & 48 deletions backend/db.py
Original file line number Diff line number Diff line change
@@ -1,50 +1,88 @@
"""Sandboxed SQL execution for the game.

Every query runs against a fresh in-memory SQLite database built from
``database/schema.sql`` and ``database/sample_data.sql``. Nothing a player
types can change shared state, and the connection is further locked down:

* an authorizer allows reads only (no writes, ATTACH, PRAGMA, etc.),
* a progress handler aborts queries that run longer than ``QUERY_TIMEOUT_SECONDS``,
* at most ``MAX_ROWS`` rows are returned.
"""

from __future__ import annotations

import functools
import sqlite3
import os

# Database file path
DB_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'database', 'tictictomb.db')

# Check if database exists, if not initialize it
if not os.path.exists(DB_PATH):
from init_database import init_database
init_database()

def execute_query(query):
"""Execute a query and return results with column names"""
# Create a new connection for each query to avoid threading issues
with sqlite3.connect(DB_PATH) as conn:
cur = conn.cursor()
try:
cur.execute(query)
conn.commit() # Commit any changes
try:
# Get column names from cursor description
columns = [desc[0] for desc in cur.description] if cur.description else []

# Fetch all rows
rows = cur.fetchall()

# If we have results and column names, convert to a list of dictionaries
if rows and columns:
# Create a list of dictionaries with column names as keys
results = []
for row in rows:
result_dict = {}
for i, col in enumerate(columns):
if i < len(row):
result_dict[col] = row[i]
results.append(result_dict)
return results
elif rows:
# If we have rows but no column names, return the raw rows
return rows
else:
# No results
return []
except sqlite3.Error as e:
print(f"Fetch error: {e}")
# If no results to fetch (e.g., for INSERT/UPDATE)
return []
except Exception as e:
print(f"Query error: {e}")
import time
from pathlib import Path

DATABASE_DIR = Path(__file__).resolve().parent.parent / "database"
SCHEMA_FILE = DATABASE_DIR / "schema.sql"
DATA_FILE = DATABASE_DIR / "sample_data.sql"

QUERY_TIMEOUT_SECONDS = 2.0
MAX_ROWS = 500
# Number of SQLite VM instructions between progress-handler checks.
_PROGRESS_INTERVAL = 10_000

_ALLOWED_ACTIONS = {
sqlite3.SQLITE_SELECT,
sqlite3.SQLITE_READ,
sqlite3.SQLITE_FUNCTION,
getattr(sqlite3, "SQLITE_RECURSIVE", 33),
}


class QueryError(Exception):
"""A player-facing error raised when a query cannot be run."""


@functools.lru_cache(maxsize=1)
def _seed_script() -> str:
return SCHEMA_FILE.read_text(encoding="utf-8") + "\n" + DATA_FILE.read_text(encoding="utf-8")


def _authorizer(action, arg1, arg2, db_name, trigger): # noqa: ARG001 - sqlite3 callback signature
if action in _ALLOWED_ACTIONS:
return sqlite3.SQLITE_OK
return sqlite3.SQLITE_DENY


def _new_connection() -> sqlite3.Connection:
conn = sqlite3.connect(":memory:")
conn.executescript(_seed_script())
conn.set_authorizer(_authorizer)
return conn


def execute_query(query: str) -> list[dict]:
"""Run a read-only query and return its rows as a list of dicts.

Raises ``QueryError`` with a readable message on any failure.
"""
conn = _new_connection()
deadline = time.monotonic() + QUERY_TIMEOUT_SECONDS
conn.set_progress_handler(lambda: 1 if time.monotonic() > deadline else 0, _PROGRESS_INTERVAL)
try:
cur = conn.execute(query)
if cur.description is None:
return []
columns = [desc[0] for desc in cur.description]
rows = cur.fetchmany(MAX_ROWS)
return [dict(zip(columns, row, strict=True)) for row in rows]
except sqlite3.OperationalError as exc:
if "interrupted" in str(exc):
raise QueryError(
f"Query took longer than {QUERY_TIMEOUT_SECONDS:g} seconds and was stopped."
) from exc
if "not authorized" in str(exc):
raise QueryError("That operation is not allowed. Only read-only SELECT queries are permitted.") from exc
raise QueryError(str(exc)) from exc
except (sqlite3.ProgrammingError, sqlite3.Warning) as exc:
# "You can only execute one statement at a time." is a ProgrammingError on
# Python 3.11+ but a sqlite3.Warning (not an sqlite3.Error) on 3.10.
raise QueryError(str(exc)) from exc
except sqlite3.Error as exc:
raise QueryError(str(exc)) from exc
finally:
conn.close()
Loading
Loading