Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

test(shared): verify identity and profile query behavior (#1194)

Generb16b99fe8b1b
diff --git a/src/shared/test/queries/community-user-profile.test.ts b/src/shared/test/queries/community-user-profile.test.ts
index cd4c2795b..ec971965b 100644
--- a/src/shared/test/queries/community-user-profile.test.ts
+++ b/src/shared/test/queries/community-user-profile.test.ts
@@ -1,65 +1,56 @@
import Sqlite from "better-sqlite3";
-import { drizzle } from "drizzle-orm/better-sqlite3";
-import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
+import { drizzle } from "drizzle-orm/d1";
+import { afterEach, beforeEach, describe, it, expect } from "vitest";
import * as profileQueries from "../../src/db/queries/community/user-profile";
-import { communityUserProfile } from "../../src/db/community-schema";
import type { Database } from "../../src/db";
-function createSelectMock(rows: any[]) {
- const chain: any = {};
- chain.select = vi.fn(() => chain);
- chain.from = vi.fn(() => chain);
- chain.where = vi.fn(() => Promise.resolve(rows));
- return chain;
-}
-
-function createUpsertMock(returnRow: any) {
- const chain: any = {};
- chain.insert = vi.fn(() => chain);
- chain.values = vi.fn(() => chain);
- chain.onConflictDoUpdate = vi.fn(() => chain);
- chain.returning = vi.fn(() => Promise.resolve([returnRow]));
- return chain;
-}
-
-
-describe("getPublicProfileForViewer", () => {
- let sqlite: Sqlite.Database;
- let db: Database;
-
- beforeEach(() => {
- sqlite = new Sqlite(":memory:");
+function createDatabase() {
+ const sqlite = new Sqlite(":memory:");
+ try {
sqlite.exec(`
+ PRAGMA foreign_keys = ON;
CREATE TABLE user (
- id TEXT PRIMARY KEY,
- name TEXT NOT NULL,
- email TEXT NOT NULL UNIQUE,
- emailVerified INTEGER,
- image TEXT,
- avatarVersion INTEGER NOT NULL DEFAULT 0,
- avatarObjectKey TEXT,
- createdAt TEXT NOT NULL,
- updatedAt TEXT NOT NULL,
- isBot INTEGER NOT NULL DEFAULT 0,
- ownerUserId TEXT,
- deletedAt TEXT,
- discriminator TEXT NOT NULL DEFAULT '0000',
- lastRefreshContextAt TEXT
+ id TEXT PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL UNIQUE,
+ emailVerified INTEGER, image TEXT, avatarVersion INTEGER NOT NULL DEFAULT 0,
+ avatarObjectKey TEXT, createdAt TEXT NOT NULL, updatedAt TEXT NOT NULL,
+ isBot INTEGER NOT NULL DEFAULT 0, ownerUserId TEXT REFERENCES user(id),
+ deletedAt TEXT, discriminator TEXT NOT NULL DEFAULT '0000', lastRefreshContextAt TEXT
);
CREATE TABLE community_user_profile (
- user_id TEXT PRIMARY KEY,
- about_me TEXT DEFAULT '',
- banner_color TEXT,
- status_emoji TEXT,
- status_text TEXT DEFAULT ''
+ user_id TEXT PRIMARY KEY REFERENCES user(id) ON DELETE CASCADE,
+ about_me TEXT DEFAULT '', banner_color TEXT, status_emoji TEXT, status_text TEXT DEFAULT ''
);
`);
- db = drizzle(sqlite) as unknown as Database;
-
+ const rawRows: unknown[][] = [];
+ const client = {
+ prepare(sql: string) {
+ return {
+ bind(...params: unknown[]) {
+ return {
+ raw: async () => {
+ const rows = sqlite.prepare(sql).raw(true).all(...params) as unknown[][];
+ rawRows.push(...rows.map(row => [...row]));
+ return rows;
+ },
+ all: async () => {
+ const rows = sqlite.prepare(sql).all(...params) as Record<string, unknown>[];
+ rawRows.push(...rows.map(row => Object.values(row)));
+ return { success: true, results: rows };
+ },
+ run: async () => {
+ const result = sqlite.prepare(sql).run(...params);
+ return { success: true, results: [], meta: { changes: result.changes, last_row_id: Number(result.lastInsertRowid) } };
+ },
+ };
+ },
+ };
+ },
+ };
+ const db = drizzle(client as never) as unknown as Database;
const insertUser = sqlite.prepare(`
INSERT INTO user
- (id, name, email, image, createdAt, updatedAt, isBot, ownerUserId, deletedAt, discriminator)
- VALUES (?, ?, ?, ?, '2026-01-01', '2026-01-01', ?, ?, ?, ?)
+ (id,name,email,image,createdAt,updatedAt,isBot,ownerUserId,deletedAt,discriminator)
+ VALUES (?,?,?,?,'2026-01-01','2026-01-01',?,?,?,?)
`);
insertUser.run("viewer_1", "Viewer", "[email protected]", null, 0, null, null, "0001");
insertUser.run("human_1", "Human", "[email protected]", "human.png", 0, null, null, "0002");
@@ -68,29 +59,53 @@ describe("getPublicProfileForViewer", () => {
insertUser.run("deleted_target", "Gone", "[email protected]", null, 0, null, "2026-02-01", "0003");
insertUser.run("deleted_owner", "Old Owner", "[email protected]", null, 0, null, "2026-02-01", "0004");
insertUser.run("orphaned_bot", "Orphan", "[email protected]", null, 1, "deleted_owner", null, "0101");
-
sqlite.prepare(`
- INSERT INTO community_user_profile
- (user_id, about_me, banner_color, status_emoji, status_text)
- VALUES ('bot_1', 'backend bot', '#123456', '๐Ÿ› ๏ธ', 'Working')
+ INSERT INTO community_user_profile (user_id,about_me,banner_color,status_emoji,status_text)
+ VALUES ('bot_1','backend bot','#123456','๐Ÿ› ๏ธ','Working')
`).run();
- });
+ return { sqlite, db, rawRows };
+ } catch (error) {
+ sqlite.close();
+ throw error;
+ }
+}
+
+type Store = ReturnType<typeof createDatabase>;
+async function withDatabase(run: (store: Store) => Promise<void>) {
+ const store = createDatabase();
+ try { await run(store); } finally { store.sqlite.close(); }
+}
+
+function seedForeignProfile(sqlite: Sqlite.Database) {
+ sqlite.prepare(`
+ INSERT INTO community_user_profile (user_id,about_me,banner_color,status_emoji,status_text)
+ VALUES ('viewer_1','Keep about','#abcdef','๐ŸŽง','Keep status')
+ `).run();
+ return sqlite.prepare("SELECT * FROM community_user_profile WHERE user_id='viewer_1'").get();
+}
+
+function expectForeignProfile(sqlite: Sqlite.Database, before: unknown) {
+ expect(sqlite.prepare("SELECT * FROM community_user_profile WHERE user_id='viewer_1'").get()).toEqual(before);
+}
+
+describe("getPublicProfileForViewer", () => {
+ let sqlite: Sqlite.Database;
+ let db: Database;
- afterEach(() => sqlite.close());
+ beforeEach(() => {
+ const store = createDatabase();
+ sqlite = store.sqlite;
+ db = store.db;
+ });
+ afterEach(() => { if (sqlite?.open) sqlite.close(); });
it("returns the human discriminator without bot-only identity fields", async () => {
+ sqlite.prepare("UPDATE user SET avatarVersion=9 WHERE id='human_1'").run();
await expect(profileQueries.getPublicProfileForViewer(db, "human_1", "viewer_1"))
.resolves.toEqual({
- id: "human_1",
- name: "Human",
- discriminator: "0002",
- image: "human.png",
- avatarVersion: 0,
- aboutMe: "",
- bannerColor: null,
- statusEmoji: null,
- statusText: null,
- identity: { kind: "human" },
+ id: "human_1", name: "Human", discriminator: "0002", image: "human.png",
+ avatarVersion: 9, aboutMe: "", bannerColor: null, statusEmoji: null,
+ statusText: null, identity: { kind: "human" },
});
});
@@ -98,32 +113,20 @@ describe("getPublicProfileForViewer", () => {
await profileQueries.updateProfile(db, "human_1", { statusEmoji: null, statusText })
expect(sqlite.prepare("SELECT status_text FROM community_user_profile WHERE user_id=?").get("human_1")).toEqual({ status_text: statusText })
expect((await profileQueries.getPublicProfileForViewer(db, "human_1", "viewer_1"))?.statusText).toBe(statusText)
- })
+ });
it("returns canonical public owner navigation and SQL-derived viewer ownership", async () => {
+ sqlite.prepare("UPDATE user SET avatarVersion=7 WHERE id='bot_1'").run();
const ownerView = await profileQueries.getPublicProfileForViewer(db, "bot_1", "owner_1");
expect(ownerView).toEqual({
- id: "bot_1",
- name: "Helper",
- discriminator: "0100",
- image: "bot.png",
- avatarVersion: 0,
- aboutMe: "backend bot",
- bannerColor: "#123456",
- statusEmoji: "๐Ÿ› ๏ธ",
- statusText: "Working",
- identity: {
- kind: "bot",
- ownerProfile: { id: "owner_1", handle: "Owner#0042" },
- ownedByViewer: true,
- },
+ id: "bot_1", name: "Helper", discriminator: "0100", image: "bot.png",
+ avatarVersion: 7, aboutMe: "backend bot", bannerColor: "#123456",
+ statusEmoji: "๐Ÿ› ๏ธ", statusText: "Working",
+ identity: { kind: "bot", ownerProfile: { id: "owner_1", handle: "Owner#0042" }, ownedByViewer: true },
});
-
const otherView = await profileQueries.getPublicProfileForViewer(db, "bot_1", "viewer_1");
expect(otherView?.identity).toEqual({
- kind: "bot",
- ownerProfile: { id: "owner_1", handle: "Owner#0042" },
- ownedByViewer: false,
+ kind: "bot", ownerProfile: { id: "owner_1", handle: "Owner#0042" }, ownedByViewer: false,
});
expect(otherView).not.toHaveProperty("ownerUserId");
expect(otherView).not.toHaveProperty("email");
@@ -138,64 +141,77 @@ describe("getPublicProfileForViewer", () => {
});
describe("getProfile", () => {
- it("returns the row including statusEmoji/statusText when a profile exists", async () => {
- const db = createSelectMock([
- { userId: "u_1", aboutMe: "hi", bannerColor: null, statusEmoji: "๐ŸŽง", statusText: "Vibing" },
- ]);
- const result = await profileQueries.getProfile(db, "u_1");
- expect(result).toMatchObject({ statusEmoji: "๐ŸŽง", statusText: "Vibing" });
+ it("returns the actual stored profile including status fields", async () => {
+ await withDatabase(async store => {
+ seedForeignProfile(store.sqlite);
+ await expect(profileQueries.getProfile(store.db, "bot_1")).resolves.toEqual({
+ userId: "bot_1", aboutMe: "backend bot", bannerColor: "#123456", statusEmoji: "๐Ÿ› ๏ธ", statusText: "Working",
+ });
+ expect(new Set(store.rawRows.flat()).has("viewer_1")).toBe(false);
+ });
});
- it("returns null when no profile row exists", async () => {
- const db = createSelectMock([]);
- const result = await profileQueries.getProfile(db, "u_missing");
- expect(result).toBeNull();
+ it("returns null for a valid user without a profile despite another stored profile", async () => {
+ await withDatabase(async store => {
+ await expect(profileQueries.getProfile(store.db, "human_1")).resolves.toBeNull();
+ expect(store.rawRows).toEqual([]);
+ });
});
});
describe("updateProfile", () => {
- it("persists statusEmoji/statusText alongside aboutMe on insert", async () => {
- const db = createUpsertMock({
- userId: "u_1",
- aboutMe: "hi",
- bannerColor: null,
- statusEmoji: "๐ŸŽง",
- statusText: "Vibing",
- });
- const result = await profileQueries.updateProfile(db, "u_1", {
- aboutMe: "hi",
- statusEmoji: "๐ŸŽง",
- statusText: "Vibing",
+ it("inserts the supplied status and about fields for only the requested user", async () => {
+ await withDatabase(async store => {
+ const foreign = seedForeignProfile(store.sqlite);
+ const beforeBot = store.sqlite.prepare("SELECT * FROM community_user_profile WHERE user_id='bot_1'").get();
+ await expect(profileQueries.updateProfile(store.db, "human_1", { aboutMe: "hi", statusEmoji: "๐ŸŽง", statusText: "Vibing" })).resolves.toEqual({
+ userId: "human_1", aboutMe: "hi", bannerColor: null, statusEmoji: "๐ŸŽง", statusText: "Vibing",
+ });
+ expect(store.sqlite.prepare("SELECT * FROM community_user_profile WHERE user_id='human_1'").get()).toEqual({
+ user_id: "human_1", about_me: "hi", banner_color: null, status_emoji: "๐ŸŽง", status_text: "Vibing",
+ });
+ expect(store.sqlite.prepare("SELECT * FROM community_user_profile WHERE user_id='bot_1'").get()).toEqual(beforeBot);
+ expectForeignProfile(store.sqlite, foreign);
+ expect(store.sqlite.prepare("SELECT count(*) AS count FROM community_user_profile").get()).toEqual({ count: 3 });
});
- expect(db.values).toHaveBeenCalledWith(
- expect.objectContaining({ userId: "u_1", aboutMe: "hi", statusEmoji: "๐ŸŽง", statusText: "Vibing" }),
- );
- expect(result).toMatchObject({ statusEmoji: "๐ŸŽง", statusText: "Vibing" });
});
- it("an aboutMe-only update's onConflictDoUpdate.set omits statusEmoji/statusText entirely", async () => {
- const db = createUpsertMock({ userId: "u_1", aboutMe: "hi", bannerColor: null, statusEmoji: null, statusText: "" });
- await profileQueries.updateProfile(db, "u_1", { aboutMe: "hi" });
- const conflictArg = db.onConflictDoUpdate.mock.calls[0][0];
- expect(conflictArg.set).not.toHaveProperty("statusEmoji");
- expect(conflictArg.set).not.toHaveProperty("statusText");
- expect(conflictArg.set).toMatchObject({ aboutMe: "hi" });
- expect(conflictArg.target).toBe(communityUserProfile.userId);
+ it("persists an about-only patch without changing status or another profile", async () => {
+ await withDatabase(async store => {
+ const foreign = seedForeignProfile(store.sqlite);
+ const result = await profileQueries.updateProfile(store.db, "bot_1", { aboutMe: "hi" });
+ expect(store.sqlite.prepare("SELECT * FROM community_user_profile WHERE user_id='bot_1'").get()).toEqual({
+ user_id: "bot_1", about_me: "hi", banner_color: "#123456", status_emoji: "๐Ÿ› ๏ธ", status_text: "Working",
+ });
+ expect(result).toEqual({ userId: "bot_1", aboutMe: "hi", bannerColor: "#123456", statusEmoji: "๐Ÿ› ๏ธ", statusText: "Working" });
+ expectForeignProfile(store.sqlite, foreign);
+ expect(store.sqlite.prepare("SELECT count(*) AS count FROM community_user_profile").get()).toEqual({ count: 2 });
+ });
});
- it("a status-only update's onConflictDoUpdate.set omits aboutMe/bannerColor entirely", async () => {
- const db = createUpsertMock({ userId: "u_1", aboutMe: "", bannerColor: null, statusEmoji: "๐ŸŽฎ", statusText: "Gaming" });
- await profileQueries.updateProfile(db, "u_1", { statusEmoji: "๐ŸŽฎ", statusText: "Gaming" });
- const conflictArg = db.onConflictDoUpdate.mock.calls[0][0];
- expect(conflictArg.set).not.toHaveProperty("aboutMe");
- expect(conflictArg.set).not.toHaveProperty("bannerColor");
- expect(conflictArg.set).toMatchObject({ statusEmoji: "๐ŸŽฎ", statusText: "Gaming" });
+ it("updates status while preserving existing about and banner facts", async () => {
+ await withDatabase(async store => {
+ const foreign = seedForeignProfile(store.sqlite);
+ await expect(profileQueries.updateProfile(store.db, "bot_1", { statusEmoji: "๐ŸŽฎ", statusText: "Gaming" })).resolves.toEqual({
+ userId: "bot_1", aboutMe: "backend bot", bannerColor: "#123456", statusEmoji: "๐ŸŽฎ", statusText: "Gaming",
+ });
+ expect(store.sqlite.prepare("SELECT * FROM community_user_profile WHERE user_id='bot_1'").get()).toEqual({
+ user_id: "bot_1", about_me: "backend bot", banner_color: "#123456", status_emoji: "๐ŸŽฎ", status_text: "Gaming",
+ });
+ expectForeignProfile(store.sqlite, foreign);
+ });
});
- it("clearing statusEmoji/statusText to null writes null through to set", async () => {
- const db = createUpsertMock({ userId: "u_1", aboutMe: "", bannerColor: null, statusEmoji: null, statusText: null });
- await profileQueries.updateProfile(db, "u_1", { statusEmoji: null, statusText: null });
- const conflictArg = db.onConflictDoUpdate.mock.calls[0][0];
- expect(conflictArg.set).toMatchObject({ statusEmoji: null, statusText: null });
+ it("clears an existing nonnull status without overwriting other profile fields", async () => {
+ await withDatabase(async store => {
+ const foreign = seedForeignProfile(store.sqlite);
+ await expect(profileQueries.updateProfile(store.db, "bot_1", { statusEmoji: null, statusText: null })).resolves.toEqual({
+ userId: "bot_1", aboutMe: "backend bot", bannerColor: "#123456", statusEmoji: null, statusText: null,
+ });
+ expect(store.sqlite.prepare("SELECT * FROM community_user_profile WHERE user_id='bot_1'").get()).toEqual({
+ user_id: "bot_1", about_me: "backend bot", banner_color: "#123456", status_emoji: null, status_text: null,
+ });
+ expectForeignProfile(store.sqlite, foreign);
+ });
});
});
diff --git a/src/shared/test/queries/param-limit.test.ts b/src/shared/test/queries/param-limit.test.ts
index 7aaaac10e..bc90f4e2d 100644
--- a/src/shared/test/queries/param-limit.test.ts
+++ b/src/shared/test/queries/param-limit.test.ts
@@ -205,27 +205,58 @@ describe("getUsersByIds bound parameters and result set", () => {
"2026-01-01T00:00:00.000Z", "2026-01-01T00:00:00.000Z", "1234"];
}
- it.each([
- { count: 100, sizes: [100] },
- { count: 101, sizes: [100, 1] },
- { count: 201, sizes: [100, 100, 1] },
- ])("returns all $count users within each statement's bind budget", async ({ count, sizes }) => {
- const ids = Array.from({ length: count }, (_, index) => `user_${index}`);
- let offset = 0;
- const responses = sizes.map((size) => {
- const rows = ids.slice(offset, offset + size).map(rawUser);
- offset += size;
- return rows;
- });
- const { db, statements } = makeD1Capture(responses);
+ function userReadDb(ids: string[]) {
+ const sqlite = new Sqlite(":memory:");
+ try {
+ sqlite.exec(`CREATE TABLE user (
+ id TEXT PRIMARY KEY, name TEXT, email TEXT, emailVerified INTEGER,
+ image TEXT, avatarVersion INTEGER, createdAt TEXT, updatedAt TEXT, discriminator TEXT
+ )`);
+ const insert = sqlite.prepare("INSERT INTO user VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
+ for (const id of [...ids, "outside-user"]) insert.run(...rawUser(id));
+ const statements: Array<{ sql: string; params: unknown[] }> = [];
+ const client = {
+ prepare(sql: string) {
+ return {
+ bind(...params: unknown[]) {
+ statements.push({ sql, params });
+ return { raw: async () => sqlite.prepare(sql).raw(true).all(...params) };
+ },
+ };
+ },
+ };
+ return { sqlite, db: drizzle(client as never), statements };
+ } catch (error) {
+ sqlite.close();
+ throw error;
+ }
+ }
- const rows = await userQueries.getUsersByIds(db as never, ids);
+ function expectedUsers(ids: string[]) {
+ return ids.map(id => ({
+ id, name: id, email: `${id}@example.test`, emailVerified: false,
+ image: null, avatarVersion: 0, createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z", discriminator: "1234",
+ }));
+ }
- expect(statements.map(({ params }) => params.length)).toEqual(sizes);
- expect(statements.flatMap(({ params }) => params)).toEqual(ids);
- expect(rows.map(({ id }) => id).sort()).toEqual([...ids].sort());
- for (const { params } of statements) {
- expect(params.length).toBeLessThanOrEqual(D1_MAX_BIND_PARAMS);
+ it.each([
+ { count: 100 },
+ { count: 101 },
+ { count: 201 },
+ ])("returns all $count users within each statement's bind budget", async ({ count }) => {
+ const ids = Array.from({ length: count }, (_, index) => `user_${index}`);
+ const originalIds = [...ids];
+ const { sqlite, db, statements } = userReadDb(ids);
+ try {
+ const rows = await userQueries.getUsersByIds(db as never, ids);
+ expect([...rows].sort((a, b) => a.id.localeCompare(b.id)))
+ .toEqual(expectedUsers(ids).sort((a, b) => a.id.localeCompare(b.id)));
+ expect(statements.flatMap(({ params }) => params).sort()).toEqual([...ids].sort());
+ for (const { params } of statements) expect(params.length).toBeLessThanOrEqual(100);
+ expect(ids).toEqual(originalIds);
+ } finally {
+ sqlite.close();
}
});
@@ -233,31 +264,31 @@ describe("getUsersByIds bound parameters and result set", () => {
const uniqueIds = Array.from({ length: 101 }, (_, index) => `user_${index}`);
const ids = [...uniqueIds.slice(0, 100), uniqueIds[0]!, uniqueIds[100]!, uniqueIds[50]!];
const originalIds = [...ids];
- const { db, statements } = makeD1Capture([
- uniqueIds.slice(0, 100).map(rawUser), [rawUser(uniqueIds[100]!)],
- ]);
-
- const rows = await userQueries.getUsersByIds(db as never, ids);
-
- expect(statements.map(({ params }) => params.length)).toEqual([100, 1]);
- expect(statements.flatMap(({ params }) => params)).toEqual(uniqueIds);
- expect(rows.map(({ id }) => id).sort()).toEqual([...uniqueIds].sort());
- expect(new Set(rows.map(({ id }) => id)).size).toBe(rows.length);
- expect(ids).toEqual(originalIds);
+ const { sqlite, db, statements } = userReadDb(uniqueIds);
+ try {
+ const rows = await userQueries.getUsersByIds(db as never, ids);
+ expect([...rows].sort((a, b) => a.id.localeCompare(b.id)))
+ .toEqual(expectedUsers(uniqueIds).sort((a, b) => a.id.localeCompare(b.id)));
+ const parameters = statements.flatMap(({ params }) => params);
+ expect([...parameters].sort()).toEqual([...uniqueIds].sort());
+ expect(new Set(parameters).size).toBe(parameters.length);
+ for (const { params } of statements) expect(params.length).toBeLessThanOrEqual(100);
+ expect(new Set(rows.map(({ id }) => id)).size).toBe(rows.length);
+ expect(ids).toEqual(originalIds);
+ } finally {
+ sqlite.close();
+ }
});
it("omits missing IDs across batches and keeps the historical public projection", async () => {
const ids = Array.from({ length: 101 }, (_, index) => `user_${index}`);
- const { db, statements } = makeD1Capture([
+ const { db } = makeD1Capture([
[rawUser(ids[0]!)], [rawUser(ids[100]!)],
]);
const rows = await userQueries.getUsersByIds(db as never, ids);
expect(rows.map(({ id }) => id)).toEqual([ids[0], ids[100]]);
- for (const { sql } of statements) {
- expect(sql).not.toMatch(/deletedAt|isBot|ownerUserId|avatarObjectKey/);
- }
expect(Object.keys(rows[0]!).sort()).toEqual([
"id", "name", "email", "emailVerified", "image", "avatarVersion",
"createdAt", "updatedAt", "discriminator",
@@ -509,9 +540,10 @@ describe("resource reads through the D1 adapter and local SQLite", () => {
console.info(JSON.stringify({ case: "resource-memberships-local-sqlite", ids: count, binds: statements.map(row => row.params.length), rows: rows.length }));
});
- it.each(cases)("reads all $count requested public profiles without unrequested IDs", async ({ count, sizes }) => {
+ it.each(cases)("reads all $count requested public profiles without unrequested IDs", async ({ count }) => {
const { sqlite, db, statements } = resourceDb();
const ids = Array.from({ length: count }, (_, index) => `profile_${index}`);
+ const originalIds = [...ids];
const insert = sqlite.prepare("INSERT INTO community_user_profile VALUES (?, ?, ?, ?, ?)");
for (const id of ids) insert.run(id, `about-${id}`, null, null, `status-${id}`);
insert.run("outside-profile", "outside", null, null, "outside");
@@ -519,8 +551,10 @@ describe("resource reads through the D1 adapter and local SQLite", () => {
const rows = await userProfileQueries.getProfilesByUserIds(db as never, ids);
expect([...rows].sort((a, b) => a.userId.localeCompare(b.userId))).toEqual(ids.map(userId => ({ userId, aboutMe: `about-${userId}`, bannerColor: null, statusEmoji: null, statusText: `status-${userId}` })).sort((a, b) => a.userId.localeCompare(b.userId)));
- expect(statements.map(({ params }) => params.length)).toEqual(sizes);
- expect(statements.flatMap(({ params }) => params)).toEqual(ids);
+ if (count === 0) expect(statements).toHaveLength(0);
+ expect(statements.flatMap(({ params }) => params).sort()).toEqual([...ids].sort());
+ for (const { params } of statements) expect(params.length).toBeLessThanOrEqual(100);
+ expect(ids).toEqual(originalIds);
console.info(JSON.stringify({ case: "resource-profiles-local-sqlite", ids: count, binds: statements.map(row => row.params.length), rows: rows.length }));
});
@@ -560,8 +594,10 @@ describe("resource reads through the D1 adapter and local SQLite", () => {
expect(rows.map(row => row.userId).sort()).toEqual([...ids].sort());
expect(new Set(rows.map(row => row.userId)).size).toBe(91);
expect(rows.every(row => row.aboutMe === null && row.bannerColor === null && row.statusEmoji === null && row.statusText === "")).toBe(true);
- expect(statements.map(({ params }) => params.length)).toEqual([90, 1]);
- expect(statements.flatMap(({ params }) => params)).toEqual(ids);
+ const parameters = statements.flatMap(({ params }) => params);
+ expect([...parameters].sort()).toEqual([...ids].sort());
+ expect(new Set(parameters).size).toBe(parameters.length);
+ for (const { params } of statements) expect(params.length).toBeLessThanOrEqual(100);
expect(input).toEqual(original);
});
});
diff --git a/src/shared/test/queries/user.test.ts b/src/shared/test/queries/user.test.ts
index 56e48e638..8b378983a 100644
--- a/src/shared/test/queries/user.test.ts
+++ b/src/shared/test/queries/user.test.ts
@@ -1,283 +1,421 @@
+import { readFileSync } from "node:fs";
+import Sqlite from "better-sqlite3";
+import { drizzle } from "drizzle-orm/d1";
import { describe, it, expect, vi } from "vitest";
import * as userQueries from "../../src/db/queries/user";
import { computeDiscriminator } from "../../src/lib/discriminator";
-
-function createSelectMock(rows: any[]) {
- const chain: any = {};
- chain.select = vi.fn(() => chain);
- chain.from = vi.fn(() => chain);
- chain.where = vi.fn(() => Promise.resolve(rows));
- chain.insert = vi.fn(() => chain);
- chain.values = vi.fn(() => chain);
- chain.returning = vi.fn(() => Promise.resolve(rows));
- return chain;
+import type { Database } from "../../src/db";
+
+const OLD = "2026-01-01T00:00:00.000Z";
+const NOW = "2026-11-05T01:02:03.000Z";
+type StoredUser = Record<string, unknown>;
+type SeedUser = {
+ id: string; name: string; discriminator: string; email?: string;
+ image?: string | null; avatarVersion?: number; deletedAt?: string | null;
+};
+
+function publicUser(overrides: Record<string, unknown> = {}) {
+ return {
+ id: "target", name: "Alice", email: "[email protected]", emailVerified: true,
+ image: "target.png", avatarVersion: 9, createdAt: OLD, updatedAt: OLD,
+ discriminator: "0001", ...overrides,
+ };
}
-/** Like `createSelectMock`, but `.where(...)` returns a chainable (for the `.limit(1)` callers, e.g. `getUserByNameAndDiscriminator`). */
-function createSelectLimitMock(rows: any[]) {
- const chain: any = {};
- chain.select = vi.fn(() => chain);
- chain.from = vi.fn(() => chain);
- chain.innerJoin = vi.fn(() => chain);
- chain.where = vi.fn(() => chain);
- chain.limit = vi.fn(() => Promise.resolve(rows));
- return chain;
+function createDatabase() {
+ const sqlite = new Sqlite(":memory:");
+ try {
+ sqlite.exec(`
+ PRAGMA foreign_keys = ON;
+ CREATE TABLE user (
+ id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL DEFAULT '',
+ email TEXT NOT NULL UNIQUE, emailVerified INTEGER, image TEXT,
+ avatarVersion INTEGER NOT NULL DEFAULT 0, avatarObjectKey TEXT,
+ createdAt TEXT NOT NULL, updatedAt TEXT NOT NULL,
+ isBot INTEGER NOT NULL DEFAULT 0, ownerUserId TEXT REFERENCES user(id),
+ deletedAt TEXT, discriminator TEXT NOT NULL DEFAULT '0000', lastRefreshContextAt TEXT
+ );
+ CREATE TABLE account (
+ id TEXT PRIMARY KEY NOT NULL, userId TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
+ accountId TEXT NOT NULL, providerId TEXT NOT NULL,
+ createdAt TEXT NOT NULL, updatedAt TEXT NOT NULL
+ );
+ `);
+ sqlite.exec(readFileSync(new URL("../../../web/migrations/0055_user_discriminator_unique.sql", import.meta.url), "utf8"));
+ const queries: Array<{ params: unknown[]; rows: unknown[][] }> = [];
+ const client = {
+ prepare(sql: string) {
+ return {
+ bind(...params: unknown[]) {
+ return {
+ raw: async () => {
+ const rows = sqlite.prepare(sql).raw(true).all(...params) as unknown[][];
+ queries.push({ params: [...params], rows: rows.map(row => [...row]) });
+ return rows;
+ },
+ all: async () => {
+ const rows = sqlite.prepare(sql).all(...params) as StoredUser[];
+ queries.push({ params: [...params], rows: rows.map(row => Object.values(row)) });
+ return { success: true, results: rows };
+ },
+ run: async () => {
+ const result = sqlite.prepare(sql).run(...params);
+ queries.push({ params: [...params], rows: [] });
+ return { success: true, results: [], meta: { changes: result.changes, last_row_id: Number(result.lastInsertRowid) } };
+ },
+ };
+ },
+ };
+ },
+ };
+ const db = drizzle(client as never) as unknown as Database;
+ const insert = sqlite.prepare(`
+ INSERT INTO user
+ (id,name,email,emailVerified,image,avatarVersion,avatarObjectKey,createdAt,updatedAt,isBot,ownerUserId,deletedAt,discriminator)
+ VALUES (?,?,?,1,?,?,?, ?,?,0,NULL,?,?)
+ `);
+ const seed = (value: SeedUser) => insert.run(
+ value.id, value.name, value.email ?? `${value.id}@fixture.test`,
+ value.image ?? null, value.avatarVersion ?? 0, `private-${value.id}`,
+ OLD, OLD, value.deletedAt ?? null, value.discriminator,
+ );
+ seed({ id: "target", name: "Alice", email: "[email protected]", image: "target.png", avatarVersion: 9, discriminator: "0001" });
+ seed({ id: "other", name: "Other", image: "other.png", avatarVersion: 7, discriminator: "0002" });
+ seed({ id: "gone", name: "Gone", image: "gone.png", avatarVersion: 5, discriminator: "0003", deletedAt: OLD });
+ const seedAccount = (id: string, userId: string, providerId: string, accountId: string) => sqlite.prepare(
+ "INSERT INTO account (id,userId,providerId,accountId,createdAt,updatedAt) VALUES (?,?,?,?,?,?)",
+ ).run(id, userId, providerId, accountId, OLD, OLD);
+ return { sqlite, db, queries, seed, seedAccount };
+ } catch (error) {
+ sqlite.close();
+ throw error;
+ }
}
-/**
- * Drizzle's built SQL condition objects are self-referencing (a column's
- * `.table` points back at the table, which lists every other column again โ€”
- * including ones the condition never touches), so `JSON.stringify` throws,
- * and a naive walk would false-positive on any column purely because it's a
- * sibling on the same table. Walk the object graph by hand, tracking
- * visited nodes and skipping `.table` back-references, looking for a
- * drizzle column/field whose `name` is `columnName` โ€” reachable only via an
- * actual queryChunks entry the condition builder produced.
- */
-function conditionReferencesColumn(node: unknown, columnName: string, seen = new Set<unknown>()): boolean {
- if (node === null || typeof node !== "object") return false;
- if (seen.has(node)) return false;
- seen.add(node);
- if ((node as { name?: unknown }).name === columnName) return true;
- for (const [key, value] of Object.entries(node as Record<string, unknown>)) {
- if (key === "table") continue;
- if (Array.isArray(value)) {
- if (value.some((v) => conditionReferencesColumn(v, columnName, seen))) return true;
- } else if (conditionReferencesColumn(value, columnName, seen)) {
- return true;
- }
+type Store = ReturnType<typeof createDatabase>;
+async function withDatabase(run: (store: Store) => Promise<void> | void) {
+ let store: Store | undefined;
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(NOW));
+ try {
+ store = createDatabase();
+ await run(store);
+ } finally {
+ try { store?.sqlite.close(); } finally { vi.useRealTimers(); }
}
- return false;
}
-function conditionContainsString(node: unknown, needle: string, seen = new Set<unknown>()): boolean {
- if (typeof node === "string") return node.includes(needle);
- if (node === null || typeof node !== "object") return false;
- if (seen.has(node)) return false;
- seen.add(node);
- for (const [key, value] of Object.entries(node as Record<string, unknown>)) {
- if (key === "table") continue;
- if (Array.isArray(value)) {
- if (value.some((v) => conditionContainsString(v, needle, seen))) return true;
- } else if (conditionContainsString(value, needle, seen)) {
- return true;
- }
- }
- return false;
+function snapshot(sqlite: Sqlite.Database) {
+ return sqlite.prepare("SELECT * FROM user ORDER BY id").all() as StoredUser[];
}
+function expectOnlyTargetChange(sqlite: Sqlite.Database, before: StoredUser[], changes: StoredUser) {
+ expect(snapshot(sqlite)).toEqual(before.map(row => row.id === "target" ? { ...row, ...changes } : row));
+}
+
+function expectNoDriverIdentities(store: Store, forbidden: string[]) {
+ const values = new Set(store.queries.flatMap(query => query.rows.flat()));
+ for (const id of forbidden) expect(values.has(id)).toBe(false);
+}
+
+function expectUsers(actual: unknown[], expected: ReturnType<typeof publicUser>[]) {
+ const ordered = (rows: unknown[]) => [...rows].sort((a, b) => String((a as StoredUser).id).localeCompare(String((b as StoredUser).id)));
+ expect(actual).toHaveLength(expected.length);
+ expect(ordered(actual)).toEqual(ordered(expected));
+}
describe("getUserPublic", () => {
- it("returns null when not found", async () => { expect(await userQueries.getUserPublic(createSelectMock([]), "x")).toBeNull(); });
- it("returns user", async () => { const u = { id: "u_1" }; expect(await userQueries.getUserPublic(createSelectMock([u]), "u_1")).toEqual(u); });
- it("filters on deletedAt unconditionally โ€” no option can disable it", async () => {
- const chain = createSelectMock([{ id: "u_1" }]);
- await userQueries.getUserPublic(chain, "u_1");
- expect(conditionReferencesColumn(chain.where.mock.calls[0][0], "deletedAt")).toBe(true);
+ it("returns null when not found", async () => {
+ await withDatabase(async store => {
+ await expect(userQueries.getUserPublic(store.db, "missing")).resolves.toBeNull();
+ expect(store.queries.flatMap(query => query.rows)).toEqual([]);
+ });
+ });
+
+ it("reads the live public user and excludes a deleted target without leaking internal columns", async () => {
+ await withDatabase(async store => {
+ await expect(userQueries.getUserPublic(store.db, "target")).resolves.toEqual(publicUser());
+ expectNoDriverIdentities(store, ["other", "gone"]);
+ store.queries.length = 0;
+ store.sqlite.prepare("UPDATE user SET deletedAt=? WHERE id=?").run(NOW, "target");
+ await expect(userQueries.getUserPublic(store.db, "target")).resolves.toBeNull();
+ expect(store.queries.flatMap(query => query.rows)).toEqual([]);
+ });
});
});
describe("getUserSelf", () => {
- it("returns null when not found", async () => { expect(await userQueries.getUserSelf(createSelectMock([]), "x")).toBeNull(); });
- it("returns user", async () => { const u = { id: "u_1" }; expect(await userQueries.getUserSelf(createSelectMock([u]), "u_1")).toEqual(u); });
- it("never filters on deletedAt โ€” self lookups see soft-deleted rows too", async () => {
- const chain = createSelectMock([{ id: "u_1" }]);
- await userQueries.getUserSelf(chain, "u_1");
- expect(conditionReferencesColumn(chain.where.mock.calls[0][0], "deletedAt")).toBe(false);
+ it("returns null when not found", async () => {
+ await withDatabase(async store => {
+ await expect(userQueries.getUserSelf(store.db, "missing")).resolves.toBeNull();
+ expect(store.queries.flatMap(query => query.rows)).toEqual([]);
+ });
+ });
+
+ it("resolves the same exact self identity before and after soft deletion", async () => {
+ await withDatabase(async store => {
+ await expect(userQueries.getUserSelf(store.db, "target")).resolves.toEqual(publicUser());
+ store.sqlite.prepare("UPDATE user SET deletedAt=? WHERE id=?").run(NOW, "target");
+ await expect(userQueries.getUserSelf(store.db, "target")).resolves.toEqual(publicUser());
+ expectNoDriverIdentities(store, ["other", "gone"]);
+ });
});
});
describe("getUsersByIds", () => {
it("does not query for an empty input", async () => {
- const db = createSelectMock([]);
- await expect(userQueries.getUsersByIds(db, [])).resolves.toEqual([]);
+ const db = { select: vi.fn() };
+ await expect(userQueries.getUsersByIds(db as never, [])).resolves.toEqual([]);
expect(db.select).not.toHaveBeenCalled();
});
- it("returns existing rows without inventing a missing user", async () => {
- const existing = { id: "existing" };
- const db = createSelectMock([existing]);
- await expect(userQueries.getUsersByIds(db, ["missing", "existing"])).resolves.toEqual([existing]);
+ it("returns requested existing users across chunks without inventing a missing identity", async () => {
+ await withDatabase(async store => {
+ const ids = Array.from({ length: 105 }, (_, index) => `requested-${index}`);
+ const expected = ids.map((id, index) => publicUser({ id, name: `Requested ${index}`, email: `${id}@fixture.test`, image: null, avatarVersion: 0, discriminator: "0042" }));
+ store.sqlite.transaction(() => {
+ for (const [index, id] of ids.entries()) store.seed({ id, name: `Requested ${index}`, discriminator: "0042" });
+ })();
+ const input = [...ids, "missing", ids[0]!, ids[100]!];
+ const before = [...input];
+ const rows = await userQueries.getUsersByIds(store.db, input);
+ expectUsers(rows, expected);
+ expect(input).toEqual(before);
+ expectNoDriverIdentities(store, ["target", "other", "gone"]);
+ expect(store.queries.length).toBeGreaterThan(0);
+ for (const query of store.queries) expect(query.params.length).toBeLessThanOrEqual(100);
+ });
});
- it("keeps public columns and does not exclude historical tombstone identities", async () => {
- const db = createSelectMock([{ id: "deleted_identity", name: "Deleted user" }]);
- await expect(userQueries.getUsersByIds(db, ["deleted_identity"])).resolves.toEqual([
- { id: "deleted_identity", name: "Deleted user" },
- ]);
- expect(Object.keys(db.select.mock.calls[0][0]).sort()).toEqual([
- "id", "name", "email", "emailVerified", "image", "avatarVersion",
- "createdAt", "updatedAt", "discriminator",
- ].sort());
- expect(conditionReferencesColumn(db.where.mock.calls[0][0], "id")).toBe(true);
- expect(conditionReferencesColumn(db.where.mock.calls[0][0], "deletedAt")).toBe(false);
+ it("returns the public historical projection for requested live and tombstone identities", async () => {
+ await withDatabase(async store => {
+ const rows = await userQueries.getUsersByIds(store.db, ["gone", "target"]);
+ expectUsers(rows, [publicUser(), publicUser({ id: "gone", name: "Gone", email: "[email protected]", image: "gone.png", avatarVersion: 5, discriminator: "0003" })]);
+ expectNoDriverIdentities(store, ["other"]);
+ });
});
});
describe("getUserByEmail", () => {
- it("returns null when not found", async () => { expect(await userQueries.getUserByEmail(createSelectMock([]), "[email protected]")).toBeNull(); });
- it("returns user", async () => { const u = { id: "u_1" }; expect(await userQueries.getUserByEmail(createSelectMock([u]), "[email protected]")).toEqual(u); });
+ it("resolves the exact internal email including tombstones and returns null for an absent address", async () => {
+ await withDatabase(async store => {
+ await expect(userQueries.getUserByEmail(store.db, "[email protected]")).resolves.toEqual(publicUser());
+ store.sqlite.prepare("UPDATE user SET deletedAt=? WHERE id=?").run(NOW, "target");
+ await expect(userQueries.getUserByEmail(store.db, "[email protected]")).resolves.toEqual(publicUser());
+ expectNoDriverIdentities(store, ["other", "gone"]);
+ store.queries.length = 0;
+ await expect(userQueries.getUserByEmail(store.db, "[email protected]")).resolves.toBeNull();
+ expect(store.queries.flatMap(query => query.rows)).toEqual([]);
+ });
+ });
});
describe("getUserByProviderAccount", () => {
- it("returns the user joined through the exact provider and account keys", async () => {
- const user = { id: "u_apple", email: "[email protected]" };
- const chain = createSelectLimitMock([user]);
-
- await expect(
- userQueries.getUserByProviderAccount(chain, "apple", "stable-sub"),
- ).resolves.toEqual(user);
- expect(chain.innerJoin).toHaveBeenCalledOnce();
- expect(chain.limit).toHaveBeenCalledWith(2);
- const condition = chain.where.mock.calls[0][0];
- expect(conditionReferencesColumn(condition, "providerId")).toBe(true);
- expect(conditionReferencesColumn(condition, "accountId")).toBe(true);
- expect(conditionContainsString(condition, "apple")).toBe(true);
- expect(conditionContainsString(condition, "stable-sub")).toBe(true);
+ it("resolves only the exact provider and subject pair despite neighboring identities", async () => {
+ await withDatabase(async store => {
+ store.seedAccount("correct", "target", "apple", "stable-sub");
+ store.seedAccount("other-provider", "other", "google", "stable-sub");
+ store.seedAccount("other-subject", "gone", "apple", "different-sub");
+ await expect(userQueries.getUserByProviderAccount(store.db, "apple", "stable-sub")).resolves.toEqual(publicUser());
+ expectNoDriverIdentities(store, ["other", "gone"]);
+ });
});
it("returns null when the identity has never been seen", async () => {
- await expect(
- userQueries.getUserByProviderAccount(
- createSelectLimitMock([]),
- "apple",
- "new-sub"
- ),
- ).resolves.toBeNull();
+ await withDatabase(async store => {
+ store.seedAccount("other-subject", "target", "apple", "different-sub");
+ store.seedAccount("other-provider", "other", "google", "new-sub");
+ await expect(userQueries.getUserByProviderAccount(store.db, "apple", "new-sub")).resolves.toBeNull();
+ expect(store.queries.flatMap(query => query.rows)).toEqual([]);
+ });
});
- it("fails closed when duplicate provider identities exist", async () => {
- await expect(
- userQueries.getUserByProviderAccount(
- createSelectLimitMock([{ id: "u_1" }, { id: "u_2" }]),
- "apple",
- "duplicate-sub"
- ),
- ).rejects.toThrow("multiple users share one provider account identity");
+ it("fails closed when two valid stored users share the same provider identity", async () => {
+ await withDatabase(async store => {
+ store.seedAccount("first", "target", "apple", "duplicate-sub");
+ await expect(userQueries.getUserByProviderAccount(store.db, "apple", "duplicate-sub")).resolves.toEqual(publicUser());
+ store.seedAccount("second", "other", "apple", "duplicate-sub");
+ const before = snapshot(store.sqlite);
+ await expect(userQueries.getUserByProviderAccount(store.db, "apple", "duplicate-sub")).rejects.toThrow();
+ expect(snapshot(store.sqlite)).toEqual(before);
+ });
});
});
describe("createUser", () => {
- it("creates user", async () => {
- const u = { id: "u_1" };
- expect(await userQueries.createUser(createSelectMock([u]), { name: "A", email: "[email protected]" })).toEqual(u);
- });
- it("writes a generated discriminator instead of relying on the schema default", async () => {
- const chain = createSelectMock([{ id: "u_1" }]);
- await userQueries.createUser(chain, { name: "A", email: "[email protected]" });
- const values = chain.values.mock.calls[0][0];
- expect(values.id).toEqual(expect.any(String));
- expect(values.discriminator).toBe(computeDiscriminator(values.id));
- expect(values.discriminator).toMatch(/^\d{4}$/);
- });
- it("rejects empty name", async () => {
- await expect(
- userQueries.createUser(createSelectMock([{ id: "u_x" }]), { name: "", email: "[email protected]" }),
- ).rejects.toThrow(/user\.name cannot be empty/);
+ it("creates and returns the stored public user", async () => {
+ await withDatabase(async store => {
+ const result = await userQueries.createUser(store.db, { name: "Created", email: "[email protected]" });
+ expect(result.id).toEqual(expect.any(String));
+ expect(result.id.length).toBeGreaterThan(0);
+ expect(result.discriminator).toMatch(/^\d{4}$/);
+ expect(result).toEqual(publicUser({ id: result.id, name: "Created", email: "[email protected]", emailVerified: null, image: null, avatarVersion: 0, createdAt: NOW, updatedAt: NOW, discriminator: result.discriminator }));
+ expect(store.sqlite.prepare("SELECT id,name,email,discriminator FROM user WHERE id=?").get(result.id)).toEqual({ id: result.id, name: "Created", email: "[email protected]", discriminator: result.discriminator });
+ });
});
- it("rejects whitespace-only name", async () => {
- await expect(
- userQueries.createUser(createSelectMock([{ id: "u_x" }]), { name: " ", email: "[email protected]" }),
- ).rejects.toThrow(/user\.name cannot be empty/);
+
+ it("stores an available generated discriminator instead of the occupied schema default", async () => {
+ await withDatabase(async store => {
+ store.seed({ id: "default-occupied", name: "Created", discriminator: "0000" });
+ const result = await userQueries.createUser(store.db, { name: "Created", email: "[email protected]" });
+ expect(result.discriminator).toMatch(/^\d{4,18}$/);
+ expect(result.discriminator).not.toBe("0000");
+ expect(store.sqlite.prepare("SELECT id,discriminator FROM user WHERE name='Created' ORDER BY id").all())
+ .toEqual([{ id: "default-occupied", discriminator: "0000" }, { id: result.id, discriminator: result.discriminator }].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
+ expect(store.sqlite.prepare("SELECT count(*) AS count FROM user WHERE name=? AND discriminator=?").get("Created", result.discriminator)).toEqual({ count: 1 });
+ });
+ });
+
+ it("rejects empty name without a durable write", async () => {
+ await withDatabase(async store => {
+ const before = snapshot(store.sqlite);
+ await expect(userQueries.createUser(store.db, { name: "", email: "[email protected]" })).rejects.toThrow();
+ expect(snapshot(store.sqlite)).toEqual(before);
+ });
+ });
+
+ it("rejects whitespace-only name without a durable write", async () => {
+ await withDatabase(async store => {
+ const before = snapshot(store.sqlite);
+ await expect(userQueries.createUser(store.db, { name: " ", email: "[email protected]" })).rejects.toThrow();
+ expect(snapshot(store.sqlite)).toEqual(before);
+ });
});
});
describe("getUserByNameAndDiscriminator", () => {
- it("returns the exact match case-insensitively on name", async () => {
- const u = { id: "u_1", name: "Alice", discriminator: "1234" };
- const chain = createSelectLimitMock([u]);
- const result = await userQueries.getUserByNameAndDiscriminator(chain, "alice", "1234");
- expect(result).toEqual(u);
+ it("returns the case-insensitive name and exact discriminator match", async () => {
+ await withDatabase(async store => {
+ store.seed({ id: "other-number", name: "Alice", discriminator: "0009" });
+ store.seed({ id: "other-name", name: "Alicia", discriminator: "0001" });
+ await expect(userQueries.getUserByNameAndDiscriminator(store.db, "aLiCe", "0001")).resolves.toEqual(publicUser());
+ expectNoDriverIdentities(store, ["other-number", "other-name", "other", "gone"]);
+ });
});
- it("returns null on no match", async () => {
- const chain = createSelectLimitMock([]);
- const result = await userQueries.getUserByNameAndDiscriminator(chain, "nobody", "0000");
- expect(result).toBeNull();
+ it("returns null when neither nearby handle is the requested pair", async () => {
+ await withDatabase(async store => {
+ store.seed({ id: "other-number", name: "Alice", discriminator: "0009" });
+ await expect(userQueries.getUserByNameAndDiscriminator(store.db, "Alice", "0042")).resolves.toBeNull();
+ expect(store.queries.flatMap(query => query.rows)).toEqual([]);
+ });
});
- it("filters on deletedAt unconditionally โ€” public lookup, no option to disable it", async () => {
- const chain = createSelectLimitMock([{ id: "u_1" }]);
- await userQueries.getUserByNameAndDiscriminator(chain, "alice", "1234");
- expect(conditionReferencesColumn(chain.where.mock.calls[0][0], "deletedAt")).toBe(true);
+ it("excludes a soft-deleted exact handle", async () => {
+ await withDatabase(async store => {
+ store.sqlite.prepare("UPDATE user SET deletedAt=? WHERE id=?").run(NOW, "target");
+ await expect(userQueries.getUserByNameAndDiscriminator(store.db, "Alice", "0001")).resolves.toBeNull();
+ expect(store.queries.flatMap(query => query.rows)).toEqual([]);
+ });
});
- it("escapes SQL LIKE metacharacters in name โ€” `_` in input is a literal, not a wildcard", async () => {
- const chain = createSelectLimitMock([]);
- await userQueries.getUserByNameAndDiscriminator(chain, "A_ex", "0001");
- const where = chain.where.mock.calls[0][0];
- // Fragment must include an ESCAPE clause so the `\_` produced by
- // escapeLikePattern is honored (without it, SQLite ignores the
- // backslash and `_` remains a wildcard).
- expect(conditionContainsString(where, "ESCAPE")).toBe(true);
- // Escaped pattern (`A\_ex`) must be a parameter of the fragment.
- expect(conditionContainsString(where, "A\\_ex")).toBe(true);
+ it("matches literal handle metacharacters without admitting wildcard neighbors", async () => {
+ await withDatabase(async store => {
+ const cases = [{ name: "A_ex", decoy: "Abex" }, { name: "B%ex", decoy: "Blongex" }, { name: "C\\ex", decoy: "Cex" }];
+ for (const [index, value] of cases.entries()) {
+ const id = `literal-${index}`;
+ store.seed({ id: `wildcard-${index}`, name: value.decoy, discriminator: "0042" });
+ store.seed({ id, name: value.name, discriminator: "0042" });
+ const result = await userQueries.getUserByNameAndDiscriminator(store.db, value.name, "0042");
+ expect(result).toEqual(publicUser({ id, name: value.name, email: `${id}@fixture.test`, image: null, avatarVersion: 0, discriminator: "0042" }));
+ store.queries.length = 0;
+ store.sqlite.prepare("DELETE FROM user WHERE id=?").run(id);
+ await expect(userQueries.getUserByNameAndDiscriminator(store.db, value.name, "0042")).resolves.toBeNull();
+ expect(store.queries.flatMap(query => query.rows)).toEqual([]);
+ }
+ });
});
});
describe("getUserByNameCaseInsensitive", () => {
- it("returns the match case-insensitively on name", async () => {
- const u = { id: "u_1", name: "Alice" };
- const chain = createSelectMock([u]);
- const result = await userQueries.getUserByNameCaseInsensitive(chain, "alice");
- expect(result).toEqual(u);
+ it("returns the literal case-insensitive name match", async () => {
+ await withDatabase(async store => {
+ store.seed({ id: "prefix-only", name: "Alicia", discriminator: "0001" });
+ await expect(userQueries.getUserByNameCaseInsensitive(store.db, "aLiCe")).resolves.toEqual(publicUser());
+ expectNoDriverIdentities(store, ["prefix-only", "other", "gone"]);
+ });
});
it("returns null on no match", async () => {
- const result = await userQueries.getUserByNameCaseInsensitive(createSelectMock([]), "nobody");
- expect(result).toBeNull();
+ await withDatabase(async store => {
+ await expect(userQueries.getUserByNameCaseInsensitive(store.db, "Nobody")).resolves.toBeNull();
+ expect(store.queries.flatMap(query => query.rows)).toEqual([]);
+ });
});
- it("filters on deletedAt unconditionally โ€” public lookup, no option to disable it", async () => {
- const chain = createSelectMock([{ id: "u_1" }]);
- await userQueries.getUserByNameCaseInsensitive(chain, "alice");
- expect(conditionReferencesColumn(chain.where.mock.calls[0][0], "deletedAt")).toBe(true);
+ it("excludes soft-deleted bare-name matches", async () => {
+ await withDatabase(async store => {
+ store.sqlite.prepare("UPDATE user SET deletedAt=? WHERE id=?").run(NOW, "target");
+ await expect(userQueries.getUserByNameCaseInsensitive(store.db, "alice")).resolves.toBeNull();
+ expect(store.queries.flatMap(query => query.rows)).toEqual([]);
+ });
});
- it("escapes SQL LIKE metacharacters in name โ€” `%` in input is a literal, not a wildcard", async () => {
- const chain = createSelectMock([]);
- await userQueries.getUserByNameCaseInsensitive(chain, "admin%");
- const where = chain.where.mock.calls[0][0];
- expect(conditionContainsString(where, "ESCAPE")).toBe(true);
- expect(conditionContainsString(where, "admin\\%")).toBe(true);
+ it("matches literal bare-name metacharacters without wildcard expansion", async () => {
+ await withDatabase(async store => {
+ for (const [index, value] of [{ name: "A%ex", decoy: "Alongex" }, { name: "B_ex", decoy: "Bbex" }, { name: "C\\ex", decoy: "Cex" }].entries()) {
+ const id = `literal-${index}`;
+ store.seed({ id: `wildcard-${index}`, name: value.decoy, discriminator: "0042" });
+ store.seed({ id, name: value.name, discriminator: "0042" });
+ await expect(userQueries.getUserByNameCaseInsensitive(store.db, value.name)).resolves.toEqual(publicUser({ id, name: value.name, email: `${id}@fixture.test`, image: null, avatarVersion: 0, discriminator: "0042" }));
+ store.queries.length = 0;
+ store.sqlite.prepare("DELETE FROM user WHERE id=?").run(id);
+ await expect(userQueries.getUserByNameCaseInsensitive(store.db, value.name)).resolves.toBeNull();
+ expect(store.queries.flatMap(query => query.rows)).toEqual([]);
+ }
+ });
});
});
describe("searchUsersByName", () => {
- it("always filters out soft-deleted rows โ€” isNull(deletedAt) is unconditional, not opt-in", async () => {
- const chain = createSelectLimitMock([{ id: "u_1", name: "Alice" }]);
- await userQueries.searchUsersByName(chain, "ali");
- const whereArg = chain.where.mock.calls[0][0];
- // drizzle's `and(...)` keeps every condition as a queryChunks entry โ€”
- // there is no code path left that can build a call without the
- // deletedAt filter, unlike the old `opts?.excludeDeleted` flag.
- expect(conditionReferencesColumn(whereArg, "deletedAt")).toBe(true);
+ it("excludes deleted matches before returning public search results", async () => {
+ await withDatabase(async store => {
+ store.sqlite.prepare("UPDATE user SET name='Alina' WHERE id='gone'").run();
+ expectUsers(await userQueries.searchUsersByName(store.db, "ali"), [publicUser()]);
+ expectNoDriverIdentities(store, ["other", "gone"]);
+ });
});
- it("returns matches for a bare-name substring search", async () => {
- const u = { id: "u_1", name: "Alice" };
- const result = await userQueries.searchUsersByName(createSelectLimitMock([u]), "ali");
- expect(result).toEqual([u]);
+ it("returns actual substring matches without unrequested identities", async () => {
+ await withDatabase(async store => {
+ store.seed({ id: "inside", name: "Malice", discriminator: "0042" });
+ expectUsers(await userQueries.searchUsersByName(store.db, "ali"), [publicUser(), publicUser({ id: "inside", name: "Malice", email: "[email protected]", image: null, avatarVersion: 0, discriminator: "0042" })]);
+ expectNoDriverIdentities(store, ["other", "gone"]);
+ });
});
- it("exact (name, discriminator) match when discriminator is provided", async () => {
- const chain = createSelectLimitMock([{ id: "u_1", name: "Alice", discriminator: "1234" }]);
- await userQueries.searchUsersByName(chain, "Alice", { discriminator: "1234" });
- expect(chain.limit).toHaveBeenCalledWith(20);
+ it("narrows an exact name search to the requested discriminator", async () => {
+ await withDatabase(async store => {
+ store.seed({ id: "other-number", name: "Alice", discriminator: "0009" });
+ store.seed({ id: "prefix-only", name: "Alicia", discriminator: "0001" });
+ expectUsers(await userQueries.searchUsersByName(store.db, "Alice", { discriminator: "0001" }), [publicUser()]);
+ expectNoDriverIdentities(store, ["other-number", "prefix-only", "other", "gone"]);
+ });
});
- it("excludeUserId narrows the query without changing the result shape", async () => {
- const u = { id: "u_2", name: "Bob" };
- const result = await userQueries.searchUsersByName(createSelectLimitMock([u]), "bob", {
- excludeUserId: "u_1",
+ it("excludes an otherwise matching user without removing another valid match", async () => {
+ await withDatabase(async store => {
+ store.sqlite.prepare("UPDATE user SET name='Bob' WHERE id='target'").run();
+ store.sqlite.prepare("UPDATE user SET name='Bobby' WHERE id='other'").run();
+ expectUsers(await userQueries.searchUsersByName(store.db, "bob", { excludeUserId: "target" }), [publicUser({ id: "other", name: "Bobby", email: "[email protected]", image: "other.png", avatarVersion: 7, discriminator: "0002" })]);
+ expectNoDriverIdentities(store, ["target", "gone"]);
});
- expect(result).toEqual([u]);
});
- it("respects a custom limit", async () => {
- const chain = createSelectLimitMock([]);
- await userQueries.searchUsersByName(chain, "x", { limit: 5 });
- expect(chain.limit).toHaveBeenCalledWith(5);
+ it("applies a positive custom limit to more eligible rows than the limit", async () => {
+ await withDatabase(async store => {
+ const allowed = new Map<string, ReturnType<typeof publicUser>>();
+ for (let index = 0; index < 6; index++) {
+ const id = `match-${index}`;
+ store.seed({ id, name: `Limit Match ${index}`, discriminator: "0042" });
+ allowed.set(id, publicUser({ id, name: `Limit Match ${index}`, email: `${id}@fixture.test`, image: null, avatarVersion: 0, discriminator: "0042" }));
+ }
+ const rows = await userQueries.searchUsersByName(store.db, "Limit Match", { limit: 5 });
+ expect(rows).toHaveLength(5);
+ expect(new Set(rows.map(row => row.id)).size).toBe(5);
+ for (const row of rows) expect(row).toEqual(allowed.get(row.id));
+ expectNoDriverIdentities(store, ["target", "other", "gone"]);
+ });
});
});
@@ -294,67 +432,48 @@ describe("withUniqueDiscriminator", () => {
expect(result).toEqual({ discriminator: computeDiscriminator("u_fixed") });
});
- it("retries with a salted discriminator on isUniqueConstraintError, then succeeds", async () => {
+ it("retries a persistent collision and returns the actual successful callback value", async () => {
const uniqueErr = Object.assign(new Error("UNIQUE constraint failed"), { code: "SQLITE_CONSTRAINT_UNIQUE" });
- const insertFn = vi
- .fn<(discriminator: string) => Promise<{ discriminator: string }>>()
- .mockRejectedValueOnce(uniqueErr)
- .mockImplementationOnce(async (discriminator: string) => ({ discriminator }));
-
- const result = await userQueries.withUniqueDiscriminator(
- {} as any,
- { id: "u_collide", name: "Alice" },
- insertFn,
- );
-
- expect(insertFn).toHaveBeenCalledTimes(2);
- expect(insertFn).toHaveBeenNthCalledWith(1, computeDiscriminator("u_collide"));
- // Salt scheme is now `id:width:attempt`; first retry stays at width 4, attempt 1.
- expect(insertFn).toHaveBeenNthCalledWith(2, computeDiscriminator("u_collide:4:1", 4));
- expect(result).toEqual({ discriminator: computeDiscriminator("u_collide:4:1", 4) });
+ let occupied: string | undefined;
+ let committed: { discriminator: string; marker: string } | undefined;
+ const insertFn = vi.fn(async (discriminator: string) => {
+ occupied ??= discriminator;
+ if (discriminator === occupied) throw uniqueErr;
+ committed = { discriminator, marker: "committed" };
+ return committed;
+ });
+ const result = await userQueries.withUniqueDiscriminator({} as never, { id: "u_collide", name: "Alice" }, insertFn);
+ expect(insertFn.mock.calls.length).toBeGreaterThanOrEqual(2);
+ expect(result).toBe(committed);
+ expect(result.discriminator).not.toBe(occupied);
+ expect(result.discriminator).toMatch(/^\d{4,18}$/);
});
- it("WIDENS by a digit after the per-width salt budget, never caps (A: variable-width)", async () => {
- // Every insert at width 4 collides; the allocator must exhaust the 5-try
- // width-4 budget then WIDEN to width 5 and keep going โ€” the (A)-vs-(B)
- // behavior reversal (B threw at the cap; A never caps under real contention).
+ it("widens when every four-digit callback candidate remains occupied", async () => {
const uniqueErr = Object.assign(new Error("UNIQUE constraint failed"), { code: "SQLITE_CONSTRAINT_UNIQUE" });
const seen: string[] = [];
const insertFn = vi.fn(async (discriminator: string) => {
seen.push(discriminator);
- // Fail every width-4 (4-digit) attempt; succeed once a wider disc arrives.
- if (discriminator.length <= 4) throw uniqueErr;
+ if (discriminator.length === 4) throw uniqueErr;
return { discriminator };
});
-
- const result = await userQueries.withUniqueDiscriminator(
- {} as any,
- { id: "u_saturated", name: "Alice" },
- insertFn,
- );
-
- // All width-4 tries happened (bare + 4 salted), then a width-5 disc won.
- const width4 = seen.filter((d) => d.length === 4);
- const width5 = seen.filter((d) => d.length === 5);
- expect(width4.length).toBe(5); // MAX_DISCRIMINATOR_ATTEMPTS at width 4
- expect(width5.length).toBeGreaterThanOrEqual(1);
- expect(result.discriminator.length).toBe(5); // widened, not capped/thrown
+ const result = await userQueries.withUniqueDiscriminator({} as never, { id: "u_saturated", name: "Alice" }, insertFn);
+ expect(seen.filter(value => value.length === 4).length).toBeGreaterThan(0);
+ expect(result.discriminator).toMatch(/^\d{5}$/);
+ expect(seen.at(-1)).toBe(result.discriminator);
});
- it("stays loud โ€” a widened insert failure still surfaces, never a silent dup", async () => {
- // A non-unique error mid-widen must rethrow immediately (loud), not be
- // swallowed as if it were a collision to retry past.
+ it("rethrows the same fatal error after the allocator reaches a wider discriminator", async () => {
const uniqueErr = Object.assign(new Error("UNIQUE constraint failed"), { code: "SQLITE_CONSTRAINT_UNIQUE" });
const fatalErr = new Error("D1_ERROR: disk full");
- let n = 0;
- const insertFn = vi.fn(async () => {
- n += 1;
- throw n === 1 ? uniqueErr : fatalErr; // collide once, then a real fault
+ const widths: number[] = [];
+ const insertFn = vi.fn(async (discriminator: string): Promise<never> => {
+ widths.push(discriminator.length);
+ throw discriminator.length === 4 ? uniqueErr : fatalErr;
});
-
- await expect(
- userQueries.withUniqueDiscriminator({} as any, { id: "u_loud", name: "Alice" }, insertFn),
- ).rejects.toBe(fatalErr);
+ await expect(userQueries.withUniqueDiscriminator({} as never, { id: "u_loud", name: "Alice" }, insertFn)).rejects.toBe(fatalErr);
+ expect(widths.some(width => width === 4)).toBe(true);
+ expect(widths.some(width => width > 4)).toBe(true);
});
it("rethrows immediately on a non-unique-constraint error (no retry)", async () => {
@@ -369,15 +488,19 @@ describe("withUniqueDiscriminator", () => {
expect(insertFn).toHaveBeenCalledTimes(1);
});
- it("retries a selected server-handle signature and preserves the salted winner", async () => {
+ it("retries only the selected signature and returns the successful callback winner", async () => {
const columns = ["community_server.name", "community_server.discriminator"];
const error = new Error("Driver error", { cause: new Error("UNIQUE constraint failed: community_server.name, community_server.discriminator") });
- const insertFn = vi.fn<(discriminator: string) => Promise<string>>()
- .mockRejectedValueOnce(error)
- .mockImplementationOnce(async (discriminator) => discriminator);
- await expect(userQueries.withUniqueDiscriminator({} as any, { id: "selected", name: "Server" }, insertFn, columns))
- .resolves.toBe(computeDiscriminator("selected:4:1", 4));
+ const seen: string[] = [];
+ const insertFn = vi.fn(async (discriminator: string) => {
+ seen.push(discriminator);
+ if (seen.length === 1) throw error;
+ return discriminator;
+ });
+ const result = await userQueries.withUniqueDiscriminator({} as never, { id: "selected", name: "Server" }, insertFn, columns);
expect(insertFn).toHaveBeenCalledTimes(2);
+ expect(result).toBe(seen[1]);
+ expect(result).toMatch(/^\d{4,18}$/);
});
it.each([
@@ -392,131 +515,92 @@ describe("withUniqueDiscriminator", () => {
.rejects.toBe(error);
expect(insertFn).toHaveBeenCalledTimes(1);
});
-
});
describe("probeAvailableDiscriminator", () => {
- it("WIDENS the probe space instead of capping at 4 digits when width-4 is saturated", async () => {
- // The first 5 probes (the width-4 salt budget: bare id + :4:1..:4:4) come
- // back taken โ†’ the probe must WIDEN to 5 digits and return a wider disc,
- // NOT hand back a capped 4-digit salt. This is the โ˜… catch: the email-signup
- // probe path must never cap at 4 either.
- let probeIdx = 0;
- const stub: any = {
- select: () => stub,
- from: () => stub,
- where: () => stub,
- limit: () => {
- const taken = probeIdx < 5; // 5 width-4 probes taken, then free
- probeIdx += 1;
- return Promise.resolve(taken ? [{ id: "u_other" }] : []);
- },
- };
-
- const returned = await userQueries.probeAvailableDiscriminator(stub, {
- id: "u_collide",
- name: "Alice",
+ it("widens only after the actual four-digit name namespace is occupied", async () => {
+ await withDatabase(async store => {
+ store.sqlite.transaction(() => {
+ for (let value = 0; value < 10000; value++) {
+ const discriminator = String(value).padStart(4, "0");
+ store.seed({ id: `occupied-${discriminator}`, name: "ProbeScope", discriminator });
+ }
+ })();
+ expect(store.sqlite.prepare("SELECT count(*) AS count FROM user WHERE name='ProbeScope'").get()).toEqual({ count: 10000 });
+ const result = await userQueries.probeAvailableDiscriminator(store.db, { id: "u_collide", name: "ProbeScope" });
+ expect(result).toMatch(/^\d{5}$/);
+ expect(store.sqlite.prepare("SELECT count(*) AS count FROM user WHERE name=? AND discriminator=? AND deletedAt IS NULL").get("ProbeScope", result)).toEqual({ count: 0 });
});
-
- // 5 width-4 probes were taken, so the winner is the first width-5 disc.
- expect(returned.length).toBe(5);
- expect(returned).toBe(computeDiscriminator("u_collide:5:0", 5));
});
- it("returns the first free salt on the happy path (still width 4)", async () => {
- // First probe (bare id) taken, second (id:4:1) free โ†’ second salt returned.
- const stub: any = {
- select: () => stub,
- from: () => stub,
- where: () => stub,
- };
- let calls = 0;
- stub.limit = () => {
- calls += 1;
- return Promise.resolve(calls === 1 ? [{ id: "u_other" }] : []);
- };
-
- const returned = await userQueries.probeAvailableDiscriminator(stub, {
- id: "u_ok",
- name: "Alice",
+ it("returns an actually available four-digit candidate after the initial occupied value", async () => {
+ await withDatabase(async store => {
+ const occupied = computeDiscriminator("u_ok");
+ store.seed({ id: "initial-occupied", name: "ProbeScope", discriminator: occupied });
+ const result = await userQueries.probeAvailableDiscriminator(store.db, { id: "u_ok", name: "ProbeScope" });
+ expect(result).toMatch(/^\d{4}$/);
+ expect(result).not.toBe(occupied);
+ expect(store.sqlite.prepare("SELECT count(*) AS count FROM user WHERE name=? AND discriminator=? AND deletedAt IS NULL").get("ProbeScope", result)).toEqual({ count: 0 });
+ expect(store.sqlite.prepare("SELECT discriminator FROM user WHERE id='initial-occupied'").get()).toEqual({ discriminator: occupied });
});
- expect(returned).toBe(computeDiscriminator("u_ok:4:1", 4));
});
});
describe("updateUser", () => {
- function createUpdateMock(rows: any[]) {
- const chain: any = {};
- chain.update = vi.fn(() => chain);
- chain.set = vi.fn(() => chain);
- chain.where = vi.fn(() => chain);
- chain.returning = vi.fn(() => Promise.resolve(rows));
- return chain;
- }
-
- it("returns null when not found", async () => {
- expect(await userQueries.updateUser(createUpdateMock([]), "x", { name: "B", image: null })).toBeNull();
- });
- it("returns updated user", async () => {
- const u = { id: "u_1" };
- expect(await userQueries.updateUser(createUpdateMock([u]), "u_1", { name: "B", image: null })).toEqual(u);
- });
-
- it("only name provided โ†’ set contains name and updatedAt, no image key", async () => {
- const chain = createUpdateMock([{ id: "u_1" }]);
- await userQueries.updateUser(chain, "u_1", { name: "B" });
- const arg = chain.set.mock.calls[0][0];
- expect(arg).toHaveProperty("name", "B");
- expect(arg).toHaveProperty("updatedAt");
- expect(arg).not.toHaveProperty("image");
+ it("returns null for an absent target without changing other stored users", async () => {
+ await withDatabase(async store => {
+ const before = snapshot(store.sqlite);
+ await expect(userQueries.updateUser(store.db, "missing", { name: "New", image: null })).resolves.toBeNull();
+ expect(snapshot(store.sqlite)).toEqual(before);
+ });
});
- it("only image (string) provided โ†’ set contains image and updatedAt, no name key", async () => {
- const chain = createUpdateMock([{ id: "u_1" }]);
- await userQueries.updateUser(chain, "u_1", { image: "https://example.com/a.png" });
- const arg = chain.set.mock.calls[0][0];
- expect(arg).toHaveProperty("image", "https://example.com/a.png");
- expect(arg).toHaveProperty("updatedAt");
- expect(arg).not.toHaveProperty("name");
+ it("updates a valid name while preserving the target image and every other user's state", async () => {
+ await withDatabase(async store => {
+ const before = snapshot(store.sqlite);
+ await expect(userQueries.updateUser(store.db, "target", { name: "New" })).resolves.toEqual(publicUser({ name: "New", updatedAt: NOW }));
+ expectOnlyTargetChange(store.sqlite, before, { name: "New", updatedAt: NOW });
+ expectNoDriverIdentities(store, ["other", "gone"]);
+ });
});
- it("image: null provided โ†’ set includes image: null (explicit clear)", async () => {
- const chain = createUpdateMock([{ id: "u_1" }]);
- await userQueries.updateUser(chain, "u_1", { image: null });
- const arg = chain.set.mock.calls[0][0];
- expect(arg).toHaveProperty("image", null);
- expect("image" in arg).toBe(true);
- expect(arg).not.toHaveProperty("name");
+ it("updates only the image while preserving the target name and foreign users", async () => {
+ await withDatabase(async store => {
+ const before = snapshot(store.sqlite);
+ await expect(userQueries.updateUser(store.db, "target", { image: "https://example.test/new.png" })).resolves.toEqual(publicUser({ image: "https://example.test/new.png", updatedAt: NOW }));
+ expectOnlyTargetChange(store.sqlite, before, { image: "https://example.test/new.png", updatedAt: NOW });
+ });
});
- it("empty data {} โ†’ set contains only updatedAt", async () => {
- const chain = createUpdateMock([{ id: "u_1" }]);
- await userQueries.updateUser(chain, "u_1", {});
- const arg = chain.set.mock.calls[0][0];
- expect(Object.keys(arg)).toEqual(["updatedAt"]);
+ it("clears a nonnull image without clearing the name or changing other users", async () => {
+ await withDatabase(async store => {
+ const before = snapshot(store.sqlite);
+ await expect(userQueries.updateUser(store.db, "target", { image: null })).resolves.toEqual(publicUser({ image: null, updatedAt: NOW }));
+ expectOnlyTargetChange(store.sqlite, before, { image: null, updatedAt: NOW });
+ });
});
- it("both provided โ†’ set contains name, image, and updatedAt", async () => {
- const chain = createUpdateMock([{ id: "u_1" }]);
- await userQueries.updateUser(chain, "u_1", { name: "B", image: null });
- const arg = chain.set.mock.calls[0][0];
- expect(arg).toHaveProperty("name", "B");
- expect(arg).toHaveProperty("image", null);
- expect(arg).toHaveProperty("updatedAt");
+ it("touches only the target timestamp for an empty update payload", async () => {
+ await withDatabase(async store => {
+ const before = snapshot(store.sqlite);
+ await expect(userQueries.updateUser(store.db, "target", {})).resolves.toEqual(publicUser({ updatedAt: NOW }));
+ expectOnlyTargetChange(store.sqlite, before, { updatedAt: NOW });
+ });
});
- it("rejects whitespace-only name when explicitly provided", async () => {
- const chain = createUpdateMock([{ id: "u_1" }]);
- await expect(userQueries.updateUser(chain, "u_1", { name: " " })).rejects.toThrow(
- /user\.name cannot be empty/,
- );
+ it("persists both fields for only the target and returns the stored public user", async () => {
+ await withDatabase(async store => {
+ const before = snapshot(store.sqlite);
+ await expect(userQueries.updateUser(store.db, "target", { name: "New", image: null })).resolves.toEqual(publicUser({ name: "New", image: null, updatedAt: NOW }));
+ expectOnlyTargetChange(store.sqlite, before, { name: "New", image: null, updatedAt: NOW });
+ });
});
- it("succeeds when name is a valid non-empty string", async () => {
- const chain = createUpdateMock([{ id: "u_1" }]);
- const result = await userQueries.updateUser(chain, "u_1", { name: "Alice" });
- expect(result).toEqual({ id: "u_1" });
- const arg = chain.set.mock.calls[0][0];
- expect(arg).toHaveProperty("name", "Alice");
+ it("rejects a whitespace-only name without changing the target or neighbors", async () => {
+ await withDatabase(async store => {
+ const before = snapshot(store.sqlite);
+ await expect(userQueries.updateUser(store.db, "target", { name: " " })).rejects.toThrow();
+ expect(snapshot(store.sqlite)).toEqual(before);
+ });
});
});