CAMPUS RESOURCE ORGANIZER · M1 / M2 / M3
Turn repairs and data structures into a usable tool
Build a standard-library Python CLI for fictional resource metadata: stable-ID CRUD, independent previews, category/tag filters and JSON saving that survives process restarts.
M3 SQLite and transactional import are available. The browser provides a teaching model; the real database runs in the local Python project. The tool does not scan, move or delete real resource files.
Start from a task snapshot or the M1 starter
Every task has an independent starting snapshot. All six share one data contract and business modules. The M1 starter contains explicitly listed bugs; it is not a finished submission.
python check_environment.py python -m unittest discover -s tests -v python cli.py --data ./my-data/resources.json
Python 3.11+, with no third-party dependencies. Windows can use py -3; POSIX commonly uses python3. See package notes for environments actually tested.
M1 save and exit rules
- Startup resolves the default JSON relative to the project; --data selects an explicit file. Only a missing file initializes an empty project. Empty, corrupt or unsupported-version files stop loading.
- Edits change memory and mark it unsaved. Preview and queries do not save. An explicit save writes data; quit with changes asks for save, discard or cancel.
- Saving uses a same-directory temporary file and replacement. On failure, memory remains unsaved and the old disk file is preserved. Fix the environment and retry, or save to another explicit path. This is not a complete power-loss durability guarantee.
list
add {"title":"Week 1","category":"CS","tags":["notes"]}
status
save
filter {"category":"CS"}
quitAdd returns a stable ID; update, remove and preview use IDs. Titles are deduplicated with strip().casefold(). See the bilingual README for complete commands and error examples.
Accept your own work
- Run all six public test groups and regression: invalid inputs leave no partial record; previews and filters preserve the source.
- Save in a temporary data directory and actually terminate the process. Restart from a different working directory with the same data file; verify IDs, titles and tags.
- Exercise corrupt JSON, empty files, unsupported versions and reproducible replacement failure. Preserve source files and use fictional data.
Independent change and delivery
Independently add tag filtering and a counterexample that catches destructive filtering. Explain the roles of Python, Git, your editor and AI, and keep one repair diff. Ask a peer to run your README in a new directory and record actual friction. Downloads do not establish installation or mastery.
M2 · STACK / QUEUE / INDEXES
M2: undo, FIFO batch checks and indexes
Extend the same M1 contract: successful edits save independent history snapshots and undo restores the latest successful edit. Batch checks produce reports without inserting data. ID and normalized-title indexes follow edits and undo, and are rebuilt from the main collection on load.
python -m unittest tests.test_d01 tests.test_d02 tests.test_d03 -v python -m unittest tests.test_m2_integration -v python -m unittest discover -s tests -v python cli.py --data ./my-data/resources.json
- History, queue attempts and check reports last only for this session. There is no redo or undo across restarts. Failed edits do not enter history; each undo restores the latest successful edit.
- Consume each enqueued attempt at most once. Continue after failure; explicit retries create new attempts. There are no threads or message brokers; the ring queue is a controlled experiment.
- Undo changes memory and marks it unsaved. Failed saves preserve data, history, indexes and dirty state while keeping the old disk file. Queue checks do not alter documents or clear dirty state.
List append has amortized cost; full undo also includes snapshots and index maintenance. Average dict lookup relies on assumptions and can degrade in the worst case. Count rebuilding and key normalization separately; a browser timing is not a complexity proof.
M3 · SQLITE / TRANSACTIONS / DELIVERY
M3: change storage, preserve the business contract
M3 is the database-and-delivery stage of the same Campus Organizer, not another application. Keep business rules, stable IDs, undo and indexes under the same contract while replacing local storage and adding one JSON import. Verify fictional data in a temporary directory before asking a peer to reproduce it.
- JsonStore/SQLiteStore.load/save must pass the same business contracts. Select --storage json|sqlite explicitly in the CLI. Report unavailable sqlite3 instead of silently falling back and claiming the database stage is complete.
- SQLite stores stable ID, original title, Python strip().casefold() title key, category and JSON-encoded tags. ID is the primary key and normalized title is UNIQUE. Persist list order in position and load with ORDER BY position; validate business fields before writing.
- JSON uses schemaVersion=1 and SQLite uses PRAGMA user_version=1. Loading a missing database creates no file. Reject existing blank files, unknown/incompatible versions and damaged databases. Initialize newly created storage only; no automatic upgrades are claimed.
- SQLiteStore.import_json(source_path) validates all records, IDs and normalized-title uniqueness first. CLI import-json PATH requires SQLite and no unsaved changes. Require a new path or a recognized empty database, use one batch transaction, roll back failures and preserve source JSON.
- Reject repeated import into a populated database instead of implicitly replacing or merging data. Valid empty input imports zero rows but can still initialize a database and commit a transaction. Update memory, history, indexes and dirty state only under the actual save-success contract.
- Real verification uses temporary database files, a second process, another working directory and reproducible failure injection. The page does not execute SQL, local code or database files, nor remotely verify student tests.
python check_environment.py python -m unittest tests.test_storage_contract tests.test_sqlite_storage tests.test_sqlite_import -v python -m unittest discover -s tests -v python cli.py --storage sqlite --data ./my-data/resources.sqlite3
- Run the M2 JSON regression first. Record Python, operating system and sqlite3.sqlite_version. If import sqlite3 fails, repair the environment and retain diagnostics rather than substituting another store.
- Implement the SQLite store, explicitly open its file, check the version and create constrained tables. Follow the package help for --storage json|sqlite and data-path arguments. Queries and previews do not save automatically.
- Bind parameters and serialize tags as JSON. Load/save under the shared business contract. Control transactions explicitly, commit on success, roll back on failure while retaining memory and dirty state, then close the connection.
- Read the source JSON without modifying it. Validate the entire batch, require an empty target and import in one transaction. Keep the actual success report: count/source/target/schemaVersion/result. count is the batch published after commit. Retain error output on failure; leave the report template at not_run or add failure notes without inventing success.
- Run identical behavior tests against both stores. Inject a second-insert or commit failure and compare original database and source contents. Test duplicate IDs, normalized duplicates, bad fields, incompatible versions, empty input and repeated import.
- Reproduce save/recovery from a new directory and second process. Deliver source, fictional samples, bilingual README, real test results, repair diff, independent change, your/AI contribution notes and a peer’s README reproduction feedback.
status import-json ./data/sample.json list save quit
import-json is available only with SQLite and no unsaved session edits. It writes in one transaction; success refreshes memory/indexes and clears session history/queue. This differs from everyday edits that change memory and require an explicit save.
SQLite and SQL bridge
Connection and environment: sqlite3 is an optional Python standard-library module connecting to a local file, not a MySQL server. Record the actual SQLite runtime version and close the connection explicitly.
import sqlite3
print(sqlite3.sqlite_version)
connection = sqlite3.connect(database_path, isolation_level=None)
try:
pass
finally:
connection.close()Tables and constraints: use explicit NOT NULL, a stable-ID primary key and a UNIQUE normalized title. Encode/decode tags in TEXT with Python json.dumps/json.loads; no SQLite JSON extension is required. Database uniqueness does not replace Python type/business validation.
CREATE TABLE documents (
position INTEGER NOT NULL UNIQUE CHECK(position >= 0),
id TEXT NOT NULL PRIMARY KEY,
title TEXT NOT NULL,
normalized_title TEXT NOT NULL UNIQUE,
category TEXT NOT NULL,
tags_json TEXT NOT NULL
);Parameter binding: pass values through ? placeholders instead of concatenating titles into SQL. Compute normalized_title in Python with title.strip().casefold(). SQLite NOCASE/LOWER must not be assumed equivalent to that Unicode rule.
import json
connection.execute(
"INSERT INTO documents (position, id, title, normalized_title, category, tags_json) "
"VALUES (?, ?, ?, ?, ?, ?)",
(position, record["id"], record["title"], record["title"].strip().casefold(),
record["category"], json.dumps(record["tags"], ensure_ascii=False)),
)Explicit transactions: this illustration uses isolation_level=None and explicit BEGIN IMMEDIATE. Commit after all inserts and roll back exceptions. BEGIN itself may fail, for example when busy. Real code must inspect state, report errors and close the connection rather than treat database errors as an empty store.
connection.execute("BEGIN IMMEDIATE")
try:
for record in validated_records:
insert_one(connection, record)
connection.commit()
except Exception:
if connection.in_transaction:
connection.rollback()
raiseVersioning: the first application schema is 1. PRAGMA user_version is an application-managed integer, not an automatic table migration. This project also recognizes application_id=0x5A4D4333, its exact table constraints and default DELETE journal format; matching the version alone is insufficient. Set 1 only when initializing a newly created database; reject existing blank files and unsupported versions. These statements illustrate reading and fixed assignment, not an upgrade implementation.
version = connection.execute("PRAGMA user_version").fetchone()[0]
marker = connection.execute("PRAGMA application_id").fetchone()[0]
# Only during validated new-database initialization:
connection.execute("PRAGMA user_version = 1")
connection.execute("PRAGMA application_id = 0x5A4D4333")MySQL bridge: reuse INSERT, CREATE TABLE, constraint and transaction concepts while separating environment and dialect. SQLite uses files and PRAGMA; do not copy MySQL USE, AUTO_INCREMENT or server connection setup. Python sqlite3 ? placeholders are not universal across MySQL drivers.
-- SQLite application schema marker, not MySQL syntax: PRAGMA user_version; -- Shared SQL concept; driver placeholders are API-specific: SELECT id, title FROM documents WHERE id = ?;
- MySQL lesson 10: INSERT
Review insertion concepts; use Python parameter binding for SQLite operations.
- MySQL lesson 13: creating and dropping tables
Review tables and constraints while distinguishing SQLite syntax and the project schema-version policy.
- F05: persistence and error protection
Keep explicit paths, failure state and second-process verification.
- D03: indexes and title uniqueness
Changing storage does not change Python title normalization or stable IDs.
Official references: Python 3.11 sqlite3 documentation · SQLite transaction documentation · SQLite PRAGMA user_version
M3 independent change and delivery
Independent change: implement challenges.category_counts(documents), returning a dictionary from exact category strings to counts without changing the list, records or tags. Reject invalid documents with ValueError under the existing contract. Neither trim nor casefold categories: Course, course and Course with a trailing space are distinct. Test empty input, repeated categories, case differences and input preservation. Explain keys and values; no implementation steps are supplied.
python -m unittest tests.test_m3_variant -v
With per-row commits, earlier rows become permanent before a later failure; rolling back the current row cannot undo earlier commits. A batch transaction places the success/failure boundary around the import: all rows become visible or the original database remains. Full validation catches expected bad input, but database and commit failures still require transactional handling. The page compares controlled states; evidence comes from your own code, tests and reproduction.
- This is a local single-process interactive project, without a Web API, accounts, cloud sync, uploads or hosted database administration. SQLite connections and transactions can fail; a file’s existence does not prove a successful save.
- Implement version 1 and explicit incompatible-version rejection only; no automatic upgrades are claimed. JSON tags retain the current list contract rather than introducing a multi-table tag system.
- Do not list systems or Python versions as tested unless actually run. The page does not verify sqlite3 availability, file locks, disks, power-loss recovery or student work.
- The model uses Python-generated normalization values, not arbitrary Unicode casefold. Valid empty source imports zero rows, but can still initialize a database and commit a transaction. Reject any populated target, including repeated import; do not imply automatic merging or idempotent replay.
Project delivery records (self-reported)
Stored only in this browser. No uploads or certificates. M1, M2 and M3 are separate; task edits invalidate the relevant delivery checks.
M3 reference implementation (answer)
The M3 reference includes the full project and SQLite answers. It records reference use for all nine units and M3 itself; passing reference tests does not establish that student work passes.
Download M3 reference · Version and source digestM2 reference implementation (answer)
The M2 reference implements all nine units; downloading records reference use for all nine. The M1 reference still marks only the six fundamentals tasks.
Download M2 reference · Version and digestM1 reference implementation (answer)
The reference contains answers to all six tasks; downloading it records reference use for all six. Its tests validate materials, not your work or peer reproduction.
Download M1 reference · Version and digest