Database: - Add missing indexes (users.credits, users_currency(type,amount), users_settings.respects_received, camera_web.timestamp, messenger_offline.user_id) via migrations 0020/0021 - Use partial .select() everywhere instead of SELECT * (tickets, users, rooms, audit logs, catalog tree, polls, radio, password reset) - Add queryPrepared/queryPreparedOne (server-side prepared statements) and switch the login check to a prepared statement; drop dead cache options from the pool config - Raise total_users/total_rooms COUNT(*) cache TTL to 5m Caching: - Consolidate the three cache helpers (cached, redisCache, cachedQuery) into a single memory-first implementation backed by Redis - invalidateKey now clears the in-process cache as well as Redis - Cache homepage sections, news list, and leaderboard tabs; share one news_list cache key between homepage and news archive - siteSettings: in-process cache with TTL so repeated getters no longer pay a Redis round-trip per call - Share a 10s poll cache across all radio SSE connections - Normalize timestamps after cache reads (Redis JSON round-trip) Assets: - Enable AVIF/WebP via images.formats and remove unoptimized from news covers and the homepage hero (149KB jpg) with proper sizes/priority - Support ?format=webp|avif|png in the /imaging proxy via sharp Other: - Fix pnpm supply-chain minimumReleaseAge failures by excluding the freshly-published packages (next 16.3.1, hookform resolvers 5.8.0, resend 6.20.0) - Remove unused before/after fields from housekeeping AuditEntry
98 lines
2.8 KiB
TypeScript
98 lines
2.8 KiB
TypeScript
import { drizzle } from "drizzle-orm/mysql2";
|
|
import type { Pool as MySqlPool } from "mysql2/promise";
|
|
import mysql from "mysql2/promise";
|
|
import * as relations from "@/db/relations";
|
|
import * as schema from "@/db/schema";
|
|
import { env } from "@/env";
|
|
import { resolveConnectionLimit } from "@/lib/db-pool";
|
|
|
|
const fullSchema = { ...schema, ...relations };
|
|
|
|
const globalForDb = globalThis as unknown as {
|
|
db?: ReturnType<typeof createDb>;
|
|
};
|
|
|
|
function createDb() {
|
|
const url = new URL(env.DATABASE_URL);
|
|
const isBuild =
|
|
process.env.NEXT_PHASE === "phase-production-build" ||
|
|
process.env.NEXT_PHASE === "phase-production-compile";
|
|
const connectionLimit = resolveConnectionLimit(env.DATABASE_POOL_SIZE);
|
|
// Fail fast during SSG so Next can retry/fallback instead of hanging 30s+.
|
|
const connectTimeout = isBuild
|
|
? Math.min(env.DATABASE_CONNECT_TIMEOUT_MS, 5_000)
|
|
: env.DATABASE_CONNECT_TIMEOUT_MS;
|
|
|
|
const pool = mysql.createPool({
|
|
host: url.hostname,
|
|
port: Number(url.port) || 3306,
|
|
user: decodeURIComponent(url.username),
|
|
password: decodeURIComponent(url.password),
|
|
database: url.pathname.replace(/^\//, ""),
|
|
charset: "utf8mb4",
|
|
waitForConnections: true,
|
|
connectionLimit,
|
|
queueLimit: 0,
|
|
connectTimeout,
|
|
idleTimeout: env.DATABASE_IDLE_TIMEOUT_MS,
|
|
enableKeepAlive: true,
|
|
// Allow :placeholder syntax for raw SQL helpers.
|
|
namedPlaceholders: true,
|
|
// Reject multiple statements (SQL injection hardening).
|
|
multipleStatements: false,
|
|
supportBigNumbers: true,
|
|
});
|
|
|
|
return drizzle(pool, {
|
|
schema: fullSchema,
|
|
mode: "default",
|
|
logger:
|
|
env.NODE_ENV === "development"
|
|
? {
|
|
logQuery(query, params) {
|
|
console.log("[db]", query, params);
|
|
},
|
|
}
|
|
: false,
|
|
});
|
|
}
|
|
|
|
export const db = globalForDb.db ?? createDb();
|
|
|
|
if (env.NODE_ENV !== "production") globalForDb.db = db;
|
|
|
|
export type Db = ReturnType<typeof createDb>;
|
|
|
|
type PreparedValue = string | number | bigint | boolean | Date | null | Buffer;
|
|
|
|
/**
|
|
* Server-side prepared statements (mysql2 pool.execute()).
|
|
*
|
|
* Drizzle's mysql2 driver runs `.select()` through the text protocol
|
|
* (pool.query()), so it never uses server-side prepared statements. For
|
|
* hot-path queries the SQL is parsed once on the server per connection
|
|
* instead of every execution. Column aliases let you pick exactly the
|
|
* columns you need (no SELECT *).
|
|
*/
|
|
export async function queryPrepared<T extends Record<string, unknown>>(
|
|
sql: string,
|
|
params?: PreparedValue[],
|
|
): Promise<T[]> {
|
|
const client = db.$client as MySqlPool;
|
|
const [rows] = (await client.execute(sql, params)) as unknown as [
|
|
T[],
|
|
unknown,
|
|
];
|
|
return rows ?? [];
|
|
}
|
|
|
|
export async function queryPreparedOne<T extends Record<string, unknown>>(
|
|
sql: string,
|
|
params?: PreparedValue[],
|
|
): Promise<T | null> {
|
|
const rows = await queryPrepared<T>(sql, params);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export * from "@/db/schema";
|