Przejdź do treści
Biblioteka skilli
Programowanie · Budowanie i kod

economy-database

/economy-database

Buduje bezpieczną bazę SQLite dla bota discord.py: tryb WAL, migracje, transakcje, klucze idempotencji i kopie zapasowe co godzinę.

Licencja
MIT
Ostatnia zmiana repozytorium
06.11.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
15
Skrypty
1
Komentarze HTML
0
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 06.11.2026, bez odwołań do wycofanych modeli i API.

Licencja

MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.

Co sprawdzić przed instalacją
  • 1 skrypt w paczce. Przejrzyj je przed instalacją, bo Claude może je uruchomić.

Skrypty: scripts/migrate.py

Co robi i kiedy

Buduje bezpieczną bazę SQLite dla bota discord.py: tryb WAL, migracje, transakcje, klucze idempotencji i kopie zapasowe co godzinę.

Wyzwalacze z opisu

add currencymy balances reset on restarttwo users bought at once and gold duplicated
Oryginalny opis (EN)

Build a safe SQLite economy for a discord.py bot: WAL mode, schema with migrations, atomic transactions, idempotency keys, and hourly backups. Use when the user says 'add currency', 'my balances reset on restart', or 'two users bought at once and gold duplicated'. Do NOT use for in-memory or JSON storage, and do NOT use SQLite for production on hosts that wipe local files; use Postgres with asyncpg there.

Jak działa

  1. Rules first
  2. Schema
  3. Every mutation bumps a revision
  4. Connection setup
  5. Atomic transfer (compare-and-swap)
  6. Idempotent credit
  7. Wiring /daily to Discord
  8. Migrations
  9. Backups
  10. The dashboard reads. It never writes.
Sekcje z nagłówków SKILL.md, w oryginale · 113 linii, 1 160 słów
Podgląd SKILL.md
---
name: economy-database
description: "Build a safe SQLite economy for a discord.py bot: WAL mode, schema with migrations, atomic transactions, idempotency keys, and hourly backups. Use when the user says 'add currency', 'my balances reset on restart', or 'two users bought at once and gold duplicated'. Do NOT use for in-memory or JSON storage, and do NOT use SQLite for production on hosts that wipe local files; use Postgres with asyncpg there."
license: MIT
compatibility: "discord.py 2.x, Python 3.10+, aiosqlite, no paid services"
metadata:
  version: "0.5.0"
  author: "drewdestar"
---

# Economy Database

A bot economy is a ledger, not a number in a column. This skill builds the SQLite layer that keeps balances correct when two commands run at the same time, when the process restarts mid-trade, and when a user retries a slow request.

> **Sources and license.** The patterns in this skill were learned from real database projects — etcd (Apache-2.0), Prisma (Apache-2.0), Laravel (MIT), Supabase (Apache-2.0), DuckDB (MIT), Prometheus (Apache-2.0), ClickHouse (Apache-2.0), H2 (MPL-2.0 / EPL-1.0) — and are described here in the skill's own words. Patterns only: no code is copied from any of those projects, and none of them is vendored or recommended as a dependency of a bot. In particular, never copy code from, vendor, or recommend as a dependency: MongoDB (SSPL-1.0, source-available, not OSI-approved), Redis (tri-license RSALv2 / SSPLv1 / AGPLv3 since v8), Metabase (AGPL-3.0, OSS edition), Blazegraph (GPL-2.0, archived and dead), or RocksDB's GPL-2.0 licensing limb (dual GPL-2.0 / Apache-2.0). Learning a pattern from one of these projects is fine; copying its code into the pack is not. etcd's compare-and-swap and revision-counter patterns are Apache-2.0, so describing them here is fine — the same "patterns, not code" rule still applies.

## Rules first

1. **One writer.** SQLite allows one writer at a time. All writes go through one connection (or one lock) so two commands never interleave a balance update.
2. **Ledger as source of truth.** Every balance change is a row in a transactions table. The balance column is a cache of the ledger sum. If the two ever disagree, the ledger wins. Prove it with a reconciliation query, not a feeling:

   ```sql
   -- Every user's ledger sum must equal their balance column.
   SELECT user_id, SUM(amount) AS ledger_sum FROM transactions GROUP BY user_id;
   ```

   Compare each `ledger_sum` against `users.balance`. A mismatch means a write moved money without a ledger row (or the reverse) — find that write, do not adjust the numbers to match.
3. **Atomic transfers.** A transfer moves money in a single transaction: check, debit, credit, ledger rows, commit. If any step fails, everything rolls back.
4. **Idempotency keys.** Every credit that comes from outside (daily claim, purchase, reward) carries a unique key. Replaying the same key credits nothing the second time.
5. **Parameterized queries, always.** Never build SQL with f-strings or string concatenation. User input in SQL is an injection bug.
6. **Every mutation bumps a revision.** A balance change without a ledger row and a version bump did not happen — roll it back.
7. **The dashboard reads; it never writes.** All writes go through the bot's economy module. A dashboard write is a bug, not a feature.

## Schema

The schema: users, ledger, idempotency keys, and the version column. See `references/schema.md`.

## Every mutation bumps a revision

Every mutation bumps a revision: the global sequence, per-user version, and compensating rows. See `references/revision-feed.md`.

## Connection setup

Connection setup: WAL mode, the PRAGMA check, and `synchronous`. See `references/connection-setup.md`.

## Atomic transfer (compare-and-swap)

The atomic transfer (compare-and-swap): one transaction, one version bump, no double-spend. See `references/transfer.md`.

## Idempotent credit

Idempotent credit: `credit_once` and the daily claim. See `references/idempotent-credit.md`.

## Wiring /daily to Discord

`credit_once` returns a boolean; the command turns it into the words the user sees. That mapping is the whole command:

```python
from datetime import datetime, timezone

@app_commands.command(name="daily", description="Claim your daily gold.")
async def daily(interaction: discord.Interaction):
    key = f"daily:{interaction.user.id}:{datetime.now(timezone.utc).date().isoformat()}"
    paid = await credit_once(interaction.client.db, interaction.client.db_lock,
                             interaction.user.id, 100, "daily", key)
    text = "You claimed 100 gold." if paid else "You already claimed today."
    await interaction.response.send_message(text, ephemeral=True)
```

- The boolean is the behaviour: `True` means "You claimed 100 gold", `False` means "already claimed". Do not re-check the balance to decide the words; the return value already knows.
- `db` and `db_lock` live on the bot object (see the starter bot's `bot.py`: the bot owns one connection and one lock). The command never opens its own connection.
- The key uses the UTC date (see "Idempotent credit"), so a user cannot claim twice by crossing a timezone boundary.

## Migrations

Migrations discipline: numbered files, one transaction each, the shadow-DB drift check, and `scripts/migrate.py`. See `references/migrations.md`.

## Backups

Backups: checkpoint, the backup API, verification, the portable dump, and retention. See `references/backups.md`.

## The dashboard reads. It never writes.

The dashboard reads. It never writes: read-only mode, `query_only`, and cheap scoped reads. See `references/dashboard-reads.md`.

## Race test: two claims at once must not double-pay

The race test: two claims at once must not double-pay. See `references/race-test.md`.

## Persistence warning

SQLite is a file. On hosts that wipe local files on redeploy (Railway, Heroku, and similar), the database disappears with the deploy and every balance resets to zero. For production on such a host, use Postgres with `asyncpg` instead, keeping the same rules: one writer, ledger as source of truth, atomic transfers, idempotency keys, parameterized queries.

## Verify live

- Restart the bot. Balances are exactly what they were before.
- Run `/daily` twice in a row in Discord. The second run says the reward was already claimed; the balance moved once.
- Restore one hourly backup into a scratch copy and read a known balance from it. A backup that was never restored is unproven.

## Quality bar (no slop)

- Never invent a balance, a price, or a count. The ledger is the source of truth; a number shown to a user comes from a query.
- No em dash in any message or embed the bot sends.

## Checklist

- [ ] WAL mode on, `busy_timeout` set, foreign keys on
- [ ] One writer: one connection plus one lock
- [ ] Every balance change writes a ledger row
- [ ] Transfers use `BEGIN IMMEDIATE` + CAS (`UPDATE … WHERE version = ?`) with a `rowcount` check and bounded retry
- [ ] Every external credit carries a unique idempotency key
- [ ] All queries parameterized, no f-strings in SQL
- [ ] `balance >= 0` enforced by a CHECK constraint
- [ ] `synchronous` set deliberately: NORMAL with WAL (can lose recent transactions on power loss), FULL for writes that must survive a power cut
- [ ] Every balance write bumps `users.version` and writes a ledger row; corrections are new rows, never edits
- [ ] Dashboard can poll "what changed since rev N" from the ledger id; a gap triggers a full re-sync
- [ ] Migrations live in numbered files with up/down, tracked in `schema_migrations`, applied explicitly before bot start; a shadow-DB drift check runs first; nothing auto-generates or auto-applies at runtime
- [ ] Dashboard connects read-only (`mode=ro` + `query_only`) and never writes economy tables; all writes go through the bot's economy module
- [ ] Hourly backups exist: checkpoint → backup API → integrity check + row-count spot-check → portable dump, and one restore was tested
- [ ] No code copied from AGPL/SSPL/GPL-licensed repos; patterns only, in the skill's own words
- [ ] `.db` files are in `.gitignore`
Pliki w paczce (15)
  • SKILL.md 8 KB
  • references/backups.md 6 KB
  • references/connection-setup.md 3 KB
  • references/dashboard-reads.md 3 KB
  • references/idempotent-credit.md 2 KB
  • references/migrations.md 6 KB
  • references/race-test.md 3 KB
  • references/revision-feed.md 2 KB
  • references/schema.md 2 KB
  • references/schema.sql 1 KB
  • references/transfer.md 6 KB
  • references/migrations/001_init.sql 1 KB
  • references/migrations/002_add_idem_key.sql 1 KB
  • references/migrations/003_add_user_version.sql 1 KB
  • scripts/migrate.py 10 KB

Wersje

W bazie nie ma innych skilli o nazwie economy-database.

Migawka bazy z 13.11.2026 · wersja paczki 91991bafac51 (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 0 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 100sqlite
    Projektuje i obsługuje pliki bazy SQLite: transakcje, WAL, migracje i kopie zapasowe, także przy blokadach zapisu.
  • 100sqlite
    Wspiera SQLite: tworzenie i odpytywanie plików .db, import CSV, użycie z Node.js i Pythona, tryb WAL i klucze obce, wyszukiwanie FTS5 oraz bezpieczna kopia zapasowa.
  • 100sqlite-embedded-database-patterns
    Pomaga osadzać SQLite w aplikacjach: konfiguruje WAL, strojenie pamięci i równoległy dostęp.
  • 100maui-sqlite-database
    Dodaje lokalną bazę SQLite do aplikacji .NET MAUI przez sqlite-net-pcl: modele z atrybutami ORM, asynchroniczna usługa bazy, rejestracja w DI, tryb WAL i zarządzanie plikami.
  • 100sqlite
    Wspiera pracę z wbudowaną bazą SQLite: tryb WAL, strojenie PRAGMA, wyszukiwanie pełnotekstowe FTS5 i współbieżność, dla aplikacji desktopowych, mobilnych i systemów wbudowanych.
  • 90bot-dashboard
    Buduje panel WWW i API dla bota discord.py: wspólna baza SQLite, logowanie OAuth2 Discord i żywe statystyki.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.