Skip to content

Database and Storage

M3rcena edited this page Nov 1, 2026 · 1 revision

💾 Database & Storage Handlers

@m3rcena/weky provides a unified, enterprise-grade persistence architecture designed to give developers absolute flexibility. Whether you want a zero-dependency, blazing-fast native SQLite database using Node's built-in node:sqlite, a production Prisma ORM integration with automatic schema migration, a simple JSON file store, or transient in-memory caching, Weky supports them all out of the box.


🚀 Quick Setup

Configure storage directly when initializing WekyManager:

import { Client } from "discord.js";
import { WekyManager } from "@m3rcena/weky";

const client = new Client({ intents: [/* ... */] });

// Option A: Native SQLite (node:sqlite - zero dependencies!)
export const weky = new WekyManager(client, {
  database: "sqlite", // saves to ./weky.sqlite with WAL mode enabled
});

// Option B: Custom SQLite Path
export const weky = new WekyManager(client, {
  database: {
    type: "sqlite",
    path: "./data/games.sqlite",
    walMode: true,
  },
});

// Option C: Enterprise Prisma ORM
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();

export const weky = new WekyManager(client, {
  database: {
    type: "prisma",
    client: prisma,
    model: "wekyPlayer", // matches model WekyPlayer
    autoMigrate: true,   // auto-appends models to schema.prisma if missing!
  },
});

// Option D: Simple JSON file
export const weky = new WekyManager(client, {
  database: {
    type: "json",
    path: "./data/weky-data.json",
  },
});

🗄️ Database Architecture & Storage Adapters

1. Built-in Native SQLite (node:sqlite)

Node.js 22+ comes with high-speed built-in SQLite (DatabaseSync), requiring zero native build dependencies (no node-gyp, no Python, no binary compilation).

  • Concurrency: Automatically enables PRAGMA journal_mode = WAL; (Write-Ahead Logging).
  • Indices: Indexes elo, wins, win_streak, and updated_at for sub-millisecond leaderboard queries.
  • Transactions: Atomic updates ensure player stats and tournament states are never corrupted.

Schema Created Automatically:

CREATE TABLE IF NOT EXISTS weky_players (
  id TEXT PRIMARY KEY,
  username TEXT NOT NULL,
  avatar_url TEXT,
  elo REAL NOT NULL DEFAULT 1200,
  wins INTEGER NOT NULL DEFAULT 0,
  losses INTEGER NOT NULL DEFAULT 0,
  draws INTEGER NOT NULL DEFAULT 0,
  win_streak INTEGER NOT NULL DEFAULT 0,
  highest_streak INTEGER NOT NULL DEFAULT 0,
  scores TEXT NOT NULL DEFAULT '{}',
  data TEXT NOT NULL,
  updated_at INTEGER NOT NULL
);

CREATE TABLE IF NOT EXISTS weky_tournaments (
  id TEXT PRIMARY KEY,
  game TEXT NOT NULL,
  state TEXT NOT NULL,
  winner_id TEXT,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_weky_elo ON weky_players (elo DESC);
CREATE INDEX IF NOT EXISTS idx_weky_wins ON weky_players (wins DESC);
CREATE INDEX IF NOT EXISTS idx_weky_streak ON weky_players (win_streak DESC);
CREATE INDEX IF NOT EXISTS idx_weky_updated ON weky_players (updated_at DESC);

2. Built-in Prisma ORM Integration (PrismaWekyStorage)

If your Discord bot already uses Prisma, @m3rcena/weky plugs into your existing PrismaClient with full type safety.

Automatic Schema Injection

When { type: "prisma", autoMigrate: true } is enabled, Weky automatically inspects your prisma/schema.prisma on startup and appends the required models if they don't already exist.

Prisma Schema Snippet:

// Added by @m3rcena/weky
model WekyPlayer {
  id            String   @id
  username      String
  avatarUrl     String?
  elo           Float    @default(1200)
  wins          Int      @default(0)
  losses        Int      @default(0)
  draws         Int      @default(0)
  winStreak     Int      @default(0)
  highestStreak Int      @default(0)
  scores        String   @default("{}")
  data          String
  updatedAt     DateTime @updatedAt

  @@index([elo])
}

model WekyTournament {
  id        String   @id
  game      String
  state     String
  winnerId  String?
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

🛠️ Accessing Storage Programmatically

You can access the active storage adapter directly through weky.storage or weky.leaderboard.storageAdapter:

// Fetch a player's record
const player = await weky.storage.get("user_123");
console.log(`ELO: ${player?.elo}, Wins: ${player?.wins}, Streak: ${player?.winStreak}`);

// Update or save
if (player) {
  player.winStreak += 1;
  await weky.storage.set("user_123", player);
}

// Fetch all players sorted by ELO
const topPlayers = await weky.leaderboard.getTopByElo(10);

🔄 Custom Storage Adapters

Implement the standard LeaderboardStorageAdapter interface to plug in MongoDB, Redis, PostgreSQL, Quick.db, or Enmap:

import { LeaderboardStorageAdapter, LeaderboardPlayer } from "@m3rcena/weky";

export class MongoWekyStorage implements LeaderboardStorageAdapter {
  async get(userId: string): Promise<LeaderboardPlayer | undefined> {
    const doc = await myMongoCollection.findOne({ id: userId });
    return doc ? JSON.parse(doc.data) : undefined;
  }

  async set(userId: string, data: LeaderboardPlayer): Promise<void> {
    await myMongoCollection.updateOne(
      { id: userId },
      { $set: { data: JSON.stringify(data), elo: data.elo } },
      { upsert: true }
    );
  }

  async getAll(): Promise<LeaderboardPlayer[]> {
    const docs = await myMongoCollection.find().toArray();
    return docs.map(d => JSON.parse(d.data));
  }
}

// Pass to WekyManager
const weky = new WekyManager(client, {
  storageAdapter: new MongoWekyStorage(),
});

Clone this wiki locally