fix: rebuild migration history as baseline so migrate works on prod
Squash the 13 historical migrations into one generated baseline whose journal entry reuses the original 0000 timestamp: the migrator skips it on every existing database (prod journal stuck at 0006) and applies it only on fresh ones. Parity with the old chain verified via pg_dump diff plus fresh/existing/prod-simulated drizzle-kit migrate runs. Historical files move to drizzle-history/pre-squash-2026-08/ for integration tests that exercise legacy migration behavior. Also repair db tests that already failed before this change: - raw SQL targeted users, but the table has always been "user" - membership recheck mocked legacy getAsset.albums instead of searchPhotos - audit rollback assertion walks drizzle's wrapped error cause chain - keyset index probe pinned to NULLS LAST ordering, removing a planner cost tie-break that flipped with index creation order
This commit is contained in:
1 parent
2949149170
commit
0b65fbba16
40 files changed
+2389
-128
No files matched your search
@@ -4,7 +4,7 @@ import path from "node:path";
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
const migration = await readFile(
|
||||
path.join(process.cwd(), "drizzle/0002_accounting_intents.sql"),
|
||||
path.join(process.cwd(), "drizzle-history/pre-squash-2026-08/0002_accounting_intents.sql"),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
|
||||
@@ -9,7 +9,10 @@ import { createUsageService, createUsageServiceRepository } from "@/modules/usag
|
||||
import { requestFingerprint } from "@/modules/usages/types";
|
||||
import { startPostgres } from "./postgres";
|
||||
|
||||
const testDb = await startPostgres({ through: "0001_editorial_approval_notice.sql" });
|
||||
const testDb = await startPostgres({
|
||||
through: "0001_editorial_approval_notice.sql",
|
||||
migrationsDir: "drizzle-history/pre-squash-2026-08",
|
||||
});
|
||||
|
||||
afterAll(() => testDb.stop());
|
||||
|
||||
@@ -76,7 +79,7 @@ test("0002 preserves dirty rows and reconstructs only provable legacy intents",
|
||||
const userId = randomUUID();
|
||||
const editorialId = randomUUID();
|
||||
await testDb.pool.query(
|
||||
`insert into users (id, name, email, email_verified)
|
||||
`insert into "user" (id, name, email, email_verified)
|
||||
values ($1, 'Legacy Redaktion', $2, true)`,
|
||||
[userId, `${userId}@example.com`],
|
||||
);
|
||||
|
||||
@@ -5,7 +5,10 @@ import { afterAll, expect, test, vi } from "vitest";
|
||||
import { createAlbumGrantRepository, createAlbumGrantService } from "@/modules/albums/grants";
|
||||
import { startPostgres } from "./postgres";
|
||||
|
||||
const testDb = await startPostgres({ through: "0001_editorial_approval_notice.sql" });
|
||||
const testDb = await startPostgres({
|
||||
through: "0001_editorial_approval_notice.sql",
|
||||
migrationsDir: "drizzle-history/pre-squash-2026-08",
|
||||
});
|
||||
|
||||
afterAll(() => testDb.stop());
|
||||
|
||||
@@ -22,7 +25,7 @@ test("grant mutations and migration preserve one deterministic active logical gr
|
||||
const adminUserId = randomUUID();
|
||||
const editorialId = randomUUID();
|
||||
await testDb.pool.query(
|
||||
`insert into users (id, name, email, email_verified)
|
||||
`insert into "user" (id, name, email, email_verified)
|
||||
values ($1, 'Grant Admin', $2, true)`,
|
||||
[adminUserId, `${adminUserId}@example.com`],
|
||||
);
|
||||
|
||||
@@ -5,7 +5,7 @@ import { expect, test } from "vitest";
|
||||
|
||||
test("0003 adds a durable voided billing state without deleting usage history", async () => {
|
||||
const migration = await readFile(
|
||||
path.join(process.cwd(), "drizzle/0003_stream_delivery.sql"),
|
||||
path.join(process.cwd(), "drizzle-history/pre-squash-2026-08/0003_stream_delivery.sql"),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
|
||||
@@ -391,19 +391,26 @@ test("history ordering queries can use the editorial keyset indexes", async () =
|
||||
try {
|
||||
await client.query("begin");
|
||||
await client.query("set local enable_seqscan = off");
|
||||
await client.query("set local enable_sort = off");
|
||||
// The keyset indexes sort NULLS LAST, so the probe queries must ask for the
|
||||
// same null ordering. Otherwise the index cannot satisfy the ORDER BY, a
|
||||
// Sort node is unavoidable and which scan feeds it is a cost tie-break
|
||||
// between equal indexes that flips with index creation order.
|
||||
const events = await client.query(
|
||||
"explain (costs off) select id from download_events where editorial_account_id = $1 order by authorized_at desc, id desc limit 26",
|
||||
"explain (costs off) select id from download_events where editorial_account_id = $1 order by authorized_at desc nulls last, id desc nulls last limit 26",
|
||||
[own.editorialId],
|
||||
);
|
||||
const usageRows = await client.query(
|
||||
"explain (costs off) select id from usages where editorial_account_id = $1 order by created_at desc, id desc limit 21",
|
||||
"explain (costs off) select id from usages where editorial_account_id = $1 order by created_at desc nulls last, id desc nulls last limit 21",
|
||||
[own.editorialId],
|
||||
);
|
||||
const eventPlan = events.rows.map((row) => row["QUERY PLAN"]).join("\n");
|
||||
const usagePlan = usageRows.rows.map((row) => row["QUERY PLAN"]).join("\n");
|
||||
|
||||
expect(eventPlan).toContain("download_events_editorial_authorized_id_idx");
|
||||
expect(eventPlan).not.toContain("Sort");
|
||||
expect(usagePlan).toContain("usages_editorial_created_id_idx");
|
||||
expect(usagePlan).not.toContain("Sort");
|
||||
} finally {
|
||||
await client.query("rollback");
|
||||
client.release();
|
||||
|
||||
@@ -5,7 +5,7 @@ import { expect, test } from "vitest";
|
||||
|
||||
test("0004 adds both editorial history keyset indexes without rewriting history", async () => {
|
||||
const migration = await readFile(
|
||||
path.join(process.cwd(), "drizzle/0004_download_history_indexes.sql"),
|
||||
path.join(process.cwd(), "drizzle-history/pre-squash-2026-08/0004_download_history_indexes.sql"),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
|
||||
+10
-8
@@ -29,7 +29,9 @@ export type PostgresTestDatabase = {
|
||||
stop(): Promise<void>;
|
||||
};
|
||||
|
||||
export async function startPostgres({ through }: { through?: string } = {}): Promise<PostgresTestDatabase> {
|
||||
export async function startPostgres(
|
||||
{ through, migrationsDir }: { through?: string; migrationsDir?: string } = {},
|
||||
): Promise<PostgresTestDatabase> {
|
||||
const container = await new PostgreSqlContainer("postgres:17-alpine")
|
||||
.withDatabase("portal")
|
||||
.withUsername("portal")
|
||||
@@ -37,11 +39,11 @@ export async function startPostgres({ through }: { through?: string } = {}): Pro
|
||||
.start();
|
||||
const pool = new Pool({ connectionString: container.getConnectionUri() });
|
||||
|
||||
const migrationFiles = await listMigrationFiles();
|
||||
const migrationFiles = await listMigrationFiles(migrationsDir);
|
||||
const throughIndex = through ? migrationFiles.indexOf(through) : migrationFiles.length - 1;
|
||||
if (through && throughIndex < 0) throw new Error(`Unknown migration: ${through}`);
|
||||
let appliedMigrationCount = throughIndex + 1;
|
||||
await applyMigrationFiles(pool, migrationFiles.slice(0, appliedMigrationCount));
|
||||
await applyMigrationFiles(pool, migrationsDir, migrationFiles.slice(0, appliedMigrationCount));
|
||||
|
||||
const db = drizzle({ client: pool, schema });
|
||||
|
||||
@@ -64,7 +66,7 @@ export async function startPostgres({ through }: { through?: string } = {}): Pro
|
||||
});
|
||||
},
|
||||
async applyRemainingMigrations() {
|
||||
await applyMigrationFiles(pool, migrationFiles.slice(appliedMigrationCount));
|
||||
await applyMigrationFiles(pool, migrationsDir, migrationFiles.slice(appliedMigrationCount));
|
||||
appliedMigrationCount = migrationFiles.length;
|
||||
},
|
||||
async stop() {
|
||||
@@ -74,15 +76,15 @@ export async function startPostgres({ through }: { through?: string } = {}): Pro
|
||||
};
|
||||
}
|
||||
|
||||
async function listMigrationFiles() {
|
||||
const migrationDirectory = path.join(process.cwd(), "drizzle");
|
||||
async function listMigrationFiles(migrationsDir?: string) {
|
||||
const migrationDirectory = path.join(process.cwd(), migrationsDir ?? "drizzle");
|
||||
return (await readdir(migrationDirectory))
|
||||
.filter((file) => /^\d+_.*\.sql$/.test(file))
|
||||
.sort();
|
||||
}
|
||||
|
||||
async function applyMigrationFiles(pool: Pool, migrationFiles: string[]) {
|
||||
const migrationDirectory = path.join(process.cwd(), "drizzle");
|
||||
async function applyMigrationFiles(pool: Pool, migrationsDir: string | undefined, migrationFiles: string[]) {
|
||||
const migrationDirectory = path.join(process.cwd(), migrationsDir ?? "drizzle");
|
||||
for (const file of migrationFiles) {
|
||||
await pool.query(await readFile(path.join(migrationDirectory, file), "utf8"));
|
||||
}
|
||||
|
||||
@@ -225,21 +225,9 @@ test("requires an active grant for the exact requested album", async () => {
|
||||
test("rechecks exact album membership after database locks before inserting", async () => {
|
||||
const editorialId = await seedEditorial();
|
||||
const { usageService, immich } = createServices();
|
||||
immich.getAsset
|
||||
.mockResolvedValueOnce({
|
||||
id: assetId,
|
||||
type: "IMAGE" as const,
|
||||
originalFileName: "jubel.jpg",
|
||||
originalMimeType: "image/jpeg",
|
||||
albums: [{ id: albumId }],
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
id: assetId,
|
||||
type: "IMAGE" as const,
|
||||
originalFileName: "jubel.jpg",
|
||||
originalMimeType: "image/jpeg",
|
||||
albums: [],
|
||||
});
|
||||
immich.searchPhotos
|
||||
.mockResolvedValueOnce({ items: [{ id: assetId }], total: 1, nextPage: null, previousPage: null })
|
||||
.mockResolvedValueOnce({ items: [], total: 0, nextPage: null, previousPage: null });
|
||||
|
||||
await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toMatchObject({
|
||||
code: "ASSET_NOT_IN_ALBUM",
|
||||
@@ -248,7 +236,7 @@ test("rechecks exact album membership after database locks before inserting", as
|
||||
.select({ value: count() })
|
||||
.from(usages)
|
||||
.where(eq(usages.editorialAccountId, editorialId));
|
||||
expect(immich.getAlbum).toHaveBeenCalledTimes(2);
|
||||
expect(immich.getAlbum).toHaveBeenCalledTimes(1);
|
||||
expect(usageCount.value).toBe(0);
|
||||
});
|
||||
|
||||
@@ -397,6 +385,19 @@ test("the same key may be reused by a different editorial but not for a differen
|
||||
});
|
||||
});
|
||||
|
||||
function errorChainIncludes(expected: string) {
|
||||
return (error: unknown): boolean => {
|
||||
let current = error;
|
||||
while (current instanceof Error) {
|
||||
if (current.message.includes(expected)) return true;
|
||||
const cause: unknown = current.cause;
|
||||
if (!cause) break;
|
||||
current = cause;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
}
|
||||
|
||||
test("an audit failure rolls back both the usage and authorized event", async () => {
|
||||
const editorialId = await seedEditorial();
|
||||
const { usageService } = createServices();
|
||||
@@ -413,7 +414,9 @@ test("an audit failure rolls back both the usage and authorized event", async ()
|
||||
`);
|
||||
|
||||
try {
|
||||
await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toThrow("audit rejected");
|
||||
await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toSatisfy(
|
||||
errorChainIncludes("audit rejected"),
|
||||
);
|
||||
} finally {
|
||||
await testDb.pool.query("drop trigger reject_billable_usage_audit on audit_events");
|
||||
await testDb.pool.query("drop function reject_billable_usage_audit()");
|
||||
|
||||
Reference in new issue
Block a user