commit
Update to JPML
diff --git a/columbina/config.py b/columbina/config.py
index 706a52f..1d1de54 100644
--- a/columbina/config.py
+++ b/columbina/config.py
@@ -53,7 +53,7 @@ def resolveDir(raw: str | None, fallback: Path) -> Path:
databaseDir = resolveDir(os.getenv("DATABASE_DIR"), repoRoot / "data")
-databasePath = databaseDir / "columbina.db"
+databasePath = databaseDir / "columbina.jp"
prefixNames: list[str] = sorted(("damselette", "columbina", "bina"), key=len, reverse=True)
diff --git a/columbina/database.py b/columbina/database.py
index 79a1b5a..04c41c1 100644
--- a/columbina/database.py
+++ b/columbina/database.py
@@ -1,8 +1,20 @@
-"""SQLite storage for moderation cases and honeypot channels.
+"""``.jp`` storage for moderation cases and honeypot channels.
-One connection, opened at start-up and closed on shutdown. ``sqlite3`` is
-blocking, so every query runs in a worker thread behind a lock — the event loop
-never stalls on disk, and writes never interleave.
+The whole store is one :mod:`jpml` document, held in memory and written back
+after every change. Top-level sections are guild IDs, which is the shape ``.jp``
+was built for::
+
+ [1234567890]
+ settings: {
+ log_channel: "999"
+ }
+ honeypots: [...]
+ cases: [...]
+
+Writing is blocking, so every save runs in a worker thread behind a lock — the
+event loop never stalls on disk, and two commands can't interleave a
+read-modify-write. :func:`jpml.dump` writes through a temp file and ``fsync``,
+so a crash leaves either the old file or the new one, never half of one.
Each punishment gets a short random hash as its public case ID: ``a3f9c1d204``
is something a mod can quote in a channel or search for later, where a row
@@ -10,45 +22,22 @@ number would leak how many cases exist.
"""
import asyncio
+import copy
import hashlib
import secrets
-import sqlite3
-from collections.abc import Callable
from dataclasses import dataclass
from datetime import UTC, datetime
from pathlib import Path
+from typing import Any
+
+import jpml
-SCHEMA_VERSION = 2
+SCHEMA_VERSION = 3
HASH_LENGTH = 10
-SCHEMA = """
-CREATE TABLE IF NOT EXISTS cases (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- hash TEXT NOT NULL UNIQUE,
- guild_id INTEGER NOT NULL,
- user_id INTEGER NOT NULL,
- moderator_id INTEGER NOT NULL,
- action TEXT NOT NULL,
- reason TEXT,
- created_at TEXT NOT NULL
-);
-CREATE INDEX IF NOT EXISTS cases_by_user ON cases (guild_id, user_id, action);
-
-CREATE TABLE IF NOT EXISTS settings (
- guild_id INTEGER NOT NULL,
- key TEXT NOT NULL,
- value TEXT,
- PRIMARY KEY (guild_id, key)
-);
-
-CREATE TABLE IF NOT EXISTS honeypots (
- guild_id INTEGER NOT NULL,
- channel_id INTEGER NOT NULL,
- added_by INTEGER NOT NULL,
- added_at TEXT NOT NULL,
- PRIMARY KEY (guild_id, channel_id)
-);
-"""
+# Guild IDs are digits, so a word can never collide with one — the meta section
+# is safe to keep in the same document.
+META_SECTION = "columbina"
# Every punishment kind she records. The value is the past-tense word used in
# replies, so adding a new action here is the only edit a new command needs.
@@ -77,51 +66,83 @@ class Case:
createdAt: datetime
@classmethod
- def fromRow(cls, row: sqlite3.Row) -> "Case":
+ def fromEntry(cls, guildId: int, entry: dict[str, Any]) -> "Case":
return cls(
- hash=row["hash"],
- guildId=row["guild_id"],
- userId=row["user_id"],
- moderatorId=row["moderator_id"],
- action=row["action"],
- reason=row["reason"],
- createdAt=datetime.fromisoformat(row["created_at"]),
+ hash=entry["hash"],
+ guildId=guildId,
+ userId=entry["user_id"],
+ moderatorId=entry["moderator_id"],
+ action=entry["action"],
+ reason=entry["reason"],
+ createdAt=datetime.fromisoformat(entry["created_at"]),
)
+ def toEntry(self) -> dict[str, Any]:
+ """The stored form — no guild ID, since the section it sits in is one."""
+ return {
+ "hash": self.hash,
+ "user_id": self.userId,
+ "moderator_id": self.moderatorId,
+ "action": self.action,
+ "reason": self.reason,
+ "created_at": self.createdAt.isoformat(),
+ }
+
class Database:
- def __init__(self, path: Path, connection: sqlite3.Connection) -> None:
+ def __init__(self, path: Path, document: dict[str, Any]) -> None:
self.path = path
- self._connection = connection
+ self._document = document
self._lock = asyncio.Lock()
+ # Case hashes are never reused or deleted, so an index built once at
+ # load stays true with nothing but an insert to keep it current. It
+ # makes case() a lookup instead of a walk over every guild.
+ self._byHash: dict[str, Case] = {
+ case.hash: case
+ for guildId, section in self._guilds()
+ for case in (
+ Case.fromEntry(guildId, entry) for entry in section.get("cases", ())
+ )
+ }
@classmethod
async def connect(cls, path: Path) -> "Database":
- """Open (creating if needed) the database at ``path``."""
-
- def open() -> sqlite3.Connection:
- path.parent.mkdir(parents=True, exist_ok=True)
- # isolation_level=None: autocommit, so each statement lands as soon
- # as it runs and a crash can't swallow a ban we already announced.
- connection = sqlite3.connect(
- path, check_same_thread=False, isolation_level=None
- )
- connection.row_factory = sqlite3.Row
- connection.execute("PRAGMA journal_mode = WAL")
- connection.executescript(SCHEMA)
- connection.execute(f"PRAGMA user_version = {SCHEMA_VERSION}")
- return connection
+ """Open (creating if needed) the store at ``path``."""
+
+ def open() -> dict[str, Any]:
+ document: dict[str, Any] = jpml.load(path) if path.exists() else {}
+ document.setdefault(META_SECTION, {})["version"] = SCHEMA_VERSION
+ # Write straight back, so a fresh install has a real file on disk
+ # rather than one that appears at the first ban.
+ jpml.dump(document, path)
+ return document
return cls(path, await asyncio.to_thread(open))
async def close(self) -> None:
+ """Flush once more on the way out."""
async with self._lock:
- await asyncio.to_thread(self._connection.close)
-
- async def run[T](self, work: Callable[[sqlite3.Connection], T]) -> T:
- """Run ``work`` against the connection in a worker thread."""
- async with self._lock:
- return await asyncio.to_thread(work, self._connection)
+ await self._save()
+
+ def _guilds(self):
+ """Every guild section, meta skipped."""
+ for name, section in self._document.items():
+ if name != META_SECTION:
+ yield int(name), section
+
+ def _section(self, guildId: int, *, create: bool = False) -> dict[str, Any]:
+ """One guild's section — empty and unattached unless ``create``."""
+ key = str(guildId)
+ if create:
+ return self._document.setdefault(key, {})
+ return self._document.get(key, {})
+
+ async def _save(self) -> None:
+ """Persist the document. Caller holds the lock."""
+ # A snapshot, because jpml walks the document in the worker thread and
+ # the event loop is free to mutate the real one while it does.
+ snapshot = copy.deepcopy(self._document)
+ await asyncio.to_thread(jpml.dump, snapshot, self.path)
async def addCase(
self,
@@ -133,150 +154,118 @@ class Database:
reason: str | None,
) -> Case:
"""Record a punishment and hand back the stored case."""
- created = datetime.now(UTC)
-
- def insert(connection: sqlite3.Connection) -> str:
- # A 10-hex-char collision is vanishingly unlikely, but the UNIQUE
- # index is the thing that decides, so just take the next one.
+ async with self._lock:
+ # A 10-hex-char collision is vanishingly unlikely, but the index is
+ # the thing that decides, so just take the next one.
for _ in range(5):
candidate = makeHash()
- try:
- connection.execute(
- "INSERT INTO cases"
- " (hash, guild_id, user_id, moderator_id, action, reason,"
- " created_at)"
- " VALUES (?, ?, ?, ?, ?, ?, ?)",
- (
- candidate,
- guildId,
- userId,
- moderatorId,
- action,
- reason,
- created.isoformat(),
- ),
- )
- except sqlite3.IntegrityError:
- continue
- return candidate
- raise RuntimeError("could not find a free case hash")
-
- return Case(
- hash=await self.run(insert),
- guildId=guildId,
- userId=userId,
- moderatorId=moderatorId,
- action=action,
- reason=reason,
- createdAt=created,
- )
+ if candidate not in self._byHash:
+ break
+ else:
+ raise RuntimeError("could not find a free case hash")
+
+ case = Case(
+ hash=candidate,
+ guildId=guildId,
+ userId=userId,
+ moderatorId=moderatorId,
+ action=action,
+ reason=reason,
+ createdAt=datetime.now(UTC),
+ )
+ self._section(guildId, create=True).setdefault("cases", []).append(
+ case.toEntry()
+ )
+ self._byHash[case.hash] = case
+ await self._save()
+ return case
async def case(self, hash: str) -> Case | None:
- def select(connection: sqlite3.Connection) -> sqlite3.Row | None:
- return connection.execute(
- "SELECT * FROM cases WHERE hash = ?", (hash,)
- ).fetchone()
-
- row = await self.run(select)
- return Case.fromRow(row) if row is not None else None
+ return self._byHash.get(hash)
async def casesFor(
self, guildId: int, userId: int, *, action: str | None = None, limit: int = 25
) -> list[Case]:
"""This user's cases, newest first."""
-
- def select(connection: sqlite3.Connection) -> list[sqlite3.Row]:
- sql = "SELECT * FROM cases WHERE guild_id = ? AND user_id = ?"
- params: list[object] = [guildId, userId]
- if action is not None:
- sql += " AND action = ?"
- params.append(action)
- sql += " ORDER BY id DESC LIMIT ?"
- params.append(limit)
- return connection.execute(sql, params).fetchall()
-
- return [Case.fromRow(row) for row in await self.run(select)]
+ entries = self._section(guildId).get("cases", ())
+ found: list[Case] = []
+ # Reversed, because cases are appended in the order they happened.
+ for entry in reversed(entries):
+ if entry["user_id"] != userId:
+ continue
+ if action is not None and entry["action"] != action:
+ continue
+ found.append(Case.fromEntry(guildId, entry))
+ if len(found) >= limit:
+ break
+ return found
async def countCases(self, guildId: int, userId: int, action: str) -> int:
- def count(connection: sqlite3.Connection) -> int:
- row = connection.execute(
- "SELECT COUNT(*) FROM cases"
- " WHERE guild_id = ? AND user_id = ? AND action = ?",
- (guildId, userId, action),
- ).fetchone()
- return int(row[0])
-
- return await self.run(count)
+ return sum(
+ 1
+ for entry in self._section(guildId).get("cases", ())
+ if entry["user_id"] == userId and entry["action"] == action
+ )
async def setting(self, guildId: int, key: str) -> str | None:
- def select(connection: sqlite3.Connection) -> sqlite3.Row | None:
- return connection.execute(
- "SELECT value FROM settings WHERE guild_id = ? AND key = ?",
- (guildId, key),
- ).fetchone()
-
- row = await self.run(select)
- return row["value"] if row is not None else None
+ return self._section(guildId).get("settings", {}).get(key)
async def setSetting(self, guildId: int, key: str, value: str) -> None:
- def upsert(connection: sqlite3.Connection) -> None:
- connection.execute(
- "INSERT INTO settings (guild_id, key, value) VALUES (?, ?, ?)"
- " ON CONFLICT (guild_id, key) DO UPDATE SET value = excluded.value",
- (guildId, key, value),
- )
-
- await self.run(upsert)
+ async with self._lock:
+ self._section(guildId, create=True).setdefault("settings", {})[key] = value
+ await self._save()
async def clearSetting(self, guildId: int, key: str) -> bool:
"""``False`` if there was nothing set."""
-
- def delete(connection: sqlite3.Connection) -> bool:
- cursor = connection.execute(
- "DELETE FROM settings WHERE guild_id = ? AND key = ?", (guildId, key)
- )
- return cursor.rowcount > 0
-
- return await self.run(delete)
+ async with self._lock:
+ settings = self._section(guildId).get("settings", {})
+ if key not in settings:
+ return False
+ del settings[key]
+ await self._save()
+ return True
+
+ def _honeypot(self, guildId: int, channelId: int) -> dict[str, Any] | None:
+ for entry in self._section(guildId).get("honeypots", ()):
+ if entry["channel_id"] == channelId:
+ return entry
+ return None
async def addHoneypot(self, guildId: int, channelId: int, addedBy: int) -> bool:
"""Mark a channel as a trap. ``False`` if it already was one."""
-
- def insert(connection: sqlite3.Connection) -> bool:
- cursor = connection.execute(
- "INSERT OR IGNORE INTO honeypots"
- " (guild_id, channel_id, added_by, added_at) VALUES (?, ?, ?, ?)",
- (guildId, channelId, addedBy, datetime.now(UTC).isoformat()),
+ async with self._lock:
+ if self._honeypot(guildId, channelId) is not None:
+ return False
+ self._section(guildId, create=True).setdefault("honeypots", []).append(
+ {
+ "channel_id": channelId,
+ "added_by": addedBy,
+ "added_at": datetime.now(UTC).isoformat(),
+ }
)
- return cursor.rowcount > 0
-
- return await self.run(insert)
+ await self._save()
+ return True
async def removeHoneypot(self, guildId: int, channelId: int) -> bool:
"""Stop trapping a channel. ``False`` if it wasn't one."""
-
- def delete(connection: sqlite3.Connection) -> bool:
- cursor = connection.execute(
- "DELETE FROM honeypots WHERE guild_id = ? AND channel_id = ?",
- (guildId, channelId),
- )
- return cursor.rowcount > 0
-
- return await self.run(delete)
+ async with self._lock:
+ entry = self._honeypot(guildId, channelId)
+ if entry is None:
+ return False
+ self._section(guildId)["honeypots"].remove(entry)
+ await self._save()
+ return True
async def honeypots(self, guildId: int) -> list[int]:
- def select(connection: sqlite3.Connection) -> list[sqlite3.Row]:
- return connection.execute(
- "SELECT channel_id FROM honeypots WHERE guild_id = ? ORDER BY added_at",
- (guildId,),
- ).fetchall()
-
- return [row["channel_id"] for row in await self.run(select)]
+ # Appended as they were added, so file order is already added_at order.
+ return [
+ entry["channel_id"] for entry in self._section(guildId).get("honeypots", ())
+ ]
async def allHoneypots(self) -> set[int]:
"""Every trapped channel, for the listener's in-memory cache."""
-
- def select(connection: sqlite3.Connection) -> list[sqlite3.Row]:
- return connection.execute("SELECT channel_id FROM honeypots").fetchall()
-
- return {row["channel_id"] for row in await self.run(select)}
+ return {
+ entry["channel_id"]
+ for _, section in self._guilds()
+ for entry in section.get("honeypots", ())
+ }
diff --git a/pyproject.toml b/pyproject.toml
index e4c95bf..78c4d16 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,6 +10,7 @@ requires-python = ">=3.14"
dependencies = [
"colorful>=0.5.8",
"discord-py>=2.7.1",
+ "jpml>=1.1.1",
"python-dotenvx>=2.0.0",
"ruff>=0.16.7",
"toml>=0.10.2",
diff --git a/uv.lock b/uv.lock
index a335c23..6ad1749 100644
--- a/uv.lock
+++ b/uv.lock
@@ -158,6 +158,7 @@ source = { virtual = "." }
dependencies = [
{ name = "colorful" },
{ name = "discord-py" },
+ { name = "jpml" },
{ name = "python-dotenvx" },
{ name = "ruff" },
{ name = "toml" },
@@ -168,6 +169,7 @@ dependencies = [
requires-dist = [
{ name = "colorful", specifier = ">=0.5.8" },
{ name = "discord-py", specifier = ">=2.7.1" },
+ { name = "jpml", specifier = ">=1.1.1" },
{ name = "python-dotenvx", specifier = ">=2.0.0" },
{ name = "ruff", specifier = ">=0.16.7" },
{ name = "toml", specifier = ">=0.10.2" },
@@ -237,6 +239,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/57/b0/0e52c878c53f245edd3a11020f20979b3f490f245af532c7cae3027754b5/idna-3.19-py3-none-any.whl", hash = "sha256:815e7be7a7806d54abb586dc943addc79e8b2ee16915059658cbeff4b1b43bf4", size = 68550, upload-time = "2026-08-18T05:14:22.343Z" },
]
+[[package]]
+name = "jpml"
+version = "1.1.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/ab/79/f7a2536c3d13e257bf3911ecc926f03106683e9845820ec38cb792fe3291/jpml-1.1.1.tar.gz", hash = "sha256:f17098324d869f73fa6730a36842fe47e5b00fa581cec887f8672e090310af0d", size = 21513, upload-time = "2026-09-12T00:37:31.812Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/56/6e/cd214a671f0f4f677ff74729d9c73b619f9f7300318bd2be1fb74bc8f408/jpml-1.1.1-py3-none-any.whl", hash = "sha256:59a8bf81c81100fa10486df673b5d313a500af2b365b5f7ad801506b3d7387ea", size = 25942, upload-time = "2026-09-12T00:37:30.642Z" },
+]
+
[[package]]
name = "multidict"
version = "6.8.0"